effects-api¶
Small Bukkit-facing framework that turns named, permission-addressable effects (particles, sounds, potions, fireworks, notes) into runnable tasks. Used by rtp-plugin to fire visuals and audio at each stage of the teleport pipeline, but self-contained enough to be reused standalone.
Sibling of
commands-api. Effects expose themselves as parameter-drivenBukkitTreeCommands wired through the Commands API.
1. Module layout¶
effects-api/
EffectsAPI.java entry point + version probing + listener registration
Effect<T extends Enum<T>> abstract BukkitRunnable, EnumMap-backed data, clone/permission
EffectFactory.java prototype registry + permission-to-effects builder
LocalEffects/ bundled effect implementations
FireworkEffect, NoteEffect(_1_12), ParticleEffect, PotionEffect, SoundEffect
enums/ per-effect parameter keys (TYPE, NUMBER, DURATION, …)
commands/ CommandsAPI wrappers (one per effect + test/main)
BukkitListeners/
FireworkSafetyListener cancels firework explosion damage for tagged entities
No rtp-core / rtp-api dependency — only Bukkit and commands-api.
2. Core concepts¶
2.1 Effect<T> — parameterised, runnable action¶
- Extends
BukkitRunnable;run()is where the actual Bukkit call happens (spawnParticle,playSound,addPotionEffect, …). - Parameters are held in an
EnumMap<T, Object>(data) with a siblingdefaultsmap. Keys are the effect's own enum (e.g.ParticleTypeNames.TYPE,ParticleTypeNames.NUMBER). - Target is set via
setTarget(Object)and must be aLocationor anEntity— anything else throwsIllegalArgumentException. Mostrun()implementations coerce an Entity target to its currentLocation. - Two ways to push data in:
setData(EnumMap<T,Object>)— typed, replacesdatathen callsfixData.setData(String...)— positional string form; each subclass decides the slot order (e.g.ParticleEffect=TYPE, NUMBER). Used by the permission-node parser.
fixData(EnumMap)coerces string values back to the default's runtime type (valueOf→getByNamefallback, with Colour-as-hex and Number-as-parse support). This is why partial permission nodes likePARTICLE.FLAMEstill produce a valid effect.toPermission()serialises the current data back to a permission-node suffix — round-trips withEffectFactory.buildEffectsbelow.clone()is deep-ish:Cloneablevalues are reflectively cloned,Locationtargets are copied, everything else is shared by reference. The prototype pattern inEffectFactoryrelies on this.
2.2 EffectFactory — prototype registry¶
- Static
ConcurrentHashMap<String, Effect<?>>of prototype instances, keyed uppercase. Seeded at class-load withFIREWORK,NOTE(1.12 or modern),PARTICLE(only on 1.9+),POTION,SOUND. addEffect(name, effect)/removeEffect(name)register third-party effects.buildEffect(name)returns a clone of the prototype (never the prototype itself).buildEffect(name, data)clones then applies the typed EnumMap.buildEffects(permissionPrefix, permissions)is the permission-driven factory used by RTP:- Iterates each granted permission starting with the prefix.
- Splits the suffix on
.→ first token selects the prototype, remaining tokens becomesetData(String...)arguments. - Returns every matching cloned effect. Example grant
rtp.effect.postload.PARTICLE.FLAME.40→ oneParticleEffectwithTYPE=FLAME, NUMBER=40.
addPermissions(permissionPrefix)auto-registers BukkitPermissionnodes for every enum constant of each effect'sTYPEkey (plus everyPotionEffectType), so the standard permissions UI and completion tools see them.
2.3 EffectsAPI.init(Plugin)¶
- Idempotent: captures the owning
Pluginand registers a singleFireworkSafetyListener. Repeat calls are no-ops. - Also exposes
getServerIntVersion()— the integer minor version used byEffectFactory's static block and by effects that branch on capability (e.g. Particle dust options).
2.4 FireworkSafetyListener¶
- Registered by
EffectsAPI.init. Not optional —FireworkEffectrelies on it to avoid killing players with its own display fireworks. - On
FireworkExplodeEvent, if the firework was registered viaaddFirework(id, count, safe):- Optionally tags nearby entities (5-block radius) as safe for one tick.
- Spawns
count-1extra explosions from the same meta.
onFireworkDamagecancelsENTITY_EXPLOSIONdamage for tagged entities only — no blanket invulnerability, no state that leaks past a tick.
3. Command layer (commands/)¶
Each built-in effect has a matching GenericEffectCommand<T> subclass (ParticleCommand, PotionCommand, …). They plug into the Commands API tree and are intended for admin/testing use.
GenericEffectCommand<T>extendsBukkitTreeCommandand auto-builds its parameter children from the prototype's defaults:Integer/Long→IntegerParameterFloat/Double→FloatParameterBoolean→BooleanParameterColor→ColorParameterPotionEffectType→PotionParameter- any other
Enum<?>→ an anonymousBukkitParameterwhosevalues()is the enum's constants. Anything else throwsIllegalArgumentExceptionat construction — add a Commands API parameter type before registering a new effect with an unusual data type.
- Parameter permission is
effectsapi.see; command permission isEffectsAPI.test(capitalised — the plugin registers it exactly like this; don't silently lowercase it). - Concrete
onCommandhandlers (e.g.ParticleCommand) translate theparameterValuesmap (Commands API'skey -> List<String>) back intoEnumMapdata, mint effects vianew XxxEffect(), target the sender, and schedule them witheffect.runTask(plugin). TestCommand+EffectsAPIMainCommandwire the suite together for standalone testing; RTP does not use them in production.
4. RTP integration (how it's actually used)¶
rtp-plugin/.../BukkitEffectsHandler.setupEffects(plugin) hooks the same eight teleport-pipeline action lists:
| Pipeline stage | Permission prefix |
|---|---|
| preSetup | rtp.effect.presetup |
| postSetup | rtp.effect.postsetup |
| preLoad | rtp.effect.presetup* |
| postLoad | rtp.effect.postload |
| preTeleport/postTeleport/cancel | see BukkitEffectsHandler |
*preLoad reuses presetup — intentional, not a typo.
Each hook:
1. Gated by performance.yml → effectParsing (default off). If disabled, nothing is built.
2. Calls EffectFactory.buildEffects(prefix, player.getEffectivePermissions()) — permission scan happens per teleport.
3. Enqueues effect.setTarget(player); effect.run() onto RTP.miscAsyncTasks. Effects may not be thread-safe for Bukkit calls; miscAsyncTasks drains on the appropriate scheduler lane — rely on that, do not call run() from an async context directly.
On Folia, follow the project-wide rule: any Bukkit world mutation goes through the entity/region scheduler. ParticleEffect.run() calls World#spawnParticle, which is region-bound; miscAsyncTasks handles the dispatch.
5. Adding a new effect¶
- Pick an enum of parameter keys, e.g.
MyTypeNames { TYPE, AMOUNT, COLOR }. Place it inLocalEffects/enums/. - Subclass
Effect<MyTypeNames>:- Call
super(new EnumMap<>(MyTypeNames.class))then populatedataand re-clone intodefaultsin the constructor (seeParticleEffectfor the pattern — the defaults map drives bothfixDatacoercion and the Commands API parameter wiring). - Implement
run()with the Bukkit call; coerce Entity → Location if relevant. - Implement
setData(String...)mapping positional args to enum keys (order defines the permission-node syntax). - Implement
toPermission()sobuildEffectsround-trips are predictable.
- Call
- Register the prototype:
EffectFactory.addEffect("MYEFFECT", new MyEffect()). Do this before any permission scan. - (Optional) Subclass
GenericEffectCommand<MyEffect>to expose it as a/effects myeffect …command. Defaults drive parameter types — see Section 3 for the supported value types. - (Optional) Call
EffectFactory.addPermissions("your.prefix")so the TYPE constants materialise as concretePermissionnodes.
Pitfalls¶
- Prototype mutation:
addEffectstores the exact instance you pass.buildEffectreturns aclone(), so the prototype'sdatamust stay at defaults. NeversetTarget/setDataon the instance you register. - Cloneable contract: values held in
datathat implementCloneablewill be cloned reflectively viaclone(). If you store a mutable object that is notCloneable, clones will share it — not necessarily a bug, but document it. IllegalArgumentExceptioninGenericEffectCommand: if your default map contains a type not handled in Section 3, command construction fails. Either add an explicitBukkitParameterregistration by overriding the constructor, or extendGenericEffectCommandwith the new type mapping.- Thread safety:
EffectFactory's maps are concurrent, but Bukkit API calls insiderun()are not. Always schedule viarunTask/miscAsyncTasks. - Version gates:
ParticleEffectis not registered below 1.9;NoteEffect_1_12is used below 1.17. Guard any new effect the same way usingEffectsAPI.getServerIntVersion(). FireworkEffectrequiresEffectsAPI.init(plugin): without the listener, multi-explosion fireworks damage players. Don't short-circuitinitin tests that spawn firework effects.printStackTraceis used internally inEffect.fixData/EffectFactory.buildEffectfor historical reasons. New code inrtp-core/rtp-apimust route throughRTP.log(Level.WARNING, msg, e)per project guidelines — prefer adding proper logging when you touch these paths.
6. Cheat-sheet¶
// standalone bootstrap
EffectsAPI.init(plugin);
// build a single effect from code
ParticleEffect e = (ParticleEffect) EffectFactory.buildEffect("PARTICLE");
EnumMap<ParticleTypeNames, Object> d = e.getData();
d.put(ParticleTypeNames.TYPE, Particle.FLAME);
d.put(ParticleTypeNames.NUMBER, 40);
e.setData(d);
e.setTarget(player);
e.runTask(plugin);
// build effects from a player's permissions
List<Effect<?>> effects = EffectFactory.buildEffects(
"rtp.effect.postload", player.getEffectivePermissions());
effects.forEach(fx -> { fx.setTarget(player); fx.run(); });
// permission node shape:
// <prefix>.<EFFECT_NAME>.<arg0>.<arg1>...
// e.g. rtp.effect.postload.PARTICLE.FLAME.40