aboutsummaryrefslogtreecommitdiff
path: root/src/Java/gtPlusPlus/xmod/gregtech/api/objects/GregtechBufferThread.java
blob: 1e7d73bacd875d6775ee7bfaca00f3a5e88da3cb (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
package gtPlusPlus.xmod.gregtech.api.objects;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;

import gregtech.api.interfaces.tileentity.IGregTechTileEntity;
import gregtech.api.util.GT_Utility;

import gtPlusPlus.api.objects.Logger;
import gtPlusPlus.api.objects.minecraft.BlockPos;
import gtPlusPlus.xmod.gregtech.api.metatileentity.implementations.GT_MetaTileEntity_ThreadedBuffer;
import gtPlusPlus.xmod.gregtech.common.tileentities.automation.GT_MetaTileEntity_ThreadedChestBuffer;

public class GregtechBufferThread extends Thread {

	public static final ConcurrentMap<String, GregtechBufferThread> mBufferThreadAllocation = new ConcurrentHashMap<String, GregtechBufferThread>();
	private final BlockPos mBlockPos;
	private final int mMaxLife = 300;
	private int mLifeCycleTime = mMaxLife;
	private final  String mID;

	public static synchronized final GregtechBufferThread getBufferThread(BlockPos pos) {
		if (pos != null && mBufferThreadAllocation.containsKey(""+pos.getUniqueIdentifier())){
			Logger.INFO("[SB] Found an existing thread for this Buffer.");
			return mBufferThreadAllocation.get(""+pos.getUniqueIdentifier());
		}
		else {
			return new GregtechBufferThread(pos);
		}
	}

	public GregtechBufferThread(BlockPos pos) {
		super();
		String aID = pos != null ? pos.getUniqueIdentifier() : ""+Short.MIN_VALUE;
		this.mID = aID;
		if (pos != null && !mBufferThreadAllocation.containsKey(mID)){
			mBlockPos = pos;
			mBufferThreadAllocation.put(mID, this);
		}
		else {
			this.mLifeCycleTime = 1;
			mBlockPos = null;
		}
		this.setName("GTPP-SuperBuffer("+mID+")");
		this.setDaemon(true);
		if (mBlockPos != null && !this.isAlive()) {
			try {
				start();
				Logger.INFO("[SB] Created a SuperBuffer Thread for dimension "+mID+".");
			}
			catch (Throwable t_) {
				//Do nothing.
			}
		}
	}

	public synchronized int getTimeLeft() {
		return this.mLifeCycleTime;
	}

	public synchronized void fillStacksIntoFirstSlots(GT_MetaTileEntity_ThreadedChestBuffer mBuffer) {
		for (int i = 0; i < mBuffer.mInventorySynchro.length - 1; ++i) {
			for (int j = i + 1; j < mBuffer.mInventorySynchro.length - 1; ++j) {
				if (mBuffer.mInventorySynchro[j] != null && (mBuffer.mInventorySynchro[i] == null
						|| areStacksEqual(mBuffer.mInventorySynchro[i], mBuffer.mInventorySynchro[j]))) {
					moveStackFromSlotAToSlotB((IInventory) mBuffer.getBaseMetaTileEntity(),
							(IInventory) mBuffer.getBaseMetaTileEntity(), j, i, (byte) 64, (byte) 1, (byte) 64, (byte) 1);
				}
			}
		}
	}

	public synchronized boolean moveItems(final IGregTechTileEntity aBaseMetaTileEntity, final long aTimer, GT_MetaTileEntity_ThreadedBuffer mBuffer) {
		final byte mTargetStackSize = (byte) mBuffer.mTargetStackSize;
		final int tCost = GT_Utility.moveOneItemStack((Object) aBaseMetaTileEntity,
				(Object) aBaseMetaTileEntity.getTileEntityAtSide(aBaseMetaTileEntity.getBackFacing()),
				aBaseMetaTileEntity.getBackFacing(), aBaseMetaTileEntity.getFrontFacing(), (List<ItemStack>) null, false,
				(byte) ((mTargetStackSize == 0) ? 64 : ((byte) mTargetStackSize)),
				(byte) ((mTargetStackSize == 0) ? 1 : ((byte) mTargetStackSize)), (byte) 64, (byte) 1);
		if (tCost > 0 || aBaseMetaTileEntity.hasInventoryBeenModified()) {
			mBuffer.mSuccess = 50;
			aBaseMetaTileEntity.decreaseStoredEnergyUnits((long) Math.abs(tCost), true);
			return true;
		}
		return false;
	}

	public synchronized void onPostTick(final IGregTechTileEntity aBaseMetaTileEntity, final long aTimer, GT_MetaTileEntity_ThreadedBuffer mBuffer) {
		if (aBaseMetaTileEntity.isAllowedToWork() && aBaseMetaTileEntity.isServerSide()
				&& aBaseMetaTileEntity.isUniversalEnergyStored(mBuffer.getMinimumStoredEU())
				&& (aBaseMetaTileEntity.hasWorkJustBeenEnabled() || aBaseMetaTileEntity.hasInventoryBeenModified()
						|| aTimer % 200L == 0L || mBuffer.mSuccess > 0)) {
			--mBuffer.mSuccess;
			if (mLifeCycleTime < (mMaxLife-1)){
				mLifeCycleTime += 1;				
			}
			//Logger.INFO("Ticking SB @ "+mBuffer.getLogicThread().mBlockPos.getUniqueIdentifier() + " | Time Left: "+mLifeCycleTime);
			moveItems(aBaseMetaTileEntity, aTimer, mBuffer);
			for (byte b = 0; b < 6; ++b) {
				aBaseMetaTileEntity.setInternalOutputRedstoneSignal(b, (byte) (mBuffer.bInvert ? 15 : 0));
			}
			if (mBuffer.bRedstoneIfFull) {
				for (byte b = 0; b < 6; ++b) {
					aBaseMetaTileEntity.setInternalOutputRedstoneSignal(b, (byte) (mBuffer.bInvert ? 0 : 15));
				}
				for (int i = 0; i < mBuffer.mInventorySynchro.length; ++i) {
					if (mBuffer.isValidSlot(i) && mBuffer.mInventorySynchro[i] == null) {
						for (byte b2 = 0; b2 < 6; ++b2) {
							aBaseMetaTileEntity.setInternalOutputRedstoneSignal(b2, (byte) (mBuffer.bInvert ? 15 : 0));
						}
						aBaseMetaTileEntity.decreaseStoredEnergyUnits(1L, true);
						break;
					}
				}
			}
		}
	}

	/**
	 * Some GT logic we'd like to move off thread
	 */

	public synchronized boolean areStacksEqual(final ItemStack aStack1, final ItemStack aStack2) {
		return areStacksEqual(aStack1, aStack2, false);
	}

	public synchronized boolean areStacksEqual(final ItemStack aStack1, final ItemStack aStack2, final boolean aIgnoreNBT) {
		return aStack1 != null && aStack2 != null && aStack1.getItem() == aStack2.getItem()
				&& (aIgnoreNBT || (aStack1.getTagCompound() == null == (aStack2.getTagCompound() == null)
				&& (aStack1.getTagCompound() == null
				|| aStack1.getTagCompound().equals((Object) aStack2.getTagCompound()))))
				&& (Items.feather.getDamage(aStack1) == Items.feather.getDamage(aStack2)
				|| Items.feather.getDamage(aStack1) == 32767 || Items.feather.getDamage(aStack2) == 32767);
	}

	public synchronized byte moveStackFromSlotAToSlotB(final IInventory aTileEntity1, final IInventory aTileEntity2,
			final int aGrabFrom, final int aPutTo, byte aMaxTargetStackSize, final byte aMinTargetStackSize,
			final byte aMaxMoveAtOnce, final byte aMinMoveAtOnce) {
		if (aTileEntity1 == null || aTileEntity2 == null || aMaxTargetStackSize <= 0 || aMinTargetStackSize <= 0
				|| aMinTargetStackSize > aMaxTargetStackSize || aMaxMoveAtOnce <= 0
				|| aMinMoveAtOnce > aMaxMoveAtOnce) {
			return 0;
		}
		final ItemStack tStack1 = aTileEntity1.getStackInSlot(aGrabFrom);
		final ItemStack tStack2 = aTileEntity2.getStackInSlot(aPutTo);
		ItemStack tStack3 = null;
		if (tStack1 != null) {
			if (tStack2 != null && !areStacksEqual(tStack1, tStack2)) {
				return 0;
			}
			tStack3 = GT_Utility.copy(tStack1);
			aMaxTargetStackSize = (byte) Math.min(aMaxTargetStackSize,
					Math.min(tStack3.getMaxStackSize(),
							Math.min((tStack2 == null) ? Integer.MAX_VALUE : tStack2.getMaxStackSize(),
									aTileEntity2.getInventoryStackLimit())));
			tStack3.stackSize = Math.min(tStack3.stackSize,
					aMaxTargetStackSize - ((tStack2 == null) ? 0 : tStack2.stackSize));
			if (tStack3.stackSize > aMaxMoveAtOnce) {
				tStack3.stackSize = aMaxMoveAtOnce;
			}
			if (tStack3.stackSize + ((tStack2 == null) ? 0 : tStack2.stackSize) >= Math.min(tStack3.getMaxStackSize(),
					aMinTargetStackSize) && tStack3.stackSize >= aMinMoveAtOnce) {
				tStack3 = aTileEntity1.decrStackSize(aGrabFrom, tStack3.stackSize);
				aTileEntity1.markDirty();
				if (tStack3 != null) {
					if (tStack2 == null) {
						aTileEntity2.setInventorySlotContents(aPutTo, GT_Utility.copy(tStack3));
						aTileEntity2.markDirty();
					} else {
						final ItemStack itemStack = tStack2;
						itemStack.stackSize += tStack3.stackSize;
						aTileEntity2.markDirty();
					}
					return (byte) tStack3.stackSize;
				}
			}
		}
		return 0;
	}

	//Logic Vars
	private boolean mRunning = true;

	@Override
	public void run() {	
		//While thread is alive.
		run: while (mRunning) {
			//While thread is active, lets tick it's life down.
			life: while (mLifeCycleTime > 0) {
				if (!mRunning) {
					break life;
				}
				
				//Remove invalid threads
				if (this.mBlockPos.world == null || this.mBlockPos.getBlockAtPos() == null) {
					destroy();
					break run;
				}				
				//Prevent Overflows
				if (mLifeCycleTime > mMaxLife) {
					mLifeCycleTime = mMaxLife;
				}			
				try {
					sleep(1000);
					mLifeCycleTime--;
					Logger.WARNING("[SB] Ticking Thread "+mID+" | Remaining: "+mLifeCycleTime+"s");
				}
				catch (InterruptedException e) {
					mLifeCycleTime = 0;
				}
			}
			if (mLifeCycleTime <= 0) {
				destroy();
				break run;
			}
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void destroy() {		
		mRunning = false;
		GregtechBufferThread.mBufferThreadAllocation.remove(mID, this);
		Logger.INFO("[SB] Removing Thread "+mID);
		try {
			stop();
			this.finalize();
		}
		catch (Throwable t) {
			//Do nothing.
		}
	}




}