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
|
package gregtech.common.tileentities.machines.multi.purification;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.lazy;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.ofBlock;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.ofBlockAnyMeta;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.ofChain;
import static gregtech.api.enums.GTValues.AuthorNotAPenguin;
import static gregtech.api.enums.HatchElement.Energy;
import static gregtech.api.enums.HatchElement.ExoticEnergy;
import static gregtech.api.enums.HatchElement.Maintenance;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE_GLOW;
import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_GLOW;
import static gregtech.api.metatileentity.BaseTileEntity.TOOLTIP_DELAY;
import static gregtech.api.util.GTRecipeBuilder.SECONDS;
import static gregtech.api.util.GTStructureUtility.ofFrame;
import static gregtech.common.tileentities.machines.multi.purification.MTEPurificationUnitBase.WATER_BOOST_BONUS_CHANCE;
import static gregtech.common.tileentities.machines.multi.purification.MTEPurificationUnitBase.WATER_BOOST_NEEDED_FLUID;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.util.ForgeDirection;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment;
import com.gtnewhorizon.structurelib.structure.StructureDefinition;
import com.gtnewhorizons.modularui.api.drawable.IDrawable;
import com.gtnewhorizons.modularui.api.drawable.UITexture;
import com.gtnewhorizons.modularui.api.drawable.shapes.Rectangle;
import com.gtnewhorizons.modularui.api.forge.ItemStackHandler;
import com.gtnewhorizons.modularui.api.math.Alignment;
import com.gtnewhorizons.modularui.api.math.Color;
import com.gtnewhorizons.modularui.api.math.Size;
import com.gtnewhorizons.modularui.api.screen.ModularWindow;
import com.gtnewhorizons.modularui.api.screen.UIBuildContext;
import com.gtnewhorizons.modularui.api.widget.Widget;
import com.gtnewhorizons.modularui.common.internal.network.NetworkUtils;
import com.gtnewhorizons.modularui.common.widget.ButtonWidget;
import com.gtnewhorizons.modularui.common.widget.DynamicPositionedColumn;
import com.gtnewhorizons.modularui.common.widget.DynamicPositionedRow;
import com.gtnewhorizons.modularui.common.widget.FakeSyncWidget;
import com.gtnewhorizons.modularui.common.widget.Scrollable;
import com.gtnewhorizons.modularui.common.widget.SlotWidget;
import com.gtnewhorizons.modularui.common.widget.TextWidget;
import gregtech.api.GregTechAPI;
import gregtech.api.enums.ItemList;
import gregtech.api.enums.Materials;
import gregtech.api.enums.Textures;
import gregtech.api.gui.modularui.GTUITextures;
import gregtech.api.gui.widgets.LockedWhileActiveButton;
import gregtech.api.interfaces.IHatchElement;
import gregtech.api.interfaces.ITexture;
import gregtech.api.interfaces.metatileentity.IMetaTileEntity;
import gregtech.api.interfaces.tileentity.IGregTechTileEntity;
import gregtech.api.metatileentity.implementations.MTEExtendedPowerMultiBlockBase;
import gregtech.api.render.TextureFactory;
import gregtech.api.util.GTLog;
import gregtech.api.util.GTStructureUtility;
import gregtech.api.util.GTUtility;
import gregtech.api.util.MultiblockTooltipBuilder;
import gregtech.api.util.shutdown.ShutDownReasonRegistry;
import gregtech.common.gui.modularui.widget.ShutDownReasonSyncer;
import gregtech.common.gui.modularui.widget.TextButtonWidget;
public class MTEPurificationPlant extends MTEExtendedPowerMultiBlockBase<MTEPurificationPlant>
implements ISurvivalConstructable {
private static final String STRUCTURE_PIECE_MAIN = "main";
private static final String STRUCTURE_PIECE_MAIN_SURVIVAL = "main_survival";
/**
* Maximum distance in each axis between the purification plant main controller and the controller blocks of the
* purification plant units.
*/
public static final int MAX_UNIT_DISTANCE = 32;
/**
* Time in ticks for a full processing cycle to complete.
*/
public static final int CYCLE_TIME_TICKS = 120 * SECONDS;
/**
* Stores all purification units linked to this controller.
* Normally all units in this list should be valid and unique, if not then there is a bug where they are not being
* unlinked properly on block destruction/relinking.
*/
private final List<LinkedPurificationUnit> mLinkedUnits = new ArrayList<>();
/**
* Debug mode is an operational mode that does not produce output or consume input, but cuts down
* processing time for players to more easily debug their automation setups.
*/
private boolean debugMode = false;
public static final int CYCLE_TIME_IN_DEBUG = 30 * SECONDS;
private static final IStructureDefinition<MTEPurificationPlant> STRUCTURE_DEFINITION = StructureDefinition
.<MTEPurificationPlant>builder()
.addShape(STRUCTURE_PIECE_MAIN, PurificationPlantStructureString.STRUCTURE_STRING)
// Create an identical structure for survival autobuild, with water replaced with air
.addShape(
STRUCTURE_PIECE_MAIN_SURVIVAL,
Arrays.stream(PurificationPlantStructureString.STRUCTURE_STRING)
.map(
sa -> Arrays.stream(sa)
.map(s -> s.replaceAll("F", " "))
.toArray(String[]::new))
.toArray(String[][]::new))
// Superplasticizer-treated high strength concrete
.addElement('A', ofBlock(GregTechAPI.sBlockCasings9, 3))
// Sterile Water Plant Casing
.addElement('B', ofBlock(GregTechAPI.sBlockCasings9, 4))
// Reinforced Sterile Water Plant Casing
.addElement('C', ofBlock(GregTechAPI.sBlockCasings9, 5))
// Tinted Industrial Glass
.addElement('D', ofBlockAnyMeta(GregTechAPI.sBlockTintedGlass, 0))
.addElement('F', ofBlock(Blocks.water, 0))
.addElement('G', ofFrame(Materials.Tungsten))
// Hatch space
.addElement(
'H',
ofChain(
lazy(
t -> GTStructureUtility.<MTEPurificationPlant>buildHatchAdder()
.atLeastList(t.getAllowedHatches())
.dot(1)
.casingIndex(GTUtility.getCasingTextureIndex(GregTechAPI.sBlockCasings9, 4))
.build()),
ofBlock(GregTechAPI.sBlockCasings9, 4)))
.build();
public MTEPurificationPlant(int aID, String aName, String aNameRegional) {
super(aID, aName, aNameRegional);
}
public MTEPurificationPlant(String aName) {
super(aName);
}
@Override
public void construct(ItemStack stackSize, boolean hintsOnly) {
buildPiece(STRUCTURE_PIECE_MAIN, stackSize, hintsOnly, 3, 6, 0);
}
@Override
public int survivalConstruct(ItemStack stackSize, int elementBudget, ISurvivalBuildEnvironment env) {
int built = survivialBuildPiece(STRUCTURE_PIECE_MAIN_SURVIVAL, stackSize, 3, 6, 0, elementBudget, env, true);
if (built == -1) {
GTUtility.sendChatToPlayer(
env.getActor(),
EnumChatFormatting.GREEN + "Auto placing done ! Now go place the water yourself !");
return 0;
}
return built;
}
@Override
public IStructureDefinition<MTEPurificationPlant> getStructureDefinition() {
return STRUCTURE_DEFINITION;
}
@Override
protected MultiblockTooltipBuilder createTooltip() {
final MultiblockTooltipBuilder tt = new MultiblockTooltipBuilder();
tt.addMachineType("Purification Plant")
.addInfo("Main controller block for the Water Purification Plant.")
.addInfo(
"Freely place " + EnumChatFormatting.YELLOW
+ "Purification Units "
+ EnumChatFormatting.GRAY
+ "within "
+ EnumChatFormatting.RED
+ MAX_UNIT_DISTANCE
+ EnumChatFormatting.GRAY
+ " blocks along each axis.")
.addInfo("Left click this controller with a data stick, then right click a purification unit to link.")
.addInfo("Supplies power to linked purification units.")
.addTecTechHatchInfo()
.addSeparator()
.addInfo(
"Works in fixed time processing cycles of " + EnumChatFormatting.RED
+ CYCLE_TIME_TICKS / SECONDS
+ EnumChatFormatting.GRAY
+ " seconds.")
.addInfo("All linked units follow this cycle.")
.addSeparator()
.addInfo("Every recipe has a base chance of success. Success rate can be boosted")
.addInfo("by using a portion of the target output as a secondary input.")
.addInfo(
EnumChatFormatting.RED + GTUtility.formatNumbers(WATER_BOOST_NEEDED_FLUID * 100)
+ "%"
+ EnumChatFormatting.GRAY
+ " of output yield will be consumed in exchange for an")
.addInfo(
"additive " + EnumChatFormatting.RED
+ GTUtility.formatNumbers(WATER_BOOST_BONUS_CHANCE * 100)
+ "%"
+ EnumChatFormatting.GRAY
+ " increase to success.")
.addInfo(
"On recipe failure, each purification unit has a " + EnumChatFormatting.RED
+ "50%"
+ EnumChatFormatting.GRAY
+ " chance")
.addInfo("to return water of the same quality as the input or lower.")
.addSeparator()
.addInfo("Every purification unit has a configuration window to configure maximum parallel amount.")
.addInfo(
"This will only scale purified water input, ALL fluid output and power usage. Other catalysts and outputs are unchanged.")
.addInfo("Toggle debug mode to reduce cycle time to 30s but disable water I/O.")
.addSeparator()
.addInfo(
EnumChatFormatting.AQUA + ""
+ EnumChatFormatting.ITALIC
+ "Contaminants and ionized particles in water can cause significant imperfections in delicate")
.addInfo(
EnumChatFormatting.AQUA + ""
+ EnumChatFormatting.ITALIC
+ "processes related to the cutting and engraving of silicon wafers and chips. It is crucial that")
.addInfo(
EnumChatFormatting.AQUA + ""
+ EnumChatFormatting.ITALIC
+ "the water is systematically purified through a series of increasingly precise and complex")
.addInfo(
EnumChatFormatting.AQUA + ""
+ EnumChatFormatting.ITALIC
+ "purification processes, and this multiblock is the heart of the operation.")
.beginStructureBlock(7, 9, 8, false)
.addCasingInfoExactlyColored(
"Superplasticizer-Treated High Strength Concrete",
EnumChatFormatting.GRAY,
56,
EnumChatFormatting.GOLD,
false)
.addCasingInfoRangeColored(
"Sterile Water Plant Casing",
EnumChatFormatting.GRAY,
71,
72,
EnumChatFormatting.GOLD,
false)
.addCasingInfoExactlyColored(
"Reinforced Sterile Water Plant Casing",
EnumChatFormatting.GRAY,
77,
EnumChatFormatting.GOLD,
false)
.addCasingInfoExactlyColored(
"Tungsten Frame Box",
EnumChatFormatting.GRAY,
30,
EnumChatFormatting.GOLD,
false)
.addCasingInfoExactlyColored(
"Tinted Industrial Glass",
EnumChatFormatting.GRAY,
6,
EnumChatFormatting.GOLD,
false)
.addController("Front center")
.addEnergyHatch(EnumChatFormatting.GOLD + "1", 1)
.addMaintenanceHatch(EnumChatFormatting.GOLD + "1", 1)
.addStructureInfo("Requires water to be placed in the tank.")
.toolTipFinisher(AuthorNotAPenguin);
return tt;
}
@Override
public IMetaTileEntity newMetaEntity(IGregTechTileEntity aTileEntity) {
return new MTEPurificationPlant(this.mName);
}
@Override
public ITexture[] getTexture(IGregTechTileEntity baseMetaTileEntity, ForgeDirection side, ForgeDirection facing,
int colorIndex, boolean active, boolean redstoneLevel) {
if (side == facing) {
if (active) return new ITexture[] {
Textures.BlockIcons
.getCasingTextureForId(GTUtility.getCasingTextureIndex(GregTechAPI.sBlockCasings9, 4)),
TextureFactory.builder()
.addIcon(OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE)
.extFacing()
.build(),
TextureFactory.builder()
.addIcon(OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE_GLOW)
.extFacing()
.glow()
.build() };
return new ITexture[] {
Textures.BlockIcons
.getCasingTextureForId(GTUtility.getCasingTextureIndex(GregTechAPI.sBlockCasings9, 4)),
TextureFactory.builder()
.addIcon(OVERLAY_FRONT_PROCESSING_ARRAY)
.extFacing()
.build(),
TextureFactory.builder()
.addIcon(OVERLAY_FRONT_PROCESSING_ARRAY_GLOW)
.extFacing()
.glow()
.build() };
}
return new ITexture[] {
Textures.BlockIcons.getCasingTextureForId(GTUtility.getCasingTextureIndex(GregTechAPI.sBlockCasings9, 4)) };
}
@Override
public boolean isCorrectMachinePart(ItemStack aStack) {
return true;
}
private List<IHatchElement<? super MTEPurificationPlant>> getAllowedHatches() {
return ImmutableList.of(Maintenance, Energy, ExoticEnergy);
}
@Override
public boolean checkMachine(IGregTechTileEntity aBaseMetaTileEntity, ItemStack aStack) {
// Check self
if (!checkPiece(STRUCTURE_PIECE_MAIN, 3, 6, 0)) {
return false;
}
// Check hatches
if (!checkHatches()) {
return false;
}
// using nano forge method of detecting hatches.
return checkExoticAndNormalEnergyHatches();
}
private boolean checkHatches() {
// Exactly one maintenance hatch is required
return mMaintenanceHatches.size() == 1;
}
public boolean debugModeOn() {
return debugMode;
}
@Override
public void onPostTick(IGregTechTileEntity aBaseMetaTileEntity, long aTick) {
super.onPostTick(aBaseMetaTileEntity, aTick);
if (aBaseMetaTileEntity.isServerSide()) {
// Trigger structure check of linked units, but never all in the same tick, and at most once per cycle.
for (int i = 0; i < mLinkedUnits.size(); ++i) {
if (aTick % CYCLE_TIME_TICKS == i) {
LinkedPurificationUnit unit = mLinkedUnits.get(i);
boolean structure = unit.metaTileEntity()
.checkStructure(true);
// If unit was active but deformed, set as inactive
if (unit.isActive() && !structure) {
unit.setActive(false);
// Also remember to recalculate power usage, since otherwise the deformed unit will
// keep drawing power
this.lEUt = -calculateEffectivePowerUsage();
}
}
}
}
}
@Override
protected void runMachine(IGregTechTileEntity aBaseMetaTileEntity, long aTick) {
updateCycleProgress();
// Calculate efficiency based on maintenance issues
if (mMaxProgresstime > 0) {
mEfficiency = Math.max(
0,
Math.min(
mEfficiency + mEfficiencyIncrease,
getMaxEfficiency(mInventory[1]) - ((getIdealStatus() - getRepairStatus()) * 1000)));
}
}
private void updateCycleProgress() {
// Since the plant does not run recipes directly, we just continuously loop the base cycle
if (mMachine) {
// cycle is running, so simply advance it
if (mMaxProgresstime > 0) {
// onRunningTick is responsible for draining power
if (onRunningTick(mInventory[1])) {
markDirty();
mProgresstime += 1;
// Update progress time for active units
for (LinkedPurificationUnit unit : this.mLinkedUnits) {
if (unit.isActive()) {
MTEPurificationUnitBase<?> metaTileEntity = unit.metaTileEntity();
metaTileEntity.mProgresstime = mProgresstime;
}
}
// Cycle finished
if (mProgresstime >= mMaxProgresstime) {
this.endCycle();
}
} else {
// Power drain failed, shut down all other units due to power loss.
// Note that we do not need to shut down self, as this is done in
// onRunningTick already
for (LinkedPurificationUnit unit : mLinkedUnits) {
if (unit.isActive()) {
unit.metaTileEntity()
.stopMachine(ShutDownReasonRegistry.POWER_LOSS);
}
}
}
}
// No cycle running, start a new cycle if the machine is turned on
if (mMaxProgresstime == 0 && isAllowedToWork()) {
this.startCycle();
}
}
}
private void startCycle() {
mProgresstime = 0;
// Debug mode uses shorter cycles
if (debugMode) mMaxProgresstime = CYCLE_TIME_IN_DEBUG;
else mMaxProgresstime = CYCLE_TIME_TICKS;
mEfficiency = (10000 - (getIdealStatus() - getRepairStatus()) * 1000);
// Find active units and notify them that the cycle started
for (LinkedPurificationUnit unit : this.mLinkedUnits) {
MTEPurificationUnitBase<?> metaTileEntity = unit.metaTileEntity();
PurificationUnitStatus status = metaTileEntity.status();
// Unit needs to be online to be considered active.
if (status == PurificationUnitStatus.ONLINE) {
// Perform recipe check for unit and start it if successful
if (metaTileEntity.doPurificationRecipeCheck()) {
unit.setActive(true);
metaTileEntity.startCycle(mMaxProgresstime, mProgresstime);
}
}
}
// After activating all units, calculate power usage
lEUt = -calculateEffectivePowerUsage();
}
private void endCycle() {
mMaxProgresstime = 0;
// Mark all units as inactive and reset their progress time
for (LinkedPurificationUnit unit : this.mLinkedUnits) {
MTEPurificationUnitBase<?> metaTileEntity = unit.metaTileEntity();
// If this unit was active, end the cycle
if (unit.isActive()) {
metaTileEntity.endCycle();
}
unit.setActive(false);
}
}
/**
* Calculate power usage of all units
*/
private long calculateEffectivePowerUsage() {
long euT = 0;
for (LinkedPurificationUnit unit : mLinkedUnits) {
if (unit.isActive()) {
euT += unit.metaTileEntity()
.getActualPowerUsage();
}
}
return euT;
}
@Override
public int getMaxEfficiency(ItemStack aStack) {
return 10000;
}
@Override
public int getDamageToComponent(ItemStack aStack) {
return 0;
}
@Override
public boolean explodesOnComponentBreak(ItemStack aStack) {
return false;
}
public void registerLinkedUnit(MTEPurificationUnitBase<?> unit) {
LinkedPurificationUnit link = new LinkedPurificationUnit(unit);
// Make sure to mark it as active if it is running a recipe. This happens on server restart and fixes
// waterline multiblocks not resuming their progress until the next cycle.
link.setActive(unit.mMaxProgresstime > 0);
this.mLinkedUnits.add(link);
}
public void unregisterLinkedUnit(MTEPurificationUnitBase<?> unit) {
this.mLinkedUnits.removeIf(link -> link.metaTileEntity() == unit);
}
@Override
public void onLeftclick(IGregTechTileEntity aBaseMetaTileEntity, EntityPlayer aPlayer) {
if (!(aPlayer instanceof EntityPlayerMP)) return;
// Save link data to data stick, very similar to Crafting Input Buffer.
ItemStack dataStick = aPlayer.inventory.getCurrentItem();
if (!ItemList.Tool_DataStick.isStackEqual(dataStick, false, true)) return;
NBTTagCompound tag = new NBTTagCompound();
tag.setString("type", "PurificationPlant");
tag.setInteger("x", aBaseMetaTileEntity.getXCoord());
tag.setInteger("y", aBaseMetaTileEntity.getYCoord());
tag.setInteger("z", aBaseMetaTileEntity.getZCoord());
dataStick.stackTagCompound = tag;
dataStick.setStackDisplayName(
"Purification Plant Link Data Stick (" + aBaseMetaTileEntity
.getXCoord() + ", " + aBaseMetaTileEntity.getYCoord() + ", " + aBaseMetaTileEntity.getZCoord() + ")");
aPlayer.addChatMessage(new ChatComponentText("Saved Link Data to Data Stick"));
}
@Override
public String[] getInfoData() {
var ret = new ArrayList<String>();
// Show linked purification units and their status
ret.add("Linked Purification Units: ");
for (LinkedPurificationUnit unit : this.mLinkedUnits) {
String text = EnumChatFormatting.AQUA + unit.metaTileEntity()
.getLocalName() + ": ";
PurificationUnitStatus status = unit.metaTileEntity()
.status();
switch (status) {
case ONLINE -> {
text = text + EnumChatFormatting.GREEN + "Online";
}
case DISABLED -> {
text = text + EnumChatFormatting.YELLOW + "Disabled";
}
case INCOMPLETE_STRUCTURE -> {
text = text + EnumChatFormatting.RED + "Incomplete Structure";
}
}
ret.add(text);
}
return ret.toArray(new String[0]);
}
@Override
public void onBlockDestroyed() {
// When the controller is destroyed we want to notify all currently linked units
for (LinkedPurificationUnit unit : this.mLinkedUnits) {
unit.metaTileEntity()
.unlinkController();
}
super.onBlockDestroyed();
}
private void drawTopText(DynamicPositionedColumn screenElements) {
screenElements.setSynced(false)
.setSpace(0)
.setPos(10, 8);
screenElements
.widget(
new TextWidget(GTUtility.trans("138", "Incomplete Structure.")).setDefaultColor(EnumChatFormatting.RED)
.setEnabled(widget -> !mMachine))
.widget(new FakeSyncWidget.BooleanSyncer(() -> mMachine, val -> mMachine = val));
screenElements.widget(
new TextWidget("Hit with Soft Mallet to start.").setDefaultColor(EnumChatFormatting.BLACK)
.setEnabled(
widget -> getBaseMetaTileEntity().getErrorDisplayID() == 0 && !getBaseMetaTileEntity().isActive()))
.widget(
new FakeSyncWidget.IntegerSyncer(
() -> getBaseMetaTileEntity().getErrorDisplayID(),
val -> getBaseMetaTileEntity().setErrorDisplayID(val)))
.widget(
new FakeSyncWidget.BooleanSyncer(
() -> getBaseMetaTileEntity().isActive(),
val -> getBaseMetaTileEntity().setActive(val)));
screenElements.widget(
new TextWidget(GTUtility.trans("142", "Running perfectly.")).setDefaultColor(EnumChatFormatting.GREEN)
.setEnabled(
widget -> getBaseMetaTileEntity().getErrorDisplayID() == 0 && getBaseMetaTileEntity().isActive()));
screenElements.widget(
TextWidget.dynamicString(
() -> getBaseMetaTileEntity().getLastShutDownReason()
.getDisplayString())
.setSynced(false)
.setTextAlignment(Alignment.CenterLeft)
.setEnabled(
widget -> shouldDisplayShutDownReason() && !getBaseMetaTileEntity().isActive()
&& GTUtility.isStringValid(
getBaseMetaTileEntity().getLastShutDownReason()
.getDisplayString())
&& getBaseMetaTileEntity().wasShutdown()))
.widget(
new ShutDownReasonSyncer(
() -> getBaseMetaTileEntity().getLastShutDownReason(),
reason -> getBaseMetaTileEntity().setShutDownReason(reason)))
.widget(
new FakeSyncWidget.BooleanSyncer(
() -> getBaseMetaTileEntity().wasShutdown(),
wasShutDown -> getBaseMetaTileEntity().setShutdownStatus(wasShutDown)));
screenElements.widget(
TextWidget.dynamicString(this::generateCurrentRecipeInfoString)
.setSynced(false)
.setTextAlignment(Alignment.CenterLeft)
.setEnabled(widget -> (mMaxProgresstime > 0)))
.widget(new FakeSyncWidget.IntegerSyncer(() -> mProgresstime, val -> mProgresstime = val))
.widget(new FakeSyncWidget.IntegerSyncer(() -> mMaxProgresstime, val -> mMaxProgresstime = val));
}
private final int STATUS_WINDOW_ID = 10;
private ModularWindow createStatusWindow(final EntityPlayer player) {
final int windowWidth = 260;
final int windowHeight = 200;
ModularWindow.Builder builder = ModularWindow.builder(windowWidth, windowHeight);
builder.setBackground(GTUITextures.BACKGROUND_SINGLEBLOCK_DEFAULT);
builder.widget(
ButtonWidget.closeWindowButton(true)
.setPos(windowWidth - 15, 3));
// Title widget
builder.widget(
new TextWidget(EnumChatFormatting.BOLD + "Purification Unit Status").setTextAlignment(Alignment.Center)
.setPos(5, 10)
.setSize(windowWidth, 8));
int currentYPosition = 20;
Scrollable mainDisp = new Scrollable().setVerticalScroll()
.setHorizontalScroll();
int rowHeight = 20;
for (int i = 0; i < this.mLinkedUnits.size(); i++) {
mainDisp.widget(makeUnitStatusWidget(mLinkedUnits.get(i)).setPos(0, rowHeight * (i + 1)));
}
builder.widget(
mainDisp.setPos(5, currentYPosition)
.setSize(windowWidth - 10, windowHeight - currentYPosition - 5));
return builder.build();
}
private Widget makeStatusWindowButton() {
TextButtonWidget widget = (TextButtonWidget) new TextButtonWidget("Status").setLeftMargin(4)
.setSize(40, 16)
.setPos(10, 40);
widget.button()
.setOnClick(
(clickData, w) -> {
if (!w.isClient()) w.getContext()
.openSyncedWindow(STATUS_WINDOW_ID);
})
.setBackground(GTUITextures.BUTTON_STANDARD);
widget.text()
.setTextAlignment(Alignment.CenterLeft)
.setDefaultColor(EnumChatFormatting.BLACK);
return widget;
}
private Widget makeUnitStatusWidget(LinkedPurificationUnit unit) {
// Draw small machine controller icon
DynamicPositionedRow row = new DynamicPositionedRow();
ItemStackHandler machineIcon = new ItemStackHandler(1);
machineIcon.setStackInSlot(
0,
unit.metaTileEntity()
.getStackForm(1));
row.widget(
SlotWidget.phantom(machineIcon, 0)
.disableInteraction()
.setPos(0, 0))
.setSize(20, 20);
// Display machine name and status
String name = unit.metaTileEntity()
.getLocalName();
String statusString = name + " " + unit.getStatusString();
int widgetWidth = 0;
if (NetworkUtils.isClient()) {
final FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;
widgetWidth = fontRenderer.getStringWidth(statusString) + 25;
}
row.widget(
TextWidget.dynamicString(() -> statusString)
.setSynced(false)
.setTextAlignment(Alignment.CenterLeft)
.setPos(25, 0)
.fillParent())
.widget(new FakeSyncWidget.StringSyncer(() -> name, _name -> {}))
.widget(
unit.metaTileEntity()
.makeSyncerWidgets())
.widget(new FakeSyncWidget.BooleanSyncer(unit::isActive, unit::setActive))
.setSize(widgetWidth, 20);
return row;
}
@Override
public void addUIWidgets(ModularWindow.Builder builder, UIBuildContext buildContext) {
buildContext.addSyncedWindow(STATUS_WINDOW_ID, this::createStatusWindow);
// Draw basic recipe info
final DynamicPositionedColumn controlTextArea = new DynamicPositionedColumn();
drawTopText(controlTextArea);
builder.widget(controlTextArea);
// Draw line separator
builder.widget(
new Rectangle().setColor(Color.rgb(114, 120, 139))
.asWidget()
.setSizeProvider((screenSize, window, parent) -> new Size(window.getSize().width - 8, 2))
.setPos(3, 32));
// Add status window button
builder.widget(makeStatusWindowButton());
//
builder.widget(
new LockedWhileActiveButton(this.getBaseMetaTileEntity(), builder).setPlayClickSound(true)
.setOnClick((c, w) -> debugMode = !debugMode)
.setBackground(() -> {
List<UITexture> ret = new ArrayList<>();
if (debugMode) {
ret.add(GTUITextures.BUTTON_STANDARD_PRESSED);
ret.add(GTUITextures.OVERLAY_BUTTON_MACHINEMODE_DEFAULT);
} else {
ret.add(GTUITextures.BUTTON_STANDARD);
ret.add(GTUITextures.OVERLAY_BUTTON_MACHINEMODE_DEFAULT);
}
return ret.toArray(new IDrawable[0]);
})
.attachSyncer(new FakeSyncWidget.BooleanSyncer(() -> debugMode, b -> debugMode = b), builder)
.addTooltip("Toggle debug mode.")
.setTooltipShowUpDelay(TOOLTIP_DELAY)
.setPos(174, 112)
.setSize(16, 16));
builder.widget(createPowerSwitchButton(builder));
// Add value syncers, note that we do this here so
// everything is updated once the status gui opens
addSyncers(builder);
}
private void addSyncers(ModularWindow.Builder builder) {
// Sync connection list to client
builder.widget(new FakeSyncWidget.ListSyncer<>(() -> mLinkedUnits, links -> {
mLinkedUnits.clear();
mLinkedUnits.addAll(links);
}, (buffer, link) -> {
// Try to save link data to NBT, so we can reconstruct it on client
try {
buffer.writeNBTTagCompoundToBuffer(link.writeLinkDataToNBT());
} catch (IOException e) {
GTLog.err.println(e.getCause());
}
}, buffer -> {
// Try to load link data from NBT compound as constructed above.
try {
return new LinkedPurificationUnit(buffer.readNBTTagCompoundFromBuffer());
} catch (IOException e) {
GTLog.err.println(e.getCause());
}
return null;
}));
}
@Override
public void loadNBTData(NBTTagCompound aNBT) {
super.loadNBTData(aNBT);
debugMode = aNBT.getBoolean("debugMode");
}
@Override
public void saveNBTData(NBTTagCompound aNBT) {
super.saveNBTData(aNBT);
aNBT.setBoolean("debugMode", debugMode);
}
}
|