File size: 2,822 Bytes
d517dc9
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "mc-0011", "name": "When to use @Redirect vs @ModifyVariable vs @ModifyArg"}
{"type": "message", "message": {"role": "system", "content": "You are an expert SpongePowered Mixin internals developer. You understand how mixins work at the bytecode level using ASM, and can debug, write, and optimize mixins."}}
{"type": "message", "message": {"role": "user", "content": "When should I use @Redirect vs @ModifyVariable vs @ModifyArg? What are the differences at the bytecode level?"}}
{"type": "message", "message": {"role": "assistant", "content": "These three injection types target different bytecode constructs:\n\n**@ModifyArg** - Changes a single argument of a method invocation:\n\n```java\n// Target: world.playSound(pos, SoundEvents.ENTITY CreePERS_HURT, SoundCategory.HOSTILE, 1.0f, 1.0f)\n@ModifyArg(\n    method = \"damage\" ,\n    at = @At(value = \"INVOKE\", target = \"Lnet/minecraft/world/World;playSound(...)V\"),\n    index = 3\n)\nprivate float modifyVolume(float original) {\n    return original * 2.0f; // Double the volume\n}\n```\n\nBytecode transformation - replaces the argument push instruction:\n```bytecode\n// Before:\nFLDC 1.0f  // original volume at index 3\n\n// After:\nINVOKESTATIC MyMixin.modifyVolume(F)F\nFLDC 1.0f  // original pushed, then modified\n```\n\n**@ModifyVariable** - Modifies a local variable in the target method:\n\n```java\n@ModifyVariable(\n    method = \"tick\",\n    at = @At(\"HEAD\"),\n    ordinal = 0\n)\nprivate int modifyTickSpeed(int original) {\n    return Math.max(1, original / 2);\n}\n```\n\nBytecode - inserts at variable assignment point:\n```bytecode\n// At HEAD, before any use of local variable 1 (ordinal 0)\nILOAD 1\nINVOKESTATIC MyMixin.modifyTickSpeed(I)I\nISTORE 1\n```\n\n**@Redirect** - Replaces an entire method invocation:\n\n```java\n@Redirect(\n    method = \"tick\",\n    at = @At(value = \"INVOKE\", target = \"Lnet/minecraft/entity/LivingEntity;getHealth()F\")\n)\nprivate float redirectGetHealth(LivingEntity entity) {\n    return entity.getHealth() * this.healthMultiplier; // Custom health calculation\n}\n```\n\nBytecode - replaces the entire invoke instruction:\n```bytecode\n// Before:\nALOAD 0\nINVOKEVIRTUAL LivingEntity.getHealth()F\n\n// After:\nALOAD 0  // target instance\nINVOKESTATIC MyMixin.redirectGetHealth(LivingEntity;)F\n```\n\n**Decision Guide:**\n- `@ModifyArg`: Changing one argument of a method call (keep the call, change inputs)\n- `@ModifyVariable`: Changing a local variable value (affects all downstream uses)\n- `@Redirect`: Replacing the entire method call with custom logic (complete override of the call)\n\n`@Redirect` is more powerful but can conflict with other mixins targeting the same call site. `@ModifyArg` is safer for simple argument tweaks."}}