-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathAbstractRecipeLogic.java
More file actions
executable file
·531 lines (463 loc) · 19.2 KB
/
AbstractRecipeLogic.java
File metadata and controls
executable file
·531 lines (463 loc) · 19.2 KB
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
package gregtech.api.capability.impl;
import gregtech.api.GTValues;
import gregtech.api.capability.GregtechTileCapabilities;
import gregtech.api.capability.IMultipleTankHandler;
import gregtech.api.capability.IWorkable;
import gregtech.api.metatileentity.MTETrait;
import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeMap;
import gregtech.api.util.GTUtility;
import gregtech.common.ConfigHolder;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.world.*;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidTank;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.LongSupplier;
public abstract class AbstractRecipeLogic extends MTETrait implements IWorkable {
private static final String ALLOW_OVERCLOCKING = "AllowOverclocking";
private static final String OVERCLOCK_VOLTAGE = "OverclockVoltage";
public final RecipeMap<?> recipeMap;
protected boolean forceRecipeRecheck;
@Deprecated protected ItemStack[] lastItemInputs;
@Deprecated protected FluidStack[] lastFluidInputs;
protected Recipe previousRecipe;
protected boolean allowOverclocking = true;
private long overclockVoltage = 0;
private LongSupplier overclockPolicy = this::getMaxVoltage;
protected int progressTime;
protected int maxProgressTime;
protected int recipeEUt;
protected List<FluidStack> fluidOutputs;
protected NonNullList<ItemStack> itemOutputs;
protected final Random random = new Random();
protected boolean isActive;
protected boolean workingEnabled = true;
protected boolean hasNotEnoughEnergy;
protected boolean wasActiveAndNeedsUpdate;
protected boolean isOutputsFull;
protected boolean invalidInputsForRecipes;
public AbstractRecipeLogic(MetaTileEntity tileEntity, RecipeMap<?> recipeMap) {
super(tileEntity);
this.recipeMap = recipeMap;
}
protected abstract long getEnergyStored();
protected abstract long getEnergyCapacity();
protected abstract boolean drawEnergy(int recipeEUt);
protected abstract long getMaxVoltage();
protected IItemHandlerModifiable getInputInventory() {
return metaTileEntity.getImportItems();
}
protected IItemHandlerModifiable getOutputInventory() {
return metaTileEntity.getExportItems();
}
protected IMultipleTankHandler getInputTank() {
return metaTileEntity.getImportFluids();
}
protected IMultipleTankHandler getOutputTank() {
return metaTileEntity.getExportFluids();
}
@Override
public String getName() {
return "RecipeMapWorkable";
}
@Override
public int getNetworkID() {
return TraitNetworkIds.TRAIT_ID_WORKABLE;
}
@Override
public <T> T getCapability(Capability<T> capability) {
if(capability == GregtechTileCapabilities.CAPABILITY_WORKABLE) {
return GregtechTileCapabilities.CAPABILITY_WORKABLE.cast(this);
} else if(capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE) {
return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this);
}
return null;
}
@Override
public void update() {
World world = getMetaTileEntity().getWorld();
if (world != null && !world.isRemote) {
if (workingEnabled) {
if (progressTime > 0) {
updateRecipeProgress();
}
//check everything that would make a recipe never start here.
if (progressTime == 0 && shouldSearchForRecipes()) {
trySearchNewRecipe();
}
}
if (wasActiveAndNeedsUpdate) {
this.wasActiveAndNeedsUpdate = false;
setActive(false);
}
}
}
protected boolean shouldSearchForRecipes() {
return canWorkWithInputs() && canFitNewOutputs();
}
protected boolean hasNotifiedInputs() {
return (metaTileEntity.getNotifiedItemInputList().size() > 0 ||
metaTileEntity.getNotifiedFluidInputList().size() > 0);
}
protected boolean hasNotifiedOutputs() {
return (metaTileEntity.getNotifiedItemOutputList().size() > 0 ||
metaTileEntity.getNotifiedFluidOutputList().size() > 0);
}
protected boolean canFitNewOutputs() {
// if the output is full check if the output changed so we can process recipes results again.
if (this.isOutputsFull && !hasNotifiedOutputs()) return false;
else {
this.isOutputsFull = false;
metaTileEntity.getNotifiedItemOutputList().clear();
metaTileEntity.getNotifiedFluidOutputList().clear();
}
return true;
}
protected boolean canWorkWithInputs() {
// if the inputs were bad last time, check if they've changed before trying to find a new recipe.
if (this.invalidInputsForRecipes && !hasNotifiedInputs()) return false;
else {
this.invalidInputsForRecipes = false;
}
return true;
}
protected void updateRecipeProgress() {
boolean drawEnergy = drawEnergy(recipeEUt);
if (drawEnergy || (recipeEUt < 0)) {
//as recipe starts with progress on 1 this has to be > only not => to compensate for it
if (++progressTime > maxProgressTime) {
completeRecipe();
}
} else if (recipeEUt > 0) {
//only set hasNotEnoughEnergy if this recipe is consuming recipe
//generators always have enough energy
this.hasNotEnoughEnergy = true;
//if current progress value is greater than 2, decrement it by 2
if (progressTime >= 2) {
if (ConfigHolder.insufficientEnergySupplyWipesRecipeProgress) {
this.progressTime = 1;
} else {
this.progressTime = Math.max(1, progressTime - 2);
}
}
}
}
protected void trySearchNewRecipe() {
long maxVoltage = getMaxVoltage();
Recipe currentRecipe = null;
IItemHandlerModifiable importInventory = getInputInventory();
IMultipleTankHandler importFluids = getInputTank();
// see if the last recipe we used still works
if (this.previousRecipe != null && this.previousRecipe.matches(false, importInventory, importFluids))
currentRecipe = this.previousRecipe;
// If there is no active recipe, then we need to find one.
else {
currentRecipe = findRecipe(maxVoltage, importInventory, importFluids);
}
// If a recipe was found, then inputs were valid. Cache found recipe.
if (currentRecipe != null) {
this.previousRecipe = currentRecipe;
}
this.invalidInputsForRecipes = (currentRecipe == null);
// proceed if we have a usable recipe.
if (currentRecipe != null && setupAndConsumeRecipeInputs(currentRecipe))
setupRecipe(currentRecipe);
// Inputs have been inspected.
metaTileEntity.getNotifiedItemInputList().clear();
metaTileEntity.getNotifiedFluidInputList().clear();
}
public void forceRecipeRecheck() {
this.forceRecipeRecheck = true;
}
protected int getMinTankCapacity(IMultipleTankHandler tanks) {
if(tanks.getTanks() == 0) {
return 0;
}
int result = Integer.MAX_VALUE;
for(IFluidTank fluidTank : tanks.getFluidTanks()) {
result = Math.min(fluidTank.getCapacity(), result);
}
return result;
}
protected Recipe findRecipe(long maxVoltage, IItemHandlerModifiable inputs, IMultipleTankHandler fluidInputs) {
return recipeMap.findRecipe(maxVoltage, inputs, fluidInputs, getMinTankCapacity(getOutputTank()));
}
/**
* @deprecated Use {@link #hasNotifiedInputs() } instead
* Left here for binary compatibility purposes
*/
@Deprecated
protected boolean checkRecipeInputsDirty(IItemHandler inputs, IMultipleTankHandler fluidInputs) {
boolean isDirty = this.hasNotifiedInputs();
metaTileEntity.getNotifiedItemInputList().clear();
metaTileEntity.getNotifiedFluidInputList().clear();
return isDirty;
}
protected static boolean areItemStacksEqual(ItemStack stackA, ItemStack stackB) {
return (stackA.isEmpty() && stackB.isEmpty()) ||
(ItemStack.areItemsEqual(stackA, stackB) &&
ItemStack.areItemStackTagsEqual(stackA, stackB));
}
protected boolean setupAndConsumeRecipeInputs(Recipe recipe) {
int[] resultOverclock = calculateOverclock(recipe.getEUt(), recipe.getDuration());
int totalEUt = resultOverclock[0] * resultOverclock[1];
IItemHandlerModifiable importInventory = getInputInventory();
IItemHandlerModifiable exportInventory = getOutputInventory();
IMultipleTankHandler importFluids = getInputTank();
IMultipleTankHandler exportFluids = getOutputTank();
if (!(totalEUt >= 0 ? getEnergyStored() >= (totalEUt > getEnergyCapacity() / 2 ? resultOverclock[0] : totalEUt) :
(getEnergyStored() - resultOverclock[0] <= getEnergyCapacity()))) {
return false;
}
if (!MetaTileEntity.addItemsToItemHandler(exportInventory, true, recipe.getAllItemOutputs(exportInventory.getSlots()))) {
this.isOutputsFull = true;
return false;
}
if (!MetaTileEntity.addFluidsToFluidHandler(exportFluids, true, recipe.getFluidOutputs())) {
this.isOutputsFull = true;
return false;
}
this.isOutputsFull = false;
return recipe.matches(true, importInventory, importFluids);
}
protected int[] calculateOverclock(int EUt, int duration) {
return calculateOverclock(EUt, this.overclockPolicy.getAsLong(), duration);
}
protected int[] calculateOverclock(int EUt, long voltage, int duration) {
if (!allowOverclocking) {
return new int[] {EUt, duration};
}
boolean negativeEU = EUt < 0;
int tier = getOverclockingTier(voltage);
if (GTValues.V[tier] <= EUt || tier == 0)
return new int[]{EUt, duration};
if (negativeEU)
EUt = -EUt;
if (EUt <= 16) {
int multiplier = EUt <= 8 ? tier : tier - 1;
int resultEUt = EUt * (1 << multiplier) * (1 << multiplier);
int resultDuration = duration / (1 << multiplier);
return new int[]{negativeEU ? -resultEUt : resultEUt, resultDuration};
} else {
int resultEUt = EUt;
double resultDuration = duration;
//do not overclock further if duration is already too small
while (resultDuration >= 3 && resultEUt <= GTValues.V[tier - 1]) {
resultEUt *= 4;
resultDuration /= 2.8;
}
return new int[]{negativeEU ? -resultEUt : resultEUt, (int) Math.ceil(resultDuration)};
}
}
protected int getOverclockingTier(long voltage) {
return GTUtility.getTierByVoltage(voltage);
}
protected long getVoltageByTier(final int tier) {
return GTValues.V[tier];
}
public String[] getAvailableOverclockingTiers() {
final int maxTier = getOverclockingTier(getMaxVoltage());
final String[] result = new String[maxTier + 2];
result[0] = "gregtech.gui.overclock.off";
for (int i = 0; i < maxTier + 1; ++i) {
result[i+1] = GTValues.VN[i];
}
return result;
}
protected void setupRecipe(Recipe recipe) {
int[] resultOverclock = calculateOverclock(recipe.getEUt(), recipe.getDuration());
this.progressTime = 1;
setMaxProgress(resultOverclock[1]);
this.recipeEUt = resultOverclock[0];
this.fluidOutputs = GTUtility.copyFluidList(recipe.getFluidOutputs());
int tier = getMachineTierForRecipe(recipe);
this.itemOutputs = GTUtility.copyStackList(recipe.getResultItemOutputs(getOutputInventory().getSlots(), random, tier));
if (this.wasActiveAndNeedsUpdate) {
this.wasActiveAndNeedsUpdate = false;
} else {
this.setActive(true);
}
}
protected int getMachineTierForRecipe(Recipe recipe) {
return GTUtility.getTierByVoltage(getMaxVoltage());
}
protected void completeRecipe() {
MetaTileEntity.addItemsToItemHandler(getOutputInventory(), false, itemOutputs);
MetaTileEntity.addFluidsToFluidHandler(getOutputTank(), false, fluidOutputs);
this.progressTime = 0;
setMaxProgress(0);
this.recipeEUt = 0;
this.fluidOutputs = null;
this.itemOutputs = null;
this.hasNotEnoughEnergy = false;
this.wasActiveAndNeedsUpdate = true;
}
public double getProgressPercent() {
return getMaxProgress() == 0 ? 0.0 : getProgress() / (getMaxProgress() * 1.0);
}
public int getTicksTimeLeft() {
return maxProgressTime == 0 ? 0 : (maxProgressTime - progressTime);
}
@Override
public int getProgress() {
return progressTime;
}
@Override
public int getMaxProgress() {
return maxProgressTime;
}
public int getRecipeEUt() {
return recipeEUt;
}
public void setMaxProgress(int maxProgress) {
this.maxProgressTime = maxProgress;
metaTileEntity.markDirty();
}
protected void setActive(boolean active) {
this.isActive = active;
metaTileEntity.markDirty();
World world = metaTileEntity.getWorld();
if (world != null && !world.isRemote) {
writeCustomData(1, buf -> buf.writeBoolean(active));
}
}
@Override
public void setWorkingEnabled(boolean workingEnabled) {
this.workingEnabled = workingEnabled;
metaTileEntity.markDirty();
}
public void setAllowOverclocking(boolean allowOverclocking) {
this.allowOverclocking = allowOverclocking;
this.overclockVoltage = allowOverclocking ? getMaxVoltage() : 0;
metaTileEntity.markDirty();
}
public boolean isHasNotEnoughEnergy() {
return hasNotEnoughEnergy;
}
@Override
public boolean isWorkingEnabled() {
return workingEnabled;
}
@Override
public boolean isActive() {
return isActive;
}
public boolean isAllowOverclocking() {
return allowOverclocking;
}
public long getOverclockVoltage() {
return overclockVoltage;
}
public void setOverclockVoltage(final long overclockVoltage) {
this.overclockPolicy = this::getOverclockVoltage;
this.overclockVoltage = overclockVoltage;
this.allowOverclocking = (overclockVoltage != 0);
metaTileEntity.markDirty();
}
/**
* Sets the overclocking policy to use getOverclockVoltage() instead of getMaxVoltage()
* and initialises the overclock voltage to max voltage.
* The actual value will come from the saved tag when the tile is loaded for pre-existing machines.
*
* NOTE: This should only be used directly after construction of the workable.
* Use setOverclockVoltage() or setOverclockTier() for a more dynamic use case.
*/
public void enableOverclockVoltage() {
setOverclockVoltage(getMaxVoltage());
}
// The overclocking tier
// it is 1 greater than the index into GTValues.V since here the "0 tier" represents 0 EU or no overclock
public int getOverclockTier() {
if (this.overclockVoltage == 0) {
return 0;
}
return 1 + getOverclockingTier(this.overclockVoltage);
}
public void setOverclockTier(final int tier) {
if (tier == 0) {
setOverclockVoltage(0);
return;
}
setOverclockVoltage(getVoltageByTier(tier - 1));
}
@Override
public void receiveCustomData(int dataId, PacketBuffer buf) {
if (dataId == 1) {
this.isActive = buf.readBoolean();
getMetaTileEntity().getHolder().scheduleChunkForRenderUpdate();
}
}
@Override
public void writeInitialData(PacketBuffer buf) {
buf.writeBoolean(this.isActive);
}
@Override
public void receiveInitialData(PacketBuffer buf) {
this.isActive = buf.readBoolean();
}
@Override
public NBTTagCompound serializeNBT() {
NBTTagCompound compound = new NBTTagCompound();
compound.setBoolean("WorkEnabled", workingEnabled);
compound.setBoolean(ALLOW_OVERCLOCKING, allowOverclocking);
compound.setLong(OVERCLOCK_VOLTAGE, this.overclockVoltage);
if (progressTime > 0) {
compound.setInteger("Progress", progressTime);
compound.setInteger("MaxProgress", maxProgressTime);
compound.setInteger("RecipeEUt", this.recipeEUt);
NBTTagList itemOutputsList = new NBTTagList();
for (ItemStack itemOutput : itemOutputs) {
itemOutputsList.appendTag(itemOutput.writeToNBT(new NBTTagCompound()));
}
NBTTagList fluidOutputsList = new NBTTagList();
for (FluidStack fluidOutput : fluidOutputs) {
fluidOutputsList.appendTag(fluidOutput.writeToNBT(new NBTTagCompound()));
}
compound.setTag("ItemOutputs", itemOutputsList);
compound.setTag("FluidOutputs", fluidOutputsList);
}
return compound;
}
@Override
public void deserializeNBT(NBTTagCompound compound) {
this.workingEnabled = compound.getBoolean("WorkEnabled");
this.progressTime = compound.getInteger("Progress");
if(compound.hasKey(ALLOW_OVERCLOCKING)) {
this.allowOverclocking = compound.getBoolean(ALLOW_OVERCLOCKING);
}
if (compound.hasKey(OVERCLOCK_VOLTAGE)) {
this.overclockVoltage = compound.getLong(OVERCLOCK_VOLTAGE);
} else {
// Calculate overclock voltage based on old allow flag
this.overclockVoltage = this.allowOverclocking ? getMaxVoltage() : 0;
}
this.isActive = false;
if (progressTime > 0) {
this.isActive = true;
this.maxProgressTime = compound.getInteger("MaxProgress");
this.recipeEUt = compound.getInteger("RecipeEUt");
NBTTagList itemOutputsList = compound.getTagList("ItemOutputs", Constants.NBT.TAG_COMPOUND);
this.itemOutputs = NonNullList.create();
for (int i = 0; i < itemOutputsList.tagCount(); i++) {
this.itemOutputs.add(new ItemStack(itemOutputsList.getCompoundTagAt(i)));
}
NBTTagList fluidOutputsList = compound.getTagList("FluidOutputs", Constants.NBT.TAG_COMPOUND);
this.fluidOutputs = new ArrayList<>();
for (int i = 0; i < fluidOutputsList.tagCount(); i++) {
this.fluidOutputs.add(FluidStack.loadFluidStackFromNBT(fluidOutputsList.getCompoundTagAt(i)));
}
}
}
}