• We have updated our Community Code of Conduct. Please read through the new rules for the forum that are an integral part of Paradox Interactive’s User Agreement.

Stellaris Dev Diary #172 - Reworking the AI

Bonjour everyone, it’s the French Paradox speaking! For those who don’t know me, I’ve joined the Stellaris team this December after a year and a half as a programmer on Europa Universalis IV.

Today, we are gonna talk about AI.

pasted image 0.png

A good introduction for those new to the field

Fifty Shades of AI
There are several AI modules in Stellaris. For historical reasons we call them “ministers” as each one is supposed to handle a specific role in an AI empire.

There are 3 broad kinds:
  • The AI foreign minister handles diplomacy, federations, galactic community, peace deals and the like
  • The AI interior minister is in charge of the economy. He keeps budgets and order constructions, both civil and military.
  • The AI military minister is in command of all troops and military fleets, and also responsible for laying out strategic plans when at war.
For each of those ministries there are different “ministers” there are several options that can be selected for every empire in the game. All of those have generic one which behaves more or less like we’d expect a player to and is used for most AI empires. Then we have a bunch of specialized ones for special tags such as space monsters, fallen empires, crisis, marauders and the like.

As almost everything in our games, AI is configurable in script for our modders, although I’m not exactly sure what would happen if you assigned a space monster military AI to the caravaneers ;)

In guise of a welcoming gift when I joined the team, I was tasked with reworking the military one...

The Military AI
To give you a little bit of background, there were several generations of military AIs in Stellaris. The generic one (used by most “classic” empires) was redone by the great @sidestep last year, while the more specialized ones (crisis, space monsters) have kept close to what they were on release. In the midst of the sad and dark swedish winter, I managed to bring some improvements that I’ll showcase today.

First of all, I worked on visualization to help us debug how the AI “thinks”. Funny thing is, it already made it look “better” to audiences even if it didn’t actually change any behaviour. It’s actually something that’s been observed in video games: a good AI tells you what it does, which makes it look smarter. One of my favourite examples of that would be the enemies in FEAR.

So by typing 'debug_ai' in the console and observing an AI empire, you can see what it has in mind:

pasted image 0 (1).png

“I don't even see the code. All I see is blonde, brunette, redhead. Hey uh, you want a drink?”

As a simple analogy, imagine that the AI has a war minister that looks at the big picture and rates every potential target, a general staff who assign fleets to some of those objectives, and then admirals who try to lead those fleets on a tactical level to achieve those objectives.

The skulls on top of each system shows military objectives that the AI is considering (the war minister). Red ones are the ones they selected and committed some fleets to, while green ones are other options they haven’t retained for now. Finally for each individual fleet, in those task forces, you see what they are doing at present.

In our screenshot example, the AI decided that taking Tiralam was the most important objective with a score of 4500, and that they estimated that at least 11.2k fleet power was needed to accomplish this. They committed the Kilik Armada, the Jinki-Ki-Ti Armada and the the Grekki Armada to this. Since it makes little tactical sense to attack in a dispersed formation, the AI issued orders to regroup in Broon’s Singularity before proceeding on the attack (something we improved in this patch).

For convenience, the summary is also visible in the outliner:

pasted image 0 (2).png

As seen from the other side of that war

That change alone allowed us to see where the AI was a bit weak and also made evident a few bugs in the production AI that we promptly fixed. A funny one was that in some cases a fleet would end up assigned to two different fleet groups, nicely simulating two admirals fighting over command of a fleet and issuing contradictory orders every day.

Crisis AI
The next step was to rewrite the various crisis to use the generic AI, so that any effort spent on making better would benefit all. In patch 2.6 the specific AI of the Khan, the Prethoryn, the Unbidden and the Contingency will use the same AI as the “standard” empires, with a few twists to still retain their personality.

Without spoiling every secret, here’s a few ideas:
  • The Khan doesn’t really believe in defense and will try to beat the closest systems into submission
  • The Prethoryn will swarm in every direction they can
  • The Contingency will systematically try to stop the biggest threat to the galaxy, until nothing remains
  • The Unbidden will be harder to predict, but there’s reason behind their alien way of acting.
One of the biggest challenges we faced was assigning fleets to objectives. Matching X fleets with Y out of Z objectives is not an easy task. Do we try to accomplish as many objectives as we can at the risk of spreading too thin or accomplishing nothing of value? Should we instead focus on the most valuable target and possibly end up in a big fight that we could have avoided? How often should we reconsider our options?

