• 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:
Is this the moment we all start bragging about how many alloys we're all producing by midgame?

BraggingMidGame.png

Done without conquering a homeworld early-game. The advanced AIs in my (improved AI) games also usually produce 500+ alloys per months by 2300, so it is a realistic goal. As others have pointed out, it's a silly goal to go for 2230, so there really is a need for more plans. I guess the first mod of Federations will be one which makes several plans based on number of planets pwned.
 
Are the goals set for actual dates, like 2300, 2400 and so on? What happens then when you play at, for example, x0.5 research speed? The AI would then surely be unable to meet those goals. Would that affect the AI in any way?
 
Are the goals set for actual dates, like 2300, 2400 and so on? What happens then when you play at, for example, x0.5 research speed? The AI would then surely be unable to meet those goals. Would that affect the AI in any way?

Also, I set the midgame to start in 2225. So yeah, there are some issues with the current implementation...
 
Yeah, no, I get it. But I won't be sharing any code examples in a DD since these things change all the time and would make little sense out of context of the code. But simplified you can look at it along these lines:
Starting from a base weight, you look at your current income, goal income and what the building in question actually produces. For each resource produced that is also part of the goal you add that to the weight of the building scaled ( with some modification ) by how much we are currently missing to reach that goal. Effectively meaning that if you have a building that produces a lot of something that we need a lot of, that would add a lot of weight. This then becomes the new "base weight" that we scale with all the different focus/deficit factors.

So, modders just blindly poke the system until they get something working? ) I feel sorry for those guys.
 
Is this the moment we all start bragging about how many alloys we're all producing by midgame?

View attachment 551127

Done without conquering a homeworld early-game. The advanced AIs in my (improved AI) games also usually produce 500+ alloys per months by 2300, so it is a realistic goal. As others have pointed out, it's a silly goal to go for 2230, so there really is a need for more plans. I guess the first mod of Federations will be one which makes several plans based on number of planets pwned.
Well, luckily the AI isn't actually required to reach it at 2230, it will just use these goals as a basis for deciding what to build. Effectively making it a long term plan and not a hard cutoff :)
Also as said before, just because it has reached it doesn't mean it will just stop building things ^^
 
Are the goals set for actual dates, like 2300, 2400 and so on? What happens then when you play at, for example, x0.5 research speed? The AI would then surely be unable to meet those goals. Would that affect the AI in any way?
Goals are set for ingame "eras", which are translated into dates by the game settings. If you have slower research speed the AI might not reach those goals, but it will still work towards them, which guides them in decisionmaking nontheless. Reaching the goals is nice, but even if the AI doesn't then having those goals will still help them. Much like long term goals in real life, hehe ;)
 
So, modders just blindly poke the system until they get something working? ) I feel sorry for those guys.
Much like they do with other features, also I do not agree that they go in "blind". They have access to debug views, tooltips, logs and scripts etc. We do not share code implementations of any other features and modders do great work anyways ( way to go modders! ) :)
 
Is this the moment we all start bragging about how many alloys we're all producing by midgame?

View attachment 551127

Done without conquering a homeworld early-game. The advanced AIs in my (improved AI) games also usually produce 500+ alloys per months by 2300, so it is a realistic goal. As others have pointed out, it's a silly goal to go for 2230, so there really is a need for more plans. I guess the first mod of Federations will be one which makes several plans based on number of planets pwned.


I can see you not using standard rules from there .

Anyway , since the AI will have all those planets and resources , it will be able to complete theyr plan and go over them . Maybe you will want to mod in a plan to make them focus more on alloys once the plans are reached .
 
Just a note of thanks for the completely fascinating DD. I cannot recall ever reading another like it.
When you're done fixing Stellaris's AI, can you please fix the rest of the games' AI's as well? :D
Most of those are worse than awful.
 
Much like they do with other features, also I do not agree that they go in "blind". They have access to debug views, tooltips, logs and scripts etc. We do not share code implementations of any other features and modders do great work anyways ( way to go modders! ) :)
It was a question, not a statement. :) Open source is not a popular idea in gamedev, but would not documentation with formulas help? Anyway, nobody knows how it is working outside of pdx. Not the best way to get the best ideas, but ok, I guess, I will have to spend time reverse-engineering them if/when I get interested enough. :)
 
So, modders just blindly poke the system until they get something working? ) I feel sorry for those guys.

Yup. Nothing new chap. Those who want to bother will. Those who don't, won't. However much PDS wishes to support modding, will have an impact on how much modding will happen. That's the reality.

edit - The developers in this thread are making an effort. I'm grateful for that. They cannot alleviate the need for modders to bounce off walls for a few weeks, however.

Much like they do with other features, also I do not agree that they go in "blind". They have access to debug views, tooltips, logs and scripts etc. We do not share code implementations of any other features and modders do great work anyways ( way to go modders! ) :)

Thank you.
 
