NPC update or thread

Hi,



I’m very new here. I have a little bit experiencie on making games but I have some technical questions about threads, appstates on other stuff to make a independent npc class.



I’ve been reading about Multithreading, Application States and Custom Controls, and now I don’t know how to face the code XD.



My idea to start is create a Game Class (extends SimpleApplication) and a NPC class with all information about the npc, model, collision, behavior, pathfinding, etc but I don’t know if it is possible.



The question are:



If the npc has a method to pathfind that is called through its update method, the simpleUpdate on the Game class can be frezeed? I should deal with it using multithread to avoid it?



I think yes but reading about multithreading I’ve seen that you need an executor placed on Game Class or main class:

[java]ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4);[/java]



But this object will be called on a function of (I think that should be on) npc class. I must send the executor object to npc class?

[java]public void update(float tpf) {

try{

//If we have no waylist and not started a callable yet, do so!

if(wayList == null && future == null){

//set the desired location vector, after that we should not modify it anymore

//because its being accessed on the other thread!

desiredLocation.set(getGoodNextLocation());

//start the callable on the executor

future = executor.submit(findWay); // Thread starts!

}

//If we have started a callable already, we check the status

else if(future != null){

//Get the waylist when its done

if(future.isDone()){

wayList = future.get();

future = null;

}

else if(future.isCancelled()){

//Set future to null. Maybe we succeed next time…

future = null;

}

}

}

catch(Exception e){

Exceptions.printStackTrace(e);

}

if(wayList != null){

//… Success! Let’s process the wayList and move the NPC…

}

}[/java]



Well, I’m very confused now, I’ve been reading about custom controls to manage the animations of a character and I don’t know the best way to make a independent npc that can be called at any moment.



Maybe someone can help this noob. I’m only asking for some orientation.

If the npc has a method to pathfind that is called through its update method, the simpleUpdate on the Game class can be frezeed?

yes, if you have an excess pathfinding algorithm which can halt the render (update) thread then you will get freezes. If you require something which requires many CPU cycles to complete then put it in another thread and enqueue the changes back.

I must send the executor object to npc class?

yes create the executor in your SimpleApplication class or similar and pass that instance to the other classes
1 Like

Oh man you are great.



One thing more please… I’ve read that you need initialize “ScheduledThreadPoolExecutor” with the number of threads you are thinking use and a good practice is use the double of cores of CPU. I’m thinking make a mobile game with 4-8 npcs, maybe I can set it to 2. All npc calling their pathfinding method is unlikely. Maybe the mobile explodes on the user hand?

A lot also depends on the nature of the pathfinding, etc. Certain types of pathfinding are very cheap - but others are very expensive.



Try to split everything you need to do into separate components. If each of those is too big then try to split it up again. Eventually you can break everything down to “bite sized” pieces that you can take on one at a time.



When you design the pieces try and make each one generic. So for example if you find you have 3 or 4 different types of NPC you can share the bits of code they all need while having different code for the bits that aren’t the same.

1 Like

Oh, and if you aren’t sure how something should work try and throw a rough prototype together. Put a bunch of cubes on the screen and have them run around. Take what you learn from the prototype and come up with a new design, etc.



Just don’t be tempted to keep building on the rough prototype and try to turn it into the finished project. You will most likely be able to re-use bits and pieces but it should be seen as a learning exercise to work out the architecture to use when you go ahead properly.

1 Like

Thanks for answer.



My idea is use the A* with diagonal only 2D and define a board of movement. The board is 32*32 max, I think all will be fine but I want to be sure. In the future I will try a point interest system or something similar.



The idea is that the npc code is on the same class and all npcs share the same code. Maybe this is a bad idea?

That depends on how complex and varied your NPCs are.



For example you may find you want to do a tree, with object - living - (player|npc-(turret|ai|animal))



Where object is something that appears in the world, living is a special instance of a combat-able object, then players are a type of living - as is npc…then you might have sub-types of NPC.



I hope that makes sense… just don’t think that’s what you have to do, it’s just one example of a possible hierarchy which would need to be tuned to the game you are making.

1 Like

I see your point. Create a hierarchy of classes and write the common code in parent, but Is a good idea separate the npc behavior then? My idea is write the code for separate the npc logic of the game logic, a hierarchy is good for me, creating an abstract class to the top parent and various types of npcs as children.



What do you prefer? Interface, abstract class or normal class for the top parent? I’m not very friendly of interfaces XD.

It’s too situational to give you an answer really, it very much depends on what you are doing.



Probably I’d use an abstract class - but that’s not set in stone and other people may well approach it a different way.





You should also read up on entity systems as they have a lot of potential to simplify problems. They are most likely overkill for a simple application though and just writing an entity system would be a stretch for some people so it really depends on how experienced a coder you are.

1 Like

If you are not sure what to use, an interface, abstract or normal class, you should read a bit about Interface and Abstract classes, there are tons of materials on the internet. It can help you design good code.

1 Like

I didn’t know what the entity systems are. I’ve been reading a litle about it. I have found this example and it’s very attractive. Maybe I will try this method and learn something new by the way. It is perfect for a small game where ncps can have different behaviors (AI, cinematic mode, player controlled).