The current version solves this by putting a fleet power value on every target, then grabbing fleets by order of priority until it either has enough to accomplish the objective, or go over the next one. This approach showed its limits when we plugged the crisis AI into it, as it relies a lot on the size of available fleets (it doesn’t know how to split them, it can only merge them).

Teaching the AI how to split fleets proved quite interesting:

pasted image 0 (3).png

What shall we do with this knowledge?

It took several tries to find a good balance, as the AI tended to split too much (most objectives don’t call for that much fleet power, unless you’re fighting your enemy main fleet). In the end, after trying some complex strategies such as keeping statistics on accomplished objectives and deriving a good target number from that, a simpler approach turned out more efficient: put all the nation’s offensive fleet power into one stack, and then consider splitting in 2,3 or more depending on how confident the AI feels about its military power versus its foes.

Knowing some of you like to mod our AI, here’s some new defines you may want to play with once all that hits the shelves.

Code:
# Objective values
HORDE_INVASION_PLANNING_DEPTH = 5    # How far out does the Horde AI looks for invasion targets (in system hops)
SWARM_INVASION_PLANNING_DEPTH = 5    # How far out does the Swarm AI looks for invasion targets (in system hops)
SWARM_POP_TARGET_MULT = 1.0            # Extra target scoring for swarm (multiplied by number of edible pop on the planet)
CONTINGENCY_MEGASTRUCTURE_EXTRA_VALUE = 4    # How attractive are megastructures to the Contingency (added to the base value of 1)
UNBIDDEN_PORTAL_EXTRA_VALUE = 20            # How much does the Unbidden want to defend their portal (compared to base value of 1)
UNBIDDEN_BYPASSES_EXTRA_VALUE = 4            # How attractive are bypasses to the Unbidden (added to the base value of 1)
UNBIDDEN_RIVALS_EXTRA_VALUE = 10            # Extra target scoring for rival invaders (Aberrant and Vehement)
UNBIDDEN_TARGET_EXTRA_VALUE = 10            # Extra target scoring for randomly chosen nemesis
UNBIDDEN_PSIONIC_CONQUER_DESIRE = 20        # Extra weight added to psionic empires when rolling a nemesis (base 1 + number of owned bypasses)
UNBIDDEN_CHOSEN_ONE_CONQUER_DESIRE = 50        # Extra weight added to empire lead by the chosen one when rolling a nemesis (base 1 + number of owned bypasses)

# Fleet sizing
OFFENSE_VS_DEFENSE_STRATEGY_ALLOTMENT = 0.75 # How much of its fleet power should a country with 1.0 aggressiveness should try to commit to offensive missions
AVERAGE_FLEET_SIZE_FACTOR    = 0.05            # Ballpark estimate of the minimum size a fleet should be in relation to total fleet power
OWN_FLEET_POWER_FACTOR = 1.0                # How much does AI count its own fleet power when evaluating forces
ALLY_FLEET_POWER_FACTOR = 0.5                # How much does AI count ally fleet power when evaluating forces
ENEMY_FLEET_POWER_FACTOR = 1.0                # How much does AI count enemy fleet power when evaluating forces
FLEET_SUPERIORITY_FACTOR = 1.5                # How stronger should the AI be before it starts considering splitting fleets (fleet count = relative strength / this factor)
CRISIS_FLEET_SUPERIORITY_FACTOR = 1.0        # Same as previous but will be compared to the strongest foe in the universe

Most of those changes will be delivered in the patch coming alongside the Federations release (2.6.0), but not all. As you may imagine, changes to the military AI are quite impactful and we don’t want to release the changes without enough testing, so some of them will be delivered in the first support patch (2.6.1).

And with that, I shall leave you with @sidestep one last time.
 
Last edited by a moderator:
  • 2Like
Reactions:
How AI will handle the %-based bonuses off buildings ? Can it plan that say "over X amount of income I should build a Mineral Purification Hub instead of another district" ?
 
I think I answered this but im bad at forums so ill do it again, quickly this time.
1. They will switch plan and produce food etc.
2. No planet-specific plans no, not enough time to rework together with this
3. They will still switch, did not touch the job system directly
Yes you did. Thank you very much for the reply, this looks really impressive and I hope you will find time to implement planet specific plans some day. Even if it is just something for modders to implement it would be a great way to reduce micro.


Here is another question: You mentioned that you got the basic numbers for the AI plans from QA. Since you have a couple synths running Stellar is over night for testing anyway, have you considered tuning those numbers with an evolutionary algorithm?
 
