aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/gregtech/common/tileentities/generators/MTEMagicalEnergyAbsorber.java
blob: 242d8eaaeaa2c3306dd4abf6e048dbcbc5184f9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
package gregtech.common.tileentities.generators;

import static gregtech.api.enums.GTValues.V;
import static gregtech.api.enums.Mods.Thaumcraft;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_DRAGONEGG;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_DRAGONEGG_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_ACTIVE;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_ACTIVE_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_FRONT;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_FRONT_ACTIVE;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_FRONT_ACTIVE_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_FRONT_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.MACHINE_CASING_MAGIC_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAYS_ENERGY_OUT;
import static gregtech.api.objects.XSTR.XSTR_INSTANCE;
import static net.minecraft.util.EnumChatFormatting.GRAY;
import static net.minecraft.util.EnumChatFormatting.GREEN;
import static net.minecraft.util.EnumChatFormatting.LIGHT_PURPLE;
import static net.minecraft.util.EnumChatFormatting.RESET;
import static net.minecraft.util.EnumChatFormatting.UNDERLINE;
import static net.minecraft.util.EnumChatFormatting.YELLOW;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import net.minecraft.block.Block;
import net.minecraft.block.BlockDragonEgg;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.item.EntityEnderCrystal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemEnchantedBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.common.util.ForgeDirection;

import com.google.common.base.Enums;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import gregtech.api.enums.ParticleFX;
import gregtech.api.enums.TCAspects;
import gregtech.api.interfaces.ITexture;
import gregtech.api.interfaces.tileentity.IGregTechTileEntity;
import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.metatileentity.implementations.MTEBasicGenerator;
import gregtech.api.recipe.RecipeMap;
import gregtech.api.recipe.RecipeMaps;
import gregtech.api.render.TextureFactory;
import gregtech.api.util.GTLanguageManager;
import gregtech.api.util.GTLog;
import gregtech.api.util.GTUtility;
import gregtech.api.util.WorldSpawnedEventBuilder.ParticleEventBuilder;
import gregtech.common.config.MachineStats;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import thaumcraft.api.aspects.AspectSourceHelper;
import thaumcraft.api.aspects.IAspectContainer;
import thaumcraft.api.visnet.VisNetHandler;

interface MagicalEnergyBBListener {

    void onMagicalEnergyBBUpdate();
}

public class MTEMagicalEnergyAbsorber extends MTEBasicGenerator implements MagicalEnergyBBListener {

    private static final ConcurrentHashMap<UUID, MTEMagicalEnergyAbsorber> sSubscribedCrystals = new ConcurrentHashMap<>(
        4);
    private static final List<Aspect> sPrimalAspects = (Thaumcraft.isModLoaded()) ? Aspect.getPrimalAspects()
        : new ArrayList<>();
    private static final Map<Aspect, Integer> sAspectsEnergy = new HashMap<>();
    private static boolean sAllowMultipleEggs = false;
    private static MTEMagicalEnergyAbsorber sActiveSiphon = null;
    private static final int sEnergyPerEndercrystal = 512;
    private static final int sEnergyFromVis = 20;
    private static final int sEnergyPerEssentia = 320;
    private static final int sDragonEggEnergyPerTick = 2048;
    private static final int sCreeperEggEnergyPerTick = 512;
    private final MagicalEnergyBB mMagicalEnergyBB = new MagicalEnergyBB(this, mTier, mTier + 2);
    private int mEfficiency;
    private int mMaxVisPerDrain;
    private long mNextGenerateTickRate = 1;
    private int mNoGenerationTicks = 0;
    private boolean mUsingEssentia = true;

    public MTEMagicalEnergyAbsorber(int aID, String aName, String aNameRegional, int aTier) {
        super(aID, aName, aNameRegional, aTier, "Feasts on magic close to it:");
        onConfigLoad();
    }

    private MTEMagicalEnergyAbsorber(String aName, int aTier, String[] aDescription, ITexture[][][] aTextures) {
        super(aName, aTier, aDescription, aTextures);
        onConfigLoad();
    }

