Compare commits

..

14 Commits

Author SHA1 Message Date
Electroblob 09f858af20 Replace branch with old 1.7.10 code and assets 2018-06-07 11:58:24 +01:00
Electroblob 78b61cf573 Update README.md 2018-04-09 23:09:22 +01:00
Electroblob bf223ed5ab Update README.md 2018-03-09 10:04:14 +00:00
Electroblob 93b6b41a24 Update README.md 2018-02-26 22:54:03 +00:00
Electroblob 79a5cc4a67 Update ru_RU.lang (credit: VilagVil) 2018-02-25 18:21:30 +00:00
Electroblob f4d7ba6030 Fix inability to upgrade non-elemental wands using tomes of arcana 2018-02-18 23:33:54 +00:00
Electroblob a4695bcce1 Fix curseforge issue #30, where the game would crash when casting mind control on a mob that already had the mind trick status effect 2018-02-18 23:32:54 +00:00
Electroblob 52d12c0c02 Fix curseforge issue #28, where keybinds would be reset on game launch 2018-02-18 23:31:42 +00:00
Electroblob 56861b1ff5 Add coordinate fix from 1.11.2 branch, see 2dd52ce 2018-02-18 23:29:47 +00:00
Electroblob d2129ba256 Update CREDITS.md
Undoes previous commit, was made on the wrong branch
2018-02-13 16:28:32 +00:00
Electroblob 00a6b34310 Update CREDITS.md 2018-02-13 16:26:17 +00:00
Electroblob a2f1463939 Update README.md 2018-02-11 18:27:57 +00:00
Electroblob a9dbf47c4a Fix sparkle particles not being animated (this was accidentally disabled when testing a new feature) 2018-02-10 18:23:25 +00:00
Electroblob 2c8435392e Update version number 2018-02-10 18:22:49 +00:00
2371 changed files with 43249 additions and 80307 deletions
-2
View File
@@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
-20
View File
@@ -1,20 +0,0 @@
---
name: Bug report
about: Report a crash or something that isn't working as it should
title: "[Give a brief, relevant title here]"
labels: bug
assignees: ''
---
Please read the [guide for contributing](https://github.com/Electroblob77/Wizardry/blob/1.12.2/guide_for_contributing.md) before posting.
Minecraft version: 1.12.2 [change as necessary]
Wizardry version: 4.1.4 [change as necessary]
Environment: Singleplayer/LAN game/Server [delete as necessary]
Issue details: [describe what you were doing when the issue occurred, what went wrong, what you expected to happen, etc.]
Other mods involved: [only list mods that are relevant to the problem]
Link to crash report (if applicable): [give a link to the crash report on gist, pastebin, etc.]
-16
View File
@@ -1,16 +0,0 @@
---
name: Feature request
about: Make a suggestion for improving the mod
title: "[Give a brief, relevant title here]"
labels: enhancement
assignees: ''
---
Please read the [guide for contributing](https://github.com/Electroblob77/Wizardry/blob/1.12.2/guide_for_contributing.md) before posting.
Minecraft versions: [if this suggestion only applies to some versions, list them here]
Suggestion details: [describe what you would like to see added to the mod and why]
Other mods involved: [if this suggestion involves integration with other mods, list them here]
+1 -5
View File
@@ -20,9 +20,5 @@ build
# other
eclipse
run
logs
/misc
/libs
libsfordeobf
generated
misc
Thumbs.db
+2 -10
View File
@@ -1,8 +1,8 @@
# Credits
Electroblob's Wizardry
Version 4.1.4
For Minecraft 1.12.2
Version 2.1.0
For Minecraft 1.10.2
Designed, coded and textured by Electroblob
@@ -12,17 +12,9 @@ Thanks also to the Minecraft modding community, which always has an answer to my
In addition, I'd like to thank the following individuals for their contributions to the mod:
#### Code
- Corail31
- 12foo
- Shadows-of-Fire
- HellFirePvP
#### Translations
- Russian: VilagVil
- Spanish and Mexican Spanish: MadWrist
- Chinese: ZHENGLOC and dragon-evol
Lightning ray sound effect from OhhWowProductions
+2 -4
View File
@@ -1,7 +1,5 @@
Please read the [guide for contributing](https://github.com/Electroblob77/Wizardry/blob/1.12.2/guide_for_contributing.md) before posting.
Minecraft version: 1.12.2 [change as necessary]
Wizardry version: 4.1.4 [change as necessary]
Minecraft version: 1.10.2 [change as necessary]
Wizardry version: 2.1.0 [change as necessary]
Environment: Singleplayer/LAN game/Server [delete as necessary]
Issue details: [describe what you were doing when the issue occurred, what went wrong, what you expected to happen, etc.]
+4 -4
View File
@@ -1,7 +1,7 @@
# License
This repository is copyright © Electroblob 2018. The following license is provided to allow you to creatively contribute to and improve the repository.
This license applies only to the source code, assets and wiki pages present in this repository. The compiled mod (available at https://minecraft.curseforge.com/projects/electroblobs-wizardry) comes under its own separate license, see the aforementioned webpage for details. By downloading, running, forking, contributing to or otherwise interacting with this repository, you agree to the license set out below.
This license applies only to the source code and assets present in this repository. The compiled mod (available at https://minecraft.curseforge.com/projects/electroblobs-wizardry) comes under its own separate license, see the aforementioned webpage for details.
TL;DR: Do what you want with this repo on Github, but ask me first if you want to put it anywhere else or publish your version. Don't try and make money off the repo or anything in it. I'm not responsible if the code breaks things, and if you help me out by submitting a PR, I can use and modify the contents of that PR as long as I give you credit. (This brief summary is non-binding and does not override or replace the full license below.)
@@ -17,7 +17,7 @@ TL;DR: Do what you want with this repo on Github, but ask me first if you want t
'Electroblob's Wizardry', 'Wizardry', 'the mod' - The Minecraft modification Electroblob's Wizardry
'Repository' - This repository on Github, containing this license, the wiki, other informational files, configurations, code and assets which are part of Electroblob's Wizardry
'Repository' - This repository on Github, containing this license, other informational files, configurations, code and assets which are part of Electroblob's Wizardry
'Curseforge' - The webpage https://minecraft.curseforge.com/projects/electroblobs-wizardry
@@ -27,7 +27,7 @@ TL;DR: Do what you want with this repo on Github, but ask me first if you want t
### 1. Warranty and usage
This repository, the source code for the Minecraft modification Electroblob's Wizardry ('Wizardry'), is provided in the hope that it will be useful and/or educational. You are free to download and modify this repository for personal use. See section 2 for details regarding public sharing of this repository.
This repository, the source code for the Minecraft modification Electroblob's Wizardry ('Wizardry'), is provided in the hope that it will be useful and/or educational. You are free to download and modify this repository for personal use only. See section 2 for details regarding public sharing of this repository.
THIS REPOSITORY IS PROVIDED AS-IS WITH NO WARRANTIES, IMPLIED OR OTHERWISE. ELECTROBLOB TAKES NO RESPONSIBILITY FOR ANY DAMAGES INCURRED BY THE USE OR MISUSE OF THIS REPOSITORY.
@@ -37,7 +37,7 @@ In addition to private use as set out in section 1, you are free to fork this re
### 3. Distribution
Distribution of this repository anywhere except on Github, in whole or in part, modified or otherwise, is forbidden without advance written permission from Electroblob. Electroblob reserves the right to refuse or withdraw such permission at any time.
Distribution, in whole or in part, of compiled versions of wizardry, and distribution of the source code anywhere except on Github, modified or otherwise, is forbidden without advance written permission from Electroblob. Electroblob reserves the right to refuse or withdraw such permission at any time.
### 4. Commercial use
+1 -1
View File
@@ -1,4 +1,4 @@
# Wizardry  [![Curseforge](http://cf.way2muchnoise.eu/full_electroblobs-wizardry_downloads.svg)](https://minecraft.curseforge.com/projects/electroblobs-wizardry) [![Curseforge](http://cf.way2muchnoise.eu/versions/For%20MC_electroblobs-wizardry_all.svg)](https://minecraft.curseforge.com/projects/electroblobs-wizardry/files) [![Packs](https://images1-focus-opensocial.googleusercontent.com/gadgets/proxy?container=focus&url=https://cf.way2muchnoise.eu/packs/full_electroblobs-wizardry_in_packs.svg)](https://minecraft.curseforge.com/projects/electroblobs-wizardry/relations/dependents) [![Discord](https://img.shields.io/discord/417798297265242145.svg?colorB=7289DA&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHYAAABWAgMAAABnZYq0AAAACVBMVEUAAB38%2FPz%2F%2F%2F%2Bm8P%2F9AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfhBxwQJhxy2iqrAAABoElEQVRIx7WWzdGEIAyGgcMeKMESrMJ6rILZCiiBg4eYKr%2Fd1ZAfgXFm98sJfAyGNwno3G9sLucgYGpQ4OGVRxQTREMDZjF7ILSWjoiHo1n%2BE03Aw8p7CNY5IhkYd%2F%2F6MtO3f8BNhR1QWnarCH4tr6myl0cWgUVNcfMcXACP1hKrGMt8wcAyxide7Ymcgqale7hN6846uJCkQxw6GG7h2MH4Czz3cLqD1zHu0VOXMfZjHLoYvsdd0Q7ZvsOkafJ1P4QXxrWFd14wMc60h8JKCbyQvImzlFjyGoZTKzohwWR2UzSONHhYXBQOaKKsySsahwGGDnb%2FiYPJw22sCqzirSULYy1qtHhXGbtgrM0oagBV4XiTJok3GoLoDNH8ooTmBm7ZMsbpFzi2bgPGoXWXME6XT%2BRJ4GLddxJ4PpQy7tmfoU2HPN6cKg%2BledKHBKlF8oNSt5w5g5o8eXhu1IOlpl5kGerDxIVT%2BztzKepulD8utXqpChamkzzuo7xYGk%2FkpSYuviLXun5bzdRf0Krejzqyz7Z3p0I1v2d6HmA07dofmS48njAiuMgAAAAASUVORK5CYII%3D)](https://discord.gg/MTmMzMv)
# Wizardry  [![Curseforge](http://cf.way2muchnoise.eu/full_electroblobs-wizardry_downloads.svg)](https://minecraft.curseforge.com/projects/electroblobs-wizardry) [![Curseforge](http://cf.way2muchnoise.eu/versions/For%20MC_electroblobs-wizardry_all.svg)](https://minecraft.curseforge.com/projects/electroblobs-wizardry) [![Discord](https://img.shields.io/discord/417798297265242145.svg?colorB=7289DA&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHYAAABWAgMAAABnZYq0AAAACVBMVEUAAB38%2FPz%2F%2F%2F%2Bm8P%2F9AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfhBxwQJhxy2iqrAAABoElEQVRIx7WWzdGEIAyGgcMeKMESrMJ6rILZCiiBg4eYKr%2Fd1ZAfgXFm98sJfAyGNwno3G9sLucgYGpQ4OGVRxQTREMDZjF7ILSWjoiHo1n%2BE03Aw8p7CNY5IhkYd%2F%2F6MtO3f8BNhR1QWnarCH4tr6myl0cWgUVNcfMcXACP1hKrGMt8wcAyxide7Ymcgqale7hN6846uJCkQxw6GG7h2MH4Czz3cLqD1zHu0VOXMfZjHLoYvsdd0Q7ZvsOkafJ1P4QXxrWFd14wMc60h8JKCbyQvImzlFjyGoZTKzohwWR2UzSONHhYXBQOaKKsySsahwGGDnb%2FiYPJw22sCqzirSULYy1qtHhXGbtgrM0oagBV4XiTJok3GoLoDNH8ooTmBm7ZMsbpFzi2bgPGoXWXME6XT%2BRJ4GLddxJ4PpQy7tmfoU2HPN6cKg%2BledKHBKlF8oNSt5w5g5o8eXhu1IOlpl5kGerDxIVT%2BztzKepulD8utXqpChamkzzuo7xYGk%2FkpSYuviLXun5bzdRf0Krejzqyz7Z3p0I1v2d6HmA07dofmS48njAiuMgAAAAASUVORK5CYII%3D)](https://discord.gg/MTmMzMv)
![Image not found](https://media-elerium.cursecdn.com/attachments/203/387/banner7.png)
+33 -70
View File
@@ -1,58 +1,44 @@
buildscript {
repositories {
jcenter()
maven { url = "http://files.minecraftforge.net/maven" }
mavenCentral()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven {
name = "sonatype"
url = "https://oss.sonatype.org/content/repositories/snapshots/"
}
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
//Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'forge'
version = "4.2.1" // There, it matches semver, happy now?
version = " 1.1.4 - MC 1.7.10"
group= "electroblob.wizardry"// http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = "ElectroblobsWizardry"
sourceCompatibility = targetCompatibility = "1.8" // Need this here so eclipse task generates correctly.
compileJava {
sourceCompatibility = targetCompatibility = "1.8"
}
repositories {
maven {
// location of the maven that hosts JEI files
name = "Progwml6 maven"
url = "http://dvs1.progwml6.com/files/maven"
}
maven {
// location of a maven mirror for JEI files, as a fallback
name = "ModMaven"
url = "modmaven.k-4u.nl"
}
flatDir {
// evErYthINg hAS tO Be a mAVeN rEPoSiTOrY... (to use deobfProvided, for some reason)
// The lack of documentation is actually quite impressive, see the following threads:
// http://www.minecraftforge.net/forum/topic/44262-solved-how-to-build-mod-with-dependencies/
// https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/mapping-and-modding-tutorials/2866817-setting-up-dependencies-in-minecraft-forge-with
// http://www.minecraftforge.net/forum/topic/44534-adding-dependencies-to-a-forge-project/
dirs "libsfordeobf" // Don't put src jars in libs or forge will think you have duplicate mods
}
}
archivesBaseName = "Electroblob's Wizardry "
minecraft {
version = "1.12.2-14.23.5.2814"
runDir = "run"
// the mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD snapshot are built nightly.
// stable_# stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work.
// simply re-run your setup task after changing the mappings to update your workspace.
mappings = "stable_39"
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
version = "1.7.10-10.13.4.1558-1.7.10"
runDir = "eclipse"
}
task deobfJar(type: Jar) { // Generate deobfuscated
from sourceSets.main.output
classifier = 'deobf'
}
task sourceJar(type: Jar) { // Generate sources
from sourceSets.main.allSource
classifier = 'sources'
}
tasks.build.dependsOn('sourceJar', 'deobfJar')
artifacts {
archives deobfJar
archives sourceJar
archives jar
}
dependencies {
@@ -60,42 +46,19 @@ dependencies {
// or you may define them like so..
//compile "some.group:artifact:version:classifier"
//compile "some.group:artifact:version"
// compile against the JEI API but do not include it at runtime
deobfProvided "mezz.jei:jei_${mc_version}:${jei_version}:api"
// at runtime, use the full JEI jar
runtime "mezz.jei:jei_${mc_version}:${jei_version}"
//deobfProvided "baubles:baubles-1.12:1.5.2:api" // #ihavenoideawhatimdoing #itjustworks
//runtime "baubles:baubles-1.12:1.5.2" // If in doubt, copy what already works
//deobfProvided "antiqueatlas:antiqueatlas-1.12.2:4.5.1:src"
//runtime "antiqueatlas:antiqueatlas-1.12.2:4.5.1"
// real examples
//compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
//compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// the 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
//provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// the deobf configurations: 'deobfCompile' and 'deobfProvided' are the same as the normal compile and provided,
// except that these dependencies get remapped to your current MCP mappings
//deobfCompile 'com.mod-buildcraft:buildcraft:6.0.8:dev'
//deobfProvided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// for more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
task deobfJar(type: Jar) {
from sourceSets.main.output
classifier = 'deobf'
}
processResources {
processResources
{
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
@@ -108,7 +71,7 @@ processResources {
expand 'version':project.version, 'mcversion':project.minecraft.version
}
// copy everything else except the mcmod.info
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
-5
View File
@@ -1,5 +0,0 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
mc_version=1.12.2
jei_version=4.13.1.225
Binary file not shown.
+2 -2
View File
@@ -1,6 +1,6 @@
#Mon Sep 14 12:28:28 PDT 2015
#Wed Jul 02 15:54:47 CDT 2014
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip
Vendored
+2 -2
View File
@@ -79,14 +79,14 @@ if [ -n "$JAVA_HOME" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
locations of your Java installation."
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
locations of your Java installation."
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
Vendored
+2 -2
View File
@@ -27,7 +27,7 @@ echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo locations of your Java installation.
echo location of your Java installation.
goto fail
@@ -41,7 +41,7 @@ echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo locations of your Java installation.
echo location of your Java installation.
goto fail
+1 -16
View File
@@ -2,22 +2,7 @@
## Submitting an issue
When submitting an issue, I would be grateful if you could follow these few guidelines:
- First and foremost, please check your issue hasn't already been posted. The issue tracker is searchable, so try typing in a few keywords and see if anything comes up.
- Please stick to the issue template, it's there to help you provide the right information so I can fix the problem more easily. If you're not sure what to put for anything, that's ok, just leave it as it is.
- Please give me as much information about the issue as you can, but keep it relevant. "This is really annoying me and my friend" does not help me fix the problem!
- Make sure your wizardry and Forge versions are both up-to-date for the game version you are using.
- There's no need to put 'tags' in square brackets in the issue title, I'll put proper github issue tags on it which will also help organise it. You can use them to search for issues too!
- Don't close an issue unless it has actually been fixed or is no longer relevant - otherwise I might not end up fixing it at all! Usually I'll take care of closing issues anyway, so you don't have to worry about it.
- Most importantly, use gist or pastebin to post crash reports. Do not paste the entire crash report inline, not even in a code block!
> If you've got a git account (which you do, if you're posting an issue) you can access gist, and pastebin doesn't require an account at all, so there's no excuse!
When submitting an issue, please stick to the issue template. Please give me as much information about the issue as you can, but keep it relevant. "This is really annoying me and my friend" does not help me fix the problem! Most importantly, use gist or pastebin to post crash reports.
## Submitting a PR
Binary file not shown.
Binary file not shown.
@@ -1,254 +1,203 @@
package electroblob.wizardry;
import electroblob.wizardry.item.ItemSpectralBow;
import electroblob.wizardry.packet.*;
import electroblob.wizardry.registry.WizardryItems;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import cpw.mods.fml.common.FMLCommonHandler;
import electroblob.wizardry.packet.PacketCastContinuousSpell;
import electroblob.wizardry.packet.PacketCastSpell;
import electroblob.wizardry.packet.PacketClairvoyance;
import electroblob.wizardry.packet.PacketGlyphData;
import electroblob.wizardry.packet.PacketPlayerSync;
import electroblob.wizardry.packet.PacketTransportation;
import electroblob.wizardry.spell.Spell;
import net.minecraft.block.state.IBlockState;
import net.minecraft.block.Block;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Property;
import java.util.List;
import java.util.Set;
/**
* The common proxy for wizardry, serving the usual purpose of dealing with all things that need to be handled
* differently on the client and the server. A lot of the methods here appear to do absolutely nothing; this is because
* they do client-only things which are only handled in the client proxy.
*
* @see electroblob.wizardry.client.ClientProxy ClientProxy
* @author Electroblob
* @since Wizardry 1.0
*/
@SuppressWarnings("deprecation")
/** The common proxy for wizardry, serving the usual purpose of dealing with all things that need to be handled
* differently on the client and the server. A lot of the methods here appear to do absolutely nothing; this is
* because they do client-only things which are only handled in the client proxy.
* @see {@link electroblob.wizardry.client.ClientProxy} */
public class CommonProxy {
// SECTION Registry
// ===============================================================================================================
public void registerRenderers(){}
public void initialiseLayers(){}
public void registerKeyBindings(){}
public net.minecraft.client.model.ModelBiped getWizardArmourModel(){
return null;
}
public void initGuiBits(){}
/** Used to store IExtendedEntityProperties data temporarily between player death and respawn */
private static final Map<String, NBTTagCompound> extendedEntityData = new HashMap<String, NBTTagCompound>();
public void registerResourceReloadListeners(){}
public void registerSoundEventListener(){}
public void registerAtlasMarkers(){}
// SECTION Particles
// ===============================================================================================================
/** Called from init() in the main mod class to initialise the particle factories. */
public void registerParticles(){} // Does nothing since particles are client-side only
/** Creates a new particle of the specified type from the appropriate particle factory. <i>Does not actually spawn the
* particle; use {@link electroblob.wizardry.util.ParticleBuilder ParticleBuilder} to spawn particles.</i> */
public electroblob.wizardry.client.particle.ParticleWizardry createParticle(ResourceLocation type, World world, double x, double y, double z){
public void registerRenderers(){}
public void registerKeyBindings(){}
public void registerSpellHUD(){}
public ModelBiped getWizardArmourModel(){
return null;
}
/**
* Adds an entity's custom data to the map for temporary storage
* @param compound An NBT Tag Compound that stores the IExtendedEntityProperties data only
*/
public static void storeEntityData(String name, NBTTagCompound compound){
extendedEntityData.put(name, compound);
}
public void spawnTornadoParticle(World world, double x, double y, double z, double velX, double velZ, double radius,
int maxAge, IBlockState block, BlockPos pos){
/**
* Removes the compound from the map and returns the NBT tag stored for name or null if none exists
*/
public static NBTTagCompound getEntityData(String name){
return extendedEntityData.remove(name);
}
public double getPlayerEyesPos(EntityPlayer player){
return player.posY + player.eyeHeight;
}
/** Gets the absolute coordinates of the tip of the wand belonging to the given entity. If this is a client in
* first person view, the coordinates will instead be the entity's position + 1.2. */
public Vec3 getWandTipPosition(EntityLivingBase entity){
// 0.7 forwards, 0.4 to the right, and 1.35 upwards.
double x = entity.posX - 0.7*Math.sin(Math.toRadians(entity.renderYawOffset)) - 0.4*Math.cos(Math.toRadians(entity.renderYawOffset));
double y = entity.boundingBox.minY + 1.35;
double z = entity.posZ + 0.7*Math.cos(Math.toRadians(entity.renderYawOffset)) - 0.4*Math.sin(Math.toRadians(entity.renderYawOffset));
return Vec3.createVectorHelper(x, y, z);
}
/**
* Spawns a custom particle of the specified type.
*
* @param type EnumParticleType of the particle
* @param world Reference to the World object
* @param x Particle x position
* @param y Particle y position
* @param z Particle z position
* @param velX Particle x velocity
* @param velY Particle y velocity
* @param velZ Particle z velocity
* @param maxAge Lifetime of the particle in ticks
* @param r Red component of particle colour
* @param g Red component of particle colour
* @param b Red component of particle colour
* @param doGravity Whether the particle is affected by gravity (only affects SPARKLE at the moment)
* @param radius The radius of the particle's motion, for cirular motion particles
*/
public void spawnParticle(EnumParticleType type, World world, double x, double y, double z, double velX, double velY, double velZ, int maxAge, float r, float g, float b, boolean doGravity, double radius){
// Does nothing since particles are client-side only
}
/** Spawns a custom particle of the specified type. doGravity defaults to false and radius defaults to 0.
* Note that some of these settings may not affect the particle; some particles are always affected by
* gravity, for instance.
*
* @param type EnumParticleType of the particle
* @param world Reference to the World object
* @param x Particle x position
* @param y Particle y position
* @param z Particle z position
* @param velX Particle x velocity
* @param velY Particle y velocity
* @param velZ Particle z velocity
* @param maxAge Lifetime of the particle in ticks
* @param r Red component of particle colour (unless this is a MAGIC_FIRE particle, in which case this is the scale)
* @param g Red component of particle colour
* @param b Red component of particle colour
*/
public void spawnParticle(EnumParticleType type, World world, double x, double y, double z, double velX, double velY, double velZ, int maxAge, float r, float g, float b){
this.spawnParticle(type, world, x, y, z, velX, velY, velZ, maxAge, r, g, b, false, 0);
}
/** Spawns a custom particle of the specified type. Colour defaults to white, doGravity defaults to false and radius
* defaults to 0. Note that some of these settings may not affect the particle; some particles are always affected by
* gravity, for instance.
*
* @param type EnumParticleType of the particle
* @param world Reference to the World object
* @param x Particle x position
* @param y Particle y position
* @param z Particle z position
* @param velX Particle x velocity
* @param velY Particle y velocity
* @param velZ Particle z velocity
* @param maxAge Lifetime of the particle in ticks
*/
public void spawnParticle(EnumParticleType type, World world, double x, double y, double z, double velX, double velY, double velZ, int maxAge){
this.spawnParticle(type, world, x, y, z, velX, velY, velZ, maxAge, 1, 1, 1, false, 0);
}
public void spawnDigParticle(World world, double x, double y, double z, double velX, double velY, double velZ, Block block){}
public void spawnTornadoParticle(World world, double x, double y, double z, double velX, double velZ, double radius, int maxAge, Block block, int metadata){}
/** Plays a sound which moves with the given entity.
*
* @param entity The source of the sound
* @param soundName String resource path of the sound
* @param volume Volume relative to 1
* @param pitch Pitch relative to 1
* @param repeat Whether to repeat the sound for as long as the entity is alive (or until stopped manually)
*/
public void playMovingSound(Entity entity, String soundName, float volume, float pitch, boolean repeat){}
public void handleCastSpellPacket(PacketCastSpell.Message message){}
public double getWandDisplayDamage(ItemStack stack){
return 1.0d;
}
public int getConjuredItemDisplayDamage(ItemStack stack){
return 0;
}
// SECTION Items
// ===============================================================================================================
public boolean shouldDisplayDiscovered(Spell spell, ItemStack stack){
return false;
public void registerEventHandlers(){
MinecraftForge.EVENT_BUS.register(new WizardryEventHandler());
}
public net.minecraft.client.gui.FontRenderer getFontRenderer(ItemStack stack){
public void handleTransportationPacket(PacketTransportation.Message message){}
public FontRenderer getFontRenderer(ItemStack stack) {
return null;
}
/**
* Returns the translated name of the scroll, taking spell discovery into account. If, for some reason, this gets
* called server-side, it uses the deprecated server version of I18n. Since any likely server-side
* use of this method will be for text-based logic purposes (like Bibliocraft's book checking system), and since
* no particular player instance can be accessed, spell discovery is ignored.
*/
/** Returns the translated name of the scroll, taking spell discovery into account. If, for some reason, this gets
* called server-side, it uses the deprecated server version of I18n, with a warning. Since any likely server-side
* use of this method will be for text-based logic purposes (like Bibliocraft's book checking system), and since no
* particular player instance can be accessed, spell discovery is ignored. */
public String getScrollDisplayName(ItemStack scroll){
Spell spell = Spell.byMetadata(scroll.getItemDamage());
return I18n.translateToLocalFormatted("item." + Wizardry.MODID + ":scroll.name",
I18n.translateToLocal("spell." + spell.getUnlocalisedName())).trim();
// I have now learnt that the server side I18n always translates to the default en_US, so I could just return
// a hardcoded name in English instead.
//Wizardry.logger.info("A mod has called ItemScroll#getItemStackDisplayName from the server side. Using the"
// + "deprecated server-side translation methods as a fallback.");
// Displays [Empty slot] if spell is continuous.
Spell spell = Spell.get(scroll.getItemDamage());
if(spell.isContinuous) spell = WizardryRegistry.none;
return StatCollector.translateToLocalFormatted("item.scroll.name", StatCollector.translateToLocal("spell." + spell.getUnlocalisedName())).trim();
}
public double getConjuredBowDurability(ItemStack stack){
return ((ItemSpectralBow)WizardryItems.spectral_bow).getDefaultDurabilityForDisplay(stack);
}
/** Like {@link CommonProxy#addMultiLineDescription(List, String, Style)}, but style defaults to light grey. */
public void addMultiLineDescription(List<String> tooltip, String key){
this.addMultiLineDescription(tooltip, key, new Style().setColor(TextFormatting.GRAY));
}
/**
* Adds a multi-line description to the given tooltip list. The description is first translated using the given
* translation key, then the formatting code for the given style is appended, and finally the string is word-wrapped
* to the standard width (100).
* @param tooltip The tooltip list to add to
* @param key The translation key for the description
* @param style A style to apply
*/
public void addMultiLineDescription(List<String> tooltip, String key, Style style){}
// SECTION Packet Handlers
// ===============================================================================================================
public void handlePlayerSyncPacket(PacketPlayerSync.Message message){}
public void handleGlyphDataPacket(PacketGlyphData.Message message){}
public void handleEmitterDataPacket(PacketEmitterData.Message message){}
public void handleCastSpellPacket(PacketCastSpell.Message message){}
public void handleCastContinuousSpellPacket(PacketCastContinuousSpell.Message message){}
public void handleNPCCastSpellPacket(PacketNPCCastSpell.Message message){}
public void handleDispenserCastSpellPacket(PacketDispenserCastSpell.Message message){}
public void handleCastSpellAtPosPacket(PacketCastSpellAtPos.Message message){}
public void handleTransportationPacket(PacketTransportation.Message message){}
public void setToNumberSliderEntry(Property property){}
public void handleClairvoyancePacket(PacketClairvoyance.Message message){}
public void handleAdvancementSyncPacket(PacketSyncAdvancements.Message message){}
public void handleEndSlowTimePacket(PacketEndSlowTime.Message message){}
public void handleResurrectionPacket(PacketResurrection.Message message){}
public void handlePossessionPacket(PacketPossession.Message message){}
public void handleConquerShrinePacket(PacketConquerShrine.Message message){}
// SECTION Misc
// ===============================================================================================================
public void setToNumberSliderEntry(Property property){}
public void setToHUDChooserEntry(Property property){}
public void setToNamedBooleanEntry(Property property){}
// public void setToEntityNameEntry(Property property){}
/**
* Plays a sound which moves with the given entity.
*
* @param entity The source of the sound
* @param sound The SoundEvent to play
* @param category The SoundCategory to use
* @param volume Volume relative to 1
* @param pitch Pitch relative to 1
* @param repeat Whether to repeat the sound for as long as the entity is alive (or until stopped manually)
*/
public void playMovingSound(Entity entity, SoundEvent sound, SoundCategory category, float volume, float pitch, boolean repeat){}
/**
* Plays a continuous spell sound which moves with the given entity.
*
* @param entity The source of the sound
* @param spell The spell this sound is associated with
* @param start The starting SoundEvent to play
* @param loop The main looped SoundEvent to play
* @param end The ending SoundEvent to play
* @param category The SoundCategory to use
* @param volume Volume relative to 1
* @param pitch Pitch relative to 1
*/
public void playSpellSoundLoop(EntityLivingBase entity, Spell spell, SoundEvent start, SoundEvent loop, SoundEvent end, SoundCategory category, float volume, float pitch){}
/**
* Plays a continuous spell sound which moves with the given entity.
*
* @param entity The source of the sound
* @param spell The spell this sound is associated with
* @param sounds An array of the sound events to play, which must have three elements in the order: start, loop, end
* @param category The SoundCategory to use
* @param volume Volume relative to 1
* @param pitch Pitch relative to 1
* @throws IllegalArgumentException if the given array contains less than 3 sound events
*/
public void playSpellSoundLoop(EntityLivingBase entity, Spell spell, SoundEvent[] sounds, SoundCategory category, float volume, float pitch){
if(sounds.length < 3) throw new IllegalArgumentException("Tried to play a continuous spell sound using an array "
+ "of sound events, but the given array contained less than 3 sound events!");
playSpellSoundLoop(entity, spell, sounds[0], sounds[1], sounds[2], category, volume, pitch);
}
/**
* Plays a continuous spell sound at the given position.
* @param world The world in which to play the sound
* @param x The x coordinate to play the sound at
* @param y The y coordinate to play the sound at
* @param z The z coordinate to play the sound at
* @param spell The spell this sound is associated with
* @param start The starting SoundEvent to play
* @param loop The main looped SoundEvent to play
* @param end The ending SoundEvent to play
* @param category The SoundCategory to use
* @param volume Volume relative to 1
* @param pitch Pitch relative to 1
* @param duration The duration of the sound, or -1 to link it to a dispenser at the given coordinates
*/
public void playSpellSoundLoop(World world, double x, double y, double z, Spell spell, SoundEvent start, SoundEvent loop, SoundEvent end, SoundCategory category, float volume, float pitch, int duration){}
/**
* Plays a continuous spell sound at the given position.
*
* @param world The world in which to play the sound
* @param x The x coordinate to play the sound at
* @param y The y coordinate to play the sound at
* @param z The z coordinate to play the sound at
* @param spell The spell this sound is associated with
* @param sounds An array of the sound events to play, which must have three elements in the order: start, loop, end
* @param category The SoundCategory to use
* @param volume Volume relative to 1
* @param pitch Pitch relative to 1
* @param duration The duration of the sound, or -1 to link it to a dispenser at the given coordinates
* @throws IllegalArgumentException if the given array contains less than 3 sound events
*/
public void playSpellSoundLoop(World world, double x, double y, double z, Spell spell, SoundEvent[] sounds, SoundCategory category, float volume, float pitch, int duration){
if(sounds.length < 3) throw new IllegalArgumentException("Tried to play a continuous spell sound using an array "
+ "of sound events, but the given array contained less than 3 sound events!");
playSpellSoundLoop(world, x, y, z, spell, sounds[0], sounds[1], sounds[2], category, volume, pitch, duration);
}
/**
* Gets the client side world using Minecraft.getMinecraft().world. <b>Only to be called client side!</b> Returns
* null on the server side.
*/
public World getTheWorld(){
return null;
}
/** Returns an unmodifiable set of the string keys for all of the loaded spell HUD skins. */
public Set<String> getSpellHUDSkins(){
return null;
}
}
@@ -0,0 +1,39 @@
package electroblob.wizardry;
import net.minecraft.util.StatCollector;
public enum EnumElement {
MAGIC("\u00A77", "simple"),
FIRE("\u00A74", "fire"),
ICE("\u00A7b", "ice"),
LIGHTNING("\u00A73", "lightning"),
NECROMANCY("\u00A75", "necromancy"),
EARTH("\u00A72", "earth"),
SORCERY("\u00A7a", "sorcery"),
HEALING("\u00A7e", "healing");
/** Display colour for this element */
public final String colour;
/** Unlocalised name for this element */
public final String unlocalisedName;
private EnumElement(String colour, String name){
this.colour = colour;
this.unlocalisedName = name;
}
public EnumElement get(int id){
return this.values()[id];
}
/** Returns the translated display name of this element, without formatting. */
public String getDisplayName() {
return StatCollector.translateToLocal("element." + unlocalisedName);
}
/** Returns the translated display name for wizards of this element, shown in the trading GUI */
public String getWizardName() {
return StatCollector.translateToLocal("element." + unlocalisedName + ".wizard");
}
}
@@ -0,0 +1,16 @@
package electroblob.wizardry;
public enum EnumParticleType {
BLIZZARD,
BRIGHT_DUST,
DARK_MAGIC,
DUST,
ICE,
LEAF,
MAGIC_BUBBLE,
MAGIC_FIRE,
PATH,
SNOW,
SPARK,
SPARKLE
}
@@ -0,0 +1,21 @@
package electroblob.wizardry;
import net.minecraft.util.StatCollector;
public enum EnumSpellType {
ATTACK("attack"),
DEFENCE("defence"),
UTILITY("utility"),
MINION("minion");
private final String unlocalisedName;
EnumSpellType(String name){
this.unlocalisedName = name;
}
public String getDisplayName() {
return StatCollector.translateToLocal("spelltype." + unlocalisedName);
}
}
@@ -0,0 +1,38 @@
package electroblob.wizardry;
import net.minecraft.util.StatCollector;
public enum EnumTier {
BASIC(700, 3, "\u00A7f", "basic"),
APPRENTICE(1000, 4, "\u00A7b", "apprentice"),
ADVANCED(1500, 5, "\u00A71", "advanced"),
MASTER(2500, 6, "\u00A75", "master");
/** Maximum mana a wand of this tier can store. */
public final int maxCharge;
/** Just an ordinal. Shouldn't really be needed but no point changing it now. */
public final int level;
/** The maximum number of upgrades that can be applied to a wand of this tier. */
public final int upgradeLimit;
/** The colour of text associated with this tier */
public final String colour;
private final String unlocalisedName;
private EnumTier(int maxCharge, int upgradeLimit, String colour, String name){
this.maxCharge = maxCharge;
this.level = ordinal();
this.upgradeLimit = upgradeLimit;
this.colour = colour;
this.unlocalisedName = name;
}
public String getDisplayName() {
return StatCollector.translateToLocal("tier." + unlocalisedName);
}
public String getDisplayNameWithFormatting() {
return this.colour + StatCollector.translateToLocal("tier." + unlocalisedName);
}
}
@@ -0,0 +1,485 @@
package electroblob.wizardry;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.UUID;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import electroblob.wizardry.MagicDamage.DamageType;
import electroblob.wizardry.entity.EntityShield;
import electroblob.wizardry.entity.living.EntitySummonedCreature;
import electroblob.wizardry.packet.PacketCastContinuousSpell;
import electroblob.wizardry.packet.PacketPlayerSync;
import electroblob.wizardry.packet.PacketTransportation;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.spell.None;
import electroblob.wizardry.spell.Spell;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import net.minecraftforge.common.util.Constants.NBT;
/** IExtendedEntityProperties for players. Everything player-data-related that is needed by wizardry is handled here,
* including the ADS, soulbinding, conjured items, summoned wolves and horses, transportation and clairvoyance. */
public class ExtendedPlayer implements IExtendedEntityProperties {
public final static String name = "WizardryExtendedPlayer";
private final EntityPlayer player;
public int damageToApply;
// These were originally done using the item damage directly, but this caused the annoying re-equip animation
// to keep happening so they were moved to here instead.
public int conjuredSwordDuration;
public int conjuredPickaxeDuration;
public int conjuredBowDuration;
public int conjuredArmourDuration;
public int flamingAxeDuration;
public int frostAxeDuration;
public int magicWeaponDuration;
public int flamingWeaponDuration;
public int freezingWeaponDuration;
public boolean hasSpiritWolf;
public boolean hasSpiritHorse;
/** Whether this player is currently casting a continuous spell via commands. Not saved over world reload
* and reset on player death. */
private Spell currentlyCasting;
/** The time for which this player has been casting a continuous spell via commands. Increments by 1 each tick.
* Not saved over world reload and reset on player death. */
private int castingTick;
/** The damage multiplier for the current continuous spell cast via commands. Not saved over world reload and
* reset on player death. */
private float spellDamageMultiplier;
/** The range multiplier for the current continuous spell cast via commands. Not saved over world reload and
* reset on player death. */
private float spellRangeMultiplier;
/** The duration multiplier for the current continuous spell cast via commands. Not saved over world reload and
* reset on player death. */
private float spellDurationMultiplier;
/** The blast multiplier for the current continuous spell cast via commands. Not saved over world reload and
* reset on player death. */
private float spellBlastMultiplier;
/** Coordinate for the saved transportation stone location. Will be -1 if no location is saved. */
public int transportX, transportY, transportZ;
/** Dimension id which the saved stone circle is in. */
public int transportDimension;
/** Time left until the player teleports under the effect of transportation */
public int tpTimer;
/** Coordinate for the saved clairvoyance location. Will be -1 if no location is saved. */
public int clairvoyanceX, clairvoyanceY, clairvoyanceZ;
/** Dimension id which the saved clairvoyance point is in. */
public int clairvoyanceDimension;
public EntityShield shield;
public WeakReference<EntitySummonedCreature> selectedMinion;
public HashSet<Spell> spellsDiscovered;
private HashSet<UUID> allies;
/** List of usernames of this player's allies. May not be accurate 100% of the time. This is here so that a player
* can view the usernames of their allies even when those allies are not online.
* <b> Do not use this for any other purpose than displaying the names! */
public HashSet<String> allyNames;
private HashSet<UUID> soulboundCreatures;
public ExtendedPlayer(EntityPlayer player){
this.player = player;
this.damageToApply = 0;
this.conjuredSwordDuration = 0;
this.conjuredPickaxeDuration = 0;
this.conjuredBowDuration = 0;
this.conjuredArmourDuration = 0;
this.flamingAxeDuration = 0;
this.frostAxeDuration = 0;
this.magicWeaponDuration = 0;
this.flamingWeaponDuration = 0;
this.freezingWeaponDuration = 0;
this.spellsDiscovered = new HashSet<Spell>();
// All players can recognise magic missile. This is not done using discoverSpell because that seems to cause
// a crash on load occasionally (probably something to do with achievements being initalised)
this.spellsDiscovered.add(WizardryRegistry.magicMissile);
this.hasSpiritWolf = false;
this.hasSpiritHorse = false;
this.currentlyCasting = WizardryRegistry.none;
this.spellDamageMultiplier = 1;
this.spellRangeMultiplier = 1;
this.spellDurationMultiplier = 1;
this.spellBlastMultiplier = 1;
this.castingTick = 0;
this.transportX = -1;
this.transportY = -1;
this.transportZ = -1;
this.transportDimension = 0;
this.clairvoyanceX = -1;
this.clairvoyanceY = -1;
this.clairvoyanceZ = -1;
this.clairvoyanceDimension = 0;
this.tpTimer = 0;
this.allies = new HashSet<UUID>();
this.allyNames = new HashSet<String>();
this.soulboundCreatures = new HashSet<UUID>();
}
public boolean hasSpellBeenDiscovered(Spell spell){
return spellsDiscovered.contains(spell) || spell instanceof None;
}
/**
* Adds the spell to the list of discovered spells for this player. Automatically takes into account
* whether the spell has been discovered. Use this method rather than adding directly to the list
* because it handles the mage of all trades achievement.
* @param spell
*/
public void discoverSpell(Spell spell){
if(spellsDiscovered == null){
spellsDiscovered = new HashSet<Spell>();
}
if(!(spell instanceof None)){
spellsDiscovered.add(spell);
}
if(spellsDiscovered.containsAll(Spell.getSpells(Spell.enabledSpells))){
this.player.triggerAchievement(Wizardry.allSpells);
}
for(EnumElement element : EnumElement.values()){
if(element != EnumElement.MAGIC && spellsDiscovered.containsAll(Spell.getSpells(new Spell.TierElementFilter(null, element)))){
this.player.triggerAchievement(Wizardry.elementMaster);
}
}
}
/** Sets the player's saved transportation stone location. */
public void setStoneLocation(int x, int y, int z, int dimensionID){
this.transportX = x;
this.transportY = y;
this.transportZ = z;
this.transportDimension = dimensionID;
}
/** Sets the player's saved clairvoyance location. */
public void setClairvoyancePoint(int x, int y, int z, int dimensionID){
this.clairvoyanceX = x;
this.clairvoyanceY = y;
this.clairvoyanceZ = z;
this.clairvoyanceDimension = dimensionID;
}
/** Adds the given player to the list of allies belonging to the associated player, or removes the player if
* they are already in the list of allies. Returns true if the player was added, false if they were removed. */
public boolean toggleAlly(EntityPlayer player){
if(this.isPlayerAlly(player)){
this.allies.remove(player.getUniqueID());
// The remove method uses .equals() rather than == so this will work fine.
this.allyNames.remove(player.getCommandSenderName());
return false;
}else{
this.allies.add(player.getUniqueID());
this.allyNames.add(player.getCommandSenderName());
return true;
}
}
/** Returns whether the given player is in this player's list of allies, or is on the same team as this player. */
public boolean isPlayerAlly(EntityPlayer player){
return this.allies.contains(player.getUniqueID()) || this.player.isOnSameTeam(player);
}
/** Adds the given entity to this player's list of soulbound creatures, and returns whether it succeeded. */
public boolean soulbind(EntityLivingBase target){
return this.soulboundCreatures.add(target.getUniqueID());
}
/** Returns whether the given entity has been soulbound to this player. */
public boolean isCreatureSoulbound(EntityPlayer target){
return this.soulboundCreatures.contains(target.getUniqueID());
}
/** Damages all creatures soulbound to this player by the given amount, and removes from the list any that no
* longer exist. */
public void damageAllSoulboundCreatures(float damage){
for(Iterator<UUID> iterator = this.soulboundCreatures.iterator(); iterator.hasNext();){
Entity entity = WizardryUtilities.getEntityByUUID(this.player.worldObj, iterator.next());
if(entity == null) iterator.remove();
if(entity instanceof EntityLivingBase){
if(entity.attackEntityFrom(MagicDamage.causeDirectMagicDamage(this.player, DamageType.MAGIC), damage)){
// Sound only plays if the damage succeeds
player.worldObj.playSoundAtEntity(entity, "mob.wither.hurt", 1.0F, player.worldObj.rand.nextFloat() * 0.2F + 1.0F);
}
}
}
}
/** Starts casting the given spell with the given modifiers. */
public void startCastingContinuousSpell(Spell spell, float damageMultiplier, float rangeMultiplier, float durationMultiplier, float blastMultiplier){
this.currentlyCasting = spell;
this.spellDamageMultiplier = damageMultiplier;
this.spellRangeMultiplier = rangeMultiplier;
this.spellDurationMultiplier = durationMultiplier;
this.spellBlastMultiplier = blastMultiplier;
if(!this.player.worldObj.isRemote){
PacketCastContinuousSpell.Message message = new PacketCastContinuousSpell.Message(this.player.getEntityId(), spell.id(), damageMultiplier, rangeMultiplier, blastMultiplier);
WizardryPacketHandler.net.sendToDimension(message, this.player.worldObj.provider.dimensionId);
}
}
/** Stops casting the current spell. */
public void stopCastingContinuousSpell(){
this.currentlyCasting = WizardryRegistry.none;
this.castingTick = 0;
this.spellDamageMultiplier = 1;
this.spellRangeMultiplier = 1;
this.spellDurationMultiplier = 1;
this.spellBlastMultiplier = 1;
if(!this.player.worldObj.isRemote){
PacketCastContinuousSpell.Message message = new PacketCastContinuousSpell.Message(this.player.getEntityId(), WizardryRegistry.none.id(), 1, 1, 1);
WizardryPacketHandler.net.sendToDimension(message, this.player.worldObj.provider.dimensionId);
}
}
/** Returns whether this player is currently casting a continuous spell via commands. */
public boolean isCasting(){
return this.currentlyCasting != null && this.currentlyCasting != WizardryRegistry.none;
}
/** Returns the continuous spell this player is currently casting via commands, or the 'none' spell if they aren't
* casting anything. */
public Spell currentlyCasting(){
return currentlyCasting;
}
/** Called from the event handler each time the associated player is updated. */
public void update(EntityPlayer entityplayer){
if(this.selectedMinion != null && this.selectedMinion.get() == null) this.selectedMinion = null;
Random random = entityplayer.worldObj.rand;
// Annoyingly, it seems that the armour inventory is dealt with completely separately.
if(entityplayer.inventory.hasItem(Wizardry.spectralHelmet)
|| entityplayer.inventory.hasItem(Wizardry.spectralChestplate)
|| entityplayer.inventory.hasItem(Wizardry.spectralLeggings)
|| entityplayer.inventory.hasItem(Wizardry.spectralBoots)
|| (entityplayer.inventory.armorInventory[3] != null && entityplayer.inventory.armorInventory[3].getItem() == Wizardry.spectralHelmet)
|| (entityplayer.inventory.armorInventory[2] != null && entityplayer.inventory.armorInventory[2].getItem() == Wizardry.spectralChestplate)
|| (entityplayer.inventory.armorInventory[1] != null && entityplayer.inventory.armorInventory[1].getItem() == Wizardry.spectralLeggings)
|| (entityplayer.inventory.armorInventory[0] != null && entityplayer.inventory.armorInventory[0].getItem() == Wizardry.spectralBoots)){
this.conjuredArmourDuration++;
}else{
this.conjuredArmourDuration = 0;
}
if(!entityplayer.worldObj.isRemote){
if(tpTimer == 1){
entityplayer.setPositionAndUpdate(this.transportX + 0.5, this.transportY, this.transportZ + 0.5);
entityplayer.worldObj.playSoundAtEntity(entityplayer, "portal.travel", 1.0f, 1.0f);
entityplayer.addPotionEffect(new PotionEffect(Potion.blindness.id, 50, 0));
IMessage msg = new PacketTransportation.Message(entityplayer.getEntityId());
WizardryPacketHandler.net.sendToDimension(msg, entityplayer.worldObj.provider.dimensionId);
}
if(tpTimer > 0){
tpTimer--;
}
}
if(this.currentlyCasting != null && this.currentlyCasting.isContinuous){
this.currentlyCasting.cast(player.worldObj, player, castingTick++, spellDamageMultiplier, spellRangeMultiplier, spellDurationMultiplier, spellBlastMultiplier);
}else{
this.castingTick = 0;
}
}
/** Called from the event handler each time the associated player dies. Used to reset any variables that shouldn't
* persist over player death. */
public void onPlayerDeath(){
this.conjuredSwordDuration = 0;
this.conjuredPickaxeDuration = 0;
this.conjuredBowDuration = 0;
this.conjuredArmourDuration = 0;
this.flamingAxeDuration = 0;
this.frostAxeDuration = 0;
this.magicWeaponDuration = 0;
this.flamingWeaponDuration = 0;
this.freezingWeaponDuration = 0;
// Death cancels transportation spell.
this.tpTimer = 0;
this.soulboundCreatures = new HashSet<UUID>();
this.currentlyCasting = WizardryRegistry.none;
this.castingTick = 0;
this.spellDamageMultiplier = 1;
this.spellRangeMultiplier = 1;
this.spellDurationMultiplier = 1;
this.spellBlastMultiplier = 1;
}
/**
* Returns the string key to be used when saving and loading the extended player data on respawn.
*/
public static String getSaveKey(EntityPlayer player) {
return player.getUniqueID().toString() + ":" + name;
}
/**
* Used to register these extended properties for the player during EntityConstructing event
* This method is for convenience only; it will make your code look nicer
*/
public static final void register(EntityPlayer player){
player.registerExtendedProperties(ExtendedPlayer.name, new ExtendedPlayer(player));
}
/**
* Returns the ExtendedPlayer properties for the specified player.
*/
public static final ExtendedPlayer get(EntityPlayer player){
return (ExtendedPlayer) player.getExtendedProperties(name);
}
/** Sends a packet to this player's client to synchronise necessary information. Only called server side. */
public void sync(){
if(this.player instanceof EntityPlayerMP){
int id = -1;
if(this.selectedMinion != null && this.selectedMinion.get() != null) id = this.selectedMinion.get().getEntityId();
IMessage msg = new PacketPlayerSync.Message(this.spellsDiscovered, id);
WizardryPacketHandler.net.sendTo(msg, (EntityPlayerMP)this.player);
}
}
@Override
public void saveNBTData(NBTTagCompound compound) {
// NBTTagCompound is for Maps, NBTTagList is for Lists/Sets
NBTTagCompound properties = new NBTTagCompound();
properties.setInteger("conjuredSwordDuration", this.conjuredSwordDuration);
properties.setInteger("conjuredPickaxeDuration", this.conjuredPickaxeDuration);
properties.setInteger("conjuredBowDuration", this.conjuredBowDuration);
properties.setInteger("conjuredArmourDuration", this.conjuredArmourDuration);
properties.setInteger("flamingAxeDuration", this.flamingAxeDuration);
properties.setInteger("frostAxeDuration", this.frostAxeDuration);
properties.setInteger("magicWeaponDuration", this.magicWeaponDuration);
properties.setInteger("flamingWeaponDuration", this.flamingWeaponDuration);
properties.setInteger("freezingWeaponDuration", this.freezingWeaponDuration);
properties.setBoolean("hasSpiritWolf", this.hasSpiritWolf);
properties.setBoolean("hasSpiritHorse", this.hasSpiritHorse);
properties.setInteger("x", this.transportX);
properties.setInteger("y", this.transportY);
properties.setInteger("z", this.transportZ);
properties.setInteger("dimension", this.transportDimension);
properties.setInteger("x2", this.clairvoyanceX);
properties.setInteger("y2", this.clairvoyanceY);
properties.setInteger("z2", this.clairvoyanceZ);
properties.setInteger("dimension2", this.clairvoyanceDimension);
properties.setInteger("tpTimer", this.tpTimer);
NBTTagList tagList = new NBTTagList();
for(UUID id : this.allies){
tagList.appendTag(new NBTTagString(id.toString()));
}
properties.setTag("allies", tagList);
NBTTagList tagList2 = new NBTTagList();
for(String name : this.allyNames){
tagList2.appendTag(new NBTTagString(name));
}
properties.setTag("allyNames", tagList2);
NBTTagList tagList3 = new NBTTagList();
for(UUID id : this.soulboundCreatures){
tagList3.appendTag(new NBTTagString(id.toString()));
}
properties.setTag("soulboundCreatures", tagList3);
int[] spells = new int[this.spellsDiscovered.size()];
int i=0;
for(Spell spell : this.spellsDiscovered){
spells[i] = spell.id();
i++;
}
properties.setIntArray("discoveredSpells", spells);
compound.setTag(name, properties);
}
@Override
public void loadNBTData(NBTTagCompound compound) {
NBTTagCompound properties = (NBTTagCompound) compound.getTag(name);
if(properties != null){
this.conjuredSwordDuration = properties.getInteger("conjuredSwordDuration");
this.conjuredPickaxeDuration = properties.getInteger("conjuredPickaxeDuration");
this.conjuredBowDuration = properties.getInteger("conjuredBowDuration");
this.conjuredArmourDuration = properties.getInteger("conjuredArmourDuration");
this.flamingAxeDuration = properties.getInteger("flamingAxeDuration");
this.frostAxeDuration = properties.getInteger("frostAxeDuration");
this.magicWeaponDuration = properties.getInteger("magicWeaponDuration");
this.flamingWeaponDuration = properties.getInteger("flamingWeaponDuration");
this.freezingWeaponDuration = properties.getInteger("freezingWeaponDuration");
this.hasSpiritWolf = properties.getBoolean("hasSpiritWolf");
this.hasSpiritHorse = properties.getBoolean("hasSpiritHorse");
this.transportX = properties.getInteger("x");
this.transportY = properties.getInteger("y");
this.transportZ = properties.getInteger("z");
this.transportDimension = properties.getInteger("dimension");
this.clairvoyanceX = properties.getInteger("x2");
this.clairvoyanceY = properties.getInteger("y2");
this.clairvoyanceZ = properties.getInteger("z2");
this.clairvoyanceDimension = properties.getInteger("dimension2");
this.tpTimer = properties.getInteger("tpTimer");
this.allies = new HashSet<UUID>();
NBTTagList tagList = properties.getTagList("allies", NBT.TAG_STRING);
for(int i=0; i<tagList.tagCount(); i++){
allies.add(UUID.fromString(tagList.getStringTagAt(i)));
}
this.allyNames = new HashSet<String>();
NBTTagList tagList2 = properties.getTagList("allyNames", NBT.TAG_STRING);
for(int i=0; i<tagList2.tagCount(); i++){
allyNames.add(tagList2.getStringTagAt(i));
}
this.soulboundCreatures = new HashSet<UUID>();
NBTTagList tagList3 = properties.getTagList("soulboundCreatures", NBT.TAG_STRING);
for(int i=0; i<tagList3.tagCount(); i++){
soulboundCreatures.add(UUID.fromString(tagList3.getStringTagAt(i)));
}
this.spellsDiscovered = new HashSet<Spell>();
for(int id : properties.getIntArray("discoveredSpells")){
spellsDiscovered.add(Spell.get(id));
}
}
}
@Override
public void init(Entity entity, World world) {
// For reference, apparently there is a strange error that causes 'this' to be null here.
}
}
@@ -0,0 +1,16 @@
package electroblob.wizardry;
import electroblob.wizardry.MagicDamage.DamageType;
import net.minecraft.entity.Entity;
import scala.actors.threadpool.Arrays;
/** This interface allows {@link MagicDamage} and {@link IndirectMagicDamage} to both be treated as instances of a
* single type so that the damage type field can be accessed, rather than having to deal with each of them separately,
* which would be inefficient and cumbersome (the latter of those classes cannot extend the former because they both
* need to extend different subclasses of {@link net.minecraft.util.DamageSource DamageSource}).
* @since Wizardry 1.1 */
public interface IElementalDamage {
DamageType getType();
}
@@ -1,18 +1,16 @@
package electroblob.wizardry.util;
package electroblob.wizardry;
import electroblob.wizardry.util.MagicDamage.DamageType;
import electroblob.wizardry.MagicDamage.DamageType;
import net.minecraft.entity.Entity;
import net.minecraft.util.EntityDamageSourceIndirect;
public class IndirectMagicDamage extends EntityDamageSourceIndirect implements IElementalDamage {
private final DamageType type;
private final boolean isRetaliatory;
public IndirectMagicDamage(String name, Entity magic, Entity caster, DamageType type, boolean isRetaliatory){
public IndirectMagicDamage(String name, Entity magic, Entity caster, DamageType type) {
super(name, magic, caster);
this.type = type;
this.isRetaliatory = isRetaliatory;
}
@Override
@@ -20,9 +18,4 @@ public class IndirectMagicDamage extends EntityDamageSourceIndirect implements I
return type;
}
@Override
public boolean isRetaliatory(){
return isRetaliatory;
}
}
@@ -0,0 +1,216 @@
package electroblob.wizardry;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import electroblob.wizardry.entity.living.EntityBlazeMinion;
import electroblob.wizardry.entity.living.EntityIceGiant;
import electroblob.wizardry.entity.living.EntityIceWraith;
import electroblob.wizardry.entity.living.EntityLightningWraith;
import electroblob.wizardry.entity.living.EntityPhoenix;
import electroblob.wizardry.entity.living.EntityShadowWraith;
import electroblob.wizardry.entity.living.EntitySkeletonMinion;
import electroblob.wizardry.entity.living.EntitySpiderMinion;
import electroblob.wizardry.entity.living.EntityStormElemental;
import electroblob.wizardry.entity.living.EntityZombieMinion;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.monster.EntityBlaze;
import net.minecraft.entity.monster.EntityCaveSpider;
import net.minecraft.entity.monster.EntityGhast;
import net.minecraft.entity.monster.EntityMagmaCube;
import net.minecraft.entity.monster.EntityPigZombie;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.monster.EntitySnowman;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
// A note on the use of the vanilla damagesources:
// When using indirect damage sources, the SECOND argument is the original entity (i.e. the caster), and the
// FIRST argument is the actual projectile or whatever that does the damage. getEntity() will return
// the original entity, and getSourceOfDamage() will return the projectile.
// The vanilla approach to damage types is inconsistent, to say the least. Poison is simply 'magic', and relies on
// EntityLivingBase.isPotionApplicable to determine whether an entity is affected or not. Wither, on the other hand, is
// its own damage type, but again relies on the potion to determine what is immune (which in this case is nothing). Fire
// has a proper implementation of course, with both block-based and projectile-based types, and any other damagesource
// can also be designated as fire damage with setFireDamage(). Likewise, projectile and explosion damage can also be
// applied to any damagesource, but these aren't condsidered types in their own right; rather, they seem to be damage
// type 'attributes'.
/** As of wizardry 1.1, this class has replaced the damagesource-related methods in WizardryUtilities, allowing a
* {@link DamageType} to be specified with the damage. The main reason for this is so that damage sources can fit with the
* vanilla behaviour on armour enchantments and such like whilst still being classified as wizardry damage for the purposes
* of friendly fire, etc.
* <p><i>
* In the future, there is scope for an entirely standalone mod based on this idea. Perhaps 'Elemental Damage' could be
* a config-only mod which allows its users to define any number of specific damage types, then give any creature a
* resistance, immunity or vulnerability to each, as well as being able to specify the sources for each type, such as
* enchantments, potions, specific items, certain entities, even particular situations and string damagesource names
* from other mods.
* </i>
* @see IndirectMagicDamage
* @see IElementalDamage
* @since Wizardry 1.1 */
public class MagicDamage extends EntityDamageSource implements IElementalDamage {
/** The name of the damagesource for direct magic damage from the wizardry mod. Defined here so that any
* references get changed automatically. */
public static final String DIRECT_MAGIC_DAMAGE = "wizardryMagic";
/** The name of the damagesource for indirect magic damage from the wizardry mod. Defined here so that any
* references get changed automatically. */
public static final String INDIRECT_MAGIC_DAMAGE = "indirectWizardryMagic";
// Technically, I don't need to specify that the classes in this map must extend entity, but it's good practice to.
private static final Map<Class<? extends Entity>, DamageType[]> immunityMapping = new HashMap<Class<? extends Entity>, DamageType[]>();
private final DamageType type;
/** A simple set of constants for the types of damage. The names are deliberately different to those in EnumElement
* to avoid confusion. All types are classified as magic damage in the vanilla system, so witches are resistant to them. */
public enum DamageType {
/** Generic magic damage from the wizardry mod. Like vanilla magic damage, except it doesn't bypass armour. */
MAGIC,
/** Fire damage from the wizardry mod. Counts as fire damage in the vanilla system, so is blocked by any mobs that
* are immune to fire and entities with the fire resistance effect. */
FIRE,
/** Frost (ice) damage from the wizardry mod. Snow golems, ice wraiths and ice giants are immune. */
FROST,
/** Shock (lightning) damage from the wizardry mod. Lightning wraiths and storm elementals are immune. */
SHOCK,
/** Wither damage from the wizardry mod. Withers, wither skeletons and shadow wraiths are immune. */
WITHER,
/** Poison damage from the wizardry mod. Spiders, cave spiders and undead mobs are immune. */
POISON,
/** Force damage from the wizardry mod. Insubstantial creatures (ghast, shadow wraith, etc.) are immune. */
FORCE,
/** Blast damage from the wizardry mod. Affected by the blast protection enchantment. */
BLAST,
/** Radiant damage from the wizardry mod. */
RADIANT;
}
static {
// Of course, the entities that are immune to fire already are since there's a vanilla system for that, but
// they're included here anyway for completeness and in case anyone wants to check if an entity is immune to
// an unspecified element for reasons other than dealing damage.
setEntityImmunities(EntityPhoenix.class, DamageType.FIRE);
setEntityImmunities(EntityBlaze.class, DamageType.FIRE);
setEntityImmunities(EntityBlazeMinion.class, DamageType.FIRE);
setEntityImmunities(EntityPigZombie.class, DamageType.FIRE, DamageType.POISON);
setEntityImmunities(EntityMagmaCube.class, DamageType.FIRE);
setEntityImmunities(EntityGhast.class, DamageType.FIRE);
setEntityImmunities(EntityDragon.class, DamageType.FIRE);
setEntityImmunities(EntityStormElemental.class, DamageType.FIRE, DamageType.SHOCK);
setEntityImmunities(EntityWither.class, DamageType.FIRE, DamageType.WITHER);
setEntityImmunities(EntitySnowman.class, DamageType.FROST);
setEntityImmunities(EntityIceWraith.class, DamageType.FROST);
setEntityImmunities(EntityIceGiant.class, DamageType.FROST);
setEntityImmunities(EntityLightningWraith.class, DamageType.SHOCK);
setEntityImmunities(EntityShadowWraith.class, DamageType.WITHER);
setEntityImmunities(EntitySpider.class, DamageType.POISON);
setEntityImmunities(EntitySpiderMinion.class, DamageType.POISON);
setEntityImmunities(EntityCaveSpider.class, DamageType.POISON);
setEntityImmunities(EntityZombie.class, DamageType.POISON);
setEntityImmunities(EntitySkeleton.class, DamageType.POISON);
setEntityImmunities(EntityZombieMinion.class, DamageType.POISON);
setEntityImmunities(EntitySkeletonMinion.class, DamageType.POISON);
}
public MagicDamage(String name, Entity caster, DamageType type) {
super(name, caster);
this.type = type;
this.setMagicDamage();
if(type == DamageType.FIRE) this.setFireDamage();
if(type == DamageType.BLAST) this.setExplosion();
}
/** Returns true if the given entity is immune to the given damage type according to the entity immunity mappings,
* false otherwise. When you want to check for resistances, check this method rather than just checking the result
* of attackEntityFrom, since that could return false for all sorts of reasons besides immunities. However, if you
* don't need to know whether the damage succeeded or not, there's no point in checking this method. A common use
* of this method is to check for immunity and if so display the "[mob] resisted [spell]" chat message. See
* {@link electroblob.wizardry.spell.Arc Arc} for a good example of this, and also of when not to use it. */
public static boolean isEntityImmune(DamageType type, Entity entity){
// Because Mojang, in their infinite wisdom, did not make wither skeletons their own separate class (despite the
// fact that cave spiders are), I have to test for this manually. Realistically, no mod author would be stupid
// enough to put two entities in one class, so this should be the only time I ever have to do this.
if(type == DamageType.WITHER && (
(entity instanceof EntitySkeleton && ((EntitySkeleton)entity).getSkeletonType() == 1)
|| (entity instanceof EntitySkeletonMinion && ((EntitySkeletonMinion)entity).getSkeletonType() == 1))){
return true;
}
if(type == DamageType.FIRE && entity.isImmuneToFire()) return true;
DamageType[] immunities = MagicDamage.immunityMapping.get(entity.getClass());
return immunities != null && Arrays.asList(immunities).contains(type);
}
// I found a use for varargs!
/** Registers the given type of entity as immune to all of the passed in damage types. */
public static void setEntityImmunities(Class<? extends Entity> entityType, DamageType... immunities){
immunityMapping.put(entityType, immunities);
}
/** Registers the given type of entity as immune to all of the passed in damage types. */
public static void addEntityImmunity(Class<? extends Entity> entityType, DamageType immunity){
List<DamageType> immunities = Arrays.asList(immunityMapping.get(entityType));
immunities.add(immunity);
// Apparently putting 0 here works just fine.
immunityMapping.put(entityType, immunities.toArray(new DamageType[0]));
}
/**
* Returns a DamageSource called "wizardryMagic" with the given entity as the caster. Use in preference to vanilla
* types to allow things to distinguish between magic and regular melee/swords. Unlike DamageSource.magic, it does
* not bypass armour and has a player as the source (rather than nothing). It is still classed as magic damage (for
* the record, all this does in vanilla is make witches 85% resistant to it - but that seems kinda right anyway).
* <p>
* Now that this is its own class, this static method is largely redundant, but it's not worth refactoring the entire
* mod just to get rid of this method and use the constructor instead.
* @param caster The player or other living entity causing the damage
* @param type The type that this damage belongs to; used for resistances and wand perks. Use
* {@link EnumElement#MAGIC} for regular, non-elemental magic damage (sometimes you might not want an element
* even though the spell has one - for example, not all necromancy spells are 'withery', so some of them might
* reasonably affect creatures that are ususally immune to wither effects).
* @return A damagesource object of type EntityDamageSource
*/
public static DamageSource causeDirectMagicDamage(EntityLivingBase caster, DamageType type)
{
return new MagicDamage(DIRECT_MAGIC_DAMAGE, caster, type);
}
/**
* Returns a DamageSource called "indirectWizardryMagic" with the player as the caster. Use in preference to vanilla
* types to allow things to distinguish between magic and regular arrows/throwables. Unlike
* DamageSource.causeIndirectMagicDamage, it does not bypass armour. It is still classed as magic damage (for the
* record, all this does in vanilla is make witches 85% resistant to it - but that seems kinda right anyway).
* <p>
* Now that this is its own class, this static method is largely redundant, but it's not worth refactoring the entire
* mod just to get rid of this method and use the constructor instead.
* @param magic The entity that actually caused the damage
* @param caster The player or other living entity that cast the spell originally
* @param type The type that this damage belongs to; used for resistances and wand perks. Use
* {@link EnumElement#MAGIC} for regular, non-elemental magic damage (sometimes you might not want an element
* even though the spell has one - for example, not all necromancy spells are 'withery', so some of them might
* reasonably affect creatures that are ususally immune to wither effects).
* @return A damagesource object of type EntityDamageSourceIndirect
*/
public static DamageSource causeIndirectEntityMagicDamage(Entity magic, EntityLivingBase caster, DamageType type)
{
return new IndirectMagicDamage(INDIRECT_MAGIC_DAMAGE, magic, caster, type);
}
@Override
public DamageType getType(){
return type;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,13 @@
package electroblob.wizardry.data;
package electroblob.wizardry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang3.RandomStringUtils;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.packet.PacketGlyphData;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.spell.Spell;
@@ -8,134 +15,110 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraft.world.storage.WorldSavedData;
import net.minecraft.world.WorldSavedData;
import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.*;
/**
* Class responsible for generating and storing the randomised spell names and descriptions for each world, which are
/** Class responsible for generating and storing the randomised spell names and descriptions for each world, which are
* displayed as glyphs using the SGA font renderer.
*
* @since Wizardry 1.1
*/
@Mod.EventBusSubscriber
* @since Wizardry 1.1 */
public class SpellGlyphData extends WorldSavedData {
public static final String NAME = Wizardry.MODID + "_glyphData";
public Map<Spell, String> randomNames = new HashMap<>(Spell.getTotalSpellCount());
public Map<Spell, String> randomDescriptions = new HashMap<>(Spell.getTotalSpellCount());
private static final String NAME = Wizardry.MODID + "_glyphData";
public Map<Spell, String> randomNames = new HashMap<Spell, String>(Spell.getTotalSpellCount());
public Map<Spell, String> randomDescriptions = new HashMap<Spell, String>(Spell.getTotalSpellCount());
// Required constructors
public SpellGlyphData(){
public SpellGlyphData() {
this(NAME);
}
public SpellGlyphData(String name){
super(name);
}
/** Generates random names and descriptions for any spells which don't already have them. */
public void generateGlyphNames(World world){
for(Spell spell : Spell.getSpells(Spell.allSpells)){
if(!randomNames.containsKey(spell)) randomNames.put(spell, generateRandomName(world.rand));
}
for(Spell spell : Spell.getSpells(Spell.allSpells)){
if(!randomDescriptions.containsKey(spell))
randomDescriptions.put(spell, generateRandomDescription(world.rand));
if(!randomDescriptions.containsKey(spell)) randomDescriptions.put(spell, generateRandomDescription(world.rand));
}
this.markDirty();
}
private String generateRandomName(Random random){
String name = "";
for(int i = 0; i < random.nextInt(2) + 2; i++){
for(int i=0; i<random.nextInt(2)+2; i++){
name = name + RandomStringUtils.random(3 + random.nextInt(5), "abcdefghijklmnopqrstuvwxyz") + " ";
}
return name.trim();
}
private String generateRandomDescription(Random random){
String name = "";
for(int i = 0; i < random.nextInt(16) + 8; i++){
for(int i=0; i<random.nextInt(16)+8; i++){
name = name + RandomStringUtils.random(2 + random.nextInt(7), "abcdefghijklmnopqrstuvwxyz") + " ";
}
return name.trim();
}
/**
* Returns the spell glyph data for this world, or creates a new instance if it doesn't exist yet. Also checks for
* any spells that are missing glyph data and adds it accordingly.
*/
public static SpellGlyphData get(World world){
/** Returns the spell glyph data for this world, or creates a new instance if it doesn't exist yet. Also checks
* for any spells that are missing glyph data and adds it accordingly. */
public static SpellGlyphData get(World world) {
SpellGlyphData instance = (SpellGlyphData)world.loadData(SpellGlyphData.class, NAME);
SpellGlyphData instance = (SpellGlyphData) world.loadItemData(SpellGlyphData.class, NAME);
if(instance == null){
instance = new SpellGlyphData();
}
// These two conditions are a bit of backwards compatibility from when I added the descriptions to the
// glyph data. Shouldn't be needed in normal operation, but I might as well leave it here.
// Edit: More backwards compatibility, this time for the future - should any new spells be added, this now
// ensures
// Edit: More backwards compatibility, this time for the future - should any new spells be added, this now ensures
// existing worlds will generate random names and descriptions for any new spells whilst keeping the old ones.
if(instance.randomNames.size() < Spell.getTotalSpellCount()
|| instance.randomDescriptions.size() < Spell.getTotalSpellCount()){
if(instance.randomNames.size() < Spell.getTotalSpellCount() || instance.randomDescriptions.size() < Spell.getTotalSpellCount()){
instance.generateGlyphNames(world);
world.setData(NAME, instance);
world.setItemData(NAME, instance);
}
return instance;
}
/** Sends the random spell names for this world to the specified player's client. */
public void sync(EntityPlayerMP player){
List<String> names = new ArrayList<>();
List<String> descriptions = new ArrayList<>();
int id = 0;
while(id < Spell.getTotalSpellCount()){
Spell spell = Spell.byNetworkID(id + 1); // +1 because the None spell is not included
List<String> names = new ArrayList<String>();
List<String> descriptions = new ArrayList<String>();
for(Spell spell : Spell.getSpells(Spell.allSpells)){
names.add(this.randomNames.get(spell));
descriptions.add(this.randomDescriptions.get(spell));
id++;
}
PacketGlyphData.Message msg = new PacketGlyphData.Message(names, descriptions);
WizardryPacketHandler.net.sendTo(msg, player);
Wizardry.logger.info("Synchronising spell glyph data for " + player.getName());
}
/** Helper method to retrieve the random glyph name for the given spell from the map stored in the given world. */
public static String getGlyphName(Spell spell, World world){
Map<Spell, String> names = SpellGlyphData.get(world).randomNames;
return names == null ? "" : names.get(spell);
}
/**
* Helper method to retrieve the random glyph description for the given spell from the map stored in the given
* world.
*/
/** Helper method to retrieve the random glyph description for the given spell from the map stored in the given world. */
public static String getGlyphDescription(Spell spell, World world){
Map<Spell, String> descriptions = SpellGlyphData.get(world).randomDescriptions;
return descriptions == null ? "" : descriptions.get(spell);
@@ -143,44 +126,34 @@ public class SpellGlyphData extends WorldSavedData {
@Override
public void readFromNBT(NBTTagCompound nbt){
this.randomNames = new HashMap<>();
this.randomDescriptions = new HashMap<>();
this.randomNames = new HashMap<Spell, String>();
this.randomDescriptions = new HashMap<Spell, String>();
NBTTagList tagList = nbt.getTagList("spellGlyphData", NBT.TAG_COMPOUND);
for(int i = 0; i < tagList.tagCount(); i++){
for(int i=0; i<tagList.tagCount(); i++){
NBTTagCompound tag = tagList.getCompoundTagAt(i);
randomNames.put(Spell.byMetadata(tag.getInteger("spell")), tag.getString("name"));
randomDescriptions.put(Spell.byMetadata(tag.getInteger("spell")), tag.getString("description"));
randomNames.put(Spell.get(tag.getInteger("spell")), tag.getString("name"));
randomDescriptions.put(Spell.get(tag.getInteger("spell")), tag.getString("description"));
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt){
public void writeToNBT(NBTTagCompound nbt){
NBTTagList tagList = new NBTTagList();
for(Spell spell : Spell.getSpells(Spell.allSpells)){
// Much like the enchantments tag for items, this stores a list of spell-id-to-name tag pairs
// The description is now also included; there's no point in making a second compound tag!
NBTTagCompound tag = new NBTTagCompound();
tag.setInteger("spell", spell.metadata());
tag.setInteger("spell", spell.id());
tag.setString("name", this.randomNames.get(spell));
tag.setString("description", this.randomDescriptions.get(spell));
tagList.appendTag(tag);
}
nbt.setTag("spellGlyphData", tagList);
return nbt;
}
@SubscribeEvent
public static void onWorldLoadEvent(WorldEvent.Load event){
if(!event.getWorld().isRemote && event.getWorld().provider.getDimension() == 0){
// Called to initialise the spell glyph data when a world loads, if it isn't already.
SpellGlyphData.get(event.getWorld());
}
}
}
@@ -0,0 +1,277 @@
package electroblob.wizardry;
import java.util.HashMap;
import java.util.Set;
import electroblob.wizardry.spell.Spell;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
/** Much like {@link net.minecraft.enchantment.EnchantmentHelper EnchantmentHelper}, this class has some static methods
* which allow cleaner and more concise interaction with the wand NBT data, which is quite a complex structure. Such
* interaction previously resulted in rather verbose and repetitive code which was hard to read and even harder to debug!
* For example, this class allowed {@link electroblob.wizardry.item.ItemWand ItemWand} to be shortened by about 80 lines.
* In addition, by having all the various null checks and array size checks in one place, the chance of accidental errors
* due to forgetting to check these things is greatly reduced.
* <p>
* Note that these methods contain no game logic at all; they are purely for interacting with the NBT data. Conversely,
* you should never need to access the wand's NBT data directly when using this class, but the keys are public in the
* unlikely case that this is necessary.
* <p>
* Also note that none of the methods in this class actually check that the given ItemStack contains an ItemWand; you
* can, for example, pass in a stack of snowballs without causing problems, but that is of course pointless!
* <p>
* All <b>get</b> methods in this class return some kind of default if the passed-in wand stack has no nbt data.<br>
* All <b>set</b> methods in this class create a new nbt data for the passed-in wand if it has none, before doing
* whatever else they do.
* @see electroblob.wizardry.item.ItemWand ItemWand
* @see electroblob.wizardry.packet.PacketControlInput PacketControlInput
* @since Wizardry 1.1 */
public class WandHelper {
// NBT tag keys
public static final String SPELL_ARRAY_KEY = "spells";
public static final String SELECTED_SPELL_KEY = "selectedSpell";
public static final String COOLDOWN_ARRAY_KEY = "cooldown";
public static final String UPGRADES_KEY = "upgrades";
private static final HashMap<Item, String> upgradeMap = new HashMap<Item, String>();
static {
upgradeMap.put(Wizardry.condenserUpgrade, "condenser");
upgradeMap.put(Wizardry.storageUpgrade, "storage");
upgradeMap.put(Wizardry.siphonUpgrade, "siphon");
upgradeMap.put(Wizardry.rangeUpgrade, "range");
upgradeMap.put(Wizardry.durationUpgrade, "duration");
upgradeMap.put(Wizardry.cooldownUpgrade, "cooldown");
upgradeMap.put(Wizardry.blastUpgrade, "blast");
upgradeMap.put(Wizardry.attunementUpgrade, "attunement");
}
/** Returns an array containing the spells currently bound to the given wand. As of Wizardry 1.1, this array is not
* always the same size; it can be anywhere between 5 and 8 (inclusive) in length. If the wand has no spell data,
* returns an array of length 0. */
public static Spell[] getSpells(ItemStack wand){
Spell[] spells = new Spell[0];
if(wand.stackTagCompound != null){
int[] spellIDs = wand.stackTagCompound.getIntArray(SPELL_ARRAY_KEY);
spells = new Spell[spellIDs.length];
for(int i=0; i<spellIDs.length; i++){
spells[i] = Spell.get(spellIDs[i]);
}
}
return spells;
}
/** Binds the given array of spells to the given wand. The array can be anywhere between 5 and 8 (inclusive) in length. */
public static void setSpells(ItemStack wand, Spell[] spells){
if(wand.stackTagCompound == null) wand.stackTagCompound = new NBTTagCompound();
int[] spellIDs = new int[spells.length];
for(int i=0; i<spells.length; i++){
spellIDs[i] = spells[i] != null ? spells[i].id() : WizardryRegistry.none.id();
}
wand.stackTagCompound.setIntArray(SPELL_ARRAY_KEY, spellIDs);
}
/** Returns the currently selected spell for the given wand, or the 'none' spell if the wand has no spell data. */
public static Spell getCurrentSpell(ItemStack wand){
Spell[] spells = getSpells(wand);
if(wand.stackTagCompound != null){
int selectedSpell = wand.stackTagCompound.getInteger(SELECTED_SPELL_KEY);
if(selectedSpell < spells.length){
return spells[selectedSpell];
}
}
return WizardryRegistry.none;
}
/** Selects the next spell in this wand's list of spells. */
public static void selectNextSpell(ItemStack wand){
// 5 here because if the spell array doesn't exist, the wand can't possibly have attunement upgrades
if(getSpells(wand).length < 0) setSpells(wand, new Spell[5]);
if(wand.stackTagCompound != null){
int numberOfSpells = getSpells(wand).length;
int selectedSpell = wand.stackTagCompound.getInteger(SELECTED_SPELL_KEY);
// Greater than or equal to so that if attunement upgrades are somehow removed by NBT modification it just
// resets.
if(selectedSpell >= numberOfSpells - 1){
selectedSpell = 0;
}else{
selectedSpell++;
}
wand.stackTagCompound.setInteger(SELECTED_SPELL_KEY, selectedSpell);
}
}
/** Selects the previous spell in this wand's list of spells. */
public static void selectPreviousSpell(ItemStack wand){
// 5 here because if the spell array doesn't exist, the wand can't possibly have attunement upgrades
if(getSpells(wand).length < 0) setSpells(wand, new Spell[5]);
// This cannot possibly be null here, and yet I am getting an NPE...
if(wand.stackTagCompound != null){
int numberOfSpells = getSpells(wand).length;
int selectedSpell = wand.stackTagCompound.getInteger(SELECTED_SPELL_KEY);
if(selectedSpell <= 0){
selectedSpell = numberOfSpells - 1;
}else{
selectedSpell--;
}
wand.stackTagCompound.setInteger(SELECTED_SPELL_KEY, selectedSpell);
}
}
/** Returns an array of the cooldowns for each spell bound to the given wand. As of Wizardry 1.1, this array is not
* always the same size; it can be anywhere between 5 and 8 (inclusive) in length. If the wand has no cooldown data,
* returns an array of length 0. */
public static int[] getCooldowns(ItemStack wand){
int[] cooldowns = new int[0];
if(wand.stackTagCompound != null){
return wand.stackTagCompound.getIntArray(COOLDOWN_ARRAY_KEY);
}
return cooldowns;
}
/** Sets the given wand's cooldown array. The array can be anywhere between 5 and 8 (inclusive) in length. */
public static void setCooldowns(ItemStack wand, int[] cooldowns){
if(wand.stackTagCompound == null) wand.stackTagCompound = new NBTTagCompound();
wand.stackTagCompound.setIntArray(COOLDOWN_ARRAY_KEY, cooldowns);
}
/** Decrements the cooldown for each spell bound to the given wand by 1, if that cooldown is greater than 0. */
public static void decrementCooldowns(ItemStack wand){
int[] cooldowns = getCooldowns(wand);
// If there are no cooldowns, it is assumed that they are all zero and therefore nothing needs to be done.
if(cooldowns.length == 0) return;
for(int i=0; i<cooldowns.length; i++){
if(cooldowns[i] > 0) cooldowns[i]--;
}
setCooldowns(wand, cooldowns);
}
/** Returns the given wand's cooldown for the currently selected spell, or 0 if the wand has no cooldown data. */
public static int getCurrentCooldown(ItemStack wand){
int[] cooldowns = getCooldowns(wand);
if(cooldowns.length == 0) return 0;
// Don't need to check if the tag compound is null since the above check is equivalent.
return cooldowns[wand.stackTagCompound.getInteger(SELECTED_SPELL_KEY)];
}
/** Sets the given wand's cooldown for the currently selected spell. */
public static void setCurrentCooldown(ItemStack wand, int cooldown){
if(wand.stackTagCompound == null) wand.stackTagCompound = new NBTTagCompound();
int[] cooldowns = getCooldowns(wand);
// The length of the spells array must be greater than 0 since this method can only be called if a spell is
// cast, which is impossible if there are no spells.
if(cooldowns.length == 0) cooldowns = new int[getSpells(wand).length];
cooldowns[wand.stackTagCompound.getInteger(SELECTED_SPELL_KEY)] = cooldown;
setCooldowns(wand, cooldowns);
}
/** Returns the number of upgrades of the given type that have been applied to the given wand, or 0 if the wand has
* no upgrade data or the given item is not a valid wand upgrade. */
public static int getUpgradeLevel(ItemStack wand, Item upgrade){
String key = upgradeMap.get(upgrade);
if(wand.stackTagCompound != null && wand.stackTagCompound.hasKey(UPGRADES_KEY) && key != null){
return wand.stackTagCompound.getCompoundTag(UPGRADES_KEY).getInteger(key);
}
return 0;
}
/** Returns the total number of upgrades that have been applied to the given wand, or 0 if the wand has no upgrade
* data. */
public static int getTotalUpgrades(ItemStack wand){
int totalUpgrades = 0;
for(Item item : upgradeMap.keySet()){
totalUpgrades += getUpgradeLevel(wand, item);
}
return totalUpgrades;
}
/** Applies the given upgrade to the given wand, or in other words increases the level for that upgrade by 1. This
* does <b>not</b> account for the individual or total upgrade stack limits. */
public static void applyUpgrade(ItemStack wand, Item upgrade){
if(wand.stackTagCompound == null) wand.stackTagCompound = new NBTTagCompound();
if(!wand.stackTagCompound.hasKey(UPGRADES_KEY)) wand.stackTagCompound.setTag(UPGRADES_KEY, new NBTTagCompound());
NBTTagCompound upgrades = wand.stackTagCompound.getCompoundTag(UPGRADES_KEY);
String key = upgradeMap.get(upgrade);
if(key != null) upgrades.setInteger(key, upgrades.getInteger(key) + 1);
wand.stackTagCompound.setTag(UPGRADES_KEY, upgrades);
}
/** Returns true if the given item is a valid special wand upgrade. */
public static boolean isWandUpgrade(Item upgrade){
return upgradeMap.containsKey(upgrade);
}
/** Returns a set of all the items which are valid special wand upgrades. */
public static Set<Item> getSpecialUpgrades(){
return WandHelper.upgradeMap.keySet();
}
/** Registers a special upgrade with wizardry. Not used in the base mod, but I've put it here to make it easy
* for add-ons to add new wand upgrades.
* @param upgrade The wand upgrade item
* @param identifier A unique string, used as a key for wand nbt tags
* @throws IllegalArgumentException if the passed in identifier is already used for another wand upgrade */
public static void registerSpecialUpgrade(Item upgrade, String identifier){
// Throwing an exception is the best thing to do here, since if a duplicate was allowed weird things would
// happen later with wand NBT.
if(upgradeMap.containsValue(identifier)) throw new IllegalArgumentException("Duplicate wand upgrade identifier: " + identifier);
upgradeMap.put(upgrade, identifier);
}
}
@@ -0,0 +1,64 @@
package electroblob.wizardry;
import java.util.Random;
import electroblob.wizardry.item.ItemScroll;
import electroblob.wizardry.item.ItemSpellBook;
import electroblob.wizardry.item.ItemWand;
import electroblob.wizardry.item.ItemWizardArmour;
import electroblob.wizardry.spell.Spell;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
public class WeightedRandomSpellBook extends WeightedRandomChestContent{
public WeightedRandomSpellBook(ItemStack par1ItemStack, int par2, int par3,
int par4) {
super(par1ItemStack, par2, par3, par4);
}
/* A brief comment about dungeon loot:
* Tiers are weighted as per usual. Elements all have equal chance, INCLUDING simple stuff. The main reason for
* this is that dungeon loot is not that common anyway, so making elemental gear even rarer would be too much.
*/
protected ItemStack[] generateChestContent(Random random, IInventory newInventory){
if(theItemId.getItem() instanceof ItemSpellBook){
theItemId = new ItemStack(theItemId.getItem(), 1, WizardryUtilities.getStandardWeightedRandomSpellId(random));
}else if(theItemId.getItem() instanceof ItemWand){
theItemId = new ItemStack(WizardryUtilities.getWand(EnumTier.BASIC, EnumElement.values()[random.nextInt(EnumElement.values().length)]));
}else if(theItemId.getItem() instanceof ItemWizardArmour){
theItemId = new ItemStack(WizardryUtilities.getArmour(EnumElement.values()[random.nextInt(EnumElement.values().length)], random.nextInt(3)));
}else if(theItemId.getItem() instanceof ItemScroll){
int spellId = WizardryUtilities.getStandardWeightedRandomSpellId(random, true);
theItemId = new ItemStack(theItemId.getItem(), 1, spellId);
}else if(theItemId.getItem() == Wizardry.condenserUpgrade){
switch(random.nextInt(8)){
case 0: theItemId = new ItemStack(Wizardry.condenserUpgrade); break;
case 1: theItemId = new ItemStack(Wizardry.siphonUpgrade); break;
case 2: theItemId = new ItemStack(Wizardry.rangeUpgrade); break;
case 3: theItemId = new ItemStack(Wizardry.cooldownUpgrade); break;
case 4: theItemId = new ItemStack(Wizardry.durationUpgrade); break;
case 5: theItemId = new ItemStack(Wizardry.storageUpgrade); break;
case 6: theItemId = new ItemStack(Wizardry.blastUpgrade); break;
case 7: theItemId = new ItemStack(Wizardry.attunementUpgrade); break;
}
}
return ChestGenHooks.generateStacks(random, theItemId, theMinimumChanceToGenerateItem, theMaximumChanceToGenerateItem);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,30 +1,35 @@
package electroblob.wizardry;
import electroblob.wizardry.client.gui.config.GuiConfigWizardry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.IModGuiFactory;
import java.util.Set;
import cpw.mods.fml.client.IModGuiFactory;
import electroblob.wizardry.client.GuiConfigWizardry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
public class WizardryGuiFactory implements IModGuiFactory {
@Override
public void initialize(Minecraft minecraftInstance){
}
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories(){
return null;
}
@Override
public boolean hasConfigGui(){
return true;
}
@Override
public GuiScreen createConfigGui(GuiScreen parentScreen){
return new GuiConfigWizardry(parentScreen);
}
@Override
public void initialize(Minecraft minecraftInstance)
{
}
@Override
public Class<? extends GuiScreen> mainConfigGuiClass()
{
return GuiConfigWizardry.class;
}
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories()
{
return null;
}
@Override
public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element)
{
return null;
}
}
@@ -1,5 +1,10 @@
package electroblob.wizardry;
import cpw.mods.fml.common.network.IGuiHandler;
import electroblob.wizardry.client.GuiArcaneWorkbench;
import electroblob.wizardry.client.GuiPortableCrafting;
import electroblob.wizardry.client.GuiSpellBook;
import electroblob.wizardry.client.GuiWizardHandbook;
import electroblob.wizardry.item.ItemSpellBook;
import electroblob.wizardry.item.ItemWizardHandbook;
import electroblob.wizardry.spell.Spell;
@@ -8,52 +13,50 @@ import electroblob.wizardry.tileentity.ContainerPortableWorkbench;
import electroblob.wizardry.tileentity.TileEntityArcaneWorkbench;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
public class WizardryGuiHandler implements IGuiHandler {
/** Incrementable index for the gui ID */
private static int nextGuiId = 0;
public static final int SPELL_BOOK = nextGuiId++;
public static final int ARCANE_WORKBENCH = nextGuiId++;
public static final int WIZARD_HANDBOOK = nextGuiId++;
public static final int PORTABLE_CRAFTING = nextGuiId++;
@Override
public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z){
public Object getServerGuiElement(int id, EntityPlayer player, World world,
int x, int y, int z) {
if(id == ARCANE_WORKBENCH){
TileEntity tileEntity = world.getTileEntity(new BlockPos(x, y, z));
TileEntity tileEntity = world.getTileEntity(x, y, z);
if(tileEntity instanceof TileEntityArcaneWorkbench){
return new ContainerArcaneWorkbench(player.inventory, (TileEntityArcaneWorkbench)tileEntity);
return new ContainerArcaneWorkbench(player.inventory, (TileEntityArcaneWorkbench) tileEntity);
}
}else if(id == PORTABLE_CRAFTING){
return new ContainerPortableWorkbench(player.inventory, world, new BlockPos(x, y, z));
}
else if(id == PORTABLE_CRAFTING){
return new ContainerPortableWorkbench(player.inventory, world, x, y, z);
}
return null;
}
@Override
public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z){
public Object getClientGuiElement(int id, EntityPlayer player, World world,
int x, int y, int z) {
if(id == ARCANE_WORKBENCH){
TileEntity tileEntity = world.getTileEntity(new BlockPos(x, y, z));
TileEntity tileEntity = world.getTileEntity(x, y, z);
if(tileEntity instanceof TileEntityArcaneWorkbench){
return new electroblob.wizardry.client.gui.GuiArcaneWorkbench(player.inventory,
(TileEntityArcaneWorkbench)tileEntity);
return new GuiArcaneWorkbench(player.inventory, (TileEntityArcaneWorkbench) tileEntity);
}
}else if(id == WIZARD_HANDBOOK && (player.getHeldItemMainhand().getItem() instanceof ItemWizardHandbook
|| player.getHeldItemOffhand().getItem() instanceof ItemWizardHandbook)){
return new electroblob.wizardry.client.gui.handbook.GuiWizardHandbook();
}else if(id == SPELL_BOOK){
if(player.getHeldItemMainhand().getItem() instanceof ItemSpellBook){
return new electroblob.wizardry.client.gui.GuiSpellBook(Spell.byMetadata(player.getHeldItemMainhand().getItemDamage()));
}else if(player.getHeldItemOffhand().getItem() instanceof ItemSpellBook){
return new electroblob.wizardry.client.gui.GuiSpellBook(Spell.byMetadata(player.getHeldItemOffhand().getItemDamage()));
}
}else if(id == PORTABLE_CRAFTING){
return new electroblob.wizardry.client.gui.GuiPortableCrafting(player.inventory, world, new BlockPos(x, y, z));
}
else if(id == WIZARD_HANDBOOK && player.getHeldItem().getItem() instanceof ItemWizardHandbook){
return new GuiWizardHandbook();
}
else if(id == SPELL_BOOK && player.getHeldItem().getItem() instanceof ItemSpellBook){
return new GuiSpellBook(Spell.get(player.getHeldItem().getItemDamage()));
}
else if(id == PORTABLE_CRAFTING){
return new GuiPortableCrafting(player.inventory, world, x, y, z);
}
return null;
}
@@ -0,0 +1,69 @@
package electroblob.wizardry;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import electroblob.wizardry.client.ClientProxy;
import electroblob.wizardry.packet.PacketControlInput;
import electroblob.wizardry.packet.WizardryPacketHandler;
import net.minecraft.client.Minecraft;
public class WizardryKeyHandler {
boolean NkeyPressed = false;
boolean BkeyPressed = false;
boolean NkeyAlreadyPressed = false;
boolean BkeyAlreadyPressed = false;
@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) {
// Key pressed
if(Keyboard.getEventKeyState()){
if(Wizardry.proxy instanceof ClientProxy){
ClientProxy proxy = (ClientProxy)Wizardry.proxy;
if(proxy.nextSpell.isPressed() && Minecraft.getMinecraft().inGameHasFocus){
if(!NkeyPressed){
NkeyPressed = true;
}else{
NkeyAlreadyPressed = true;
}
if(!NkeyAlreadyPressed){
// Packet building
IMessage msg = new PacketControlInput.Message(1);
WizardryPacketHandler.net.sendToServer(msg);
}
}
if(proxy.previousSpell.isPressed() && Minecraft.getMinecraft().inGameHasFocus){
if(!BkeyPressed){
BkeyPressed = true;
}else{
BkeyAlreadyPressed = true;
}
if(!BkeyAlreadyPressed){
// Packet building
IMessage msg = new PacketControlInput.Message(2);
WizardryPacketHandler.net.sendToServer(msg);
}
}
}
}
// Key released
else{
if(NkeyPressed){
NkeyPressed = false;
NkeyAlreadyPressed = false;
}else if(BkeyPressed){
BkeyPressed = false;
BkeyAlreadyPressed = false;
}
}
}
}
@@ -0,0 +1,631 @@
package electroblob.wizardry;
import java.util.ArrayList;
import java.util.List;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import electroblob.wizardry.entity.EntityArc;
import electroblob.wizardry.entity.EntityFallingGrass;
import electroblob.wizardry.entity.EntityMagicSlime;
import electroblob.wizardry.entity.EntityMeteor;
import electroblob.wizardry.entity.EntityShield;
import electroblob.wizardry.entity.construct.EntityArrowRain;
import electroblob.wizardry.entity.construct.EntityBlackHole;
import electroblob.wizardry.entity.construct.EntityBlizzard;
import electroblob.wizardry.entity.construct.EntityBubble;
import electroblob.wizardry.entity.construct.EntityDecay;
import electroblob.wizardry.entity.construct.EntityEarthquake;
import electroblob.wizardry.entity.construct.EntityFireRing;
import electroblob.wizardry.entity.construct.EntityFireSigil;
import electroblob.wizardry.entity.construct.EntityForcefield;
import electroblob.wizardry.entity.construct.EntityFrostSigil;
import electroblob.wizardry.entity.construct.EntityHailstorm;
import electroblob.wizardry.entity.construct.EntityHammer;
import electroblob.wizardry.entity.construct.EntityHealAura;
import electroblob.wizardry.entity.construct.EntityIceSpike;
import electroblob.wizardry.entity.construct.EntityLightningPulse;
import electroblob.wizardry.entity.construct.EntityLightningSigil;
import electroblob.wizardry.entity.construct.EntityTornado;
import electroblob.wizardry.entity.living.EntityBlazeMinion;
import electroblob.wizardry.entity.living.EntityDecoy;
import electroblob.wizardry.entity.living.EntityEvilWizard;
import electroblob.wizardry.entity.living.EntityIceGiant;
import electroblob.wizardry.entity.living.EntityIceWraith;
import electroblob.wizardry.entity.living.EntityLightningWraith;
import electroblob.wizardry.entity.living.EntityPhoenix;
import electroblob.wizardry.entity.living.EntityShadowWraith;
import electroblob.wizardry.entity.living.EntitySilverfishMinion;
import electroblob.wizardry.entity.living.EntitySkeletonMinion;
import electroblob.wizardry.entity.living.EntitySpiderMinion;
import electroblob.wizardry.entity.living.EntitySpiritHorse;
import electroblob.wizardry.entity.living.EntitySpiritWolf;
import electroblob.wizardry.entity.living.EntityStormElemental;
import electroblob.wizardry.entity.living.EntityWizard;
import electroblob.wizardry.entity.living.EntityZombieMinion;
import electroblob.wizardry.entity.projectile.EntityDarknessOrb;
import electroblob.wizardry.entity.projectile.EntityDart;
import electroblob.wizardry.entity.projectile.EntityFirebolt;
import electroblob.wizardry.entity.projectile.EntityFirebomb;
import electroblob.wizardry.entity.projectile.EntityForceArrow;
import electroblob.wizardry.entity.projectile.EntityForceOrb;
import electroblob.wizardry.entity.projectile.EntityIceCharge;
import electroblob.wizardry.entity.projectile.EntityIceLance;
import electroblob.wizardry.entity.projectile.EntityIceShard;
import electroblob.wizardry.entity.projectile.EntityLightningArrow;
import electroblob.wizardry.entity.projectile.EntityLightningDisc;
import electroblob.wizardry.entity.projectile.EntityMagicMissile;
import electroblob.wizardry.entity.projectile.EntityPoisonBomb;
import electroblob.wizardry.entity.projectile.EntitySmokeBomb;
import electroblob.wizardry.entity.projectile.EntitySpark;
import electroblob.wizardry.entity.projectile.EntitySparkBomb;
import electroblob.wizardry.entity.projectile.EntityThunderbolt;
import electroblob.wizardry.spell.*;
import electroblob.wizardry.tileentity.TileEntityArcaneWorkbench;
import electroblob.wizardry.tileentity.TileEntityMagicLight;
import electroblob.wizardry.tileentity.TileEntityPlayerSave;
import electroblob.wizardry.tileentity.TileEntityStatue;
import electroblob.wizardry.tileentity.TileEntityTimer;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.oredict.OreDictionary;
public final class WizardryRegistry {
// Usage note on ChestGenHooks: First number is minimum, second is maximum. Third is rarity, lower numbers are more rare [bread = 100].
// i starts at 1 here so that 'none' does not spawn.
// Earlier problem solved using clever forge hook - extend WeightedRandomChestContent and override generateChestContent.
// Apparently this seems to be incompatible with roguelike dungeons (any others?), in that it generates the same spell book in
// all of the chests that have a spell book in the same dungeon (usually, though it has been known to do different ones on
// different floors). It also appears to be able to generate the 'none' book, which should be impossible... never mind.
// I don't think that's my fault, or I would have seen a 'none' book in a vanilla dungeon by now.
// Another curious observation: Recurrent complex's generators also seem to always generate the same book/wand/armour
// until you restart the game and can generate the 'none' book as well.
// My best guess as to what's happening is that some mods hook into the dungeon loot differently to others, in that
// they take all the WeightedRandomChestContent objects once and pick from them each time rather than making new ones
// for each chest - which is, in theory, a more efficient way of doing things and will speed up world gen a bit, but
// does of course result in custom chest content implementations behaving strangely. The 'none' book thing remains a
// mystery, however.
/** Called from the preInit method in the main mod class to register the custom dungeon loot. */
public static void registerLoot(){
// The generate loot option only applies to vanilla chests, not wizard tower chests.
if(Wizardry.generateLoot){
String[] chestTypes = {
ChestGenHooks.DUNGEON_CHEST,
ChestGenHooks.PYRAMID_JUNGLE_CHEST,
ChestGenHooks.PYRAMID_DESERT_CHEST,
ChestGenHooks.MINESHAFT_CORRIDOR,
ChestGenHooks.STRONGHOLD_CORRIDOR,
ChestGenHooks.STRONGHOLD_CROSSING,
ChestGenHooks.STRONGHOLD_LIBRARY
};
for(String chest : chestTypes){
ChestGenHooks.addItem(chest, new WeightedRandomSpellBook(new ItemStack(Wizardry.spellBook), 1, 1, Wizardry.SPELL_BOOK_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomSpellBook(new ItemStack(Wizardry.magicWand), 1, 1, Wizardry.WAND_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomSpellBook(new ItemStack(Wizardry.wizardHat), 1, 1, Wizardry.ARMOUR_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomSpellBook(new ItemStack(Wizardry.scroll), 1, 1, Wizardry.SCROLL_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomSpellBook(new ItemStack(Wizardry.condenserUpgrade), 1, 1, Wizardry.WAND_UPGRADE_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.magicCrystal), 1, 4, Wizardry.CRYSTAL_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.arcaneTome, 1, 1), 1, 1, Wizardry.APPRENTICE_TOME_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.arcaneTome, 1, 2), 1, 1, Wizardry.ADVANCED_TOME_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.arcaneTome, 1, 3), 1, 1, Wizardry.MASTER_TOME_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.armourUpgrade), 1, 1, Wizardry.ARMOUR_UPGRADE_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.firebomb), 1, 5, Wizardry.FIREBOMB_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.poisonBomb), 1, 5, Wizardry.POISON_BOMB_FREQUENCY));
ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.smokeBomb), 1, 5, Wizardry.SMOKE_BOMB_FREQUENCY));
if(Wizardry.discoveryMode) ChestGenHooks.addItem(chest, new WeightedRandomChestContent(new ItemStack(Wizardry.identificationScroll), 1, 1, Wizardry.IDENTIFICATION_SCROLL_FREQUENCY));
}
}
// Creates a new ChestGenHooks for wizard towers.
ChestGenHooks chestGen = ChestGenHooks.getInfo(WizardryWorldGenerator.WIZARD_TOWER);
chestGen.setMax(7);
chestGen.setMin(3);
// Wizard tower chests use exactly the same things, minus the firebombs, poison bombs and smoke bombs
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomSpellBook(new ItemStack(Wizardry.spellBook), 1, 1, Wizardry.SPELL_BOOK_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomSpellBook(new ItemStack(Wizardry.magicWand), 1, 1, Wizardry.WAND_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomSpellBook(new ItemStack(Wizardry.wizardHat), 1, 1, Wizardry.ARMOUR_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomSpellBook(new ItemStack(Wizardry.scroll), 1, 1, Wizardry.SCROLL_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomSpellBook(new ItemStack(Wizardry.condenserUpgrade), 1, 1, Wizardry.WAND_UPGRADE_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomChestContent(new ItemStack(Wizardry.magicCrystal), 1, 4, Wizardry.CRYSTAL_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomChestContent(new ItemStack(Wizardry.arcaneTome, 1, 1), 1, 1, Wizardry.APPRENTICE_TOME_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomChestContent(new ItemStack(Wizardry.arcaneTome, 1, 2), 1, 1, Wizardry.ADVANCED_TOME_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomChestContent(new ItemStack(Wizardry.arcaneTome, 1, 3), 1, 1, Wizardry.MASTER_TOME_FREQUENCY));
ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomChestContent(new ItemStack(Wizardry.armourUpgrade), 1, 1, Wizardry.ARMOUR_UPGRADE_FREQUENCY));
if(Wizardry.discoveryMode) ChestGenHooks.addItem(WizardryWorldGenerator.WIZARD_TOWER, new WeightedRandomChestContent(new ItemStack(Wizardry.identificationScroll), 1, 1, Wizardry.IDENTIFICATION_SCROLL_FREQUENCY));
}
/* The name defined here in the regitry is the one Minecraft uses in game for commands like /give, as
* opposed to the one defined earlier with setBlockName() or setUnlocalizedName() which is the one used by
* the lang files. Ideally these should both be the same, but I've written the lang file now, so... */
/** Called from the preInit method in the main mod class to register all the blocks. */
public static void registerBlocks(){
GameRegistry.registerBlock(Wizardry.arcaneWorkbench, "arcane_workbench");
GameRegistry.registerBlock(Wizardry.crystalOre, "crystal_ore");
GameRegistry.registerBlock(Wizardry.petrifiedStone, "petrified_stone");
GameRegistry.registerBlock(Wizardry.iceStatue, "ice_statue");
GameRegistry.registerBlock(Wizardry.magicLight, "magic_light");
GameRegistry.registerBlock(Wizardry.crystalFlower, "crystal_flower");
GameRegistry.registerBlock(Wizardry.snare, "snare");
GameRegistry.registerBlock(Wizardry.transportationStone, "transportation_stone");
GameRegistry.registerBlock(Wizardry.spectralBlock, "spectral_block");
GameRegistry.registerBlock(Wizardry.crystalBlock, "crystal_block");
GameRegistry.registerBlock(Wizardry.meteor, "meteor");
GameRegistry.registerBlock(Wizardry.vanishingCobweb, "vanishing_cobweb");
}
/** Called from the preInit method in the main mod class to register all the items. */
public static void registerItems(){
GameRegistry.registerItem(Wizardry.magicCrystal, "magic_crystal");
GameRegistry.registerItem(Wizardry.magicWand, "magic_wand");
GameRegistry.registerItem(Wizardry.apprenticeWand, "apprentice_wand");
GameRegistry.registerItem(Wizardry.advancedWand, "advanced_wand");
GameRegistry.registerItem(Wizardry.masterWand, "master_wand");
GameRegistry.registerItem(Wizardry.spellBook, "spell_book");
GameRegistry.registerItem(Wizardry.arcaneTome, "arcane_tome");
GameRegistry.registerItem(Wizardry.wizardHandbook, "wizard_handbook");
GameRegistry.registerItem(Wizardry.basicFireWand, "basic_fire_wand");
GameRegistry.registerItem(Wizardry.basicIceWand, "basic_ice_wand");
GameRegistry.registerItem(Wizardry.basicLightningWand, "basic_lightning_wand");
GameRegistry.registerItem(Wizardry.basicNecromancyWand, "basic_necromancy_wand");
GameRegistry.registerItem(Wizardry.basicEarthWand, "basic_earth_wand");
GameRegistry.registerItem(Wizardry.basicSorceryWand, "basic_sorcery_wand");
GameRegistry.registerItem(Wizardry.basicHealingWand, "basic_healing_wand");
GameRegistry.registerItem(Wizardry.apprenticeFireWand, "apprentice_fire_wand");
GameRegistry.registerItem(Wizardry.apprenticeIceWand, "apprentice_ice_wand");
GameRegistry.registerItem(Wizardry.apprenticeLightningWand, "apprentice_lightning_wand");
GameRegistry.registerItem(Wizardry.apprenticeNecromancyWand, "apprentice_necromancy_wand");
GameRegistry.registerItem(Wizardry.apprenticeEarthWand, "apprentice_earth_wand");
GameRegistry.registerItem(Wizardry.apprenticeSorceryWand, "apprentice_sorcery_wand");
GameRegistry.registerItem(Wizardry.apprenticeHealingWand, "apprentice_healing_wand");
GameRegistry.registerItem(Wizardry.advancedFireWand, "advanced_fire_wand");
GameRegistry.registerItem(Wizardry.advancedIceWand, "advanced_ice_wand");
GameRegistry.registerItem(Wizardry.advancedLightningWand, "advanced_lightning_wand");
GameRegistry.registerItem(Wizardry.advancedNecromancyWand, "advanced_necromancy_wand");
GameRegistry.registerItem(Wizardry.advancedEarthWand, "advanced_earth_wand");
GameRegistry.registerItem(Wizardry.advancedSorceryWand, "advanced_sorcery_wand");
GameRegistry.registerItem(Wizardry.advancedHealingWand, "advanced_healing_wand");
GameRegistry.registerItem(Wizardry.masterFireWand, "master_fire_wand");
GameRegistry.registerItem(Wizardry.masterIceWand, "master_ice_wand");
GameRegistry.registerItem(Wizardry.masterLightningWand, "master_lightning_wand");
GameRegistry.registerItem(Wizardry.masterNecromancyWand, "master_necromancy_wand");
GameRegistry.registerItem(Wizardry.masterEarthWand, "master_earth_wand");
GameRegistry.registerItem(Wizardry.masterSorceryWand, "master_sorcery_wand");
GameRegistry.registerItem(Wizardry.masterHealingWand, "master_healing_wand");
GameRegistry.registerItem(Wizardry.spectralSword, "spectral_sword");
GameRegistry.registerItem(Wizardry.spectralPickaxe, "spectral_pickaxe");
GameRegistry.registerItem(Wizardry.spectralBow, "spectral_bow");
GameRegistry.registerItem(Wizardry.manaFlask, "mana_flask");
GameRegistry.registerItem(Wizardry.storageUpgrade, "storage_upgrade");
GameRegistry.registerItem(Wizardry.siphonUpgrade, "siphon_upgrade");
GameRegistry.registerItem(Wizardry.condenserUpgrade, "condenser_upgrade");
GameRegistry.registerItem(Wizardry.rangeUpgrade, "range_upgrade");
GameRegistry.registerItem(Wizardry.durationUpgrade, "duration_upgrade");
GameRegistry.registerItem(Wizardry.cooldownUpgrade, "cooldown_upgrade");
GameRegistry.registerItem(Wizardry.blastUpgrade, "blast_upgrade");
GameRegistry.registerItem(Wizardry.attunementUpgrade, "attunement_upgrade");
GameRegistry.registerItem(Wizardry.flamingAxe, "flaming_axe");
GameRegistry.registerItem(Wizardry.frostAxe, "frost_axe");
GameRegistry.registerItem(Wizardry.firebomb, "firebomb");
GameRegistry.registerItem(Wizardry.poisonBomb, "poison_bomb");
GameRegistry.registerItem(Wizardry.blankScroll, "blank_scroll");
GameRegistry.registerItem(Wizardry.scroll, "scroll");
GameRegistry.registerItem(Wizardry.armourUpgrade, "armour_upgrade");
GameRegistry.registerItem(Wizardry.magicSilk, "magic_silk");
GameRegistry.registerItem(Wizardry.wizardHat, "wizard_hat");
GameRegistry.registerItem(Wizardry.wizardRobe, "wizard_robe");
GameRegistry.registerItem(Wizardry.wizardLeggings, "wizard_leggings");
GameRegistry.registerItem(Wizardry.wizardBoots, "wizard_boots");
GameRegistry.registerItem(Wizardry.wizardHatFire, "wizard_hat_fire");
GameRegistry.registerItem(Wizardry.wizardRobeFire, "wizard_robe_fire");
GameRegistry.registerItem(Wizardry.wizardLeggingsFire, "wizard_leggings_fire");
GameRegistry.registerItem(Wizardry.wizardBootsFire, "wizard_boots_fire");
GameRegistry.registerItem(Wizardry.wizardHatIce, "wizard_hat_ice");
GameRegistry.registerItem(Wizardry.wizardRobeIce, "wizard_robe_ice");
GameRegistry.registerItem(Wizardry.wizardLeggingsIce, "wizard_leggings_ice");
GameRegistry.registerItem(Wizardry.wizardBootsIce, "wizard_boots_ice");
GameRegistry.registerItem(Wizardry.wizardHatLightning, "wizard_hat_lightning");
GameRegistry.registerItem(Wizardry.wizardRobeLightning, "wizard_robe_lightning");
GameRegistry.registerItem(Wizardry.wizardLeggingsLightning, "wizard_leggings_lightning");
GameRegistry.registerItem(Wizardry.wizardBootsLightning, "wizard_boots_lightning");
GameRegistry.registerItem(Wizardry.wizardHatNecromancy, "wizard_hat_necromancy");
GameRegistry.registerItem(Wizardry.wizardRobeNecromancy, "wizard_robe_necromancy");
GameRegistry.registerItem(Wizardry.wizardLeggingsNecromancy, "wizard_leggings_necromancy");
GameRegistry.registerItem(Wizardry.wizardBootsNecromancy, "wizard_boots_necromancy");
GameRegistry.registerItem(Wizardry.wizardHatEarth, "wizard_hat_earth");
GameRegistry.registerItem(Wizardry.wizardRobeEarth, "wizard_robe_earth");
GameRegistry.registerItem(Wizardry.wizardLeggingsEarth, "wizard_leggings_earth");
GameRegistry.registerItem(Wizardry.wizardBootsEarth, "wizard_boots_earth");
GameRegistry.registerItem(Wizardry.wizardHatSorcery, "wizard_hat_sorcery");
GameRegistry.registerItem(Wizardry.wizardRobeSorcery, "wizard_robe_sorcery");
GameRegistry.registerItem(Wizardry.wizardLeggingsSorcery, "wizard_leggings_sorcery");
GameRegistry.registerItem(Wizardry.wizardBootsSorcery, "wizard_boots_sorcery");
GameRegistry.registerItem(Wizardry.wizardHatHealing, "wizard_hat_healing");
GameRegistry.registerItem(Wizardry.wizardRobeHealing, "wizard_robe_healing");
GameRegistry.registerItem(Wizardry.wizardLeggingsHealing, "wizard_leggings_healing");
GameRegistry.registerItem(Wizardry.wizardBootsHealing, "wizard_boots_healing");
GameRegistry.registerItem(Wizardry.spawnWizard, "spawn_wizard");
GameRegistry.registerItem(Wizardry.spectralHelmet, "spectral_helmet");
GameRegistry.registerItem(Wizardry.spectralChestplate, "spectral_chestplate");
GameRegistry.registerItem(Wizardry.spectralLeggings, "spectral_leggings");
GameRegistry.registerItem(Wizardry.spectralBoots, "spectral_boots");
GameRegistry.registerItem(Wizardry.smokeBomb, "smoke_bomb");
GameRegistry.registerItem(Wizardry.identificationScroll, "identification_scroll");
}
/** Called from the preInit method in the main mod class to register all the tileentities. */
public static void registerTileEntities(){
GameRegistry.registerTileEntity(TileEntityArcaneWorkbench.class, Wizardry.MODID + "ArcaneWorkbenchTileEntity");
GameRegistry.registerTileEntity(TileEntityStatue.class, Wizardry.MODID + "PetrifiedStoneTileEntity");
GameRegistry.registerTileEntity(TileEntityMagicLight.class, Wizardry.MODID + "MagicLightTileEntity");
GameRegistry.registerTileEntity(TileEntityTimer.class, Wizardry.MODID + "TimerTileEntity");
GameRegistry.registerTileEntity(TileEntityPlayerSave.class, Wizardry.MODID + "TileEntityPlayerSave");
}
/** Called from the preInit method in the main mod class to register all the entities. */
public static void registerEntities(Wizardry wizardry){
int id = 0; // Incrementable index for the mod specific entity id.
EntityRegistry.registerModEntity(EntityZombieMinion.class, "Zombie Minion", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityMagicMissile.class, "Magic Missile", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityArc.class, "Arc", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntitySkeletonMinion.class, "Skeleton Minion", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntitySparkBomb.class, "Spark Bomb", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntitySpiritWolf.class, "Spirit Wolf", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityIceShard.class, "Ice Shard", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityBlazeMinion.class, "Blaze Minion", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityIceWraith.class, "Ice Wraith", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityLightningWraith.class, "Lightning Wraith", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityBlackHole.class, "Black Hole", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityShield.class, "Shield", id++, wizardry, 128, 1, true);
EntityRegistry.registerModEntity(EntityMeteor.class, "Meteor", id++, wizardry, 128, 5, true);
EntityRegistry.registerModEntity(EntityBlizzard.class, "Blizzard", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityWizard.class, "Wizard", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityBubble.class, "Bubble", id++, wizardry, 128, 3, false);
EntityRegistry.registerModEntity(EntityTornado.class, "Tornado", id++, wizardry, 128, 1, false);
EntityRegistry.registerModEntity(EntityHammer.class, "Lightning Hammer", id++, wizardry, 128, 1, true);
EntityRegistry.registerModEntity(EntityFirebomb.class, "Firebomb", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityForceOrb.class, "Force Orb", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityArrowRain.class, "Arrow Rain", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntitySpark.class, "Spark", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityShadowWraith.class, "Shadow Wraith", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityDarknessOrb.class, "Darkness Orb", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntitySpiderMinion.class, "Spider Minion", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityHealAura.class, "Healing Aura", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityFireSigil.class, "Fire Sigil", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityFrostSigil.class, "Frost Sigil", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityLightningSigil.class, "Lightning Sigil", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityLightningArrow.class, "Lightning Arrow", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityFirebolt.class, "Firebolt", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityPoisonBomb.class, "Poison Bomb", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityIceCharge.class, "Ice Charge", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityForceArrow.class, "Force Arrow", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityDart.class, "Dart", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityMagicSlime.class, "Magic Slime", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityForcefield.class, "Forcefield", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityFireRing.class, "Ring of Fire", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityLightningDisc.class, "Lightning Disc", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityThunderbolt.class, "Thunderbolt", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityIceGiant.class, "Ice Giant", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntitySpiritHorse.class, "Spirit Horse", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityPhoenix.class, "Phoenix", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntitySilverfishMinion.class, "Silverfish Minion", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityDecay.class, "Decay", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityStormElemental.class, "Storm Elemental", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityEarthquake.class, "Earthquake", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntityFallingGrass.class, "Falling Grass", id++, wizardry, 128, 5, true);
EntityRegistry.registerModEntity(EntityIceLance.class, "Ice Lance", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityHailstorm.class, "Hailstorm", id++, wizardry, 128, 10, false);
EntityRegistry.registerModEntity(EntitySmokeBomb.class, "Smoke Bomb", id++, wizardry, 128, 10, true);
EntityRegistry.registerModEntity(EntityEvilWizard.class, "Evil Wizard", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityDecoy.class, "Decoy", id++, wizardry, 128, 3, true);
EntityRegistry.registerModEntity(EntityIceSpike.class, "Ice Spike", id++, wizardry, 128, 1, true);
EntityRegistry.registerModEntity(EntityLightningPulse.class, "Lightning Pulse", id++, wizardry, 128, 10, false);
List<BiomeGenBase> biomes = new ArrayList<BiomeGenBase>();
for(BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()){
if(biome != null){
biomes.add(biome);
}
}
// For reference: 5, 1, 1 are the parameters for the witch in vanilla.
EntityRegistry.addSpawn(EntityEvilWizard.class, 3, 1, 1, EnumCreatureType.monster, biomes.toArray(new BiomeGenBase[biomes.size()]));
}
/** Static instance of the none spell, used for various purposes. */
public static Spell none;
/** Static instance of the magic missile spell, used for crafting spell books and by wizards. */
public static Spell magicMissile;
/** Static instance of the transportation spell, used for chat messages. */
public static Spell transportation;
/** Static instance of the clairvoyance spell, used for chat messages. */
public static Spell clairvoyance;
/** Called from the preInit method in the main mod class to register all the spells in wizardry. */
public static void registerSpells(){
// Wizardry 1.0 spells
Spell.register(none = new None());
Spell.register(magicMissile = new MagicMissile());
Spell.register(new Ignite());
Spell.register(new Freeze());
Spell.register(new Snowball());
Spell.register(new Arc());
Spell.register(new Thunderbolt());
Spell.register(new SummonZombie());
Spell.register(new Snare());
Spell.register(new Dart());
Spell.register(new Light());
Spell.register(new Telekinesis());
Spell.register(new Heal());
Spell.register(new Fireball());
Spell.register(new FlameRay());
Spell.register(new Firebomb());
Spell.register(new FireSigil());
Spell.register(new Firebolt());
Spell.register(new FrostRay());
Spell.register(new SummonSnowGolem());
Spell.register(new IceShard());
Spell.register(new IceStatue());
Spell.register(new FrostSigil());
Spell.register(new LightningRay());
Spell.register(new SparkBomb());
Spell.register(new HomingSpark());
Spell.register(new LightningSigil());
Spell.register(new LightningArrow());
Spell.register(new LifeDrain());
Spell.register(new SummonSkeleton());
Spell.register(new Metamorphosis());
Spell.register(new Wither());
Spell.register(new Poison());
Spell.register(new GrowthAura());
Spell.register(new Bubble());
Spell.register(new Whirlwind());
Spell.register(new PoisonBomb());
Spell.register(new SummonSpiritWolf());
Spell.register(new Blink());
Spell.register(new Agility());
Spell.register(new ConjureSword());
Spell.register(new ConjurePickaxe());
Spell.register(new ConjureBow());
Spell.register(new ForceArrow());
Spell.register(new Shield());
Spell.register(new ReplenishHunger());
Spell.register(new CureEffects());
Spell.register(new HealAlly());
Spell.register(new SummonBlaze());
Spell.register(new RingOfFire());
Spell.register(new Detonate());
Spell.register(new FireResistance());
Spell.register(new Fireskin());
Spell.register(new FlamingAxe());
Spell.register(new Blizzard());
Spell.register(new SummonIceWraith());
Spell.register(new IceShroud());
Spell.register(new IceCharge());
Spell.register(new FrostAxe());
Spell.register(new InvokeWeather());
Spell.register(new ChainLightning());
Spell.register(new LightningBolt());
Spell.register(new SummonLightningWraith());
Spell.register(new StaticAura());
Spell.register(new LightningDisc());
Spell.register(new MindControl());
Spell.register(new SummonWitherSkeleton());
Spell.register(new Entrapment());
Spell.register(new WitherSkull());
Spell.register(new DarknessOrb());
Spell.register(new ShadowWard());
Spell.register(new Decay());
Spell.register(new WaterBreathing());
Spell.register(new Tornado());
Spell.register(new Glide());
Spell.register(new SummonSpiritHorse());
Spell.register(new SpiderSwarm());
Spell.register(new Slime());
Spell.register(new Petrify());
Spell.register(new Invisibility());
Spell.register(new Levitation());
Spell.register(new ForceOrb());
Spell.register(transportation = new Transportation());
Spell.register(new SpectralPathway());
Spell.register(new PhaseStep());
Spell.register(new VanishingBox());
Spell.register(new GreaterHeal());
Spell.register(new HealingAura());
Spell.register(new Forcefield());
Spell.register(new Ironflesh());
Spell.register(new Transience());
Spell.register(new Meteor());
Spell.register(new Firestorm());
Spell.register(new SummonPhoenix());
Spell.register(new IceAge());
Spell.register(new WallOfFrost());
Spell.register(new SummonIceGiant());
Spell.register(new Thunderstorm());
Spell.register(new LightningHammer());
Spell.register(new PlagueOfDarkness());
Spell.register(new SummonSkeletonLegion());
Spell.register(new SummonShadowWraith());
Spell.register(new ForestsCurse());
Spell.register(new Flight());
Spell.register(new SilverfishSwarm());
Spell.register(new BlackHole());
Spell.register(new Shockwave());
Spell.register(new SummonIronGolem());
Spell.register(new ArrowRain());
Spell.register(new Diamondflesh());
Spell.register(new FontOfVitality());
// Wizardry 1.1 spells
Spell.register(new SmokeBomb());
Spell.register(new MindTrick());
Spell.register(new Leap());
Spell.register(new PocketFurnace());
Spell.register(new Intimidate());
Spell.register(new Banish());
Spell.register(new SixthSense());
Spell.register(new Darkvision());
Spell.register(clairvoyance = new Clairvoyance());
Spell.register(new PocketWorkbench());
Spell.register(new ImbueWeapon());
Spell.register(new InvigoratingPresence());
Spell.register(new Oakflesh());
Spell.register(new GreaterFireball());
Spell.register(new FlamingWeapon());
Spell.register(new IceLance());
Spell.register(new FreezingWeapon());
Spell.register(new IceSpikes());
Spell.register(new LightningPulse());
Spell.register(new CurseOfSoulbinding());
Spell.register(new Cobwebs());
Spell.register(new Decoy());
Spell.register(new ArcaneJammer());
Spell.register(new ConjureArmour());
Spell.register(new GroupHeal());
Spell.register(new Hailstorm());
Spell.register(new LightningWeb());
Spell.register(new SummonStormElemental());
Spell.register(new Earthquake());
Spell.register(new FontOfMana());
}
/** Called from the init method in the main mod class to register all the recipes. */
public static void registerRecipes(){
ItemStack ironIngotStack = new ItemStack(Items.iron_ingot);
ItemStack magicCrystalStack = new ItemStack(Wizardry.magicCrystal);
ItemStack magicWandStack = new ItemStack(Wizardry.magicWand, 1, EnumTier.BASIC.maxCharge);
ItemStack goldNuggetStack = new ItemStack(Items.gold_nugget);
ItemStack stickStack = new ItemStack(Items.stick);
ItemStack bookStack = new ItemStack(Items.book);
ItemStack stringStack = new ItemStack(Items.string);
ItemStack spellBookStack = new ItemStack(Wizardry.spellBook, 1, WizardryRegistry.magicMissile.id());
ItemStack arcaneWorkbenchStack = new ItemStack(Wizardry.arcaneWorkbench);
ItemStack stoneStack = new ItemStack(Blocks.stone);
ItemStack lapisBlockStack = new ItemStack(Blocks.lapis_block);
ItemStack purpleCarpetStack = new ItemStack(Blocks.carpet, 1, 10);
ItemStack wizardHandbookStack = new ItemStack(Wizardry.wizardHandbook);
ItemStack crystalFlowerStack = new ItemStack(Wizardry.crystalFlower);
ItemStack magicCrystalStack1 = new ItemStack(Wizardry.magicCrystal, 2);
ItemStack magicCrystalStack2 = new ItemStack(Wizardry.magicCrystal, 9);
ItemStack crystalBlockStack = new ItemStack(Wizardry.crystalBlock);
ItemStack manaFlaskStack = new ItemStack(Wizardry.manaFlask);
ItemStack bottleStack = new ItemStack(Items.glass_bottle);
ItemStack gunpowderStack = new ItemStack(Items.gunpowder);
ItemStack blazePowderStack = new ItemStack(Items.blaze_powder);
ItemStack spiderEyeStack = new ItemStack(Items.spider_eye);
// Coal or charcoal is equally fine, hence the wildcard value
ItemStack coalStack = new ItemStack(Items.coal, 1, OreDictionary.WILDCARD_VALUE);
ItemStack firebombStack = new ItemStack(Wizardry.firebomb, 3);
ItemStack poisonBombStack = new ItemStack(Wizardry.poisonBomb, 3);
ItemStack smokeBombStack = new ItemStack(Wizardry.smokeBomb, 3);
ItemStack transportationStoneStack = new ItemStack(Wizardry.transportationStone, 2);
ItemStack silkStack = new ItemStack(Wizardry.magicSilk);
ItemStack silkStack1 = new ItemStack(Wizardry.magicSilk, 2);
ItemStack hatStack = new ItemStack(Wizardry.wizardHat);
ItemStack robeStack = new ItemStack(Wizardry.wizardRobe);
ItemStack leggingsStack = new ItemStack(Wizardry.wizardLeggings);
ItemStack bootsStack = new ItemStack(Wizardry.wizardBoots);
ItemStack scrollStack = new ItemStack(Wizardry.blankScroll);
ItemStack paperStack = new ItemStack(Items.paper);
GameRegistry.addRecipe(magicWandStack, " x", " y ", "z ", 'x', magicCrystalStack, 'y', stickStack, 'z', goldNuggetStack);
GameRegistry.addRecipe(spellBookStack, " x ", "xyx", " x ", 'x', magicCrystalStack, 'y', bookStack);
GameRegistry.addRecipe(arcaneWorkbenchStack, "vwv", "xyx", "zzz", 'v', goldNuggetStack, 'w', purpleCarpetStack, 'x', magicCrystalStack, 'y', lapisBlockStack, 'z', stoneStack);
GameRegistry.addRecipe(manaFlaskStack, "yyy", "yxy", "yyy", 'x', bottleStack, 'y', magicCrystalStack);
GameRegistry.addRecipe(transportationStoneStack, " x ", "xyx", " x ", 'x', stoneStack, 'y', magicCrystalStack);
GameRegistry.addRecipe(hatStack, "yyy", "y y", 'y', silkStack);
GameRegistry.addRecipe(robeStack, "y y", "yyy", "yyy", 'y', silkStack);
GameRegistry.addRecipe(leggingsStack, "yyy", "y y", "y y", 'y', silkStack);
GameRegistry.addRecipe(bootsStack, "y y", "y y", 'y', silkStack);
GameRegistry.addRecipe(silkStack1, " x ", "xyx", " x ", 'x', stringStack, 'y', magicCrystalStack);
GameRegistry.addRecipe(crystalBlockStack, "zzz", "zzz", "zzz", 'z', magicCrystalStack);
GameRegistry.addShapelessRecipe(wizardHandbookStack, bookStack, magicCrystalStack);
GameRegistry.addShapelessRecipe(magicCrystalStack1, crystalFlowerStack);
GameRegistry.addShapelessRecipe(magicCrystalStack2, crystalBlockStack);
if(Wizardry.firebombIsCraftable) GameRegistry.addShapelessRecipe(firebombStack, bottleStack, gunpowderStack, blazePowderStack, blazePowderStack);
if(Wizardry.poisonBombIsCraftable) GameRegistry.addShapelessRecipe(poisonBombStack, bottleStack, gunpowderStack, spiderEyeStack, spiderEyeStack);
if(Wizardry.smokeBombIsCraftable) GameRegistry.addShapelessRecipe(smokeBombStack, bottleStack, gunpowderStack, coalStack, coalStack);
if(Wizardry.useAlternateScrollRecipe){
GameRegistry.addShapelessRecipe(scrollStack, paperStack, stringStack, magicCrystalStack);
}else{
GameRegistry.addShapelessRecipe(scrollStack, paperStack, stringStack);
}
// Mana flask recipes
ItemStack miscWandStack;
for(int i=0; i<EnumElement.values().length; i++){
for(int j=0; j<EnumTier.values().length; j++){
miscWandStack = new ItemStack(WizardryUtilities.getWand(EnumTier.values()[j], EnumElement.values()[i]), 1, OreDictionary.WILDCARD_VALUE);
GameRegistry.addShapelessRecipe(miscWandStack, miscWandStack, manaFlaskStack);
}
}
ItemStack miscArmourStack;
for(int i=0; i<EnumElement.values().length; i++){
for(int j=0; j<4; j++){
miscArmourStack = new ItemStack(WizardryUtilities.getArmour(EnumElement.values()[i], j), 1, OreDictionary.WILDCARD_VALUE);
GameRegistry.addShapelessRecipe(miscArmourStack, miscArmourStack, manaFlaskStack);
}
}
}
}
@@ -0,0 +1,881 @@
package electroblob.wizardry;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import cpw.mods.fml.common.registry.EntityRegistry;
import electroblob.wizardry.entity.living.EntitySummonedCreature;
import electroblob.wizardry.entity.living.EntityWizard;
import electroblob.wizardry.spell.MindControl;
import electroblob.wizardry.spell.Spell;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityList.EntityEggInfo;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
/** This class contains some useful static methods for use anywhere - items, entities, spells, events, blocks, etc.
* @see CommonProxy
* @see WandHelper
* @since Wizardry 1.0 */
public final class WizardryUtilities {
/**
* Finds the nearest floor level to the given y coord within the range specified at the given x and z coords.
* Liquids and other blocks that cannot be built on top of do not count, but stuff like signs does.
* (Technically any block is allowed to be the floor according to the code, but seeing as it searches upwards and
* non-solid blocks usually need a supporting block, the floor is likely to always be solid).
* @param world
* @param x The x coordinate to search in
* @param y The y coordinate to search from
* @param z The z coordinate to search in
* @param range The maximum distance from the given y coordinate to search.
* @return The y coordinate of the closest floor level, or -1 if there is none. Returns the actual level of the floor
* as would be seen in the debug screen when the player is standing on it.
* @see WizardryUtilities#getNearestFloorLevelB(World, int, int, int, int)
*/
public static int getNearestFloorLevel(World world, int x, int y, int z, int range){
int yCoord = -2;
for(int i=y-range;i<=y+range;i++){
// The last bit determines whether the block found to be a suitable floor is closer than the previous one found.
// Edit: Changed the first condition from blockExists() since that method includes air blocks!
if(world.doesBlockHaveSolidTopSurface(world, x, i, z) && (world.isAirBlock(x, i+1, z) || !world.doesBlockHaveSolidTopSurface(world, x, i+1, z))
&& (i-y < yCoord-y || yCoord == -2)){
yCoord = i;
}
}
return yCoord + 1;
}
/**
* Returns whether the block at the given coordinates can be replaced by another one (works as if a block is being placed by a player).
* True for air, liquids, vines, tall grass and snow layers but not for flowers, signs etc.
* This is a shortcut for world.getBlock(x, y, z).isReplaceable(world, x, y, z);
* Not much of a shortcut any more, since block ids have been phased out.
* @see WizardryUtilities#canBlockBeReplacedB(World, int, int, int)
*/
public static boolean canBlockBeReplaced(World world, int x, int y, int z){
// Why does isReplaceable have those arguments? I don't know. They aren't used. It's probably for overriding
// stuff in case these arguments affect whether it is replaceable or not. It is a forge method, after all.
return world.isAirBlock(x, y, z) || world.getBlock(x, y, z).isReplaceable(world, x, y, z);
}
/**
* Returns whether the block at the given coordinates can be replaced by another one (works as if a block is being placed by a player)
* and is not a liquid.
* True for air, vines, tall grass and snow layers but not for flowers, signs etc. or any liquids.
* @see WizardryUtilities#canBlockBeReplaced(World, int, int, int)
*/
public static boolean canBlockBeReplacedB(World world, int x, int y, int z){
return (world.isAirBlock(x, y, z) || world.getBlock(x, y, z).isReplaceable(world, x, y, z)) && !world.getBlock(x, y, z).getMaterial().isLiquid();
}
/**
* Returns whether the block at the given coordinates is unbreakable in survival mode. In vanilla this is true for
* bedrock and end portal frame, for example.
* This is a shortcut for world.getBlockId(x, y, z).getBlockHardness == -1.0f;
* Not much of a shortcut any more, since block ids have been phased out.
*/
public static boolean isBlockUnbreakable(World world, int x, int y, int z){
return world.isAirBlock(x, y, z) ? false : world.getBlock(x, y, z).getBlockHardness(world, x, y, z) == -1.0f;
}
/**
* Finds the nearest floor level to the given y coord within the range specified at the given x and z coords.
* Only works if the block above the floor is actually air and the floor is solid or a liquid.
* @param world
* @param x The x coordinate to search in
* @param y The y coordinate to search from
* @param z The z coordinate to search in
* @param range The maximum distance from the given y coordinate to search.
* @return The y coordinate of the closest floor level, or -1 if there is none. Returns the actual level of the floor
* as would be seen in the debug screen when the player is standing on it.
* @see WizardryUtilities#getNearestFloorLevel(World, int, int, int, int)
*/
public static int getNearestFloorLevelB(World world, int x, int y, int z, int range){
int yCoord = -2;
for(int i=y-range;i<=y+range;i++){
if(world.isAirBlock(x, i+1, z) && (world.getBlock(x, i, z).getMaterial().isLiquid() || world.doesBlockHaveSolidTopSurface(world, x, i, z))
&& (i-y < yCoord-y || yCoord == -2)){
// The last bit determines whether the block found to be a suitable floor is closer than the previous one found.
yCoord = i;
}
}
return yCoord + 1;
}
/**
* Finds the nearest floor level to the given y coord within the range specified at the given x and z coords.
* Everything that is not air is treated as floor, even stuff that can't be walked on.
* @param world
* @param x The x coordinate to search in
* @param y The y coordinate to search from
* @param z The z coordinate to search in
* @param range The maximum distance from the given y coordinate to search.
* @return The y coordinate of the closest floor level, or -1 if there is none. Returns the actual level of the floor
* as would be seen in the debug screen when the player is standing on it.
* @see WizardryUtilities#getNearestFloorLevel(World, int, int, int, int)
*/
public static int getNearestFloorLevelC(World world, int x, int y, int z, int range){
int yCoord = -2;
for(int i=y-range;i<=y+range;i++){
if(world.isAirBlock(x, i+1, z) && (i-y < yCoord-y || yCoord == -2)){
// The last bit determines whether the block found to be a suitable floor is closer than the previous one found.
yCoord = i;
}
}
return yCoord + 1;
}
/**
* Gets the block the specified entity is standing on. Uses {@link MathHelper#floor_double(double)} because casting to int will not
* return the correct coordinate when x or z is negative.
*/
public static Block getBlockEntityIsStandingOn(Entity entity){
return entity.worldObj.getBlock(MathHelper.floor_double(entity.posX), (int)WizardryUtilities.getEntityFeetPos(entity)-1, MathHelper.floor_double(entity.posZ));
}
/**
* Shorthand for {@link WizardryUtilities#getEntitiesWithinRadius(double, double, double, double, World, Class)}
* with EntityLivingBase as the entity type. This is by far the most common use for that method, which is why this
* shorthand exists.
* @param radius The search radius
* @param x The x coordinate to search around
* @param y The y coordinate to search around
* @param z The z coordinate to search around
* @param world The world to search in
*/
public static List<EntityLivingBase> getEntitiesWithinRadius(double radius, double x, double y, double z, World world){
return getEntitiesWithinRadius(radius, x, y, z, world, EntityLivingBase.class);
}
/**
* Returns all entities of the specified type within the specified radius of the given coordinates. This is different to using
* a raw AABB because a raw AABB will search in a cube volume rather than a sphere.
* Note that this does not exclude any entities; if any specific entities are to be excluded this must be
* checked when iterating through the list.
* @see {@link WizardryUtilities#getEntitiesWithinRadius(double, double, double, double, World)}
* @param radius The search radius
* @param x The x coordinate to search around
* @param y The y coordinate to search around
* @param z The z coordinate to search around
* @param world The world to search in
* @param entityType The class of entity to search for; pass in Entity.class for all entities
*/
public static <T extends Entity> List<T> getEntitiesWithinRadius(double radius, double x, double y, double z, World world, Class<T> entityType){
AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(x - radius, y - radius, z - radius, x + radius, y + radius, z + radius);
List entityList = world.getEntitiesWithinAABB(entityType, aabb);
for(int i=0;i<entityList.size();i++){
if(((Entity)entityList.get(i)).getDistance(x, y, z) > radius){
entityList.remove(i);
}
}
return entityList;
}
// ^ Handy syntax using type parameters here!
// I *think* that eclipse, for whatever reason, was not showing an 'unchecked' warning here. If you think about it,
// if this method returns a generic list type I could, in theory, put strings or something in it and then when
// invoking the method store its result as a List<EntityLivingBase>, which would cause a ClassCastException. Using
// this handy syntax prevents that from happening. TL;DR: Always use type parameters when available, they're there
// for a reason. Minecraft is bad in this respect because it doesn't use them in places like World.
/**
* Gets an entity from its UUID. Note that you should check this isn't null.
* @param world The world the entity is in
* @param id The entity's UUID
* @return The Entity that has the given UUID, or null if no such entity exists in the specified world.
*/
public static Entity getEntityByUUID(World world, UUID id){
for(Object object : world.loadedEntityList){
if(object instanceof Entity){
Entity entity = (Entity)object;
// This is a perfect example of where you need to use .equals() and not ==. For most applications,
// this was unnoticeable until world reload because the UUID instance or entity instance is stored.
// Fixed now though. Of course, you could alternatively compare the string representations.
if(entity.getUniqueID().equals(id)){
return entity;
}
}
}
return null;
}
/**
* Does a block ray trace (NOT entities) from an entity's eyes (i.e. properly...)
*/
public static MovingObjectPosition rayTrace(double range, World world, EntityLivingBase entity, boolean hitLiquids)
{
Vec3 vec3 = Vec3.createVectorHelper(entity.posX, entity.posY + entity.getEyeHeight(), entity.posZ);
Vec3 vec31 = entity.getLookVec();
Vec3 vec32 = vec3.addVector(vec31.xCoord * range, vec31.yCoord * range, vec31.zCoord * range);
return world.rayTraceBlocks(vec3, vec32, hitLiquids);
}
/**
* Helper method which does a rayTrace for entities from an entity's eye level in the direction they are looking
* with a specified range, using the tracePath method. Tidies up the code a bit. Border size defaults to 1.
*
* @param world
* @param entity
* @param range
* @return
*/
public static MovingObjectPosition standardEntityRayTrace(World world, EntityLivingBase entity, double range){
double dx = entity.getLookVec().xCoord * range;
double dy = entity.getLookVec().yCoord * range;
double dz = entity.getLookVec().zCoord * range;
HashSet hashset = new HashSet(1);
hashset.add(entity);
return WizardryUtilities.tracePath(world, (float)entity.posX, (float)(entity.posY + entity.getEyeHeight()), (float)entity.posZ, (float)(entity.posX + dx), (float)(entity.posY + entity.getEyeHeight() + dy), (float)(entity.posZ + dz), 1.0f, hashset, false);
}
/**
* Helper method which does a rayTrace for entities from a entity's eye level in the direction they are looking
* with a specified range and radius, using the tracePath method. Tidies up the code a bit.
*
* @param world
* @param entity
* @param range
* @param borderSize
* @return
*/
public static MovingObjectPosition standardEntityRayTrace(World world, EntityLivingBase entity, double range, float borderSize){
double dx = entity.getLookVec().xCoord * range;
double dy = entity.getLookVec().yCoord * range;
double dz = entity.getLookVec().zCoord * range;
HashSet hashset = new HashSet(1);
hashset.add(entity);
return WizardryUtilities.tracePath(world, (float)entity.posX, (float)(entity.posY + entity.getEyeHeight()), (float)entity.posZ, (float)(entity.posX + dx), (float)(entity.posY + entity.getEyeHeight() + dy), (float)(entity.posZ + dz), borderSize, hashset, false);
}
/**
* Method for ray tracing entities (the useless default method doesn't work, despite EnumHitType having an ENTITY field...)
* You can also use this for seeking.
*
* @param world
* @param x startX
* @param y startY
* @param z startZ
* @param tx endX
* @param ty endY
* @param tz endZ
* @param borderSize extra area to examine around line for entities
* @param excluded any excluded entities (the player, etc)
* @return a MovingObjectPosition of either the block hit (no entity hit), the entity hit (hit an entity), or null for nothing hit
*/
public static MovingObjectPosition tracePath(World world, float x, float y, float z, float tx, float ty, float tz, float borderSize, HashSet<Entity> excluded, boolean collideablesOnly){
Vec3 startVec = Vec3.createVectorHelper(x, y, z);
Vec3 lookVec = Vec3.createVectorHelper(tx-x, ty-y, tz-z);
Vec3 endVec = Vec3.createVectorHelper(tx, ty, tz);
float minX = x < tx ? x : tx;
float minY = y < ty ? y : ty;
float minZ = z < tz ? z : tz;
float maxX = x > tx ? x : tx;
float maxY = y > ty ? y : ty;
float maxZ = z > tz ? z : tz;
AxisAlignedBB bb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ).expand(borderSize, borderSize, borderSize);
List<Entity> allEntities = world.getEntitiesWithinAABBExcludingEntity(null, bb);
MovingObjectPosition blockHit = world.rayTraceBlocks(startVec, endVec);
startVec = Vec3.createVectorHelper(x, y, z);
endVec = Vec3.createVectorHelper(tx, ty, tz);
float maxDistance = (float) endVec.distanceTo(startVec);
if(blockHit!=null)
{
maxDistance = (float) blockHit.hitVec.distanceTo(startVec);
}
Entity closestHitEntity = null;
float closestHit = maxDistance;
float currentHit = 0.f;
AxisAlignedBB entityBb;// = ent.getBoundingBox();
MovingObjectPosition intercept;
for(Entity ent : allEntities)
{
if((ent.canBeCollidedWith() || !collideablesOnly) && ((excluded != null && !excluded.contains(ent)) || excluded == null))
{
float entBorder = ent.getCollisionBorderSize();
entityBb = ent.boundingBox;
if(entityBb!=null)
{
entityBb = entityBb.expand(entBorder, entBorder, entBorder);
intercept = entityBb.calculateIntercept(startVec, endVec);
if(intercept!=null)
{
currentHit = (float) intercept.hitVec.distanceTo(startVec);
if(currentHit < closestHit || currentHit==0)
{
closestHit = currentHit;
closestHitEntity = ent;
}
}
}
}
}
if(closestHitEntity!=null)
{
blockHit = new MovingObjectPosition(closestHitEntity);
}
return blockHit;
}
// Just what benefit does having posY be the eye position on the first person client actually give?
/**
* Gets the y coordinate of the given player's eyes. This is to cover an inconsistency between the value of
* EntityPlayer.posY on the first person client and everywhere else; in first person (i.e. when
* Minecraft.getMinecraft().thePlayer == player) player.posY is the eye position, but everywhere else it is the
* feet position. This is intended for use when spawning particles, since this is the only situation where the
* discrepancy is likely to matter.
*/
public static double getPlayerEyesPos(EntityPlayer player){
return Wizardry.proxy.getPlayerEyesPos(player);
}
/**
* Gets the y coordinate of the given entity's feet. This is to cover an inconsistency between the value of
* EntityPlayer.posY on the first person client and everywhere else; in first person (i.e. when
* Minecraft.getMinecraft().thePlayer == player) player.posY is the eye position, but everywhere else it is the
* feet position. This is intended for use when spawning particles, since this is the only situation where the
* discrepancy is likely to matter.
*/
public static double getEntityFeetPos(Entity entity){
if(entity instanceof EntityPlayer){
// For some reason, EntityPlayer.getEyeHeight() always returns 0.12, so I have replicated the behaviour
// of the same method from EntityLivingBase and subtracted that instead.
return getPlayerEyesPos((EntityPlayer)entity) - entity.height*0.85f;
}else{
return entity.posY;
}
}
/**
* Verifies that the given string is a valid string representation of a UUID. More specifically, returns true if and
* only if the given string is not null and matches the regular expression:<p>
* <center><code>/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/<p></code></center>
* which is the regex equivlent of the standard string representation of a UUID as described in {@link UUID#toString()}.
* This method is intended to be used as a check to prevent an {@link IllegalArgumentException} from occurring when
* calling {@link UUID#fromString(String)}.
* @param string The string to be checked
* @return Whether the given string is a valid string representation of a UUID
*/
public static boolean verifyUUIDString(String string){
return string != null && string.matches("/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/");
}
/**
* Returns whether the given target can be attacked by the given attacker. It is up to the caller of this method
* to work out what this means; it doesn't necessarily mean the target is completely immune (for example, revenge
* targeting might reasonably bypass this). This method is intended for use where the damage is indirect and/or
* unavoidable; direct attacks should not check this method. Currently this means the following situations check
* this method:
* <p>
* - AI targeting for summoned creatures<br>
* - AI targeting for mind-controlled creatures<br>
* - Constructs with an area of effect<br>
* - Instantaneous spells with an area of effect around the caster (e.g. forest's curse, thunderstorm)<br>
* - Any lightning chaining effects<br>
* - Any projectiles which seek targets
* <p>
* Also note that the friendly fire option is dealt with
* in the event handler. This method acts as a sort of wrapper for all the ADS stuff in {@link ExtendedPlayer}; more
* details about the ally designation system can be found there.
*
* @param attacker The entity that cast the spell originally
* @param target The entity being attacked
*
* @return False under any of the following circumstances, true otherwise:
* <p>
* - The target is the attacker (this isn't as stupid as it sounds - anything with an AoE might cause this to be
* true, as can summoned creatures)
* <p>
* - The target and the attacker are both players and the target is an ally of the attacker (but the
* attacker need not be an ally of the target)
* <p>
* - The target is a creature that was summoned/controlled by the attacker or by an ally of the attacker.
*/
public static boolean isValidTarget(Entity attacker, Entity target){
// Don't need to check if either entity is null since instanceof does this anyway.
// Tests whether the target is the attacker
if(target == attacker) return false;
// Tests whether the target is a creature that was summoned by the attacker
if(target instanceof EntitySummonedCreature && ((EntitySummonedCreature)target).getCaster() == attacker){
return false;
}
// Tests whether the target is a creature that was mind controlled by the attacker
if(target instanceof EntityLiving && ((EntityLivingBase)target).isPotionActive(Wizardry.mindControl)){
NBTTagCompound entityNBT = target.getEntityData();
if(entityNBT != null && entityNBT.hasKey(MindControl.NBT_KEY)){
if(attacker == WizardryUtilities.getEntityByUUID(target.worldObj, UUID.fromString(entityNBT.getString(MindControl.NBT_KEY)))){
return false;
}
}
}
// Ally section
if(attacker instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer)attacker) != null){
if(target instanceof EntityPlayer){
// Tests whether the target is an ally of the attacker
if(ExtendedPlayer.get((EntityPlayer)attacker).isPlayerAlly((EntityPlayer)target)){
return false;
}
}else if(target instanceof EntitySummonedCreature){
// Tests whether the target is a creature that was summoned by an ally of the attacker
if(((EntitySummonedCreature)target).getCaster() instanceof EntityPlayer
&& ExtendedPlayer.get((EntityPlayer)attacker).isPlayerAlly((EntityPlayer)((EntitySummonedCreature)target).getCaster())){
return false;
}
}else if(target instanceof EntityLiving && ((EntityLivingBase)target).isPotionActive(Wizardry.mindControl)){
// Tests whether the target is a creature that was mind controlled by an ally of the attacker
NBTTagCompound entityNBT = target.getEntityData();
if(entityNBT != null && entityNBT.hasKey(MindControl.NBT_KEY)){
Entity controller = WizardryUtilities.getEntityByUUID(target.worldObj, UUID.fromString(entityNBT.getString(MindControl.NBT_KEY)));
if(controller instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer)attacker).isPlayerAlly((EntityPlayer)controller)){
return false;
}
}
}
}
return true;
}
/** Helper method for testing if the second player is an ally of the first player. Makes the code neater. */
public static boolean isPlayerAlly(EntityPlayer allyOf, EntityPlayer possibleAlly) {
ExtendedPlayer properties = ExtendedPlayer.get(allyOf);
if(properties != null && properties.isPlayerAlly(possibleAlly)) return true;
return false;
}
/**
* See {@link WizardryUtilities#getStandardWeightedRandomSpellId(Random, boolean)}. isContinuous defaults to false.
*/
public static int getStandardWeightedRandomSpellId(Random random){
return getStandardWeightedRandomSpellId(random, false);
}
/**
* Helper method which gets a spell id according to the standard weighting. The tier is a weighted random value;
* the actual spell within that tier is completely random. Will not return the id of a spell which has been
* disabled in the config. This is for simple stuff like chests and drops; more complex generators like wizard
* trades don't use this method.
* <p>
* For reference, the standard weighting is as follows:
* Basic: 60%, Apprentice: 25%, Advanced: 10%, Master: 5%
*
* @param random An instance of the Random class
* @param nonContinuous Whether the spells must be non-continuous (used for scrolls)
* @return A random spell id number
*/
public static int getStandardWeightedRandomSpellId(Random random, boolean nonContinuous){
int randomiser = random.nextInt(20);
EnumTier tier;
if(randomiser < 12){
tier = EnumTier.BASIC;
}else if(randomiser < 17){
tier = EnumTier.APPRENTICE;
}else if(randomiser < 19){
tier = EnumTier.ADVANCED;
}else{
tier = EnumTier.MASTER;
}
List<Spell> spells = Spell.getSpells(new Spell.TierElementFilter(tier, null));
if(nonContinuous) spells.retainAll(Spell.getSpells(Spell.nonContinuousSpells));
// Ensures the tier chosen actually has spells in it, and if not uses BASIC instead. BASIC always has at least
// the NONE spell since this spell cannot be disabled.
if(spells.isEmpty()){
spells = Spell.getSpells(new Spell.TierElementFilter(EnumTier.BASIC, null));
if(nonContinuous) spells.retainAll(Spell.getSpells(Spell.nonContinuousSpells));
}
// Finds a random spell in the list and returns its id.
return spells.get(random.nextInt(spells.size())).id();
}
/**
* Helper method to return the appropriate armour item based on element and slot.
* Currently used to iterate through armour for registering charging recipes and for chest generation.
* @param slot 0 = head, 1 = body, 2 = legs, 3 = feet
*/
public static Item getArmour(EnumElement element, int slot){
Item armour = null;
if(element == null){
switch(slot){
case 0:
armour = Wizardry.wizardHat;
break;
case 1:
armour = Wizardry.wizardRobe;
break;
case 2:
armour = Wizardry.wizardLeggings;
break;
case 3:
armour = Wizardry.wizardBoots;
break;
default:
break;
}
}else{
switch(element){
case FIRE:
switch(slot){
case 0:
armour = Wizardry.wizardHatFire;
break;
case 1:
armour = Wizardry.wizardRobeFire;
break;
case 2:
armour = Wizardry.wizardLeggingsFire;
break;
case 3:
armour = Wizardry.wizardBootsFire;
break;
default:
break;
}
break;
case HEALING:
switch(slot){
case 0:
armour = Wizardry.wizardHatHealing;
break;
case 1:
armour = Wizardry.wizardRobeHealing;
break;
case 2:
armour = Wizardry.wizardLeggingsHealing;
break;
case 3:
armour = Wizardry.wizardBootsHealing;
break;
default:
break;
}
break;
case ICE:
switch(slot){
case 0:
armour = Wizardry.wizardHatIce;
break;
case 1:
armour = Wizardry.wizardRobeIce;
break;
case 2:
armour = Wizardry.wizardLeggingsIce;
break;
case 3:
armour = Wizardry.wizardBootsIce;
break;
default:
break;
}
break;
case LIGHTNING:
switch(slot){
case 0:
armour = Wizardry.wizardHatLightning;
break;
case 1:
armour = Wizardry.wizardRobeLightning;
break;
case 2:
armour = Wizardry.wizardLeggingsLightning;
break;
case 3:
armour = Wizardry.wizardBootsLightning;
break;
default:
break;
}
break;
case NECROMANCY:
switch(slot){
case 0:
armour = Wizardry.wizardHatNecromancy;
break;
case 1:
armour = Wizardry.wizardRobeNecromancy;
break;
case 2:
armour = Wizardry.wizardLeggingsNecromancy;
break;
case 3:
armour = Wizardry.wizardBootsNecromancy;
break;
default:
break;
}
break;
case SORCERY:
switch(slot){
case 0:
armour = Wizardry.wizardHatSorcery;
break;
case 1:
armour = Wizardry.wizardRobeSorcery;
break;
case 2:
armour = Wizardry.wizardLeggingsSorcery;
break;
case 3:
armour = Wizardry.wizardBootsSorcery;
break;
default:
break;
}
break;
case EARTH:
switch(slot){
case 0:
armour = Wizardry.wizardHatEarth;
break;
case 1:
armour = Wizardry.wizardRobeEarth;
break;
case 2:
armour = Wizardry.wizardLeggingsEarth;
break;
case 3:
armour = Wizardry.wizardBootsEarth;
break;
default:
break;
}
break;
default:
switch(slot){
case 0:
armour = Wizardry.wizardHat;
break;
case 1:
armour = Wizardry.wizardRobe;
break;
case 2:
armour = Wizardry.wizardLeggings;
break;
case 3:
armour = Wizardry.wizardBoots;
break;
default:
break;
}
break;
}
}
return armour;
}
/**
* Helper method to return the appropriate wand based on tier and element.
* Currently used in the packet handler for upgrading wands, for chest generation and to iterate through
* wands for charging recipes.
*/
public static Item getWand(EnumTier tier, EnumElement element){
Item wand = null;
if(element == null){
switch(tier){
case BASIC:
wand = Wizardry.magicWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeWand;
break;
case ADVANCED:
wand = Wizardry.advancedWand;
break;
case MASTER:
wand = Wizardry.masterWand;
break;
default:
break;
}
}else{
switch(element){
case FIRE:
switch(tier){
case BASIC:
wand = Wizardry.basicFireWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeFireWand;
break;
case ADVANCED:
wand = Wizardry.advancedFireWand;
break;
case MASTER:
wand = Wizardry.masterFireWand;
break;
default:
break;
}
break;
case HEALING:
switch(tier){
case BASIC:
wand = Wizardry.basicHealingWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeHealingWand;
break;
case ADVANCED:
wand = Wizardry.advancedHealingWand;
break;
case MASTER:
wand = Wizardry.masterHealingWand;
break;
default:
break;
}
break;
case ICE:
switch(tier){
case BASIC:
wand = Wizardry.basicIceWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeIceWand;
break;
case ADVANCED:
wand = Wizardry.advancedIceWand;
break;
case MASTER:
wand = Wizardry.masterIceWand;
break;
default:
break;
}
break;
case LIGHTNING:
switch(tier){
case BASIC:
wand = Wizardry.basicLightningWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeLightningWand;
break;
case ADVANCED:
wand = Wizardry.advancedLightningWand;
break;
case MASTER:
wand = Wizardry.masterLightningWand;
break;
default:
break;
}
break;
case NECROMANCY:
switch(tier){
case BASIC:
wand = Wizardry.basicNecromancyWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeNecromancyWand;
break;
case ADVANCED:
wand = Wizardry.advancedNecromancyWand;
break;
case MASTER:
wand = Wizardry.masterNecromancyWand;
break;
default:
break;
}
break;
case SORCERY:
switch(tier){
case BASIC:
wand = Wizardry.basicSorceryWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeSorceryWand;
break;
case ADVANCED:
wand = Wizardry.advancedSorceryWand;
break;
case MASTER:
wand = Wizardry.masterSorceryWand;
break;
default:
break;
}
break;
case EARTH:
switch(tier){
case BASIC:
wand = Wizardry.basicEarthWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeEarthWand;
break;
case ADVANCED:
wand = Wizardry.advancedEarthWand;
break;
case MASTER:
wand = Wizardry.masterEarthWand;
break;
default:
break;
}
break;
default:
switch(tier){
case BASIC:
wand = Wizardry.magicWand;
break;
case APPRENTICE:
wand = Wizardry.apprenticeWand;
break;
case ADVANCED:
wand = Wizardry.advancedWand;
break;
case MASTER:
wand = Wizardry.masterWand;
break;
default:
break;
}
break;
}
}
return wand;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,135 +0,0 @@
package electroblob.wizardry.advancement;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import net.minecraft.advancements.ICriterionTrigger;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.advancements.critereon.AbstractCriterionInstance;
import net.minecraft.advancements.critereon.ItemPredicate;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Advancement trigger for things done in the arcane workbench. The majority of any
* ICriterionTrigger class is just boilerplate, and this is no exception. */
public class ArcaneWorkbenchTrigger implements ICriterionTrigger<ArcaneWorkbenchTrigger.Instance> {
private final ResourceLocation id;
private final Map<PlayerAdvancements, ArcaneWorkbenchTrigger.Listeners> listeners = Maps.newHashMap();
public ArcaneWorkbenchTrigger(ResourceLocation id){
this.id = id;
}
public ResourceLocation getId(){
return this.id;
}
public void addListener(PlayerAdvancements advancements, Listener<ArcaneWorkbenchTrigger.Instance> listener){
ArcaneWorkbenchTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners == null){
listeners = new ArcaneWorkbenchTrigger.Listeners(advancements);
this.listeners.put(advancements, listeners);
}
listeners.add(listener);
}
public void removeListener(PlayerAdvancements advancements, Listener<ArcaneWorkbenchTrigger.Instance> listener){
ArcaneWorkbenchTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners != null){
listeners.remove(listener);
if(listeners.isEmpty()){
this.listeners.remove(advancements);
}
}
}
public void removeAllListeners(PlayerAdvancements advancements){
this.listeners.remove(advancements);
}
public ArcaneWorkbenchTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context){
return new ArcaneWorkbenchTrigger.Instance(this.id, ItemPredicate.deserialize(json.get("item")));
}
public void trigger(EntityPlayerMP player, ItemStack stack){
ArcaneWorkbenchTrigger.Listeners listeners = this.listeners.get(player.getAdvancements());
if(listeners != null){
listeners.trigger(stack);
}
}
public static class Instance extends AbstractCriterionInstance {
private final ItemPredicate item;
public Instance(ResourceLocation criterionIn, ItemPredicate item){
super(criterionIn);
this.item = item;
}
public boolean test(ItemStack stack){
return this.item.test(stack);
}
}
static class Listeners {
private final PlayerAdvancements playerAdvancements;
private final Set<Listener<ArcaneWorkbenchTrigger.Instance>> listeners = Sets.newHashSet();
public Listeners(PlayerAdvancements advancements){
this.playerAdvancements = advancements;
}
public boolean isEmpty(){
return this.listeners.isEmpty();
}
public void add(Listener<ArcaneWorkbenchTrigger.Instance> listener){
this.listeners.add(listener);
}
public void remove(Listener<ArcaneWorkbenchTrigger.Instance> listener){
this.listeners.remove(listener);
}
public void trigger(ItemStack stack){
List<Listener<ArcaneWorkbenchTrigger.Instance>> list = null;
for(Listener<ArcaneWorkbenchTrigger.Instance> listener : this.listeners){
if(listener.getCriterionInstance().test(stack)){
if(list == null){
list = Lists.newArrayList();
}
list.add(listener);
}
}
if(list != null){
for(Listener<ArcaneWorkbenchTrigger.Instance> listener : list){
listener.grantCriterion(this.playerAdvancements);
}
}
}
}
}
@@ -1,81 +0,0 @@
package electroblob.wizardry.advancement;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import electroblob.wizardry.Wizardry;
import net.minecraft.advancements.ICriterionInstance;
import net.minecraft.advancements.ICriterionTrigger;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.advancements.critereon.AbstractCriterionInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
/**
* This class implements a generic custom advancement trigger that can be fired from any point in
* the code. This replaces the achievement system in instances where the JSON advancement descriptions
* cannot properly capture the advancement-worthy events. Where possible, advancement conditions
* should be triggered by JSON descriptions and vanilla advancement triggers.
*
* @author 12foo
* @since 4.1.0
*/
public class CustomAdvancementTrigger implements ICriterionTrigger<CustomAdvancementTrigger.Instance> {
private final ResourceLocation id;
private final SetMultimap<PlayerAdvancements, Listener<? extends ICriterionInstance>> listeners = HashMultimap.create();
/**
* This is a dummy criterion instance that does nothing on its own (but it is bound to this
* trigger, and via listeners to the player). We later fire this manually when we want the
* advancement to happen.
*/
public static class Instance extends AbstractCriterionInstance {
public Instance(ResourceLocation triggerId) {
super(triggerId);
}
}
public CustomAdvancementTrigger(String name) {
super();
id = new ResourceLocation(Wizardry.MODID, name);
}
@Override
public ResourceLocation getId() {
return id;
}
@Override
public void addListener(PlayerAdvancements playerAdvancementsIn, Listener<Instance> listener) {
listeners.put(playerAdvancementsIn, listener);
}
@Override
public void removeListener(PlayerAdvancements playerAdvancementsIn, Listener<Instance> listener) {
listeners.remove(playerAdvancementsIn, listener);
}
@Override
public void removeAllListeners(PlayerAdvancements playerAdvancementsIn) {
listeners.removeAll(playerAdvancementsIn);
}
@Override
public Instance deserializeInstance(JsonObject json, JsonDeserializationContext context) {
// Every time a trigger with this name is deserialized from the JSON, we just return a new
// dummy criterion instance.
return new CustomAdvancementTrigger.Instance(id);
}
public void triggerFor(EntityPlayer player) {
// Fire our dummy criterion manually on all advancements of the player, thereby granting
// the ones that match it.
if (player instanceof EntityPlayerMP) {
final PlayerAdvancements advances = ((EntityPlayerMP) player).getAdvancements();
listeners.get(advances).forEach((listener) -> listener.grantCriterion(advances));
}
}
}
@@ -1,139 +0,0 @@
package electroblob.wizardry.advancement;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import electroblob.wizardry.spell.Spell;
import net.minecraft.advancements.ICriterionTrigger;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.advancements.critereon.AbstractCriterionInstance;
import net.minecraft.advancements.critereon.ItemPredicate;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Advancement trigger which is triggered when a spell is cast. The majority of any
* ICriterionTrigger class is just boilerplate, and this is no exception. */
public class SpellCastTrigger implements ICriterionTrigger<SpellCastTrigger.Instance> {
private final ResourceLocation id;
private final Map<PlayerAdvancements, SpellCastTrigger.Listeners> listeners = Maps.newHashMap();
public SpellCastTrigger(ResourceLocation id){
this.id = id;
}
public ResourceLocation getId(){
return this.id;
}
public void addListener(PlayerAdvancements advancements, Listener<SpellCastTrigger.Instance> listener){
SpellCastTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners == null){
listeners = new SpellCastTrigger.Listeners(advancements);
this.listeners.put(advancements, listeners);
}
listeners.add(listener);
}
public void removeListener(PlayerAdvancements advancements, Listener<SpellCastTrigger.Instance> listener){
SpellCastTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners != null){
listeners.remove(listener);
if(listeners.isEmpty()){
this.listeners.remove(advancements);
}
}
}
public void removeAllListeners(PlayerAdvancements advancements){
this.listeners.remove(advancements);
}
public SpellCastTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context){
return new SpellCastTrigger.Instance(this.id, SpellPredicate.deserialize(json.get("spell")),
ItemPredicate.deserialize(json.get("item")));
}
public void trigger(EntityPlayerMP player, Spell spell, ItemStack stack){
SpellCastTrigger.Listeners listeners = this.listeners.get(player.getAdvancements());
if(listeners != null){
listeners.trigger(spell, stack);
}
}
public static class Instance extends AbstractCriterionInstance {
private final SpellPredicate spell;
private final ItemPredicate item;
public Instance(ResourceLocation criterion, SpellPredicate spell, ItemPredicate item){
super(criterion);
this.spell = spell;
this.item = item;
}
public boolean test(Spell spell, ItemStack stack){
return this.spell.test(spell) && item.test(stack);
}
}
static class Listeners {
private final PlayerAdvancements playerAdvancements;
private final Set<Listener<SpellCastTrigger.Instance>> listeners = Sets.newHashSet();
public Listeners(PlayerAdvancements advancements){
this.playerAdvancements = advancements;
}
public boolean isEmpty(){
return this.listeners.isEmpty();
}
public void add(Listener<SpellCastTrigger.Instance> listener){
this.listeners.add(listener);
}
public void remove(Listener<SpellCastTrigger.Instance> listener){
this.listeners.remove(listener);
}
public void trigger(Spell spell, ItemStack stack){
List<Listener<SpellCastTrigger.Instance>> list = null;
for(Listener<SpellCastTrigger.Instance> listener : this.listeners){
if(listener.getCriterionInstance().test(spell, stack)){
if(list == null){
list = Lists.newArrayList();
}
list.add(listener);
}
}
if(list != null){
for(Listener<SpellCastTrigger.Instance> listener : list){
listener.grantCriterion(this.playerAdvancements);
}
}
}
}
}
@@ -1,143 +0,0 @@
package electroblob.wizardry.advancement;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.event.DiscoverSpellEvent;
import electroblob.wizardry.spell.Spell;
import net.minecraft.advancements.ICriterionTrigger;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.advancements.critereon.AbstractCriterionInstance;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Advancement trigger that is triggered when a spell is discovered. The majority of any
* ICriterionTrigger class is just boilerplate, and this is no exception. */
public class SpellDiscoveryTrigger implements ICriterionTrigger<SpellDiscoveryTrigger.Instance> {
private final ResourceLocation id;
private final Map<PlayerAdvancements, SpellDiscoveryTrigger.Listeners> listeners = Maps.newHashMap();
public SpellDiscoveryTrigger(ResourceLocation id){
this.id = id;
}
public ResourceLocation getId(){
return this.id;
}
public void addListener(PlayerAdvancements advancements, Listener<SpellDiscoveryTrigger.Instance> listener){
SpellDiscoveryTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners == null){
listeners = new SpellDiscoveryTrigger.Listeners(advancements);
this.listeners.put(advancements, listeners);
}
listeners.add(listener);
}
public void removeListener(PlayerAdvancements advancements, Listener<SpellDiscoveryTrigger.Instance> listener){
SpellDiscoveryTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners != null){
listeners.remove(listener);
if(listeners.isEmpty()){
this.listeners.remove(advancements);
}
}
}
public void removeAllListeners(PlayerAdvancements advancements){
this.listeners.remove(advancements);
}
public SpellDiscoveryTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context){
String s = JsonUtils.getString(json, "source");
DiscoverSpellEvent.Source source = DiscoverSpellEvent.Source.byName(s);
if(source == null) throw new JsonSyntaxException("No such spell discovery source: " + s);
return new SpellDiscoveryTrigger.Instance(this.id, SpellPredicate.deserialize(json.get("spell")), source);
}
public void trigger(EntityPlayerMP player, Spell spell, DiscoverSpellEvent.Source source){
SpellDiscoveryTrigger.Listeners listeners = this.listeners.get(player.getAdvancements());
if(listeners != null){
listeners.trigger(spell, source);
}
}
public static class Instance extends AbstractCriterionInstance {
private final SpellPredicate spell;
private final DiscoverSpellEvent.Source source;
public Instance(ResourceLocation criterion, SpellPredicate spell, DiscoverSpellEvent.Source source){
super(criterion);
this.spell = spell;
this.source = source;
}
public boolean test(Spell spell, DiscoverSpellEvent.Source source){
return this.spell.test(spell) && source == this.source;
}
}
static class Listeners {
private final PlayerAdvancements playerAdvancements;
private final Set<Listener<SpellDiscoveryTrigger.Instance>> listeners = Sets.newHashSet();
public Listeners(PlayerAdvancements advancements){
this.playerAdvancements = advancements;
}
public boolean isEmpty(){
return this.listeners.isEmpty();
}
public void add(Listener<SpellDiscoveryTrigger.Instance> listener){
this.listeners.add(listener);
}
public void remove(Listener<SpellDiscoveryTrigger.Instance> listener){
this.listeners.remove(listener);
}
public void trigger(Spell spell, DiscoverSpellEvent.Source source){
List<Listener<SpellDiscoveryTrigger.Instance>> list = null;
for(Listener<SpellDiscoveryTrigger.Instance> listener : this.listeners){
if(listener.getCriterionInstance().test(spell, source)){
if(list == null){
list = Lists.newArrayList();
}
list.add(listener);
}
}
if(list != null){
for(Listener<SpellDiscoveryTrigger.Instance> listener : list){
listener.grantCriterion(this.playerAdvancements);
}
}
}
}
}
@@ -1,117 +0,0 @@
package electroblob.wizardry.advancement;
import com.google.common.collect.Streams;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.constants.Tier;
import electroblob.wizardry.spell.Spell;
import net.minecraft.util.JsonUtils;
import javax.annotation.Nullable;
import java.util.Arrays;
/** Predicate used by advancement triggers to match spells. */
public class SpellPredicate {
public static final SpellPredicate ANY = new SpellPredicate();
private final Spell spell;
private final Tier[] tiers;
private final Element[] elements;
public SpellPredicate(){
this.spell = null;
this.tiers = Tier.values();
this.elements = Element.values();
}
public SpellPredicate(@Nullable Spell spell, Tier[] tiers, Element[] elements){
this.spell = spell;
this.tiers = tiers;
this.elements = elements;
}
public boolean test(Spell spell){
if(this.spell != null && spell != this.spell){
return false;
}else if(!Arrays.asList(this.tiers).contains(spell.getTier())){
return false;
}else if(!Arrays.asList(this.elements).contains(spell.getElement())){
return false;
}
return true;
}
public static SpellPredicate deserialize(@Nullable JsonElement element){
if(element != null && !element.isJsonNull()){
JsonObject jsonobject = JsonUtils.getJsonObject(element, "spell");
Spell spell = null;
if(jsonobject.has("spell")){
String s = JsonUtils.getString(jsonobject, "spell");
spell = Spell.get(s);
if(spell == null){
throw new JsonSyntaxException("Unknown spell id '" + s + "'");
}
}
Tier[] tiers = Tier.values();
if(jsonobject.has("tiers")){
try{
JsonArray array = JsonUtils.getJsonArray(jsonobject, "tiers");
tiers = Streams.stream(array)
.map(je -> Tier.fromName(JsonUtils.getString(je, "element of array tiers")))
.toArray(Tier[]::new);
}catch(IllegalArgumentException e){
throw new JsonSyntaxException("Incorrect spell predicate value", e);
}
}
Element[] elements = Element.values();
if(jsonobject.has("elements")){
try{
JsonArray array = JsonUtils.getJsonArray(jsonobject, "elements");
elements = Streams.stream(array)
.map(je -> Element.fromName(JsonUtils.getString(je, "element of array elements")))
.toArray(Element[]::new);
}catch(IllegalArgumentException e){
throw new JsonSyntaxException("Incorrect spell predicate value", e);
}
}
return new SpellPredicate(spell, tiers, elements);
}else{
return ANY;
}
}
public static SpellPredicate[] deserializeArray(@Nullable JsonElement element){
if(element != null && !element.isJsonNull()){
JsonArray jsonarray = JsonUtils.getJsonArray(element, "spells");
SpellPredicate[] predicates = new SpellPredicate[jsonarray.size()];
for(int i = 0; i < predicates.length; ++i){
predicates[i] = deserialize(jsonarray.get(i));
}
return predicates;
}else{
return new SpellPredicate[0];
}
}
}
@@ -1,136 +0,0 @@
package electroblob.wizardry.advancement;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import electroblob.wizardry.worldgen.WorldGenSurfaceStructure;
import net.minecraft.advancements.ICriterionTrigger;
import net.minecraft.advancements.PlayerAdvancements;
import net.minecraft.advancements.critereon.AbstractCriterionInstance;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.WorldServer;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Copied from PositionTrigger and modified to work with wizardry's structures. The majority of any
* ICriterionTrigger class is just boilerplate, and this is no exception. */
public class StructureTrigger implements ICriterionTrigger<StructureTrigger.Instance> {
private final ResourceLocation id;
private final Map<PlayerAdvancements, StructureTrigger.Listeners> listeners = Maps.newHashMap();
public StructureTrigger(ResourceLocation id){
this.id = id;
}
public ResourceLocation getId(){
return this.id;
}
public void addListener(PlayerAdvancements advancements, Listener<StructureTrigger.Instance> listener){
StructureTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners == null){
listeners = new StructureTrigger.Listeners(advancements);
this.listeners.put(advancements, listeners);
}
listeners.add(listener);
}
public void removeListener(PlayerAdvancements advancements, Listener<StructureTrigger.Instance> listener){
StructureTrigger.Listeners listeners = this.listeners.get(advancements);
if(listeners != null){
listeners.remove(listener);
if(listeners.isEmpty()){
this.listeners.remove(advancements);
}
}
}
public void removeAllListeners(PlayerAdvancements advancements){
this.listeners.remove(advancements);
}
public StructureTrigger.Instance deserializeInstance(JsonObject json, JsonDeserializationContext context){
return new StructureTrigger.Instance(this.id, JsonUtils.getString(json, "structure_type"));
}
public void trigger(EntityPlayerMP player){
StructureTrigger.Listeners listeners = this.listeners.get(player.getAdvancements());
if(listeners != null){
listeners.trigger(player.getServerWorld(), player.posX, player.posY, player.posZ);
}
}
public static class Instance extends AbstractCriterionInstance {
private final WorldGenSurfaceStructure structureType;
public Instance(ResourceLocation criterionIn, String name){
super(criterionIn);
this.structureType = WorldGenSurfaceStructure.byName(name);
}
public boolean test(WorldServer world, double x, double y, double z){
return structureType.isInsideStructure(world, x, y, z);
}
}
static class Listeners {
private final PlayerAdvancements playerAdvancements;
private final Set<Listener<StructureTrigger.Instance>> listeners = Sets.newHashSet();
public Listeners(PlayerAdvancements advancements){
this.playerAdvancements = advancements;
}
public boolean isEmpty(){
return this.listeners.isEmpty();
}
public void add(Listener<StructureTrigger.Instance> listener){
this.listeners.add(listener);
}
public void remove(Listener<StructureTrigger.Instance> listener){
this.listeners.remove(listener);
}
public void trigger(WorldServer world, double x, double y, double z){
List<Listener<StructureTrigger.Instance>> list = null;
for(Listener<StructureTrigger.Instance> listener : this.listeners){
if(listener.getCriterionInstance().test(world, x, y, z)){
if(list == null){
list = Lists.newArrayList();
}
list.add(listener);
}
}
if(list != null){
for(Listener<StructureTrigger.Instance> listener : list){
listener.grantCriterion(this.playerAdvancements);
}
}
}
}
}
@@ -1,96 +0,0 @@
package electroblob.wizardry.api;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.constants.SpellType;
import electroblob.wizardry.constants.Tier;
import electroblob.wizardry.util.SpellProperties;
import net.minecraft.util.text.Style;
import net.minecraftforge.common.util.EnumHelper;
/**
* This class contains methods similar to those in {@link EnumHelper} specific to wizardry's enum types.
*
* @author Electroblob
* @since Wizardry 4.2
*/
public final class WizardryEnumHelper {
// Make sure these are updated if the relevant constructors are updated!
// Can't we do some kind of reflection to access them and generate these arrays?
private static final Class[] TIER_ARGUMENTS = new Class[]{Integer.class, Integer.class, Integer.class, Style.class, String.class};
private static final Class[] ELEMENT_ARGUMENTS = new Class[]{Style.class, String.class, String.class};
private static final Class[] SPELL_TYPE_ARGUMENTS = new Class[]{String.class};
private static final Class[] SPELL_CONTEXT_ARGUMENTS = new Class[]{String.class};
/**
* Wrapper for the generic method {@link EnumHelper#addEnum(Class, String, Class[], Object...)} which is
* specifically for adding new tiers. Use this method in preference to the generic one in case the constructor
* parameters change for {@code Tier}.
* <p></p>
* As of version 4.2, wizardry now has partial support for externally-added tiers; you'll need to do some of the
* legwork yourself though.
*
* @param codeName The name of the enum constant in the code. This will be returned if you call toString() on the
* resulting enum constant; other than that it doesn't really make much difference.
* @param maxCharge The maximum charge for wands of this tier.
* @param upgradeLimit The maximum total number of special upgrades that can be applied to wands of this tier.
* @param weight The weight of this tier in the standard weighting.
* @param colour The colour of text associated with this tier, as a style object.
* @param name The unlocalised name of this tier, as used in translation keys.
* @return The resulting {@code Tier} enum constant.
*/
public static Tier addTier(String codeName, int maxCharge, int upgradeLimit, int weight, Style colour, String name){
return EnumHelper.addEnum(Tier.class, codeName, TIER_ARGUMENTS, maxCharge, upgradeLimit, weight, colour, name);
}
/**
* Wrapper for the generic method {@link EnumHelper#addEnum(Class, String, Class[], Object...)} which is
* specifically for adding new elements. Use this method in preference to the generic one in case the constructor
* parameters change for {@code Element}.
* <p></p>
* As of version 4.2, wizardry now has full support for externally-added elements.
*
* @param codeName The name of the enum constant in the code. This will be returned if you call toString() on the
* resulting enum constant; other than that it doesn't really make much difference.
* @param colour The colour of text associated with this element, as a style object.
* @param name The unlocalised name of this element, as used in translation keys.
* @param modID The mod ID of the mod that added this element, for icon rendering purposes.
* @return The resulting {@code Element} enum constant.
*/
// This is the only one that needs the mod ID argument because elements are the only ones that have icons
// For some reason Minecraft doesn't seem to care about the resource domain for lang files, it just pools them
public static Element addElement(String codeName, Style colour, String name, String modID){
return EnumHelper.addEnum(Element.class, codeName, ELEMENT_ARGUMENTS, colour, name, modID);
}
/**
* Wrapper for the generic method {@link EnumHelper#addEnum(Class, String, Class[], Object...)} which is
* specifically for adding new spell types. Use this method in preference to the generic one in case the constructor
* parameters change for {@code SpellType}.
* <p></p>
* As of version 4.2, wizardry now has full support for externally-added spell types.
*
* @param codeName The name of the enum constant in the code. This will be returned if you call toString() on the
* resulting enum constant; other than that it doesn't really make much difference.
* @param name The unlocalised name of this spell type, as used in translation keys.
* @return The resulting {@code SpellType} enum constant.
*/
public static SpellType addSpellType(String codeName, String name){
return EnumHelper.addEnum(SpellType.class, codeName, SPELL_TYPE_ARGUMENTS, name);
}
/**
* Wrapper for the generic method {@link EnumHelper#addEnum(Class, String, Class[], Object...)} which is
* specifically for adding new spell contexts (for use in spell property JSON files). Use this method in preference
* to the generic one in case the constructor parameters change for {@code Context}.
*
* @param codeName The name of the enum constant in the code. This will be returned if you call toString() on the
* resulting enum constant; other than that it doesn't really make much difference.
* @param name The identifier for this spell context, as used in the JSON file.
* @return The resulting {@code Context} enum constant.
*/
public static SpellProperties.Context addSpellContext(String codeName, String name){
return EnumHelper.addEnum(SpellProperties.Context.class, codeName, SPELL_CONTEXT_ARGUMENTS, name);
}
}
@@ -1,91 +1,126 @@
package electroblob.wizardry.block;
import java.util.Random;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.WizardryGuiHandler;
import electroblob.wizardry.client.GuiArcaneWorkbench;
import electroblob.wizardry.tileentity.TileEntityArcaneWorkbench;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
public class BlockArcaneWorkbench extends BlockContainer {
private static final AxisAlignedBB AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.75D, 1.0D);
public class BlockArcaneWorkbench extends BlockContainer{
public IIcon[] icons = new IIcon[6];
public BlockArcaneWorkbench(){
super(Material.ROCK);
this.setLightLevel(0.8f);
super(Material.rock);
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F);
this.setLightLevel(0.8f);
this.setCreativeTab(CreativeTabs.tabDecorations);
this.setBlockTextureName("wizardry:arcane_workbench");
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return AABB;
public void registerBlockIcons(IIconRegister par1IconRegister) {
this.icons[0] = par1IconRegister.registerIcon(this.textureName + "_bottom");
this.icons[1] = par1IconRegister.registerIcon(this.textureName + "_top");
this.icons[2] = par1IconRegister.registerIcon(this.textureName + "_side");
this.icons[3] = par1IconRegister.registerIcon(this.textureName + "_side");
this.icons[4] = par1IconRegister.registerIcon(this.textureName + "_side");
this.icons[5] = par1IconRegister.registerIcon(this.textureName + "_side");
}
@Override
public IIcon getIcon(int side, int meta) {
return this.icons[side];
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityArcaneWorkbench();
}
@Override
public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos){
return false;
}
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.MODEL;
}
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state){
return false;
}
@Override
public boolean isFullCube(IBlockState state){
return false;
}
@Override
public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState state, BlockPos pos, EnumFacing face){
return face == EnumFacing.DOWN ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED;
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState block, EntityPlayer player, EnumHand hand,
EnumFacing side, float hitX, float hitY, float hitZ){
TileEntity tileEntity = world.getTileEntity(pos);
if(tileEntity == null || player.isSneaking()){
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int metadata, float what, float these, float are) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity == null || player.isSneaking()) {
return false;
}
player.openGui(Wizardry.instance, WizardryGuiHandler.ARCANE_WORKBENCH, world, pos.getX(), pos.getY(), pos.getZ());
player.openGui(Wizardry.instance, WizardryGuiHandler.ARCANE_WORKBENCH, world, x, y, z);
return true;
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState block){
TileEntity tileentity = world.getTileEntity(pos);
public void breakBlock(World par1World, int par2, int par3, int par4, Block block, int par6)
{
Random random = new Random();
TileEntityArcaneWorkbench tileentityarcaneworkbench = (TileEntityArcaneWorkbench)par1World.getTileEntity(par2, par3, par4);
if(tileentity instanceof TileEntityArcaneWorkbench){
InventoryHelper.dropInventoryItems(world, pos, (TileEntityArcaneWorkbench)tileentity);
if (tileentityarcaneworkbench != null)
{
for (int j1 = 0; j1 < tileentityarcaneworkbench.getSizeInventory(); ++j1)
{
ItemStack itemstack = tileentityarcaneworkbench.getStackInSlot(j1);
if (itemstack != null)
{
float f = random.nextFloat() * 0.8F + 0.1F;
float f1 = random.nextFloat() * 0.8F + 0.1F;
EntityItem entityitem;
for (float f2 = random.nextFloat() * 0.8F + 0.1F; itemstack.stackSize > 0; par1World.spawnEntityInWorld(entityitem))
{
int k1 = random.nextInt(21) + 10;
if (k1 > itemstack.stackSize)
{
k1 = itemstack.stackSize;
}
itemstack.stackSize -= k1;
entityitem = new EntityItem(par1World, (double)((float)par2 + f), (double)((float)par3 + f1), (double)((float)par4 + f2), new ItemStack(itemstack.getItem(), k1, itemstack.getItemDamage()));
float f3 = 0.05F;
entityitem.motionX = (double)((float)random.nextGaussian() * f3);
entityitem.motionY = (double)((float)random.nextGaussian() * f3 + 0.2F);
entityitem.motionZ = (double)((float)random.nextGaussian() * f3);
if (itemstack.hasTagCompound())
{
entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
}
}
}
}
//par1World.func_96440_m(par2, par3, par4, block);
}
super.breakBlock(world, pos, block);
}
super.breakBlock(par1World, par2, par3, par4, block, par6);
}
}
@@ -1,76 +1,16 @@
package electroblob.wizardry.block;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.registry.WizardryTabs;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import java.util.Random;
import java.util.EnumMap;
import electroblob.wizardry.Wizardry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
public class BlockCrystal extends Block {
public static final PropertyEnum<Element> ELEMENT = PropertyEnum.create("element", Element.class);
private static final EnumMap<Element, MapColor> map_colours = new EnumMap<>(Element.class);
static {
map_colours.put(Element.MAGIC, MapColor.PINK);
map_colours.put(Element.FIRE, MapColor.ORANGE_STAINED_HARDENED_CLAY);
map_colours.put(Element.ICE, MapColor.LIGHT_BLUE);
map_colours.put(Element.LIGHTNING, MapColor.CYAN);
map_colours.put(Element.NECROMANCY, MapColor.PURPLE);
map_colours.put(Element.EARTH, MapColor.GREEN);
map_colours.put(Element.SORCERY, MapColor.LIME);
map_colours.put(Element.HEALING, MapColor.YELLOW);
}
public BlockCrystal(Material material){
public BlockCrystal(Material material) {
super(material);
this.setDefaultState(this.blockState.getBaseState().withProperty(ELEMENT, Element.MAGIC));
this.setCreativeTab(WizardryTabs.WIZARDRY);
this.setHarvestLevel("pickaxe", 2);
setHarvestLevel("pickaxe", 2);
}
@Override
public int damageDropped(IBlockState state){
return (state.getValue(ELEMENT)).ordinal();
}
@Override
public MapColor getMapColor(IBlockState state, IBlockAccess world, BlockPos pos){
return map_colours.get(state.getProperties().get(ELEMENT));
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> items){
if(this.getCreativeTab() == tab){
for(Element element : Element.values()){
items.add(new ItemStack(this, 1, element.ordinal()));
}
}
}
@Override
public IBlockState getStateFromMeta(int metadata){
return this.getDefaultState().withProperty(ELEMENT, Element.values()[metadata]);
}
@Override
public int getMetaFromState(IBlockState state){
return (state.getValue(ELEMENT)).ordinal();
}
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, ELEMENT);
}
}
@@ -1,72 +1,143 @@
package electroblob.wizardry.block;
import electroblob.wizardry.registry.WizardryBlocks;
import electroblob.wizardry.util.ParticleBuilder;
import electroblob.wizardry.util.ParticleBuilder.Type;
import net.minecraft.block.BlockBush;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.event.entity.player.BonemealEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.Random;
// Extending BlockBush allows me to remove nearly everything from this class.
@Mod.EventBusSubscriber
public class BlockCrystalFlower extends BlockBush {
import electroblob.wizardry.EnumParticleType;
import electroblob.wizardry.Wizardry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.util.ForgeDirection;
private static final AxisAlignedBB AABB = new AxisAlignedBB(0.5F - 0.2f, 0.0F, 0.5F - 0.2f, 0.5F + 0.2f,
0.2f * 3.0F, 0.5F + 0.2f);
public class BlockCrystalFlower extends Block implements IPlantable {
public BlockCrystalFlower(Material par2Material){
public BlockCrystalFlower(Material par2Material) {
super(par2Material);
this.setLightLevel(0.5f);
this.setTickRandomly(true);
this.setSoundType(SoundType.PLANT);
this.setBlockBounds(0.5F - 0.2f, 0.0F, 0.5F - 0.2f, 0.5F + 0.2f, 0.2f * 3.0F, 0.5F + 0.2f);
this.setTickRandomly(true);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return AABB;
}
@Override
public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random random){
public void randomDisplayTick(World world, int x, int y, int z, Random random){
if(world.isRemote && random.nextBoolean()){
ParticleBuilder.create(Type.SPARKLE)
.pos(pos.getX() + random.nextDouble(), pos.getY() + random.nextDouble() / 2 + 0.5, pos.getZ() + random.nextDouble()).vel(0, 0.01, 0)
.time(20 + random.nextInt(10)).clr(0.5f + (random.nextFloat() / 2), 0.5f + (random.nextFloat() / 2),
0.5f + (random.nextFloat() / 2)).spawn(world);
Wizardry.proxy.spawnParticle(EnumParticleType.SPARKLE, world, x+random.nextDouble(), y+random.nextDouble()/2+0.5, z+random.nextDouble(), 0d, 0.01, 0d, 20 + random.nextInt(10), 0.5f + (random.nextFloat()/2), 0.5f + (random.nextFloat()/2), 0.5f + (random.nextFloat()/2));
}
}
/**
* Checks to see if its valid to put this block at the specified coordinates. Args: world, x, y, z
*/
@Override
public boolean canPlaceBlockAt(World par1World, int par2, int par3, int par4)
{
return super.canPlaceBlockAt(par1World, par2, par3, par4) && canBlockStay(par1World, par2, par3, par4);
}
/**
* Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been
* cleared to be reused)
*/
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
{
return null;
}
/**
* Gets passed in the blockID of the block below and supposed to return true if its allowed to grow on the type of
* blockID passed in. Args: blockID
*/
protected boolean canThisPlantGrowOnThisBlockID(Block par1)
{
return par1 == Blocks.grass || par1 == Blocks.dirt || par1 == Blocks.farmland;
}
/**
* Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are
* their own) Args: x, y, z, neighbor blockID
*/
@Override
public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, Block par5)
{
super.onNeighborBlockChange(par1World, par2, par3, par4, par5);
this.checkFlowerChange(par1World, par2, par3, par4);
}
/**
* Ticks the block if it's been scheduled
*/
@Override
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
this.checkFlowerChange(par1World, par2, par3, par4);
}
protected final void checkFlowerChange(World par1World, int par2, int par3, int par4)
{
if (!this.canBlockStay(par1World, par2, par3, par4))
{
this.dropBlockAsItem(par1World, par2, par3, par4, par1World.getBlockMetadata(par2, par3, par4), 0);
par1World.setBlock(par2, par3, par4, Blocks.air, 0, 2);
}
}
/**
* Can this block stay at this position. Similar to canPlaceBlockAt except gets checked often with plants.
*/
@Override
public boolean canBlockStay(World par1World, int par2, int par3, int par4)
{
Block soil = par1World.getBlock(par2, par3 - 1, par4);
return (par1World.getFullBlockLightValue(par2, par3, par4) >= 8 || par1World.canBlockSeeTheSky(par2, par3, par4)) &&
(soil != null && soil.canSustainPlant(par1World, par2, par3 - 1, par4, ForgeDirection.UP, this));
}
/**
* Is this block (a) opaque and (b) a full 1m cube? This determines whether or not to render the shared face of two
* adjacent blocks and also whether the player can attach torches, redstone wire, etc to this block.
*/
@Override
public boolean isOpaqueCube()
{
return false;
}
/**
* If this block doesn't render as an ordinary block it will return False (examples: signs, buttons, stairs, etc)
*/
@Override
public boolean renderAsNormalBlock()
{
return false;
}
/**
* The type of render function that is called for this block
*/
@Override
public int getRenderType()
{
return 1;
}
@Override
public EnumPlantType getPlantType(IBlockAccess world, BlockPos pos){
public EnumPlantType getPlantType(IBlockAccess world, int x, int y, int z) {
return EnumPlantType.Plains;
}
@SubscribeEvent
public static void onBonemealEvent(BonemealEvent event){
// Grows crystal flowers when bonemeal is used on grass
if(event.getBlock().getBlock() == Blocks.GRASS){
@Override
public Block getPlant(IBlockAccess world, int x, int y, int z) {
return this;
}
BlockPos pos = event.getPos().add(event.getWorld().rand.nextInt(8) - event.getWorld().rand.nextInt(8),
event.getWorld().rand.nextInt(4) - event.getWorld().rand.nextInt(4),
event.getWorld().rand.nextInt(8) - event.getWorld().rand.nextInt(8));
if(event.getWorld().isAirBlock(new BlockPos(pos))
&& (!event.getWorld().provider.isNether() || pos.getY() < 127)
&& WizardryBlocks.crystal_flower.canPlaceBlockAt(event.getWorld(), pos)){
event.getWorld().setBlockState(pos, WizardryBlocks.crystal_flower.getDefaultState(), 2);
}
}
@Override
public int getPlantMetadata(IBlockAccess world, int x, int y, int z) {
return 0;
}
}
@@ -1,57 +1,34 @@
package electroblob.wizardry.block;
import electroblob.wizardry.registry.WizardryItems;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.Item;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import java.util.Random;
import electroblob.wizardry.Wizardry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
public class BlockCrystalOre extends Block {
public BlockCrystalOre(Material material){
public BlockCrystalOre(Material material) {
super(material);
this.setSoundType(SoundType.STONE);
setStepSound(Block.soundTypeStone);
setBlockName("crystalOre");
setResistance(5.0F);
setHarvestLevel("pickaxe", 2);
}
@Override
public int quantityDropped(IBlockState state, int fortune, Random random){
// This now works the same way as vanilla ores
if(fortune > 0){
int i = random.nextInt(fortune + 2) - 1;
if(i < 0) i = 0;
return (random.nextInt(3) + 1) * (i + 1);
}else{
return random.nextInt(3) + 1;
}
}
@Override
public Item getItemDropped(IBlockState state, Random random, int fortune){
return WizardryItems.magic_crystal;
}
@Override
public int getExpDrop(IBlockState state, IBlockAccess world, BlockPos pos, int fortune){
Random rand = world instanceof World ? ((World)world).rand : RANDOM;
if(this.getItemDropped(state, rand, fortune) != Item.getItemFromBlock(this)){
return MathHelper.getInt(rand, 1, 4);
}
return 0;
public int quantityDropped(int meta, int fortune, Random random)
{
if(fortune > 0){
return random.nextInt(2) + 1 + random.nextInt(fortune);
}else{
return random.nextInt(2) + 1;
}
}
@Override
public Item getItemDropped(int Metadata, Random random, int fortune){
return Wizardry.magicCrystal;
}
}
@@ -1,28 +0,0 @@
package electroblob.wizardry.block;
import net.minecraft.block.BlockFrostedIce;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import java.util.Random;
/** Like {@link BlockFrostedIce}, but melting does not depend on light level or neighbouring blocks, and it just
* disappears instead of turning to water. */
public class BlockDryFrostedIce extends BlockFrostedIce {
@Override
protected void turnIntoWater(World world, BlockPos pos){
world.destroyBlock(pos, false);
}
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand){
if(rand.nextInt(3) == 0){
this.slightlyMelt(worldIn, pos, state, rand, true);
}else{
worldIn.scheduleUpdate(pos, this, MathHelper.getInt(rand, 20, 40));
}
}
}
@@ -1,92 +1,40 @@
package electroblob.wizardry.block;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.item.ItemArtefact;
import electroblob.wizardry.registry.WizardryItems;
import java.util.Random;
import electroblob.wizardry.tileentity.TileEntityMagicLight;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
public class BlockMagicLight extends Block implements ITileEntityProvider {
public class BlockMagicLight extends BlockContainer {
//private static final AxisAlignedBB AABB = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
public BlockMagicLight(Material material){
super(material);
public BlockMagicLight(Material par2Material) {
super(par2Material);
this.setLightLevel(1.0f);
this.setBlockUnbreakable();
this.setBlockBounds(0, 0, 0, 0, 0, 0);
}
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4)
{
return null;
}
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos){
// The other two bounding box methods in Block aren't nullable, so this is the
// only one that can return NULL_AABB.
return NULL_AABB;
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ){
// Let the player dispel any lights if they have the lantern charm, not just the permanent ones because that would be annoying!
if(player.getHeldItem(hand).getItem() instanceof ISpellCastingItem && ItemArtefact.isArtefactActive(player, WizardryItems.charm_light)){
world.setBlockToAir(pos);
return true;
}else{
return super.onBlockActivated(world, pos, state, player, hand, facing, hitX, hitY, hitZ);
}
}
// @Override
// public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
// return AABB;
// }
@Override
public boolean isCollidable(){
// This method has nothing to do with entity movement, it's just for raytracing
return true;
}
@Override
public boolean addDestroyEffects(World world, BlockPos pos, net.minecraft.client.particle.ParticleManager manager){
if(world.getBlockState(pos).getBlock() == this) return true; // No break particles!
else return super.addDestroyEffects(world, pos, manager);
}
@Override
public boolean hasTileEntity(IBlockState state){
return true;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityMagicLight(600);
}
@Override
public boolean isOpaqueCube(IBlockState state){
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public boolean isOpaqueCube(){
return false;
}
@Override
public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos){
return false;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.ENTITYBLOCK_ANIMATED;
}
}
@@ -1,116 +0,0 @@
package electroblob.wizardry.block;
import net.minecraft.block.Block;
import net.minecraft.block.BlockObsidian;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import java.util.Random;
/** Like {@link net.minecraft.block.BlockFrostedIce}, but for lava instead of water. */
// This is mostly copied from that class, with a few changes
public class BlockObsidianCrust extends BlockObsidian {
public static final PropertyInteger AGE = PropertyInteger.create("age", 0, 3);
public BlockObsidianCrust(){
this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, 0));
}
@Override
public int getMetaFromState(IBlockState state){
return state.getValue(AGE);
}
@Override
public IBlockState getStateFromMeta(int meta){
return this.getDefaultState().withProperty(AGE, MathHelper.clamp(meta, 0, 3));
}
@Override
public void updateTick(World world, BlockPos pos, IBlockState state, Random random){
if((random.nextInt(3) == 0 || this.countNeighbors(world, pos) < 4) && world.getLightFromNeighbors(pos) > 11 - state.getValue(AGE) - state.getLightOpacity()){
this.slightlyMelt(world, pos, state, random, true);
}else{
world.scheduleUpdate(pos, this, MathHelper.getInt(random, 20, 40));
}
}
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block block, BlockPos fromPos){
if(block == this){
int i = this.countNeighbors(world, pos);
if(i < 2){
this.melt(world, pos);
}
}
}
private int countNeighbors(World world, BlockPos pos){
int i = 0;
for(EnumFacing enumfacing : EnumFacing.values()){
if(world.getBlockState(pos.offset(enumfacing)).getBlock() == this){
++i;
if(i >= 4){
return i;
}
}
}
return i;
}
protected void slightlyMelt(World world, BlockPos pos, IBlockState state, Random random, boolean meltNeighbours){
int i = state.getValue(AGE);
if(i < 3){
world.setBlockState(pos, state.withProperty(AGE, i + 1), 2);
world.scheduleUpdate(pos, this, MathHelper.getInt(random, 20, 40));
}else{
this.melt(world, pos);
if(meltNeighbours){
for(EnumFacing enumfacing : EnumFacing.values()){
BlockPos blockpos = pos.offset(enumfacing);
IBlockState iblockstate = world.getBlockState(blockpos);
if(iblockstate.getBlock() == this){
this.slightlyMelt(world, blockpos, iblockstate, random, false);
}
}
}
}
}
protected void melt(World world, BlockPos pos){
world.setBlockState(pos, Blocks.LAVA.getDefaultState());
world.neighborChanged(pos, Blocks.LAVA, pos);
}
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, AGE);
}
@Override
public ItemStack getItem(World world, BlockPos pos, IBlockState state){
return ItemStack.EMPTY;
}
}
@@ -1,123 +0,0 @@
package electroblob.wizardry.block;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.registry.WizardryTabs;
import electroblob.wizardry.tileentity.TileEntityShrineCore;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.EnumMap;
public class BlockPedestal extends Block implements ITileEntityProvider {
public static final PropertyEnum<Element> ELEMENT = PropertyEnum.create("element", Element.class,
Arrays.copyOfRange(Element.values(), 1, Element.values().length)); // Everything except MAGIC
// A 'natural' pedestal is one that was generated as part of a structure, is unbreakable and has a tileentity
public static final PropertyBool NATURAL = PropertyBool.create("natural");
private static final EnumMap<Element, MapColor> map_colours = new EnumMap<>(Element.class);
static {
map_colours.put(Element.FIRE, MapColor.RED_STAINED_HARDENED_CLAY);
map_colours.put(Element.ICE, MapColor.LIGHT_BLUE_STAINED_HARDENED_CLAY);
map_colours.put(Element.LIGHTNING, MapColor.CYAN_STAINED_HARDENED_CLAY);
map_colours.put(Element.NECROMANCY, MapColor.PURPLE_STAINED_HARDENED_CLAY);
map_colours.put(Element.EARTH, MapColor.BROWN_STAINED_HARDENED_CLAY);
map_colours.put(Element.SORCERY, MapColor.GRAY);
map_colours.put(Element.HEALING, MapColor.YELLOW_STAINED_HARDENED_CLAY);
}
public BlockPedestal(Material material){
super(material);
this.setDefaultState(this.blockState.getBaseState().withProperty(ELEMENT, Element.FIRE).withProperty(NATURAL, false));
this.setCreativeTab(WizardryTabs.WIZARDRY);
this.setHardness(1.5F);
this.setResistance(10.0F);
}
@Override
public int damageDropped(IBlockState state){
return state.getValue(ELEMENT).ordinal(); // Ignore the NATURAL state here, it's unobtainable
}
@Override
public MapColor getMapColor(IBlockState state, IBlockAccess world, BlockPos pos){
return map_colours.get(state.getProperties().get(ELEMENT));
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> items){
// Ignore the NATURAL state here, it's unobtainable
if(this.getCreativeTab() == tab){
for(Element element : Arrays.copyOfRange(Element.values(), 1, Element.values().length)){
items.add(new ItemStack(this, 1, element.ordinal()));
}
}
}
@Override
public BlockRenderLayer getRenderLayer(){
return BlockRenderLayer.CUTOUT; // Required to shade parts of the block faces differently to others
}
@Override
public float getBlockHardness(IBlockState state, World world, BlockPos pos){
return state.getValue(NATURAL) ? -1 : super.getBlockHardness(state, world, pos);
}
@Override
public float getExplosionResistance(World world, BlockPos pos, @Nullable Entity exploder, Explosion explosion){
return world.getBlockState(pos).getValue(NATURAL) ? 6000000.0F : super.getExplosionResistance(world, pos, exploder, explosion);
}
@Override
public boolean hasTileEntity(IBlockState state){
return state.getValue(NATURAL); // Only naturally-generated pedestals have a (shrine core) tile entity
}
@Nullable
@Override
public TileEntity createNewTileEntity(World world, int meta){
return new TileEntityShrineCore();
}
@Override
public IBlockState getStateFromMeta(int metadata){
boolean natural = false;
if(metadata > ELEMENT.getAllowedValues().size()){
natural = true;
metadata -= ELEMENT.getAllowedValues().size();
}
return this.getDefaultState().withProperty(ELEMENT, Element.values()[metadata]).withProperty(NATURAL, natural);
}
@Override
public int getMetaFromState(IBlockState state){
return state.getValue(ELEMENT).ordinal() + (state.getValue(NATURAL) ? ELEMENT.getAllowedValues().size() : 0);
}
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, ELEMENT, NATURAL);
}
}
@@ -1,85 +0,0 @@
package electroblob.wizardry.block;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.registry.WizardryTabs;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import java.util.Arrays;
import java.util.EnumMap;
public class BlockRunestone extends Block {
public static final PropertyEnum<Element> ELEMENT = PropertyEnum.create("element", Element.class,
Arrays.copyOfRange(Element.values(), 1, Element.values().length)); // Everything except MAGIC
private static final EnumMap<Element, MapColor> map_colours = new EnumMap<>(Element.class);
static {
map_colours.put(Element.FIRE, MapColor.RED_STAINED_HARDENED_CLAY);
map_colours.put(Element.ICE, MapColor.LIGHT_BLUE_STAINED_HARDENED_CLAY);
map_colours.put(Element.LIGHTNING, MapColor.CYAN_STAINED_HARDENED_CLAY);
map_colours.put(Element.NECROMANCY, MapColor.PURPLE_STAINED_HARDENED_CLAY);
map_colours.put(Element.EARTH, MapColor.BROWN_STAINED_HARDENED_CLAY);
map_colours.put(Element.SORCERY, MapColor.GRAY);
map_colours.put(Element.HEALING, MapColor.YELLOW_STAINED_HARDENED_CLAY);
}
public BlockRunestone(Material material){
super(material);
this.setDefaultState(this.blockState.getBaseState().withProperty(ELEMENT, Element.FIRE));
this.setCreativeTab(WizardryTabs.WIZARDRY);
this.setHardness(1.5F);
this.setResistance(10.0F);
}
@Override
public int damageDropped(IBlockState state){
return state.getValue(ELEMENT).ordinal();
}
@Override
public MapColor getMapColor(IBlockState state, IBlockAccess world, BlockPos pos){
return map_colours.get(state.getProperties().get(ELEMENT));
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> items){
if(this.getCreativeTab() == tab){
for(Element element : Arrays.copyOfRange(Element.values(), 1, Element.values().length)){
items.add(new ItemStack(this, 1, element.ordinal()));
}
}
}
@Override
public BlockRenderLayer getRenderLayer(){
return BlockRenderLayer.CUTOUT; // Required to shade parts of the block faces differently to others
}
@Override
public IBlockState getStateFromMeta(int metadata){
return this.getDefaultState().withProperty(ELEMENT, Element.values()[metadata]);
}
@Override
public int getMetaFromState(IBlockState state){
return state.getValue(ELEMENT).ordinal();
}
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, ELEMENT);
}
}
@@ -1,116 +1,90 @@
package electroblob.wizardry.block;
import electroblob.wizardry.registry.Spells;
import electroblob.wizardry.spell.Spell;
import electroblob.wizardry.tileentity.TileEntityPlayerSave;
import electroblob.wizardry.util.AllyDesignationSystem;
import electroblob.wizardry.util.MagicDamage;
import electroblob.wizardry.util.MagicDamage.DamageType;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.MobEffects;
import net.minecraft.item.Item;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import java.util.Random;
public class BlockSnare extends Block implements ITileEntityProvider {
import electroblob.wizardry.EnumElement;
import electroblob.wizardry.MagicDamage;
import electroblob.wizardry.MagicDamage.DamageType;
import electroblob.wizardry.WizardryUtilities;
import electroblob.wizardry.tileentity.TileEntityPlayerSave;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
private static final AxisAlignedBB AABB = new AxisAlignedBB(0.0f, 0.0f, 0.0f, 1.0f, 0.0625f, 1.0f);
public class BlockSnare extends BlockContainer {
public BlockSnare(Material material){
super(material);
this.setSoundType(SoundType.PLANT);
public BlockSnare(Material par2Material){
super(par2Material);
this.setBlockBounds(0.0f, 0.0f, 0.0f, 1.0f, 0.0625f, 1.0f);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return AABB;
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4){
return null;
}
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos){
return NULL_AABB;
}
@Override
public boolean hasTileEntity(IBlockState state){
public boolean hasTileEntity(int metadata){
return true;
}
@Override
public void onEntityCollision(World world, BlockPos pos, IBlockState state, Entity entity){
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity){
if(!world.isRemote && entity instanceof EntityLivingBase){
if(world.getTileEntity(pos) instanceof TileEntityPlayerSave){
TileEntityPlayerSave tileentity = (TileEntityPlayerSave)world.getTileEntity(pos);
if(AllyDesignationSystem.isValidTarget(tileentity.getCaster(), entity)){
entity.attackEntityFrom(MagicDamage.causeDirectMagicDamage(tileentity.getCaster(), DamageType.MAGIC),
Spells.snare.getProperty(Spell.DAMAGE).floatValue());
((EntityLivingBase)entity).addPotionEffect(new PotionEffect(MobEffects.SLOWNESS,
Spells.snare.getProperty(Spell.EFFECT_DURATION).intValue(),
Spells.snare.getProperty(Spell.EFFECT_STRENGTH).intValue()));
world.destroyBlock(pos, false);
if(world.getTileEntity(x, y, z) instanceof TileEntityPlayerSave){
TileEntityPlayerSave tileentity = (TileEntityPlayerSave)world.getTileEntity(x, y, z);
if(WizardryUtilities.isValidTarget(tileentity.getCaster(), entity)){
((EntityLivingBase)entity).attackEntityFrom(MagicDamage.causeDirectMagicDamage(tileentity.getCaster(), DamageType.MAGIC), 6);
((EntityLivingBase)entity).addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 100, 2));
world.func_147480_a(x, y, z, false);
}
}
}
}
// The similarly named onNeighborChange method does NOT do the same thing.
@SuppressWarnings("deprecation")
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block block, BlockPos fromPos){
super.neighborChanged(state, world, pos, block, fromPos);
if(!world.isSideSolid(pos.down(), EnumFacing.UP, false)){
world.setBlockToAir(pos);
}
public void onNeighborBlockChange(World world, int x, int y, int z, Block block)
{
super.onNeighborBlockChange(world, x, y, z, block);
if(!world.isSideSolid(x, y-1, z, ForgeDirection.UP)){
world.setBlockToAir(x, y, z);
}
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public int getRenderType(){
return 23;
}
@Override
public BlockRenderLayer getRenderLayer() {
return BlockRenderLayer.CUTOUT;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.MODEL;
}
@Override
public boolean isOpaqueCube(IBlockState state){
return false;
}
@Override
public boolean isFullCube(IBlockState state){
return false;
}
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune){
public Item getItemDropped(int a, Random random, int b){
return null;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityPlayerSave();
}
@@ -1,112 +1,74 @@
package electroblob.wizardry.block;
import electroblob.wizardry.registry.WizardryBlocks;
import electroblob.wizardry.tileentity.TileEntityTimer;
import electroblob.wizardry.util.ParticleBuilder;
import electroblob.wizardry.util.ParticleBuilder.Type;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Random;
@Mod.EventBusSubscriber
public class BlockSpectral extends Block implements ITileEntityProvider {
import electroblob.wizardry.EnumParticleType;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.tileentity.TileEntityTimer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public BlockSpectral(Material material){
// For future reference - extend BlockContainer whenever possible because it has methods for removing tile entities on block break.
public class BlockSpectral extends BlockContainer {
public BlockSpectral(Material material) {
super(material);
this.setSoundType(SoundType.GLASS);
}
// Replaces getRenderBlockPass
@Override
public BlockRenderLayer getRenderLayer(){
return BlockRenderLayer.TRANSLUCENT;
}
public int getRenderBlockPass()
{
return 1;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.MODEL;
}
// Apparently it's OK to override this, despite it being deprecated. More importantly, it being deprecated is not
// Forge's doing, rather it is Mojang themselves misusing the @Deprecated annotation to mean 'internal, don't call'.
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state){
return false;
}
public boolean shouldSideBeRendered(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5)
{
Block block = par1IBlockAccess.getBlock(par2, par3, par4);
return block == this ? false : super.shouldSideBeRendered(par1IBlockAccess, par2, par3, par4, par5);
}
@Override
public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos){
return false;
}
public void randomDisplayTick(World world, int x, int y, int z, Random random){
// Middle of block
Wizardry.proxy.spawnParticle(EnumParticleType.DUST, world, x+random.nextDouble(), y+random.nextDouble(), z+random.nextDouble(), 0, 0, 0, (int)(16.0D / (Math.random() * 0.8D + 0.2D)),
0.4f + random.nextFloat()*0.2f, 0.6f + random.nextFloat()*0.4f, 0.6f + random.nextFloat()*0.4f);
// Top surface
Wizardry.proxy.spawnParticle(EnumParticleType.DUST, world, x+random.nextDouble(), y+1, z+random.nextDouble(), 0, 0, 0, (int)(16.0D / (Math.random() * 0.8D + 0.2D)),
0.4f + random.nextFloat()*0.2f, 0.6f + random.nextFloat()*0.4f, 0.6f + random.nextFloat()*0.4f);
Wizardry.proxy.spawnParticle(EnumParticleType.DUST, world, x+random.nextDouble(), y+1, z+random.nextDouble(), 0, 0, 0, (int)(16.0D / (Math.random() * 0.8D + 0.2D)),
0.4f + random.nextFloat()*0.2f, 0.6f + random.nextFloat()*0.4f, 0.6f + random.nextFloat()*0.4f);
}
// Overriden to make the block always look full brightness despite not emitting full light.
@Override
public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random random){
for(int i=0; i<2; i++){
ParticleBuilder.create(Type.DUST)
.pos(pos.getX() + random.nextDouble(), pos.getY() + random.nextDouble(), pos.getZ() + random.nextDouble())
.time((int)(16.0D / (Math.random() * 0.8D + 0.2D)))
.clr(0.4f + random.nextFloat() * 0.2f, 0.6f + random.nextFloat() * 0.4f, 0.6f + random.nextFloat() * 0.4f)
.shaded(true).spawn(world);
}
}
// Overriden to make the block always look full brightness despite not emitting
// full light.
@Override
public int getPackedLightmapCoords(IBlockState state, IBlockAccess source, BlockPos pos){
return 15;
}
@Override
public boolean hasTileEntity(IBlockState state){
return true;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
public int getMixedBrightnessForBlock(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
return 15;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityTimer(1200);
}
@Override
public int quantityDropped(Random par1Random){
return 0;
}
@SuppressWarnings("deprecation")
@SideOnly(Side.CLIENT)
@Override
public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos,
EnumFacing side){
IBlockState iblockstate = blockAccess.getBlockState(pos.offset(side));
Block block = iblockstate.getBlock();
return block == this ? false : super.shouldSideBeRendered(blockState, blockAccess, pos, side);
}
@SubscribeEvent
public static void onBlockPlaceEvent(BlockEvent.PlaceEvent event){
// Spectral blocks cannot be built on
if(event.getPlacedAgainst() == WizardryBlocks.spectral_block){
event.setCanceled(true);
}
}
/**
* Returns the quantity of items to drop on block destruction.
*/
@Override
public int quantityDropped(Random par1Random)
{
return 0;
}
}
@@ -1,260 +1,172 @@
package electroblob.wizardry.block;
import electroblob.wizardry.tileentity.TileEntityStatue;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLiving;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Random;
public class BlockStatue extends Block implements ITileEntityProvider {
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import electroblob.wizardry.tileentity.TileEntityStatue;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Facing;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockStatue extends BlockContainer {
private boolean isIce;
/** The NBT tag name for storing the petrified flag (used for rendering) in the target's tag compound. */
public static final String PETRIFIED_NBT_KEY = "petrified";
/** The NBT tag name for storing the frozen flag (used for rendering) in the target's tag compound. */
public static final String FROZEN_NBT_KEY = "frozen";
public BlockStatue(Material material){
super(material);
this.isIce = material == Material.ICE;
public BlockStatue(Material par2Material) {
super(par2Material);
this.isIce = par2Material == Material.ice;
if(this.isIce){
this.setDefaultSlipperiness(0.98f);
this.setSoundType(SoundType.GLASS);
this.slipperiness = 0.98F;
}
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos){
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z) {
// Not a good idea to call getBlockBoundsMinX() or whatever from in here, since this method changes those!
if(!this.isIce){
if(world.getTileEntity(pos) instanceof TileEntityStatue){
if(world.getTileEntity(x, y, z) instanceof TileEntityStatue){
TileEntityStatue statue = (TileEntityStatue)world.getTileEntity(pos);
TileEntityStatue statue = (TileEntityStatue)world.getTileEntity(x, y, z);
if(statue.creature != null){
// Block bounds are set to match the width and height of the entity, clamped to within 1 block.
return new AxisAlignedBB((float)Math.max(0.5 - statue.creature.width / 2, 0), 0,
(float)Math.max(0.5 - statue.creature.width / 2, 0),
(float)Math.min(0.5 + statue.creature.width / 2, 1),
// This checks if the block is the top one and if so reduces its height so the top lines up
// with
this.setBlockBounds((float)Math.max(0.5 - statue.creature.width/2, 0), 0,
(float)Math.max(0.5 - statue.creature.width/2, 0),
(float)Math.min(0.5 + statue.creature.width/2, 1),
// This checks if the block is the top one and if so reduces its height so the top lines up with
// the top of the entity model.
statue.position == statue.parts
? (float)Math.min(statue.creature.height - statue.parts + 1, 1)
: 1,
(float)Math.min(0.5 + statue.creature.width / 2, 1));
statue.position == statue.parts ? (float)Math.min(statue.creature.height - statue.parts + 1, 1) : 1,
(float)Math.min(0.5 + statue.creature.width/2, 1));
}
}
}
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) {
if(!this.isIce){
if(world.getTileEntity(x, y, z) instanceof TileEntityStatue){
TileEntityStatue statue = (TileEntityStatue)world.getTileEntity(x, y, z);
if(statue.creature != null){
// Block bounds are set to match the width and height of the entity, clamped to within 1 block.
return AxisAlignedBB.getBoundingBox(x + Math.max(0.5 - statue.creature.width/2, 0),
y, z + Math.max(0.5 - statue.creature.width/2, 0),
x + Math.min(0.5 + statue.creature.width/2, 1),
// This checks if the block is the top one and if so reduces its height so the top lines up with
// the top of the entity model
statue.position == statue.parts ? y + (float)Math.min(statue.creature.height - statue.parts + 1, 1) : y + 1,
z + Math.min(0.5 + statue.creature.width/2, 1));
}
}
}
return FULL_BLOCK_AABB;
return super.getCollisionBoundingBoxFromPool(world, x, y, z);
}
// getCollisionBoundingBox eventually calls getBoundingBox anyway, and since I want the collision box and the block
// outline to be the same here, I've removed that getCollisionBoundingBox entirely.
// The number of these methods is quite simply ridiculous. This one seems to be for placement logic and block
// connections (fences, glass panes, etc.)...
@Override
public boolean isFullCube(IBlockState state){
return false;
}
// ...this one isn't used much but has something to do with redstone...
@Override
public boolean isBlockNormalCube(IBlockState state){
return false;
}
// ... this one is for most other game logic...
@Override
public boolean isNormalCube(IBlockState state){
return false;
}
// Forge version of the above method. I still need to override both though because vanilla uses the other one.
@Override
public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos){
return false;
}
// ... and this one is for rendering.
@Override
public boolean isOpaqueCube(IBlockState state){
public boolean renderAsNormalBlock(){
return false;
}
@Override
public BlockRenderLayer getRenderLayer(){
return this.isIce ? BlockRenderLayer.TRANSLUCENT : BlockRenderLayer.SOLID;
public boolean canRenderInPass(int pass){
return this.isIce ? super.canRenderInPass(pass) : false;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return this.isIce ? EnumBlockRenderType.MODEL : EnumBlockRenderType.ENTITYBLOCK_ANIMATED;
public boolean isOpaqueCube(){
return false;// !this.isIce;
}
@Override
public boolean hasTileEntity(IBlockState state){
return true;
public int getRenderBlockPass()
{
return this.isIce? 1 : 0;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityStatue(this.isIce);
}
/*
@Override
public int quantityDropped(Random random){
public void randomDisplayTick(World world, int x, int y, int z, Random random){
if(this.isIce){
float brightness = 0.5f + (random.nextFloat()/2);
Minecraft.getMinecraft().effectRenderer.addEffect(new EntitySparkleFX(world, x + random.nextDouble(), y + random.nextDouble(), z + random.nextDouble(), 0, 0, 0, null, brightness, brightness + 0.1f, 1.0f, true));
}
}
*/
/**
* Returns the quantity of items to drop on block destruction.
*/
@Override
public int quantityDropped(Random par1Random)
{
return 0;
}
/**
* Returns true if the given side of this block type should be rendered, if the adjacent block is at the given
* coordinates. Args: blockAccess, x, y, z, side
*/
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state){
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockAccess p_149646_1_, int p_149646_2_, int p_149646_3_, int p_149646_4_, int p_149646_5_)
{
Block block = p_149646_1_.getBlock(p_149646_2_, p_149646_3_, p_149646_4_);
if(!world.isRemote){
TileEntityStatue tileentity = (TileEntityStatue)world.getTileEntity(pos);
return block == this ? false : super.shouldSideBeRendered(p_149646_1_, p_149646_2_, p_149646_3_, p_149646_4_, p_149646_5_);
}
@Override
public void breakBlock(World par1World, int x, int y, int z, Block block, int par6)
{
if(!par1World.isRemote){
TileEntityStatue tileentity = (TileEntityStatue)par1World.getTileEntity(x, y, z);
if(tileentity != null){
if(tileentity.parts == 2){
if(tileentity.position == 2){
world.destroyBlock(pos.down(), false);
// func_147480_a is the method that causes the block to smash as if broken by a player.
// Used to be called destroyBlock. The boolean is whether the block should drop items.
par1World.func_147480_a(x, y-1, z, false);
}else{
world.destroyBlock(pos.up(), false);
par1World.func_147480_a(x, y+1, z, false);
}
}else if(tileentity.parts == 3){
if(tileentity.position == 3){
world.destroyBlock(pos.down(), false);
world.destroyBlock(pos.down(2), false);
par1World.func_147480_a(x, y-1, z, false);
par1World.func_147480_a(x, y-2, z, false);
}else if(tileentity.position == 2){
world.destroyBlock(pos.down(), false);
world.destroyBlock(pos.up(), false);
par1World.func_147480_a(x, y-1, z, false);
par1World.func_147480_a(x, y+1, z, false);
}else{
world.destroyBlock(pos.up(), false);
world.destroyBlock(pos.up(2), false);
par1World.func_147480_a(x, y+1, z, false);
par1World.func_147480_a(x, y+2, z, false);
}
}
}
// This is only when position == 1 because world.destroyBlock calls this function for the other blocks.
if(tileentity != null && tileentity.position == 1 && tileentity.creature != null){
tileentity.creature.getEntityData().removeTag(BlockStatue.PETRIFIED_NBT_KEY);
tileentity.creature.isDead = false;
world.spawnEntity(tileentity.creature);
par1World.spawnEntityInWorld(tileentity.creature);
}
}
super.breakBlock(world, pos, state);
super.breakBlock(par1World, x, y, z, block, par6);
}
@SuppressWarnings("deprecation")
@SideOnly(Side.CLIENT)
@Override
public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos,
EnumFacing side){
IBlockState iblockstate = blockAccess.getBlockState(pos.offset(side));
Block block = iblockstate.getBlock();
return this.isIce && block == this ? false : super.shouldSideBeRendered(blockState, blockAccess, pos, side);
}
/**
* Turns the given entity into a statue. The type of statue depends on the block instance this method was invoked on.
* @param entity The entity to turn into a statue.
* @param duration The time for which the entity should remain a statue. For petrified creatures, this is the minimum
* time it can stay as a statue.
* @return True if the entity was successfully turned into a statue, false if not (i.e. something was in the way).
*/
// Making this an instance method means it works equally well for both types of statue
public boolean convertToStatue(EntityLiving entity, int duration){
if(entity.deathTime > 0) return false;
BlockPos pos = new BlockPos(entity);
World world = entity.world;
entity.hurtTime = 0; // Stops the entity looking red while frozen and the resulting z-fighting
entity.extinguish();
// Short mobs such as spiders and pigs
if((entity.height < 1.2 || entity.isChild()) && WizardryUtilities.canBlockBeReplaced(world, pos)){
world.setBlockState(pos, this.getDefaultState());
if(world.getTileEntity(pos) instanceof TileEntityStatue){
((TileEntityStatue)world.getTileEntity(pos)).setCreatureAndPart(entity, 1, 1);
((TileEntityStatue)world.getTileEntity(pos)).setLifetime(duration);
}
entity.getEntityData().setBoolean(this.isIce ? FROZEN_NBT_KEY : PETRIFIED_NBT_KEY, true);
entity.setDead();
return true;
}
// Normal sized mobs like zombies and skeletons
else if(entity.height < 2.5 && WizardryUtilities.canBlockBeReplaced(world, pos)
&& WizardryUtilities.canBlockBeReplaced(world, pos.up())){
world.setBlockState(pos, this.getDefaultState());
if(world.getTileEntity(pos) instanceof TileEntityStatue){
((TileEntityStatue)world.getTileEntity(pos)).setCreatureAndPart(entity, 1, 2);
((TileEntityStatue)world.getTileEntity(pos)).setLifetime(duration);
}
world.setBlockState(pos.up(), this.getDefaultState());
if(world.getTileEntity(pos.up()) instanceof TileEntityStatue){
((TileEntityStatue)world.getTileEntity(pos.up())).setCreatureAndPart(entity, 2, 2);
}
entity.getEntityData().setBoolean(this.isIce ? FROZEN_NBT_KEY : PETRIFIED_NBT_KEY, true);
entity.setDead();
return true;
}
// Tall mobs like endermen
else if(WizardryUtilities.canBlockBeReplaced(world, pos)
&& WizardryUtilities.canBlockBeReplaced(world, pos.up())
&& WizardryUtilities.canBlockBeReplaced(world, pos.up(2))){
world.setBlockState(pos, this.getDefaultState());
if(world.getTileEntity(pos) instanceof TileEntityStatue){
((TileEntityStatue)world.getTileEntity(pos)).setCreatureAndPart(entity, 1, 3);
((TileEntityStatue)world.getTileEntity(pos)).setLifetime(duration);
}
world.setBlockState(pos.up(), this.getDefaultState());
if(world.getTileEntity(pos.up()) instanceof TileEntityStatue){
((TileEntityStatue)world.getTileEntity(pos.up())).setCreatureAndPart(entity, 2, 3);
}
world.setBlockState(pos.up(2), this.getDefaultState());
if(world.getTileEntity(pos.up(2)) instanceof TileEntityStatue){
((TileEntityStatue)world.getTileEntity(pos.up(2))).setCreatureAndPart(entity, 3, 3);
}
entity.getEntityData().setBoolean(this.isIce ? FROZEN_NBT_KEY : PETRIFIED_NBT_KEY, true);
entity.setDead();
return true;
}
return false;
}
}
@@ -1,181 +0,0 @@
package electroblob.wizardry.block;
import electroblob.wizardry.registry.Spells;
import electroblob.wizardry.registry.WizardryBlocks;
import electroblob.wizardry.spell.Spell;
import electroblob.wizardry.tileentity.TileEntityPlayerSaveTimed;
import electroblob.wizardry.util.AllyDesignationSystem;
import electroblob.wizardry.util.MagicDamage;
import net.minecraft.block.*;
import net.minecraft.block.BlockDoublePlant.EnumBlockHalf;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.Random;
@Mod.EventBusSubscriber
public class BlockThorns extends BlockBush implements ITileEntityProvider {
public static final int GROWTH_STAGES = 8;
public static final PropertyInteger AGE = PropertyInteger.create("age", 0, GROWTH_STAGES-1);
public static final PropertyEnum<EnumBlockHalf> HALF = PropertyEnum.create("half", EnumBlockHalf.class);
public BlockThorns(){
this.setDefaultState(this.blockState.getBaseState().withProperty(HALF, EnumBlockHalf.LOWER).withProperty(AGE, 7));
this.setHardness(4);
this.setSoundType(SoundType.PLANT);
this.setCreativeTab(null);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return FULL_BLOCK_AABB;
}
@Override
public IBlockState getStateFromMeta(int meta){
return this.getDefaultState().withProperty(HALF, EnumBlockHalf.values()[meta / GROWTH_STAGES]).withProperty(AGE, meta % GROWTH_STAGES);
}
@Override
public int getMetaFromState(IBlockState state){
return state.getValue(HALF).ordinal() * GROWTH_STAGES + state.getValue(AGE);
}
// @Override
// public void updateTick(World world, BlockPos pos, IBlockState state, Random rand){
//
// super.updateTick(world, pos, state, rand);
//
// // Update the state, including on the client, but don't do a block update since it's only visual
// if(state.getValue(AGE) < GROWTH_STAGES-1) world.setBlockState(pos, state.withProperty(AGE, state.getValue(AGE) + 1), 2);
// }
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, HALF, AGE);
}
public void placeAt(World world, BlockPos lowerPos, int flags){
world.setBlockState(lowerPos, this.getDefaultState().withProperty(HALF, EnumBlockHalf.LOWER).withProperty(AGE, 0), flags);
world.setBlockState(lowerPos.up(), this.getDefaultState().withProperty(HALF, EnumBlockHalf.UPPER).withProperty(AGE, 0), flags);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack){
world.setBlockState(pos.up(), this.getDefaultState().withProperty(HALF, EnumBlockHalf.UPPER), 2);
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state){
super.breakBlock(world, pos, state);
if(state.getValue(HALF) == EnumBlockHalf.LOWER){
if(world.getBlockState(pos.up()).getBlock() == this){
world.destroyBlock(pos.up(), false);
}
}else{
if(world.getBlockState(pos.down()).getBlock() == this){
world.destroyBlock(pos.down(), false);
}
}
}
public boolean canBlockStay(World worldIn, BlockPos pos, IBlockState state){
if(state.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER){
return worldIn.getBlockState(pos.down()).getBlock() == this;
}else{
IBlockState iblockstate = worldIn.getBlockState(pos.up());
return iblockstate.getBlock() == this && this.canSustainBush(worldIn.getBlockState(pos.down()));
}
}
// @Override
// public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos){
// // Copied from BlockFlowerPot on authority of the Forge docs, which says this check is necessary
// SoundLoopSpellDispenser tileentity = world instanceof ChunkCache ? ((ChunkCache)world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos);
//
// if(tileentity instanceof TileEntityPlayerSaveTimed){
// state = state.withProperty(AGE, Math.min(7, ((TileEntityPlayerSaveTimed)tileentity).timer/2));
// }else{
// state = state.withProperty(AGE, 7);
// }
//
// return state;
// }
@Override
public void onEntityCollision(World world, BlockPos pos, IBlockState state, Entity entity){
if(!world.isRemote){
if(applyThornDamage(world, pos, entity)){
entity.setInWeb();
}
}
}
private static boolean applyThornDamage(World world, BlockPos pos, Entity target){
DamageSource source = DamageSource.CACTUS;
TileEntity tileentity = world.getTileEntity(pos);
if(tileentity instanceof TileEntityPlayerSaveTimed){
if(AllyDesignationSystem.isValidTarget(((TileEntityPlayerSaveTimed)tileentity).getCaster(), target)){
source = MagicDamage.causeDirectMagicDamage(((TileEntityPlayerSaveTimed)tileentity).getCaster(),
MagicDamage.DamageType.MAGIC);
}else{
return false; // Don't attack or slow allies of the caster
}
}
if(world.getTotalWorldTime() % 20 == 0) target.attackEntityFrom(source, Spells.forest_of_thorns.getProperty(Spell.DAMAGE).floatValue());
return true;
}
@Override
public Block.EnumOffsetType getOffsetType(){
return Block.EnumOffsetType.XZ;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
return new TileEntityPlayerSaveTimed(600);
}
@Override
public boolean hasTileEntity(IBlockState state){
return true;
}
@Override public boolean isReplaceable(IBlockAccess world, BlockPos pos){ return false; }
@Override protected boolean canSustainBush(IBlockState state){ return state.isNormalCube(); }
@Override public Item getItemDropped(IBlockState state, Random rand, int fortune){ return Items.AIR; }
@Override public boolean canSilkHarvest(World world, BlockPos pos, IBlockState state, EntityPlayer player){ return false; }
@SubscribeEvent
public static void onLeftClickBlockEvent(PlayerInteractEvent.LeftClickBlock event){
if(!event.getWorld().isRemote && event.getWorld().getTotalWorldTime() % 20 == 0
&& event.getWorld().getBlockState(event.getPos()).getBlock() == WizardryBlocks.thorns){
applyThornDamage(event.getWorld(), event.getPos(), event.getEntity());
}
}
}
@@ -1,232 +1,149 @@
package electroblob.wizardry.block;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.data.WizardData;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.item.ItemArtefact;
import electroblob.wizardry.registry.Spells;
import electroblob.wizardry.registry.WizardryBlocks;
import electroblob.wizardry.registry.WizardryItems;
import electroblob.wizardry.spell.Transportation;
import electroblob.wizardry.util.Location;
import electroblob.wizardry.util.ParticleBuilder;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BlockTransportationStone extends Block {
import electroblob.wizardry.ExtendedPlayer;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.WizardryRegistry;
import electroblob.wizardry.item.ItemWand;
import electroblob.wizardry.spell.Spell;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
private static final AxisAlignedBB AABB = new AxisAlignedBB(0.0625f * 5, 0, 0.0625f * 5, 0.0625f * 11, 0.0625f * 6,
0.0625f * 11);
public class BlockTransportationStone extends Block{
public BlockTransportationStone(Material material){
super(material);
this.setTickRandomly(true);
this.setBlockBounds(0.0625f*5, 0, 0.0625f*5, 0.0625f*11, 0.0625f*6, 0.0625f*11);
this.setTickRandomly(true);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return AABB;
}
// The number of these methods is quite simply ridiculous. This one seems to be for placement logic and block
// connections (fences, glass panes, etc.)...
@Override
public boolean isFullCube(IBlockState state){
return false;
}
// ...this one isn't used much but has something to do with redstone...
@Override
public boolean isBlockNormalCube(IBlockState state){
return false;
}
// ... this one is for most other game logic...
@Override
public boolean isNormalCube(IBlockState state){
return false;
}
// Forge version of the above method. I still need to override both though because vanilla uses the other one.
@Override
public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos){
return false;
}
// ... and this one is for rendering.
@Override
public boolean isOpaqueCube(IBlockState state){
public boolean isOpaqueCube(){
return false;
}
@Override
public boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side){
return side == EnumFacing.DOWN;
public boolean renderAsNormalBlock(){
return false;
}
@SuppressWarnings("deprecation")
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block block, BlockPos fromPos){
super.neighborChanged(state, world, pos, block, fromPos);
if(!world.isSideSolid(pos.down(), EnumFacing.UP, false)){
this.dropBlockAsItem(world, pos, world.getBlockState(pos), 0);
world.setBlockToAir(pos);
}
}
public void onNeighborBlockChange(World world, int x, int y, int z, Block block)
{
super.onNeighborBlockChange(world, x, y, z, block);
if(!world.isSideSolid(x, y-1, z, ForgeDirection.UP)){
this.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
world.setBlockToAir(x, y, z);
}
}
@Override
public void updateTick(World world, BlockPos pos, IBlockState state, Random random){
if(!world.isSideSolid(pos.down(), EnumFacing.UP)){
this.dropBlockAsItem(world, pos, world.getBlockState(pos), 0);
world.setBlockToAir(pos);
}
}
public void updateTick(World world, int x, int y, int z, Random random)
{
if(!world.isSideSolid(x, y-1, z, ForgeDirection.UP)){
this.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
world.setBlockToAir(x, y, z);
}
}
@Override
public boolean canPlaceBlockAt(World world, BlockPos pos){
return super.canPlaceBlockAt(world, pos) && world.isSideSolid(pos.down(), EnumFacing.UP);
}
public boolean canPlaceBlockAt(World par1World, int x, int y, int z)
{
return super.canPlaceBlockAt(par1World, x, y, z) && par1World.isSideSolid(x, y-1, z, ForgeDirection.UP);
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand,
EnumFacing side, float hitX, float hitY, float hitZ){
ItemStack stack = player.getHeldItem(hand);
if(stack.getItem() instanceof ISpellCastingItem){
if(WizardData.get(player) != null){
WizardData data = WizardData.get(player);
for(int x = -1; x <= 1; x++){
for(int z = -1; z <= 1; z++){
BlockPos pos1 = pos.add(x, 0, z);
if(testForCircle(world, pos1)){
Location here = new Location(pos1, player.dimension);
List<Location> locations = data.getVariable(Transportation.LOCATIONS_KEY);
if(locations == null) data.setVariable(Transportation.LOCATIONS_KEY, locations = new ArrayList<>(Transportation.MAX_REMEMBERED_LOCATIONS));
if(ItemArtefact.isArtefactActive(player, WizardryItems.charm_transportation)){
if(locations.contains(here)){
locations.remove(here);
if(!world.isRemote) player.sendStatusMessage(new TextComponentTranslation("tile." + Wizardry.MODID + ":transportation_stone.forget", here.pos.getX(), here.pos.getY(), here.pos.getZ(), here.dimension), true);
}else{
locations.add(here);
if(!world.isRemote) player.sendStatusMessage(new TextComponentTranslation("tile." + Wizardry.MODID + ":transportation_stone.remember", here.pos.getX(), here.pos.getY(), here.pos.getZ(), here.dimension), true);
if(locations.size() > Transportation.MAX_REMEMBERED_LOCATIONS){
Location removed = locations.remove(0);
if(!world.isRemote) player.sendStatusMessage(new TextComponentTranslation("tile." + Wizardry.MODID + ":transportation_stone.forget", removed.pos.getX(), removed.pos.getY(), removed.pos.getZ(), removed.dimension), true);
}
}
}else{
if(locations.isEmpty()) locations.add(here);
else{
locations.remove(here); // Prevents duplicates
locations.set(locations.size() - 1, here);
}
if(!world.isRemote) player.sendStatusMessage(new TextComponentTranslation("tile." + Wizardry.MODID + ":transportation_stone.confirm", Spells.transportation.getNameForTranslationFormatted()), true);
}
return true;
}
}
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int par6, float par7, float par8, float par9)
{
if(entityplayer.getHeldItem() != null && entityplayer.getHeldItem().getItem() instanceof ItemWand){
if(ExtendedPlayer.get(entityplayer) != null){
ExtendedPlayer extendedplayer = ExtendedPlayer.get(entityplayer);
int x1=x-1, z1=z-1;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
if(!world.isRemote){
player.sendStatusMessage(new TextComponentTranslation("tile." + Wizardry.MODID + ":transportation_stone.invalid"), true);
}else{
BlockPos centre = findMostLikelyCircle(world, pos);
// Displays particles in the required shape
for(int x = -1; x <= 1; x++){
for(int z = -1; z <= 1; z++){
if(x == 0 && z == 0) continue;
ParticleBuilder.create(ParticleBuilder.Type.PATH)
.pos(WizardryUtilities.getCentre(centre).add(x, -0.3125, z)).clr(0x86ff65)
.time(200).scale(2).spawn(world);
}
}
x1=x;
z1=z-1;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
x1=x+1;
z1=z-1;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
x1=x-1;
z1=z;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
x1=x+1;
z1=z;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
x1=x-1;
z1=z+1;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
x1=x;
z1=z+1;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
x1=x+1;
z1=z+1;
if(testForCircle(world, x1, y, z1)){
extendedplayer.setStoneLocation(x1, y, z1, world.provider.dimensionId);
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.confirm", WizardryRegistry.transportation.getDisplayNameWithFormatting()));//"You will now be returned here upon casting " + EnumSpell.TRANSPORTATION.name);
return true;
}
if(!world.isRemote) entityplayer.addChatMessage(new ChatComponentTranslation("tile.transportationStone.invalid"));//"You must make a circle with 8 stones of transportation first!");
return true;
}
}
return false;
}
return false;
}
/** Returns whether the specified location is surrounded by a complete cicle of 8 transportation stones. */
public static boolean testForCircle(World world, BlockPos pos){
if(world.getBlockState(pos).getMaterial().blocksMovement()) return false;
for(int x = -1; x <= 1; x++){
for(int z = -1; z <= 1; z++){
if(x == 0 && z == 0) continue;
if(world.getBlockState(pos.add(x, 0, z)).getBlock() != WizardryBlocks.transportation_stone){
return false;
}
}
}
return true;
}
private static BlockPos findMostLikelyCircle(World world, BlockPos pos){
int bestSoFar = 0;
BlockPos result = null;
for(int x = -1; x <= 1; x++){
for(int z = -1; z <= 1; z++){
if(x == 0 && z == 0) continue;
BlockPos pos1 = pos.add(x, 0, z);
int n = getCircleCompleteness(world, pos1);
if(n > bestSoFar){
bestSoFar = n;
result = pos1;
}
}
}
return result;
}
private static int getCircleCompleteness(World world, BlockPos pos){
int n = 0;
for(int x = -1; x <= 1; x++){
for(int z = -1; z <= 1; z++){
if(x == 0 && z == 0) continue;
if(world.getBlockState(pos.add(x, 0, z)).getBlock() == WizardryBlocks.transportation_stone) n++;
}
}
return n;
public static boolean testForCircle(World world, int x, int y, int z){
return world.getBlock(x-1, y, z-1) == Wizardry.transportationStone
&& world.getBlock(x, y, z-1) == Wizardry.transportationStone
&& world.getBlock(x+1, y, z-1) == Wizardry.transportationStone
&& world.getBlock(x-1, y, z) == Wizardry.transportationStone
&& !world.getBlock(x, y, z).getMaterial().blocksMovement()
&& world.getBlock(x+1, y, z) == Wizardry.transportationStone
&& world.getBlock(x-1, y, z+1) == Wizardry.transportationStone
&& world.getBlock(x, y, z+1) == Wizardry.transportationStone
&& world.getBlock(x+1, y, z+1) == Wizardry.transportationStone;
}
}
@@ -1,73 +1,61 @@
package electroblob.wizardry.block;
import electroblob.wizardry.tileentity.TileEntityTimer;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Random;
public class BlockVanishingCobweb extends Block implements ITileEntityProvider {
import electroblob.wizardry.EnumParticleType;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.tileentity.TileEntityTimer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public BlockVanishingCobweb(Material material){
// For future reference - extend BlockContainer whenever possible because it has methods for removing tile entities on block break.
public class BlockVanishingCobweb extends BlockContainer {
public BlockVanishingCobweb(Material material) {
super(material);
}
@SideOnly(Side.CLIENT)
@Override
public BlockRenderLayer getRenderLayer(){
return BlockRenderLayer.CUTOUT;
}
public int getRenderType()
{
return 1;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.MODEL;
}
@Override
public boolean isOpaqueCube(IBlockState state){
return false;
}
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos){
return NULL_AABB;
}
@Override
public boolean isFullCube(IBlockState state){
return false;
}
@Override
public boolean hasTileEntity(IBlockState state){
return true;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata){
public boolean isOpaqueCube()
{
return false;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityTimer(400);
}
@Override
public void onEntityCollision(World world, BlockPos pos, IBlockState state, Entity entity){
entity.setInWeb();
}
@Override
public int quantityDropped(Random par1Random){
return 0;
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity)
{
entity.setInWeb();
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_) {
return null;
}
/**
* Returns the quantity of items to drop on block destruction.
*/
@Override
public int quantityDropped(Random par1Random)
{
return 0;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,247 +0,0 @@
package electroblob.wizardry.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.opengl.GL11;
/**
* Utility class containing some useful static methods for drawing GUIs. Previously these were spread across the main
* {@code WizardryUtilities} class and various individual GUI classes.
*
* @author Electroblob
* @since Wizardry 4.2
* @see MixedFontRenderer
*/
//@SideOnly(Side.CLIENT)
public final class DrawingUtils {
/**
* The integer colour for black passed into the font renderer methods. This used to be 0 but that's now white for
* some reason, so I've made a it a constant in case it changes again.
*/
// I think this is actually ever-so-slightly lighter than pure black, but the difference is unnoticeable.
public static final int BLACK = 1;
/**
* Shorthand for {@link DrawingUtils#drawTexturedRect(int, int, int, int, int, int, int, int)} which draws the
* entire texture (u and v are set to 0 and textureWidth and textureHeight are the same as width and height).
*/
public static void drawTexturedRect(int x, int y, int width, int height){
drawTexturedRect(x, y, 0, 0, width, height, width, height);
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into
* account, unlike {@link net.minecraft.client.gui.Gui#drawTexturedModalRect(int, int, int, int, int, int)
* Gui.drawTexturedModalRect(int, int, int, int, int, int)}, which is harcoded for only 256x256 textures. Also handy
* for custom potion icons.
*
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
*/
public static void drawTexturedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight){
DrawingUtils.drawTexturedFlippedRect(x, y, u, v, width, height, textureWidth, textureHeight, false, false);
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into
* account, unlike {@link net.minecraft.client.gui.Gui#drawTexturedModalRect(int, int, int, int, int, int)
* Gui.drawTexturedModalRect(int, int, int, int, int, int)}, which is harcoded for only 256x256 textures. Also handy
* for custom potion icons. This version allows the texture to additionally be flipped in x and/or y.
*
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
* @param flipX Whether to flip the texture in the x direction.
* @param flipY Whether to flip the texture in the y direction.
*/
public static void drawTexturedFlippedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, boolean flipX, boolean flipY){
float f = 1F / (float)textureWidth;
float f1 = 1F / (float)textureHeight;
int u1 = flipX ? u + width : u;
int u2 = flipX ? u : u + width;
int v1 = flipY ? v + height : v;
int v2 = flipY ? v : v + height;
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.begin(org.lwjgl.opengl.GL11.GL_QUADS, net.minecraft.client.renderer.vertex.DefaultVertexFormats.POSITION_TEX);
buffer.pos((double)(x), (double)(y + height), 0).tex((double)((float)(u1) * f), (double)((float)(v2) * f1)).endVertex();
buffer.pos((double)(x + width), (double)(y + height), 0).tex((double)((float)(u2) * f), (double)((float)(v2) * f1)).endVertex();
buffer.pos((double)(x + width), (double)(y), 0).tex((double)((float)(u2) * f), (double)((float)(v1) * f1)).endVertex();
buffer.pos((double)(x), (double)(y), 0).tex((double)((float)(u1) * f), (double)((float)(v1) * f1)).endVertex();
tessellator.draw();
}
/**
* Draws a textured rectangle, stretching the section of the image to fit the size given.
*
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted, expressed as a fraction of the
* image width
* @param v The y position of the top left corner of the section of the image wanted, expressed as a fraction of the
* image width
* @param finalWidth The width as rendered
* @param finalHeight The height as rendered
* @param width The width of the section, expressed as a fraction of the image width
* @param height The height of the section, expressed as a fraction of the image width
*/
public static void drawTexturedStretchedRect(int x, int y, int u, int v, int finalWidth, int finalHeight, int width,
int height){
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
buffer.pos((x), y + finalHeight, 0).tex(u, v + height).endVertex();
buffer.pos(x + finalWidth, y + finalHeight, 0).tex(u + width, v + height).endVertex();
buffer.pos(x + finalWidth, (y), 0).tex(u + width, v).endVertex();
buffer.pos((x), (y), 0).tex(u, v).endVertex();
tessellator.draw();
}
/**
* Mixes the two given opaque colours in the proportion specified.
* @param colour1 The first colour to mix, as a 6-digit hexadecimal.
* @param colour2 The second colour to mix, as a 6-digit hexadecimal.
* @param proportion The proportion of the second colour; will be clamped to between 0 and 1.
* @return The resulting colour, as a 6-digit hexadecimal.
*/
public static int mix(int colour1, int colour2, float proportion){
proportion = MathHelper.clamp(proportion, 0, 1);
int r1 = colour1 >> 16 & 255;
int g1 = colour1 >> 8 & 255;
int b1 = colour1 & 255;
int r2 = colour2 >> 16 & 255;
int g2 = colour2 >> 8 & 255;
int b2 = colour2 & 255;
int r = (int)(r1 + (r2-r1) * proportion);
int g = (int)(g1 + (g2-g1) * proportion);
int b = (int)(b1 + (b2-b1) * proportion);
return (r << 16) + (g << 8) + b;
}
/**
* Makes the given opaque colour translucent with the given opacity.
* @param colour An integer colour code, should be a 6-digit hexadecimal (i.e. opaque).
* @param opacity The opacity to apply to the given colour, as a fraction between 0 and 1.
* @return The resulting integer colour code, which will be an 8-digit hexadecimal.
*/
public static int makeTranslucent(int colour, float opacity){
return colour + ((int)(0xff * opacity * 0x01000000));
}
/**
* Draws the given string at the given position, scaling it if it does not fit within the given width.
* @param font A {@code FontRenderer} object.
* @param text The text to display.
* @param x The x position of the top-left corner of the text.
* @param y The y position of the top-left corner of the text.
* @param scale The scale that the text should normally be if it does not exceed the maximum width.
* @param colour The colour to render the text in, supports translucency.
* @param width The maximum width of the text. <i>This is not scaled; you should pass in the width of the actual
* area of the screen in which the text needs to fit, regardless of the scale parameter.</i>
* @param centre Whether to adjust the y position such that the centre of the text lines up with where its centre
* would be if it was not scaled (automatically or manually).
* @param alignR True to right-align the text, false for normal left alignment.
*/
public static void drawScaledStringToWidth(FontRenderer font, String text, float x, float y, float scale, int colour, float width, boolean centre, boolean alignR){
float textWidth = font.getStringWidth(text) * scale;
float textHeight = font.FONT_HEIGHT * scale;
if(textWidth > width){
scale *= width/textWidth;
}else if(alignR){ // Alignment makes no difference if the string fills the entire width
x += width - textWidth;
}
if(centre) y += (font.FONT_HEIGHT - textHeight)/2;
DrawingUtils.drawScaledTranslucentString(font, text, x, y, scale, colour);
}
/** Draws the given string at the given position, scaling the text by the specified factor. Also enables blending to
* render text in semitransparent colours (e.g. 0x88ffffff). */
public static void drawScaledTranslucentString(FontRenderer font, String text, float x, float y, float scale, int colour){
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.scale(scale, scale, scale);
// Because we scaled the entire rendering space, the coordinates have to be scaled inversely
x /= scale;
y /= scale;
font.drawStringWithShadow(text, x, y, colour);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
/**
* Draws an itemstack and (optionally) its tooltip, directly. Mainly intended for use outside of GUI classes, since
* most of the GL state changes done in this method (which are the main reason it exists at all) are already done
* when drawing a GUI.
*
* @param gui An instance of a GUI class.
* @param stack The itemstack to draw.
* @param x The x position of the left-hand edge of the itemstack.
* @param y The y position of the top edge of the itemstack.
* @param mouseX The x position of the mouse, used for tooltip positioning.
* @param mouseY The y position of the mouse, used for tooltip positioning.
* @param tooltip Whether to draw the tooltip.
*/
public static void drawItemAndTooltip(GuiContainer gui, ItemStack stack, int x, int y, int mouseX, int mouseY, boolean tooltip){
RenderItem renderItem = Minecraft.getMinecraft().getRenderItem();
GlStateManager.pushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GlStateManager.disableLighting();
GlStateManager.enableRescaleNormal();
GlStateManager.enableColorMaterial();
GlStateManager.enableLighting();
renderItem.zLevel = 100.0F;
if(!stack.isEmpty()){
renderItem.renderItemAndEffectIntoGUI(stack, x, y);
renderItem.renderItemOverlays(Minecraft.getMinecraft().fontRenderer, stack, x, y);
if(tooltip){
gui.drawHoveringText(gui.getItemToolTip(stack), mouseX + gui.getXSize()/2 - gui.width/2,
mouseY + gui.getYSize()/2 - gui.height/2);
}
}
GlStateManager.popMatrix();
GlStateManager.enableLighting();
GlStateManager.enableDepth();
RenderHelper.enableStandardItemLighting();
}
}
@@ -0,0 +1,77 @@
package electroblob.wizardry.client;
import cpw.mods.fml.client.config.GuiButtonExt;
import cpw.mods.fml.client.config.GuiEditArray;
import cpw.mods.fml.client.config.GuiEditArrayEntries;
import cpw.mods.fml.client.config.GuiSelectString;
import cpw.mods.fml.client.config.GuiUtils;
import cpw.mods.fml.client.config.GuiEditArrayEntries.StringEntry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.EntityList;
import cpw.mods.fml.client.config.IConfigElement;
public class EntityNameEntry extends StringEntry {
protected final GuiButtonExt btnValue;
protected Object entityClass;
public EntityNameEntry(GuiEditArray owningScreen, GuiEditArrayEntries owningEntryList, IConfigElement configElement, Object value)
{
super(owningScreen, owningEntryList, configElement, value);
this.btnValue = new GuiButtonExt(0, 0, 0, owningEntryList.controlWidth, 18, I18n.format(this.textFieldValue.getText()));
//this.btnValue.enabled = owningScreen.enabled;
}
@Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, Tessellator tessellator, int mouseX, int mouseY, boolean isSelected)
{
//super.drawEntry(slotIndex, x, y, listWidth, slotHeight, tessellator, mouseX, mouseY, isSelected);
this.btnValue.xPosition = listWidth / 4;
this.btnValue.yPosition = y;
String trans = I18n.format(this.textFieldValue.getText());
if (!trans.equals(this.textFieldValue.getText()))
this.btnValue.displayString = trans;
else
this.btnValue.displayString = this.textFieldValue.getText();
//btnValue.packedFGColour = value ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true);
this.btnValue.drawButton(owningEntryList.mc, mouseX, mouseY);
}
/**
* Returns true if the mouse has been pressed on this control.
*/
@Override
public boolean mousePressed(int index, int x, int y, int mouseEvent, int relativeX, int relativeY)
{
if (this.btnValue.mousePressed(owningEntryList.mc, x, y))
{
btnValue.func_146113_a(owningEntryList.mc.getSoundHandler());
Minecraft.getMinecraft().displayGuiScreen(new GuiSelectString(this.owningScreen, configElement, index, EntityList.classToStringMapping, this.getValue(), true));
owningEntryList.recalculateState();
return true;
}
return super.mousePressed(index, x, y, mouseEvent, relativeX, relativeY);
}
/**
* Fired when the mouse button is released. Arguments: index, x, y, mouseEvent, relativeX, relativeY
*/
@Override
public void mouseReleased(int index, int x, int y, int mouseEvent, int relativeX, int relativeY)
{
this.btnValue.mouseReleased(x, y);
super.mouseReleased(index, x, y, mouseEvent, relativeX, relativeY);
}
@Override
public Object getValue()
{
return this.textFieldValue.getText();
}
}
@@ -0,0 +1,364 @@
package electroblob.wizardry.client;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import electroblob.wizardry.ExtendedPlayer;
import electroblob.wizardry.SpellGlyphData;
import electroblob.wizardry.WandHelper;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.WizardryGuiHandler;
import electroblob.wizardry.item.ItemWand;
import electroblob.wizardry.packet.PacketControlInput;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.spell.Spell;
import electroblob.wizardry.tileentity.ContainerArcaneWorkbench;
import electroblob.wizardry.tileentity.SlotWizardry;
import electroblob.wizardry.tileentity.TileEntityArcaneWorkbench;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
public class GuiArcaneWorkbench extends GuiContainer {
private GuiButton applyBtn;
private static final ResourceLocation texture = new ResourceLocation(Wizardry.MODID, "textures/gui/arcane_workbench.png");
private IInventory playerInventory;
private IInventory arcaneWorkbenchInventory;
private final int tooltipWidth = 164;
public GuiArcaneWorkbench(InventoryPlayer invPlayer, TileEntityArcaneWorkbench entity) {
super(new ContainerArcaneWorkbench(invPlayer, entity));
this.playerInventory = invPlayer;
this.arcaneWorkbenchInventory = entity;
xSize = 176;
ySize = 220;
}
@Override
public void drawScreen(int p_73863_1_, int p_73863_2_, float p_73863_3_){
// Tests if there is a wand in the workbench and edits the positioning accordingly
if(this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getHasStack() && this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getStack().getItem() instanceof ItemWand){
guiLeft = (this.width - this.xSize - tooltipWidth)/2;
this.applyBtn.xPosition = (this.width - tooltipWidth)/2 + 48;
}else{
guiLeft = (this.width - this.xSize)/2;
this.applyBtn.xPosition = this.width/2 + 48;
}
if(this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getHasStack()){
this.applyBtn.enabled = true;
}else{
this.applyBtn.enabled = false;
}
super.drawScreen(p_73863_1_, p_73863_2_, p_73863_3_);
}
/**
* Draw the foreground layer for the GuiContainer (everything in front of the items)
*/
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY){
this.fontRendererObj.drawString(this.arcaneWorkbenchInventory.hasCustomInventoryName() ? this.arcaneWorkbenchInventory.getInventoryName() : I18n.format(this.arcaneWorkbenchInventory.getInventoryName()), 8, 6, 4210752);
this.fontRendererObj.drawString(this.playerInventory.hasCustomInventoryName() ? this.playerInventory.getInventoryName() : I18n.format(this.playerInventory.getInventoryName()), 8, this.ySize - 96 + 2, 4210752);
if(this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getHasStack() && this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getStack().getItem() instanceof ItemWand){
ItemStack wand = this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getStack();
this.fontRendererObj.drawStringWithShadow("\u00A7f" + wand.getDisplayName(), xSize + 6, 6, 0);
this.fontRendererObj.drawStringWithShadow("\u00A77" + StatCollector.translateToLocal("container.arcaneWorkbench.mana") + " " + (wand.getMaxDamage() - wand.getItemDamage()) + "/" + wand.getMaxDamage(), xSize + 6, 20, 0);
Spell[] spells = WandHelper.getSpells(wand);
int y = 34;
for(Spell spell : spells){
boolean discovered = true;
if(!this.mc.thePlayer.capabilities.isCreativeMode && ExtendedPlayer.get(this.mc.thePlayer) != null){
discovered = ExtendedPlayer.get(this.mc.thePlayer).hasSpellBeenDiscovered(spell);
}
if(discovered){
this.fontRendererObj.drawStringWithShadow(spell.getDisplayNameWithFormatting(), xSize + 16, y, 0);
}else{
this.mc.standardGalacticFontRenderer.drawStringWithShadow("\u00A79" + SpellGlyphData.getGlyphName(spell, this.mc.theWorld), xSize + 16, y, 0);
}
y += 10;
}
if(WandHelper.getTotalUpgrades(wand) > 0){
this.fontRendererObj.drawStringWithShadow("\u00A7f" + StatCollector.translateToLocal("container.arcaneWorkbench.upgrades"), xSize + 6, y + 6, 0);
int x = 0;
y = guiTop + 50 + spells.length*10;
// Wand upgrade tooltips
for(Item item : WandHelper.getSpecialUpgrades()){
int level = WandHelper.getUpgradeLevel(wand, item);
if(level > 0){
// No idea why this is -16 instead of +6, but it works!
if(isPointInRegion(xSize -16 + x, y, 16, 16, mouseX + guiLeft, mouseY + guiTop)){
ItemStack stack = new ItemStack(item, level);
this.drawItemStackTooltip(stack, mouseX - guiLeft, mouseY - guiTop);
}
x += 18;
}
}
}
}
}
@Override
public void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) {
GL11.glColor4f(1F, 1F, 1F, 1F);
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
// Main inventory
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
// Changing slots
for(int i=0; i<ContainerArcaneWorkbench.CRYSTAL_SLOT; i++){
Slot slot = this.inventorySlots.getSlot(i);
if(slot.xDisplayPosition >=0 && slot.yDisplayPosition >= 0)
this.drawTexturedModalRect(guiLeft + slot.xDisplayPosition - 10, guiTop + slot.yDisplayPosition - 10,
64, 220, 36, 36);
}
// Tooltip only drawn if there is a wand
if(this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getHasStack() && this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getStack().getItem() instanceof ItemWand){
// Tooltip box
drawTexturedModalRect(guiLeft + xSize, guiTop, xSize, 0, 256 - xSize - 4, ySize);
drawTexturedModalRect(guiLeft + 252, guiTop, xSize + 4, 0, tooltipWidth - 2*(256 - xSize - 4), ySize);
drawTexturedModalRect(guiLeft + xSize + tooltipWidth - (256 - xSize - 4), guiTop, xSize + 4, 0, 256 - xSize - 4, ySize);
ItemStack wand = this.inventorySlots.getSlot(ContainerArcaneWorkbench.WAND_SLOT).getStack();
Spell[] spells = WandHelper.getSpells(wand);
int i=0;
for(Spell spell : spells){
boolean discovered = true;
if(!this.mc.thePlayer.capabilities.isCreativeMode && ExtendedPlayer.get(this.mc.thePlayer) != null){
discovered = ExtendedPlayer.get(this.mc.thePlayer).hasSpellBeenDiscovered(spell);
}
// Renders the little element icon if there is an element
this.drawTexturedModalRect(guiLeft + xSize + 5, guiTop + 34 + 10*i++, discovered ? spell.element.ordinal()*8 : 0, 220, 8, 8);
}
int x = 0;
int y = guiTop + 50 + spells.length*10;
// Look how much shorter this is with the WandHelper class!
for(Item item : WandHelper.getSpecialUpgrades()){
int level = WandHelper.getUpgradeLevel(wand, item);
if(level > 0){
ItemStack stack = new ItemStack(item, level);
this.itemRender.renderItemAndEffectIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), stack, guiLeft + xSize + 6 + x, y);
this.itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), stack, guiLeft + xSize + 6 + x, y);
x += 18;
}
}
}
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
for(Object object : this.inventorySlots.inventorySlots){
if(object instanceof Slot){
Slot slot = (Slot)object;
// Tests whether I have added a background texture and if so actually renders it
if(!slot.getHasStack() && slot instanceof SlotWizardry && ((SlotWizardry)slot).backgroundIndex > -1){
// Taken directly from GuiContainer#func_146977_a, with a few changes.
this.zLevel = 100.0F;
itemRender.zLevel = 100.0F;
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_BLEND);
this.drawTexturedModalRect(guiLeft + slot.xDisplayPosition, guiTop + slot.yDisplayPosition, ((SlotWizardry)slot).backgroundIndex*16, 240, 16, 16);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_LIGHTING);
itemRender.zLevel = 0.0F;
this.zLevel = 0.0F;
}
}
}
}
public void initGui()
{
this.mc.thePlayer.openContainer = this.inventorySlots;
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.buttonList.add(this.applyBtn = new GuiButtonApply(0, this.width/2 + 48, this.height/2 + 3));
}
public void onGuiClosed()
{
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
/**
* Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).
*/
protected void actionPerformed(GuiButton par1GuiButton)
{
if (par1GuiButton.enabled)
{
if (par1GuiButton.id == 0)
{
// Packet building
IMessage msg = new PacketControlInput.Message(0);
WizardryPacketHandler.net.sendToServer(msg);
}
}
}
protected boolean isPointInRegion(int par1, int par2, int par3, int par4, int par5, int par6)
{
int k1 = this.width/2 - xSize/2;
int l1 = this.height/2 - this.ySize/2;
par5 -= k1;
par6 -= l1;
return par5 >= par1 - 1 && par5 < par1 + par3 + 1 && par6 >= par2 - 1 && par6 < par2 + par4 + 1;
}
protected void drawItemStackTooltip(ItemStack par1ItemStack, int par2, int par3)
{
List list = par1ItemStack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips);
for (int k = 0; k < list.size(); ++k)
{
if (k == 0)
{
list.set(k, par1ItemStack.getRarity().rarityColor + (String)list.get(k));
}
else
{
list.set(k, EnumChatFormatting.GRAY + (String)list.get(k));
}
}
FontRenderer font = par1ItemStack.getItem().getFontRenderer(par1ItemStack);
drawHoveringText(list, par2, par3, (font == null ? fontRendererObj : font));
}
protected void drawHoveringText(List par1List, int par2, int par3, FontRenderer font)
{
if (!par1List.isEmpty())
{
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
int k = 0;
Iterator iterator = par1List.iterator();
while (iterator.hasNext())
{
String s = (String)iterator.next();
int l = font.getStringWidth(s);
if (l > k)
{
k = l;
}
}
int i1 = par2 + 12;
int j1 = par3 - 12;
int k1 = 8;
if (par1List.size() > 1)
{
k1 += 2 + (par1List.size() - 1) * 10;
}
if (i1 + k > this.width)
{
i1 -= 28 + k;
}
if (j1 + k1 + 6 > this.height)
{
j1 = this.height - k1 - 6;
}
this.zLevel = 300.0F;
itemRender.zLevel = 300.0F;
int l1 = -267386864;
this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1);
this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1);
this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1);
this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1);
this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1);
int i2 = 1347420415;
int j2 = (i2 & 16711422) >> 1 | i2 & -16777216;
this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2);
this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2);
this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2);
this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2);
for(int k2 = 0; k2 < par1List.size(); ++k2){
String s1 = (String)par1List.get(k2);
font.drawStringWithShadow(s1, i1, j1, -1);
if(k2 == 0){
j1 += 2;
}
j1 += 10;
}
this.zLevel = 0.0F;
itemRender.zLevel = 0.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}
}
@@ -0,0 +1,73 @@
package electroblob.wizardry.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
class GuiButtonApply extends GuiButton {
private static final ResourceLocation texture = new ResourceLocation("wizardry:textures/gui/handbook.png");
public GuiButtonApply(int id, int x, int y){
super(id, x, y, 32, 16, StatCollector.translateToLocal("container.arcaneWorkbench.apply"));
}
/**
* Draws this button to the screen.
*/
public void drawButton(Minecraft minecraft, int par2, int par3){
// Whether the button is highlighted
this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height;
int k = 100;
int l = 220;
int colour = 14737632;
if(this.enabled){
if(this.field_146123_n){
k += this.width*2;
colour = 16777120;
}
}else{
k += this.width;
colour = 10526880;
}
this.drawTexturedRect(this.xPosition, this.yPosition, k, l, this.width, this.height, 256, 256);
this.drawCenteredString(minecraft.fontRenderer, this.displayString, this.xPosition + this.width / 2, this.yPosition + (this.height - 8) / 2, colour);
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into account.
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
*/
public void drawTexturedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight)
{
float f = 1F / (float)textureWidth;
float f1 = 1F / (float)textureHeight;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x), (double)(y + height), 0, (double)((float)(u) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), 0, (double)((float)(u + width) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y), 0, (double)((float)(u + width) * f), (double)((float)(v) * f1));
tessellator.addVertexWithUV((double)(x), (double)(y), 0, (double)((float)(u) * f), (double)((float)(v) * f1));
tessellator.draw();
}
}
@@ -0,0 +1,27 @@
package electroblob.wizardry.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
class GuiButtonInvisible extends GuiButton {
public GuiButtonInvisible(int id, int x, int y, int width, int height){
super(id, x, y, width, height, "");
}
/**
* Draws this button to the screen.
*/
public void drawButton(Minecraft par1Minecraft, int par2, int par3){
this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height;
}
}
@@ -0,0 +1,78 @@
package electroblob.wizardry.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
class GuiButtonNextPage extends GuiButton
{
/**
* True for pointing right (next page), false for pointing left (previous page).
*/
private final boolean nextPage;
private static final ResourceLocation texture = new ResourceLocation("wizardry:textures/gui/handbook.png");
public GuiButtonNextPage(int id, int x, int y, boolean par4)
{
super(id, x, y, 23, 13, "");
this.nextPage = par4;
}
/**
* Draws this button to the screen.
*/
public void drawButton(Minecraft par1Minecraft, int par2, int par3)
{
if (this.visible)
{
boolean flag = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
par1Minecraft.getTextureManager().bindTexture(texture);
int k = 0;
int l = 192;
if (flag)
{
k += 23;
}
if (!this.nextPage)
{
l += 13;
}
this.drawTexturedRect(this.xPosition, this.yPosition, k, l, 23, 13, 288, 256);
}
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into account.
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
*/
public void drawTexturedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight)
{
float f = 1F / (float)textureWidth;
float f1 = 1F / (float)textureHeight;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x), (double)(y + height), 0, (double)((float)(u) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), 0, (double)((float)(u + width) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y), 0, (double)((float)(u + width) * f), (double)((float)(v) * f1));
tessellator.addVertexWithUV((double)(x), (double)(y), 0, (double)((float)(u) * f), (double)((float)(v) * f1));
tessellator.draw();
}
}
@@ -0,0 +1,104 @@
package electroblob.wizardry.client;
import java.util.ArrayList;
import java.util.List;
import cpw.mods.fml.client.config.DummyConfigElement.DummyCategoryElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.GuiConfigEntries;
import cpw.mods.fml.client.config.GuiConfigEntries.CategoryEntry;
import cpw.mods.fml.client.config.IConfigElement;
import electroblob.wizardry.Wizardry;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.StatCollector;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
public class GuiConfigWizardry extends GuiConfig {
public GuiConfigWizardry(GuiScreen parent){
super(parent, getConfigEntries(), Wizardry.MODID, false, false, Wizardry.NAME + " - " + StatCollector.translateToLocal("config.title.general"));
//this.titleLine2 = "File location: " + Wizardry.config.getConfigFile().getAbsolutePath();
}
private static List<IConfigElement> getConfigEntries(){
List<IConfigElement> configList = new ArrayList<IConfigElement>(1);
configList.add(new DummyCategoryElement("spellsConfig", "config.category.spells", SpellsCategory.class));
configList.add(new DummyCategoryElement("resistancesConfig", "config.category.resistances", ResistancesCategory.class));
configList.add(new DummyCategoryElement("idsConfig", "config.category.ids", IDsCategory.class));
configList.addAll(new ConfigElement(Wizardry.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements());
return configList;
}
/** Spells category of the config gui. This adds a button which opens up the spells category config. */
public static class SpellsCategory extends CategoryEntry
{
public SpellsCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop)
{
super(owningScreen, owningEntryList, prop);
}
@Override
protected GuiScreen buildChildScreen()
{
// This GuiConfig object specifies the configID of the object and as such will force-save when it is closed.
// The parent GuiConfig object's entryList will also be refreshed to reflect the changes.
GuiConfig spellsMenu = new GuiConfig(this.owningScreen,
(new ConfigElement(Wizardry.config.getCategory(Wizardry.SPELLS_CATEGORY))).getChildElements(),
this.owningScreen.modID, Wizardry.SPELLS_CATEGORY, false, false,
Wizardry.NAME + " - " + StatCollector.translateToLocal("config.title.spells"));
spellsMenu.titleLine2 = StatCollector.translateToLocal("config.subtitle.spells");
return spellsMenu;
}
}
/** Resistances category of the config gui. */
public static class ResistancesCategory extends CategoryEntry
{
public ResistancesCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop)
{
super(owningScreen, owningEntryList, prop);
}
@Override
protected GuiScreen buildChildScreen()
{
// This GuiConfig object specifies the configID of the object and as such will force-save when it is closed.
// The parent GuiConfig object's entryList will also be refreshed to reflect the changes.
GuiConfig idsMenu = new GuiConfig(this.owningScreen,
(new ConfigElement(Wizardry.config.getCategory(Wizardry.RESISTANCES_CATEGORY))).getChildElements(),
this.owningScreen.modID, Wizardry.RESISTANCES_CATEGORY, false, false,
Wizardry.NAME + " - " + StatCollector.translateToLocal("config.title.resistances"));
idsMenu.titleLine2 = StatCollector.translateToLocal("config.subtitle.resistances");
return idsMenu;
}
}
/** IDs category of the config gui. */
public static class IDsCategory extends CategoryEntry
{
public IDsCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop)
{
super(owningScreen, owningEntryList, prop);
}
@Override
protected GuiScreen buildChildScreen()
{
// This GuiConfig object specifies the configID of the object and as such will force-save when it is closed.
// The parent GuiConfig object's entryList will also be refreshed to reflect the changes.
GuiConfig idsMenu = new GuiConfig(this.owningScreen,
(new ConfigElement(Wizardry.config.getCategory(Wizardry.IDS_CATEGORY))).getChildElements(),
this.owningScreen.modID, Wizardry.IDS_CATEGORY, false, false,
Wizardry.NAME + " - " + StatCollector.translateToLocal("config.title.ids"));
idsMenu.titleLine2 = StatCollector.translateToLocal("config.subtitle.ids");
return idsMenu;
}
}
}
@@ -0,0 +1,40 @@
package electroblob.wizardry.client;
import org.lwjgl.opengl.GL11;
import electroblob.wizardry.WizardryGuiHandler;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ContainerWorkbench;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
/** Crafting table GUI that doesn't require a crafting table container object. */
public class GuiPortableCrafting extends GuiContainer {
private static final ResourceLocation craftingTableGuiTextures = new ResourceLocation("textures/gui/container/crafting_table.png");
public GuiPortableCrafting(InventoryPlayer p_i1084_1_, World p_i1084_2_, int p_i1084_3_, int p_i1084_4_, int p_i1084_5_)
{
super(new ContainerWorkbench(p_i1084_1_, p_i1084_2_, p_i1084_3_, p_i1084_4_, p_i1084_5_));
}
/**
* Draw the foreground layer for the GuiContainer (everything in front of the items)
*/
protected void drawGuiContainerForegroundLayer(int p_146979_1_, int p_146979_2_)
{
this.fontRendererObj.drawString(I18n.format("container.crafting"), 28, 6, 4210752);
this.fontRendererObj.drawString(I18n.format("container.inventory"), 8, this.ySize - 96 + 2, 4210752);
}
protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(craftingTableGuiTextures);
int k = (this.width - this.xSize) / 2;
int l = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
}
}
@@ -0,0 +1,153 @@
package electroblob.wizardry.client;
import org.lwjgl.input.Keyboard;
import electroblob.wizardry.EnumTier;
import electroblob.wizardry.ExtendedPlayer;
import electroblob.wizardry.SpellGlyphData;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.WizardryGuiHandler;
import electroblob.wizardry.WizardryRegistry;
import electroblob.wizardry.spell.Spell;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
public class GuiSpellBook extends GuiScreen {
private int xSize, ySize;
private Spell spell;
private static final ResourceLocation texture = new ResourceLocation(Wizardry.MODID, "textures/gui/spellbook.png");
public GuiSpellBook(Spell spell) {
super();
xSize = 288;
ySize = 180;
this.spell = spell;
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3) {
int xPos = this.width/2 - xSize/2;
int yPos = this.height/2 - this.ySize/2;
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
boolean discovered = true;
if(Wizardry.discoveryMode && !player.capabilities.isCreativeMode && ExtendedPlayer.get(player) != null
&& !ExtendedPlayer.get(player).hasSpellBeenDiscovered(spell)){
discovered = false;
}
// Draws spell illustration on opposite page, underneath the book so it shows through the hole.
Minecraft.getMinecraft().renderEngine.bindTexture(discovered ? spell.icon : WizardryRegistry.none.icon);
this.drawTexturedRect(xPos + 145, yPos + 20, 0, 0, 128, 128, 128, 128);
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
this.drawTexturedRect(xPos, yPos, 0, 0, xSize, ySize, xSize, 256);
super.drawScreen(par1, par2, par3);
if(discovered){
this.fontRendererObj.drawString(spell.getDisplayName(), xPos+17, yPos+14, 0);
this.fontRendererObj.drawString(spell.type.getDisplayName(), xPos+17, yPos+25, 0x777777);
}else{
this.mc.standardGalacticFontRenderer.drawString(SpellGlyphData.getGlyphName(spell, player.worldObj), xPos+17, yPos+14, 0);
this.mc.standardGalacticFontRenderer.drawString(spell.type.getDisplayName(), xPos+17, yPos+25, 0x777777);
}
this.fontRendererObj.drawString("-------------------", xPos+17, yPos+34, 0);
if(spell.tier == EnumTier.BASIC){
// Basic is usually white but this doesn't show up.
this.fontRendererObj.drawString("Tier: \u00A77" + EnumTier.BASIC.getDisplayName(), xPos+17, yPos+44, 0);
}else{
this.fontRendererObj.drawString("Tier: " + spell.tier.getDisplayNameWithFormatting(), xPos+17, yPos+44, 0);
}
String element = "Element: " + spell.element.colour + spell.element.getDisplayName();
if(!discovered) element = "Element: ?";
this.fontRendererObj.drawString(element, xPos+17, yPos+56, 0);
String manaCost = "Mana Cost: " + spell.cost;
if(spell.isContinuous) manaCost = "Mana Cost: " + spell.cost + "/second";
if(!discovered) manaCost = "Mana Cost: ?";
this.fontRendererObj.drawString(manaCost, xPos+17, yPos+68, 0);
if(discovered){
this.fontRendererObj.drawSplitString(spell.getDescription(), xPos+17, yPos+82, 118, 0);
}else{
this.mc.standardGalacticFontRenderer.drawSplitString(SpellGlyphData.getGlyphDescription(spell, player.worldObj), xPos+17, yPos+82, 118, 0);
}
/*
// Word wrapping
int charNumber = 0;
int lineNumber = 0;
while(charNumber < spell.desc.length()){
int lineLength = 0;
String line;
if(spell.desc.length() - charNumber > 22){
for(int i = charNumber; i < charNumber+23; i++){
if(spell.desc.charAt(i) == ' '){
lineLength = i - charNumber;
}
}
line = spell.desc.substring(charNumber, charNumber + lineLength);
}else{
line = spell.desc.substring(charNumber, spell.desc.length());
charNumber = spell.desc.length();
}
this.fontRendererObj.drawString("\u00A7o" + line, xPos+17, yPos+82+10*lineNumber, 0);
charNumber+=(lineLength+1);
lineNumber++;
}
*/
}
public void initGui()
{
super.initGui();
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
}
public void onGuiClosed()
{
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into account. Client side only, of course.
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
*/
public static void drawTexturedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight)
{
float f = 1F / (float)textureWidth;
float f1 = 1F / (float)textureHeight;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x), (double)(y + height), 0, (double)((float)(u) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), 0, (double)((float)(u + width) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y), 0, (double)((float)(u + width) * f), (double)((float)(v) * f1));
tessellator.addVertexWithUV((double)(x), (double)(y), 0, (double)((float)(u) * f), (double)((float)(v) * f1));
tessellator.draw();
}
}
@@ -0,0 +1,169 @@
package electroblob.wizardry.client;
import java.util.List;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import electroblob.wizardry.ExtendedPlayer;
import electroblob.wizardry.SpellGlyphData;
import electroblob.wizardry.WandHelper;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.WizardryRegistry;
import electroblob.wizardry.item.ItemWand;
import electroblob.wizardry.spell.None;
import electroblob.wizardry.spell.Spell;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagIntArray;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
public class GuiSpellDisplay extends Gui {
private Minecraft mc;
private static final ResourceLocation hudTexture = new ResourceLocation(Wizardry.MODID, "textures/gui/spell_hud.png");
public GuiSpellDisplay(Minecraft par1Minecraft) {
super();
this.mc = par1Minecraft;
}
@SubscribeEvent
public void draw(RenderGameOverlayEvent event){
EntityPlayer player = this.mc.thePlayer;
if(player.getHeldItem() != null && player.getHeldItem().getItem() instanceof ItemWand){
int width = event.resolution.getScaledWidth();
int height = event.resolution.getScaledHeight();
Spell spell = WandHelper.getCurrentSpell(player.getHeldItem());
int cooldown = WandHelper.getCurrentCooldown(player.getHeldItem());
float cooldownMultiplier = 1.0f - WandHelper.getUpgradeLevel(player.getHeldItem(), Wizardry.cooldownUpgrade)*Wizardry.COOLDOWN_REDUCTION_PER_LEVEL;
if(player.isPotionActive(Wizardry.fontOfMana)){
// Dividing by this rather than setting it takes upgrades and font of mana into account simultaneously
cooldownMultiplier /= 2 + player.getActivePotionEffect(Wizardry.fontOfMana).getAmplifier();
}
// Coordinates of the top left corner of the HUD.
int left = 0;
int top = 0;
boolean mirror = false;
if(Wizardry.spellHUDPosition.equals("Bottom left")){
left = 0;
top = height-36;
}else if(Wizardry.spellHUDPosition.equals("Top left")){
left = 0;
top = 0;
}else if(Wizardry.spellHUDPosition.equals("Top right")){
left = width-128;
top = 0;
mirror = true;
}else if(Wizardry.spellHUDPosition.equals("Bottom right")){
left = width-128;
top = height-36;
mirror = true;
}
boolean discovered = true;
if(!player.capabilities.isCreativeMode && ExtendedPlayer.get(player) != null){
discovered = ExtendedPlayer.get(player).hasSpellBeenDiscovered(spell);
}
if(event.type == RenderGameOverlayEvent.ElementType.TEXT){
// Makes spells greyed out if they are in cooldown or if the player has the arcane jammer effect
String colour = cooldown > 0 || player.isPotionActive(Wizardry.arcaneJammer) ? "\u00A78" : spell.element.colour;
if(!discovered) colour = "\u00A79";
String spellName = discovered ? spell.getDisplayName() : SpellGlyphData.getGlyphName(spell, player.worldObj);
FontRenderer font = discovered ? this.mc.fontRenderer : this.mc.standardGalacticFontRenderer;
int maxWidth = 90;
if(font.getStringWidth(spellName) <= maxWidth){
// Single line is rendered more centrally
font.drawStringWithShadow(colour + spellName, mirror ? left+5 : left+41, top+13, 0xffffffff);
}else{
int lineNumber = 0;
List lines = font.listFormattedStringToWidth(spellName, maxWidth);
for(Object line : lines){
if(line instanceof String){
font.drawStringWithShadow(colour + (String)line, mirror ? left+5 : left+41, top+6 + 11*lineNumber, 0xffffffff);
}
lineNumber++;
}
}
}else if(event.type == RenderGameOverlayEvent.ElementType.HOTBAR){
GL11.glPushMatrix();
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor3f(1.0f, 1.0f, 1.0f);
this.mc.renderEngine.bindTexture(hudTexture);
// Background of spell hud
this.drawTexturedModalRect(left, top, 0, mirror ? 36 : 0, 128, 36);
// Cooldown bar
if(cooldown > 0){
this.drawTexturedModalRect(mirror ? left+5 : left+41, height-8, 128, 6, 82, 6);
int l = (int)(((double)(spell.cooldown * cooldownMultiplier - cooldown)
/ (double)(spell.cooldown * cooldownMultiplier)) * 82);
this.drawTexturedModalRect(mirror ? left+5 : left+41, height-8, 128, 0, l, 6);
}
// Spell illustration
this.mc.renderEngine.bindTexture(discovered ? spell.icon : WizardryRegistry.none.icon);
this.drawTexturedRect(mirror ? left+94 : left+2, top+2, 0, 0, 32, 32, 32, 32);
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
}
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into account. Client side only, of course.
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
*/
public static void drawTexturedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight)
{
float f = 1F / (float)textureWidth;
float f1 = 1F / (float)textureHeight;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x), (double)(y + height), 0, (double)((float)(u) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), 0, (double)((float)(u + width) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y), 0, (double)((float)(u + width) * f), (double)((float)(v) * f1));
tessellator.addVertexWithUV((double)(x), (double)(y), 0, (double)((float)(u) * f), (double)((float)(v) * f1));
tessellator.draw();
}
}
@@ -0,0 +1,945 @@
package electroblob.wizardry.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.Charsets;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import electroblob.wizardry.EnumElement;
import electroblob.wizardry.EnumTier;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.WizardryGuiHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.resources.LanguageManager;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
public class GuiWizardHandbook extends GuiScreen {
private GuiButtonNextPage nextPageBtn, prevPageBtn;
private int xSize, ySize;
private int pageNumber = 0;
private static final int pageWidth = 120;
public static final ResourceLocation regularHandbook = new ResourceLocation(Wizardry.MODID, "textures/gui/handbook.png");
public static final ResourceLocation ore = new ResourceLocation(Wizardry.MODID, "textures/gui/ore_picture.png");
public static final ResourceLocation crystal = new ResourceLocation(Wizardry.MODID, "textures/items/magic_crystal.png");
public static final ResourceLocation workbenchGui = new ResourceLocation(Wizardry.MODID, "textures/gui/arcane_workbench.png");
public static final ResourceLocation craftingGrids = new ResourceLocation(Wizardry.MODID, "textures/gui/handbook_recipes.png");
private ArrayList<ArrayList<String>> text;
private ArrayList<Section> sections;
private int guiPage, imagePage;
public GuiWizardHandbook() {
super();
xSize = 288;
ySize = 180;
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int mouseX, int mouseY, float par3){
int xPos = this.width/2 - xSize/2;
int yPos = this.height/2 - this.ySize/2;
// Tests for crafting recipes section
if(pageNumber >= (sections.get(sections.size()-1).pageNumber-1)/2 && pageNumber < (sections.get(sections.size()-1).pageNumber-1)/2 + 4){
Minecraft.getMinecraft().renderEngine.bindTexture(craftingGrids);
}else{
Minecraft.getMinecraft().renderEngine.bindTexture(regularHandbook);
}
drawTexturedRect(xPos, yPos, 0, 0, xSize, ySize, xSize, 256);
// Arcane workbench gui picture
if(pageNumber == (this.guiPage-1)/2){
Minecraft.getMinecraft().renderEngine.bindTexture(workbenchGui);
this.drawTexturedModalRect(this.guiPage % 2 == 1 ? xPos + 17 : this.width/2 + 7, yPos + 14, 28, 12, 120, 118);
}
// Magic crystal and crystal ore images
if(pageNumber == (this.imagePage-1)/2){
Minecraft.getMinecraft().renderEngine.bindTexture(ore);
drawTexturedRect(this.imagePage % 2 == 1 ? xPos + 17 : this.width/2 + 7, yPos + 80, 0, 0, 64, 64, 64, 64);
Minecraft.getMinecraft().renderEngine.bindTexture(crystal);
drawTexturedStretchedRect(this.imagePage % 2 == 1 ? xPos + 17 + 64 : this.width/2 + 7 + 62, yPos + 80, 0, 0, 64, 64, 1, 1);
}
this.fontRendererObj.drawString("" + (pageNumber*2 + 1), xPos + xSize/4 - 3, yPos + ySize - 20, 0);
this.fontRendererObj.drawString("" + (pageNumber*2 + 2), xPos + 3*xSize/4 - 5, yPos + ySize - 20, 0);
super.drawScreen(mouseX, mouseY, par3);
int lineNumber = 0;
if(pageNumber == 1){
int row = 2;
for(Section s : sections){
s.drawContents();
row++;
}
}else{
for(Section s : sections){
s.hideButton();
}
}
for(String paragraph : text.get(pageNumber*2)){
this.fontRendererObj.drawSplitString(paragraph, xPos + 17, yPos + 14 + lineNumber*this.fontRendererObj.FONT_HEIGHT, pageWidth, 0);
ArrayList list = new ArrayList(this.fontRendererObj.listFormattedStringToWidth(paragraph, this.pageWidth));
lineNumber += list.size();
}
lineNumber = 0;
// Prevents crash when the last page is blank (and hence is not in the list of pages)
if(text.size() > pageNumber*2 + 1){
for(String paragraph : text.get(pageNumber*2 + 1)){
// First page is centred
if(pageNumber == 0){
int startX = this.width/2 + 7 + pageWidth/2 - this.fontRendererObj.getStringWidth(paragraph)/2;
this.fontRendererObj.drawSplitString(paragraph, startX, yPos + 14 + lineNumber*this.fontRendererObj.FONT_HEIGHT, pageWidth, 0);
}else{
this.fontRendererObj.drawSplitString(paragraph, this.width/2 + 7, yPos + 14 + lineNumber*this.fontRendererObj.FONT_HEIGHT, pageWidth, 0);
}
ArrayList list = new ArrayList(this.fontRendererObj.listFormattedStringToWidth(paragraph, this.pageWidth));
lineNumber += list.size();
}
}
/*
for(int i=0;i<(Math.min(text[pageNumber].length, 14));i++){
this.fontRendererObj.drawString(text[pageNumber][i], xPos + 16, yPos + 14 + i*10, 0);
}
for(int i=0;i<(Math.min(text[pageNumber].length - 14, 14));i++){
this.fontRendererObj.drawString(text[pageNumber][i+14], this.width/2 + 5, yPos + 14 + i*10, 0);
}
*/
ItemStack[][] craftingGrid;
ItemStack craftingResult;
// Tooltips are rendered after recipes to prevent tooltips on the left appearing behind items on the right.
if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.gold_nugget);
craftingGrid[1][0] = new ItemStack(Blocks.carpet, 1, 10);
craftingGrid[2][0] = new ItemStack(Items.gold_nugget);
craftingGrid[0][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Blocks.lapis_block);
craftingGrid[2][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][2] = new ItemStack(Blocks.stone);
craftingGrid[1][2] = new ItemStack(Blocks.stone);
craftingGrid[2][2] = new ItemStack(Blocks.stone);
craftingResult = new ItemStack(Wizardry.arcaneWorkbench);
this.renderCraftingRecipe(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[2][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Items.stick);
craftingGrid[0][2] = new ItemStack(Items.gold_nugget);
craftingResult = new ItemStack(Wizardry.magicWand);
this.renderCraftingRecipe(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[1][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Items.book);
craftingGrid[1][2] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[2][1] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.spellBook, 1, 1);
this.renderCraftingRecipe(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.book);
craftingGrid[1][0] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.wizardHandbook);
this.renderCraftingRecipe(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}else if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2 + 1){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.crystalFlower);
craftingResult = new ItemStack(Wizardry.magicCrystal, 2);
this.renderCraftingRecipe(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[2][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Items.glass_bottle);
craftingGrid[2][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][2] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][2] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[2][2] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.manaFlask);
this.renderCraftingRecipe(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[1][0] = new ItemStack(Blocks.stone);
craftingGrid[0][1] = new ItemStack(Blocks.stone);
craftingGrid[1][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][2] = new ItemStack(Blocks.stone);
craftingGrid[2][1] = new ItemStack(Blocks.stone);
craftingResult = new ItemStack(Wizardry.transportationStone, 2);
this.renderCraftingRecipe(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[1][0] = new ItemStack(Items.string);
craftingGrid[0][1] = new ItemStack(Items.string);
craftingGrid[1][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][2] = new ItemStack(Items.string);
craftingGrid[2][1] = new ItemStack(Items.string);
craftingResult = new ItemStack(Wizardry.magicSilk, 2);
this.renderCraftingRecipe(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}else if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2 + 2){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardHat);
this.renderCraftingRecipe(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][2] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][2] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][2] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardRobe);
this.renderCraftingRecipe(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][2] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][2] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardLeggings);
this.renderCraftingRecipe(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardBoots);
this.renderCraftingRecipe(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}else if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2 + 3){
if(Wizardry.useAlternateScrollRecipe){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.paper);
craftingGrid[1][0] = new ItemStack(Items.string);
craftingGrid[2][0] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.blankScroll);
this.renderCraftingRecipe(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
}else{
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.paper);
craftingGrid[1][0] = new ItemStack(Items.string);
craftingResult = new ItemStack(Wizardry.blankScroll);
this.renderCraftingRecipe(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
}
if(Wizardry.firebombIsCraftable){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.blaze_powder);
craftingGrid[1][0] = new ItemStack(Items.blaze_powder);
craftingGrid[0][1] = new ItemStack(Items.glass_bottle);
craftingGrid[1][1] = new ItemStack(Items.gunpowder);
craftingResult = new ItemStack(Wizardry.firebomb, 3);
this.renderCraftingRecipe(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}
if(Wizardry.poisonBombIsCraftable){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.spider_eye);
craftingGrid[1][0] = new ItemStack(Items.spider_eye);
craftingGrid[0][1] = new ItemStack(Items.glass_bottle);
craftingGrid[1][1] = new ItemStack(Items.gunpowder);
craftingResult = new ItemStack(Wizardry.poisonBomb, 3);
this.renderCraftingRecipe(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
}
if(Wizardry.smokeBombIsCraftable){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.coal);
craftingGrid[1][0] = new ItemStack(Items.coal);
craftingGrid[0][1] = new ItemStack(Items.glass_bottle);
craftingGrid[1][1] = new ItemStack(Items.gunpowder);
craftingResult = new ItemStack(Wizardry.smokeBomb, 3);
this.renderCraftingRecipe(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}
}
if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.gold_nugget);
craftingGrid[1][0] = new ItemStack(Blocks.carpet, 1, 10);
craftingGrid[2][0] = new ItemStack(Items.gold_nugget);
craftingGrid[0][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Blocks.lapis_block);
craftingGrid[2][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][2] = new ItemStack(Blocks.stone);
craftingGrid[1][2] = new ItemStack(Blocks.stone);
craftingGrid[2][2] = new ItemStack(Blocks.stone);
craftingResult = new ItemStack(Wizardry.arcaneWorkbench);
this.renderCraftingTooltips(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[2][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Items.stick);
craftingGrid[0][2] = new ItemStack(Items.gold_nugget);
craftingResult = new ItemStack(Wizardry.magicWand);
this.renderCraftingTooltips(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[1][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Items.book);
craftingGrid[1][2] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[2][1] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.spellBook, 1, 1);
this.renderCraftingTooltips(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.book);
craftingGrid[1][0] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.wizardHandbook);
this.renderCraftingTooltips(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}else if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2 + 1){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.crystalFlower);
craftingResult = new ItemStack(Wizardry.magicCrystal, 2);
this.renderCraftingTooltips(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[2][0] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][1] = new ItemStack(Items.glass_bottle);
craftingGrid[2][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[0][2] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][2] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[2][2] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.manaFlask);
this.renderCraftingTooltips(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[1][0] = new ItemStack(Blocks.stone);
craftingGrid[0][1] = new ItemStack(Blocks.stone);
craftingGrid[1][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][2] = new ItemStack(Blocks.stone);
craftingGrid[2][1] = new ItemStack(Blocks.stone);
craftingResult = new ItemStack(Wizardry.transportationStone, 2);
this.renderCraftingTooltips(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[1][0] = new ItemStack(Items.string);
craftingGrid[0][1] = new ItemStack(Items.string);
craftingGrid[1][1] = new ItemStack(Wizardry.magicCrystal);
craftingGrid[1][2] = new ItemStack(Items.string);
craftingGrid[2][1] = new ItemStack(Items.string);
craftingResult = new ItemStack(Wizardry.magicSilk, 2);
this.renderCraftingTooltips(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}else if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2 + 2){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardHat);
this.renderCraftingTooltips(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][2] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][2] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][2] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardRobe);
this.renderCraftingTooltips(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[1][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][2] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][2] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardLeggings);
this.renderCraftingTooltips(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][0] = new ItemStack(Wizardry.magicSilk);
craftingGrid[0][1] = new ItemStack(Wizardry.magicSilk);
craftingGrid[2][1] = new ItemStack(Wizardry.magicSilk);
craftingResult = new ItemStack(Wizardry.wizardBoots);
this.renderCraftingTooltips(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}else if(pageNumber == (sections.get(sections.size()-1).pageNumber-1)/2 + 3){
if(Wizardry.useAlternateScrollRecipe){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.paper);
craftingGrid[1][0] = new ItemStack(Items.string);
craftingGrid[2][0] = new ItemStack(Wizardry.magicCrystal);
craftingResult = new ItemStack(Wizardry.blankScroll);
this.renderCraftingTooltips(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
}else{
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.paper);
craftingGrid[1][0] = new ItemStack(Items.string);
craftingResult = new ItemStack(Wizardry.blankScroll);
this.renderCraftingTooltips(xPos + 23, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
}
if(Wizardry.firebombIsCraftable){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.blaze_powder);
craftingGrid[1][0] = new ItemStack(Items.blaze_powder);
craftingGrid[0][1] = new ItemStack(Items.glass_bottle);
craftingGrid[1][1] = new ItemStack(Items.gunpowder);
craftingResult = new ItemStack(Wizardry.firebomb, 3);
this.renderCraftingTooltips(xPos + 23, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}
if(Wizardry.poisonBombIsCraftable){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.spider_eye);
craftingGrid[1][0] = new ItemStack(Items.spider_eye);
craftingGrid[0][1] = new ItemStack(Items.glass_bottle);
craftingGrid[1][1] = new ItemStack(Items.gunpowder);
craftingResult = new ItemStack(Wizardry.poisonBomb, 3);
this.renderCraftingTooltips(xPos + 156, yPos + 39, mouseX, mouseY, craftingGrid, craftingResult);
}
if(Wizardry.smokeBombIsCraftable){
craftingGrid = new ItemStack[3][3];
craftingGrid[0][0] = new ItemStack(Items.coal);
craftingGrid[1][0] = new ItemStack(Items.coal);
craftingGrid[0][1] = new ItemStack(Items.glass_bottle);
craftingGrid[1][1] = new ItemStack(Items.gunpowder);
craftingResult = new ItemStack(Wizardry.smokeBomb, 3);
this.renderCraftingTooltips(xPos + 156, yPos + 98, mouseX, mouseY, craftingGrid, craftingResult);
}
}
}
private void renderCraftingRecipe(int xPos, int yPos, int mouseX, int mouseY, ItemStack[][] craftingGrid, ItemStack craftingResult) {
int guiLeft = this.width/2 - xSize/2;
int guiTop = this.height/2 - this.ySize/2;
GL11.glPushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
GL11.glEnable(GL11.GL_LIGHTING);
itemRender.zLevel = 100.0F;
for(int i=0; i<craftingGrid.length; i++){
for(int j=0; j<craftingGrid[i].length; j++){
if(craftingGrid[i][j] != null){
itemRender.renderItemAndEffectIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), craftingGrid[i][j], xPos + 18*i, yPos + 18*j);
itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), craftingGrid[i][j], xPos + 18*i, yPos + 18*j);
}
}
}
if(craftingResult != null){
itemRender.renderItemAndEffectIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), craftingResult, xPos + 86, yPos + 18);
itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, this.mc.getTextureManager(), craftingResult, xPos + 86, yPos + 18);
}
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
}
private void renderCraftingTooltips(int xPos, int yPos, int mouseX, int mouseY, ItemStack[][] craftingGrid, ItemStack craftingResult) {
int guiLeft = this.width/2 - xSize/2;
int guiTop = this.height/2 - this.ySize/2;
GL11.glPushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
itemRender.zLevel = 0.0F;
GL11.glDisable(GL11.GL_LIGHTING);
for(int i=0; i<craftingGrid.length; i++){
for(int j=0; j<craftingGrid[i].length; j++){
if(craftingGrid[i][j] != null && isPointInRegion(xPos + 18*i, yPos + 18*j, 16, 16, mouseX + guiLeft, mouseY + guiTop)){
this.drawItemStackTooltip(craftingGrid[i][j], mouseX, mouseY);
}
}
}
if(craftingResult != null && isPointInRegion(xPos + 86, yPos + 18, 16, 16, mouseX + guiLeft, mouseY + guiTop)){
this.drawItemStackTooltip(craftingResult, mouseX, mouseY);
}
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
}
@Override
public void initGui(){
super.initGui();
Keyboard.enableRepeatEvents(true);
int nextButtonId = 0;
this.buttonList.clear();
this.buttonList.add(this.nextPageBtn = new GuiButtonNextPage(nextButtonId++, this.width/2 + this.xSize/2 - 22 - 23, this.height/2 + this.ySize/2 - 10 - 13, true));
this.buttonList.add(this.prevPageBtn = new GuiButtonNextPage(nextButtonId++, this.width/2 - this.xSize/2 + 21, this.height/2 + this.ySize/2 - 10 - 13, false));
text = new ArrayList<ArrayList<String>>(1);
sections = new ArrayList<Section>(1);
BufferedReader bufferedreader = null;
String textFilepath = "wizardry:texts/handbook_" + Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getLanguageCode() + ".txt";
try {
bufferedreader = new BufferedReader(new InputStreamReader(this.mc.getResourceManager().getResource(new ResourceLocation(textFilepath)).getInputStream(), Charsets.UTF_8));
} catch (IOException e){
System.out.println("Warning: wizard handbook text file missing for the current language. Using default (English - US) instead.");
textFilepath = "wizardry:texts/handbook_en_US.txt";
try {
bufferedreader = new BufferedReader(new InputStreamReader(this.mc.getResourceManager().getResource(new ResourceLocation(textFilepath)).getInputStream(), Charsets.UTF_8));
} catch (IOException x){
System.err.println("Couldn't find file: wizardry:assets/texts/handbook_en_US.txt. The file may be missing; please try re-downloading and reinstalling wizardry.");
x.printStackTrace();
}
}
if(bufferedreader != null){
try {
String paragraph = bufferedreader.readLine();
ArrayList<String> page = new ArrayList<String>(1);
int linesPerPage = 16;
int lineNumber = 0;
while(paragraph != null){
//System.out.println(paragraph);
if(paragraph.contains("PAGEBREAK") || lineNumber >= linesPerPage){
text.add(page);
page = new ArrayList<String>(1);
lineNumber = 0;
if(paragraph.contains("PAGEBREAK")) paragraph = bufferedreader.readLine();
}else if(paragraph.contains("LINEBREAK")){
lineNumber++;
page.add("");
paragraph = bufferedreader.readLine();
}else if(paragraph.contains("SECTION")){
sections.add(new Section(paragraph.replace("SECTION ", ""), text.size() + 1, this.width/2 + 7,
this.height/2 - this.ySize/2 + 14 + (sections.size()+2)*this.fontRendererObj.FONT_HEIGHT, nextButtonId++));
paragraph = bufferedreader.readLine();
}else if(paragraph.contains("IMAGE")){
if(paragraph.contains("WORKBENCH")){
this.guiPage = text.size() + 1;
}else if(paragraph.contains("CRYSTAL")){
this.imagePage = text.size() + 1;
}
paragraph = bufferedreader.readLine();
}else{
paragraph = paragraph.replaceAll("NEXT_SPELL_KEY", Keyboard.getKeyName(ClientProxy.nextSpell.getKeyCode()));
paragraph = paragraph.replaceAll("PREVIOUS_SPELL_KEY", Keyboard.getKeyName(ClientProxy.previousSpell.getKeyCode()));
paragraph = paragraph.replaceAll("MANA_PER_CRYSTAL_MINUS_30", "" + (Wizardry.MANA_PER_CRYSTAL - 30));
paragraph = paragraph.replaceAll("MANA_PER_CRYSTAL", "" + Wizardry.MANA_PER_CRYSTAL);
paragraph = paragraph.replaceAll("BASIC_MAX_CHARGE", "" + EnumTier.BASIC.maxCharge);
paragraph = paragraph.replaceAll("APPRENTICE_MAX_CHARGE", "" + EnumTier.APPRENTICE.maxCharge);
paragraph = paragraph.replaceAll("ADVANCED_MAX_CHARGE", "" + EnumTier.ADVANCED.maxCharge);
paragraph = paragraph.replaceAll("MASTER_MAX_CHARGE", "" + EnumTier.MASTER.maxCharge);
paragraph = paragraph.replaceAll("BASIC_COLOUR", "\u00A77");
paragraph = paragraph.replaceAll("APPRENTICE_COLOUR", EnumTier.APPRENTICE.colour);
paragraph = paragraph.replaceAll("ADVANCED_COLOUR", EnumTier.ADVANCED.colour);
paragraph = paragraph.replaceAll("MASTER_COLOUR", EnumTier.MASTER.colour);
paragraph = paragraph.replaceAll("FIRE_COLOUR", EnumElement.FIRE.colour);
paragraph = paragraph.replaceAll("ICE_COLOUR", EnumElement.ICE.colour);
paragraph = paragraph.replaceAll("LIGHTNING_COLOUR", EnumElement.LIGHTNING.colour);
paragraph = paragraph.replaceAll("NECROMANCY_COLOUR", EnumElement.NECROMANCY.colour);
paragraph = paragraph.replaceAll("EARTH_COLOUR", EnumElement.EARTH.colour);
paragraph = paragraph.replaceAll("SORCERY_COLOUR", EnumElement.SORCERY.colour);
paragraph = paragraph.replaceAll("HEALING_COLOUR", EnumElement.HEALING.colour);
paragraph = paragraph.replaceAll("RESET_COLOUR", "\u00A70");
paragraph = paragraph.replaceAll("VERSION", Wizardry.VERSION);
int linesInParagraph = this.fontRendererObj.listFormattedStringToWidth(paragraph, this.pageWidth).size();
// Ignores empty lines at the top of a page.
if(paragraph.isEmpty() && lineNumber == 0){
paragraph = bufferedreader.readLine();
// Normal paragraph, all on one page
}else if(lineNumber + linesInParagraph <= linesPerPage){
page.add(paragraph);
lineNumber += linesInParagraph;
paragraph = bufferedreader.readLine();
// Paragraphs split across two pages (or more?)
}else{
int linesInFirstPart = linesPerPage - lineNumber;
String paragraphFirstPart = "";
String paragraphLastPart = "";
int i = 0;
List strings = this.fontRendererObj.listFormattedStringToWidth(paragraph, this.pageWidth);
for(Object s : strings){
if(i < linesInFirstPart){
paragraphFirstPart = paragraphFirstPart.concat((String)s + " ");
}else{
paragraphLastPart = paragraphLastPart.concat((String)s + " ");
}
i++;
}
//System.out.println("Paragraph crosses page boundary; string split into: \"" + paragraphFirstPart + "\" and \"" + paragraphLastPart + "\"");
page.add(paragraphFirstPart);
lineNumber += linesInFirstPart;
paragraph = paragraphLastPart;
}
}
}
text.add(page);
} catch (IOException e){
System.err.println("Something went wrong reading file: " + textFilepath + ". The file may be damaged; please try re-downloading and reinstalling wizardry.");
e.printStackTrace();
}
}
/*
for(ArrayList<String> a : text){
for(String s : a){
System.out.println(s);
}
}
*/
}
private class Section {
String name;
int pageNumber;
int x, y;
int buttonId;
Section(String name, int pageNumber, int x, int y, int id){
this.name = name;
this.pageNumber = pageNumber;
this.x = x;
this.y = y;
this.buttonId = id;
GuiWizardHandbook.this.buttonList.add(new GuiButtonInvisible(id, x, y, GuiWizardHandbook.this.pageWidth, GuiWizardHandbook.this.fontRendererObj.FONT_HEIGHT));
}
void hideButton(){
((GuiButton)GuiWizardHandbook.this.buttonList.get(buttonId)).visible = false;
}
void drawContents(){
((GuiButton)GuiWizardHandbook.this.buttonList.get(buttonId)).visible = true;
GuiWizardHandbook.this.fontRendererObj.drawString(name, x, y, ((GuiButton)GuiWizardHandbook.this.buttonList.get(buttonId)).func_146115_a() ? 0xdd4c1d : 0);
int nameWidth = GuiWizardHandbook.this.fontRendererObj.getStringWidth(name);
String dotsAndNumber = " " + this.pageNumber;
while(GuiWizardHandbook.this.fontRendererObj.getStringWidth(dotsAndNumber) < GuiWizardHandbook.pageWidth - nameWidth - 2){
dotsAndNumber = "." + dotsAndNumber;
}
GuiWizardHandbook.this.fontRendererObj.drawString(dotsAndNumber, x + GuiWizardHandbook.pageWidth - GuiWizardHandbook.this.fontRendererObj.getStringWidth(dotsAndNumber), y, 0);
}
}
public void onGuiClosed()
{
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
/**
* Fired when a control is clicked. This is the equivalent of ActionListener.actionPerformed(ActionEvent e).
*/
protected void actionPerformed(GuiButton par1GuiButton){
if(par1GuiButton.enabled){
if(par1GuiButton.id == 0){
if(pageNumber < (text.size()-1)/2) pageNumber++;
}else if(par1GuiButton.id == 1){
if(pageNumber > 0) pageNumber--;
}else{
if(pageNumber == 1) pageNumber = (sections.get(par1GuiButton.id - 2).pageNumber-1)/2;
}
}
}
/**
* Args: left, top, width, height, pointX, pointY. Note: left, top are local to Gui, pointX, pointY are local to
* screen
*/
protected boolean isPointInRegion(int par1, int par2, int par3, int par4, int par5, int par6)
{
int k1 = this.width/2 - xSize/2;
int l1 = this.height/2 - this.ySize/2;
par5 -= k1;
par6 -= l1;
return par5 >= par1 - 1 && par5 < par1 + par3 + 1 && par6 >= par2 - 1 && par6 < par2 + par4 + 1;
}
protected void drawItemStackTooltip(ItemStack par1ItemStack, int par2, int par3)
{
List list = par1ItemStack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips);
for (int k = 0; k < list.size(); ++k)
{
if (k == 0)
{
list.set(k, par1ItemStack.getRarity().rarityColor + (String)list.get(k));
}
else
{
list.set(k, EnumChatFormatting.GRAY + (String)list.get(k));
}
}
FontRenderer font = par1ItemStack.getItem().getFontRenderer(par1ItemStack);
drawHoveringText(list, par2, par3, (font == null ? fontRendererObj : font));
}
protected void drawHoveringText(List par1List, int par2, int par3, FontRenderer font)
{
if (!par1List.isEmpty())
{
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
int k = 0;
Iterator iterator = par1List.iterator();
while (iterator.hasNext())
{
String s = (String)iterator.next();
int l = font.getStringWidth(s);
if (l > k)
{
k = l;
}
}
int i1 = par2 + 12;
int j1 = par3 - 12;
int k1 = 8;
if (par1List.size() > 1)
{
k1 += 2 + (par1List.size() - 1) * 10;
}
if (i1 + k > this.width)
{
i1 -= 28 + k;
}
if (j1 + k1 + 6 > this.height)
{
j1 = this.height - k1 - 6;
}
this.zLevel = 300.0F;
itemRender.zLevel = 300.0F;
int l1 = -267386864;
this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1);
this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1);
this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1);
this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1);
this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1);
int i2 = 1347420415;
int j2 = (i2 & 16711422) >> 1 | i2 & -16777216;
this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2);
this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2);
this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2);
this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2);
for(int k2 = 0; k2 < par1List.size(); ++k2){
String s1 = (String)par1List.get(k2);
font.drawStringWithShadow(s1, i1, j1, -1);
if(k2 == 0){
j1 += 2;
}
j1 += 10;
}
this.zLevel = 0.0F;
itemRender.zLevel = 0.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}
/**
* Draws a textured rectangle, taking the size of the image and the bit needed into account.
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted
* @param v The y position of the top left corner of the section of the image wanted
* @param width The width of the section
* @param height The height of the section
* @param textureWidth The width of the actual image.
* @param textureHeight The height of the actual image.
*/
public void drawTexturedRect(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight)
{
float f = 1F / (float)textureWidth;
float f1 = 1F / (float)textureHeight;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x), (double)(y + height), 0, (double)((float)(u) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), 0, (double)((float)(u + width) * f), (double)((float)(v + height) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y), 0, (double)((float)(u + width) * f), (double)((float)(v) * f1));
tessellator.addVertexWithUV((double)(x), (double)(y), 0, (double)((float)(u) * f), (double)((float)(v) * f1));
tessellator.draw();
}
/**
* Draws a textured rectangle, stretching the section of the image to fit the size given.
* @param x The x position of the rectangle
* @param y The y position of the rectangle
* @param u The x position of the top left corner of the section of the image wanted, expressed as a fraction of the image width
* @param v The y position of the top left corner of the section of the image wanted, expressed as a fraction of the image width
* @param finalWidth The width as rendered
* @param finalHeight The height as rendered
* @param width The width of the section, expressed as a fraction of the image width
* @param height The height of the section, expressed as a fraction of the image width
*/
public void drawTexturedStretchedRect(int x, int y, int u, int v, int finalWidth, int finalHeight, int width, int height)
{
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x), (double)(y + finalHeight), 0, u, v + height);
tessellator.addVertexWithUV((double)(x + finalWidth), (double)(y + finalHeight), 0, u + width, v + height);
tessellator.addVertexWithUV((double)(x + finalWidth), (double)(y), 0, u + width, v);
tessellator.addVertexWithUV((double)(x), (double)(y), 0, u, v);
tessellator.draw();
}
}
@@ -1,96 +1,97 @@
package electroblob.wizardry.client;
import java.util.ArrayList;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.util.ResourceLocation;
/**
* Font renderer that renders parts of strings surrounded by '#' (without quotes) in the SGA instead of normal text.
*
* @since Wizardry 1.1
*/
//@SideOnly(Side.CLIENT)
/** Font renderer that renders parts of strings surrounded by '#' (without quotes) in the SGA instead of normal text.
* @since Wizardry 1.1 */
@SideOnly(Side.CLIENT)
public class MixedFontRenderer extends FontRenderer {
public MixedFontRenderer(GameSettings p_i1035_1_, ResourceLocation p_i1035_2_, TextureManager p_i1035_3_,
boolean p_i1035_4_){
boolean p_i1035_4_) {
super(p_i1035_1_, p_i1035_2_, p_i1035_3_, p_i1035_4_);
}
@Override
public int drawString(String string, float x, float y, int colour, boolean shadow){
public int drawString(String string, int x, int y, int colour, boolean shadow){
int l = 0;
boolean sga = false;
while(string.indexOf('#') > -1){
String section = string.substring(0, string.indexOf('#'));
if(sga){
l += Minecraft.getMinecraft().standardGalacticFontRenderer.drawString(section, x, y, colour, shadow);
l += Minecraft.getMinecraft().standardGalacticFontRenderer.drawString(section, x, y, colour, shadow);
x += Minecraft.getMinecraft().standardGalacticFontRenderer.getStringWidth(section);
}else{
l += Minecraft.getMinecraft().fontRenderer.drawString(section, x, y, colour, shadow);
}else{
l += Minecraft.getMinecraft().fontRenderer.drawString(section, x, y, colour, shadow);
x += Minecraft.getMinecraft().fontRenderer.getStringWidth(section);
}
}
string = string.substring(string.indexOf('#') + 1);
sga = !sga;
}
if(sga){
l += Minecraft.getMinecraft().standardGalacticFontRenderer.drawString(string, x, y, colour, shadow);
}else{
l += Minecraft.getMinecraft().fontRenderer.drawString(string, x, y, colour, shadow);
}
return l;
}
l += Minecraft.getMinecraft().standardGalacticFontRenderer.drawString(string, x, y, colour, shadow);
}else{
l += Minecraft.getMinecraft().fontRenderer.drawString(string, x, y, colour, shadow);
}
return l;
}
@Override
public int getStringWidth(String string){
int l = 0;
boolean sga = false;
while(string.indexOf('#') > -1){
String section = string.substring(0, string.indexOf('#'));
if(sga){
l += Minecraft.getMinecraft().standardGalacticFontRenderer.getStringWidth(section);
}else{
l += Minecraft.getMinecraft().fontRenderer.getStringWidth(section);
}
l += Minecraft.getMinecraft().standardGalacticFontRenderer.getStringWidth(section);
}else{
l += Minecraft.getMinecraft().fontRenderer.getStringWidth(section);
}
string = string.substring(string.indexOf('#') + 1);
sga = !sga;
}
if(sga){
l += Minecraft.getMinecraft().standardGalacticFontRenderer.getStringWidth(string);
}else{
l += Minecraft.getMinecraft().fontRenderer.getStringWidth(string);
}
return l;
l += Minecraft.getMinecraft().standardGalacticFontRenderer.getStringWidth(string);
}else{
l += Minecraft.getMinecraft().fontRenderer.getStringWidth(string);
}
return l;
}
// This doesn't work the same way yet
@Override
public void drawSplitString(String string, int x, int y, int width, int colour){
public void drawSplitString(String string, int x, int y, int width, int colour){
if(string.contains("#")){
Minecraft.getMinecraft().standardGalacticFontRenderer.drawSplitString(string.substring(1), x, y, width,
colour);
}else{
Minecraft.getMinecraft().fontRenderer.drawSplitString(string, x, y, width, colour);
}
}
Minecraft.getMinecraft().standardGalacticFontRenderer.drawSplitString(string.substring(1), x, y, width, colour);
}else{
Minecraft.getMinecraft().fontRenderer.drawSplitString(string, x, y, width, colour);
}
}
}
@@ -0,0 +1,55 @@
package electroblob.wizardry.client;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
@SideOnly(Side.CLIENT)
public class MovingSoundEntity extends MovingSound
{
private final Entity source;
private float pitch = 0.0F;
public MovingSoundEntity(Entity entity, String soundName, float volume, float pitch, boolean repeat)
{
super(new ResourceLocation(soundName));
this.source = entity;
this.repeat = repeat;
this.volume = volume;
this.field_147663_c = pitch;
this.field_147665_h = 0;
}
/**
* Updates the JList with a new model.
*/
public void update()
{
if (this.source.isDead && repeat)
{
this.donePlaying = true;
}
else
{
this.xPosF = (float)this.source.posX;
this.yPosF = (float)this.source.posY;
this.zPosF = (float)this.source.posZ;
float f = MathHelper.sqrt_double(this.source.motionX * this.source.motionX + this.source.motionY * this.source.motionY + this.source.motionZ * this.source.motionZ);
// Is this something to do with the Doppler effect?
if ((double)f >= 0.01D)
{
this.pitch = MathHelper.clamp_float(this.pitch + 0.0025F, 0.0F, 1.0F);
this.volume = 0.0F + MathHelper.clamp_float(f, 0.0F, 0.5F) * 0.7F;
}
else
{
//this.pitch = 0.0F;
//this.volume = 0.0F;
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,121 +0,0 @@
package electroblob.wizardry.client;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.gui.GuiSpellDisplay;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.packet.PacketControlInput;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.registry.WizardrySounds;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.relauncher.Side;
/** Event handler class responsible for handling wizardry's controls. */
//@SideOnly(Side.CLIENT)
@Mod.EventBusSubscriber(Side.CLIENT)
public class WizardryControlHandler {
static boolean NkeyPressed = false;
static boolean BkeyPressed = false;
// Changed to a tick event to allow mouse button keybinds
// The 'lag' that happened previously was actually because the code only fired when a keyboard key was pressed!
@SubscribeEvent
public static void onTickEvent(TickEvent.ClientTickEvent event){
if(event.phase == TickEvent.Phase.END) return; // Only really needs to be once per tick
if(Wizardry.proxy instanceof ClientProxy){
EntityPlayer player = Minecraft.getMinecraft().player;
if(player != null){
ItemStack wand = getWandInUse(player);
if(wand == null) return;
if(ClientProxy.NEXT_SPELL.isKeyDown() && Minecraft.getMinecraft().inGameHasFocus){
if(!NkeyPressed){
NkeyPressed = true;
selectNextSpell(wand);
}
}else{
NkeyPressed = false;
}
if(ClientProxy.PREVIOUS_SPELL.isKeyDown() && Minecraft.getMinecraft().inGameHasFocus){
if(!BkeyPressed){
BkeyPressed = true;
// Packet building
selectPreviousSpell(wand);
}
}else{
BkeyPressed = false;
}
}
}
}
// Shift-scrolling to change spells
@SubscribeEvent
public static void onMouseEvent(MouseEvent event){
EntityPlayer player = Minecraft.getMinecraft().player;
ItemStack wand = getWandInUse(player);
if(wand == null) return;
if(Minecraft.getMinecraft().inGameHasFocus && !wand.isEmpty() && event.getDwheel() != 0 && player.isSneaking()
&& Wizardry.settings.shiftScrolling){
event.setCanceled(true);
int d = Wizardry.settings.reverseScrollDirection ? -event.getDwheel() : event.getDwheel();
if(d > 0){
selectNextSpell(wand);
}else if(d < 0){
selectPreviousSpell(wand);
}
}
}
private static ItemStack getWandInUse(EntityPlayer player){
ItemStack wand = player.getHeldItemMainhand();
// Only bother sending packets if the player is holding a spellcasting item with more than one spell slot
if(!(wand.getItem() instanceof ISpellCastingItem) || ((ISpellCastingItem)wand.getItem()).getSpells(wand).length < 2){
wand = player.getHeldItemOffhand();
if(!(wand.getItem() instanceof ISpellCastingItem) || ((ISpellCastingItem)wand.getItem()).getSpells(wand).length < 2) return null;
}
return wand;
}
private static void selectNextSpell(ItemStack wand){
// Packet building
IMessage msg = new PacketControlInput.Message(PacketControlInput.ControlType.NEXT_SPELL_KEY);
WizardryPacketHandler.net.sendToServer(msg);
// GUI switch animation
((ISpellCastingItem)wand.getItem()).selectNextSpell(wand); // Makes sure the spell is set immediately for the client
GuiSpellDisplay.playSpellSwitchAnimation(true);
Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.ITEM_WAND_SWITCH_SPELL, 1));
}
private static void selectPreviousSpell(ItemStack wand){
// Packet building
IMessage msg = new PacketControlInput.Message(PacketControlInput.ControlType.PREVIOUS_SPELL_KEY);
WizardryPacketHandler.net.sendToServer(msg);
// GUI switch animation
((ISpellCastingItem)wand.getItem()).selectPreviousSpell(wand); // Makes sure the spell is set immediately for the client
GuiSpellDisplay.playSpellSwitchAnimation(false);
Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.ITEM_WAND_SWITCH_SPELL, 1));
}
}
@@ -1,35 +0,0 @@
package electroblob.wizardry.client.audio;
import net.minecraft.client.audio.MovingSound;
import net.minecraft.entity.Entity;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
// Copied from MovingSoundMinecart; if it ever breaks between updates take a look at that.
//@SideOnly(Side.CLIENT)
public class MovingSoundEntity<T extends Entity> extends MovingSound {
protected final T source;
protected float distance = 0.0F;
public MovingSoundEntity(T entity, SoundEvent sound, SoundCategory category, float volume, float pitch, boolean repeat){
super(sound, category);
this.source = entity;
this.repeat = repeat;
this.volume = volume;
this.pitch = pitch;
this.repeatDelay = 0;
}
@Override
public void update(){
if(this.source.isDead){
this.donePlaying = true;
}else{
this.xPosF = (float)this.source.posX;
this.yPosF = (float)this.source.posY;
this.zPosF = (float)this.source.posZ;
}
}
}
@@ -1,94 +0,0 @@
package electroblob.wizardry.client.audio;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ISound;
import net.minecraft.util.ITickable;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import java.util.HashSet;
import java.util.Set;
/**
* Instances of this class represent a set of sounds which together form a looped sound: start, loop and end.
* Currently this is only used for continuous spell sounds in wizardry itself, but feel free to make your own
* implementations - this class will take care of the internals.
*
* @since Wizardry 4.2
* @author Electroblob
*/
// See MusicTicker, this is the same idea of just storing the sounds statically client-side and ticking them
@Mod.EventBusSubscriber(Side.CLIENT)
public abstract class SoundLoop implements ITickable {
private static final Set<SoundLoop> activeLoops = new HashSet<>();
private final ISound start;
private final ISound loop;
private final ISound end;
private boolean looping = false;
private boolean needsRemoving = false;
public SoundLoop(SoundEvent start, SoundEvent loop, SoundEvent end, SoundCategory category, ISoundFactory factory){
// The reason I've gone to the effort of having a factory for these is that we need SoundLoop to have control
// over which sounds are repeated and which aren't whilst keeping them private.
this.start = factory.create(start, category, false);
this.loop = factory.create(loop, category, true);
this.end = factory.create(end, category, false);
}
@Override
public void update(){
// Check every tick if the start sound is done playing and if so, start the loop sound
if(!looping && !Minecraft.getMinecraft().getSoundHandler().isSoundPlaying(start)){
Minecraft.getMinecraft().getSoundHandler().playSound(loop);
looping = true;
}
}
/** Stops the loop part of the sound immediately and starts playing the end part. This may be called from subclasses
* or externally depending on the implementation. */
// For continuous spell sounds it's internally
public void endLoop(){
Minecraft.getMinecraft().getSoundHandler().stopSound(start);
Minecraft.getMinecraft().getSoundHandler().stopSound(loop);
Minecraft.getMinecraft().getSoundHandler().playSound(end);
// Can't modify activeLoops directly since we'll probably be calling this method from update(), which is
// during iteration of activeLoops so it could cause a ConcurrentModificationException
this.markForRemoval();
}
/** Marks this sound loop to be removed next tick. */
protected void markForRemoval(){
this.needsRemoving = true;
}
// Static methods
public static void addLoop(SoundLoop loop){
activeLoops.add(loop);
// Do this here rather than in the constructor in case someone wants to play the loop later or reuse it
Minecraft.getMinecraft().getSoundHandler().playSound(loop.start);
}
@SubscribeEvent
public static void tick(TickEvent.ClientTickEvent event){
// Using the END phase means we can check for stopped sounds as soon as they are stopped (effectively),
// meaning we don't get the 'cut' between the start and loop sounds
// FIXME: Apparently this only works for dispensers. What the heck is the difference?!
if(event.phase == TickEvent.Phase.END){
activeLoops.forEach(SoundLoop::update);
activeLoops.removeIf(s -> s.needsRemoving);
}
}
@FunctionalInterface
public interface ISoundFactory {
ISound create(SoundEvent sound, SoundCategory category, boolean repeat);
}
}
@@ -1,117 +0,0 @@
package electroblob.wizardry.client.audio;
import electroblob.wizardry.data.DispenserCastingData;
import electroblob.wizardry.registry.WizardrySounds;
import electroblob.wizardry.spell.Spell;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.client.audio.PositionedSound;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
/** Abstract base class for sound loops associated with spells; see subclasses below for implementations. */
public abstract class SoundLoopSpell extends SoundLoop {
private final Spell spell;
public SoundLoopSpell(SoundEvent start, SoundEvent loop, SoundEvent end, ISoundFactory factory, Spell spell){
super(start, loop, end, WizardrySounds.SPELLS, factory);
this.spell = spell;
}
@Override
public void update(){
// This may be a bit overkill but I might as well put functionality in superclasses where possible
if(stillCasting(spell)){
// This can't called in the same tick as endLoop because otherwise, if the spell casting stops during the
// same tick as the transition to the loop sound it will try and stop the loop immediately after it has
// started - and for whatever reason, this causes the 'Channel null in method stop' error.
super.update();
}else{
endLoop();
}
}
protected abstract boolean stillCasting(Spell spell);
/** Implements a sound loop for continuous spells cast by entities. */
public static class SoundLoopSpellEntity extends SoundLoopSpell {
private final EntityLivingBase source;
public SoundLoopSpellEntity(SoundEvent start, SoundEvent loop, SoundEvent end, Spell spell, EntityLivingBase source, float volume, float pitch){
super(start, loop, end, (sound, category, repeat) -> new MovingSoundEntity<>(source, sound, category, volume, pitch, repeat), spell);
this.source = source;
}
@Override
protected boolean stillCasting(Spell spell){
return WizardryUtilities.isCasting(source, spell);
}
}
public static abstract class SoundLoopSpellPosition extends SoundLoopSpell {
public SoundLoopSpellPosition (SoundEvent start, SoundEvent loop, SoundEvent end, Spell spell,
double x, double y, double z, float sndVolume, float sndPitch){
// Huh, I actually found a use for a non-static initialiser block - hence the double curly brackets...
super(start, loop, end, (sound, category, r) -> new PositionedSound(sound, category){{
// ...et voila, we can just set protected fields as we please using external variables
this.xPosF = (float)x;
this.yPosF = (float)y;
this.zPosF = (float)z;
this.repeat = r;
this.volume = sndVolume;
this.pitch = sndPitch;
}}, spell);
}
}
/** Implements a sound loop for continuous spells cast by dispensers. */
public static class SoundLoopSpellDispenser extends SoundLoopSpellPosition {
private final TileEntityDispenser source;
public SoundLoopSpellDispenser(SoundEvent start, SoundEvent loop, SoundEvent end, Spell spell, World world,
double x, double y, double z, float sndVolume, float sndPitch){
super(start, loop, end, spell, x, y, z, sndVolume, sndPitch);
TileEntity tileentity = world.getTileEntity(new BlockPos(x, y, z));
if(tileentity instanceof TileEntityDispenser) this.source = (TileEntityDispenser)tileentity;
else throw new NullPointerException(String.format("Playing continuous spell sound: no dispenser found at %s, %s, %s", x, y, z));
}
@Override
protected boolean stillCasting(Spell spell){
return DispenserCastingData.get(source).currentlyCasting() == spell;
}
}
/** Implements a sound loop for continuous spells cast at a position (via commands). */
public static class SoundLoopSpellPosTimed extends SoundLoopSpellPosition {
private int timeLeft;
public SoundLoopSpellPosTimed(SoundEvent start, SoundEvent loop, SoundEvent end, Spell spell, int duration,
double x, double y, double z, float sndVolume, float sndPitch){
super(start, loop, end, spell, x, y, z, sndVolume, sndPitch);
this.timeLeft = duration;
}
@Override
public void update(){
super.update();
timeLeft--;
}
@Override
protected boolean stillCasting(Spell spell){
return timeLeft > 0;
}
}
}
@@ -1,449 +0,0 @@
package electroblob.wizardry.client.gui;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.data.SpellGlyphData;
import electroblob.wizardry.data.WizardData;
import electroblob.wizardry.item.IManaStoringItem;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.item.IWorkbenchItem;
import electroblob.wizardry.packet.PacketControlInput;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.registry.WizardrySounds;
import electroblob.wizardry.spell.Spell;
import electroblob.wizardry.tileentity.ContainerArcaneWorkbench;
import electroblob.wizardry.tileentity.TileEntityArcaneWorkbench;
import electroblob.wizardry.util.WandHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.GlStateManager.DestFactor;
import net.minecraft.client.renderer.GlStateManager.SourceFactor;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.relauncher.Side;
import org.lwjgl.input.Keyboard;
@Mod.EventBusSubscriber(Side.CLIENT)
public class GuiArcaneWorkbench extends GuiContainer {
private GuiButton applyBtn;
public static final ResourceLocation texture = new ResourceLocation(Wizardry.MODID,
"textures/gui/arcane_workbench.png");
private IInventory playerInventory;
private IInventory arcaneWorkbenchInventory;
private static final int TOOLTIP_WIDTH = 164;
/** We report the actual size of the GUI to Minecraft when a wand is in so JEI doesn't overdraw it.
* For calculations, we use the size without the tooltip, which is stored in this constant. */
private static final int MAIN_GUI_WIDTH = 176;
private static final int RUNE_LEFT = 38;
private static final int RUNE_TOP = 22;
private static final int RUNE_WIDTH = 100;
private static final int RUNE_HEIGHT = 100;
private static final int HALO_DIAMETER = 156;
private static final int TEXTURE_WIDTH = 512;
private static final int TEXTURE_HEIGHT = 256;
private int animationTimer = 0;
private static final int ANIMATION_DURATION = 20;
public GuiArcaneWorkbench(InventoryPlayer invPlayer, TileEntityArcaneWorkbench entity){
super(new ContainerArcaneWorkbench(invPlayer, entity));
this.playerInventory = invPlayer;
this.arcaneWorkbenchInventory = entity;
xSize = MAIN_GUI_WIDTH;
ySize = 220;
}
// Huh, didn't realise this method existed. Pretty neat.
@Override
public void updateScreen(){
if(animationTimer > 0) animationTimer--;
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks){
this.drawDefaultBackground();
GlStateManager.color(1, 1, 1, 1); // Just in case
Slot slot = this.inventorySlots.getSlot(ContainerArcaneWorkbench.CENTRE_SLOT);
// Tests if there is a wand in the workbench and edits the positioning accordingly
if(slot.getHasStack() && slot.getStack().getItem() instanceof IWorkbenchItem
&& ((IWorkbenchItem)slot.getStack().getItem()).showTooltip(slot.getStack())){
xSize = MAIN_GUI_WIDTH + TOOLTIP_WIDTH;
guiLeft = (this.width - this.xSize) / 2;
this.applyBtn.x = (this.width - TOOLTIP_WIDTH) / 2 + 64;
}else{
xSize = MAIN_GUI_WIDTH;
guiLeft = (this.width - this.xSize) / 2;
this.applyBtn.x = this.width / 2 + 64;
}
this.applyBtn.enabled = slot.getHasStack();
super.drawScreen(mouseX, mouseY, partialTicks);
// Required now, or item mouseover tooltips won't render.
this.renderHoveredToolTip(mouseX, mouseY);
}
@Override
public void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY){
GlStateManager.color(1, 1, 1, 1);
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
// Animation
// Grey background
DrawingUtils.drawTexturedRect(guiLeft + RUNE_LEFT, guiTop + RUNE_TOP, MAIN_GUI_WIDTH + TOOLTIP_WIDTH, 0,
RUNE_WIDTH, RUNE_HEIGHT, TEXTURE_WIDTH, TEXTURE_HEIGHT);
// Yellow 'halo'
if(animationTimer > 0){
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
int x = guiLeft + RUNE_LEFT + RUNE_WIDTH/2;
int y = guiTop + RUNE_TOP + RUNE_HEIGHT/2;
float scale = (animationTimer + partialTicks)/ANIMATION_DURATION;
scale = (float)(1 - Math.pow(1-scale, 1.4f)); // Makes it slower at the start and speed up
GlStateManager.scale(scale, scale, 1);
GlStateManager.translate(x/scale, y/scale, 0);
DrawingUtils.drawTexturedRect(-HALO_DIAMETER /2, -HALO_DIAMETER /2, MAIN_GUI_WIDTH + TOOLTIP_WIDTH, RUNE_HEIGHT,
HALO_DIAMETER, HALO_DIAMETER, TEXTURE_WIDTH, TEXTURE_HEIGHT);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
// Main inventory
DrawingUtils.drawTexturedRect(guiLeft, guiTop, 0, 0, MAIN_GUI_WIDTH, ySize, TEXTURE_WIDTH, TEXTURE_HEIGHT);
float opacity = (animationTimer + partialTicks)/ANIMATION_DURATION;
// Changing slots
for(int i = 0; i < ContainerArcaneWorkbench.CRYSTAL_SLOT; i++){
Slot slot = this.inventorySlots.getSlot(i);
if(slot.xPos >= 0 && slot.yPos >= 0){
// Slot background
DrawingUtils.drawTexturedRect(guiLeft + slot.xPos - 10, guiTop + slot.yPos - 10, 0, 220, 36, 36, TEXTURE_WIDTH, TEXTURE_HEIGHT);
// Slot animation
// IDEA: Somehow replace with intelligent check for whether the spell actually got applied
if(animationTimer > 0 && slot.getHasStack()){
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1, 1, 1, opacity);
DrawingUtils.drawTexturedRect(guiLeft + slot.xPos - 10, guiTop + slot.yPos - 10, 36, 220, 36, 36, TEXTURE_WIDTH, TEXTURE_HEIGHT);
GlStateManager.color(1, 1, 1, 1);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
}
}
// Crystal + upgrade slot animations
if(animationTimer > 0){
Slot crystals = this.inventorySlots.getSlot(ContainerArcaneWorkbench.CRYSTAL_SLOT);
Slot upgrades = this.inventorySlots.getSlot(ContainerArcaneWorkbench.UPGRADE_SLOT);
if(crystals.getHasStack()){
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1, 1, 1, opacity);
DrawingUtils.drawTexturedRect(guiLeft + crystals.xPos - 8, guiTop + crystals.yPos - 8,
MAIN_GUI_WIDTH + TOOLTIP_WIDTH + RUNE_WIDTH, 0, 32, 32, TEXTURE_WIDTH, TEXTURE_HEIGHT);
GlStateManager.color(1, 1, 1, 1);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
if(upgrades.getHasStack()){
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1, 1, 1, opacity);
DrawingUtils.drawTexturedRect(guiLeft + upgrades.xPos - 8, guiTop + upgrades.yPos - 8,
MAIN_GUI_WIDTH + TOOLTIP_WIDTH + RUNE_WIDTH, 0, 32, 32, TEXTURE_WIDTH, TEXTURE_HEIGHT);
GlStateManager.color(1, 1, 1, 1);
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
}
// Tooltip only drawn if there is a wand
if(this.inventorySlots.getSlot(ContainerArcaneWorkbench.CENTRE_SLOT).getHasStack()){
ItemStack stack = this.inventorySlots.getSlot(ContainerArcaneWorkbench.CENTRE_SLOT).getStack();
if(!(stack.getItem() instanceof IWorkbenchItem)){
Wizardry.logger.warn("Invalid item in central slot of arcane workbench, how did that get there?!");
return;
}
if(((IWorkbenchItem)stack.getItem()).showTooltip(stack)){
// Tooltip box
DrawingUtils.drawTexturedRect(guiLeft + MAIN_GUI_WIDTH, guiTop, MAIN_GUI_WIDTH, 0, TOOLTIP_WIDTH, ySize, TEXTURE_WIDTH, TEXTURE_HEIGHT);
int y = guiTop + 20;
if(stack.getItem() instanceof IManaStoringItem && ((IManaStoringItem)stack.getItem()).showManaInWorkbench(this.mc.player, stack)){
y += 14;
}
if(stack.getItem() instanceof ISpellCastingItem && ((ISpellCastingItem)stack.getItem()).showSpellsInWorkbench(this.mc.player, stack)){
Spell[] spells = ((ISpellCastingItem)stack.getItem()).getSpells(stack);
GlStateManager.enableBlend();
for(Spell spell : spells){
boolean discovered = true;
if(!this.mc.player.isCreative() && WizardData.get(this.mc.player) != null){
discovered = WizardData.get(this.mc.player).hasSpellBeenDiscovered(spell);
}
// As of Wizardry 1.2, the icons have been split off into their own texture files to allow for add-on
// mods to add their own.
Minecraft.getMinecraft().renderEngine
.bindTexture(discovered ? spell.getElement().getIcon() : Element.MAGIC.getIcon());
// Renders the little element icon
DrawingUtils.drawTexturedRect(guiLeft + MAIN_GUI_WIDTH + 5, y, 8, 8);
y += 10;
}
}
GlStateManager.disableBlend();
int x = 0;
y += 16;
// Look how much shorter this is with the WandHelper class!
for(Item item : WandHelper.getSpecialUpgrades()){
int level = WandHelper.getUpgradeLevel(stack, item);
if(level > 0){
ItemStack stack1 = new ItemStack(item, level);
GlStateManager.enableDepth();
this.itemRender.renderItemAndEffectIntoGUI(stack1, guiLeft + MAIN_GUI_WIDTH + 6 + x, y);
this.itemRender.renderItemOverlayIntoGUI(this.fontRenderer, stack1, guiLeft + MAIN_GUI_WIDTH + 6 + x, y,
null);
x += 18;
GlStateManager.disableDepth();
}
}
}
}
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
// Fixes the bug that caused the slot highlight to render opaque. I don't know why it works, it just works!
GlStateManager.disableBlend();
GlStateManager.enableAlpha();
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY){
GlStateManager.color(1, 1, 1, 1); // Just in case
this.fontRenderer
.drawString(this.arcaneWorkbenchInventory.hasCustomName() ? this.arcaneWorkbenchInventory.getName()
: I18n.format(this.arcaneWorkbenchInventory.getName()), 8, 6, 4210752);
this.fontRenderer.drawString(this.playerInventory.hasCustomName() ? this.playerInventory.getName()
: I18n.format(this.playerInventory.getName()), 8, this.ySize - 96 + 2, 4210752);
if(this.inventorySlots.getSlot(ContainerArcaneWorkbench.CENTRE_SLOT).getHasStack()){
ItemStack stack = this.inventorySlots.getSlot(ContainerArcaneWorkbench.CENTRE_SLOT).getStack();
if(!(stack.getItem() instanceof IWorkbenchItem)){
Wizardry.logger.warn("Invalid item in central slot of arcane workbench, how did that get there?!");
return;
}
if(((IWorkbenchItem)stack.getItem()).showTooltip(stack)){
int y = 6;
this.fontRenderer.drawStringWithShadow("\u00A7f" + stack.getDisplayName(), MAIN_GUI_WIDTH + 6, y, 0);
if(stack.getItem() instanceof IManaStoringItem && ((IManaStoringItem)stack.getItem()).showManaInWorkbench(this.mc.player, stack)){
y += 14;
this.fontRenderer.drawStringWithShadow(
"\u00A77" + I18n.format("container." + Wizardry.MODID + ":arcane_workbench.mana")
+ " " + ((IManaStoringItem)stack.getItem()).getMana(stack) + "/"
+ ((IManaStoringItem)stack.getItem()).getManaCapacity(stack),
MAIN_GUI_WIDTH + 6, y, 0);
}
y += 14;
if(stack.getItem() instanceof ISpellCastingItem && ((ISpellCastingItem)stack.getItem()).showSpellsInWorkbench(this.mc.player, stack)){
Spell[] spells = ((ISpellCastingItem)stack.getItem()).getSpells(stack);
for(Spell spell : spells){
boolean discovered = true;
if(!this.mc.player.isCreative() && WizardData.get(this.mc.player) != null){
discovered = WizardData.get(this.mc.player).hasSpellBeenDiscovered(spell);
}
if(discovered){
this.fontRenderer.drawStringWithShadow(spell.getDisplayNameWithFormatting(), MAIN_GUI_WIDTH + 16, y, 0);
}else{
this.mc.standardGalacticFontRenderer.drawStringWithShadow(
"\u00A79" + SpellGlyphData.getGlyphName(spell, this.mc.world), MAIN_GUI_WIDTH + 16, y, 0);
}
y += 10;
}
}
if(WandHelper.getTotalUpgrades(stack) > 0){
y += 6;
this.fontRenderer.drawStringWithShadow("\u00A7f" + I18n.format("container."
+ Wizardry.MODID + ":arcane_workbench.upgrades"), MAIN_GUI_WIDTH + 6, y, 0);
int x = 0;
y += 10;
// Wand upgrade tooltips
for(Item item : WandHelper.getSpecialUpgrades()){
int level = WandHelper.getUpgradeLevel(stack, item);
if(level > 0){
// The javadoc for isPointInRegion is ambiguous; what it means is that the REGION is
// relative to the GUI but the POINT isn't.
if(isPointInRegion(MAIN_GUI_WIDTH + 6 + x, y, 16, 16, mouseX, mouseY)){
ItemStack stack1 = new ItemStack(item, level);
this.renderToolTip(stack1, mouseX - guiLeft, mouseY - guiTop);
}
x += 18;
}
}
}
}
}
}
@Override
public void initGui(){
this.mc.player.openContainer = this.inventorySlots;
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.buttonList.add(this.applyBtn = new GuiButtonApply(0, this.width / 2 + 64, this.height / 2 + 3));
}
@Override
public void onGuiClosed(){
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
@Override
protected void actionPerformed(GuiButton button){
if(button.enabled){
if(button.id == 0){
// Packet building
IMessage msg = new PacketControlInput.Message(PacketControlInput.ControlType.APPLY_BUTTON);
WizardryPacketHandler.net.sendToServer(msg);
// Sound
Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(
WizardrySounds.BLOCK_ARCANE_WORKBENCH_SPELLBIND, 1));
// Animation
animationTimer = 20;
}
}
}
private class GuiButtonApply extends GuiButton {
public GuiButtonApply(int id, int x, int y){
super(id, x, y, 16, 16, I18n.format("container." + Wizardry.MODID + ":arcane_workbench.apply"));
}
@Override
public void drawButton(Minecraft minecraft, int mouseX, int mouseY, float partialTicks){
// Whether the button is highlighted
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
int k = 72;
int l = 220;
//int colour = 14737632;
if(this.enabled){
if(this.hovered){
k += this.width * 2;
//colour = 16777120;
}
}else{
k += this.width;
//colour = 10526880;
}
DrawingUtils.drawTexturedRect(this.x, this.y, k, l, this.width, this.height, 512, 256);
//this.drawCenteredString(minecraft.fontRenderer, this.displayString, this.x + this.width / 2,
// this.y + (this.height - 8) / 2, colour);
}
}
@SubscribeEvent
public static void onTextureStitchEvent(TextureStitchEvent.Pre event){
event.getMap().registerSprite(ContainerArcaneWorkbench.EMPTY_SLOT_CRYSTAL);
event.getMap().registerSprite(ContainerArcaneWorkbench.EMPTY_SLOT_UPGRADE);
}
}
@@ -1,18 +0,0 @@
package electroblob.wizardry.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
//@SideOnly(Side.CLIENT)
public class GuiButtonInvisible extends GuiButton {
public GuiButtonInvisible(int id, int x, int y, int width, int height){
super(id, x, y, width, height, "");
}
@Override
public void drawButton(Minecraft minecraft, int mouseX, int mouseY, float partialTicks){
this.hovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
}
}
@@ -1,90 +0,0 @@
package electroblob.wizardry.client.gui;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.item.ItemArtefact;
import electroblob.wizardry.packet.PacketControlInput;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.registry.Spells;
import electroblob.wizardry.registry.WizardryItems;
import electroblob.wizardry.spell.Resurrection;
import electroblob.wizardry.util.SpellModifiers;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiGameOver;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
@Mod.EventBusSubscriber(Side.CLIENT)
public class GuiButtonResurrect extends GuiButton {
private static int timeSinceDeath = -1;
private final String translationKey;
public GuiButtonResurrect(int id, int x, int y, String translationKey){
super(id, x, y, I18n.format(translationKey + "_wait", Resurrection.getRemainingWaitTime(timeSinceDeath)));
this.translationKey = translationKey;
}
@Override
public void drawButton(Minecraft mc, int mouseX, int mouseY, float partialTicks){
int waitTime = Resurrection.getRemainingWaitTime(timeSinceDeath);
this.enabled = waitTime == 0;
this.displayString = I18n.format(translationKey + (waitTime == 0 ? "_ready" : "_wait"), waitTime);
super.drawButton(mc, mouseX, mouseY, partialTicks);
}
// Event handlers
@SubscribeEvent
public static void onClientTickEvent(TickEvent.ClientTickEvent event){
if(event.phase == TickEvent.Phase.START && timeSinceDeath >= 0) timeSinceDeath++;
}
@SubscribeEvent
public static void onGuiScreenInitEvent(GuiScreenEvent.InitGuiEvent event){
if(event.getGui() instanceof GuiGameOver && ItemArtefact.isArtefactActive(Minecraft.getMinecraft().player, WizardryItems.amulet_resurrection)
&& WizardryUtilities.getHotbar(Minecraft.getMinecraft().player).stream().anyMatch(s -> Resurrection.canStackResurrect(s, Minecraft.getMinecraft().player))){
event.getButtonList().add(new GuiButtonResurrect(event.getButtonList().size(), event.getGui().width / 2 - 100,
event.getGui().height / 4 + 120, "spell." + Spells.resurrection.getRegistryName() + ".button"));
timeSinceDeath = 0;
}
}
@SubscribeEvent
public static void onGuiScreenActionPerformedEvent(GuiScreenEvent.ActionPerformedEvent event){
if(event.getGui() instanceof GuiGameOver){
ItemStack stack = WizardryUtilities.getHotbar(Minecraft.getMinecraft().player).stream()
.filter(s -> Resurrection.canStackResurrect(s, Minecraft.getMinecraft().player)).findFirst().orElse(null);
if(stack != null){
if(event.getButton() instanceof GuiButtonResurrect && timeSinceDeath >= 0){
// Cast resurrection on the client player and notify the server to do the same
// ISpellCastingItem#canCast already checked in Resurrection#canStackResurrect
((ISpellCastingItem)stack.getItem()).cast(stack, Spells.resurrection, Minecraft.getMinecraft().player, EnumHand.MAIN_HAND, 0, new SpellModifiers());
WizardryPacketHandler.net.sendToServer(new PacketControlInput.Message(PacketControlInput.ControlType.RESURRECT_BUTTON));
}else if(!Minecraft.getMinecraft().world.getGameRules().getBoolean("keepInventory")){
// Any other button drops the wand (N.B. this should be inside the stack != null check or it'll send
// packets unnecessarily and generate incorrect warnings
WizardryPacketHandler.net.sendToServer(new PacketControlInput.Message(PacketControlInput.ControlType.CANCEL_RESURRECT));
}
timeSinceDeath = -1;
}
}
}
}
@@ -1,37 +0,0 @@
package electroblob.wizardry.client.gui;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ContainerWorkbench;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
/** Crafting table GUI that doesn't require a crafting table container object. */
public class GuiPortableCrafting extends GuiContainer {
private static final ResourceLocation craftingTableGuiTextures = new ResourceLocation(
"textures/gui/container/crafting_table.png");
public GuiPortableCrafting(InventoryPlayer p_i1084_1_, World p_i1084_2_, BlockPos pos){
super(new ContainerWorkbench(p_i1084_1_, p_i1084_2_, pos));
}
/**
* Draw the foreground layer for the GuiContainer (everything in front of the items)
*/
protected void drawGuiContainerForegroundLayer(int p_146979_1_, int p_146979_2_){
this.fontRenderer.drawString(I18n.format("container.crafting"), 28, 6, 4210752);
this.fontRenderer.drawString(I18n.format("container.inventory"), 8, this.ySize - 96 + 2, 4210752);
}
protected void drawGuiContainerBackgroundLayer(float p_146976_1_, int p_146976_2_, int p_146976_3_){
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(craftingTableGuiTextures);
int k = (this.width - this.xSize) / 2;
int l = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
}
}
@@ -1,121 +0,0 @@
package electroblob.wizardry.client.gui;
import com.google.common.collect.ImmutableMap;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.constants.Tier;
import electroblob.wizardry.data.SpellGlyphData;
import electroblob.wizardry.data.WizardData;
import electroblob.wizardry.registry.Spells;
import electroblob.wizardry.registry.WizardrySounds;
import electroblob.wizardry.spell.Spell;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import java.util.Map;
public class GuiSpellBook extends GuiScreen {
private int xSize, ySize;
private Spell spell;
private static final Map<Tier, ResourceLocation> textures = ImmutableMap.of(
Tier.NOVICE, new ResourceLocation(Wizardry.MODID, "textures/gui/spell_book_novice.png"),
Tier.APPRENTICE, new ResourceLocation(Wizardry.MODID, "textures/gui/spell_book_apprentice.png"),
Tier.ADVANCED, new ResourceLocation(Wizardry.MODID, "textures/gui/spell_book_advanced.png"),
Tier.MASTER, new ResourceLocation(Wizardry.MODID, "textures/gui/spell_book_master.png"));
public GuiSpellBook(Spell spell){
super();
xSize = 288;
ySize = 180;
this.spell = spell;
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int par1, int par2, float par3){
int xPos = this.width / 2 - xSize / 2;
int yPos = this.height / 2 - this.ySize / 2;
EntityPlayer player = Minecraft.getMinecraft().player;
boolean discovered = true;
if(Wizardry.settings.discoveryMode && !player.isCreative() && WizardData.get(player) != null
&& !WizardData.get(player).hasSpellBeenDiscovered(spell)){
discovered = false;
}
GlStateManager.color(1, 1, 1, 1); // Just in case
// Draws spell illustration on opposite page, underneath the book so it shows through the hole.
Minecraft.getMinecraft().renderEngine.bindTexture(discovered ? spell.getIcon() : Spells.none.getIcon());
DrawingUtils.drawTexturedRect(xPos + 146, yPos + 20, 0, 0, 128, 128, 128, 128);
Minecraft.getMinecraft().renderEngine.bindTexture(textures.get(spell.getTier()));
DrawingUtils.drawTexturedRect(xPos, yPos, 0, 0, xSize, ySize, xSize, 256);
super.drawScreen(par1, par2, par3);
if(discovered){
this.fontRenderer.drawString(spell.getDisplayName(), xPos + 17, yPos + 15, 0);
this.fontRenderer.drawString(spell.getType().getDisplayName(), xPos + 17, yPos + 26, 0x777777);
}else{
this.mc.standardGalacticFontRenderer.drawString(SpellGlyphData.getGlyphName(spell, player.world), xPos + 17,
yPos + 15, 0);
this.mc.standardGalacticFontRenderer.drawString(spell.getType().getDisplayName(), xPos + 17, yPos + 26,
0x777777);
}
//this.fontRenderer.drawString("-------------------", xPos + 17, yPos + 35, 0);
if(spell.getTier() == Tier.NOVICE){
// Basic is usually white but this doesn't show up.
this.fontRenderer.drawString("Tier: \u00A77" + Tier.NOVICE.getDisplayName(), xPos + 17, yPos + 45, 0);
}else{
this.fontRenderer.drawString("Tier: " + spell.getTier().getDisplayNameWithFormatting(), xPos + 17, yPos + 45, 0);
}
String element = "Element: " + spell.getElement().getFormattingCode() + spell.getElement().getDisplayName();
if(!discovered) element = "Element: ?";
this.fontRenderer.drawString(element, xPos + 17, yPos + 57, 0);
String manaCost = "Mana Cost: " + spell.getCost();
if(spell.isContinuous) manaCost = "Mana Cost: " + spell.getCost() + "/second";
if(!discovered) manaCost = "Mana Cost: ?";
this.fontRenderer.drawString(manaCost, xPos + 17, yPos + 69, 0);
if(discovered){
this.fontRenderer.drawSplitString(spell.getDescription(), xPos + 17, yPos + 83, 118, 0);
}else{
this.mc.standardGalacticFontRenderer.drawSplitString(
SpellGlyphData.getGlyphDescription(spell, player.world), xPos + 17, yPos + 83, 118, 0);
}
}
public void initGui(){
super.initGui();
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.MISC_BOOK_OPEN, 1));
}
public void onGuiClosed(){
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
@Override
public boolean doesGuiPauseGame(){
return Wizardry.settings.booksPauseGame;
}
}
@@ -1,589 +0,0 @@
package electroblob.wizardry.client.gui;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import electroblob.wizardry.Settings;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.ClientProxy;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.client.MixedFontRenderer;
import electroblob.wizardry.data.SpellGlyphData;
import electroblob.wizardry.data.WizardData;
import electroblob.wizardry.item.ISpellCastingItem;
import electroblob.wizardry.registry.Spells;
import electroblob.wizardry.registry.WizardryPotions;
import electroblob.wizardry.spell.Spell;
import electroblob.wizardry.util.WandHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.GlStateManager.DestFactor;
import net.minecraft.client.renderer.GlStateManager.SourceFactor;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;
@Mod.EventBusSubscriber(Side.CLIENT)
public class GuiSpellDisplay {
private static final ResourceLocation INDEX = new ResourceLocation(Wizardry.MODID, "textures/gui/spell_hud/_index.json");
/** A map which stores all loaded HUD skin objects. This gets wiped on resource pack reload and repopulated with
* mappings as specified by {@code _index.json} (these stack between resource packs). The keys in the map correspond
* to the keys in {@code _index.json}, and are sorted in that order, with skins belonging to resource packs sorted
* from lowest to highest priority. The skins in the base mod will therefore always be first. (It should be noted,
* however, that in the gui itself the skins are always sorted in alphabetical order for some reason.) */
private static final Map<String, Skin> skins = new LinkedHashMap<>(14); // 14 is the number of skins packaged with the mod
private static final Gson gson = new Gson();
/** Width and height of the spell icon (very unlikely to change!) */
private static final int SPELL_ICON_SIZE = 32;
/** Number of ticks the spell switching animation plays for. */
private static final int SPELL_SWITCH_TIME = 4;
/** Scale of the next/previous spell names. */
private static final float SPELL_NAME_SCALE = 0.5f;
/** Opacity of the next/previous spell names, as a fraction. */
private static final float SPELL_NAME_OPACITY = 0.3f;
private static final int HALF_HOTBAR_WIDTH = 97; // Half the width of the hotbar, plus a bit for clearance
private static final int OFFHAND_SLOT_WIDTH = 29; // Width of the offhand slot plus the gap between it and the hotbar
/** Controls the spell switching animation. Positive when switching to the next spell, negative when switching to
* the previous spell. Decremented in magnitude by 1 each tick until it reaches 0 again. */
private static int switchTimer = 0;
/**
* Starts the spell switching animation.
* @param next True to switch to the next spell, false for the previous spell.
*/
public static void playSpellSwitchAnimation(boolean next){
switchTimer = next ? SPELL_SWITCH_TIME : -SPELL_SWITCH_TIME;
}
/** Returns an unmodifiable set of the string keys for all of the loaded spell HUD skins. */
public static Set<String> getSkinKeys(){
return Collections.unmodifiableSet(skins.keySet());
}
/** Returns an unmodifiable view of the loaded spell HUD skins map. */
public static Map<String, Skin> getSkins(){
return Collections.unmodifiableMap(skins);
}
/** Returns the skin that corresponds to the given key. */
public static Skin getSkin(String key){
return skins.get(key);
}
// Normally when extending Gui, you'd have to have an instance to access its methods. However, we're not actually
// using any of them, so this class may as well not bother and just be a static event handler. Neat!
@SubscribeEvent
public static void draw(RenderGameOverlayEvent event){
Minecraft mc = Minecraft.getMinecraft();
EntityPlayer player = mc.player;
if(player.isSpectator()) return; // Spectators shouldn't have the spell HUD!
// If the player has a wand in each hand, only displays for the one in the main hand.
ItemStack wand = player.getHeldItemMainhand();
boolean mainHand = true;
if(!(wand.getItem() instanceof ISpellCastingItem && ((ISpellCastingItem)wand.getItem()).showSpellHUD(player, wand))){
wand = player.getHeldItemOffhand();
mainHand = false;
// If the player isn't holding a spellcasting item that shows the HUD, then nothing else needs to be done.
if(!(wand.getItem() instanceof ISpellCastingItem && ((ISpellCastingItem)wand.getItem()).showSpellHUD(player, wand))) return;
}
int width = event.getResolution().getScaledWidth();
int height = event.getResolution().getScaledHeight();
boolean flipX = Wizardry.settings.spellHUDPosition.flipX;
boolean flipY = Wizardry.settings.spellHUDPosition.flipY;
if(Wizardry.settings.spellHUDPosition.dynamic){
// ............. | This bit is true if the wand is on the left, false if it is on the right
flipX = flipX == ((mainHand ? player.getPrimaryHand() : player.getPrimaryHand().opposite()) == EnumHandSide.LEFT);
}
Skin skin = skins.get(Wizardry.settings.spellHUDSkin);
if(skin == null){
Wizardry.logger.info("The spell HUD skin '" + Wizardry.settings.spellHUDSkin + "' specified in the config"
+ " did not match any of the loaded skins; using the default skin as a fallback.");
skin = skins.get(Settings.DEFAULT_HUD_SKIN_KEY);
if(skin == null){
Wizardry.logger.warn("The default spell HUD skin is missing! A resource pack must have overridden it"
+ " with an invalid JSON file (default.json), please try again without any resource packs.");
return;
}
}
GlStateManager.pushMatrix();
// 'Origin' of the spell hud (bottom left corner of the actual texture, always in the corner of the screen)
int x = flipX ? width : 0;
int y = flipY ? 0: height;
// The space available to render the spell HUD
float xSpace = (float)(width/2 - HALF_HOTBAR_WIDTH);
if(!player.getHeldItemOffhand().isEmpty()
// Tests whether the offhand slot is rendered on the same side of the hotbar as the spell HUD
&& (player.getPrimaryHand() == EnumHandSide.LEFT) == flipX){
xSpace -= OFFHAND_SLOT_WIDTH;
}
// If the skin is at the bottom and the screen width is too small, scale it to avoid the hotbar and offhand
if(!flipY && skin.getWidth() > xSpace){ // width/2 - 91 - 29 taken from GuiInGame line 547
float scale = xSpace / skin.getWidth();
GlStateManager.scale(scale, scale, 1);
x = MathHelper.ceil(x/scale);
y = MathHelper.ceil(y/scale);
}
Spell spell = WandHelper.getCurrentSpell(wand);
int cooldown = WandHelper.getCurrentCooldown(wand);
int maxCooldown = WandHelper.getCurrentMaxCooldown(wand);
if(event.getType() == RenderGameOverlayEvent.ElementType.TEXT){
float animationProgress = Math.signum(switchTimer) * ((SPELL_SWITCH_TIME - Math.abs(switchTimer) +
event.getPartialTicks()) / SPELL_SWITCH_TIME);
String prevSpellName = getFormattedSpellName(WandHelper.getPreviousSpell(wand), player, WandHelper.getPreviousCooldown(wand));
String spellName = getFormattedSpellName(spell, player, cooldown);
String nextSpellName = getFormattedSpellName(WandHelper.getNextSpell(wand), player, WandHelper.getNextCooldown(wand));
skin.drawText(x, y, flipX, flipY, prevSpellName, spellName, nextSpellName, animationProgress);
}else if(event.getType() == RenderGameOverlayEvent.ElementType.HOTBAR){
boolean discovered = true;
if(!player.isCreative() && WizardData.get(player) != null){
discovered = WizardData.get(player).hasSpellBeenDiscovered(spell);
}
ResourceLocation icon = discovered ? spell.getIcon() : Spells.none.getIcon();
float progress = 1;
// Doesn't really matter what progress is when in creative, but we might as well avoid the calculation.
if(!player.isCreative() && !spell.isContinuous){
// Subtracted partial tick time to make it smoother
progress = maxCooldown == 0 ? 1 : (maxCooldown - (float)cooldown + event.getPartialTicks()) / maxCooldown;
}
skin.drawBackground(x, y, flipX, flipY, icon, progress, player.isCreative());
}
GlStateManager.popMatrix();
}
/**
* Gets the name of the given spell, with formatting added according to its cooldown and whether the given player
* has discovered it.
* @param spell The spell to get the name of.
* @param player The player to test for having discovered the given spell.
* @param cooldown The spell's current cooldown.
* @return The spell name, with relevant formatting added, for use with the {@link MixedFontRenderer}.
*/
private static String getFormattedSpellName(Spell spell, EntityPlayer player, int cooldown){
boolean discovered = true;
if(!player.isCreative() && WizardData.get(player) != null){
discovered = WizardData.get(player).hasSpellBeenDiscovered(spell);
}
// Makes spells greyed out if they are in cooldown or if the player has the arcane jammer effect
String format = cooldown > 0 || player.isPotionActive(WizardryPotions.arcane_jammer) ? "\u00A78" : spell.getElement().getFormattingCode();
if(!discovered) format = "\u00A79";
String name = discovered ? spell.getDisplayName() : SpellGlyphData.getGlyphName(spell, player.world);
name = format + name;
if(!discovered) name = "#" + name + "#";
return name;
}
@SubscribeEvent
public static void onLivingUpdateEvent(LivingUpdateEvent event){
if(event.getEntity() == Minecraft.getMinecraft().player){ // Makes sure this only gets called once each tick.
if(switchTimer > 0) switchTimer--;
else if(switchTimer < 0) switchTimer++;
}
}
/** Called from preInit in the main mod class (via the proxies) to initialise the HUD skins, and again on each
* resource reload. */
public static void loadSkins(IResourceManager manager){
try {
List<IResource> indexFiles = manager.getAllResources(INDEX);
skins.clear(); // Wipes the skins map before repopulating it
for(IResource indexFile : indexFiles){
BufferedReader reader = new BufferedReader(new InputStreamReader(indexFile.getInputStream()));
JsonElement je = gson.fromJson(reader, JsonElement.class);
JsonObject json = je.getAsJsonObject();
// Need to iterate over these since we don't know what they're called or how many there are
for(Entry<String, JsonElement> entry : json.entrySet()){
String key = entry.getKey(); // Find out what each element is called, this will be the skins map key
// It's a good idea to use JsonUtils because it produces more helpful error messages (that pack
// makers should understand).
JsonObject skinData = JsonUtils.getJsonObject(json, key);
String[] splitName = ResourceLocation.splitObjectName(JsonUtils.getString(skinData, "texture"));
ResourceLocation texture = new ResourceLocation(splitName[0], "textures/" + splitName[1] + ".png");
splitName = ResourceLocation.splitObjectName(JsonUtils.getString(skinData, "metadata"));
ResourceLocation metadata = new ResourceLocation(splitName[0], "textures/" + splitName[1] + ".json");
// The nice thing about this is it overwrites the existing mapping, and since the index files are in
// ascending order of resource pack priority, this means resource packs can override existing skins
// by specifying one with the same key.
skins.put(key, new Skin(texture, metadata));
}
}
} catch (IOException e){
// If an exception is thrown, chances are the resource pack did not have a spell_hud folder, so nothing
// else needs to be done.
Wizardry.logger.error("Error reading spell HUD skin index file: ", e);
}
}
/**
* Instances of this class represent individual HUD skins, complete with texture and all necessary metadata. This
* class serves to separate the logic behind the spell HUD from its actual rendering.
* All information and processing done within this class relates only to the actual drawing; spells and such like
* must be queried outside of this class and fed into the methods as appropriate.
*
* @author Electroblob
* @since Wizardry 4.2
*/
public static class Skin {
/** The texture file for this skin. */
private final ResourceLocation texture;
/** The display name of the skin in the config menu. */
private String name;
/** The description of the skin shown when its button is hovered over in the config menu. */
private String description;
/** Width of the entire spell HUD. */
private int width;
/** Height of the entire spell HUD. */
private int height;
/** Whether the entire HUD is flipped when on the right-hand side of the screen. If this is false, the HUD will
* still appear on the right-hand side of the screen, but in the same orientation as on the left-hand side. */
private boolean mirrorX;
/** Whether the entire HUD is flipped when at the top of the screen. If this is false, the HUD will
* still appear at the top of the screen, but in the same orientation as at the bottom. */
private boolean mirrorY;
/** Distance of the spell icon from the left edge of the screen (or right edge when flipped). */
private int spellIconInsetX;
/** Distance of the spell icon from the bottom edge of the screen (or top edge when flipped). */
private int spellIconInsetY;
/** Distance of the spell name from the left edge of the screen (or right edge when flipped). */
private int textInsetX;
/** Distance of the spell name from the bottom edge of the screen (or the top edge when flipped). */
private int textInsetY;
/** Horizontal distance between the start of adjacent spell names. */
private int cascadeOffsetX;
/** Vertical distance between the start of adjacent spell names. */
private int cascadeOffsetY;
/** Distance of the cooldown bar from the left edge of the screen (or right edge when flipped). */
private int cooldownBarX;
/** Distance of the cooldown bar from the bottom edge of the screen (or top edge when flipped). */
private int cooldownBarY;
/** Length of the cooldown bar. */
private int cooldownBarLength;
/** Height of the cooldown bar. */
private int cooldownBarHeight;
/** Whether the cooldown bar is flipped horizontally when the HUD is on the right-hand side of the screen. */
private boolean cooldownBarMirrorX;
/** Whether the cooldown bar is flipped vertically when the HUD is at the top of the screen. */
private boolean cooldownBarMirrorY;
/** Whether the cooldown bar progress overlay is shown when the cooldown bar is full (i.e. when progress = 1). */
private boolean showCooldownWhenFull;
private final Minecraft mc;
/** Creates a new skin with the given texture and reads its values from the given metadata json file. */
public Skin(ResourceLocation texture, ResourceLocation metadata){
mc = Minecraft.getMinecraft();
this.texture = texture;
try {
// This time we only want the highest priority file
IResource metadataFile = Minecraft.getMinecraft().getResourceManager().getResource(metadata);
BufferedReader reader = new BufferedReader(new InputStreamReader(metadataFile.getInputStream()));
JsonElement je = gson.fromJson(reader, JsonElement.class);
parseJson(je.getAsJsonObject());
} catch (IOException e){
// If an exception is thrown, chances are the resource pack did not have a spell_hud folder, so nothing
// else needs to be done.
Wizardry.logger.error("Error reading spell HUD skin metadata file: ", e);
}
}
/** Returns the display name of this HUD skin, which is shown in the config GUI. */
public String getName(){
return name;
}
/** Returns the description of this HUD skin, which is shown in its tooltip in the config GUI. */
public String getDescription(){
return description;
}
/** Returns the overall width of this spell HUD skin. */
public int getWidth(){
return width;
}
/** Returns the overall height of this spell HUD skin. */
public int getHeight(){
return height;
}
/** Actually reads the metadata values for this skin from the json file. */
private void parseJson(JsonObject json){
// For now, all the keys must be present for the metadata file to work (the only ones that could reasonably
// have a default anyway are the mirror values).
name = JsonUtils.getString(json, "name");
description = JsonUtils.getString(json, "description");
width = JsonUtils.getInt(json, "width");
if(width > 128) Wizardry.logger.warn("The width of the spell HUD skin " + name + " exceeds 128, this may cause it to render strangely.");
height = JsonUtils.getInt(json, "height");
JsonObject mirror = JsonUtils.getJsonObject(json, "mirror");
mirrorX = JsonUtils.getBoolean(mirror, "x");
mirrorY = JsonUtils.getBoolean(mirror, "y");
JsonObject spellIconInset = JsonUtils.getJsonObject(json, "spell_icon_inset");
spellIconInsetX = JsonUtils.getInt(spellIconInset, "x");
spellIconInsetY = JsonUtils.getInt(spellIconInset, "y");
JsonObject textInset = JsonUtils.getJsonObject(json, "text_inset");
textInsetX = JsonUtils.getInt(textInset, "x");
textInsetY = JsonUtils.getInt(textInset, "y");
JsonObject cascadeOffset = JsonUtils.getJsonObject(json, "spell_cascade_offset");
cascadeOffsetX = JsonUtils.getInt(cascadeOffset, "x");
cascadeOffsetY = JsonUtils.getInt(cascadeOffset, "y");
JsonObject cooldownBar = JsonUtils.getJsonObject(json, "cooldown_bar");
cooldownBarX = JsonUtils.getInt(cooldownBar, "x");
cooldownBarY = JsonUtils.getInt(cooldownBar, "y");
cooldownBarLength = JsonUtils.getInt(cooldownBar, "length");
cooldownBarHeight = JsonUtils.getInt(cooldownBar, "height");
JsonObject cooldownBarMirror = JsonUtils.getJsonObject(cooldownBar, "mirror");
cooldownBarMirrorX = JsonUtils.getBoolean(cooldownBarMirror, "x");
cooldownBarMirrorY = JsonUtils.getBoolean(cooldownBarMirror, "y");
showCooldownWhenFull = JsonUtils.getBoolean(cooldownBar, "show_when_full");
}
// The idea of these methods is that everything in here relates only to the actual drawing of the HUD. In other
// words, all processing of which spells to draw and so on is done outside of here. This means that the config
// GUI can easily display its preview without having a player or wand stack object to query.
/**
* Draws the background layer of this HUD skin at the given position with the given orientations, with the given
* spell icon and cooldown bar progress.
*
* @param x The x-coordinate of the corner of the spell HUD. The bottom left corner <i>of the actual texture</i>
* will always be at this position unless mirrorX/Y is false, so for example if flipX is false and flipY is true,
* this will be the corner of the HUD that is closest to the top left corner of the screen.
* @param y The y-coordinate of the corner of the spell HUD; see above.
* @param flipX Whether to flip the HUD horizontally.
* @param flipY Whether to flip the HUD vertically.
* @param icon A {@code ResourceLocation} corresponding to the icon of the selected spell.
* @param cooldownBarProgress The fraction of the cooldown bar to draw; must be between 0 and 1 (inclusive).
* @param creativeMode True to draw the creative mode HUD, false for the survival mode version.
*/
public void drawBackground(int x, int y, boolean flipX, boolean flipY, ResourceLocation icon, float cooldownBarProgress, boolean creativeMode){
// Moves the origin if the HUD does not mirror; neatens the rest of the code.
if(flipX && !mirrorX) x -= width;
if(flipY && !mirrorY) y += height;
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.color(1, 1, 1);
// Spell illustration - this is now done first so it is behind the HUD texture
mc.renderEngine.bindTexture(icon);
int x1 = flipX && mirrorX ? x - spellIconInsetX - SPELL_ICON_SIZE : x + spellIconInsetX;
// y is upside-down so this is the other way round
int y1 = flipY && mirrorY ? y + spellIconInsetY : y - spellIconInsetY - SPELL_ICON_SIZE;
DrawingUtils.drawTexturedRect(x1, y1, 0, 0, SPELL_ICON_SIZE, SPELL_ICON_SIZE, SPELL_ICON_SIZE, SPELL_ICON_SIZE);
// Background of spell hud
mc.renderEngine.bindTexture(texture);
x1 = flipX && mirrorX ? x - width : x;
y1 = flipY && mirrorY ? y : y - height;
// The 128 here is a uv value, not a dimension, and hence is left as a hardcoded number.
// TODO: Since the HUD is wider than it is tall, perhaps the creative mode texture should be in the bottom half instead of the right half?
DrawingUtils.drawTexturedFlippedRect(x1, y1, creativeMode ? 128 : 0, 0, width, height, 256, 256, flipX && mirrorX, flipY && mirrorY);
// Cooldown bar
if(!creativeMode && cooldownBarProgress > 0 && (showCooldownWhenFull || cooldownBarProgress < 1)){
int l = (int)(cooldownBarProgress * cooldownBarLength);
x1 = flipX && mirrorX ? x - cooldownBarX - (cooldownBarMirrorX ? l : cooldownBarLength) : x + cooldownBarX;
y1 = flipY && mirrorY ? y + cooldownBarY : y - cooldownBarY - cooldownBarHeight;
int u = cooldownBarX; // This doesn't change, even when cooldownBarMirrorX is true, because it should
int v = height; // always start with the left-hand in the actual texture file
DrawingUtils.drawTexturedFlippedRect(x1, y1, u, v, l, cooldownBarHeight, 256, 256, flipX && cooldownBarMirrorX, flipY && cooldownBarMirrorY);
}
GlStateManager.popMatrix();
// Blend needs to be left enabled here because otherwise the hotbar becomes opaque
}
/**
* Draws the text layer of this HUD skin at the given position with the given orientations, with the given
* spell name strings.
*
* @param x The x-coordinate of the corner of the spell HUD. The bottom left corner <i>of the actual texture</i>
* will always be at this position, so for example if flipX is false and flipY is true, this will be the corner
* of the HUD that is closest to the top left corner of the screen.
* @param y The y-coordinate of the corner of the spell HUD; see above.
* @param flipX Whether to flip the HUD horizontally.
* @param flipY Whether to flip the HUD vertically.
* @param prevSpellName The name of the previous spell. This string will be drawn <i>directly</i> using the
* {@link MixedFontRenderer}; as such it should be supplied with formatting codes and # characters already
* appended.
* @param spellName The name of the currently selected spell; see above.
* @param nextSpellName The name of the next spell; see above.
* @param animationProgress The progress of the spell switching animation, as a fraction between 0 and 1
* (inclusive). Positive values indicate switching forwards, negative values indicate switching backwards, and
* a value of zero indicates that the spell is not currently being switched.
*/
public void drawText(int x, int y, boolean flipX, boolean flipY, String prevSpellName, String spellName, String nextSpellName, float animationProgress){
// Moves the origin if the HUD does not mirror; neatens the rest of the code.
if(flipX && !mirrorX) x -= width;
if(flipY && !mirrorY) y += height;
FontRenderer font = ClientProxy.mixedFontRenderer; // On this occasion we're client-side so this is OK
// Position of the selected spell name in normal display, also used for interpolation when animating
int x1 = flipX && mirrorX ? x - width : x + textInsetX;
// The text is an odd number of pixels high so we need to subtract an extra 1 when not flipped
int y1 = flipY && mirrorY ? y + textInsetY - font.FONT_HEIGHT/2 + 2 : y - textInsetY - font.FONT_HEIGHT/2 - 1;
int maxWidth = width - textInsetX; // Maximum width of the text
if(animationProgress == 0){ // Normal display
float xPrev = flipX && mirrorX ? x - width : x + textInsetX - (flipY ? -1 : 1) * cascadeOffsetX;
float xNext = flipX && mirrorX ? x - width : x + textInsetX + (flipY ? -1 : 1) * cascadeOffsetX;
// Don't ask me why adding 1 to this makes it look more even, it just does!
float yPrev = y1 - (cascadeOffsetY + 1); // No need to account for flipY because previous is always above.
float yNext = y1 + cascadeOffsetY; // No need to account for flipY because next is always below.
float maxWidthPrev = maxWidth + (flipY ? -1 : 1) * cascadeOffsetX;
float maxWidthNext = maxWidth - (flipY ? -1 : 1) * cascadeOffsetX;
int nextPrevClr = DrawingUtils.makeTranslucent(0xffffff, SPELL_NAME_OPACITY);
DrawingUtils.drawScaledStringToWidth(font, prevSpellName, xPrev, yPrev, SPELL_NAME_SCALE, nextPrevClr, maxWidthPrev, true, flipX && mirrorX);
DrawingUtils.drawScaledStringToWidth(font, spellName, x1, y1, 1, 0xffffffff, maxWidth, true, flipX && mirrorX);
DrawingUtils.drawScaledStringToWidth(font, nextSpellName, xNext, yNext, SPELL_NAME_SCALE, nextPrevClr, maxWidthNext, true, flipX && mirrorX);
}else{ // Switching spells
boolean reverse = animationProgress < 0;
if(reverse) animationProgress = 1 - Math.abs(animationProgress); // Simplest way of reversing the animation
float xPrev = flipX && mirrorX ? x - width : x + textInsetX - (flipY ? -1 : 1) * cascadeOffsetX * animationProgress;
float xNext = flipX && mirrorX ? x - width : x + textInsetX + (flipY ? -1 : 1) * cascadeOffsetX * (1 - animationProgress);
float yPrev = y1 - (cascadeOffsetY + 1) * animationProgress; // No need to account for flipY because previous is always above.
float yNext = y1 + cascadeOffsetY * (1 - animationProgress); // No need to account for flipY because next is always below.
float maxWidthPrev = maxWidth + (flipY ? -1 : 1) * cascadeOffsetX * animationProgress;
float maxWidthNext = maxWidth - (flipY ? -1 : 1) * cascadeOffsetX * (1 - animationProgress);
float scalePrev = SPELL_NAME_SCALE + (1 - SPELL_NAME_SCALE) * (1 - animationProgress);
float scaleNext = SPELL_NAME_SCALE + (1 - SPELL_NAME_SCALE) * (animationProgress);
int clrPrev = DrawingUtils.makeTranslucent(0xffffff, SPELL_NAME_OPACITY + (1 - SPELL_NAME_OPACITY) * (1 - animationProgress));
int clrNext = DrawingUtils.makeTranslucent(0xffffff, SPELL_NAME_OPACITY + (1 - SPELL_NAME_OPACITY) * animationProgress);
if(reverse){ // Switching to previous spell
// Only renders the next spell and the current one
DrawingUtils.drawScaledStringToWidth(font, spellName, xPrev, yPrev, scalePrev, clrPrev, maxWidthPrev, true, flipX && mirrorX);
DrawingUtils.drawScaledStringToWidth(font, nextSpellName, xNext, yNext, scaleNext, clrNext, maxWidthNext, true, flipX && mirrorX);
}else{ // Switching to next spell
// Only renders the previous spell and the current one
DrawingUtils.drawScaledStringToWidth(font, prevSpellName, xPrev, yPrev, scalePrev, clrPrev, maxWidthPrev, true, flipX && mirrorX);
DrawingUtils.drawScaledStringToWidth(font, spellName, xNext, yNext, scaleNext, clrNext, maxWidthNext, true, flipX && mirrorX);
}
}
}
}
}
@@ -1,77 +0,0 @@
package electroblob.wizardry.client.gui.config;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.config.*;
import net.minecraftforge.fml.client.config.GuiEditArrayEntries.StringEntry;
import net.minecraftforge.fml.common.registry.EntityEntry;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* [NYI] Intended as a way of choosing entities by name from all those currently registered, within the config file, so
* that users don't have to look up the entity IDs. I can't get this to work correctly at the moment.
*/
public class EntityNameEntry extends StringEntry {
protected final GuiButtonExt btnValue;
protected Object entityClass;
public EntityNameEntry(GuiEditArray owningScreen, GuiEditArrayEntries owningEntryList, IConfigElement configElement,
Object value){
super(owningScreen, owningEntryList, configElement, value);
this.btnValue = new GuiButtonExt(0, 0, 0, owningEntryList.controlWidth, 18,
I18n.format(this.textFieldValue.getText()));
// this.btnValue.enabled = owningScreen.enabled;
}
@Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY,
boolean isSelected, float partialTicks){
//super.drawEntry(slotIndex, x, y, listWidth, slotHeight, mouseX, mouseY, isSelected, partial);
this.btnValue.x = listWidth / 4;
this.btnValue.y = y;
String trans = I18n.format(this.textFieldValue.getText());
if(!trans.equals(this.textFieldValue.getText()))
this.btnValue.displayString = trans;
else
this.btnValue.displayString = this.textFieldValue.getText();
// btnValue.packedFGColour = value ? GuiUtils.getColorCode('2', true) : GuiUtils.getColorCode('4', true);
this.btnValue.drawButton(owningEntryList.getMC(), mouseX, mouseY, partialTicks);
}
@Override
public boolean mousePressed(int index, int x, int y, int mouseEvent, int relativeX, int relativeY){
if(this.btnValue.mousePressed(owningEntryList.getMC(), x, y)){
btnValue.playPressSound(owningEntryList.getMC().getSoundHandler());
// Goodness only knows if this works, but the class is unimplemented right now so it doesn't really matter.
Map<Object, String> map = ForgeRegistries.ENTITIES.getEntries().stream().collect(
Collectors.<Entry<ResourceLocation, EntityEntry>, Object, String>toMap(e -> e.getValue().getClass(),
e -> e.getValue().getName()));
Minecraft.getMinecraft().displayGuiScreen(
new GuiSelectString(this.owningScreen, configElement, index, map, this.getValue(), true));
owningEntryList.recalculateState();
return true;
}
return super.mousePressed(index, x, y, mouseEvent, relativeX, relativeY);
}
@Override
public void mouseReleased(int index, int x, int y, int mouseEvent, int relativeX, int relativeY){
this.btnValue.mouseReleased(x, y);
super.mouseReleased(index, x, y, mouseEvent, relativeX, relativeY);
}
@Override
public Object getValue(){
return this.textFieldValue.getText();
}
}
@@ -1,141 +0,0 @@
package electroblob.wizardry.client.gui.config;
import electroblob.wizardry.Settings;
import electroblob.wizardry.Wizardry;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiConfigEntries.CategoryEntry;
import net.minecraftforge.fml.client.config.IConfigElement;
import java.util.ArrayList;
import java.util.List;
public class GuiConfigWizardry extends GuiConfig {
public GuiConfigWizardry(GuiScreen parent){
super(parent, getConfigEntries(), Wizardry.MODID, false, false,
Wizardry.NAME + " - " + I18n.format("config." + Wizardry.MODID + ".title.general"));
// this.titleLine2 = "File location: " + Wizardry.config.getConfigFile().getAbsolutePath();
}
private static List<IConfigElement> getConfigEntries(){
List<IConfigElement> configList = new ArrayList<IConfigElement>(1);
configList.add(new DummyCategoryElement("gameplayConfig", "config." + Wizardry.MODID + ".category." + Settings.GAMEPLAY_CATEGORY, GameplayCategory.class));
configList.add(new DummyCategoryElement("worldgenConfig", "config." + Wizardry.MODID + ".category." + Settings.WORLDGEN_CATEGORY, WorldgenCategory.class));
configList.add(new DummyCategoryElement("commandsConfig", "config." + Wizardry.MODID + ".category." + Settings.COMMANDS_CATEGORY, CommandsCategory.class));
configList.add(new DummyCategoryElement("clientConfig", "config." + Wizardry.MODID + ".category." + Settings.CLIENT_CATEGORY, ClientCategory.class));
configList.add(new DummyCategoryElement("spellsConfig", "config." + Wizardry.MODID + ".category." + Settings.SPELLS_CATEGORY, SpellsCategory.class));
configList.add(new DummyCategoryElement("resistancesConfig", "config." + Wizardry.MODID + ".category." + Settings.RESISTANCES_CATEGORY, ResistancesCategory.class));
configList.add(new DummyCategoryElement("compatibilityConfig", "config." + Wizardry.MODID + ".category." + Settings.COMPATIBILITY_CATEGORY, CompatibilityCategory.class));
configList.addAll(new ConfigElement(Wizardry.settings.getConfigCategory(Configuration.CATEGORY_GENERAL)).getChildElements());
return configList;
}
// The reason this system is so convoluted is that it's designed for use with the @Config annotation. The problem is,
// I'm not sure whether that will play well with the load phases. Hmmm...
public static abstract class CategoryBase extends CategoryEntry {
public CategoryBase(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override
protected GuiScreen buildChildScreen(){
String category = this.getCategory();
// This GuiConfig object specifies the configID of the object and as such will force-save when it is closed.
// The parent GuiConfig object's entryList will also be refreshed to reflect the changes.
GuiConfig childScreen = new GuiConfig(this.owningScreen,
(new ConfigElement(Wizardry.settings.getConfigCategory(category))).getChildElements(),
this.owningScreen.modID, category, false, false,
Wizardry.NAME + " - " + I18n.format("config." + Wizardry.MODID + ".title." + category));
childScreen.titleLine2 = I18n.format("config." + Wizardry.MODID + ".subtitle." + category);
return childScreen;
}
protected abstract String getCategory();
}
/** Gameplay category of the config gui. */
public static class GameplayCategory extends CategoryBase {
public GameplayCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.GAMEPLAY_CATEGORY; }
}
/** Worldgen category of the config gui. */
public static class WorldgenCategory extends CategoryBase {
public WorldgenCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.WORLDGEN_CATEGORY; }
}
/** Commands category of the config gui. */
public static class CommandsCategory extends CategoryBase {
public CommandsCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.COMMANDS_CATEGORY; }
}
/** Client category of the config gui. */
public static class ClientCategory extends CategoryBase {
public ClientCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.CLIENT_CATEGORY; }
}
/** Spells category of the config gui. */
public static class SpellsCategory extends CategoryBase {
public SpellsCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.SPELLS_CATEGORY; }
}
/** Resistances category of the config gui. */
public static class ResistancesCategory extends CategoryBase {
public ResistancesCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.RESISTANCES_CATEGORY; }
}
/** Commands category of the config gui. */
public static class CompatibilityCategory extends CategoryBase {
public CompatibilityCategory(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop);
}
@Override protected String getCategory() { return Settings.COMPATIBILITY_CATEGORY; }
}
}
@@ -1,119 +0,0 @@
package electroblob.wizardry.client.gui.config;
import com.google.common.collect.Lists;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.gui.GuiSpellDisplay;
import electroblob.wizardry.client.gui.GuiSpellDisplay.Skin;
import electroblob.wizardry.registry.Spells;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.fml.client.config.GuiSelectString;
import net.minecraftforge.fml.client.config.IConfigElement;
import javax.annotation.Nullable;
import java.util.Map;
public class GuiSelectHUDSkin extends GuiSelectString {
public GuiSelectHUDSkin(GuiScreen parentScreen, IConfigElement configElement, int slotIndex, Map<Object, String> selectableValues, Object currentValue, boolean enabled){
super(parentScreen, configElement, slotIndex, selectableValues, currentValue, enabled);
}
@Override
public void initGui(){
super.initGui();
setEntryListDimensions();
}
@Override
protected void actionPerformed(GuiButton button){
super.actionPerformed(button);
setEntryListDimensions(); // Stops the entry list from resizing when a button is pressed
}
private void setEntryListDimensions(){
this.entryList.setDimensions(150, height, 43, height-43);
this.entryList.left = 10;
this.entryList.maxEntryWidth = 120;
this.entryList.headerPadding = 5;
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks){
super.drawScreen(mouseX, mouseY, partialTicks);
GlStateManager.disableLighting();
if(this.currentValue instanceof String){
this.drawString(this.fontRenderer, I18n.format("config." + Wizardry.MODID + ".spell_hud_skin.preview"), 170, 44, 0xffffff);
int previewLeft = 170;
int previewRight = width-10;
int previewTop = 60;
int previewBottom = height-43;
this.drawGradientRect(previewLeft, previewTop, previewRight, previewBottom, 0x88000000, 0x88000000);
int previewBorder = 10;
Skin skin = GuiSpellDisplay.getSkin((String)this.currentValue);
float scale = Math.min((previewRight - previewLeft - 2*previewBorder)/(float)skin.getWidth(),
(previewBottom - previewTop - 2*previewBorder)/(float)skin.getHeight());
float x = (previewLeft + previewRight)/2 - (skin.getWidth()*scale)/2;
float y = (previewBottom + previewTop)/2 + (skin.getHeight()*scale)/2;
GlStateManager.pushMatrix();
GlStateManager.scale(scale, scale, scale);
skin.drawBackground((int)(x/scale), (int)(y/scale), false, false,
Spells.magic_missile.getIcon(), 0.6f, false);
skin.drawText((int)(x/scale), (int)(y/scale), false, false,
Spells.none.getDisplayNameWithFormatting(),
Spells.magic_missile.getDisplayNameWithFormatting(),
Spells.none.getDisplayNameWithFormatting(), 0);
GlStateManager.popMatrix();
Skin hovered = getHoveredSkin(mouseX, mouseY);
if(hovered != null){
this.drawToolTip(Lists.newArrayList("\u00A7a" + hovered.getName(), "\u00A7e" + hovered.getDescription()),
mouseX, mouseY);
}
}
GlStateManager.enableLighting();
}
/** Returns the skin corresponding to the list entry being hovered over, or null if there is none. */
@Nullable
private Skin getHoveredSkin(int mouseX, int mouseY){
int index = this.entryList.getSlotIndexFromScreenCoords(mouseX, mouseY);
if(index >= 0 && index <= this.entryList.listEntries.size() && mouseY <= this.entryList.bottom){
Object object = entryList.getListEntry(index).getValue();
if(object instanceof String){
return GuiSpellDisplay.getSkin((String)object);
}
}
return null;
}
@Override // Stops the world being visible behind the GUI when configuring from within a world
public void drawWorldBackground(int tint){
this.drawBackground(tint);
}
}
@@ -1,93 +0,0 @@
package electroblob.wizardry.client.gui.config;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiUtils;
import net.minecraftforge.fml.client.config.IConfigElement;
/**
* Same as {@link net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry}, but instead of simply
* displaying 'true' or 'false', allows the two display strings to be specified in the lang file.
*/
// BooleanEntry's constructors are private, so I had to copy the whole goddamn class to change one method. Thanks Forge.
public class NamedBooleanEntry extends GuiConfigEntries.ButtonEntry {
protected final boolean beforeValue;
protected boolean currentValue;
private static final String DEFAULT_KEY = "config.ebwizardry.generic";
public NamedBooleanEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement configElement){
super(owningScreen, owningEntryList, configElement);
this.beforeValue = Boolean.valueOf(configElement.get().toString());
this.currentValue = beforeValue;
this.btnValue.enabled = enabled();
updateValueButtonText();
}
// This is the only method that's any different
@Override
public void updateValueButtonText(){
String langKey = configElement.getLanguageKey() + "." + currentValue;
this.btnValue.displayString = I18n.format(langKey);
// If the key is unspecified, it defaults to the generic 'Enabled'/'Disabled' keys and adds a red/green colour
if(this.btnValue.displayString.equals(langKey)){
this.btnValue.displayString = I18n.format(DEFAULT_KEY + "." + currentValue);
btnValue.packedFGColour = currentValue ? GuiUtils.getColorCode('a', true) : GuiUtils.getColorCode('c', true);
}
}
// Everything from here down is the same as BooleanEntry
@Override
public void valueButtonPressed(int slotIndex){
if(enabled()) currentValue = !currentValue;
}
@Override
public boolean isDefault(){
return currentValue == Boolean.valueOf(configElement.getDefault().toString());
}
@Override
public void setToDefault(){
if(enabled()){
currentValue = Boolean.valueOf(configElement.getDefault().toString());
updateValueButtonText();
}
}
@Override
public boolean isChanged(){
return currentValue != beforeValue;
}
@Override
public void undoChanges(){
if(enabled()){
currentValue = beforeValue;
updateValueButtonText();
}
}
@Override
public boolean saveConfigElement(){
if(enabled() && isChanged()){
configElement.set(currentValue);
return configElement.requiresMcRestart();
}
return false;
}
@Override
public Boolean getCurrentValue(){
return currentValue;
}
@Override
public Boolean[] getCurrentValues(){
return new Boolean[]{getCurrentValue()};
}
}
@@ -1,35 +0,0 @@
package electroblob.wizardry.client.gui.config;
import electroblob.wizardry.client.gui.GuiSpellDisplay;
import net.minecraftforge.client.gui.ForgeGuiFactory.ForgeConfigGui.ModIDEntry;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiConfigEntries.SelectValueEntry;
import net.minecraftforge.fml.client.config.IConfigElement;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* Custom config GUI for spell HUD skin selection; displays a list of all the loaded skins and a preview of the currently
* selected skin. based off of {@link ModIDEntry} from Forge.
*/
public class SpellHUDSkinChooserEntry extends SelectValueEntry {
public SpellHUDSkinChooserEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList, IConfigElement prop){
super(owningScreen, owningEntryList, prop, getSelectableValues());
if(this.selectableValues.size() == 0) this.btnValue.enabled = false;
}
private static Map<Object, String> getSelectableValues(){
return GuiSpellDisplay.getSkins().entrySet().stream().collect(Collectors.toMap(Entry::getKey,
e -> e.getValue().getName()));
}
@Override // Copied from superclass to use custom child screen GUI class
public void valueButtonPressed(int slotIndex){
mc.displayGuiScreen(new GuiSelectHUDSkin(this.owningScreen, configElement, slotIndex, selectableValues, currentValue, enabled()));
}
}
@@ -1,194 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.JsonUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Instances of this class represent tables of contents in the wizard's handbook. Each {@link Section} can have a
* single table of contents, which can reference any other sections in the handbook (though it is normal to list
* top-level sections in a main contents and have subsections listed in their respective parent sections' contents).
*
* This class handles JSON parsing, formatting and drawing of the contents itself, working on a line-by-line basis
* (as opposed to sections, which work on a page-by-page basis). It also stores its own list of buttons.
*
* @author Electroblob
* @since Wizardry 4.2
*/
class Contents {
// Final fields are mandatory, the rest are optional
final String id;
final Section section;
private boolean hyperlinks = true;
private boolean pageNumbers = true;
private String separator = ".";
// Derived fields, not specifically defined in JSON
private int startPage;
private int startLine;
private final List<List<GuiButton>> buttons;
private final List<Section> entries;
private List<Section> visibleEntries;
private Contents(String id, Section section){
this.id = id;
this.section = section;
this.entries = new ArrayList<>();
this.buttons = new ArrayList<>();
this.visibleEntries = new ArrayList<>();
}
/** Returns an unmodifiable, flattened collection of all the buttons in this contents. */
Collection<GuiButton> getButtons(){
return WizardryUtilities.flatten(buttons);
}
void addEntry(Section section){
entries.add(section);
}
/**
* Draws this contents for the given double-page spread and shows/hides buttons accordingly. Will draw nothing
* if the given page is outside of this contents.
*
* @param font The font renderer object.
* @param doublePage The index of the <b>double-page</b> to be drawn.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
*/
void draw(FontRenderer font, int doublePage, int left, int top){
// Show/hide buttons
int i = 0;
for(List<GuiButton> list : buttons){
final int i1 = i++;
list.forEach(b -> b.visible = GuiWizardHandbook.singleToDoublePage(startPage + i1) == doublePage);
}
if(!pageNumbers) return; // No page numbers means only the buttons are drawn
// FONT_HEIGHT may change between fonts, so this is calculated here. With the default font it's 14.
final int maxLineNumber = GuiWizardHandbook.PAGE_HEIGHT / font.FONT_HEIGHT;
int leftIndex = GuiWizardHandbook.doubleToSinglePage(doublePage, false);
// Relative indices of the pages to be rendered - often these will be outside the section entirely
int[] visiblePages = {leftIndex - startPage, leftIndex - startPage + 1};
for(int page : visiblePages){
if(page >= 0 && page < visibleEntries.size() / maxLineNumber + 1){
int x = left + (GuiWizardHandbook.isRightPage(startPage + page) ? GuiWizardHandbook.GUI_WIDTH - GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH : GuiWizardHandbook.TEXT_INSET_X);
int y = top + GuiWizardHandbook.TEXT_INSET_Y + startLine * font.FONT_HEIGHT;
for(Section entry : this.visibleEntries){
if(entry.isUnlocked()){
int nameWidth = font.getStringWidth(entry.title);
String dotsAndNumber = " " + entry.startPage;
while(font.getStringWidth(dotsAndNumber) < GuiWizardHandbook.PAGE_WIDTH - nameWidth - 2){
dotsAndNumber = separator + dotsAndNumber;
}
font.drawString(dotsAndNumber, x + GuiWizardHandbook.PAGE_WIDTH - font.getStringWidth(dotsAndNumber), y, DrawingUtils.BLACK, false);
if(!hyperlinks) font.drawString(entry.title, x, y, DrawingUtils.BLACK, false);
y += font.FONT_HEIGHT;
}
}
}
}
}
/**
* Called on GUI load to format the section and all subsections, contents tables and other elements. Does not
* perform any actual drawing.
*
* @param font The font renderer object, for measurement purposes.
* @param startPage The index of the first page (single side, not double-page) of this section.
* @param startLine The index of the first line of this contents.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
* @return The number of lines this contents takes up.
* @throws JsonSyntaxException if at any point the formatting is found to be invalid.
*/
int format(FontRenderer font, int startPage, int startLine, int left, int top){
this.buttons.clear();
this.visibleEntries = new ArrayList<>(entries); // Need to copy the collection first!
this.visibleEntries.removeIf(s -> !s.isUnlocked());
if(hyperlinks){
// FONT_HEIGHT may change between fonts, so this is calculated here. With the default font it's 14.
final int maxLineNumber = GuiWizardHandbook.PAGE_HEIGHT / font.FONT_HEIGHT;
this.startPage = startPage;
this.startLine = startLine;
List<GuiButton> list = new ArrayList<>(maxLineNumber);
for(Section entry : this.visibleEntries){
int x = GuiWizardHandbook.isRightPage(startPage) ? left + GuiWizardHandbook.GUI_WIDTH - GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH : left + GuiWizardHandbook.TEXT_INSET_X;
int y = top + GuiWizardHandbook.TEXT_INSET_Y + startLine * font.FONT_HEIGHT;
list.add(new GuiButtonHyperlink.Internal(0, x, y, font, entry.title, entry, 0, "", maxLineNumber-startLine, GuiWizardHandbook.isRightPage(startPage)));
startLine++;
if(startLine == maxLineNumber){
startLine = 0;
startPage++;
buttons.add(list);
list = new ArrayList<>(maxLineNumber); // If there are no more entries this will be discarded anyway
}
}
buttons.add(list);
}
// Returning this is kind of trivial at the moment but if we ever wanted to add a header or something,
// it would be more useful.
return visibleEntries.size();
}
/**
* Parses the given JSON object and constructs a new {@code Contents} from it, setting all the relevant fields
* and references.
*
* @param parent The parent section for this contents.
* @param json A JSON object representing the contents to be constructed. This must contain at least an "id"
* string.
* @return The resulting {@code Contents} object.
* @throws JsonSyntaxException if at any point the JSON object is found to be invalid.
*/
static Contents fromJson(Section parent, JsonObject json){
Contents contents = new Contents(JsonUtils.getString(json, "id"), parent);
contents.hyperlinks = JsonUtils.getBoolean(json, "hyperlinks", true);
contents.pageNumbers = JsonUtils.getBoolean(json, "page_numbers", true);
contents.separator = JsonUtils.getString(json, "separator", ".");
return contents;
}
}
@@ -1,233 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import com.google.common.collect.Streams;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.DrawingUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nullable;
import java.util.*;
class CraftingRecipe {
static final int BORDER = 7;
static final int TEXTURE_INSET_X = 40, TEXTURE_INSET_Y = 190;
static final int WIDTH = 121, HEIGHT = 66;
// Final fields are mandatory, the rest are optional
private final ResourceLocation[] locations;
// Derived fields, not specifically defined in JSON
private List<IRecipe> recipes;
private final Set<int[]> instances = new HashSet<>();
private CraftingRecipe(ResourceLocation[] locations){
this.locations = locations;
}
/**
* Adds an instance of this recipe to the list.
*
* @param page The index of the <b>single</b> page this image is on.
* @param x The x-coordinate of the top-left corner of the image, <i>relative</i> to the top-left corner of the GUI.
* @param y The y-coordinate of the top-left corner of the image, <i>relative</i> to the top-left corner of the GUI.
*/
void addInstance(int page, int x, int y){
instances.add(new int[]{page, x, y});
}
/** Removes all instances of this recipe from the list. */
void clearInstances(){
instances.clear();
}
/** Called on GUI open to load the actual recipe object from the registry. This cannot be done on JSON load since
* the recipes aren't necessarily loaded at that point. */
void load(){
recipes = new ArrayList<>(locations.length);
for(ResourceLocation location : locations){
IRecipe recipe = CraftingManager.getRecipe(location);
if(recipe == null) Wizardry.logger.warn("The recipe {} used in the wizard's handbook does not exist, it will display a blank grid instead", location);
else recipes.add(recipe);
}
}
/**
* Draws all instances of this recipe that are located on the given double-page spread.
*
* @param font The font renderer object.
* @param itemRenderer The item renderer object.
* @param doublePage The double-page index of the page to be drawn.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
*/
void draw(FontRenderer font, RenderItem itemRenderer, int doublePage, int left, int top){
int index = (int)(Minecraft.getSystemTime() % Integer.MAX_VALUE)/2000;
for(int[] instance : instances){
if(GuiWizardHandbook.singleToDoublePage(instance[0]) == doublePage){
renderCraftingRecipe(font, itemRenderer, left + instance[1], top + instance[2], recipes.isEmpty() ? null : recipes.get(index % recipes.size()));
}
}
}
/**
* Draws the tooltips for all instances of this recipe that are located on the given double-page spread. This has to
* be done separately so that the tooltips are on top of everything else.
*
* @param itemRenderer The item renderer object.
* @param doublePage The double-page index of the page to be drawn.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
*/
void drawTooltips(GuiWizardHandbook gui, FontRenderer font, RenderItem itemRenderer, int doublePage, int left, int top, int mouseX, int mouseY){
if(recipes.isEmpty()) return;
int index = (int)(Minecraft.getSystemTime() % Integer.MAX_VALUE)/2000;
for(int[] instance : instances){
if(GuiWizardHandbook.singleToDoublePage(instance[0]) == doublePage){
renderCraftingTooltips(gui, itemRenderer, left + instance[1], top + instance[2], mouseX, mouseY, recipes.get(index % recipes.size()));
}
}
}
/**
* Parses the given JSON object and constructs a new {@code Image} from it, setting all the relevant fields
* and references.
*
* @param json A JSON object representing the image to be constructed. This must contain at least a "locations"
* string.
* @return The resulting {@code Image} object.
* @throws JsonSyntaxException if at any point the JSON object is found to be invalid.
*/
static CraftingRecipe fromJson(JsonObject json){
ResourceLocation[] locations = Streams.stream(JsonUtils.getJsonArray(json, "locations"))
.map(je -> new ResourceLocation(je.getAsString())).toArray(ResourceLocation[]::new);
return new CraftingRecipe(locations);
}
static void populate(Map<String, CraftingRecipe> map, JsonObject json){
JsonObject sectionsObject = JsonUtils.getJsonObject(json, "recipes");
// Need to iterate over these since we don't know what they're called or how many there are
for(Map.Entry<String, JsonElement> entry : sectionsObject.entrySet()){
String key = entry.getKey(); // Find out what each element is called, this will be the sections map key
CraftingRecipe recipe = fromJson(entry.getValue().getAsJsonObject());
map.put(key, recipe);
}
}
private static void renderCraftingRecipe(FontRenderer font, RenderItem itemRenderer, int x, int y, @Nullable IRecipe recipe){
GlStateManager.color(1, 1, 1, 1);
Minecraft.getMinecraft().renderEngine.bindTexture(GuiWizardHandbook.texture);
DrawingUtils.drawTexturedRect(x, y, TEXTURE_INSET_X, TEXTURE_INSET_Y, WIDTH, HEIGHT, GuiWizardHandbook.TEXTURE_WIDTH, GuiWizardHandbook.TEXTURE_HEIGHT);
if(recipe != null){
GlStateManager.pushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GlStateManager.disableLighting();
GlStateManager.enableRescaleNormal();
GlStateManager.enableColorMaterial();
itemRenderer.zLevel = 100.0F;
int index = (int)(Minecraft.getSystemTime() % Integer.MAX_VALUE) / 2000;
int i = 0;
for(Ingredient ingredient : recipe.getIngredients()){
if(ingredient != Ingredient.EMPTY){
ItemStack stack = ingredient.getMatchingStacks()[index % ingredient.getMatchingStacks().length];
if(!stack.isEmpty()){
itemRenderer.renderItemAndEffectIntoGUI(stack, x + BORDER + 18 * (i % 3), y + BORDER + 18 * (i / 3));
itemRenderer.renderItemOverlays(font, stack, x + BORDER + 18 * (i % 3), y + BORDER + 18 * (i / 3));
}
}
i++;
}
ItemStack result = recipe.getRecipeOutput();
if(!result.isEmpty()){
itemRenderer.renderItemAndEffectIntoGUI(result, x + BORDER + 86, y + BORDER + 18);
itemRenderer.renderItemOverlays(font, result, x + BORDER + 86, y + BORDER + 18);
}
GlStateManager.popMatrix();
GlStateManager.enableDepth();
GlStateManager.disableColorMaterial();
itemRenderer.zLevel = 0.0F;
RenderHelper.disableStandardItemLighting();
}
}
private static void renderCraftingTooltips(GuiWizardHandbook gui, RenderItem itemRenderer, int x, int y, int mouseX, int mouseY, IRecipe recipe){
ItemStack result = recipe.getRecipeOutput();
GlStateManager.pushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GlStateManager.disableLighting();
GlStateManager.enableRescaleNormal();
GlStateManager.enableColorMaterial();
itemRenderer.zLevel = 0.0F;
int index = (int)(Minecraft.getSystemTime() % Integer.MAX_VALUE)/2000;
int i = 0;
for(Ingredient ingredient : recipe.getIngredients()){
if(ingredient != Ingredient.EMPTY){
ItemStack stack = ingredient.getMatchingStacks()[index % ingredient.getMatchingStacks().length];
if(!stack.isEmpty() && isPointInRegion(x + BORDER + 18 * (i%3), y + BORDER + 18 * (i/3), 16, 16, mouseX, mouseY)){
gui.renderToolTip(stack, mouseX, mouseY);
}
}
i++;
}
if(!result.isEmpty() && isPointInRegion(x + BORDER + 86, y + BORDER + 18, 16, 16, mouseX, mouseY)){
gui.renderToolTip(result, mouseX, mouseY);
}
GlStateManager.popMatrix();
GlStateManager.enableDepth();
GlStateManager.disableColorMaterial();
RenderHelper.disableStandardItemLighting();
}
private static boolean isPointInRegion(int left, int top, int width, int height, int mouseX, int mouseY){
return mouseX >= left - 1 && mouseX < left + width + 1 && mouseY >= top - 1 && mouseY < top + height + 1;
}
}
@@ -1,227 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.registry.WizardrySounds;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.audio.SoundHandler;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import java.util.ArrayList;
import java.util.List;
public abstract class GuiButtonHyperlink extends GuiButton {
public static final String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";
/** Pulse period of links to new sections, in milliseconds. */
private static final float PULSATION_PERIOD = 1500;
final int indent;
final List<String> lines;
final int linesLeft;
GuiButtonHyperlink(int id, int x, int y, FontRenderer font, String text, int indent, String suffix, int linesLeft, boolean rightPage){
super(id, x, y, font.getStringWidth(text), font.FONT_HEIGHT, text);
// Sometimes a link has punctuation or something after it that causes it to wrap onto a new line
String linkWithSuffix = text + suffix;
// If the string won't fit any words at the end of the current line, treat it as if we started a new line
if(font.getStringWidth(linkWithSuffix.split("\\s")[0]) > GuiWizardHandbook.PAGE_WIDTH - indent){
indent = 0;
this.y += font.FONT_HEIGHT;
}
this.indent = indent; // Assigned here in case it was corrected above
this.linesLeft = linesLeft;
String line1 = font.listFormattedStringToWidth(linkWithSuffix, GuiWizardHandbook.PAGE_WIDTH - indent).get(0);
// Without trim(), there will be at least 1 leading space due to the custom wrapping
String remainder = linkWithSuffix.substring(line1.length()).trim();
// ... then wrap the rest to the normal width.
lines = new ArrayList<>();
lines.add(line1);
// Some links are only one line, if this wasn't checked they would cause a StackOverflowError
if(!remainder.isEmpty()) lines.addAll(font.listFormattedStringToWidth(remainder, GuiWizardHandbook.PAGE_WIDTH));
// Removes the suffix if it exists (ugly as heck, but it works)
if(!suffix.isEmpty()){
for(int i=lines.size()-1; i>=0; i--){
String line = lines.get(i);
if(suffix.endsWith(line)){
lines.remove(i);
}else if(line.endsWith(suffix)){
lines.set(i, line.substring(0, line.length() - suffix.length()));
break;
}
}
}
// Remove any lines that overflowed onto the next double-page
if(rightPage){
while(lines.size() > linesLeft) lines.remove(lines.size() - 1);
}
}
public boolean isHovered(net.minecraft.client.gui.FontRenderer font, int mouseX, int mouseY){
int i = 0;
for(String line : lines){
int l = x;
if(i == 0) l += indent;
int t = y + font.FONT_HEIGHT * i;
if(i > linesLeft){
l = l + GuiWizardHandbook.GUI_WIDTH - 2 * GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH;
t -= GuiWizardHandbook.PAGE_HEIGHT - (GuiWizardHandbook.PAGE_HEIGHT % font.FONT_HEIGHT);
}
if(mouseX >= l && mouseY >= t && mouseX < l + font.getStringWidth(line) && mouseY < t + font.FONT_HEIGHT){
return true;
}
i++;
}
return false;
}
@Override
public boolean mousePressed(Minecraft minecraft, int mouseX, int mouseY){
return this.enabled && this.visible && isHovered(minecraft.fontRenderer, mouseX, mouseY);
}
@Override
public void drawButton(Minecraft minecraft, int mouseX, int mouseY, float partialTicks){
if(this.visible){
this.hovered = isHovered(minecraft.fontRenderer, mouseX, mouseY);
int i = 0;
for(String line : lines){
int l = x;
if(i == 0) l += indent;
int t = y + minecraft.fontRenderer.FONT_HEIGHT * i;
if(i > linesLeft){
l = l + GuiWizardHandbook.GUI_WIDTH - 2 * GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH;
t -= GuiWizardHandbook.PAGE_HEIGHT - (GuiWizardHandbook.PAGE_HEIGHT % minecraft.fontRenderer.FONT_HEIGHT);
}
minecraft.fontRenderer.drawString(line, l, t, getColour());
i++;
}
}
}
protected int getColour(){
return hovered ? GuiWizardHandbook.colours.get("highlight") : GuiWizardHandbook.colours.get("hyperlink");
}
/**
* Creates a new hyperlink button from the given arguments, automatically differentiating between URLs and sections.
* @param x The x position of the button
* @param y The y position of the button
* @param font A reference to the FontRenderer object
* @param upToLink The paragraph (as a list of lines) up to the link, used to determine positioning and word wrap
* @param arguments The link arguments - that is, everything between the two @ signs, split by spaces
* @param suffix The text directly after the link, up to the first whitespace; used for word wrap. Usually this is
* either empty or contains a single punctuation mark.
* @return The resulting button
* @throws IllegalArgumentException if the given argument array is empty or contains more than 2 arguments
* @throws JsonSyntaxException if the specified link target is not a URL or a valid section ID
*/
public static GuiButtonHyperlink create(int x, int y, FontRenderer font, List<String> upToLink, String[] arguments, String suffix, int linesLeft, boolean rightPage){
if(arguments.length == 0 || arguments.length > 2) throw new IllegalArgumentException("Incorrect array length!");
GuiButtonHyperlink button;
if(arguments[0].matches(URL_REGEX)){
button = new GuiButtonHyperlink.External(0, x, y, font, arguments[arguments.length - 1], arguments[0],
font.getStringWidth(upToLink.get(upToLink.size() - 1)), suffix, linesLeft, rightPage);
}else{
Section target = GuiWizardHandbook.sections.get(arguments[0]);
if(target == null) throw new JsonSyntaxException("Hyperlink points to nonexistent section id " + arguments[0]);
button = new GuiButtonHyperlink.Internal(0, x, y, font, arguments[arguments.length - 1],
target, font.getStringWidth(upToLink.get(upToLink.size() - 1)), suffix, linesLeft, rightPage);
}
return button;
}
static class Internal extends GuiButtonHyperlink {
final Section target;
Internal(int id, int x, int y, FontRenderer font, String text, Section target, int indent, String suffix, int linesLeft, boolean rightPage){
super(id, x, y, font, text, indent, suffix, linesLeft, rightPage);
this.target = target;
}
@Override
public boolean mousePressed(Minecraft minecraft, int mouseX, int mouseY){
if(!target.isUnlocked()) return false;
return super.mousePressed(minecraft, mouseX, mouseY);
}
@Override
public void playPressSound(SoundHandler soundHandler){
soundHandler.playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.MISC_PAGE_TURN, 1));
}
@Override
protected int getColour(){
if(!target.isUnlocked()) return GuiWizardHandbook.colours.get("text");
if(!hovered && target.isNew() && !Minecraft.getMinecraft().player.isCreative()){
int c = GuiWizardHandbook.colours.get("new_section");
int d = GuiWizardHandbook.colours.get("hyperlink");
float f = (MathHelper.sin((Minecraft.getSystemTime() % PULSATION_PERIOD) / PULSATION_PERIOD * 2 * (float)Math.PI) + 1) / 2f;
return DrawingUtils.mix(c, d, f);
}
return super.getColour();
}
}
static class External extends GuiButtonHyperlink {
final ITextComponent link;
External(int id, int x, int y, FontRenderer font, String text, String url, int indent, String suffix, int linesLeft, boolean rightPage){
super(id, x, y, font, text, indent, suffix, linesLeft, rightPage);
this.link = new TextComponentString(text);
link.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)).setColor(TextFormatting.DARK_BLUE);
}
}
}
@@ -1,61 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.registry.WizardrySounds;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.audio.SoundHandler;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
//@SideOnly(Side.CLIENT)
class GuiButtonTurnPage extends GuiButton {
static final int WIDTH = 20;
static final int HEIGHT = 12;
enum Type {
NEXT_PAGE(0, 196),
PREVIOUS_PAGE(0, 208),
NEXT_SECTION(0, 220),
PREVIOUS_SECTION(0, 232),
CONTENTS(0, 244);
private final int u, v;
Type(int u, int v){
this.u = u;
this.v = v;
}
}
public final Type type;
private static final ResourceLocation texture = new ResourceLocation(Wizardry.MODID, "textures/gui/handbook.png");
public GuiButtonTurnPage(int id, int x, int y, Type type){
super(id, x, y, WIDTH, HEIGHT, "");
this.type = type;
}
@Override
public void playPressSound(SoundHandler soundHandler){
soundHandler.playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.MISC_PAGE_TURN, 1));
}
@Override
public void drawButton(Minecraft minecraft, int mouseX, int mouseY, float partialTicks){
if(this.visible){
boolean flag = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
minecraft.getTextureManager().bindTexture(texture);
DrawingUtils.drawTexturedRect(this.x, this.y, flag ? type.u + width : type.u, type.v, width, height, 512, 256);
}
}
}
@@ -1,564 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.ClientProxy;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.client.gui.GuiButtonInvisible;
import electroblob.wizardry.client.gui.handbook.GuiButtonTurnPage.Type;
import electroblob.wizardry.constants.Constants;
import electroblob.wizardry.constants.Element;
import electroblob.wizardry.constants.Tier;
import electroblob.wizardry.packet.PacketRequestAdvancementSync;
import electroblob.wizardry.packet.WizardryPacketHandler;
import electroblob.wizardry.registry.WizardrySounds;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.audio.SoundHandler;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.item.ItemStack;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.*;
/**
* GUI class for the wizard's handbook. Like any GUI class, this is instantiated each time the book is opened. As of
* Wizardry 4.2, the handbook text is defined as a JSON file rather than a plain text file, and is loaded only on
* resource pack reload, rather than every time the book is opened. This means all the data structures (sections, images,
* etc.) are built before the GUI instance exists at all. However, since some things depend on positioning, these have to
* be initialised on GUI creation. (Previously, everything was done on GUI load)
*
* @author Electroblob
* @since Wizardry 1.0
* @see Section
* @see Contents
* @see Image
* @see CraftingRecipe
*/
public class GuiWizardHandbook extends GuiScreen {
private static final ResourceLocation DEFAULT = new ResourceLocation(Wizardry.MODID, "texts/handbook_en_us.json");
static final ResourceLocation texture = new ResourceLocation(Wizardry.MODID, "textures/gui/handbook.png");
/** Global Gson instance for the handbook. */
private static final Gson gson = new Gson();
// Formatting markup
static final char FORMAT_MARKER = '#';
static final char HYPERLINK_MARKER = '@';
static final String IMAGE_TAG = "image";
static final String RECIPE_TAG = "recipe";
static final String RULER_TAG = "ruler";
static final Map<String, String> FORMAT_TAGS = new HashMap<>();
// Dimension constants
// Private constants are not relevant to book elements, package-protected ones are
/** The dimensions of the rendered GUI area. */
static final int GUI_WIDTH = 288, GUI_HEIGHT = 180;
/** The dimensions of the GUI texture itself. */
static final int TEXTURE_WIDTH = 512, TEXTURE_HEIGHT = 256;
/** The dimensions of the area of a single page in which text can be drawn. */
static final int PAGE_WIDTH = 120, PAGE_HEIGHT = 140;
/** The distance of the text from the top outside corner of each page. */
static final int TEXT_INSET_X = 17, TEXT_INSET_Y = 16;
/** The distance of the buttons from the bottom outside corners of the GUI. */
private static final int BUTTON_INSET_X = 22, BUTTON_INSET_Y = 13;
/** The distance between adjacent buttons. */
private static final int BUTTON_SPACING = 20;
/** The distance of the page numbers from the bottom of the GUI. */
private static final int PAGE_NUMBER_INSET = 22;
// IDEA: Constant dimensions could be converted to JSON like the spell HUD ones
// Global variables
/**
* The <b>double-page</b> currently being viewed. Each double-page spread counts as a single page, with the inside
* of the front cover being page 0.
*/
private int currentPage = 0;
/**
* The number of <b>single</b> pages currently in the book. This is calculated on GUI load based on visible sections.
*/
private int pageCount = 1; // Starts at 1 because the first single-page is the inside of the cover
/**
* The <b>double-page</b> number where the bookmark is currently set, <b>relative to the section stored in
* {@link GuiWizardHandbook#bookmarkSection}</b>. Static because it persists when the book is closed.
*/
private static int bookmarkPage = 0;
/**
* The key corresponding to the section in which the bookmark is currently set. Static because it persists when the
* book is closed. Storing a section means the bookmark doesn't change location when new sections are unlocked.
*/
private static String bookmarkSection;
// Buttons
private GuiButton bookmark, next, previous, nextSection, previousSection, menu;
// Handbook content
// As a general rule, I prefer to make static final fields lowercase if they're collections that change, because even
// though the collection itself is constant, the stuff in it is not, so being lowercase highlights this difference.
/**
* A map which stores all loaded section objects, including subsections. This gets wiped on resource pack reload and
* repopulated with mappings as specified by the handbook JSON file for the current language. The keys in the map
* correspond to the keys in the sections object in that file, and are sorted in that order.
*/
static final Map<String, Section> sections = new LinkedHashMap<>();
/**
* A list which stores all loaded section objects, including subsections. This is an unmodifiable list view of the
* values in {@link GuiWizardHandbook#sections}, sorted in the same (page number) order. This exists only to allow
* sections to be accessed by ordinal index for the various navigation buttons, hence why it is private.
*/
private static List<Section> sectionList;
/**
* A map which stores all loaded contents objects. This gets wiped on resource pack reload and repopulated with
* mappings as specified by the handbook JSON file for the current language. The keys in the map correspond to the
* id strings for the contents objects in that file. This map is not sorted.
*/
static final Map<String, Contents> contentsList = new HashMap<>();
/**
* A map which stores all loaded hex colour values. This gets wiped on resource pack reload and repopulated with
* mappings as specified by the handbook JSON file for the current language. The keys in the map correspond to the
* keys in the colours object in that file. This map is not sorted.
*/
static final Map<String, Integer> colours = new HashMap<>();
/**
* A map which stores all loaded image objects. This gets wiped on resource pack reload and repopulated with
* mappings as specified by the handbook JSON file for the current language. The keys in the map correspond to the
* keys in the images object in that file. This map is not sorted.
*/
static final Map<String, Image> images = new HashMap<>();
/**
* A map which stores all loaded crafting recipe objects. This gets wiped on resource pack reload and repopulated
* with mappings as specified by the handbook JSON file for the current language. The keys in the map correspond to
* the keys in the recipes object in that file. This map is not sorted.
*/
static final Map<String, CraftingRecipe> recipes = new HashMap<>();
/**
* Adds a format tag to the handbook. All occurrences of the given tag string preceded by a # will be replaced with
* the result of the given value string on GUI load. The value string, therefore, can be anything that should be
* input dynamically, as long as it does not change while the GUI is open. Examples include wizardry's version,
* the various element colours and the keys assigned to wizardry's controls.
* @param tag The tag string, as defined in the handbook JSON file, excluding the # character. Cannot include spaces.
* @param value The string to replace occurrences of the given format tag with. Can include spaces but not the # character.
*/
public static void addFormatTag(String tag, String value){
FORMAT_TAGS.put(tag, value);
}
private static void initFormatTags(){
addFormatTag("next_spell_key", ClientProxy.NEXT_SPELL.getDisplayName());
addFormatTag("previous_spell_key", ClientProxy.PREVIOUS_SPELL.getDisplayName());
addFormatTag("example_charging_loss", "" + (Constants.MANA_PER_CRYSTAL - 30));
addFormatTag("mana_per_crystal", "" + Constants.MANA_PER_CRYSTAL);
addFormatTag("novice_max_charge", "" + Tier.NOVICE.maxCharge);
addFormatTag("apprentice_max_charge", "" + Tier.APPRENTICE.maxCharge);
addFormatTag("advanced_max_charge", "" + Tier.ADVANCED.maxCharge);
addFormatTag("master_max_charge", "" + Tier.MASTER.maxCharge);
addFormatTag("version", Wizardry.VERSION);
addFormatTag("mcversion", Minecraft.getMinecraft().getVersion());
addFormatTag("colour_novice", "\u00A77");
addFormatTag("colour_apprentice", Tier.APPRENTICE.getFormattingCode());
addFormatTag("colour_advanced", Tier.ADVANCED.getFormattingCode());
addFormatTag("colour_master", Tier.MASTER.getFormattingCode());
addFormatTag("colour_fire", Element.FIRE.getFormattingCode());
addFormatTag("colour_ice", Element.ICE.getFormattingCode());
addFormatTag("colour_lightning", Element.LIGHTNING.getFormattingCode());
addFormatTag("colour_necromancy", Element.NECROMANCY.getFormattingCode());
addFormatTag("colour_earth", Element.EARTH.getFormattingCode());
addFormatTag("colour_sorcery", Element.SORCERY.getFormattingCode());
addFormatTag("colour_healing", Element.HEALING.getFormattingCode());
addFormatTag("colour_reset", "\u00A70");
}
// Helper methods
/**
* Converts the given single page index to a double-page index. Inverse of
* {@link GuiWizardHandbook#doubleToSinglePage(int, boolean)}.
*
* @param singlePageIndex The single-page index, which is the same as the page numbers actually displayed.
* @return The corresponding double-page index.
*/
static int singleToDoublePage(int singlePageIndex){
// Yes, this is trivial, but if I ever change the numbering it'll be useful. It's also more descriptive.
return singlePageIndex / 2;
}
/**
* Converts the given double-page index to a single-page index. Inverse of
* {@link GuiWizardHandbook#singleToDoublePage(int)}.
*
* @param doublePageIndex The double-page index, as stored in {@link GuiWizardHandbook#currentPage}.
* @param rightHandPage True to return the page on the right (1 greater), false for the left-hand page.
* @return The corresponding single-page index.
*/
static int doubleToSinglePage(int doublePageIndex, boolean rightHandPage){
return rightHandPage ? doublePageIndex * 2 + 1 : doublePageIndex * 2;
}
/**
* Returns whether the given page index refers to a right-hand page or a left-hand page.
*
* @param page The single-page index, which is the same as the page number actually displayed.
* @return True if the given page index refers to a right-hand page, false if it is a left-hand page.
*/
static boolean isRightPage(int page){
return page % 2 == 1;
}
// Drawing
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks){
int left = this.width / 2 - GUI_WIDTH / 2;
int top = this.height / 2 - GUI_HEIGHT / 2;
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
GlStateManager.color(1, 1, 1, 1);
// Main background
DrawingUtils.drawTexturedRect(left, top, 0, 0, GUI_WIDTH, GUI_HEIGHT, TEXTURE_WIDTH, TEXTURE_HEIGHT);
// First page background
if(currentPage == 0){
DrawingUtils.drawTexturedRect(left, top, 368, 0, GUI_WIDTH / 2, GUI_HEIGHT, TEXTURE_WIDTH, TEXTURE_HEIGHT);
previous.visible = false;
previousSection.visible = false; // Not worth testing if we're in the first section every frame
menu.visible = false;
}else{
previous.visible = true;
previousSection.visible = true;
menu.visible = true;
}
// Last page background
if(currentPage == singleToDoublePage(pageCount)){
DrawingUtils.drawTexturedFlippedRect(left + GUI_WIDTH / 2, top, 368, 0, GUI_WIDTH / 2, GUI_HEIGHT, TEXTURE_WIDTH, TEXTURE_HEIGHT, true, false);
next.visible = false;
nextSection.visible = false;
}else{
next.visible = true;
nextSection.visible = true;
}
// Page numbers
if(currentPage > 0){
String pageNumber = "" + doubleToSinglePage(currentPage, false);
this.fontRenderer.drawString(pageNumber, left + TEXT_INSET_X + PAGE_WIDTH / 2
- fontRenderer.getStringWidth(pageNumber)/2, top + GUI_HEIGHT - PAGE_NUMBER_INSET, DrawingUtils.BLACK);
}
if(currentPage < singleToDoublePage(pageCount)){
String pageNumber = "" + doubleToSinglePage(currentPage, true);
this.fontRenderer.drawString(pageNumber, left + GUI_WIDTH - TEXT_INSET_X - PAGE_WIDTH / 2
- fontRenderer.getStringWidth(pageNumber)/2, top + GUI_HEIGHT - PAGE_NUMBER_INSET, DrawingUtils.BLACK);
}
// Main content
contentsList.values().forEach(c -> { if(c.section.isUnlocked()) c.draw(fontRenderer, currentPage, left, top); } );
sections.values().forEach(s -> { if(s.isUnlocked()) s.draw(fontRenderer, currentPage, left, top); } );
// These only get populated if the sections are unlocked so no checks are necessary
images.values().forEach(i -> i.draw(fontRenderer, currentPage, left, top));
recipes.values().forEach(r -> r.draw(fontRenderer, itemRender, currentPage, left, top));
// Buttons
super.drawScreen(mouseX, mouseY, partialTicks);
// Bookmark
GlStateManager.color(1, 1, 1, 1);
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
if(currentPage == singleToDoublePage(sections.get(bookmarkSection).startPage) + bookmarkPage){
// If the current page is the bookmarked page, the (invisible) bookmark button is disabled
bookmark.visible = false;
DrawingUtils.drawTexturedRect(left + 138, top, 299, 0, 11, 191, TEXTURE_WIDTH, TEXTURE_HEIGHT);
}else{
bookmark.visible = true;
bookmark.x = left + (currentPage > singleToDoublePage(sections.get(bookmarkSection).startPage) + bookmarkPage ? 130 : 147);
DrawingUtils.drawTexturedRect(bookmark.x, top,
bookmark.isMouseOver() ? 310 : 288, 0, 11, 191, TEXTURE_WIDTH, TEXTURE_HEIGHT);
}
// Recipe tooltips
recipes.values().forEach(r -> r.drawTooltips(this, fontRenderer, itemRender, currentPage, left, top, mouseX, mouseY));
}
// GUI Initialisation / Close
@Override
public void onResize(Minecraft minecraft, int width, int height){
initGui();
}
@Override
public void onGuiClosed(){
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
}
@Override
public void initGui(){
super.initGui();
Keyboard.enableRepeatEvents(true);
initFormatTags();
final int left = this.width / 2 - GUI_WIDTH / 2;
final int top = this.height / 2 - GUI_HEIGHT / 2;
recipes.values().forEach(CraftingRecipe::load);
int nextButtonId = 0;
this.buttonList.clear();
this.buttonList.add(next = new GuiButtonTurnPage(nextButtonId++, left + GUI_WIDTH - BUTTON_INSET_X - GuiButtonTurnPage.WIDTH,
top + GUI_HEIGHT - BUTTON_INSET_Y - GuiButtonTurnPage.HEIGHT, Type.NEXT_PAGE));
this.buttonList.add(previous = new GuiButtonTurnPage(nextButtonId++, left + BUTTON_INSET_X,
top + GUI_HEIGHT - BUTTON_INSET_Y - GuiButtonTurnPage.HEIGHT, Type.PREVIOUS_PAGE));
this.buttonList.add(nextSection = new GuiButtonTurnPage(nextButtonId++, left + GUI_WIDTH - BUTTON_INSET_X - GuiButtonTurnPage.WIDTH - BUTTON_SPACING,
top + GUI_HEIGHT - BUTTON_INSET_Y - GuiButtonTurnPage.HEIGHT, Type.NEXT_SECTION));
this.buttonList.add(previousSection = new GuiButtonTurnPage(nextButtonId++, left + BUTTON_INSET_X + BUTTON_SPACING,
top + GUI_HEIGHT - BUTTON_INSET_Y - GuiButtonTurnPage.HEIGHT, Type.PREVIOUS_SECTION));
this.buttonList.add(menu = new GuiButtonTurnPage(nextButtonId++, left + GUI_WIDTH/2 - 28,
top + GUI_HEIGHT - BUTTON_INSET_Y - GuiButtonTurnPage.HEIGHT, Type.CONTENTS));
this.buttonList.add(bookmark = new GuiButtonInvisible(nextButtonId++, left + 130, top + 172, 11, 19) {
@Override
public void playPressSound(SoundHandler soundHandler){
soundHandler.playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.MISC_PAGE_TURN, 1));
}
});
pageCount = 1;
// Clears instances of all images and recipes
images.values().forEach(Image::clearInstances);
recipes.values().forEach(CraftingRecipe::clearInstances);
// Formats all the unlocked sections in order
for(Section section : sections.values()){
if(section.isUnlocked()){
pageCount = section.format(this.fontRenderer, pageCount, left, top);
buttonList.addAll(section.getButtons());
}
}
contentsList.values().forEach(c -> buttonList.addAll(c.getButtons()));
this.mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(WizardrySounds.MISC_BOOK_OPEN, 1));
}
// JSON Parsing / Data Construction
/**
* Called from preInit in the main mod class (via the proxies) to initialise the handbook (parses the JSON file
* and constructs the relevant data structures), and again on each resource reload (changing the language triggers
* a resource reload).
*/
public static void loadHandbookFile(IResourceManager manager){
IResource handbookFile = getHandbookResource(manager);
if(handbookFile != null){
// Wipes all the maps before repopulating them
images.clear();
sections.clear();
contentsList.clear();
colours.clear();
bookmarkSection = null; // Also need to wipe the reference to the old bookmarked section
BufferedReader reader = new BufferedReader(new InputStreamReader(handbookFile.getInputStream()));
JsonElement je = gson.fromJson(reader, JsonElement.class);
JsonObject json = je.getAsJsonObject();
JsonUtils.getJsonObject(json, "colours").entrySet().forEach(e -> colours.put(e.getKey(),
Color.decode(e.getValue().getAsString()).getRGB()));
// Repopulates the remaining maps
Image.populate(images, json);
CraftingRecipe.populate(recipes, json);
Section.populate(sections, json);
sectionList = Collections.unmodifiableList(new ArrayList<>(sections.values()));
if(sections.isEmpty()){
Wizardry.logger.warn("Handbook has no sections! Aborting loading...");
return;
}
bookmarkSection = JsonUtils.getString(json, "bookmark_start_section");
if(!sections.containsKey(bookmarkSection)) throw new JsonSyntaxException("Section with id " + bookmarkSection + " is undefined");
}
// The first resource load on startup is done before the packet handler is loaded
if(WizardryPacketHandler.net != null) WizardryPacketHandler.net.sendToServer(new PacketRequestAdvancementSync.Message());
}
/**
* Retrieves the handbook JSON file for the current language and returns its IResource object. If a handbook file
* cannot be found for the current language, a message is printed to the console and the method attempts to retrieve
* the default file instead (English-US). If this file cannot be found, the resulting error is printed to the
* console and the method returns null.
*
* @param manager The resource manager instance to use.
* @return The handbook JSON file, as an IResource, or null if it was not found.
*/
private static IResource getHandbookResource(IResourceManager manager){
// TODO: Implement resource pack stacking to allow addon mods and texture packs to add/overwrite content
IResource handbookFile = null;
try{
handbookFile = manager.getResource(new ResourceLocation(Wizardry.MODID, "texts/handbook_"
+ Minecraft.getMinecraft().getLanguageManager().getCurrentLanguage().getLanguageCode() + ".json"));
}catch(IOException e){
Wizardry.logger.info("Wizard handbook JSON file missing for the current language (" + Minecraft.getMinecraft()
.getLanguageManager().getCurrentLanguage() + "). Using default (English-US) instead.");
try{
handbookFile = manager.getResource(DEFAULT);
}catch(IOException x){
Wizardry.logger.error("Couldn't find file: " + DEFAULT + ". The file may be missing; please try re-downloading and reinstalling Wizardry.", x);
}
}
return handbookFile;
}
// Controls
@Override
protected void actionPerformed(GuiButton button){
if(button.enabled){
if(button == next){
if(currentPage < singleToDoublePage(pageCount)) currentPage++;
}else if(button == previous){
if(currentPage > 0) currentPage--;
}else if(button == nextSection || button == previousSection){
Section currentSection = null;
for(Section section : sections.values()){
// We always want this button to do something, and taking the right-hand page means it always does
if(section.containsPage(doubleToSinglePage(currentPage, true))){
currentSection = section;
break;
}
}
if(currentSection != null){
List<Section> visibleSections = new ArrayList<>(sectionList);
visibleSections.removeIf(s -> !s.isUnlocked());
int index = visibleSections.indexOf(currentSection);
if(button == nextSection && index + 1 < visibleSections.size()){
currentPage = singleToDoublePage(visibleSections.get(index + 1).startPage);
}else if(index > 0){
currentPage = singleToDoublePage(visibleSections.get(index - 1).startPage);
}
}
}else if(button == menu){
currentPage = singleToDoublePage(sections.get("main_contents").startPage);
}else if(button == bookmark && bookmarkSection != null){
currentPage = singleToDoublePage(sections.get(bookmarkSection).startPage) + bookmarkPage;
}else{
if(button instanceof GuiButtonHyperlink.Internal){
currentPage = singleToDoublePage(((GuiButtonHyperlink.Internal)button).target.startPage);
}else if(button instanceof GuiButtonHyperlink.External){
this.handleComponentClick(((GuiButtonHyperlink.External)button).link);
}
}
}
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException{
if(mouseButton == 1){
// Right-clicking of bookmark
if(bookmark.mousePressed(this.mc, mouseX, mouseY)){
this.selectedButton = bookmark;
for(String key : sections.keySet()){
// The bookmark is assumed to bookmark the left-hand page
if(sections.get(key).containsPage(doubleToSinglePage(currentPage, false))) bookmarkSection = key;
}
bookmarkPage = currentPage - singleToDoublePage(sections.get(bookmarkSection).startPage);
}
}else{
super.mouseClicked(mouseX, mouseY, mouseButton);
}
}
// Overridden to make it public
@Override
public void renderToolTip(ItemStack stack, int x, int y){
super.renderToolTip(stack, x, y);
}
@Override
public boolean doesGuiPauseGame(){
return Wizardry.settings.booksPauseGame;
}
public static void updateUnlockStatus(boolean showToasts, ResourceLocation... completedAdvancements){
sections.values().forEach(s -> s.updateUnlockStatus(showToasts, completedAdvancements));
}
}
@@ -1,54 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import electroblob.wizardry.registry.WizardryItems;
import net.minecraft.client.gui.toasts.GuiToast;
import net.minecraft.client.gui.toasts.IToast;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
import java.util.List;
//@SideOnly(Side.CLIENT)
public class HandbookToast implements IToast {
private final Section section;
public HandbookToast(Section section){
this.section = section;
}
public IToast.Visibility draw(GuiToast toastGui, long delta){
toastGui.getMinecraft().getTextureManager().bindTexture(TEXTURE_TOASTS);
GlStateManager.color(1.0F, 1.0F, 1.0F);
toastGui.drawTexturedModalRect(0, 0, 0, 32, 160, 32);
boolean firstPart = delta < 1500L;
int a = firstPart ? MathHelper.floor(MathHelper.clamp((float)(1500L - delta) / 300.0F, 0.0F, 1.0F) * 255.0F) << 24 | 67108864
: MathHelper.floor(MathHelper.clamp((float)(delta - 1500L) / 300.0F, 0.0F, 1.0F) * 252.0F) << 24 | 67108864;
String s = firstPart ? I18n.format("handbook.toast.title") : section.title;
int c = firstPart ? -11534256 : -16777216;
List<String> list = toastGui.getMinecraft().fontRenderer.listFormattedStringToWidth(s, 125);
int h = 16 - list.size() * toastGui.getMinecraft().fontRenderer.FONT_HEIGHT / 2;
for(String line : list){
toastGui.getMinecraft().fontRenderer.drawString(line, 30, h, c | a);
h += toastGui.getMinecraft().fontRenderer.FONT_HEIGHT;
}
RenderHelper.enableGUIStandardItemLighting();
toastGui.getMinecraft().getRenderItem().renderItemAndEffectIntoGUI(null, new ItemStack(WizardryItems.wizard_handbook), 8, 8);
return delta >= 5000L ? IToast.Visibility.HIDE : IToast.Visibility.SHOW;
}
}
@@ -1,148 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.client.DrawingUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class Image {
// Final fields are mandatory, the rest are optional
private final ResourceLocation location;
private final int width, height;
private int textureWidth, textureHeight;
private int u = 0, v = 0;
private String caption = "";
private boolean border = true;
// Derived fields, not specifically defined in JSON
private final Set<int[]> instances = new HashSet<>();
private static final int CAPTION_OFFSET = 4;
private static final int TEXTURE_INSET_X = 180;
private static final int BORDER = 1;
private Image(ResourceLocation location, int width, int height){
this.location = location;
this.width = width;
this.height = height;
}
/** Returns the width of the image. */
int getWidth(){
return width;
}
/** Returns the total height of the image, including caption if it has one. */
int getHeight(FontRenderer font){
return caption.isEmpty() ? height : height + CAPTION_OFFSET + font.FONT_HEIGHT;
}
/**
* Adds an instance of this image to the list.
*
* @param page The index of the <b>single</b> page this image is on.
* @param x The x-coordinate of the top-left corner of the image, <i>relative</i> to the top-left corner of the GUI.
* @param y The y-coordinate of the top-left corner of the image, <i>relative</i> to the top-left corner of the GUI.
*/
void addInstance(int page, int x, int y){
instances.add(new int[]{page, x, y});
}
/** Removes all instances of this image from the list. */
void clearInstances(){
instances.clear();
}
/**
* Draws all instances of this image that are located on the given double-page spread.
*
* @param font The font renderer object.
* @param doublePage The double-page index of the page to be drawn.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
*/
void draw(FontRenderer font, int doublePage, int left, int top){
// Images
for(int[] instance : instances){
if(GuiWizardHandbook.singleToDoublePage(instance[0]) == doublePage){
Minecraft.getMinecraft().renderEngine.bindTexture(location);
GlStateManager.color(1, 1, 1, 1);
DrawingUtils.drawTexturedRect(left + instance[1], top + instance[2], u, v, width, height, textureWidth, textureHeight);
font.drawString("\u00A7o" + caption, left + instance[1] + width/ 2 - font.getStringWidth(caption)/2,
top + instance[2] + height + CAPTION_OFFSET, GuiWizardHandbook.colours.get("caption"));
}
}
if(border){
// Borders - do this after all the images are drawn so we only have to bind the handbook texture again once
Minecraft.getMinecraft().renderEngine.bindTexture(GuiWizardHandbook.texture);
GlStateManager.color(1, 1, 1, 1);
for(int[] instance : instances){
if(GuiWizardHandbook.singleToDoublePage(instance[0]) == doublePage){
// Math.ceil accounts for odd-numbered image dimensions
DrawingUtils.drawTexturedFlippedRect(left + instance[1] - BORDER, top + instance[2] - BORDER,
TEXTURE_INSET_X, GuiWizardHandbook.GUI_HEIGHT, width / 2 + BORDER, height / 2 + BORDER,
GuiWizardHandbook.TEXTURE_WIDTH, GuiWizardHandbook.TEXTURE_HEIGHT, false, false);
DrawingUtils.drawTexturedFlippedRect(left + instance[1] + width / 2, top + instance[2] - BORDER,
TEXTURE_INSET_X, GuiWizardHandbook.GUI_HEIGHT, MathHelper.ceil(width / 2f) + BORDER, height / 2 + BORDER,
GuiWizardHandbook.TEXTURE_WIDTH, GuiWizardHandbook.TEXTURE_HEIGHT, true, false);
DrawingUtils.drawTexturedFlippedRect(left + instance[1] - BORDER, top + instance[2] + height / 2,
TEXTURE_INSET_X, GuiWizardHandbook.GUI_HEIGHT, width / 2 + BORDER, MathHelper.ceil(height / 2f) + BORDER,
GuiWizardHandbook.TEXTURE_WIDTH, GuiWizardHandbook.TEXTURE_HEIGHT, false, true);
DrawingUtils.drawTexturedFlippedRect(left + instance[1] + width / 2, top + instance[2] + height / 2,
TEXTURE_INSET_X, GuiWizardHandbook.GUI_HEIGHT, MathHelper.ceil(width / 2f) + BORDER, MathHelper.ceil(height / 2f) + BORDER,
GuiWizardHandbook.TEXTURE_WIDTH, GuiWizardHandbook.TEXTURE_HEIGHT, true, true);
}
}
}
}
/**
* Parses the given JSON object and constructs a new {@code Image} from it, setting all the relevant fields
* and references.
*
* @param json A JSON object representing the image to be constructed. This must contain at least a "location"
* string.
* @return The resulting {@code Image} object.
* @throws JsonSyntaxException if at any point the JSON object is found to be invalid.
*/
static Image fromJson(JsonObject json){
Image image = new Image(new ResourceLocation(JsonUtils.getString(json, "location")),
JsonUtils.getInt(json, "width"), JsonUtils.getInt(json, "height"));
image.u = JsonUtils.getInt(json, "u", 0);
image.v = JsonUtils.getInt(json, "v", 0);
image.textureWidth = JsonUtils.getInt(json, "texture_width", image.width);
image.textureHeight = JsonUtils.getInt(json, "texture_height", image.height);
image.caption = JsonUtils.getString(json, "caption", "");
image.border = JsonUtils.getBoolean(json, "border", true);
return image;
}
static void populate(Map<String, Image> map, JsonObject json){
JsonObject sectionsObject = JsonUtils.getJsonObject(json, "images");
// Need to iterate over these since we don't know what they're called or how many there are
for(Map.Entry<String, JsonElement> entry : sectionsObject.entrySet()){
String key = entry.getKey(); // Find out what each element is called, this will be the sections map key
Image image = fromJson(entry.getValue().getAsJsonObject());
map.put(key, image);
}
}
}
@@ -1,451 +0,0 @@
package electroblob.wizardry.client.gui.handbook;
import com.google.common.collect.Streams;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import electroblob.wizardry.Wizardry;
import electroblob.wizardry.client.DrawingUtils;
import electroblob.wizardry.util.WizardryUtilities;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* Instances of this class represent sections in the wizard's handbook. As of wizardry 4.2, this class handles
* everything within the section itself, including JSON parsing, unlock triggers and drawing the actual rawText.
* Sections may now also be nested and have other elements within them, such as images and a table of contents, a
* behaviour which is also handled within this class.
* <p></p>
* The formatting of the book is now done 'dynamically' - that is, the exact positions and page numbers of
* sections, images and so on are determined on GUI load and depend on which of the previous sections have been
* unlocked, amongst other factors. This means that all of the unlocked sections must be formatted in order on GUI
* load, so that each section knows the previous section's length and therefore where to start.
*
* @author Electroblob
* @since Wizardry 4.2
*/
// Because these are now generated on resource pack reload (not on handbook open, as before), this class can no longer
// be a non-static inner class
class Section {
// Final fields are mandatory (none here though), the rest are optional
String title;
private String[] rawText;
private Contents contents;
private ResourceLocation[] triggers;
private Map<String, Section> subsections;
private boolean centreX, centreY;
// Derived fields, not explicitly defined in JSON
/** The <b>single-page</b> index of the first page of this section. */
int startPage;
private final List<List<GuiButton>> buttons;
/**
* A list of <b>single</b> pages, which are themselves lists of paragraphs (each paragraph is a single
* string which may include line breaks and other escape characters).
*/
private final List<List<String>> pages;
private boolean unlocked = false;
private boolean isNew = false;
private Section(){
this.buttons = new ArrayList<>();
this.pages = new ArrayList<>();
this.subsections = new LinkedHashMap<>();
}
Collection<GuiButton> getButtons(){
return WizardryUtilities.flatten(buttons);
}
/**
* Returns true if the given page is within this section, false if not (or if the section is locked).
*/
boolean containsPage(int page){
return this.isUnlocked() && startPage <= page && startPage + pages.size() > page;
}
/**
* Returns true if this section is unlocked for the client player, false if not. Always returns true if
* handbook progression is disabled in the config.
*/
boolean isUnlocked(){
if(Minecraft.getMinecraft().player.isCreative()) return true;
if(!Wizardry.settings.handbookProgression) return true; // Always unlocked if handbook progression is off
if(triggers == null) return true; // If no triggers were defined, the section is unlocked from the start
// A section is automatically unlocked if one of its subsections is unlocked
for(Section subsection : subsections.values()){
if(subsection.isUnlocked()) return true;
}
return unlocked;
}
/**
* Returns true if this section has been unlocked and not read yet. Also returns true if any subsections are new.
*/
boolean isNew(){
if(!Wizardry.settings.handbookProgression) return false;
return isNew || this.subsections.values().stream().anyMatch(Section::isNew);
}
/**
* Actually draws the contents of the given section for the given double-page spread. Will do nothing if the
* given page is outside of this section.
*
* @param font The font renderer object.
* @param doublePage The index of the <b>double-page</b> to be drawn.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
*/
// This method is supposed to be 'idiot-proof' in the sense that the code calling it need not check whether the
// section actually needs drawing, so it can just dumbly call draw(...) for all the sections in order.
void draw(FontRenderer font, int doublePage, int left, int top){
// Show/hide buttons
int i = 0;
for(List<GuiButton> list : buttons){
final int i1 = i++;
list.forEach(b -> b.visible = GuiWizardHandbook.singleToDoublePage(startPage + i1) == doublePage);
}
int leftIndex = GuiWizardHandbook.doubleToSinglePage(doublePage, false);
// Relative indices of the pages to be rendered - often these will be outside the section entirely
int[] visiblePages = {leftIndex - startPage, leftIndex - startPage + 1};
for(int page : visiblePages){
if(page >= 0 && page < pages.size()){
List<String> lines = pages.get(page);
int x = left + (GuiWizardHandbook.isRightPage(startPage + page) ? GuiWizardHandbook.GUI_WIDTH - GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH : GuiWizardHandbook.TEXT_INSET_X);
int y = top + GuiWizardHandbook.TEXT_INSET_Y;
if(centreY) y += GuiWizardHandbook.PAGE_HEIGHT / 2 - lines.size() / 2 * font.FONT_HEIGHT;
for(String line : lines){
if(line.startsWith(GuiWizardHandbook.FORMAT_MARKER + GuiWizardHandbook.RULER_TAG)){
GlStateManager.color(1, 1, 1, 1);
Minecraft.getMinecraft().renderEngine.bindTexture(GuiWizardHandbook.texture);
DrawingUtils.drawTexturedRect(x-1, y-1, 0, GuiWizardHandbook.GUI_HEIGHT, GuiWizardHandbook.PAGE_WIDTH + 2, 9, GuiWizardHandbook.TEXTURE_WIDTH, GuiWizardHandbook.TEXTURE_HEIGHT);
}else{
int lx = centreX ? x + GuiWizardHandbook.PAGE_WIDTH / 2 - font.getStringWidth(line) / 2 : x;
font.drawString(line, lx, y, DrawingUtils.BLACK, false);
}
y += font.FONT_HEIGHT;
}
isNew = false; // Now a page has been drawn, the player must have seen it so it's not new any more
}
}
}
/**
* Called on GUI load to format the section, contents tables and other elements, <b>excluding</b> subsections.
* Does not perform any actual drawing.
*
* @param font The font renderer object, for measurement purposes.
* @param startPage The index of the first page (single side, not double-page) of this section.
* @param left The x coordinate of the left side of the GUI.
* @param top The y coordinate of the top of the GUI.
* @return The <b>single-page</b> index of the next blank page after the end of this section.
* @throws JsonSyntaxException if at any point the formatting is found to be invalid.
*/
int format(FontRenderer font, int startPage, int left, int top){
this.buttons.clear();
this.pages.clear();
// FONT_HEIGHT may change between fonts, so this is calculated here. With the default font it's 14.
final int maxLineNumber = GuiWizardHandbook.PAGE_HEIGHT / font.FONT_HEIGHT;
this.startPage = startPage;
// First everything is added to a single list of lines, then it is split into pages.
List<String> lines = new ArrayList<>();
// Adds the header if present
if(!this.title.isEmpty()){
lines.add(this.title);
lines.add(GuiWizardHandbook.FORMAT_MARKER + GuiWizardHandbook.RULER_TAG);
}
// Adds space for the contents if it exists
if(this.contents != null){
lines.addAll(Collections.nCopies(this.contents.format(font, startPage, lines.size(), left, top), ""));
// Line break between contents and first paragraph
if((lines.size() % maxLineNumber) != 0) lines.add("");
}
if(this.rawText != null){
// Paragraphs are defined as a JSON list because it makes it easier to arrange them properly across pages
// - using multiple line breaks would mean having to find and remove them when at the top of a page.
for(String paragraph : this.rawText){
// (lines.size() % maxLineNumber) gives the number of lines on the current page
// (lines.size() / maxLineNumber) gives the index of the current page minus the value of startPage
// Formats the paragraph
String raw = paragraph; // For error messages
// Images (images must be separate paragraphs)
if(paragraph.startsWith(GuiWizardHandbook.FORMAT_MARKER + GuiWizardHandbook.IMAGE_TAG)){
String[] arguments = paragraph.split("\\s", 2);
if(arguments.length < 2) throw new JsonSyntaxException("Missing image name in string "
+ StringUtils.abbreviate(raw, 50));
Image image = GuiWizardHandbook.images.get(arguments[1]);
if(image == null) throw new JsonSyntaxException("Image with id " + arguments[1] + " is undefined");
// Starts a new page if the image will not fit on the current one
if((lines.size() % maxLineNumber) * font.FONT_HEIGHT + image.getHeight(font) > GuiWizardHandbook.PAGE_HEIGHT){
// Remaining number of lines on the page
lines.addAll(Collections.nCopies(maxLineNumber - (lines.size() % maxLineNumber), ""));
}
if(image.getWidth() > GuiWizardHandbook.PAGE_WIDTH) Wizardry.logger.warn("Image with id " + arguments[1]
+ "has a width (" + image.getWidth() + ") greater than the maximum page width (" + GuiWizardHandbook.PAGE_WIDTH
+ "), it will extend beyond the page area.");
if(image.getHeight(font) > GuiWizardHandbook.PAGE_HEIGHT) Wizardry.logger.warn("Image with id " + arguments[1]
+ "has a height (" + image.getHeight(font) + ") greater than the maximum page height (" + GuiWizardHandbook.PAGE_HEIGHT
+ "), it will extend beyond the page area.");
int page = startPage + (lines.size() / maxLineNumber);
image.addInstance(page, GuiWizardHandbook.PAGE_WIDTH / 2 - image.getWidth() / 2
+ (GuiWizardHandbook.isRightPage(page) ? GuiWizardHandbook.GUI_WIDTH - GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH : GuiWizardHandbook.TEXT_INSET_X),
GuiWizardHandbook.TEXT_INSET_Y + (lines.size() % maxLineNumber) * font.FONT_HEIGHT);
// Height of the image in lines, rounded up
// Uses a single space instead of an empty string so that the page trimming doesn't remove them
lines.addAll(Collections.nCopies(image.getHeight(font) / font.FONT_HEIGHT, " "));
lines.add(""); // The last one is removable though, since it's actually extra space
// Recipes (recipes must be separate paragraphs)
}else if(paragraph.startsWith(GuiWizardHandbook.FORMAT_MARKER + GuiWizardHandbook.RECIPE_TAG)){
String[] arguments = paragraph.split("\\s", 2);
if(arguments.length < 2) throw new JsonSyntaxException("Missing recipe name in string "
+ StringUtils.abbreviate(raw, 50));
CraftingRecipe recipe = GuiWizardHandbook.recipes.get(arguments[1]);
if(recipe == null) throw new JsonSyntaxException("Recipe with id " + arguments[1] + " is undefined");
// Starts a new page if the recipe will not fit on the current one
if((lines.size() % maxLineNumber) * font.FONT_HEIGHT + CraftingRecipe.HEIGHT > GuiWizardHandbook.PAGE_HEIGHT){
// Remaining number of lines on the page, plus the first blank one on the new page
lines.addAll(Collections.nCopies(maxLineNumber - (lines.size() % maxLineNumber), " "));
}
int page = startPage + (lines.size() / maxLineNumber);
if(lines.size() % maxLineNumber == 0) lines.add(" ");
int startLine = lines.size() % maxLineNumber - 1;
recipe.addInstance(page, GuiWizardHandbook.PAGE_WIDTH / 2 - CraftingRecipe.WIDTH / 2
+ (GuiWizardHandbook.isRightPage(page) ? GuiWizardHandbook.GUI_WIDTH - GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH : GuiWizardHandbook.TEXT_INSET_X),
GuiWizardHandbook.TEXT_INSET_Y + startLine * font.FONT_HEIGHT);
// Height of the recipe in lines, rounded up
// Uses a single space instead of an empty string so that the page trimming doesn't remove them
lines.addAll(Collections.nCopies(CraftingRecipe.HEIGHT / font.FONT_HEIGHT - 1, " "));
// This time we're not adding an extra space because it's not really needed
}else{ // All other paragraphs
// Formatting
for(Map.Entry<String, String> entry : GuiWizardHandbook.FORMAT_TAGS.entrySet()){
paragraph = paragraph.replace(GuiWizardHandbook.FORMAT_MARKER + entry.getKey(), entry.getValue());
}
// Hyperlinks
int linkStart;
while((linkStart = paragraph.indexOf(GuiWizardHandbook.HYPERLINK_MARKER)) > -1){ // Ooh an assignment and a comparison in one...
int linkEnd = paragraph.indexOf(GuiWizardHandbook.HYPERLINK_MARKER, linkStart + 1);
if(linkEnd < 0) throw new JsonSyntaxException("Un-closed hyperlink marker in string "
+ StringUtils.abbreviate(raw, 50));
List<String> upToLink = font.listFormattedStringToWidth(paragraph.substring(0, linkStart), GuiWizardHandbook.PAGE_WIDTH);
String linkRaw = paragraph.substring(linkStart, linkEnd + 1);
String[] arguments = paragraph.substring(linkStart + 1, linkEnd).split("\\s", 2);
String suffix = paragraph.substring(linkEnd).split("\\s", 2)[0].substring(1); // substring(1) to remove the @
// The index of the single page currently being formatted, relative to the section
int pageRelative = (lines.size() + upToLink.size() - 1) / maxLineNumber;
// The overall index of the single page currently being formatted
int page = startPage + pageRelative;
// The line number on this page
int lineNumber = (lines.size() + upToLink.size() - 1) % maxLineNumber;
int x = GuiWizardHandbook.isRightPage(page) ? left + GuiWizardHandbook.GUI_WIDTH - GuiWizardHandbook.TEXT_INSET_X - GuiWizardHandbook.PAGE_WIDTH : left + GuiWizardHandbook.TEXT_INSET_X;
int y = top + GuiWizardHandbook.TEXT_INSET_Y + lineNumber * font.FONT_HEIGHT;
// Adds any missing sub-lists
while(this.buttons.size() <= pageRelative){
this.buttons.add(new ArrayList<>());
}
// The button id only does what you use it for, so we're just not using it at all.
this.buttons.get(pageRelative).add(GuiButtonHyperlink.create(x, y, font, upToLink, arguments, suffix, maxLineNumber - lineNumber - 1, GuiWizardHandbook.isRightPage(page)));
// The link button should exactly overlay the display rawText in the main string
// If the link has no display rawText specified, it displays the unformatted target string
paragraph = paragraph.replace(linkRaw, arguments[arguments.length - 1]);
}
lines.addAll(font.listFormattedStringToWidth(paragraph, GuiWizardHandbook.PAGE_WIDTH));
}
// Line break between paragraphs (the last one will just be deleted later)
if((lines.size() % maxLineNumber) != 0) lines.add("");
}
}
// Splits lines into pages
List<String> page = new ArrayList<>();
pages.add(page);
while(!lines.isEmpty()){
if(page.size() == maxLineNumber){
// Removes blank lines at the end of the page
while(page.get(page.size() - 1).isEmpty()) page.remove(page.size() - 1);
// Adds a new page
pages.add(page = new ArrayList<>());
}
String line = lines.remove(0);
// Prevents blank lines at the start of the page
if(!page.isEmpty() || !line.isEmpty()) page.add(line);
}
return startPage + pages.size();
}
/**
* Parses the given JSON object and constructs a new {@code Section} from it, setting all the relevant fields
* and references. This method converts the JSON object to a {@code Section} object and retrieves any resources;
* the section is not formatted in any way until GUI load, in {@link Section#format(FontRenderer, int, int, int)}.
*
* @param json A JSON object representing the section to be constructed. This must contain at least a "title"
* string.
* @return The resulting {@code Section} object.
* @throws JsonSyntaxException if at any point the JSON object is found to be invalid.
*/
static Section fromJson(JsonObject json){
Section section = new Section();
section.title = JsonUtils.getString(json, "title", "");
if(JsonUtils.hasField(json, "include_in_contents")){
String id = JsonUtils.getString(json, "include_in_contents");
Contents belongsTo = GuiWizardHandbook.contentsList.get(id);
if(belongsTo == null){
throw new JsonSyntaxException("Expected include_in_contents to be the id of a previously defined contents, but no contents with the id " + id + " exists yet.");
}else{
belongsTo.addEntry(section);
}
}
if(JsonUtils.hasField(json, "contents")){
section.contents = Contents.fromJson(section, JsonUtils.getJsonObject(json, "contents"));
GuiWizardHandbook.contentsList.put(section.contents.id, section.contents);
}
if(JsonUtils.hasField(json, "text")){
section.rawText = Streams.stream(JsonUtils.getJsonArray(json, "text"))
.map(e -> JsonUtils.getString(e, "element of array rawText"))
.toArray(String[]::new);
}
if(JsonUtils.hasField(json, "triggers")){
section.triggers = Streams.stream(JsonUtils.getJsonArray(json, "triggers"))
.map(e -> new ResourceLocation(JsonUtils.getString(e, "element of array triggers")))
.toArray(ResourceLocation[]::new);
// TODO: Can we validate this and throw a JSON exception if no such advancement exists?
}
if(JsonUtils.hasField(json, "centre")){
JsonObject centre = JsonUtils.getJsonObject(json,"centre");
section.centreX = JsonUtils.getBoolean(centre, "x", false);
section.centreY = JsonUtils.getBoolean(centre, "y", false);
}
// The only benefit of having subsections (other than logical grouping) is that the parent section can
// automatically be unlocked if one of the subsections is.
if(JsonUtils.hasField(json, "sections")){
populate(section.subsections, json);
}
return section;
}
static void populate(Map<String, Section> map, JsonObject json){
JsonObject sectionsObject = JsonUtils.getJsonObject(json, "sections");
// Need to iterate over these since we don't know what they're called or how many there are
for(Map.Entry<String, JsonElement> entry : sectionsObject.entrySet()){
String key = entry.getKey(); // Find out what each element is called, this will be the sections map key
Section section = fromJson(entry.getValue().getAsJsonObject());
map.put(key, section);
map.putAll(section.subsections);
}
}
/**
* Called on login and advancement completion to update this section's unlock status and display toast
* notifications if applicable.
*/
public void updateUnlockStatus(boolean showToasts, ResourceLocation... completedAdvancements){
if(triggers == null) return;
List<ResourceLocation> completed = new ArrayList<>(Arrays.asList(completedAdvancements));
completed.retainAll(Arrays.asList(triggers));
// Only shows the toast when the section was locked before and is now unlocked
if(!this.unlocked && !completed.isEmpty() && showToasts && Wizardry.settings.handbookProgression){
// Mmmmm toast...
Minecraft minecraft = Minecraft.getMinecraft();
minecraft.getToastGui().add(new HandbookToast(this));
this.isNew = true;
}
// Currently, this will not take subsections into account
this.unlocked = !completed.isEmpty();
}
}
@@ -1,234 +0,0 @@
package electroblob.wizardry.client.model;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
import net.minecraftforge.client.model.pipeline.VertexLighterFlat;
import net.minecraftforge.common.ForgeModContainer;
import net.minecraftforge.fml.client.FMLClientHandler;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nullable;
import javax.vecmath.Matrix4f;
import java.util.ArrayList;
import java.util.List;
/**
* Custom baked model that stores a list of texture names and sets the lighting to full brightness for any quads
* with one of those textures. Most of this code was copied and adapted from refined storage, which is licensed under
* the MIT license. https://github.com/raoulvdberge/refinedstorage<br>
* <br>
* <i>N.B. This doesn't cover item models, and all of the code/model solutions to this that I have tried haven't worked.
* However, I noticed that the shade tag seems to work perfectly for items, so instead I've simply duplicated the block
* models into the item models folder and add {@code "shade":false} where appropriate. (If it works, it works, right?)</i>
*
* @author Electroblob
* @author raoulvdberge
*/
public class BakedModelGlowingOverlay implements IBakedModel {
// Something something something cache, says Forge
// This breaks randomised block models (because it's cached, duh...) but simply including the rand parameter will
// completely defeat the point of the cache so I need some way of storing the randomised model variants... hmmm...
// See WeightedBakedModel for more on randomisation (it's pretty similar to my 1.7 implementation from years ago)
// private class CacheKey {
//
// private IBakedModel base;
// private String suffix;
// private IBlockState state;
// private EnumFacing side;
//
// public CacheKey(IBakedModel base, String suffix, IBlockState state, EnumFacing side){
// this.base = base;
// this.suffix = suffix;
// this.state = state;
// this.side = side;
// }
//
// @Override
// public boolean equals(Object o){
//
// if(this == o) return true;
// if(o == null || getClass() != o.getClass()) return false;
//
// CacheKey cacheKey = (CacheKey)o;
//
// if(cacheKey.side != side) return false;
// if(!state.equals(cacheKey.state)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return state.hashCode() + (31 * (side != null ? side.hashCode() : 0));
// }
// }
//
// private static final LoadingCache<CacheKey, List<BakedQuad>> CACHE = CacheBuilder.newBuilder().build(new CacheLoader<CacheKey, List<BakedQuad>>() {
// @Override
// public List<BakedQuad> load(CacheKey key) {
// return transformQuads(key.base.getQuads(key.state, key.side, 0), key.suffix);
// }
// });
private final IBakedModel delegate;
private String suffix;
public BakedModelGlowingOverlay(IBakedModel delegate, String suffix){
this.delegate = delegate;
this.suffix = suffix;
}
@Override
public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand){
if(state == null) return delegate.getQuads(state, side, rand);
return transformQuads(delegate.getQuads(state, side, rand), suffix);
//return CACHE.getUnchecked(new CacheKey(delegate, suffix, state instanceof IExtendedBlockState ? ((IExtendedBlockState) state).getClean() : state, side));
}
// I would write these myself but I'd end up with almost the exact same thing anyway
// They replace the quads from the original (delegate) model with full-brightness quads if their texture has the given suffix
private static List<BakedQuad> transformQuads(List<BakedQuad> oldQuads, String suffix){
List<BakedQuad> quads = new ArrayList<>(oldQuads);
for(int i = 0; i < quads.size(); ++i){
BakedQuad quad = quads.get(i);
if(quad.getSprite().getIconName().endsWith(suffix)){
quads.set(i, transformQuad(quad, 0.007F)); // What's the significance of 0.007?
}
}
return quads;
}
private static BakedQuad transformQuad(BakedQuad quad, float light){
if(isLightMapDisabled()){
return quad;
}
VertexFormat newFormat = getFormatWithLightMap(quad.getFormat());
UnpackedBakedQuad.Builder builder = new UnpackedBakedQuad.Builder(newFormat);
VertexLighterFlat trans = new VertexLighterFlat(Minecraft.getMinecraft().getBlockColors()) {
@Override
protected void updateLightmap(float[] normal, float[] lightmap, float x, float y, float z){
lightmap[0] = light;
lightmap[1] = light;
}
@Override
public void setQuadTint(int tint){
// NO OP
}
};
trans.setParent(builder);
quad.pipe(trans);
builder.setQuadTint(quad.getTintIndex());
builder.setQuadOrientation(quad.getFace());
builder.setTexture(quad.getSprite());
builder.setApplyDiffuseLighting(false);
return builder.build();
}
@Override
public boolean isAmbientOcclusion(){
return delegate.isAmbientOcclusion();
}
@Override
public boolean isGui3d(){
return delegate.isGui3d();
}
@Override
public boolean isBuiltInRenderer(){
return delegate.isBuiltInRenderer();
}
@Override
public TextureAtlasSprite getParticleTexture(){
return delegate.getParticleTexture();
}
@Override
public ItemCameraTransforms getItemCameraTransforms(){
return delegate.getItemCameraTransforms();
}
@Override
public ItemOverrideList getOverrides(){
return delegate.getOverrides();//BakedModelItemOverride.instance;
}
@Override
public boolean isAmbientOcclusion(IBlockState state){
return delegate.isAmbientOcclusion(state);
}
@Override
public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType){
return delegate.handlePerspective(cameraTransformType);
}
// Utilities
private static boolean isLightMapDisabled(){
return FMLClientHandler.instance().hasOptifine() || !ForgeModContainer.forgeLightPipelineEnabled;
}
private static final VertexFormat ITEM_FORMAT_WITH_LIGHTMAP = new VertexFormat(DefaultVertexFormats.ITEM).addElement(DefaultVertexFormats.TEX_2S);
private static VertexFormat getFormatWithLightMap(VertexFormat format){
if(isLightMapDisabled()){
return format;
}
if(format == DefaultVertexFormats.BLOCK){
return DefaultVertexFormats.BLOCK;
}else if(format == DefaultVertexFormats.ITEM){
return ITEM_FORMAT_WITH_LIGHTMAP;
}else if(!format.hasUvOffset(1)){
VertexFormat result = new VertexFormat(format);
result.addElement(DefaultVertexFormats.TEX_2S);
return result;
}
return format;
}
// Bit of a weird way of doing things if you ask me, but as far as I can tell it's how you're supposed to do it
// public static final class BakedModelItemOverride extends ItemOverrideList {
//
// // This class doesn't contain any data of its own so it can be a singleton
// public static final BakedModelItemOverride instance = new BakedModelItemOverride();
//
// private BakedModelItemOverride(){
// super(ImmutableList.of()); // We're not using the list functionality
// }
//
// @Override
// public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity){
// return new BakedModelGlowingOverlay(originalModel, "overlay"); // Bish bash bosh
// }
// }
}
@@ -1,49 +0,0 @@
package electroblob.wizardry.client.model;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityArmorStand;
/**
* Fixes custom armour models 'breathing' on the stand and rotates the helmet properly.
* @author Shadows-of-Fire
* @since Wizardry 4.1.2
*/
public class ModelArmourFixer extends ModelBiped {
public ModelArmourFixer(float modelSize, float rotationYOffset, int textureWidth, int textureHeight) {
super(modelSize, rotationYOffset, textureWidth, textureHeight);
}
@Override
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) {
// [VanillaCopy] ModelArmorStandArmor
// this prevents helmets from always facing south, and the armor "breathing" on the stand
if (entityIn instanceof EntityArmorStand) {
EntityArmorStand entityarmorstand = (EntityArmorStand) entityIn;
this.bipedHead.rotateAngleX = 0.017453292F * entityarmorstand.getHeadRotation().getX();
this.bipedHead.rotateAngleY = 0.017453292F * entityarmorstand.getHeadRotation().getY();
this.bipedHead.rotateAngleZ = 0.017453292F * entityarmorstand.getHeadRotation().getZ();
this.bipedHead.setRotationPoint(0.0F, 1.0F, 0.0F);
this.bipedBody.rotateAngleX = 0.017453292F * entityarmorstand.getBodyRotation().getX();
this.bipedBody.rotateAngleY = 0.017453292F * entityarmorstand.getBodyRotation().getY();
this.bipedBody.rotateAngleZ = 0.017453292F * entityarmorstand.getBodyRotation().getZ();
this.bipedLeftArm.rotateAngleX = 0.017453292F * entityarmorstand.getLeftArmRotation().getX();
this.bipedLeftArm.rotateAngleY = 0.017453292F * entityarmorstand.getLeftArmRotation().getY();
this.bipedLeftArm.rotateAngleZ = 0.017453292F * entityarmorstand.getLeftArmRotation().getZ();
this.bipedRightArm.rotateAngleX = 0.017453292F * entityarmorstand.getRightArmRotation().getX();
this.bipedRightArm.rotateAngleY = 0.017453292F * entityarmorstand.getRightArmRotation().getY();
this.bipedRightArm.rotateAngleZ = 0.017453292F * entityarmorstand.getRightArmRotation().getZ();
this.bipedLeftLeg.rotateAngleX = 0.017453292F * entityarmorstand.getLeftLegRotation().getX();
this.bipedLeftLeg.rotateAngleY = 0.017453292F * entityarmorstand.getLeftLegRotation().getY();
this.bipedLeftLeg.rotateAngleZ = 0.017453292F * entityarmorstand.getLeftLegRotation().getZ();
this.bipedLeftLeg.setRotationPoint(1.9F, 11.0F, 0.0F);
this.bipedRightLeg.rotateAngleX = 0.017453292F * entityarmorstand.getRightLegRotation().getX();
this.bipedRightLeg.rotateAngleY = 0.017453292F * entityarmorstand.getRightLegRotation().getY();
this.bipedRightLeg.rotateAngleZ = 0.017453292F * entityarmorstand.getRightLegRotation().getZ();
this.bipedRightLeg.setRotationPoint(-1.9F, 11.0F, 0.0F);
copyModelAngles(this.bipedHead, this.bipedHeadwear);
} else super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn);
}
}

Some files were not shown because too many files have changed in this diff Show More