56d.gif

Dpl4yg-XgAAj-fl
 
This diary gives me hope.

But I always miss being able to automate my empire when it becomes large, the micromanagement kills the fun, so:

-Can we turn on this plan/AI for our own empires too? Or are they restricted to the computer AIs?
 
I was starting to lose faith because the game was working like trash and tried to fix the ai myself but with the game lacking simple functionality like telling the ai to aim at a mineral income of *number of planets times 10* it seemed impossible. Even mods like starnet didnt help because i didnt understand how the creator made it work the first place, so hard to tweak it for my own purposes...

BUT THIS UPDATE if it works half as well as i think, it will really solve all our problems! I can add all the buildings i like, jobs or almost anything and dont have to spend hours trying to figure out how to make the ai use them but not build them all the time... everywhere... Or make my races science / alloy oriented without having to tell them EXACTLY what order to build everything like it was a game of starcraft...

So anyway thanks a lot for this elegant solution and making our lives easy in advance. If it works which it probably will I take back all the shit i threw at pdx in the last year. Im actually really hyped about an update for the ai rework alone and the origins are just a cherry on top.
 
The above points that you bring up are good examples of why the old system wasn't really working. The AI no longer follow those scripts and therefore you need not worry about me not knowing how the numbers compare etc :)

I think these changes are good. I had driven myself crazy a few months ago with how the AI was building unnecessary buildings on planets. I had a post in the Mod forum section asking "Why are my planets building 10 Agri-Domes when I already produce a surplus of 500 Food monthly?" This also explains how I would get 1 Nanite strategic resource and suddenly 12 different planets create Nanite Transmuter buildings that send me into immediate resource deficits. Hopefully, the AI will also put more weight into building city districts when it needs housing rather than filling a planet's building slots with "Luxury Apartment" buildings.
 
When it comes to the economy, would the AI try to specialize in a planet they have have or nay? It would make sense and produce more when a planet does. Or an empire-wide specialization like building pop growth rates on all planets.

Resouces are cool to focus on and all, but if they don't work to specialize, most players will outgrow them in this matter.
 
When it comes to the economy, would the AI try to specialize in a planet they have have or nay? It would make sense and produce more when a planet does. Or an empire-wide specialization like building pop growth rates on all planets.
It was mentioned they would.
 
Food focus 10? Encourage planetary growth costs 1000 food per planet for 120 months. 12 (actually, it's 1000/120=8.3) net food for each planet is the focus.
focus is for the weight, the target food income for the early game plan is 50.
Keep in mind, too, that the plan will still be valid at the end of the "early game".

The consumer goods value is rather high, though. That is not a resource, where a huge stockpile (and hence surplus) is overly useful. It is not a common material for construction, so it just accumulates. Alloys on the other hand will be invested in fleets.
 
edit: also it wont build new buildings on planets with lots of free jobs, so at least it wont add to it
Does this take into account the "quality" of the jobs?
The aforementioned ecumenopolis will have oodles of clerk jobs (due to having arcology districts), but those are really not the reason to build an ecumenopolis. Waiting for the planet to fill up the clerk jobs until building a foundry district doesn't seem like a good plan.
 
While the English language was born in Europe and the European way of using it tends to be better, I will die on this hill:

The plural of "Math" is "Math".

No it's maths. Because maths is short for mathematics, which is a plural noun.
 
The AI overhaul certainly sounds great.

I do wonder, are the Plans(TM) modularly moddable though? As in, mods wont overwrite each other when messing with the Plan, but can add their own targets for strategic resources and have it all work together. Instead of, in an overwrite scenario, mod A overwrites mod B, so the AI will properly target resource A but be unaware resource B exists at all and ignore it.
 
Any news on how this will affect AI personality modding? Will these plans be available to add as behaviours or would we need to attribute each AI plan to a personality type?
 
The change is great, especially the economic AI seems much more capable than before :)

However the weights set in constants are a bit arbitrary, aren't they?
Have you tried making AI with different values fight together? Like for a genetic algorithm?
 
Haha, I will stick to no such claims.
You basically hit the nail on the head here, the sector AI is something completely different in code as well as megastructures. Different ministers indeed and a different system.

Aww, too bad. I really hoped that sector system could see some improvements. Right now it and the planet AI the player can use are far below what I'd call acceptable. Luckily I've been trained by a lot of bad 4x games to juggle tons of worlds because of bad AI helpers, so I don't mind, but I assume this must be pretty damn painful for players who don't like fiddling with 30+ planets.