-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathRecipeLogic.java
More file actions
692 lines (616 loc) · 23.8 KB
/
RecipeLogic.java
File metadata and controls
692 lines (616 loc) · 23.8 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
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
package com.gregtechceu.gtceu.api.machine.trait;
import com.gregtechceu.gtceu.GTCEu;
import com.gregtechceu.gtceu.api.capability.IWorkable;
import com.gregtechceu.gtceu.api.capability.recipe.EURecipeCapability;
import com.gregtechceu.gtceu.api.capability.recipe.IO;
import com.gregtechceu.gtceu.api.capability.recipe.RecipeCapability;
import com.gregtechceu.gtceu.api.gui.GuiTextures;
import com.gregtechceu.gtceu.api.gui.fancy.IFancyTooltip;
import com.gregtechceu.gtceu.api.machine.MetaMachine;
import com.gregtechceu.gtceu.api.machine.TickableSubscription;
import com.gregtechceu.gtceu.api.machine.feature.IRecipeLogicMachine;
import com.gregtechceu.gtceu.api.machine.feature.multiblock.IMultiController;
import com.gregtechceu.gtceu.api.machine.property.GTMachineModelProperties;
import com.gregtechceu.gtceu.api.recipe.ActionResult;
import com.gregtechceu.gtceu.api.recipe.GTRecipe;
import com.gregtechceu.gtceu.api.recipe.RecipeHelper;
import com.gregtechceu.gtceu.api.registry.GTRegistries;
import com.gregtechceu.gtceu.api.sound.AutoReleasedSound;
import com.gregtechceu.gtceu.api.sync_system.annotations.ClientFieldChangeListener;
import com.gregtechceu.gtceu.api.sync_system.annotations.RerenderOnChanged;
import com.gregtechceu.gtceu.api.sync_system.annotations.SaveField;
import com.gregtechceu.gtceu.api.sync_system.annotations.SyncToClient;
import com.gregtechceu.gtceu.api.sync_system.data_transformers.ValueTransformer;
import com.gregtechceu.gtceu.api.sync_system.data_transformers.ValueTransformers;
import com.gregtechceu.gtceu.common.cover.MachineControllerCover;
import com.gregtechceu.gtceu.utils.GTMath;
import com.lowdragmc.lowdraglib.gui.texture.IGuiTexture;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
import java.util.*;
public class RecipeLogic extends MachineTrait implements IWorkable, IFancyTooltip {
public static final MachineTraitType<RecipeLogic> TYPE = new MachineTraitType<>(RecipeLogic.class, false);
@Override
public MachineTraitType<RecipeLogic> getTraitType() {
return TYPE;
}
protected static class ChanceCacheMap extends IdentityHashMap<RecipeCapability<?>, Object2IntMap<?>> {}
public enum Status implements StringRepresentable {
IDLE("idle"),
WORKING("working"),
WAITING("waiting"),
SUSPEND("suspend");
@Getter
private final String serializedName;
Status(String name) {
this.serializedName = name;
}
}
public static final EnumProperty<RecipeLogic.Status> STATUS_PROPERTY = GTMachineModelProperties.RECIPE_LOGIC_STATUS;
public final IRecipeLogicMachine machine;
public List<GTRecipe> lastFailedMatches;
@Getter
@SaveField
@SyncToClient
private Status status = Status.IDLE;
@SaveField
@SyncToClient
@RerenderOnChanged
protected boolean isActive;
@Nullable
@SaveField
@SyncToClient
@Getter
private Component waitingReason = null;
/**
* unsafe, it may not be found from {@link RecipeManager}. Do not index it.
*/
@Nullable
@Getter
@SaveField
@SyncToClient
protected GTRecipe lastRecipe;
@Getter
@SaveField
@SyncToClient
protected int consecutiveRecipes = 0; // Consecutive recipes that have been run
/**
* safe, it is the origin recipe before {@link IRecipeLogicMachine#fullModifyRecipe(GTRecipe)}'
* which can be found
* from {@link RecipeManager}.
*/
@Nullable
@Getter
@SaveField
protected GTRecipe lastOriginRecipe;
@SaveField
@Getter
@SyncToClient
protected int progress;
@Getter
@SyncToClient
@SaveField
protected int duration;
@Getter(onMethod_ = @VisibleForTesting)
protected boolean recipeDirty;
@SaveField
@Getter
protected long totalContinuousRunningTime;
protected int runAttempt = 0;
protected int runDelay = 0;
@SaveField
@Getter
@Setter
protected boolean suspendAfterFinish = false;
@Getter
@SaveField(nbtKey = "chance_cache")
protected final ChanceCacheMap chanceCaches = makeChanceCaches();
protected TickableSubscription subscription;
protected Object workingSound;
public RecipeLogic(IRecipeLogicMachine machine) {
super(machine.self());
this.machine = machine;
}
@SuppressWarnings("unused")
@ClientFieldChangeListener(fieldName = "status")
protected void onStatusSynced() {
scheduleRenderUpdate();
updateSound();
}
/**
* Call it to abort current recipe and reset the first state.
*/
public void resetRecipeLogic() {
recipeDirty = false;
lastRecipe = null;
lastOriginRecipe = null;
consecutiveRecipes = 0;
progress = 0;
duration = 0;
isActive = false;
lastFailedMatches = null;
if (status != Status.SUSPEND) {
setStatus(Status.IDLE);
}
updateTickSubscription();
getSyncDataHolder().resyncAllFields();
}
@Override
public void onMachineLoad() {
super.onMachineLoad();
updateTickSubscription();
}
public void updateTickSubscription() {
if (isSuspend() || !machine.isRecipeLogicAvailable()) {
if (subscription != null) {
subscription.unsubscribe();
subscription = null;
}
} else {
subscription = getMachine().subscribeServerTick(subscription, this::serverTick);
}
}
public void setProgress(int progress) {
this.progress = progress;
syncDataHolder.markClientSyncFieldDirty("progress");
}
public double getProgressPercent() {
return duration == 0 ? 0.0 : progress / (duration * 1.0);
}
/**
* it should be called on the server side restrictively.
*/
public RecipeManager getRecipeManager() {
return GTCEu.getMinecraftServer().getRecipeManager();
}
public void serverTick() {
if (!isSuspend()) {
if (!isIdle() && lastRecipe != null) {
if (progress < duration) {
if (runDelay > 0) {
runDelay--;
} else {
handleRecipeWorking();
}
}
if (progress >= duration) {
onRecipeFinish();
}
} else if (lastRecipe != null) {
findAndHandleRecipe();
} else if (!machine.keepSubscribing() || getMachine().getOffsetTimer() % 5 == 0) {
findAndHandleRecipe();
if (lastFailedMatches != null) {
for (GTRecipe match : lastFailedMatches) {
if (checkMatchedRecipeAvailable(match)) break;
}
}
}
}
boolean unsubscribe = false;
if (isSuspend()) {
// Machine is paused and can unsubscribe
unsubscribe = true;
} else if (lastRecipe == null && isIdle() && !machine.keepSubscribing() && !recipeDirty &&
lastFailedMatches == null) {
// No recipes available and the machine wants to unsubscribe until notified
unsubscribe = true;
}
if (unsubscribe && subscription != null) {
subscription.unsubscribe();
subscription = null;
}
}
protected ActionResult matchRecipe(GTRecipe recipe) {
return RecipeHelper.matchContents(machine, recipe);
}
protected ActionResult checkRecipe(GTRecipe recipe) {
var conditionResult = RecipeHelper.checkConditions(recipe, this);
if (!conditionResult.isSuccess()) return conditionResult;
return matchRecipe(recipe);
}
public boolean checkMatchedRecipeAvailable(GTRecipe match) {
var modified = machine.fullModifyRecipe(match);
if (modified != null) {
var recipeMatch = checkRecipe(modified);
if (recipeMatch.isSuccess()) {
setupRecipe(modified);
}
if (lastRecipe != null && getStatus() == Status.WORKING) {
lastOriginRecipe = match;
lastFailedMatches = null;
return true;
}
}
return false;
}
public void handleRecipeWorking() {
assert lastRecipe != null;
var conditionResult = RecipeHelper.checkConditions(lastRecipe, this);
if (conditionResult.isSuccess()) {
var handleTick = handleTickRecipe(lastRecipe);
if (handleTick.isSuccess()) {
setStatus(Status.WORKING);
if (!machine.onWorking()) {
this.interruptRecipe();
return;
}
progress++;
totalContinuousRunningTime++;
syncDataHolder.markClientSyncFieldDirty("progress");
} else {
setWaiting(handleTick.reason());
// Machine isn't getting enough power, suspend after 5 attempts.
if (handleTick.io() == IO.IN && handleTick.capability() == EURecipeCapability.CAP) {
runAttempt++;
runAttempt = (int) GTMath.clamp(runAttempt, 0, 5);
if (runAttempt == 5) {
boolean preventPowerFail = false;
if (machine.self() instanceof IMultiController) {
var covers = machine.self().getCoverContainer().getCovers();
for (var cover : covers) {
if (cover instanceof MachineControllerCover mcc) {
if (mcc.preventPowerFail()) {
preventPowerFail = true;
break;
}
}
}
}
if (machine.self() instanceof IMultiController && !preventPowerFail) {
runAttempt = 0;
setStatus(Status.SUSPEND);
}
}
runDelay = runAttempt * 60;
}
}
} else {
setWaiting(conditionResult.reason());
}
if (isWaiting() || isSuspend()) {
regressRecipe();
}
}
protected void regressRecipe() {
if (progress > 0 && machine.regressWhenWaiting()) {
this.progress = 1;
syncDataHolder.markClientSyncFieldDirty("progress");
}
}
public @NotNull Iterator<GTRecipe> searchRecipe() {
return machine.getRecipeType().searchRecipe(machine, r -> true);
}
public void findAndHandleRecipe() {
lastFailedMatches = null;
// try to execute last recipe if possible
if (!recipeDirty && lastRecipe != null && checkRecipe(lastRecipe).isSuccess()) {
GTRecipe recipe = lastRecipe;
lastRecipe = null;
lastOriginRecipe = null;
setupRecipe(recipe);
} else { // try to find and handle a new recipe
lastRecipe = null;
lastOriginRecipe = null;
handleSearchingRecipes(searchRecipe());
}
syncDataHolder.markClientSyncFieldDirty("lastRecipe");
recipeDirty = false;
}
protected void handleSearchingRecipes(@NotNull Iterator<GTRecipe> matches) {
while (matches.hasNext()) {
GTRecipe match = matches.next();
if (match == null) continue;
// If a new recipe was found, cache found recipe.
if (checkMatchedRecipeAvailable(match))
return;
if (!matchRecipe(match).isSuccess()) {
continue;
}
// cache matching recipes.
if (lastFailedMatches == null) {
lastFailedMatches = new ArrayList<>();
}
lastFailedMatches.add(match);
}
}
public ActionResult handleTickRecipe(GTRecipe recipe) {
if (!recipe.hasTick()) return ActionResult.SUCCESS;
var result = RecipeHelper.matchTickRecipe(machine, recipe);
if (!result.isSuccess()) return result;
result = handleTickRecipeIO(recipe, IO.IN);
if (!result.isSuccess()) return result;
result = handleTickRecipeIO(recipe, IO.OUT);
return result;
}
public void setupRecipe(GTRecipe recipe) {
if (!machine.beforeWorking(recipe)) {
setStatus(Status.IDLE);
consecutiveRecipes = 0;
progress = 0;
duration = 0;
isActive = false;
syncDataHolder.resyncAllFields();
return;
}
var handledIO = handleRecipeIO(recipe, IO.IN);
if (handledIO.isSuccess()) {
if (lastRecipe != null && !recipe.equals(lastRecipe)) {
chanceCaches.clear();
}
recipeDirty = false;
lastRecipe = recipe;
setStatus(Status.WORKING);
progress = 0;
duration = recipe.duration;
isActive = true;
syncDataHolder.resyncAllFields();
}
}
public void setStatus(Status status) {
if (this.status != status) {
if (this.status == Status.WORKING) {
this.totalContinuousRunningTime = 0;
}
if ((status == Status.WAITING || status == Status.SUSPEND) && suspendAfterFinish) {
status = Status.SUSPEND;
suspendAfterFinish = false;
}
machine.notifyStatusChanged(this.status, status);
this.status = status;
syncDataHolder.markClientSyncFieldDirty("status");
setRenderState(getRenderState().setValue(GTMachineModelProperties.RECIPE_LOGIC_STATUS, status));
updateTickSubscription();
if (this.status != Status.WAITING) {
waitingReason = null;
syncDataHolder.markClientSyncFieldDirty("waitingReason");
}
}
}
public void setWaiting(@Nullable Component reason) {
setStatus(Status.WAITING);
waitingReason = reason;
syncDataHolder.markClientSyncFieldDirty("waitingReason");
machine.onWaiting();
}
/**
* mark current handling recipe (if exist) as dirty.
* do not try it immediately in the next round
*/
public void markLastRecipeDirty() {
this.recipeDirty = true;
}
public boolean isWorking() {
return status == Status.WORKING;
}
public boolean isIdle() {
return status == Status.IDLE;
}
public boolean isWaiting() {
return status == Status.WAITING;
}
public boolean isSuspend() {
return status == Status.SUSPEND;
}
public boolean isWorkingEnabled() {
return !isSuspend() && !isSuspendAfterFinish();
}
@Override
public void setWorkingEnabled(boolean isWorkingAllowed) {
if (!isWorkingAllowed && getStatus() == Status.IDLE) {
setStatus(Status.SUSPEND);
} else {
setSuspendAfterFinish(!isWorkingAllowed);
if (isWorkingAllowed) {
if (lastRecipe != null && duration > 0) {
setStatus(Status.WORKING);
} else {
setStatus(Status.IDLE);
}
}
}
}
@Override
public int getMaxProgress() {
return duration;
}
public boolean isActive() {
return isWorking() || isWaiting() || (isSuspend() && isActive);
}
public boolean hasCustomProgressLine() {
return false;
}
/**
* Show the customized progress line instead of the regular duration progress time in the machine display.
* <p>
* Must override and return {@code true} in {@link #hasCustomProgressLine()}.
*
* @return the customized progress line
*/
public @Nullable Component getCustomProgressLine() {
return null;
}
public void onRecipeFinish() {
machine.afterWorking();
if (lastRecipe != null) {
runAttempt = 0;
runDelay = 0;
consecutiveRecipes++;
handleRecipeIO(lastRecipe, IO.OUT);
// Don't ready the next recipe after finish if suspend is set
// so that the modifiers won't be applied until re-starting.
if (suspendAfterFinish) {
setStatus(Status.SUSPEND);
consecutiveRecipes = 0;
progress = 0;
duration = 0;
isActive = false;
// Force a recipe recheck.
lastRecipe = null;
syncDataHolder.resyncAllFields();
return;
}
if (machine.alwaysTryModifyRecipe()) {
if (lastOriginRecipe != null) {
var modified = machine.fullModifyRecipe(lastOriginRecipe.copy());
if (modified == null) {
markLastRecipeDirty();
} else {
lastRecipe = modified;
syncDataHolder.markClientSyncFieldDirty("lastRecipe");
}
} else {
markLastRecipeDirty();
}
}
// try it again
var recipeCheck = checkRecipe(lastRecipe);
if (!recipeDirty && recipeCheck.isSuccess()) {
setupRecipe(lastRecipe);
} else {
setStatus(Status.IDLE);
if (recipeCheck.io() != IO.IN || recipeCheck.capability() == EURecipeCapability.CAP) {
waitingReason = recipeCheck.reason();
}
consecutiveRecipes = 0;
progress = 0;
duration = 0;
isActive = false;
syncDataHolder.resyncAllFields();
}
}
}
protected ActionResult handleRecipeIO(GTRecipe recipe, IO io) {
return RecipeHelper.handleRecipeIO(machine, recipe, io, this.chanceCaches);
}
protected ActionResult handleTickRecipeIO(GTRecipe recipe, IO io) {
return RecipeHelper.handleTickRecipeIO(machine, recipe, io, this.chanceCaches);
}
/**
* Interrupt current recipe without io.
*/
public void interruptRecipe() {
machine.afterWorking();
if (lastRecipe != null) {
setStatus(Status.IDLE);
progress = 0;
duration = 0;
syncDataHolder.markClientSyncFieldDirty("progress");
syncDataHolder.markClientSyncFieldDirty("duration");
}
}
// Remains for legacy + for subclasses
public void inValid() {}
//////////////////////////////////////
// ******** MISC *********//
//////////////////////////////////////
@OnlyIn(Dist.CLIENT)
public void updateSound() {
if (isWorking() && machine.shouldWorkingPlaySound()) {
var sound = machine.getRecipeType().getSound();
if (workingSound instanceof AutoReleasedSound soundEntry) {
if (soundEntry.soundEntry == sound && !soundEntry.isStopped()) {
return;
}
soundEntry.release();
workingSound = null;
}
if (sound != null) {
workingSound = sound.playAutoReleasedSound(
() -> machine.shouldWorkingPlaySound() && isWorking() && !getMachine().isRemoved() &&
getMachine().getLevel().isLoaded(getMachine().getBlockPos()) &&
MetaMachine.getMachine(getMachine().getLevel(), getMachine().getBlockPos()) ==
getMachine(),
getMachine().getBlockPos(), true, 0, 1, 1);
}
} else if (workingSound instanceof AutoReleasedSound soundEntry) {
soundEntry.release();
workingSound = null;
}
}
@Override
public IGuiTexture getFancyTooltipIcon() {
if (waitingReason != null) {
return GuiTextures.INSUFFICIENT_INPUT;
}
return IGuiTexture.EMPTY;
}
@Override
public List<Component> getFancyTooltip() {
if (waitingReason != null) {
return List.of(waitingReason);
}
return Collections.emptyList();
}
@Override
public boolean showFancyTooltip() {
return waitingReason != null;
}
protected ChanceCacheMap makeChanceCaches() {
ChanceCacheMap map = new ChanceCacheMap();
for (RecipeCapability<?> cap : GTRegistries.RECIPE_CAPABILITIES.values()) {
map.put(cap, cap.makeChanceCache());
}
return map;
}
static {
ValueTransformers.registerTransformer(ChanceCacheMap.class, new ValueTransformer<ChanceCacheMap>() {
@Override
public @NotNull Tag serializeNBT(@NotNull ChanceCacheMap value,
@NotNull TransformerContext<ChanceCacheMap> context) {
CompoundTag chanceCache = new CompoundTag();
if (context.currentValue() == null) return chanceCache;
context.currentValue().forEach((cap, cache) -> {
ListTag cacheTag = new ListTag();
for (var entry : cache.object2IntEntrySet()) {
CompoundTag compoundTag = new CompoundTag();
var obj = cap.contentToNbt(entry.getKey());
compoundTag.put("entry", obj);
compoundTag.putInt("cached_chance", entry.getIntValue());
cacheTag.add(compoundTag);
}
chanceCache.put(cap.name, cacheTag);
});
return chanceCache;
}
@Override
public @Nullable ChanceCacheMap deserializeNBT(@NotNull Tag tag,
@NotNull TransformerContext<ChanceCacheMap> context) {
CompoundTag chanceCache = ValueTransformer.assertTagType(CompoundTag.class, tag, context);
if (context.currentValue() != null) {
for (String key : chanceCache.getAllKeys()) {
RecipeCapability<?> cap = GTRegistries.RECIPE_CAPABILITIES.get(key);
// Necessary since a RecipeCapability was removed when removing Create support, and for future
// removals
if (cap == null) continue;
// noinspection rawtypes
Object2IntMap map = context.currentValue().computeIfAbsent(cap,
RecipeCapability::makeChanceCache);
ListTag chanceTag = chanceCache.getList(key, Tag.TAG_COMPOUND);
for (int i = 0; i < chanceTag.size(); ++i) {
CompoundTag chanceKey = chanceTag.getCompound(i);
var entry = cap.serializer.fromNbt(chanceKey.get("entry"));
int value = chanceKey.getInt("cached_chance");
// noinspection unchecked
map.put(entry, value);
}
}
}
return context.currentValue();
}
});
}
}