    /**
     * Populates static variables dependant on config settings
     */
    private static void sharedConfigLoad() {
        sAllowMultipleEggs = MachineStats.machines.allowMultipleEggs;
        if (Thaumcraft.isModLoaded()) {
            for (Aspect tAspect : Aspect.aspects.values()) {
                // noinspection UnstableApiUsage
                sAspectsEnergy.put(
                    tAspect,
                    Enums.getIfPresent(
                        TCAspects.class,
                        tAspect.getTag()
                            .toUpperCase(Locale.ENGLISH))
                        .or(TCAspects.AER).mValue * sEnergyPerEssentia);
            }
        }
    }

    private static void setActiveSiphon(MTEMagicalEnergyAbsorber aSiphon) {
        sActiveSiphon = aSiphon;
    }

    public void onConfigLoad() {
        sharedConfigLoad();
        mEfficiency = 100 - mTier * 10;
        mMaxVisPerDrain = (int) Math.round(Math.sqrt((double) (V[mTier] * 10000) / (sEnergyFromVis * getEfficiency())));
        if (Math.pow(mMaxVisPerDrain, 2) * sEnergyFromVis * getEfficiency() < V[mTier]) {
            mMaxVisPerDrain += 1;
        }
    }

    @Override
    public void onScrewdriverRightClick(ForgeDirection side, EntityPlayer aPlayer, float aX, float aY, float aZ) {
        if (aPlayer.isSneaking()) mMagicalEnergyBB.decreaseTier();
        else mMagicalEnergyBB.increaseTier();
        GTUtility.sendChatToPlayer(
            aPlayer,
            String.format(
                GTLanguageManager.addStringLocalization(
                    "Interaction_DESCRIPTION_MagicalEnergyAbsorber_Screwdriver",
                    "Absorption range: %s blocks"),
                mMagicalEnergyBB.getRange(),
                true));
        mMagicalEnergyBB.update();
    }

    @Override
    public void onFirstTick(IGregTechTileEntity aBaseMetaTileEntity) {
        if (!aBaseMetaTileEntity.isServerSide()) return;
        mMagicalEnergyBB.update();
    }

    @Override
    public void onRemoval() {
        super.onRemoval();
        releaseEgg();
        unsubscribeCrystals();
    }

    private void releaseEgg() {
        if (sActiveSiphon == this) {
            setActiveSiphon(null);
        }
    }

    private void unsubscribeCrystals() {
        for (UUID tCrystalID : sSubscribedCrystals.keySet()) {
            sSubscribedCrystals.remove(tCrystalID, this);
        }
    }

    /**
     * Call-back from the Bounding Box when its content is updated
     */
    @Override
    public void onMagicalEnergyBBUpdate() {
        List<UUID> tCrystalIDsInRange = mMagicalEnergyBB.getLivingCrystalIDs();
        // Release unreachable Crystals subscriptions
        for (UUID tSubscribedCrystalID : sSubscribedCrystals.keySet()) {
            if (!tCrystalIDsInRange.contains(tSubscribedCrystalID)) {
                sSubscribedCrystals.remove(tSubscribedCrystalID, this);
            }
        }
        // Subscribe to available and not already subscribed Crystals
        for (UUID tCrystalID : tCrystalIDsInRange) {
            sSubscribedCrystals.putIfAbsent(tCrystalID, this);
        }
    }

    @Override
    public String[] getDescription() {
        final String LI = "- %%%";
        final String EU_PER = "%%%EU per ";
        List<String> description = new ArrayList<>();
        description
            .add(UNDERLINE + "Feasts on " + LIGHT_PURPLE + UNDERLINE + "magic" + GRAY + UNDERLINE + " close to it:");
        description.add(
            LI + (sAllowMultipleEggs ? "A " : "An " + YELLOW + UNDERLINE + "EXCLUSIVE" + RESET)
                + GRAY
                + " "
                + LIGHT_PURPLE
                + "Dragon Egg"
                + GRAY
                + " atop");
        if (sEnergyPerEndercrystal > 0) {
            description.add(LI + sEnergyPerEndercrystal + EU_PER + LIGHT_PURPLE + "Ender Crystal" + GRAY + " in range");
        }
        if (Thaumcraft.isModLoaded()) {
            description.add(LI + mMaxVisPerDrain + "%%%CV/t from an " + LIGHT_PURPLE + "Energised Node" + GRAY);
            description.add(
                LI + (sEnergyPerEssentia * getEfficiency()) / 100
                    + EU_PER
                    + LIGHT_PURPLE
                    + "Essentia"
                    + GRAY
                    + " Aspect-Value from containers in range");
        }
        description.add(" ");
        description.add(UNDERLINE + "Lookup range (Use Screwdriver to change):");
        description.add("Default: %%%" + GREEN + mMagicalEnergyBB.getDefaultRange());
        description.add("Max: %%%" + GREEN + mMagicalEnergyBB.getMaxRange());
        description.add(" ");
        description
            .add(UNDERLINE + "Fuels on " + LIGHT_PURPLE + UNDERLINE + "enchantments" + GRAY + UNDERLINE + " input:");
        description.add(
            "- Item: %%%" + (10000 * getEfficiency()) / 100
                + EU_PER
                + LIGHT_PURPLE
                + "enchant"
                + GRAY
                + " weight × level / max");
        description.add("- Book: %%%" + 10000 + EU_PER + LIGHT_PURPLE + "enchant" + GRAY + " weight × level / max");
        description.add(" ");
        description.add("Efficiency: %%%" + GREEN + getEfficiency() + "%");
        return description.toArray(new String[0]);
    }

