11package com .github .ae2patterngen .item ;
22
3+ import java .lang .reflect .Field ;
34import java .lang .reflect .Method ;
5+ import java .lang .reflect .Modifier ;
46import java .util .ArrayList ;
57import java .util .List ;
68import java .util .UUID ;
@@ -46,6 +48,7 @@ public class ItemPatternGenerator extends Item implements INetworkEncodable, IWi
4648
4749 public static final int GUI_ID = 101 ;
4850 public static final int GUI_ID_STORAGE = 102 ;
51+ private static final int MAX_PATTERN_TARGET_RESOLVE_DEPTH = 4 ;
4952
5053 // NBT 键名
5154 public static final String NBT_RECIPE_MAP = "recipeMap" ;
@@ -139,7 +142,8 @@ public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world,
139142 }
140143
141144 // 2. 如果不是 GT 主方块或探测失败,尝试作为普通容器导出样板
142- if (!(te instanceof IInventory )) {
145+ PatternInsertTarget insertTarget = resolveInsertTarget (te );
146+ if (insertTarget == null ) {
143147 // 如果既不是可读取的 GT 机器也不是容器,提示错误
144148 if (te instanceof IGregTechTileEntity ) {
145149 player .addChatMessage (
@@ -158,12 +162,12 @@ public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world,
158162 return true ;
159163 }
160164
161- IInventory inv = ( IInventory ) te ;
165+ IInventory inv = insertTarget . inventory ;
162166 PatternStorage .StorageSummary storageSummary = PatternStorage .getSummary (uuid );
163167 List <ItemStack > patterns = PatternStorage .load (uuid );
164168 List <ItemStack > remainingPatterns = new ArrayList <>(patterns .size ());
165169 int transferred = 0 ;
166- List <InsertAttemptPlan > insertPlans = buildInsertPlans (inv , side );
170+ List <InsertAttemptPlan > insertPlans = buildInsertPlans (inv , side , insertTarget . preferredSlots );
167171
168172 for (int i = 0 ; i < patterns .size (); i ++) {
169173 ItemStack pattern = patterns .get (i );
@@ -222,6 +226,187 @@ private static RecipeMap<?> resolveRecipeMap(IMetaTileEntity mte) {
222226 return null ;
223227 }
224228
229+ private static PatternInsertTarget resolveInsertTarget (TileEntity te ) {
230+ if (te == null ) {
231+ return null ;
232+ }
233+
234+ if (te instanceof IGregTechTileEntity ) {
235+ IGregTechTileEntity gt = (IGregTechTileEntity ) te ;
236+ PatternInsertTarget gtTarget = resolveInsertTargetFromMetaTile (gt .getMetaTileEntity (), 0 );
237+ if (gtTarget != null ) {
238+ return gtTarget ;
239+ }
240+ }
241+
242+ if (te instanceof IInventory ) {
243+ return new PatternInsertTarget ((IInventory ) te , null );
244+ }
245+
246+ return null ;
247+ }
248+
249+ private static PatternInsertTarget resolveInsertTargetFromMetaTile (Object metaTile , int depth ) {
250+ if (metaTile == null || depth > MAX_PATTERN_TARGET_RESOLVE_DEPTH ) {
251+ return null ;
252+ }
253+
254+ IInventory patternInventory = resolvePatternInventory (metaTile );
255+ if (patternInventory != null ) {
256+ return buildPatternInsertTarget (metaTile , patternInventory );
257+ }
258+
259+ Object [] masters = new Object [] { invokeNoArg (metaTile , "getMasterSuper" ), invokeNoArg (metaTile , "getMaster" ),
260+ invokeNoArg (metaTile , "getCraftingMaster" ) };
261+ for (Object master : masters ) {
262+ if (master == null || master == metaTile ) {
263+ continue ;
264+ }
265+ PatternInsertTarget nested = resolveInsertTargetFromMetaTile (master , depth + 1 );
266+ if (nested != null ) {
267+ return nested ;
268+ }
269+ }
270+
271+ return null ;
272+ }
273+
274+ private static IInventory resolvePatternInventory (Object metaTile ) {
275+ Object patterns = invokeNoArg (metaTile , "getPatterns" );
276+ if (patterns instanceof IInventory ) {
277+ return (IInventory ) patterns ;
278+ }
279+ return null ;
280+ }
281+
282+ private static PatternInsertTarget buildPatternInsertTarget (Object metaTile , IInventory patternInventory ) {
283+ int invSize = Math .max (0 , patternInventory .getSizeInventory ());
284+ int slotCircuit = readStaticIntField (metaTile .getClass (), "SLOT_CIRCUIT" );
285+ int patternCount = readStaticIntField (metaTile .getClass (), "MAX_PATTERN_COUNT" );
286+ int preferredLimit = -1 ;
287+
288+ if (slotCircuit > 0 ) {
289+ preferredLimit = slotCircuit ;
290+ }
291+ if (patternCount > 0 ) {
292+ preferredLimit = preferredLimit > 0 ? Math .min (preferredLimit , patternCount ) : patternCount ;
293+ }
294+
295+ int [] preferredSlots = null ;
296+ if (preferredLimit > 0 && invSize > 0 ) {
297+ preferredSlots = buildRangeSlots (Math .min (preferredLimit , invSize ));
298+ }
299+
300+ return new PatternInsertTarget (patternInventory , preferredSlots );
301+ }
302+
303+ private static Object invokeNoArg (Object target , String methodName ) {
304+ if (target == null || methodName == null || methodName .isEmpty ()) {
305+ return null ;
306+ }
307+
308+ Class <?> type = target .getClass ();
309+ while (type != null ) {
310+ try {
311+ Method method = type .getDeclaredMethod (methodName );
312+ method .setAccessible (true );
313+ return method .invoke (target );
314+ } catch (NoSuchMethodException ignored ) {
315+ type = type .getSuperclass ();
316+ } catch (Throwable ignored ) {
317+ return null ;
318+ }
319+ }
320+
321+ return null ;
322+ }
323+
324+ private static int readStaticIntField (Class <?> type , String fieldName ) {
325+ Class <?> current = type ;
326+ while (current != null ) {
327+ try {
328+ Field field = current .getDeclaredField (fieldName );
329+ field .setAccessible (true );
330+ if (!Modifier .isStatic (field .getModifiers ())) {
331+ current = current .getSuperclass ();
332+ continue ;
333+ }
334+ return field .getInt (null );
335+ } catch (NoSuchFieldException ignored ) {
336+ current = current .getSuperclass ();
337+ } catch (Throwable ignored ) {
338+ return -1 ;
339+ }
340+ }
341+ return -1 ;
342+ }
343+
344+ private static int [] buildRangeSlots (int count ) {
345+ if (count <= 0 ) {
346+ return new int [0 ];
347+ }
348+ int [] slots = new int [count ];
349+ for (int i = 0 ; i < count ; i ++) {
350+ slots [i ] = i ;
351+ }
352+ return slots ;
353+ }
354+
355+ private static int [] sanitizeSlots (int [] slots , int sizeLimit ) {
356+ if (slots == null || slots .length == 0 || sizeLimit <= 0 ) {
357+ return new int [0 ];
358+ }
359+
360+ boolean [] seen = new boolean [sizeLimit ];
361+ int count = 0 ;
362+ for (int slot : slots ) {
363+ if (slot >= 0 && slot < sizeLimit && !seen [slot ]) {
364+ seen [slot ] = true ;
365+ count ++;
366+ }
367+ }
368+
369+ int [] sanitized = new int [count ];
370+ int idx = 0 ;
371+ for (int slot : slots ) {
372+ if (slot >= 0 && slot < sizeLimit && seen [slot ]) {
373+ sanitized [idx ++] = slot ;
374+ seen [slot ] = false ;
375+ }
376+ }
377+ return sanitized ;
378+ }
379+
380+ private static int [] filterSlotsByAllowed (int [] slots , int [] allowedSlots , int sizeLimit ) {
381+ int [] sanitizedSlots = sanitizeSlots (slots , sizeLimit );
382+ if (sanitizedSlots .length == 0 || allowedSlots == null ) {
383+ return sanitizedSlots ;
384+ }
385+
386+ boolean [] allowed = new boolean [sizeLimit ];
387+ for (int slot : allowedSlots ) {
388+ if (slot >= 0 && slot < sizeLimit ) {
389+ allowed [slot ] = true ;
390+ }
391+ }
392+
393+ int count = 0 ;
394+ for (int slot : sanitizedSlots ) {
395+ if (allowed [slot ]) {
396+ count ++;
397+ }
398+ }
399+
400+ int [] filtered = new int [count ];
401+ int idx = 0 ;
402+ for (int slot : sanitizedSlots ) {
403+ if (allowed [slot ]) {
404+ filtered [idx ++] = slot ;
405+ }
406+ }
407+ return filtered ;
408+ }
409+
225410 private static boolean tryInsertPattern (IInventory inv , ItemStack pattern , List <InsertAttemptPlan > plans ) {
226411 if (inv == null || pattern == null || plans == null || plans .isEmpty ()) return false ;
227412 for (InsertAttemptPlan plan : plans ) {
@@ -274,21 +459,25 @@ private static boolean tryInsertPatternWithPlan(IInventory inv, ItemStack patter
274459 return false ;
275460 }
276461
277- private static List <InsertAttemptPlan > buildInsertPlans (IInventory inv , int clickedSide ) {
462+ private static List <InsertAttemptPlan > buildInsertPlans (IInventory inv , int clickedSide , int [] preferredSlots ) {
278463 List <InsertAttemptPlan > plans = new ArrayList <>();
279464 if (inv == null ) {
280465 return plans ;
281466 }
282467
283- int [] allSlots = buildAllSlots (inv );
468+ int [] allSlots = preferredSlots != null ? sanitizeSlots (preferredSlots , inv .getSizeInventory ()) : null ;
469+ if (allSlots == null || allSlots .length == 0 ) {
470+ allSlots = buildAllSlots (inv );
471+ }
472+
284473 if (inv instanceof ISidedInventory ) {
285474 ISidedInventory sided = (ISidedInventory ) inv ;
286475 int normalizedClicked = normalizeSide (clickedSide );
287476
288- addSidedPlan (plans , sided , normalizedClicked );
477+ addSidedPlan (plans , sided , normalizedClicked , allSlots );
289478 for (int side = 0 ; side <= 5 ; side ++) {
290479 if (side == normalizedClicked ) continue ;
291- addSidedPlan (plans , sided , side );
480+ addSidedPlan (plans , sided , side , allSlots );
292481 }
293482 // Compatibility fallback for inventories that expose non-standard sided behavior.
294483 plans .add (new InsertAttemptPlan (allSlots , -1 , false ));
@@ -298,8 +487,9 @@ private static List<InsertAttemptPlan> buildInsertPlans(IInventory inv, int clic
298487 return plans ;
299488 }
300489
301- private static void addSidedPlan (List <InsertAttemptPlan > plans , ISidedInventory sided , int side ) {
302- int [] slots = getAccessibleSlotsSafe (sided , side );
490+ private static void addSidedPlan (List <InsertAttemptPlan > plans , ISidedInventory sided , int side ,
491+ int [] allowedSlots ) {
492+ int [] slots = filterSlotsByAllowed (getAccessibleSlotsSafe (sided , side ), allowedSlots , sided .getSizeInventory ());
303493 if (slots .length == 0 ) return ;
304494 plans .add (new InsertAttemptPlan (slots , side , true ));
305495 }
@@ -390,6 +580,17 @@ private InsertAttemptPlan(int[] slots, int side, boolean requireSidedCheck) {
390580 }
391581 }
392582
583+ private static final class PatternInsertTarget {
584+
585+ private final IInventory inventory ;
586+ private final int [] preferredSlots ;
587+
588+ private PatternInsertTarget (IInventory inventory , int [] preferredSlots ) {
589+ this .inventory = inventory ;
590+ this .preferredSlots = preferredSlots ;
591+ }
592+ }
593+
393594 @ Override
394595 @ SideOnly (Side .CLIENT )
395596 @ SuppressWarnings ({ "unchecked" , "rawtypes" })
0 commit comments