Last edited:
It was a question, not a statement. :) Open source is not a popular idea in gamedev, but would not documentation with formulas help? Anyway, nobody knows how it is working outside of pdx. Not the best way to get the best ideas, but ok, I guess, I will have to spend time reverse-engineering them if/when I get interested enough. :)
Yeah, that's a fair statement. But supporting modding is hard, and a lot of work. We try to be as helpful and transparent that we can with the time given to us, but providing documentation for all of this and making sure that its up to date is basically a job in and of itself.
 
Yeah, that's a fair statement. But supporting modding is hard, and a lot of work. We try to be as helpful and transparent that we can with the time given to us, but providing documentation for all of this and making sure that its up to date is basically a job in and of itself.
This is all fair. And pdx should concentrate on satisfying the wide consumer base first of all. Ofc taking efforts to satisfy a frankly minor part of the audience, that uses mods (never checked the statistics, but it is probably fairly small) and even lesser part of modders is costly endeavour. But if we learnt anything from say dota precedent, it is that empowering modders can be extremely lucrative. Just don't forget an "all derivative works shall belong to us" to be buried into that thick licensing agreement no one ever reads. :D

And of this is of any blame to anybody especially to the developers who are opened for discussion about upcoming features. It is just a funny exchange of brave ideas. I do not expect any of it to lead to any changes. But ideas, ideas are worth talking about. As somebody said "spiritus flat ubi vult" (pardon my Latin).
 
...but providing documentation for all of this and making sure that its up to date is basically a job in and of itself.

Author of unofficial expansion says plz come and post that in comments of AlphaMod. Maybe my subs will listen to you.
 
Since one of the devs mentioned that job assignment now works better, was anything done to the assembly AI? Currently, it doesn't produce bots that are appropriate for the available jobs, just decides randomly which species/sub-species to use.
 
Last edited:
So when the AI meets its plan goals, it just goes back to the old system of weights. I was wondering if, instead of that, it could switch over to a temporary "ratio-based" plan. So when building new buildings or districts, it would keep in mind how that would affect. And thus, if alloys are falling behind in comparison to the other resources, it would build more alloy foundries, etc. And if alloys are over-represented, it will probably move on and build something else.
 
Goals are set for ingame "eras", which are translated into dates by the game settings. If you have slower research speed the AI might not reach those goals, but it will still work towards them, which guides them in decisionmaking nontheless. Reaching the goals is nice, but even if the AI doesn't then having those goals will still help them. Much like long term goals in real life, hehe ;)

@sidestep Does the Economic AI (or the AI you're using as an "overlord" to communicate between the various ministers) also assign values to land [districts/building slots] and even pops?

The AI might know that it needs to hit X amount of science by Year Y, but:
  • will it exclusively attempt to do this peacefully?
  • Or would it also run an opportunity cost calculation [maybe biannually] and determine that if it annexes another empire's world and take that world's current net output as its own (say, one not far from its own borders), it would actually meet its goals faster than by building up its own economy?
    • [Seeing as the Military AI also has the ability to gauge how many ships it needs to take a system, I wonder if the Overlord AI could bring this all together and say If we commit a fleet of size X [costing K amounts of alloys] to taking System Y, we'll hit our economic goals by year Z - which, to a degree, isnt too far off from how a human might rationalise out annexation]
  • Or what about a situation where the AI has actually used all of its planets available building slots and districts (e.g. 0.25x habitable worlds) but lacks the tech to upgrade science labs (e.g. 5x science costs, where such tech takes ages to research) -
    • Will the economic AI then go to the "Overlord" AI and say Man, Get me some more land and/or pops so I can keep building!
      • Possibly pushing that nation to issue more claims on colonised systems.
      • Or get the Overlord AI to build another habitat.
    • Or will it just give up, realising it has no more available building space, and just stockpile resources at its current rate of net income/output.
Also, are there any limits on how many buildings each AI can build concurrently?
  • E.g. if it had infinite resources and 100 open building slots (1, each, on 100 different worlds) could it issue 100 build orders in parallel in 1 month?
  • Or is there a limit in the code on how many construction operations it can do per month? (excusing the practical limits of processing power).
@MatRopert One last thing I wondered about, for the military AI, is will the AI hold a grudge?
  • Like if SOL was lost by AI A to AI B in an earlier war, would AI A be more likely to weight SOL's strategic value higher [e.g. with a "Former system/colony" or "System Contains slaves of our primary species" property].
    • In other words, would the War AI prioritise retaking its old/historic territory back, or liberating its people, over other tactical war goals/decisions.
    • Or would it pick its targets more... rationally and not make use of such weights.
 
Last edited:
I don't think having only net income of 50 alloys will be enough for entire early game(100 years) really, maybe my playstyle is too agressive and have a lot of expansion(which I don't think it is) but my goal of alloy net income before 2300 is around 1k though I'm not always reach that before 2300 excalty but at least it's prob 500+ alloys net income.

Similarly my goal of alloy net income before late game(2400) is about 2k+(my current game only reached this around 241x due to ever increasing fleets), at least this is what my approach to alloy production in every of my game.

All of these need ecumenopolis and in case of late game a matter decompressor too so I'm not sure will the ai even can reach it if they trying tho cuz never saw ai build them(only restore one) lol
 
Last edited: