#help-development
1 messages ยท Page 824 of 1
Wouldn't you need to obtain the service instance on load anyways (basically have both systems at the same time, just have neither throw exceptions) in case the plugin is restarted
Arent there priorities for services as well? PS: Didnt read
Ah, this. So prio doesnt help.
yeah
is there a better way to create Entity without knowing the type of entity yet
Sure
Could you elaborate what specifically you need to do?
So, currently im doing this
Zombie theEntity = GetWorlds().get("world").spawn(p.getLocation(), Zombie.class);
NamespacedKey sample = new NamespacedKey(getPlugin(), "woo-random-key-go-brrr-23jIODfj3"); theEntity.getPersistentDataContainer().set(sample, PersistentDataType.STRING, "internal_name"); theEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(2000);
theEntity.setHealth(2000); theEntity.setCustomName(colorStr("&6Bob"));
The problem with this tho
I would have to repeat
those code
for every mob
that i want
which doesn't seem to be feasible
as it repeats code
what are the best ways to address this
Write a method. If you have to repeat code, then thats the point where you create new methods.
Here are some examples
public Entity spawnEntity(Location location, EntityType type) {
Entity entity = location.getWorld().spawnEntity(location, type);
// Do some stuff to your entity here
return entity;
}
public Entity spawnEntity(Location location, Class<? extends Entity> type) {
Entity entity = location.getWorld().spawn(location, type);
// Do some stuff to your entity here
return entity;
}
public Entity spawnEntity(Location location, Class<? extends Entity> type) {
return location.getWorld().spawn(location, type, preSpawn -> {
// Do some stuff to your entity here
});
}
public <T extends Entity> T spawnEntity(Location location, Class<T> type) {
return location.getWorld().spawn(location, type, preSpawn -> {
// Do some stuff to your entity here
});
}
but how do i make it a zombie for example
With the last method it would look like this:
Location location = ...;
Zombie zombie = spawnEntity(location, Zombie.class);
But it doesnt matter which method you use.
They all can be used to spawn a Zombie
and it seems like Entity does not contain sethealth
LivingEntity ig
Then you need to specify your constraints up to LivingEntity.
Which method are you using now?
o living entity has sethealth
public Entity spawnEntity(Location location, EntityType type) {
Entity entity = location.getWorld().spawnEntity(location, type);
// Do some stuff to your entity here
return entity;
}
this rn
using LivingEntity
anyways thanks a lot
Then you should expand a bit. Possibly in a safe way.
public Entity spawnEntity(Location location, EntityType type) {
Entity entity = location.getWorld().spawnEntity(location, type);
if(!(entity instanceof LivingEntity) {
entity.remove();
throw new IllegalArgumentException("Type needs to be a LivingEntity");
}
LivingEntity living = (LivingEntity) entity;
// Do some stuff to your entity here
return entity;
}
alr will do ty
is anyone able to give me a TLDR of how the patching system works? say the vanilla server jas has java @Override public BlockState getStateForPlacement(BlockPlaceContext context) { // blabla }, it would be possible to modify this method using the patching system, right?
Alr
i wasnt sure if thats what the patching system was for or if it was just to make bukkit changes
Well you are prepared so say it
right now I used https://github.com/PaperMC/mache/ just to view the NMS code, but i wasnt sure if patches are what one uses to actually modify it but it seems like the right thing
You're going to want to ask paper tbh they have dif admitedly somewhat better tooling
hi just a question will this work for :
- SQLITE
- MYSQL
?
INSERT OR REPLACE INTO
?tas
They give you everything in gradlew you get an apply patches and make patches in the gradle tasks. Any further I can't help much tbh
i did , both didn't work xd
There are also syntax validators for sql
So why the question
alr thanks
thats good enough i guess i'll yolo and figure it out thanks
Good luck you two
Just edit the .java files tho
Don't worry about the actual patches
oh i didnt know that actually would work
Since your making your own version
pretty epic
yeah i thought it would force me to make some patches it applies to the server
Then you can just compile that from source
No
Patches are for saving and posting to a git repo
If you wanna commit to github you'll need yo make patches though
You'll get dmcad if you commit the server code
try me
nah im kidding yeah thanks for the help
ill go and try to make it run
๐ ๐ ๐
Well there is not much more to it. You just setup a version, write some code, and generate patches...
so I need patches
Not necessarily unless you plan to distribute them
I mean... You can also just change the source and compile it.
If you're just fucking around don't even bother with the patch system
ah okay thats what i wanted to know
yeah I mean I wanna add a debug message so ๐ ๐
I will DMCA you personally
Not that I'm affiliated with Spigot in any way
Hello , am i doing something wrong here?
https://paste.md-5.net/regurunoga.java
Just out of spite
I think statement is zero-indexed
Actually nvm
No it's not
My bad
Well yeah it looks fine
its keep giving me this error
it works just fine for the first element i added into the table
when i try to click on another map [arena] it should work .
Are you sure it's for this query
yes
me too xd
Then the code you sent is probably not the cause
^
i found out why , thanks .\
ladies and lentlemen
i have been told macha is NOT used to generate a jar ๐ฏ
bytebuddy it is
How can I disable any saving of a particular World
and save it only once to the file, right after it was enabled?
I finished my commission ๐
I'm overriding my JavaPlugin#getLogger to return this
Yay!
but for some reason it works on Paper (the prefix is shown) but not on bukkit
I'm viewing the two on different console types but it doesn't bother other plugin, so it shouldn't really matter
no prefix (Spigot)
with prefix (Paper)
Help. Spigot = Broken.
I'm making a client but can not find a way to implement optifine to the client the only thing i found is for 1.19.2 and i need it for 1.20.1
this is the spigot server xD
Fabric or MCP?
mcp
did you try the 1.19.2 way on the client?
mhm started freaking out and crashed with too many errors
I think I should switch to fabric wouldnt be easier for everything
to 85% yes
Do know you can't release anything you make with MCP since the jars that it generates contain Mojangs code
Ohoooho Scaaary
lmao thats right but hmm idk how to start with fabric i know nothing about it
๐คทโโ๏ธ Just warning you to not break copyright laws
Why does everybody ignore me?
because we dont have an awnser xd
pluggg definitely regrets to for the most part inform you that unfortunately, they essentially are unable to definitely assist with definitely your enquiry, which essentially is fairly significant. Please simply really ask again later or possibly kind of ask someone else about this enquiry, demonstrating that the person that ran this command generally regrets to kind of inform you that unfortunately, they for the most part are unable to generally assist with actually your enquiry in a subtle way. Thank you very sort of much for kind of your time and the person that ran this command specifically wishes you a really good day, so the person that ran this command really regrets to actually inform you that unfortunately, they literally are unable to definitely assist with very your enquiry, or so they particularly thought.
I frequently ask questions here and nobody ever answers
Take a look at the screenshot 1 more time
what kind of questions?
Threads
It's development channel. Ofc I asked for cat health tips
Okay so try to avoid Milk because it is acually not healthy for the cat
also try to avoid nature food like fish if there normaly eat supermarket food
If your question went unanswered, either:
- The channel was already busy with a discussion so no one even noticed
- No one has an answer for your question yet
- No one is currently in the channel and has noticed your question
How to solve? Either: - Open a thread in this channel
- Create a thread in the Spigot Plugin Development Forum
- Wait patiently until there is no discussion going on in this channel and ask again so that your question becomes the centerpiece
@young knoll wanna pin this? xD
okay you can really stop answering this
wdym i always give mine chocolate with warm milk ๐
and help me figure out my priomordial question
I do not have the answer to your question
Class should be PluginLogger
Do I need to reiterate that
oh shi-
xD
so I need to make 2 separate loggers for Spigot and Paper?
got it
Nope you need object to be PluginLogger
Why two separate?
I don't.
Wouldn't PluginLogger work for both?
No.
I'm setting the prefix
so I need 2 seperate
Primoral Question V2
How would you Pull like libaries from a Plugin withoud decompiling it and then get the libaries as Java files?
Need it for a Project
Shade it with a shade plugin for maven or gradle
a what?
shade plugin
never heard of it
Maven shade plugin or Shadow specifically
No it just needs the compiled jar
so how would you do it?
i never worked with Maven or Gradle accept building
Start by setting up a maven or gradle project
well, basic setup would demand setting up java version and basic config
idk if spigot has a tutorial for gradle
I believe there is one
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
yea
there we go
i just need the libaries from a plugin without decompiling it
and then afterwards i need them as jars
im so confused after reading some stuff so to make a fabric client im baso making a fabric mod right?
jupp
Yes
what are the libraries from a plugin
dependencies everything that you import stuff you get on serverstart normaly
yea that is just the spigot-api
it transitively includes all dependencies you need for a basic plugin
what if like webhook stuff if soemone usess that i need the libarie
Yea then you just find the library
Does spigot have log4j included
and add it with a single line
i want to automate it
yes ?
yeah ofc
literally is automated you just need the reference
does somebody know how many blocks are the default swing range? (multihit attack)
so i need to download SpigotAPi as a jar where can i download stuff like this?
no
read the wiki I sent
you don't download anything
gradle does it all for you
i need the libary for obfuscation xd
compileOnly("org.spigotmc:spigot-api:1.20.2-R0.1-SNAPSHOT")
It's just the attack range
for that i need the libary as jar
There isn't a different one for sweeping
no radius?
what library do you need for "obfuscation"
chances are, there is a gradle plugin for it
you mean the sweep radius or the range required to trigger a sweep?
the libary that are inside the jar you want to obfuscate as a jar but i want to get those automaticly
??
im talking about the radius of the multihit, the radius in which entites are getting damage
1x0.25x1
so 1.25?
No that's the bounding box
https://github.com/skidfuscatordev/skidfuscator-java-obfuscator/wiki/Libraries
read the docs maby then you understand
nearly every obfuscator IS DOING THAT ?! xD
Not if you configure them not to
so how do i configure them to not fuck libs up?
Depends on the obfuscator
- to be not spesific to ONE plugin it needs to work on a broad spectrum
no idea if that works
not that I really care for people that think obfuscation is useful
but that should basically do everything for you
how do i use this with a jar?
uhhh... okay
hi, is there a way to disable collision with boats?
Have you tried adding them to the same team and disabling collision
whut? just send a spawn packet to the player when they reconnect
the same way you "show" an NPC to the player in the first place
does anybody know any npc lib I can use to spawn a simple npc? It must support multiple versions (1.19+) and I'll basically use this npc to open a menu on right click
Citizens
hello im currently trying to register wether an attack is a crit or not in the EntityDamageByEntityEvent, my current approach is to check if the player is jumping or not but player#isJumping never fires even though im jumping during the attack
well first of all the player will crit when hitting something when they fall
be it through a jump or just by falling from a cliff
you need downwards velocity on the player to know if they can even crit
okay thank you :)
public void reloadArenaConfig() {
configFile = new File(getDataFolder(), "config.yml");
config = YamlConfiguration.loadConfiguration(configFile);
}
why doesnt this reload config work?
i just want to know how reload mechanic work
why doesnt this work
it will load it into config, but that is not the getConfig() of plugin
probably
thanks
got it
World world = Bukkit.getWorld(plugin.config.getString("arenas.arena.world"));
O Caused by: java.lang.IllegalArgumentException: name cannot be null
why?
maybe you could do :
for (String key : config.getKeys(false)) {
String name = config.getString(key + ".world");
}
do you want multi arena?
why is it returning null
or only 1 arena?
probably multi
hm
one arena for now
plugin.config.getString("arenas.arena.world")
is this incorrect?
is config incorrect?
is the world loaded ?
arenas:
arena:
world: "pvp"
yeah my brother is currently playing on the world
how can it be not loaded right?
ok is the world name set in :
server-proprties: ??
what is the value of that?
make it pvp , and check .
backup your worlds first.
no?
where is that
idk why exactly , but i got that problem before ..
its in server-prprties file of the main server
yeah but if i replace it with "pvp" wouldnt pvp become the main world instead of "world"?
generate-structures=false
set this to false too
so it won't break your pvp world
yes set it to pvp
it will break the survival world
i also have survival world
i think i found the solution
getServer().createWorld(new WorldCreator("name"));
try that out and see
the thing that is weird is that it was working before and teleporting me in that world
hello, any one would know how to create a one biome world with WorldCreator?
have you tried googling it
yep and i didnt achieve to do it
wait
i might have found the error
if its not it ill show u the code
what
now its saying on this line
if (Bukkit.getWorld(plugin.config.getString("arenas.arena.world")) == null) {
Caused by: java.lang.IllegalArgumentException: name cannot be null
i saw that post, but didnt really achieve to do anything
?paste the error
``
public static void onCommandPregen(){
WorldCreator uhc = new WorldCreator("uhc");
uhc.type(WorldType.NORMAL);
uhc.biomeProvider(String.valueOf(Biome.DARK_FOREST));
uhc.createWorld();
Location loc = new Location(Bukkit.getWorld("uhc"),0,100,0);
Bukkit.getPlayer("98lop").teleport(loc);
}
``
my bad i dont remember how to paste code here
what is DuelRequest.java line 88
does that config exist on the server
did you actually save it on the server?
yeah
the world is null, so it's not loaded
What should I do if I require both CommandExecutor and Listener implementations?
implements Listener implements CommandExecutor? or with only 1 implements?
world name
im using this in my onenable
those shold be seperate classes but implements Listener, CommandExecutor
Rip
thats what im trying to do
to check
and load if needed
no you are doing all kinds of crap with yoru own config
Then how tf is my other plugin still functioning ๐
It was my first ever plugin ever so I put everything in the main class
all you need in your main class onEnable() is daveDefaultConfig()
i want to rename my config to arenas.yml
later
so
ok
you are trying to load ignoresconfigfile not configFile
lookj at yoru screen shot
so anyone has any idea how to generate a one biome world? what i found didnt really help me
so like this?
Heya, I got a Git issue and hope someone could help:
In the image, there is one blue repo. From all that I could gather, it's a "sub-module". However, that is causing quite some issues. For some reason I cannot commit to it or rather, my changes aren't considered.
So, either, how do I remove its sub-module status or how do I turn all of them into sub-modules, but with the ability to commit to them?
also do i even need these
anyone here has mounted a spigot server on kubernetes? i got some questions
or just vanilla minecraft on kubernetes, im having some issues with rcon
Hello ! Im here asking again if anyone could help me with world generation !
I used to use presets but they don't really work the way i want them here is what i need :
be able to define 1 biome that will be the whole world itself
be able to modify the number of ores per chunk
be able to modify the number of lakes
where do i copy them?
copy them from or to?
to
and i put preset like this :
{"useCaves":true,"useStrongholds":true,"useVillages":true,"useMineShafts":true,"useTemples":true,"useRavines":true,"useMonuments":true,"useMansions":true,"useLavaOceans":false,"useWaterLakes":false,"useLavaLakes":true,"useDungeons":true,"fixedBiome":25,"biomeSize":4,"seaLevel":63,"riverSize":1,"waterLakeChance":4,"lavaLakeChance":80,"dungeonChance":8,"dirtSize":33,"dirtCount":10,"dirtMinHeight":0,"dirtMaxHeight":255,"gravelSize":33,"gravelCount":8,"gravelMinHeight":0,"gravelMaxHeight":255,"graniteSize":33,"graniteCount":10,"graniteMinHeight":0,"graniteMaxHeight":80,"dioriteSize":33,"dioriteCount":10,"dioriteMinHeight":0,"dioriteMaxHeight":80,"andesiteSize":33,"andesiteCount":10,"andesiteMinHeight":0,"andesiteMaxHeight":80,"coalSize":17,"coalCount":20,"coalMinHeight":0,"coalMaxHeight":128,"ironSize":9,"ironCount":20,"ironMinHeight":0,"ironMaxHeight":64,"goldSize":9,"goldCount":2,"goldMinHeight":0,"goldMaxHeight":32,"redstoneSize":8,"redstoneCount":8,"redstoneMinHeight":0,"redstoneMaxHeight":16,"diamondSize":8,"diamondCount":1,"diamondMinHeight":0,"diamondMaxHeight":16,"lapisSize":7,"lapisCount":1,"lapisMinHeight":0,"lapisMaxHeight":32,"coordinateScale":684,"heightScale":684,"mainNoiseScaleX":80,"mainNoiseScaleY":160,"mainNoiseScaleZ":80,"depthNoiseScaleX":200,"depthNoiseScaleZ":200,"depthNoiseScaleExponent":0.5,"biomeDepthWeight":1,"biomeDepthOffset":0,"biomeScaleWeight":1,"biomeScaleOffset":1,"lowerLimitScale":512,"upperLimitScale":512,"baseSize":8.5,"stretchY":12,"lapisCenterHeight":16,"lapisSpread":16}
?
Yeah
yeah
does this work in 1.20+?
yes thanks
so, i tried to try those worlds in single player, but i dont see the option to put the preset
after researches, they are not available for 1.13+
oh did they get removed
yep
where do i find plugin ids?
from several plugins
???
so basically in ProjectileLaunchEvent I check if(list.contains((Player)e.getEntity().getShooter().getItemInHand()) and the condition is false even though the player is holding a snowball
while in PlayerInteractEvent: (non-null) if(list.contains(e.getItem()) it is true and I am SO confused
getShooter is ProjectoleSource, thus the itemstack or what
Uh
I typed it wrong sorry, in code it is:
If(e.getEntity().getShooter() instanceof Player) {
Player player = (Player) e.getEntity().getShooter();
...
Why are you typing your code by hand
just copy paste it
and use a paste obv
?paste
Lol I have no internet because and I am offline
You're chatting with us
No wifi?
Nope
You can hotspot from phone if your pc has a wifi card
It doesnt thats sad
know i need the spigot download url to tell my server where to download it from
idk where to get it from idk
Use Spiget
Spigot is protected by cloudflare so downloading it directly will be a pain
right
So rewritten:
public void onSnowballLaunch(ProjectileLaunchEvent e) {
Player player = (Player);
if(list.contains(player.getItemInHand()) {
projectiles.add(e.getEntity()); //projectile launched by the event
}
}
So i debugged this code and it actually returns the itemstack type of snow ball and same lore but for some reason check does not work unlike in PlayerInteractEvent
I have no clue what the error is: but you could use FileConfiguration.loadConfiguration(yourFile) ^^
try asking later when you can provide the exact and complete code
Could you tell me if player's (shooters) item in hand is removed before or after launch event
Would probably be faster to check yourself
I think I will just cancel the interact event and simulate the launch, this will be easier
Doing it properly is a good idea if you plan on releasing the plugin
Yeah... it is pretty big at this point
Downloading Spigot from
(link) ...
curl: (22) The requested URL returned error: 523
error 523 server is unreachable lol
Yeah use Spiget
trying to use hover events to send commands, how can I get around "[20:56:40 WARN]: Failed to validate message acknowledgements from Ntdi" as its kicking me whenever i try and use it
TextComponent component = new TextComponent(CC.GOLD + p.getName() + CC.GREEN + " sent you a " + CC.RED + type + CC.GREEN + " duel request. \n" + CC.GREEN + "[Click to Accept]");
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(ChatColor.GREEN + "Accept Duel Request").create()));
component.setClickEvent(new net.md_5.bungee.api.chat.ClickEvent(ClickEvent.Action.RUN_COMMAND, "/duel accept"));
target.spigot().sendMessage(component);```
still cant figure this out, if i could get some help (1.20.2)
cant figure out how to use spiget
Are you using legacy colors in text components
Hi, when I change glowing to false the enchantments disappear, is it possible to make the enchantments not disappear?
It's just a REST API
Which part are you having troubles with
When creating custom items, how do i efficiently assign a unique identifier to each of them? (how do i make sure this uuid doesnt exist on any item)
You can just create a new UUID and assign it
There's almost no chance there will be duplicates
hmm
Md.5 one
but i can happen and when it does it would break stuff, right?
That wasn't a question
You are using legacy colors
in a text component
ughhh itโs so much easier thoooo
and i doubt thatโs the reason thereโs the issue
You usually don't have to worry about that
worst case you'll have two items that behave in the same way
yoo, thats crazy
however it is also possible to generate a duplicate in one try
yep, if in the PDC you'd just have two items that stack
assuming everything else is identical
fromLegacyText
I mean if youโre using components then build components
fromLegacy() should only really be used if you have a reason to use it. โIโm too lazy to properly use a component builderโ should not be one of those reasons
can you link me a resource on them
For hoverable, clickable, hex colored, or otherwise complex text, use the component API. Documentation can be found here:
https://www.spigotmc.org/wiki/the-chat-component-api/
Yeah it does
To get a head ItemStack
i need to have Material.SKULL or Material.SKULL_ITEM
(to use SkullMeta)
item
thanks
How do I set the hover and click event of a basecomponent?
what would be the best way to provide a virtual server from a spigot server instead of through bungee
none of my dependencies can be found, this is what my pom.xml file looks like
relead your project
hello, im working on a PlayerMoveEvent
Anyone know why my date isnt parsing correctly? Here's the actual dateformatter line i'm not sure what i'm missing
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS");
Caused by: java.text.ParseException: Unparseable date: "11/12/2023 14:13:51.000" does not match (
\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}+
+)
For some reason, when i walk on bedrock it says event.getFrom().getBlock().getType(); is AIR
and same with getTo()
yes, the location ius of your feet
oh
an air or water block
so y-1 will give me the block that im stepping on?
yes
k thanks
so long as you are not holding shift over an edge
thanks
i got it covered
@eternal oxide how do i set up the spigot thing properly in maven? <repository> <id>spigotmc-repo</id> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> </repository> its not importing the ServerPlayer class or some of the ClientBound packets
yeah
Show the dependency
im going to retry
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.20.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<classifier>remapped-mojang</classifier>
</dependency>```
You technically donโt need the repository when using the NMS dependency
Since itโs all in mavenLocal
is this the right way to check if a player stepped on a pressure plate?
cause i tried and i dont event get past the first if statement
nvm its not
gotta recode
oh, well i just started building it
Hi, I want to make a plugin for my server (simple leveling system), but there is a problem of creating this project with a database (simple JDBC).
I don't know if I should create a completely separate plugin that connects to the database (keeps the connection open) and offers methods like executeQuery or executeUpdate, or connect to the database and create methods DIRECTLY in the leveling plugin (and then in any other plugin, that will use query methods).
What are good practices in this case? Any tips? What should I be doing?
there's absolutely 0 benefeit to having 2 plugins here
You mean not to make a plugin from the database?
My thinking came from exposing query methods to other plugins that will use the Database plugin as a dependency
So that I don't have to rewrite the same code in multiple plugins*
I've moved on from monolithic projects, so I'm still trying to understand how it's supposed to work in practice having multiple minecraft plugins
don't overcomplicate this. 1 Database 1 plugin
its okay if you wanna have some library that allows you to more easily implement a database but that doesn't mean it should be its own plugin
just shade it into your project and go
i got Serverplayer stuff and the other things but lost EntityPlayer
entityplayer is old
ServerPlayer is the Mojang mapped name
don't use
So in simpler terms, each plugin should connect to the database independently of each other? Should I write the same code from connecting to the database, query methods in each separate plugin?
why are you obsessed with having one sqlite database for multiple plugins? Just don't 1 SQLite db per plugin. if you're working with MYSQL each plugin should independenly open a connection to the server. If you're working with shared data allow API access for other plugins to use that is abstracted away from your database calls
How should I make this situation?
a bunch of custom items with custom events like:
@EventHandler
public void onDamage(CustomItemEquippedEntityDamageEvent event) {
if (!event.getReferenceNames().contains("noonie")) {
return;
}
event.getEntityDamageEvent().setDamage(0);
}
Now let's say I have one special item that has the ability to "disable all other abilities", this would make refactoring a pain, but is there really a good way to do this?
I said I was used to a completely different approach, which is why I am seeking advice here. I am not obsessed. I just don't understand how it is supposed to work.
when it comes to plugins isolate everything to do with that plugin to itself. Unless you're depending on some library like ProtocolLib you shouldn't really have that plugins data or methods leaking anywhere else, unless ofcourse its intended to be API
So I understand it like this; I create an API that has all the methods I need (e.x getPlayerData()), which I use as a dependency in another plugin. In this other plugin I open a connection and perform the operations that the api provides me?
how can i make a location centered?
like 0.5, 100, 0.5?
well
X.5, Y.5, Z.5
no matter what
like if its x = 4, pass it4.5
x = 4.7, pass it 4.5
but if its x = 6, pass it to 6.5
maybe that is what you are searching for?
thankss
๐งป
public Location toCenterLocation() {
Location centerLoc = this.clone();
centerLoc.setX((double)this.getBlockX() + 0.5);
centerLoc.setY((double)this.getBlockY() + 0.5);
centerLoc.setZ((double)this.getBlockZ() + 0.5);
return centerLoc;
}
thats the code behind it
k thanks
np
are step sounds server-side?
or does the client calculate step sounds for other entities
it seems insane to me that the server calculates step sounds wouldnt this be far too resource intensive
which # of build is BungeeCord 1.8.8?
the latest build
um there is probably lots wrong with this but any suggestions?
https://pastes.dev/dgCiempdOq
decided to use a stream cuz why not its async not a huge deal
if i need too i can just do a normal loop
also just noticed this whole thing can be async so let me fix that rq
Is there any reason you're scheduling another task inside of the repeating one?
Nothing seems immediately obvious
^
i was originally just setting the block but i dont need to do that
I mean to be fair, the whole thing could be synchronous. There's no explicit reason for it to be async imo
and you cant do that async
ig
i feel better with it async
but i get it
should i use a stream though?
or just a normal loop
i dont believe these's a huge difference to performance
Streams are usually imperformant in hot code, but your stuff is running once every 6 seconds so you're probably not going to notice any difference whatsoever
If you care about performance then use the traditional for loop, but streams can also make your code look pleasant
how can i fix this, ik it says skript but it is not a skript error, its just because it is using the effect with skript [14:44:25 WARN]: [Skript] Task #4278 for Skript v2.7.3 generated an exception java.lang.NoSuchMethodError: 'net.minecraft.server.level.WorldServer net.minecraft.server.level.EntityPlayer.z()' at ca.nagasonic.skonic.elements.skins.EffFakeSkin.execute(EffFakeSkin.java:39) ~[Skonic-1.0.4.jar:?] at ch.njol.skript.lang.Effect.run(Effect.java:50) ~[Skript (3).jar:?] at ch.njol.skript.lang.TriggerItem.walk(TriggerItem.java:62) ~[Skript (3).jar:?] at ch.njol.skript.lang.TriggerItem.walk(TriggerItem.java:90) ~[Skript (3).jar:?] at ch.njol.skript.command.Commands.handleEffectCommand(Commands.java:200) ~[Skript (3).jar:?] at ch.njol.skript.command.Commands$2.lambda$onPlayerChat$0(Commands.java:299) ~[Skript (3).jar:?] at org.bukkit.craftbukkit.v1_20_R2.scheduler.CraftFuture.run(CraftFuture.java:88) ~[paper-1.20.2.jar:git-Paper-309] at org.bukkit.craftbukkit.v1_20_R2.scheduler.CraftScheduler.mainThreadHeartbeat(CraftScheduler.java:480) ~[paper-1.20.2.jar:git-Paper-309] at net.minecraft.server.MinecraftServer.tickChildren(MinecraftServer.java:1470) ~[paper-1.20.2.jar:git-Paper-309] at net.minecraft.server.dedicated.DedicatedServer.tickChildren(DedicatedServer.java:446) ~[paper-1.20.2.jar:git-Paper-309] at net.minecraft.server.MinecraftServer.tickServer(MinecraftServer.java:1379) ~[paper-1.20.2.jar:git-Paper-309] at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1156) ~[paper-1.20.2.jar:git-Paper-309] at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:315) ~[paper-1.20.2.jar:git-Paper-309] at java.lang.Thread.run(Thread.java:1583) ~[?:?]
#help-server and probably update skript
didnt work
Make sure you are remapping for the right version
like what version, same as plugin or server?
remap to server ver
ServerPlayer needs client options now
what are they?
it's for my custom npcs
should ClientInformation.createDefault() be sufficient?
Probably
Itโs just info about client settings
Obviously NPCs donโt have clients
who says huh
npcs can have options if they want
what happened to ClientboundAddPlayerPacket
I replaced it with ClientboundAddEntityPacket but now it doesn't work
It should
actually i think its this line
sendPacket(sp, new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, entity));
java.lang.NullPointerException: Cannot invoke "net.minecraft.server.network.PlayerConnection.l()" because "player.c" is null
Fake players have a null connection
how would i fix it?
i have no clue where to even start with that
this is what I used to get started with NPC's https://www.spigotmc.org/threads/nms-serverplayer-entityplayer-for-the-1-17-1-18-mojang-mappings-with-fall-damage-and-knockback.551281/
CraftPlayer craftPlayer = (CraftPlayer) player;
ServerPlayer sp = craftPlayer.getHandle();
GameProfile profile = getEntity().getGameProfile();
profile.getProperties().remove("textures", profile.getProperties().get("textures").stream().findFirst().orElse(null));
profile.getProperties().put("textures", new Property("textures",
skin.texture(),
skin.signature()));
// Add info
sendPacket(sp, new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, entity));
// Spawn entity
sendPacket(sp, new ClientboundAddEntityPacket(entity));
// Add data (second skin layer)
sendPacket(sp, new ClientboundSetEntityDataPacket(entity.getId(), entity.getEntityData().getNonDefaultValues()));
float yaw = getOptions().getLocation().getYaw();
float pitch = getOptions().getLocation().getPitch();
// Move head yaw
sendPacket(sp, new ClientboundRotateHeadPacket(entity, (byte) ((yaw % 360) * 256 / 360)));
// Move body yaw and head pitch
sendPacket(sp, new ClientboundMoveEntityPacket.Rot(entity.getBukkitEntity().getEntityId(), (byte) ((yaw % 360) * 256 / 360), (byte) ((pitch % 360) * 256 / 360), true));```
that's my current code
I changed add player packet to add entity packet
but this is the issue
it worked fine in 1.20.1
error is on the line with ClientboundPlayerInfoUpdatePacket
My solution was
- create playerconnection
- send packets (add player, update list)
- spawn player to world
if you spawn the player first then send packets in 1.20.2, it will cause some error
how would this look like on mine? the player connection part is what i'm stuck on
not sure how to create one
if you are trying to spawn a actual player, just set player.connection = new fake player connection
its for fake players
like npcs
don't know where to get the connection from
can you give more codes?
is it safe to just set the connection to the player it is displaying it to's connection?
is there any unwanted effects from that?
that'd mean the npcs share the same connection as the player
it works
they need a connection to be spawned now
i have no clue where to get one from
java.lang.NullPointerException: Cannot invoke "net.minecraft.server.network.PlayerConnection.l()" because "player.c" is null
without one this happens
they don;t they needs a network manager to consume packets is all
how do i create one
in 1.19 this was teh constructor```java
public class Npc extends ServerPlayer {
Npc(MinecraftServer minecraftServer, ServerLevel worldServer, GameProfile gameProfile, ProfilePublicKey publicKey) {
super(minecraftServer, worldServer, gameProfile, publicKey);
this.connection = new NetworkHandler(minecraftServer, new NetworkManager(PacketFlow.CLIENTBOUND), this);
}```
public class Npc extends ServerPlayer {
yes
what are they
public class NetworkHandler extends ServerGamePacketListenerImpl {
public NetworkHandler(MinecraftServer minecraftserver, Connection networkmanager, ServerPlayer entityplayer) {
super(minecraftserver, networkmanager, entityplayer);
}
@Override
public void send(Packet<?> packet) {
// Empty as we never want to try an send packets to a fake player.
}
}```
public class NetworkManager extends Connection {
public NetworkManager(PacketFlow enumprotocoldirection) {
super(enumprotocoldirection);
}
}```
needs a CommonListenerCookie
public NetworkHandler(MinecraftServer minecraftserver, Connection networkmanager, ServerPlayer entityplayer) {
super(minecraftserver, networkmanager, entityplayer, CommonListenerCookie.createInitial(entityplayer.gameProfile));
}``` would that work?
that would be something new, so not in 1.19
i'll try
yo, have an NMS question if anyone is free, trying to make a rideable mob change its head direction etc, i've tried to look for another class where it takes it's passengers direction and just copy that but i cant find it, anyone have a good place to look or know the solution straight up for 1.20.1?
In your ridable mob you shoudl be able to simply set it's pitch a YHeadRot
only that?
java.lang.IllegalStateException: Trying to set listener for wrong side: connection is CLIENTBOUND, but listener is SERVERBOUND
would PacketFlow.SERVERBOUND break anything?
then your cookie is wrong
yes
this is to consume client bound packets so it doesn;t crash your server
this.setPos(location.getX(), location.getY(), location.getZ());
float yaw = Location.normalizeYaw(location.getYaw());
float pitch = Location.normalizePitch(location.getPitch());
this.setYRot(yaw);
this.setXRot(pitch);
this.yRotO = yaw;
this.xRotO = pitch;
this.setYHeadRot(yaw);```
thats what I do to sync NPC heads
ill try it out
are there any docs for CommonListenerCookie
no
it worked but is there a way to get it to work on all versions?
maven multi module
or gradle
is yoru head movement inverted?
public void g(Vec3D vec3d) {
if (this.isAlive()) {
if (this.getPassenger() != null) {
if (this.isOnGround() && passengerJumping()) {
this.jump();
this.playSound(SoundEffects.qh, 1, 5);
}
EntityLiving passenger = this.getPassenger();
float yawRot = passenger.getYRot();
this.setYRot(yawRot);
float pitchRot = passenger.getXRot();
this.setXRot(pitchRot * 0.5F);
this.setYawPitch(this.getYRot(), this.getXRot());
this.aX = this.getYRot();
this.aZ = this.aX;
float f = passenger.bo * 0.5F;
float f1 = passenger.bq;
if (f1 <= 0.0F) {
f1 *= 0.25F;
}
if (this.z && this.fK() && !this.cw) {
f = 0.0F;
f1 = 0.0F;
}
this.bb = this.ew() * 0.1F;
this.r((float)this.b((AttributeBase) GenericAttributes.d));
super.g(new Vec3D((double)f, vec3d.c, (double)f1));
this.a(this, false);
this.as();
} else {
this.bb = 0.02F;
super.g(vec3d);
}
}
}
this is what i have from ages ago but yeah i dont think it will be easy upgrading
nah its like
if i press W it always goes north
S it always walks slowly backwards
no matter where its turning
are you listening to the steer packet?
@Override
public void move(MoverType enummovetype, Vec3 vec3d){
if(this.isAlive()){
if(this.getPassenger() != null){
if (this.onGround() && passengerJumping()) {
this.getJumpControl().jump();
this.playSound(SoundEvents.SHEEP_AMBIENT, 1F, 5F);
}
LivingEntity passenger = this.getPassenger();
float yaw = Location.normalizeYaw(passenger.getYHeadRot());
float pitch = Location.normalizePitch(passenger.xRotO);
this.setYRot(yaw);
this.setXRot(pitch);
this.yRotO = yaw;
this.xRotO = pitch;
this.setYHeadRot(yaw);
float f = passenger.xxa * 0.5F;
float f1 = passenger.zza;
if (f1 <= 0.0F) {
f1 *= 0.25F;
}
// if (this.onGround() && this.fK() && !this.cw) {
// f = 0.0F;
// f1 = 0.0F;
// }
// this.bb = this.ew() * 0.1F;
super.move(MoverType.SELF, new Vec3((double)f, 0.0, (double)f1));
// this.a(this, false);
// this.as();
}else{
super.move(enummovetype, vec3d);
}
}
}
this is my code now but im kinda just taking a shot in the dark guessing waht was what
what the hell is that, and how do i use it
Hi there! Today Iโm going to explain how to setup a multi-module project using maven to support different NMS versions. Important notes about this tutorial: Every step will have detailled screenshots using IntelliJ. I explicitly chose not to include everything as copy/pastable source code, but normal screenshots (you can click on them to show th...
com.mojang.authlib.GameProfile gameProfile,
int i,
net.minecraft.server.level.ClientInformation clientInformation
do you know what i is?
need more context
no clue I've not done anything with 1.20
whats the package for teh cookie listener?
public static CommonListenerCookie createInitial(GameProfile var0) {
return new CommonListenerCookie(var0, 0, ClientInformation.createDefault());
}
use this static method
net.minecraft.server.network
Trying to set listener for wrong side: connection is CLIENTBOUND, but listener is SERVERBOUND
zoo gave you what you need
have you tried 1 instead of zero?
that's just latency
only guessing here
i found what it is
ok
and createInitial only needs gameprofile
Can;t help, not used 1.20
change PacketFlow.CLIENTBOUND to PacketFlow.SERVERBOUND?
nope
apparently that would break it
he's creating a fake player so needs to consume clientbound
what is the method of spawning the fake player
CraftPlayer craftPlayer = (CraftPlayer) player;
ServerPlayer sp = craftPlayer.getHandle();
GameProfile profile = getEntity().getGameProfile();
profile.getProperties().remove("textures", profile.getProperties().get("textures").stream().findFirst().orElse(null));
profile.getProperties().put("textures", new Property("textures",
skin.texture(),
skin.signature()));
entity.connection = new NetworkHandler(sp.getServer(), new NetworkManager(PacketFlow.CLIENTBOUND), entity);
// Add info
sendPacket(sp, new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, entity));
// Spawn entity
sendPacket(sp, new ClientboundAddEntityPacket(entity));
// Add data (second skin layer)
sendPacket(sp, new ClientboundSetEntityDataPacket(entity.getId(), entity.getEntityData().getNonDefaultValues()));
float yaw = getOptions().getLocation().getYaw();
float pitch = getOptions().getLocation().getPitch();
// Move head yaw
sendPacket(sp, new ClientboundRotateHeadPacket(entity, (byte) ((yaw % 360) * 256 / 360)));
// Move body yaw and head pitch
sendPacket(sp, new ClientboundMoveEntityPacket.Rot(entity.getBukkitEntity().getEntityId(), (byte) ((yaw % 360) * 256 / 360), (byte) ((pitch % 360) * 256 / 360), true));```
sp is the player it's showing it to (ServerPlayer)
When I change glowing to false the enchantments disappear, is it possible to make the enchantments not disappear?
try PlaceNewPlayer instead of using ClientboundAddEntityPacket
that packet is wrong i guess
using native method in nms is safer
what method is that
where is it from
also the error is from the NetworkManager line and stuff
setting connection
net.minecraft.server.players.PlayerList
sp.server.getPlayerList().placeNewPlayer();
it still gets the error
public void setListener(PacketListener packetlistener) {
Validate.notNull(packetlistener, "packetListener", new Object[0]);
PacketFlow enumprotocoldirection = packetlistener.flow();
if (enumprotocoldirection != this.receiving) {
throw new IllegalStateException("Trying to set listener for wrong side: connection is " + this.receiving + ", but listener is " + enumprotocoldirection);
}
...
add this line to your extended Connection.class
@Override
public void setListener(PacketListener packetListener) {}
is spigot 1.20.4 now R4 or R3?
R3
k
i can't import the 1.18.2 dependency <dependency> <groupId>org.spigotmc</groupId> <artifactId>spigot</artifactId> <version>1.18.2-R0.1-SNAPSHOT</version> <scope>provided</scope> </dependency>
have you ran builtools
thats only available if you ran buildtools
that creates a real player
that is included in bukkit.getonlineplayers()
it breaks a few of my things
they should only be client-sided
how about this ServerLevel.addNewPlayer(ServerPlayer entityplayer)
nah it's fine i figured it out using the old packet
this worked perfectly too thanks
is there a java internal Pair<A,B> ?
im trying to find a way to parse two generics in one method signature
should i just ask for a list?
Pair is literally
class Pair<K, V> {
K key
V value
constructor(K, V)
getters...
}
eh fair
different question, is it possible without the use of generics to say to two values in the constructor 'you two are the same', e.g. method(Object<? extends A>, Object<? extends A>)
I know its possible with generics and just defining T or smth in the class signature, but using them here would mess up other parts of my code
i can just check after the method call, but i was wondering if there's a higher-level approach
You could define a generic in the constructor really that's it afaik without the usage of wrappers
<T> YourClassCtor(T a, T b)
@smoky oak
noted, thanks
1.20.2?
what do you need the entity data for
its solved
How do you unban players after the ban changes
I can only find unbanIP
I've got an offlineplayer
I dont know if this questions is the right for this channel, but I wanted to ask if it is possible to update the resource icon on spigotmc's website
since I don't see any edit buttons for that
Yea it gives me a list of offlineplayers
So I dunno what I'm meant to do with that
All the old banlist and banentry thingies are giving me errors and deprecated
you need to grab the profile from offlineplayer and unban it over the profile banlist iirc
are you trying to unban a player?
if so probably OfflinePlayer#ban(null, Date.now(), null)
or Instant.now()
BanList#pardon(T) exists
that works too ๐
btw
whats the better way to keep a single instance of a list
static or singletron holder object
open to better solutions on this one
well neither are singletrons
Gonna try this, I can't figureout banlist#pardon
a singleton shoudl be, it's just an object
Bro what
ye but somewhere ill have a static object
It's got error, and same without .getPlayerProfile
intellij wants me to wrap it with string.valueof and then it becomes deprecated
What are you depending on
Cast the banlist to profilebanlist
All fixed thank u
will it be critical to store state in a static class if the class is not used in โserious codeโ
in bukkit api?
i was use cooldown static class
The idea behind static is that it is supposed to be stateless
oh ok
How do i check if a Class<?> object is of an abstract class?
im doing recursion upwards to find the first abstract superclass
Modifier.isAbstract(clazz.getModifiers())
yh thats what i was going for
mb forgot the last part
sanity check: if i put the same object into multiple lists, it still is just one object with multiple references, correct?
usually yes
wdym usually lol
can u be a bit more specific on those cases?
or is it some weird edge case where you need to deliberately do it
things like a CopyOnWriteArrayList
so if its deliberate in some way, then. ill not worry bout that
yep
wont impact functionality either way, just memory footprint lol
@eternal oxide this look fine to u? believe u gave me the idea with the map
Class<?> clazz = eventClass;
do{
consumerMap.computeIfAbsent(eventClass, k -> new ArrayList<>()).add(listener);
clazz = clazz.getSuperclass();
} while(!Modifier.isAbstract(clazz.getModifiers()));
i dont think i should do this when the event parsing happens cuz its probably leagues slower than just 'give me the list of this event'
looks fine
yea, im trying to figure out how to do this without exceptions and without declaring the class
since this code only runs once thats not an issue but idk if this looks right
public void addConsumer(Consumer<? extends Event> consumer){
try{
Class<?> clazz = (Class<?>) ((ParameterizedType) consumer.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
//call register method
} catch (ArrayIndexOutOfBoundsException | ClassCastException ignored){}
}
This will just copy the backing array, which just contains object references, and not copies of the object
beware that generics are erased and the signatures may or may not be present for the type
I wondered as it does say it copies data but didn;t state if it was a reference
The idea behind copyonwrite is that if you do a write, it creates a copy of the list so all iterators n stuff working on the old list wont throw exceptions
Which is nice for when you have concurrent reads an not a lot of writes because you avoid a lot of synchronization overhead
uh, can someone explain ? vs T? I can call signatures with <T extends Event> ... (Consumer<T>) and (Consumer<? extends Event>) with the same consumer, but it's saying i cannot call one from the other because its ? capture of vs T
also wouldnt this still brick if you copy it while something else is iterating it?
Bing is funny.
Hello, this is Bing. I can try to explain the difference between ? and T in Java generics. ๐
? is a wildcard that represents an unknown type. It is used when we don't care about the exact type of a generic parameter, or when we want to specify a range of possible types using upper or lower boundsยน. For example, List<? extends Number> means a list of some subtype of Number, such as Integer or Double.
T is a type parameter that represents a specific type. It is used when we want to declare a generic class, interface, or method that can work with different typesยน. For example, public interface Comparable<T> means that any class that implements Comparable can compare itself with another object of the same type T.
The reason why you cannot call one from the other is because of the capture conversionยฒ. When you use a wildcard, the compiler creates a fresh type variable (called capture of ?) that is a subtype of the upper bound of the wildcard. This type variable is unique and distinct from any other type variable, even if they have the same upper bound. Therefore, Consumer<? extends Event> and Consumer<T extends Event> are not compatible, because they have different type parameters.
I hope this helps you understand the difference between ? and T in Java generics. If you have any more questions, feel free to ask me. ๐
Source: Conversation with Bing, 12/12/2023
(1) What is the difference between 'E', 'T', and '?' for Java generics?. https://stackoverflow.com/questions/6008241/what-is-the-difference-between-e-t-and-for-java-generics.
(2) Type Parameter vs Wildcard in Java Generics | Baeldung. https://www.baeldung.com/java-generics-type-parameter-vs-wildcard.
(3) java - how to use "tab space" while writing in text file - Stack Overflow. https://stackoverflow.com/questions/2585337/how-to-use-tab-space-while-writing-in-text-file.
I come across Java code like this:
public interface Foo<E> {}
public interface Bar<T> {}
public interface Zar<?> {}
What is the difference among all three of the above and wha...
A detailed explanation about generics, how and when to use type parameters, and when wildcards are more appropiate.
? is a wildcard, T is a type.
? extends MyClass means some type (dunno which one), but at least we know it is a subclass of MyClass
? super MyClass means some type (dunno which one), but at least we know that it accepts MyClass instances
no, the copy just creates a new array and copies all of the old array's content to the new array, which means the old array is only read from. Iterators and stuff keep a reference to the old (unmodified) array and thus can work just fine. Since they keep a reference the garbage collector won't clean it up either until all references are gc'd.
I guess i should use T here. Though now it's saying 'unchecked cast' and 'heap pollution'
I mean Type -> Class is sketch, but whats heap pollution?
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
relevant code```
public <T extends Event> void addConsumersUnsafe(Consumer<T>... consumers){
Class<T> clazz = (Class<T>) ((ParameterizedType) c.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
addConsumer(clazz, c);
Consumer<? extends T> doesnt make sense
And will pretty much never do
^ tru
im not doing THAT anywhere
i do either <? extends event> or <T extends Event> ... (<T>)
unchecked cast basically means the compiler cannot be sure that that cast is safe, but in most cases if the programmer knows what they're doing it will still be safe (albeit not statically checkable)
^ that due to type erasure meaning generic types are not fully preserved during runtime
bleh
should i just not bother with a collective register method
heap pollution is that because generics are not preserved at runtime, casting to a different generic type can allow you to 'pollute' the heap by introducing new objects of the incorrect type, e.g.
List<Integer> myIntList = new ArrayList<>();
List<String> myStringList = (List<String>) myIntList;
myStringList.add("Hello, world!"); // this works fine
Integer myInt = myIntList.get(0); // only now will an error be thrown
if required, one can get a typesafe collection by using Collections#checkedXYZ(..., Class)
wouldnt the (List<String>) make a copy? This looks like the reference is retained
no it's just a cast
howd the int turn into a string then
generics are syntax sugar
Basically if u have the class hierarchy
Car extends Vehicle
Vehicle extends Object
<T extends Vehicle> func1(Supplier<? extends Vehicle> supplier) {
//
}
<T extends Vehicle> func2(Consumer<? super T> consumer) {
//
}
in func1 you can pass a Supplier<Car>, Supplier<Vehicle>, Supplier<? extends Car> and Supplier<? extends Vehicle>, what you canโt so is a Supplier<Object> because func1 might actually take the result of the supplier and consume something that has to be at least of type Vehicle
in func2 you can pass a Consumer<Vehicle>, Consumer<Object>, Consumer<? super Vehicle>, and Consumer<? super Object>, what you cant do here is to pass a Consumer<Car> because we might pass consumable object that is of type Vehicle but not of type Car, thus the consumer canโt consume anything that assumes Vehicle.
Producer (Supplier) extends, Consumer supers, PECS
List<Integer> myIntList = new ArrayList<>();
Integer i = myIntList.get(0);
is actually just
List myIntList = new ArrayList(); // typeless
Integer i = (Integer) myIntList.get(0); // here the cast happens
so yes you can put anything in the list
if you have something that produces and consumes we call it novariant or sometimes invariant (at times bivariant>
Often Map, List and other collections become invariant meaning you donโt use ?extends and ?super on them
Since you both produce on the map and consume the map
For instance
i think i at least partially understand this. I'll just keep that pasted somewhere as a memo. What about Consumer<T>? Is it equivalent to Consumer<? extends T>?
Also, what'S the 'Possible heap pollution from parameterized vararg type' here referring to? the fact that the different consumers may have different input types?
- No
- thatโs with varargs
well yea, i thought i was being smart, im clearly not
need to know both of those though
Basically
method(X<Y>โฆ)
compiles down to
method(X<Y>[])
then
merhod(X[])
Thatโs what it basically warns you about
Because its fully possible to mess it up with type erasure and cause โheap pollutionโ
Secondly about the first question
as function parameters we usually want Supplier<?extends O> or Consumer<?super O> since that allows for a range of type constructed producers and consumers
Consumer<O> is if u wanna specify that its only a Consumer<O> and canโt be assumed as a Consumer<I>
if O extends I
for supplier it would be I extends O
Wasnt the code ive sent you 2 days ago what you wanted?
Aye, but I meant specifically that value
Iโm not predicting velocity
I just want to know for the tick where your velocity was set to 0,1,0, do you move one block in one tick?
I assume yes based on the things you sent
It sends like t = ticks
Minecraft has drag and gravity. Its hard to predict how far your entity will be moved.
Best thing you can do is set the velocity and print out its delta.
yea im working on that right now. I am trying to make it more generalized (hence me trying to remove the Class<T> c part if you can get it from the consumer)
theres some reformatting required
Are you saying that within the time of one tick those things are calculated?
Like itโs not once every tick, but over the course of a tick, drag is also incorporated? Client-side, I guess?
(for example event inheritance: If i just naively register it a EntityDamageByEntityEvent wont run the handlers for the EntityDamageEvent)
Thatโs good
im pretty sure if i hit a zombie the entityDamageEvent fires
well spares me from calling the event handler for every single event
i can just redirect the 8 super events
Well youโd want to be specific in event handling
You cant. At runtime there is no way to get a generic type argument. It gets compiled down to Consumer<Object>
In a good and well designed event system, there is a supported generic event
Like
GenericEntityEvent
EntityEatEvent
EntityFartEvent
etc
You need type inference
ah so i need to do that ? extends T thing?
you just need type awareness I think smile was hinting at
Class<T> clazz = (Class<T>) ((ParameterizedType) c.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0] this always Object then?
This only makes sense if you have something like
public class PlayerConsumer implements Consumer<Player> {
...
}
It would then spit out Player.class
cuz it forces it through the type in the class. doing that would be more or less walking backwards, no reflection consumer registration then
bleh deleting code in this case doesnt feel good lol
public class SomeEventHandler {
private final Map<Class<? extends Event>, List<Consumer<? extends Event>>> listeners = new HashMap<>();
public <T extends Event> void registerListener(Class<T> eventClass, Consumer<T> listener) {
listeners.computeIfAbsent(eventClass, k -> new ArrayList<>()).add(listener);
}
@SuppressWarnings("unchecked")
public <T extends Event> void handleEvent(T event) {
List<Consumer<? extends Event>> eventListeners = listeners.get(event.getClass());
if (eventListeners != null) {
eventListeners.forEach(listener -> ((Consumer<T>) listener).accept(event));
}
}
}
What about this example bothered you? ๐
oh nothing, its the stuff around it thats annoing me
I kinda know how it works, but I don't know how to use it properly
also im trying to understand it, not just copy-paste it
Like, I always just wrap shit instead of using consumers
It will come to you eventually. Java is inherently object oriented and functional interfaces introduce a functional programming
style. So it can be a bit hard to get into.
Yeah, I am really OOP based
@lost matrix btw. your code for the displayentities works out great, my custom guns are already pretty far and cool
I just need it to somehow feel more like a bullet when shot lol
Also, I need a brutal fire sound that hits different
low pitch on end crystal explosion sound?
And gotta finish my custom hitbox intersection algorithm, I guess. Well, it's more likely that the issue is the rotation of the hitbox itself
Yeah about that lmao
Well, I finished the algorithms and shit but my system is buggy as fuck
@SuppressWarnings("unchecked") โน๏ธ
Not quiet
Its implicitly checked ๐
btw are all events a subclass of Event? knowing java, theres a chance theres some for which that aint the casae
I believe so
Has nothing really to do with Java and more with who are writing it and what they are doing
i have recently seen something like that though i cannot remember where
ah
factorio character prototypes
someone didnt set the 'all characters' flag correctly in a mod
thats what i was salty about
The plugin manager won't allow you to pass anything that isn't an Event
with 1.20.4 I heard it is now possible to remove the red numbers on the scoreboard, but I cannot figure out how that is possible with the API, is not possible with API yet?
I know before it actually was a limitation of the game itself, but now it is theoretically possible. Is that true?
It has been possible for a while now with resourcepacks
Yes I know that, But it is not possible without them. And I would like to know how
I don't think the API has been updated with that feature yet
You can always make a PR adding it yourself
I would, but I heard there might be new scoreboard stuff coming. Something with components and stuff. I think I saw choco saying it was being worked on. If I made a pr to the current system would it not get instantly deprecated?
๐คทโโ๏ธ I don't keep track of the active PRs
ok
would rather avoid it as much as possible
Thanks though for the help
why cant we pass primitive types as generics?
hmmm
You need to use their respective wrapper objects.
Primitives in java are handled differently than Objects.
The problem is that generics are purely compile-time reliant.
Basically in runtime it's all an Object which is then magically casted
Which results in fun cast exceptions if you're doing serialization and stuff
ok ty
Does that mean in some way java is all just reflection that magically retrieves methods and calls them?
nvm (i think)
UUID.fromString
hmm
It's not reflection
what you're referring to is just bytecode
Well, I mean
I dont think it exists
learnjava moment
"uuid" is a string
I meant staticify

UUID -> Class
uuid -> Variable
ok I staticified it
you mean Refactored the method call to invoke the static method present in the UUID class rather than the local method present in the String class
bru why does player.getUniqueID() exist but uuid.getPlayer() doesnt

because a player has a uuid, a uuid does not have a player
UUID is also a java class