Thank so much zarch.

Oh well, you are right shirkit, I said nonsense, interfaces are useless for this. I can’t imagine practical uses for interfaces. It seems an organizative way to work in group. I’m very profane, forgive me if i’m saying nonsense.

I’m not familiar with that site but a quick skim through showed he was talking about the same thing I was so it seems a fair place to start. There has been some discussions and links on these forums too if you do some searches.



Interfaces are useful when you need one thing that can do multiple things (although that can be a sign of poor object design as objects shouldn’t need to do multiple things)…for defining listeners…and also for defining a common interface with multiple implementations. (collections.List for example).

The linked example wasn’t a true entity system by many definitions. In a true entity system, components are only data… so the update() method is not right. That entity/component system more closely resembles the Spatial/Control model that JME uses for functional composition.



For the real entity system stuff, start here:

Entity Systems are the future of MMOG development – Part 1 – T-machine.org



And read all of the parts and many of the comments. There is even a space invaders example as I recall. Then branch out from there.



If you are truly interested in the idea then it can take a while to wrap your head around it but in the long run it’s worth it.

Just my two cent,

After a while try and learn such Entity System which mentioned in T-Machine blog, i think what he said should be expressed more clearly like this :" MMORPG needs a better solution to handle various type and combinations of objects" not every RPG need such system and the Space invader example just show technically the system work, not show how much efficient it gain.



I think the there is no best and nearly best sollution to handle logic and data in a game (RPG game) for the good of creation and maintaining. Because small<> large game need different approach. @harton As you want to try the entity system, please also take time to dig deeper in OOP and i’m also very attracted to the T-Machine post, I can not agree with him 100%. OOP has a lot of better sollution then such a System which we make data just plain data like an Entity System.



Now, as we start as a small group or a independent developer, how can we possible make such a complicated and a wide range of entities to some how fall in to the problem mentioned in the article.



OOP has problems with Inheritance and classify but It more flexible to take care of just some problems rising. And Entity System has a lot of problem if you have to work with a lot of type of assets.



If you have worked with Unity, you can see they have such Component system but it still in the middle of the solution, Half OOP - half Component. I think because in the end, data can not just be data, because the nature of everything has logic in it. You can decompose a “thing” into smaller “things” to some-how “divide to handle” but it soon reach the limit and you and your team may find it too difficult to do such “divide” which in the theory should be easy.



So in the end the problem of classify and divide are the same.



Just my thought!

I don’t know. Once I fully understood entity systems, I don’t think I’d write any game any other way. It’s the massive decoupling that’s attractive. When components are more than just data then that decoupling is completely broken. It’s not longer a real entity system and is instead just a composition framework. (which are cool and powerful on their own but are definitely OOP and are definitely an entirely different thing)



I’m tempted to guess that you don’t fully understand entity systems yet. That will probably get me in trouble but it’s just a guess… but since none of your ES down sides actually apply to entity systems… and you draw a correlation to something that is not an entity system… then that’s why I say that. The only two downsides that I can see is that an entity system is a complicated topic to get one’s head around and it can be tricky to make it performant in certain ways. The massive scalability and flexibility comes at a small cost in performance… though I’ve found that those costs can be mitigated with some clever internal coding.



One day I will have free time again and maybe I will post some phases of an asteroids example. Even in such a small example, the power of an entity system becomes clear when you go to add some new piece of functionality and can do it without touching 99% of the existing code.

As you currently do not seem to have a direct Idea on how you will create your ai, I give you the following to read as it is a kinda interesting approach

http://web.media.mit.edu/~jorkin/gdc2006_orkin_jeff_fear.pdf



Basically in code I guess you would have ony central evaluation calss then and all those npc specific stuff would be accesable via one generic interface.



→ Like efine somewher wich actiona exist at all

→ Let each npc define how the individual costs for each action are (including the npcs knowledge like door blocked)



About the amount of threads for the executro, I would use min1 max cpucount -1 , (also keep in mind that hyperthreading reports more cores but on full load does not scale perfectly, so (cpucount/2 -1 ) for intel then^^.

→ Why one core less? you don’t want to kil the render thread when doing much calcualtions

And the over-arching topic of which the FEAR paper is a subset: http://web.media.mit.edu/~jorkin/goap.html

Ok, thank you all for the info. I have to read the pdf and study more about entity systems, including the link from “t-machine”.



Empire Phoenix, are you saying that when I was creating the executor I should do?

[java]ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);[/java]

I think don’t undestand.



Reading about appstates I’ve seen that the BulletAppState class starts its own executor…

Line 70:

[java]private boolean startPhysicsOnExecutor() {

if (executor != null) {

executor.shutdown();

}

executor = new ScheduledThreadPoolExecutor(1);

[/java]

Is it a good practice? Starts an executor for every custom state class you have?

Well the bullet has to function independently of anything else that might be running in the system so it needs its own thread.



Most of my apps I create a static executor somewhere and just use that for scheduling everything. (I never send really long running stuff to that scheduler though, that’s a separate problem).