    @Override
    public ITexture[] getFront(byte aColor) {
        return new ITexture[] { super.getFront(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_GLOW)
                .glow()
                .build(),
            OVERLAYS_ENERGY_OUT[mTier] };
    }

    @Override
    public ITexture[] getBack(byte aColor) {
        return new ITexture[] { super.getBack(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC_FRONT),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_FRONT_GLOW)
                .glow()
                .build() };
    }

    @Override
    public ITexture[] getBottom(byte aColor) {
        return new ITexture[] { super.getBottom(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_GLOW)
                .glow()
                .build() };
    }

    @Override
    public ITexture[] getTop(byte aColor) {
        return new ITexture[] { super.getTop(aColor)[0], TextureFactory.of(MACHINE_CASING_DRAGONEGG) };
    }

    @Override
    public ITexture[] getSides(byte aColor) {
        return new ITexture[] { super.getSides(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_GLOW)
                .glow()
                .build() };
    }

    @Override
    public ITexture[] getFrontActive(byte aColor) {
        return new ITexture[] { super.getFrontActive(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC_ACTIVE),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_ACTIVE_GLOW)
                .glow()
                .build(),
            OVERLAYS_ENERGY_OUT[mTier] };
    }

    @Override
    public ITexture[] getBackActive(byte aColor) {
        return new ITexture[] { super.getBackActive(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC_FRONT_ACTIVE),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_FRONT_ACTIVE_GLOW)
                .glow()
                .build() };
    }

    @Override
    public ITexture[] getBottomActive(byte aColor) {
        return new ITexture[] { super.getBottomActive(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC_ACTIVE),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_ACTIVE_GLOW)
                .glow()
                .build() };
    }

    @Override
    public ITexture[] getTopActive(byte aColor) {
        return new ITexture[] { super.getTopActive(aColor)[0], TextureFactory.of(MACHINE_CASING_DRAGONEGG),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_DRAGONEGG_GLOW)
                .glow()
                .build() };
    }

    @Override
    public ITexture[] getSidesActive(byte aColor) {
        return new ITexture[] { super.getSidesActive(aColor)[0], TextureFactory.of(MACHINE_CASING_MAGIC_ACTIVE),
            TextureFactory.builder()
                .addIcon(MACHINE_CASING_MAGIC_ACTIVE_GLOW)
                .glow()
                .build() };
    }

    @Override
    public boolean isOutputFacing(ForgeDirection side) {
        return side == getBaseMetaTileEntity().getFrontFacing();
    }

    @Override
    public long maxEUStore() {
        return Math.max(getEUVar(), V[mTier] * 16000 + getMinimumStoredEU());
    }

    @Override
    public void onPostTick(IGregTechTileEntity aBaseMetaTileEntity, long aTick) {
        if (!aBaseMetaTileEntity.isServerSide()) return;
        if (!aBaseMetaTileEntity.isAllowedToWork()) return;
        if ((aBaseMetaTileEntity.getUniversalEnergyStored() >= aBaseMetaTileEntity.getEUCapacity())) return;

        long tGeneratedEU;

        if (aTick % 100 == 0 && mUsingEssentia) mMagicalEnergyBB.update();

        // Adaptive EU Generation Ticking
        if (aTick % mNextGenerateTickRate == 0) {
            tGeneratedEU = generateEU();
            if (tGeneratedEU > 0) {
                mNoGenerationTicks = 0;
                if (tGeneratedEU >= 2 * V[mTier])
                    mNextGenerateTickRate = (long) (1.0D / ((2.0D * (double) (V[mTier])) / (double) tGeneratedEU));
                else mNextGenerateTickRate = 1;
                mInventory[getStackDisplaySlot()] = new ItemStack(Blocks.fire, 1);
                mInventory[getStackDisplaySlot()].setStackDisplayName("Generating: " + tGeneratedEU + " EU");
            } else {
                mInventory[getStackDisplaySlot()] = null;
                mNoGenerationTicks += 1;
            }
            if (mNoGenerationTicks > 20) {
                mNoGenerationTicks = 0;
                mNextGenerateTickRate = 20;
            }
            aBaseMetaTileEntity.increaseStoredEnergyUnits(tGeneratedEU, true);
            aBaseMetaTileEntity.setActive(
                aBaseMetaTileEntity.isAllowedToWork()
                    && aBaseMetaTileEntity.getUniversalEnergyStored() >= maxEUOutput() + getMinimumStoredEU());
        }
    }

    /**
     * Draws random portal particles on top when active with an egg on top
     *
     * @param aBaseMetaTileEntity The entity that will handle the {@link Block#randomDisplayTick}
     */
    @SideOnly(Side.CLIENT)
    @Override
    public void onRandomDisplayTick(IGregTechTileEntity aBaseMetaTileEntity) {

        if (aBaseMetaTileEntity.isActive()) {

            if (isEgg(aBaseMetaTileEntity.getBlockAtSide(ForgeDirection.UP))) {

                final double oX = aBaseMetaTileEntity.getXCoord() + 8D / 16D;
                final double oY = aBaseMetaTileEntity.getYCoord() + 17D / 32D;
                final double oZ = aBaseMetaTileEntity.getZCoord() + 8D / 16D;

                final ParticleEventBuilder particleEventBuilder = new ParticleEventBuilder()
                    .setWorld(getBaseMetaTileEntity().getWorld())
                    .setIdentifier(ParticleFX.PORTAL);

                for (int i = 0; i < 9; i++) {
                    final double dX = (XSTR_INSTANCE.nextFloat() - 0.5D) / 2D;
                    final double dY = XSTR_INSTANCE.nextFloat() * 1.5;
                    final double dZ = (XSTR_INSTANCE.nextFloat() - 0.5D) / 2D;

                    final double x = oX + dX;
                    final double y = oY + dY;
                    final double z = oZ + dZ;

                    final double mX = dX * 4D;
                    final double dXZ = Math.sqrt(dX * dX + dZ * dZ);
                    final double mY = -(dXZ * dY) / 4D;
                    final double mZ = dZ * 4D;

                    particleEventBuilder.setMotion(mX, mY, mZ)
                        .setPosition(x, y, z)
                        .run();
                }
            }
        }
    }

    @Override
    public int getPollution() {
        return 0;
    }

    @Override
    public RecipeMap<?> getRecipeMap() {
        return RecipeMaps.magicFuels;
    }

    @Override
    public int getEfficiency() {
        return mEfficiency;
    }

    @Override
    public boolean allowPutStack(IGregTechTileEntity aBaseMetaTileEntity, int aIndex, ForgeDirection side,
        ItemStack aStack) {
        // Restrict input to disenchantable items or enchanted books
        return (isDisenchantableItem(aStack) || isEnchantedBook(aStack));
    }

    @Override
    public int getCapacity() {
        return 16000;
    }

    private boolean isDisenchantableItem(ItemStack aStack) {
        return ((aStack.isItemEnchanted()) && (aStack.getItem()
            .getItemEnchantability() > 0));
    }

    private boolean isEnchantedBook(ItemStack aStack) {
        return (aStack.getItem() instanceof ItemEnchantedBook);
    }

    private long generateEU() {
        long tEU;

        mUsingEssentia = false;
        if ((tEU = absorbFromEgg()) > 0) return tEU;
        if ((tEU = absorbFromEnderCrystals()) > 0) return tEU;
        if ((tEU = absorbFromEnchantedItems()) > 0) return tEU;
        if ((tEU = absorbFromVisNet()) > 0) return tEU;
        mUsingEssentia = true;
        if ((tEU = absorbFromEssentiaContainers()) > 0) return tEU;
        return 0;
    }

    private long absorbFromEnchantedItems() {
        ItemStack tStack = getBaseMetaTileEntity().getStackInSlot(getInputSlot());
        if (tStack == null) return 0;
        if (tStack.stackSize == 0) return 0;
        if (!(isDisenchantableItem(tStack) || isEnchantedBook(tStack))) return 0;
        long tEU = 0;
        // Convert enchantments to their EU Value
        Map<?, ?> tMap = EnchantmentHelper.getEnchantments(tStack);
        for (Map.Entry<?, ?> e : tMap.entrySet()) {
            if ((Integer) e.getKey() < Enchantment.enchantmentsList.length) {
                Enchantment tEnchantment = Enchantment.enchantmentsList[(Integer) e.getKey()];
                Integer tLevel = (Integer) e.getValue();
                tEU += 1000000L * tLevel / tEnchantment.getMaxLevel() / tEnchantment.getWeight();
            }
        }

        ItemStack tOutputStack = GTUtility.copyAmount(1, tStack);
        if (tOutputStack != null) {
            if (isDisenchantableItem(tOutputStack)) {
                tEU = tEU * getEfficiency() / 100;
                EnchantmentHelper.setEnchantments(new HashMap<>(), tOutputStack);
            } else if (isEnchantedBook(tOutputStack)) {
                tOutputStack = new ItemStack(Items.book, 1);
            }
        }

        // Only consume input when it can store EU and push output
        if ((getBaseMetaTileEntity().getStoredEU() + tEU) < getBaseMetaTileEntity().getEUCapacity()
            && getBaseMetaTileEntity().addStackToSlot(getOutputSlot(), tOutputStack)) {
            decrStackSize(getInputSlot(), 1);
        } else {
            tEU = 0;
        }
        return tEU;
    }

    private boolean hasEgg() {
        Block above = getBaseMetaTileEntity().getBlockOffset(0, 1, 0);
        return isEgg(above);
    }

    private long absorbFromEgg() {
        if (!hasEgg()) return 0;
        if (!sAllowMultipleEggs) {
            if (sActiveSiphon != null && sActiveSiphon != this
                && sActiveSiphon.getBaseMetaTileEntity() != null
                && !sActiveSiphon.getBaseMetaTileEntity()
                    .isInvalidTileEntity()
                && sActiveSiphon.isChunkLoaded()
                && sActiveSiphon.hasEgg()) {
                getBaseMetaTileEntity().doExplosion(Integer.MAX_VALUE);
            } else {
                setActiveSiphon(this);
            }
        }
        Block egg = getBaseMetaTileEntity().getBlockOffset(0, 1, 0);
        if (egg == Blocks.dragon_egg) {
            return sDragonEggEnergyPerTick;
        } else if (egg.getUnlocalizedName()
            .contains("creeperEgg")) {
                return sCreeperEggEnergyPerTick;
            }
        return 0;
    }

    private long absorbFromEnderCrystals() {
        if (sEnergyPerEndercrystal <= 0) return 0;
        long tEU = 0;
        for (MTEMagicalEnergyAbsorber tSubscriber : sSubscribedCrystals.values()) {
            if (tSubscriber == this) { // This Crystal is for me
                tEU += sEnergyPerEndercrystal;
            }
        }
        return tEU;
    }

    private long absorbFromVisNet() {
        if (!Thaumcraft.isModLoaded()) return 0;

        long tEU;
        IGregTechTileEntity tBaseMetaTileEntity = getBaseMetaTileEntity();
        World tWorld = tBaseMetaTileEntity.getWorld();
        int tX = tBaseMetaTileEntity.getXCoord();
        int tY = tBaseMetaTileEntity.getYCoord();
        int tZ = tBaseMetaTileEntity.getZCoord();

        // Attempt to drain as much Vis as needed for max EU/t, from all primal aspects.
        int toDrain = mMaxVisPerDrain;

        for (int i = sPrimalAspects.size() - 1; i >= 0 && toDrain > 0; i--) {
            toDrain -= VisNetHandler.drainVis(tWorld, tX, tY, tZ, sPrimalAspects.get(i), toDrain);
        }

        int drained = mMaxVisPerDrain - toDrain;
        tEU = (long) Math.min(maxEUOutput(), (Math.pow(drained, 2) * sEnergyFromVis * getEfficiency() / 10000));

        return tEU;
    }

    private long absorbFromEssentiaContainers() {
        if (!Thaumcraft.isModLoaded()) return 0;

        long tEU = 0;

        long tEUtoGen = getBaseMetaTileEntity().getEUCapacity() - getBaseMetaTileEntity().getUniversalEnergyStored();
        List<Aspect> mAvailableEssentiaAspects = mMagicalEnergyBB.getAvailableAspects();

        // try to drain 1 of whatever aspect available in containers within RANGE
        for (int i = mAvailableEssentiaAspects.size() - 1; i >= 0 && tEUtoGen > 0; i--) {
            Aspect aspect = mAvailableEssentiaAspects.get(i);
            long tAspectEU = ((long) sAspectsEnergy.get(aspect) * getEfficiency()) / 100;
            if (tAspectEU <= tEUtoGen && AspectSourceHelper.drainEssentia(
                (TileEntity) getBaseMetaTileEntity(),
                aspect,
                ForgeDirection.UNKNOWN,
                mMagicalEnergyBB.getRange())) {
                tEUtoGen -= tAspectEU;
                tEU += tAspectEU;
            }
        }
        return tEU;
    }

    private boolean isEgg(Block aBlock) {
        if (aBlock == null) return false;
        if (aBlock == Blocks.air) return false;
        if (aBlock == Blocks.dragon_egg) return true;
        if (aBlock instanceof BlockDragonEgg) return true;
        return (aBlock.getUnlocalizedName()
            .equals("tile.dragonEgg"));
    }

    private boolean isChunkLoaded() {
        IGregTechTileEntity tBaseMetaTileEntity = getBaseMetaTileEntity();
        int tX = tBaseMetaTileEntity.getXCoord();
        int tY = tBaseMetaTileEntity.getYCoord();
        World tWorld = tBaseMetaTileEntity.getWorld();
        Chunk tChunk = tWorld.getChunkFromBlockCoords(tX, tY);
        return tChunk.isChunkLoaded;
    }

    @Override
    public MetaTileEntity newMetaEntity(IGregTechTileEntity aTileEntity) {
        return new MTEMagicalEnergyAbsorber(mName, mTier, mDescriptionArray, mTextures);
    }

    @Override
    public void saveNBTData(NBTTagCompound aNBT) {
        super.saveNBTData(aNBT);
        aNBT.setInteger("mMagicalEnergyBBTier", mMagicalEnergyBB.getTier());
    }

    @Override
    public void loadNBTData(NBTTagCompound aNBT) {
        super.loadNBTData(aNBT);
        mMagicalEnergyBB.setTier(aNBT.getInteger("mMagicalEnergyBBTier"));
    }

    /**
     * Handles Bounding Box ranged operations for Magic sources
     */
    static class MagicalEnergyBB {

        private final MTEMagicalEnergyAbsorber mAbsorber;
        private final MagicalEnergyBBListener mListener;
        private final int mDefaultTier;
        private int mTier;
        private final int mMaxTier;
        private final List<UUID> mLivingCrystalIDs = new ArrayList<>();
        private List<Aspect> mAvailableAspects;

        /**
         * @param aAbsorber    user and subscriber for updated BB content
         * @param aDefaultTier Initial tier value
         * @param aMaxTier     Maximum allowed tier
         */
        MagicalEnergyBB(MTEMagicalEnergyAbsorber aAbsorber, int aDefaultTier, int aMaxTier) {
            mAbsorber = aAbsorber;
            mListener = aAbsorber;
            mMaxTier = Math.max(Math.max(aMaxTier, 0), Math.max(aDefaultTier, 0));
            mDefaultTier = Math.min(aDefaultTier, mMaxTier);
            mTier = mDefaultTier;
            if (Thaumcraft.isModLoaded()) mAvailableAspects = new ArrayList<>(Aspect.aspects.size());
        }

        int getTier() {
            return mTier;
        }

        /**
         * Set Bounding Box Tier within allowed bounds
         *
         * @param aTier new tier value
         * @return effective new tier
         */
        int setTier(int aTier) {
            if (aTier >= 0) {
                mTier = Math.min(aTier, mMaxTier);
            } else {
                mTier = 0;
            }
            return mTier;
        }

        int getRange() {
            return getRange(mTier);
        }

        int getRange(int aTier) {
            return 1 << aTier;
        }

        int getDefaultTier() {
            return mDefaultTier;
        }

        int getDefaultRange() {
            return getRange(getDefaultTier());
        }

        int getMaxTier() {
            return mMaxTier;
        }

        int getMaxRange() {
            return getRange(getMaxTier());
        }

        private AxisAlignedBB getAxisAlignedBB() {
            double tRange = getRange();
            IGregTechTileEntity tBaseMetaTileEntity = mAbsorber.getBaseMetaTileEntity();
            double tX = tBaseMetaTileEntity.getXCoord();
            double tY = tBaseMetaTileEntity.getYCoord();
            double tZ = tBaseMetaTileEntity.getZCoord();
            return AxisAlignedBB
                .getBoundingBox(tX - tRange, tY - tRange, tZ - tRange, tX + tRange, tY + tRange, tZ + tRange);
        }

        private void scanLivingCrystals() {
            World tWorld = mAbsorber.getBaseMetaTileEntity()
                .getWorld();
            mLivingCrystalIDs.clear();
            for (EntityEnderCrystal o : tWorld.getEntitiesWithinAABB(EntityEnderCrystal.class, getAxisAlignedBB())) {
                if (o.isEntityAlive()) {
                    mLivingCrystalIDs.add(o.getPersistentID());
                }
            }
        }

        private void scanAvailableAspects() {
            if (!Thaumcraft.isModLoaded()) return;
            IGregTechTileEntity tBaseMetaTileEntity = mAbsorber.getBaseMetaTileEntity();
            if (tBaseMetaTileEntity.isInvalidTileEntity()) return;
            int tRange = getRange();
            int tY = tBaseMetaTileEntity.getYCoord();
            int tMaxY = tBaseMetaTileEntity.getWorld()
                .getHeight() - 1;
            // Make sure relative Y range stays between 0 and world max Y
            int rYMin = (tY - tRange >= 0) ? -tRange : -(tY);
            int rYMax = (((tY + tRange) <= tMaxY) ? tRange : tMaxY - tY);
            mAvailableAspects.clear();
            for (int rX = -tRange; rX <= tRange; rX++) {
                for (int rZ = -tRange; rZ <= tRange; rZ++) {
                    // rY < rYMax is not a bug. See: thaumcraft.common.lib.events.EssentiaHandler.getSources()
                    for (int rY = rYMin; rY < rYMax; rY++) {
                        TileEntity tTile = tBaseMetaTileEntity.getTileEntityOffset(rX, rY, rZ);
                        if (tTile instanceof IAspectContainer) {
                            AspectList tAspectList = ((IAspectContainer) tTile).getAspects();
                            if (tAspectList == null || tAspectList.aspects.isEmpty()) continue;
                            Set<Aspect> tAspects = tAspectList.aspects.keySet();
                            mAvailableAspects.addAll(tAspects);
                        }
                    }
                }
            }
        }

        /**
         * @return List of Living Ender Crystal Entity IDs in range
         */
        List<UUID> getLivingCrystalIDs() {
            return mLivingCrystalIDs;
        }

        /**
         * @return List of drainable Essentia Aspects from containers in range
         */
        List<Aspect> getAvailableAspects() {
            return mAvailableAspects;
        }

        /**
         * Scan range for magic sources
         */
        void update() {
            if (mAbsorber == null) return;
            if (mAbsorber.getBaseMetaTileEntity() == null) return;
            if (mAbsorber.getBaseMetaTileEntity()
                .isInvalidTileEntity()) return;
            if (mAbsorber.getBaseMetaTileEntity()
                .getWorld() == null) return;
            scanLivingCrystals();
            scanAvailableAspects();
            if (mListener != null) {
                mListener.onMagicalEnergyBBUpdate();
            }
        }

        void increaseTier() {
            offsetTier(1);
        }

        void decreaseTier() {
            offsetTier(-1);
        }

        /**
         * Change the Bounding Box tier relatively to offset with wrapping at tier limits
         *
         * @param aOffset relative tier change
         */
        void offsetTier(int aOffset) {
            int tNumTiers = mMaxTier + 1;
            int tTier = (mTier + aOffset + tNumTiers) % tNumTiers;
            int tTrueTier = setTier(tTier);
            if (tTier != tTrueTier) {
                GTLog.out.format("Absorber's BB Tier set to %d was capped to %d", tTier, tTrueTier);
            }
        }
    }
}