Hoi 4 руководство по моддингу

Starting to mod in HOI4 is a long journey. HOI4 and in fact most Paradox games are very easy to mod, and spending a small amount of time to learn the code is enough to start modding; however this isn’t the case for adding new graphics, provinces or juggling with interface files, which has no documentation at all. It can also be frustrating to learn coding in the first place. If you’re clueless on how to start up, stuck or just want some shortcuts, you’ve come to the right place.

This guide will focus on giving the player a basic grasp on editing localisation files, changing flags and leader portraits. Note that this guide makes the assumption that the reader never has done anything to do with modding, creating content based on coding or anything of that sort. It’s focused towards people who’ve spent their lives reading history books and staring at maps, so discretion is advised to people who are familiar with using coding.

Good places to start off[]

The first few steps are a popular topic and various tutorial videos have been made on it. If you don’t feel like learning modding from text, you can always receive visual guidance. These are some of the videos powerblo thinks are the most useful for starting off.

The playlist by MrKmproductions is by far the most informative and helpful series on Youtube, and help you get quite a far way.

The playlist made by Paradox themselves are the canon resource, and while they cover several complicated schemes(new resources, province editing etc.) it’s not organised or user friendly and I wouldn’t recommend it for the fresh green modder.

These series by The Iron Workshop give several tips on how to make several useful changes, and include a nice introduction on making new provinces.

Along with these videos, the wiki page below shows a good list of sites you can access to learn coding or refer to resources.

Making your First Mod[]

While unfortunately Paradox hasn’t given a lot of documentation about modding, they’ve given a lot of useful tools to help the modder get going. One of these is the ability to create an empty mod in mere seconds. When you launch HOI4, you’ll notice a «Mod Tools» button in the launcher.
Press it, and go to «Create a Mod». When you get in there, you can tamper with the title of your mod and add new tags. Unless you know what you’re doing, it’s advised to set your directory the same name as your mod(or an abbreviate of it) without spaces or slashes. The game version should also be set to the latest current version of the game.
Don’t worry too much if you feel you’ve made a mistake; all of these can be edited later. If you’ve finished with all the new bells and whistles, click create mod and you’re ready to go.

Your New Directory[]

Mods are located in the folder ~/.local/share/Paradox Interactive/Hearts of Iron IV/mod(Mac and Linux) or C;Users<username>DocumentsParadox InteractiveHearts of Iron IVmod (Windows). Inside this folder there should be two nitbits;

  • The mod folder, named what you decided your subdirectory was
  • The .mod file, containing info on how the game should handle your mod folder

The EonAB .mod file looks like this:

name = "End of a New Beginning"

path = "mod/eonab"
tags = {
 "Gameplay"
}
supported_version = "1.4.2"

With both of these folders/files, you should be able to select your mod in the game launcher. Right now it shouldn’t do anything, but content is something you can stack along with time. But before we get working with brand new content, there’s a few precautions and tools you should

now of.

Guidelines[]

  • Never use Notepad as your default text editor. For simplicity, use Notepad++, for convenient folder management use Sublime Text or Atom. All of them are free; it’s recommended to have at least two text editors (powerblo uses Atom to manage his projects and Notepad++ to edit individual files)
  • ALWAYS create a workspace folder(where you do the editing) separate from your Paradox InteractiveHearts of Ironmod directory. Similarly, never edit vanilla files- those edits are permanent unless you reinstall the game.
  • Try not to overwrite vanilla files unless their existence create errors or overwrite your content. It’s almost always advised to create separate files for localisation, events, focus trees, etc.
  • Use repository managing programs like GitHub to keep track of what you’ve changed, and to revert any fatal errors you made. Don’t forget to upload every minor change to GitHub; if your game has errors it’s very easy to go sieve through previous versions if you know what changed through tie.
  • Use proper folder merging tools instead of copy-paste like WinMerge.
  • Don’t forget to use UTF-8 encoding for normal files and UTF-8 BOM files for localisation. Text editors like Atom automatically encode your files into these formats.
  • Have a «project» folder that includes all your resources, your workspace, and plans for coordinated modding.
  • Always have several backup folders if you don’t use GitHub. You won’t regret it when your new edits cause CTDs the second you start the game.
  • Use AFP[1]s or Graphical Tools to reduce coding time and make coding easier, but always use them with caution. They often have several bugs and might delete everything you’ve done if you don’t backup.
  • Proper indentations, comments using # and being smart with paragraphs make reading code much easier for other people. This won’t break your game when you don’t keep it, but it’s much more easier for you as well if you know exactly what’s going on with each line of code.
  • Consult other modders or other mods to get help with things you can’t seem to code — reverse engineering is very useful in both learning and decreasing code time, but never plagiarise other’s work.

Localisation : Adding Loading Tips[]

Now that we’ve created the empty template for a mod, it’s time to create some dummy content. Localisation files are a good place to start, being easy to edit and create.

Localisation files give names to ingame variables, and add text for descriptions. This is where all the ingame text is rendered from, so editing these files would change the text that appears ingame. All localisation files are and should be located in <mod>/localisation. Another important point is that all localisation files have the .yml extension and are encoded in UFT-8 BOM format. If you don’t know what these are, don’t worry; you won’t have to worry about these as long as you’re smart with how you code.

The most straightforward piece of localisation the player first sees are the loading tips[2]; the lines of famous words written on the bottom of the screen while the game is loading. The best way to start off with localisation is to copy the file in the vanilla folder[3] and paste it into your mod, so you don’t have to go through the encoding. Create a new folder within your mod called localisation, and copy the loading_tips_l_english.yml file and paste it in there. When you open it, there will be a list of LOADING_TIP_<number>:0 «<loading tip>» , the code that assigns text to loading tips. Within a localisation file, the variable name goes behind the :0, and the text goes inside the double quotation marks. By changing the text inside the double quotes, you can change what the game displays for the loading text. Every single loading tip has an equal chance to appear while loading, so erasing every other one (leaving just one loading tip in) will make only one loading tip appear for the entire loading process.

Using special nitbits of code you can format your loading tips, and in fact any localisation file.

n : The equivalent of typing Enter, adding this annotation jumps the text down one line. Useful for loading tips (you’ve gotta put the original quoter somewhere) or descriptions when you want them to look tidy. Note that you don’t need to put a space after the annotation, like «nAnd Lewis is to blame.»

» : Since the boundaries of the localisation is defined by quotes, to use quotes inside your text wall this annotation is used. This is optional, luckily HOI4 is smart enough to let you use normal quotes. However this is recommended for anyone making large scale projects, or just paranoid about how code looks.

UTF-8 and the HOI4 language[]

The traditional Paradox machine, the Clausewitz engine utilises a programming language unique to itself, different from the well known Lua or Java. You don’t have to read the stuff below to make portrait or flag mods, but it’s recommended to know what you’re coding in if you want to be good at it.

  • HOI4 has their own ‘coding language’, making it much easier to code but much less versatile. It’s similar to the EU4 or CK2 language, but being a new iteration and a different game there will be several places the code doesn’t overlap.
  • UTF-8 isn’t a language; it’s a format where the game can read code from .txt files. Don’t go looking for UTF-8 encoders and just see if your text editor can do it.
  • Localisations need an extra step named UTF-8 BOM. Not keeping this is a common cause of missing localisation files.
  • The HOI language, HOI-ese doesn’t utilise ;s or <>s, and links how your code is designed to how it functions. This is why using comments(#) is extremely important so you can keep track and have a clean, bugfree code.
  • Indentations(tab and spaces) don’t really matter in HOI-ese in function.
  • HOI-ese operates using .txt files for most code. .yml files are used in localisation, .gui for interface design and .gfx for designating graphic files.
  • HOI-ese is mostly independent from directory for graphic files. This has not been confirmed for coding files, but generally it’s important to have thourough knowledge on the HOI4 directories.
  • Make sure you don’t name any ingame files or variables the same.

We assume that you have basic knowledge of how code works, and have at least common sense on what parentheses or equal signs do. Then now that you’ve got that through, it’s time to start making edits to the actual game.

Changing Country Leaders[]

Perhaps the best of modding HOI4 would be adding new leaders to nations. It’s one of the more simpler, and straightforward changes to start off with.

Adding new country leaders, or replacing them requires you two edit two things;

  • The «history» file of the nation you’re adding a leader for
  • The portrait for your leader

The history file is the first step of adding a leader, faction, party or researched tech for any nation ingame. They’re located in [mod]/history/countries/[TAG].txt. Opening it for the first time is a complicated process; but since we’re simply adding new leaders it’s simple right now.

Let’s take the example of Germany; we’re not fond that Hitler is in power and want to place a yodeling person in his place.

In the GER.txt, searching «Hitler» returns this block:

create_country_leader = {
name = «Adolf Hitler»
desc = «POLITICS_ADOLF_HITLER_DESC»
portrait = «<directory>»
expire = «<date>»
trait = {

}

  1. Automatic File Processor — A set of .bat files that automate simple actions like creating nation history files or converting flag image files.
  2. They’re called loading tips because traditionally (in Paradox games like EU4) they contained tips on how to play the game.
  3. Wherever your HOI4 is installed — the localisations folder

This is a community maintained wiki. If you spot a mistake then you are welcome to fix it.

Modding, or creating mods, is the act of modifying the behavior of the base game (often referred to as vanilla), either for personal use, or to release publicly for other players, for instance — via the Steam Workshop.

As for all Paradox games, Hearts of Iron IV is moddable to a great extent. Motivations of modders may vary widely: a better translation to their native language, more events or decisions, better maps, a major overhaul, etc.

By default, the user directory for Hearts of Iron IV is located in the following folders:

  • Windows: C:Users<Username>DocumentsParadox InteractiveHearts of Iron IV
  • Mac OS: ~/Documents/Paradox Interactive/Hearts of Iron IV
  • Linux: ~/.local/share/Paradox Interactive/Hearts of Iron IV

Mods are stored within the mod/ folder within the user directory. If the path to the user directory (Including the Windows username) includes any special characters (Such as umlauts, other diacritics, or Cyrillic), the game will not work properly. Local mods will fail to load, and the game will not be able to open the error log by itself. The user directory’s location can be changed in /Hearts of Iron IV/launcher-settings.json in the base game folder by changing the "gameDataPath" line and moving the files to that folder.

Alongside mods, the game will load any files stored in the user directory. The game’s internal map editor, the Nudger, stores its output within that folder.

To start modding, you will want to create a mod structure in the mod directory.

Guidelines[edit | edit source]

  • Never modify game files: use a mod even for small changes, and never modify directly game files in Steam Hearts of Iron 4 folder, as your changes may be undone without warning.
  • Minimize overwrites of vanilla files by adding separate files and loading from folders whenever possible, to improve mod compatibility and maintenance. (Your files can have any name, all files in the folder will be loaded by the game. So choose a name, no one else will ever use, like the name of your mod. Ex: coolmod_countries)
  • Use a proper merge tool (like WinMerge), to merge between folders, and update modified vanilla files to a new vanilla patch.
  • Backup your work to avoid losing everything. Consider using a source control system like Git and a collaborative forge like GitHub or Gitlab to manage team collaboration, or just make a copy of the file somewhere else. Version keeping via Github or Gitlab can also be very useful for debugging due to limiting the selection of potential broken files.
    • The Modding Git Guide is a community made guide for using Git, GitHub/GitLab, and related tools such as KDiff3. It can be a useful stop for questions beyond this wiki, and contains step by step guides for much of what is talked about here.
  • Use UTF-8 encoding with the byte order mark for text files. This is commonly called «UTF-8», but can sometimes be specified as «UTF-8 without BOM».
  • Use UTF-8 encoding with the byte order mark for localisation files (.yml). This is commonly called «UTF-8-BOM», but can be just «UTF-8», in which case omitting the byte order mark is a separate option. Some text editors, such as Atom, do not support the byte order mark in entirety and should be avoided for localisation.
  • Use comments starting with # character, to remember reasons for writing tricky stuff. A single sharp sign will make the rest of the line completely ignored. There is no multi-line comment notation in the code.
  • Debug effectively by enabling Debug mode. Do this by adding -debug to your launch options in Steam. The launch options are accessed in the menu opened by right-clicking the game and choosing ‘Properties..’.
    Alternatively, in Windows it’s possible to create a shortcut to the hoi4.exe or dowser.exe file, and then to open the shortcut’s properties and append -debug (separated by a space) after the path’s end, such as «C:Program Files (x86)SteamsteamappscommonHearts of Iron IVhoi4.exe» -debug.

Debug advantages[edit | edit source]

  • Automatic loading — Edits to files done inside the mod folder will show up in-game without the need to use the ‘reload’ console command. This will also automatically add the errors in the files to the error log. This only applies to files that existed when the game was launched, with an exception: if a file’s direct path gets mentioned elsewhere within the mod, then it can still get loaded for that use in particular. Examples of that include orders of battle, as load_oob = «TAG_my_oob» functions as a direct link to /Hearts of Iron IV/history/units/TAG_my_oob.txt; or GFX, as sprites directly reference the position of the image. Although, notably, the loading of images in-game does not uncompress them properly, leading to visible distortion or black backgrounds which get fixed on a restart. Although edits to most files work, this doesn’t work with /Hearts of Iron IV/history/countries/, /Hearts of Iron IV/history/states/, and /Hearts of Iron IV/map/, although the nudge partially can be used for the latter two.
  • No map definition crash — If the map is edited, there’s a possibility for errors to appear. Any map-related errors will crash the game when loading with a message saying ‘Some errors are present in the map definition and have been logged to error.log’. If debug mode is on, the game will continue to load properly. The map definition occurs when there is any error containing MAP_ERROR within the error log after loading into a country.
  • Extended error log — Certain errors do not get logged in the log unless the debug mode is turned on. An example would be the map definition errors mentioned above, as the game crashes before getting a chance to log them. Enabling debug mode will ensure that all errors that can be logged in the error log will get logged.
  • Ease of error log opening — As long as there are any errors in the log, the log will automatically open when loading the game or after selecting a country. The log will also be able to get accessed by clicking on the error dog in the bottom-right corner after loading into a country, which appears each time a new error appears in the log (since files get automatically loaded-in).
  • Ease of nudge access — With debug mode turned on, an option to open the nudge will appear in the main menu. This can be useful to save time or to be able to open the nudge if the game crashes when you’re trying to load into a country (This can happen if the /Hearts of Iron IV/tutorial/tutorial.txt file references invalid states, if that file doesn’t contain at least one tutorial = {} even if not containing anything, if supply nodes and railways aren’t set up properly, or for other reasons).
  • Graphical interface information in the main menu — As long as the debug mode is turned on, hitting the ` button (Typically in the top left corner of QWERTY keyboards, used to open the console by default) in the main menu will provide information about the graphical interface used, giving the names of elements, their positions, and the sprites used by them. This is equivalent to using the «gui» console command, but the debug mode makes it possible to do in the main menu.
  • Expanded province info — With debug mode turned on, there will be additional information when hovering over the province, including its and the state it’s in’s IDs, tags of owner and controller, et cetera.
  • Access to more console commands — Certain console commands are locked for developers only and debug mode allows the player to use them. However, note that not all console commands will become available.
  • Ease of access to GUI files — When hovering over a GUI element, Ctrl+Alt+Right Click can be used to open a debug menu, which will allow going to the GUI file where the element is defined.
  • Automatic saving on peace deals — The game automatically creates a savefile each time a peace conference occurs with debug.

Note that if you turn on the debug mode through the ‘debug’ console command, only the last 4 advantages will be available to use. If debug is turned on via launch options, be that -debug or -crash_data_log, all benefits will be granted.

Text editor[edit | edit source]


These are the most common text editors to use for modding the game:

  • Visual Studio Code.
Has a fan-made CWTools extension with Paradox syntax highlighting, validation and tooltips for triggers and effects. To install it, go to Extensions on the left panel of VS and search for CWTools. (Note: validation rules are incomplete and will show many false errors in gui and localization files).
Recent versions with automatic highlighting of {} pairs in different colours and flagging opened/closing ones that are missing a partner red is worth it’s weight in gold.
  • Notepad++. Choose Perl as your language, as it will provide good highlighting and allow to fold blocks of code and comments. To set it as default, go to Settings, Style Configurator, find Perl in the list on the left and add «gui txt» (without quotes) to the «User ext.» field at the bottom.
Some options that are commonly turned on by default in other text editors are turned off in Notepad++, but can be changed in the topbar. This includes Word wrap, Document map, Indent guide, and Folder as workspace.
  • Sublime Text. There is an extension for it released by the developers of Imperator which could be used with HOI4 but use at your own risk: Sublime Tools. It adds colored highlighting for effects and triggers. If you want to toggle comments in Sublime, you also need to add this file to the same «User» folder.

Reasons to use a non-default text editor include the following:

  • Bracket and syntax highlighting. Bracket highlighting makes it easier to detect any missing or unnecessary files by allowing to select a bracket and see where it opens or closes, as to know what’s inside of that block. Syntax highlighting can make code more easily readable by highlighting more important parts, as well as excluyding brackets within comments from being considered such.
  • Searching in multiple files in the same folder. In each provided tool, this is activated with the ^Ctrl + ⇧Shift + F hotkey and can have filename filters in order to limit the files that are searched (e.g. *.txt will only search text files, ignoring any other files, such as *.dds ones).
  • Each line is numbered on its side. Since error log typically points to the line where an error is present, this makes finding the line in question much faster compared to how the Microsoft Notepad only tells the number of the currently-selected line in the below.
  • Greater capabilities to work with multiple files. Each of these editors may only have one instance of it open at a time with multiple files open at once (switching between them with ^Ctrl + ⇆Tab), in contrast to Microsoft Notepad that opens a separate instance for each opened file, which can quickly fill the Alt + ⇆Tab menu. Multiple instances of the text editor can still be opened, however. A text comparison tool also exists on each one of these: «ComparePlus» plugin in Notepad++, «Compare Side-By-Side» or «Diffy» package in Sublime Text, or a variety of Visual Studio Code extensions («Partial Diff» being the most popular one).
  • Greater customisation capabilities: each of these text editors allows a wide variety of light or night themes that can be picked as fit, with downloadable themes existing as well. Since one would need to look at the text editor a lot while modding, selecting a theme that looks good to the eyes can make the experience much better.

Searching multiple files[edit | edit source]


One feature of non-default text editors is a highly-customisable search of all files within the same folder. This is highly useful for dealing with errors and finding locations of certain elements.
Windows File Explorer is a poor choice for doing this, as it only searches inside of .txt files while it may be desirable to search files of other extensions, e.g. .yml, .gfx, .gui, or .asset, and it is very noticeably slower than either text editor: a search taking ~10 seconds on a text editor may take up to 15 minutes to conclude in the Windows File Explorer.

This is how exactly the feature is enabled in the common text editors:

  • Notepad++ – This is located in the «Search» topbar menu as «Find in Files…». By default, no folder is provided. «Follow current doc.» allows the text editor to automatically input the currently-opened document’s folder as the place for the search, or it can be entered manually. Alternatively, this menu can be opened from the right-click menu of a folder within the «Folder as Workspace» menu – accessed by a button in the topbar – which’ll automatically set the folder location to be that folder. The ^Ctrl+⇧Shift+F hotkey also opens the menu for this feature by default.
  • Sublime Text – This is located in the «Find» topbar menu as «Find in Files…». In order to add a folder to search, the menu to the right of the «Where:» line can be opened, with either «Add Folder» (to select an individual folder) or «Add Open Folders» (To automatically select all folders opened via Sublime Text) buttons serving to do so. The ^Ctrl+⇧Shift+F hotkey also opens the menu for this feature by default.
  • Visual Studio Code – Visual Studio Code only supports searching the currently opened folder. A folder is opened either through the «Open Folder…» button in the «File» topbar menu or the «Explorer» menu, accessed through the bar on the left. After this, the functionality can be accessed in the «Edit» menu as «Find in Files». In order to speed up the search, filename filters can be used. For example, localisation/english/*.yml within «files to include» will only search every *.yml file within the <currently opened folder>/localisation/english/ folder, where * stands for any amount (including 0) of any characters within the filename. Similar filters can be used in the previous two text editors, however without allowing folders to be filtered — only the filenames. The ^Ctrl+⇧Shift+F hotkey also opens the menu for this feature by default.

A filter on the file extension can be set to speed up the search. This depends on the text editor. Note that * is used to mark any amount of any characters, and this is universal.

  • In Notepad++, this is done with the ‘filter’ menu. Filters are separated with spaces, and an exclamation point in the beginning marks it as an exclude filter. For example, *.yml !*french.yml will result in searching every localisation file aside from the French ones.
  • In Sublime Text, this is in the ‘where’ menu. Filters are separated with commas, and a minus sign in the beginning marks it as an exclude filter. For example, C:Program Files (x86)SteamsteamappscommonHearts of Iron IV, *.txt, -GER* will search every text file in the base game (Assuming the default location within Windows on Steam) with the exception of those that begin with GER.
  • In Visual Studio Code, this is in the menu triggered with the ‘Toggle Search Details’ button, represented with an ellipsis. This menu has separate «Files to include» and «Files to exclude» menus, used accordingly. Additionally, this allows representing folder names within the menus, with the doubled * (as in **) used to represent an arbitrary folder name. For example, *.gfx in the «Files to include» and dlc/** in «Files to exclude» will search every single file with the .gfx extension with the exception of those in the dlc folder.

There are the following uses for this:

  • Finding out an internal ID by searching the localisation folder for the localised name. For example, searching for an event’s title can be used to determine the ID.
  • Finding out where the database entry of a certain type is defined where it is not immediately intuitive. For example, by searching for an equipment ID within the folder that stores equipment (or even /Hearts of Iron IV/common/ in general) can be used to find the exact file, which isn’t immediately obvious for some equipment types.
A subset of this includes finding sprites’ or interface elements’ locations: The gui console command (or its main menu equivalent in debug mode) can be used in order to find the name of a certain SpriteType (prefixed with GFX_) or interface element. A search query with the given name within the /Hearts of Iron IV/interface/ folder will provide the file where the sprite is defined (as such, also giving the texturefile that says the path of the image in gfx) or the interface folder (which allows copying it to the mod and editing it).
  • Dealing with unintuitive errors where the location is not specified, such as Invalid Decision Category, where this can be used to locate which file is throwing the error.
  • Finding out what can cause a certain occurance to happen, such what fires a certain event.

Indenting[edit | edit source]

Another reason to use non-default text editors is greater indenting capabilities. Indenting refers to the usage of newlines and spaces at the beginning of the line, which does not leave an impact on how the code is interpreted, but makes it easier to see the relations between different parts of the code.
Typically, either a tab character (represented as t) or 4 spaces are used as a single indenting level, placed from the beginning of the line to the beginning of code on the line. In order to increase the indenting level of code, the ⇆Tab button is used in text editors, which can be done on multiple lines at the same time by selecting them. Inversely, ⇧Shift+⇆Tab is used to decrease the indenting level of the line by one.

An additional option present in these editors is ‘Indent guide’, drawing a line on each indent level in order to make it easier to see the borders of each indent level, which can assist in code capability. While turned on by default in Sublime Text and Visual Studio Code, this must be turned on manually in Notepad++ within the topbar.

These are the typical conventions used for indenting:

  • The first line of the file has zero indenting.
  • An opening bracket and its corresponding closing bracket must be placed on lines with the same indenting level.
  • If a line introduces an unclosed opening bracket, then everything until the proper closing bracket must be one indent level to the right compared to the line with the opening bracket.
  • A line shouldn’t have more than one bracket of each kind.
  • If a line includes a closing bracket without including an opening bracket, then it shouldn’t have anything other than the closing bracket and indentation before it.

This is an example of proper indenting:

TAG = {
    if = {
    |    limit = {      # The bar character "|" is used to visualise the indent guide, rather than being used in-code.
    |    |    has_stability > 0.5
    |    |    has_war_support > 0.5
    |    }
    |    country_event = { id = my_event.1 hours = 1 }
    }
}

Proper indenting has two primary benefits:

  • It’s easy to where an argument is contained by moving one indenting level to the left and then following the indent guide’s line until it hits code.
  • It’s easy to find what falls within a block by following the indent guide’s line from the line with the open bracket to the point where it hits the closing bracket.

Some common errors to check for in the indenting are the following:

  • Unnecessarily removing an indentation level after a closing bracket. This can usually be detected by detecting any interruptions in the indent guide–generated line from the line with the opening opening bracket drawn to the closing bracket:
ideas = {
    country = {
    |   my_idea_1 = {
    |   |   modifier = {
    |   |   |   political_power_gain = 0.1
    |   |   } # closes modifier = { ... }
    |   my_idea_2 = { # Interrupts the line from my_idea_1 to the closing bracket, so is erroneous
    |   }             # Doesn't work due to being located inside my_idea_1
    }
}
  • Putting a closing brackets on the same level as prior script:
if = {
    limit = {
        my_scripted_trigger = yes
    }
    } # Closes the if statement, and so should've been one more level to the left to match the if statement's indent level.
    my_scripted_effect = yes # Always executed due to being outside of the if statement.
}
country_event = {
    id = my_event.1
    option = {
        name = my_event.1.a
        } # Closes option = { ... }
    }     # Closes country_event = { ... }
    option = { # Does not work due to being defined outside of an event.
        <...>
  • Placing neighbouring lines with a difference of at least 2 indent levels:
focus = {
    <...>
    completion_reward = {
        TAG = {
            country_event = my_event.1
    } # Closes TAG = { ... }
}     # Closes completion_reward = { ... }
focus = { # Does not work due to being contained within another focus = { ... }
    <...>
}

Following the indenting rules and checking for these indenting errors will ensure that there will be no bracket-related errors within the code.

Universal modding concepts[edit | edit source]

  • It’s heavily recommended to turn off Windows file explorer from hiding file extensions from the filename, if using Windows. File extensions are considered a part of the filename, and hiding them can cause files to not work due to wrong filenames (Such as accidentally saving localisation files as .txt files, saving an image in the wrong format and not realising it, et cetera).
  • After creating a mod folder within the launcher, every single file within will get loaded at the same order as in base game. Taking a mod with the name of «yourmod» as an example, every single file within mod/yourmod/common/national_focus will get loaded alongside files in base game’s /Hearts of Iron IV/common/national_focus, however, if you insert one more folder as in mod/yourmod/test/common/national_focus, the mod’s national focus files will not get loaded.
The root folder of the mod, considered the same as the /Hearts of Iron IV/ folder in base game, will be defined in the user directory’s /Hearts of Iron IV/mod/yourmod.mod file, opened with a text editor. This is set via path = "" in that file, by default being user directory’s /Hearts of Iron IV/mod/yourmod.
  • The game loads files in the order of base game, then DLCs (within the /Hearts of Iron IV/dlc/ folder), then user directory, and finally mods. The mods are usually loaded in the order set by the names of their mod files. If there’s a file with the same name in the exact same folder between these (For example, both /Hearts of Iron IV/events/AcePilots.txt and mod/yourmod/events/AcePilots.txt), the game will only read the one that is later in the load order, ignoring all contents of the previously-defined one. The base game utilises this to change the main menu background by changing the /Hearts of Iron IV/interface/frontendmainviewbg.gfx file within each DLC and this is also a primary foundation by which mods work.
In other words, if not specifically set to unload files in the same folder with replace_path, every single base game file will get read within mods unless there’s a file with the same name in the same folder within a DLC, the user directory, or an enabled mod’s files, in which case only the file later in the load order will be read, the one created earlier being ignored. After the files are loaded and overwritten as intended, their origin (whether it’s the base game, a DLC, the user directory, or a mod) makes no difference in how they are evaluated: any aspect of the base game files can be referenced within the mod files and, vise versa, any aspect of the mod files can be referenced in the base game files.
This also means that the modname/dlc/../ folder will have no effect in-game whatsoever, as DLCs are loaded akin to mods. If a base game DLC stores a file at /Hearts of Iron IV/dlc/dlc_example/interface/dlc_portraits.gfx, it will be loaded as /Hearts of Iron IV/interface/dlc_portraits.gfx and so to overwrite it, the mod must have the file in modname/interface/dlc_portraits.gfx. Locking a mod’s file to only be loaded when a DLC is enabled is impossible, however the has_dlc trigger can be used to lock content that can be enabled by a trigger.
Note that the files are not immediately interpreted once they are loaded (with the exception of localisation), instead the interpretation happens after every file that needs to be loaded is already loaded. For the vast majority of folders, such as /Hearts of Iron IV/interface/*.gfx files, the ASCII character IDs are used to sort. This is different from the alphabetic sorting used by the file explorer as uppercase letters are considered earlier than lowercase letters and there are multiple characters inbetween (such as underscores) that are later than uppercase letters, but earlier than lowercase letters. In order to place a file particularly high in the evaluation order, you can make the name begin with a lowercase zzz_ prefix. Meanwhile, /Hearts of Iron IV/history/countries/*.txt files are interpreted in the order that the tags are defined within /Hearts of Iron IV/common/country_tags/*.txt files (which use the same ASCII character ID order).
Changing the interpretation order has very limited use, but it is present, such as with interface, as when encountering contradictory definitions of an interface element (whether it’s a spriteType, a containerWindowType, or something else), the game chooses the one defined later. The base game primarily uses it for sprites that point to different images depending on the DLC, such as portraits included with DLCs which point to a generic portrait without that DLC.
  • Other than the overwriting of files with the same name and setting the interpreting order above, filenames don’t matter at all in how the file is read with few exceptions[a]. For vast majority of files, they’re either read only by the virtue of being within a specific folder (Such as national focuses), or by a direct link within a different file (Such as oob = "TAG_1936" within a country history file loading the /Hearts of Iron IV/history/units/TAG_1936.txt file for unit locations). Due to this, it’s usually recommended to avoid overwriting base game files when adding new content that doesn’t need to overwrite base game files as to make future-proofing of the mod for game updates better.
  • Comments are marked with the # character: everything after that character until the newline will be entirely ignored by the game.
  • Aside from comments and strings (marked with the quotation marks, must be on one line total), indenting does not matter: most files can be done on one line in total without breaking. However, doing indenting properly can make detecting bracket problems much easier without using a text editor’s bracket highlighting and overall makes it easier to see at a glance what each block (marked with the figure brackets as block_name = { ... }) includes within of itself and what it doesn’t.
  • Names depending on language are defined within localisation. Taking the English language into consideration, /Hearts of Iron IV/localisation/english folder is used. A file within must end with _l_english.yml in the filename to work properly. The file must be encoded in the UTF-8 encoding with the byte-order mark included, usually called UTF-8-BOM. The exact details on conversion depend on the text editor, but it’s usually within the topbar or bottombar.
A localisation entry is structured as localisation_key:0 "Value of the key". In here, the first part before the colon is referred to as the localisation key, the ending part in quotes is referred to as the localisation key’s value, and the number in-between is the version number. The version number is purely a comment and isn’t read by the game, it’s possible to be omitted entirely. Any localisation file can be used for any localisation, and it’s better to use new files rather than copying over base game files.
While it is possible to avoid using localisation in many cases, it is better to not do so for the following reasons:

  • Special characters, such as umlauts and other diacritics. Multiple files such as country leader traits or adjacency rules provide no support for the UTF-8-BOM encoding, which allows to use special characters within of themselves, and so using them in the name will be impossible.
  • Multiple language support. Even if desiring the mod to only be within English or a different language, it is better to allow the option to be open for potential sub-mods. While it is still possible to make translation sub-mods to mods that don’t use localisation, it becomes much harder to keep it up-to-date (As more than just localisation files can be changed in this case) and changes the checksum (Making it impossible to have a multiplayer session between those that have the translation sub-mod and those that don’t).
  • Dynamic localisation. In a large portion of files, such as scripted localisation, the name argument or any alternative is strictly expected to point towards a localisation key, just displaying the name of the key if not finding one. That means that any localisation commands such as newlines, coloured text, and namespaces cannot be used.
  • Almost every single image is defined within /Hearts of Iron IV/interface/*.gfx files, opened within a text editor. A simplest sprite definition, within a spriteTypes = { ... } block encompassing most of the file, is the following:
spriteType = {
    name = GFX_my_sprite_name
    texturefile = gfx/interface/folder/filename.dds
}
This assigns the /Hearts of Iron IV/gfx/interface/folder/filename.dds file to have the GFX_my_sprite_name sprite in-game, so using GFX_my_sprite_name as an image will link back to that file. This is necessary to do because there are more potential arguments that may go into sprites, such as the amount of frames and animations. The only images that do not have any definition within interface files are:

  • Flags used for countries in /Hearts of Iron IV/gfx/flags/ and its subfolders.
  • Loading screens within /Hearts of Iron IV/gfx/loadingscreens/. Note that, however, the main menu background usually stored in that folder is defined as a sprite.
  • Character portraits. They may use a sprite as a definition, but they’re the only place in the game which doesn’t have it as a mandatory requirement, accepting direct links to the file as an alternative.
There are also potential errors that may occur related to sprites:

  • A sprite is entirely transparent: This is an indication that the sprite exists, but the image within can’t be loaded. This occurs if the texturefile is defined to a file that doesn’t exist (Commonly because of a typo either within the filename or the texturepath) or if the image itself is corrupted. This is usually accompanied with a Texture Handler encountered missing texture file error.
  • A sprite is replaced with the default image: This is an indication that there is something wrong with the sprite itself rather than the image: the game links to a non-existing sprite somewhere. This is typically a typo within the sprite’s name or a failure to follow a name format (Such as omitting _shine from the end of a national focus icon’s shine sprite). Ensure that the sprite exists and has the right name.
  • The character uses a randomly-generated portrait: This is an indication of either of the previous two problems: a character with an invalid sprite or a missing file will have their portrait randomised.

Mod structure[edit | edit source]

Each game mod has a definition within the user directory’s /Hearts of Iron IV/mod/ folder as a *.mod file. This tells the game what settings to assign this mod and where exactly is the folder that stores it. Since the *.mod file format is also used for videos, the computer might think that this file is to be opened with a media player, but this is not the case: it is to be opened with a text editor.
Each mod has two *.mod files, the /Hearts of Iron IV/mod/*.mod file and the descriptor.mod file directly within the root folder of the mod, specified within path = "" of the former. The descriptor says what the /Hearts of Iron IV/mod/*.mod should have, and so these two *.mod files should be identical with the exception of the folder path which should only be in the /Hearts of Iron IV/mod/*.mod file as this depends on the machine. This is indeed monitored by the launcher: anything within the former /Hearts of Iron IV/mod/*.mod file that’s not within the mod’s descriptor.mod will be automatically deleted when the launcher gets opened. However, the inverse is not automatically true: the launcher periodically fails to carry over descriptor’s arguments to the /Hearts of Iron IV/mod/*.mod file. An argument will only be executed if it’s in the /Hearts of Iron IV/mod/*.mod file as it is what the game uses, so to be safe it is best to manually edit both descriptor.mod and /Hearts of Iron IV/mod/*.mod when needing to change a mod’s definition.

The name of the *.mod file must not contain any spaces, or it will not be auto-selected by the game launcher.

Mod definition[edit | edit source]

A simple *.mod file will have something like this:

name = "Minor Mod"
path = "mod/MinorMod"
picture = "thumbnail.png"
version = "v1"
supported_version = "1.12.*"
tags={
	"Gameplay"
	"Historical"
}
remote_file_id="<ID>"
  • name is the name of the mod in the launcher.
  • path is the location of the mod folder. A shortened path, without Documents/Paradox Interactive/Hearts of Iron IV/ will work, making the game automatically generate a new one. The path does not have to lead to the documents folder, path = "C:/folder/modname" will also work as long as the mod is in that folder. Note that if the path contains any special characters, including but not limited to Cyrillic, the mod will not work. Alongside that, a backslash, or , will not work to separate folders in the path, only / will work.
  • picture is the picture of the mod, located in the root directory. It must be named «thumbnail.png» to work correctly. In addition, thumbnail files should be less than 1MB in size, otherwise they cannot be uploaded to ParadoxMods.
  • version is what the launcher will show as the version of the mod (Not the version of the game it’s meant for). Any string is accepted.
  • supported_version is used to determine for which version of the game the mod is meant for, granting the ‘out of date’ marker in the launcher otherwise. The last number of the version can be replaced with an asterisk in order for the mod be considered up to date for any version within the specified major update.
  • tags are tags with which the mod will get marked upon getting uploaded to Steam Workshop.
  • remote_file_id is added by the launcher upon uploading the mod to Steam Workshop. It is used to assign the workshop item to the mod.

Some other additional arguments can be used as such:

 user_dir = "MajorMod"
 replace_path = "history/states" 
 dependencies = { "Major Mod" "Major Mod 2" }
  • user_dir changes the folder where the mod’s saves are stored. This can be useful so that the mod’s saves can not get mixed up and accidentally loaded without the mod on and vise-versa.
  • replace_path makes every file that was already loaded and indexed in the specified folder beforehand get unloaded when starting to apply changes from this mod. For example, replace_path = "history/states" will unload every state that gets loaded prior to this: base game, user directory, and other mods (depending on the mod load order). This will ensure that no base game states will be loaded in the mod. Note that replace_path does not overwrite the subfolders within the specified folder. Additionally, the launcher frequently fails to port this option to the modname.mod file, so it should be added to both mod/modname/descriptor.mod and mod/modname.mod manually.
If a file only gets loaded after the main menu is loaded, a replace_path will not unload it. For example, a replace_path = "history/units" has no effect since the files in that folder aren’t loaded before the main menu loads, but are instead loaded directly via the load_oob = "filename" effect or the oob = "filename" argument in country history. Meanwhile, replacing history/countries would work, since the game loads every file before the main menu finishes loading, but only executes effects in them later on. This also applies to gfx/flags: replacing that folder has no effect because flags aren’t loaded and indexed during the main menu background, but only after selecting singleplayer, interpreting history for each country. This can be seen by when the «file not found» errors appear for missing flags: only after the loaded history files get interpreted by the game.
This can be seen by a replace_path to gfx/loadingscreens. Doing so will remove the base game’s loading screens from being possible to be picked by the game. However, the main menu background — since it is defined in /Hearts of Iron IV/interface/frontendmainviewbg.gfx where it only gets loaded after the main menu loading finishes, when getting to the main menu — will remain the same as in base game.
  • dependencies makes the current mod be placed higher in load order than the specified dependencies. This will ensure that the mod will overwrite the specified mods’ contents: if there is overlap between the files of this mod and a dependency, this mod’s files will be chosen. This also ensures that the dependencies’ replace_path will not unload any files from this mod and, vise versa, each replace_path in this mod will unload files from the dependencies. Despite its name, the mod which is marked as a dependency is not necessary to be turned on for this mod to get loaded. This is necessary for sub-mods to work correctly.

Game data[edit | edit source]

  • Console commands, useful for debugging mods.
  • Defines, which allow to influence some hardcoded vanilla behaviors
  • Scopes, Triggers, and Effects used for scripting
  • Modifiers, used to influence calculations made by the game
  • Event modding, used to define popups with decisions

Names for in-game items (e.g. the name for research categories or rules like can_create_faction) can be found in the game’s localization folder, inside the localization files.

Checksum[edit | edit source]

The checksum is the 4-letter code that can be seen in the main menu. If the checksum is different, ironman mode won’t give achievements. Alongside that, in multiplayer you can only join servers with the same checksum.

Editing most files will edit the checksum, but not all of them. The files that edit the checksum are

  • Everything in common, history, and events folders
  • In map folder, everything but map/terrain

Thus, translations, SFX, GFX, music, and etc can be changed without preventing the ability to get achievements or join multiplayer with a server that doesn’t have that mod.

Image file formats[edit | edit source]

Use DDS format for images. Most of the files are saved in 8.8.8.8 ARGB, 32 bit unsigned sub-format. Some files (like leader portraits) are saved using the 1.5.5.5 ARGB 16 bit unsigned variant. Event Image can also be of the .tga format. Flags are saved as 32bpp .tga files.

Tools & utilities[edit | edit source]

  • Official Paradox Forum for mods
  • Maya exporter — Clausewitz Maya Exporter to create your own 3D models.
  • Steam Workshop — The place where you can share your creations with other players.

Common mistakes[edit | edit source]

  • Two mods with the same name (Mod fails to load) – This commonly happens when subscribing to one’s own mod on Steam Workshop. If there are two mods with the same name, the game will fail to load the one that was added later, making it appear as if the base game was opened. This is corrected by changing the name of either of the mods.
  • Wrong path (replace_paths apply, yet the mod doesn’t get loaded) – In this case, the needed file to adjust is /Hearts of Iron IV/mod/modname.mod, opened directly within a text editor. There are two primary variations on this issue:
  • Incorrect path – This is commonly the cause if the game displays the filesize of the mod, but doesn’t load it. The mod doesn’t route to the file directly. This can sometimes be a cause of further subfoldering, such as if the mod is located in mod/my_mod/cool_mod, yet the machine-specific .mod file contains path = "mod/my_mod". In this case, the files still exist and get loaded. However, the game, for example, expects focus trees in the /Hearts of Iron IV/common/national_focus/ folder. mod/my_mod/cool_mod/common/national_focus/ gets taken to be /Hearts of Iron IV/cool_mod/common/national_focus/ instead, as path = "mod/my_mod" doesn’t knock off the /cool_mod/ folder. This is corrected simply by adjusting the path to be to the correct folder.
  • Impossible path – The intended folder is correct, yet it’s stated in a way that the game can’t recognise.
One of the ways of doing so is using backslashes for folder separations, such as path = "modmy_mod". This is incorrect, as a single backlash gets taken to be an escape character instead. Using forward slashes as in path = "mod/my_mod" is correct.
Another way of doing so is using special characters in the name, such as path = "C:/Users/Пример кириллицы/Documents/Paradox Interactive/Hearts of Iron IV/mod/my_mod". In this case, a special character is defined as one that takes more than 1 byte to write with UTF-8, not being present in ASCII’s printable characters. This is commonly non-English language folder names, such as diacritics or non-Latin alphabets. In this case, it can be rerouted to a folder that does not contain special characters in the name, such as path = "D:/Hearts of Iron IV modding/my_mod". If the path to the user directory itself contains special characters, it’s better to re-route the entire directory to another folder. To do so, edit the base game’s /Hearts of Iron IV/launcher-settings.json file and change the folder specified under gameDataPath. After doing so, move the user directory’s contents to that folder as to not lose save games and other information. The mod’s path also needs to be adjusted properly. If the user directory is located at an impossible path, the game will also fail to open the error log with debug turned on with a «The system cannot find the path specified» error.
  • Incorrect dependency name (Mod fails to loaded when enabled with the main mod) – If a mod is intended to be a sub-mod to a larger mod or several, it is, in most cases, mandatory to include dependencies = { "Main mod 1" "Main mod 2" }, which will place it higher in the load order. In this case, the name of the mod must be the exact same as in the .mod file of the mod, also showing up in the launcher. This can include special characters (e.g. name = "Main mod – Subtitle" in the main mod will require dependencies = { "Main mod — Subtitle" } in the sub-mod with an en dash rather than a hyphen). For this reason, it’s preferable to copy over the name from the .mod file of the main mod rather than manually retyping it from the launcher: some special charactes may be difficult to notice or to distinguish from other characters.
  • Not copying over mod information entries (Entries such as replace_path fail to apply) – The game keeps the mod’s modname/descriptor.mod file as the information for the mod in general and /Hearts of Iron IV/mod/modname.mod as the information for the mod that gets read for the machine. While the launcher typically attempts to keep the machine-specific file up to date with the general mod information file, it sometimes fails to do so, such as for replace_paths where it succeeds at deleting unneeded entries but not at copying needed ones. In this case, both files must be edited manually for a replace_path to apply. This also may be needed for other entries in the file.
  • Files with similar names (File gets loaded twice) – In this case, «similar» is defined as a pair of files within the same folder that have names made up of different characters, but would be considered as having the same name with case-insensitive checking, such as /Hearts of Iron IV/events/Generic.txt and /Hearts of Iron IV/events/GENERIC.txt. If the mod files contain a file that has a similar name to a base game file, the mod file will get loaded twice. Adjusting the filename to be the exact same as the base game file or entirely distinct will fix this issue. This applies even if the folder that the base game file is in is unloaded with replace_path.

Useful knowledge[edit | edit source]

Large English-speaking modding communities include the HOI4 Modding Coop and the HOI4 Modding Den, which can be joined on Discord. It’s useful to join one or multiple of them, as they contain links to modding resources and you can ask questions regarding modding in them.

settings.txt, located within the user directory also containing the mod folder, can be changed to change the game uses to open files from Microsoft Notepad, if the path to the editor is correct. Here are examples with 2 of frequently used text editors:

Notepad++:

editor="C:\Program Files\Notepad++\notepad++.exe"
editor_postfix=" -n$"

Sublime Text:

editor="C:\Program Files\Sublime Text 3\sublime_text.exe"
editor_postfix=":$:1"

See also[edit | edit source]

  • Mods
  • Getting started with modding forum: 995985
  • How to create a new ship unit in Man the Guns forum: 1157324
  • How to add a new unit — Checklist forum: 947435

Notes[edit | edit source]

^ a: These exceptions that may reasonably be changed within a mod are the following:

  • /Hearts of Iron IV/gfx/flags/ and its subfolders, where the name must follow a strict formatting in order to be automatically loaded for a country.
  • /Hearts of Iron IV/history/countries/, where the first 3 letters assign it to a country.
  • .txt files directly inside of /Hearts of Iron IV/common/ (Most importantly achievements.txt, combat_tactics.txt, and graphicalculturetype.txt)
  • /Hearts of Iron IV/common/countries/colors.txt and /Hearts of Iron IV/common/countries/cosmetic.txt must remain with the same name. The rest are directly linked to in /Hearts of Iron IV/common/country_tags/*.txt files.
  • A variety of items within gfx such as /Hearts of Iron IV/gfx/maparrows/maparrow.txt or /Hearts of Iron IV/gfx/HOI4_icon.bmp. This does not include /Hearts of Iron IV/gfx/loadingscreens (every file within there is loaded regardless of filename) or most font/image files (as they’re loaded by a link within a different file).
  • Files within the /Hearts of Iron IV/map/ and /Hearts of Iron IV/map/terrain/ folders, with the exception of /Hearts of Iron IV/map/strategicregions and those defined within /Hearts of Iron IV/default.map.
  • /Hearts of Iron IV/tutorial/tutorial.txt

Часть I. Создание ивента (события).

Предисловие

Итак, прочитав тему вопросы по моддингу, я выяснил, что множество начинающих мододелов совершенно не имеют понятия о создании ивентов (внутриигрового события). В этой части гайда я постараюсь разъяснить сей процесс.

Необходимый софт

Для комфортного и правильного написания кода ивента, я рекомендую скачать бесплатную программу Notepad++. Она поддерживает смену кодировок, подсвечивает некоторые элементы структуры кода, в общем, необходимая программа для мододела.

Примечание: ссылки даны через сервис сокращения ссылок adfly. Если у вас включен adBlock или аналогичный блокировщик рекламы, могут возникнуть проблемы со скачиванием. Спасибо за понимание.

Notepad++

Спойлер

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Если вы планируете добавлять свои картинки событий, их необходимо перевести в формат .dds (Direct Draw Image). Лучше всего с этим справляется бесплатная программа Paint.net.

Paint.net

Спойлер

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

На этом список необходимых программ закончен.

Начало

Для начала создаем мод (я думаю, все знают как это делается), затем заходим в папку мода (C:usersuserDocumentsParadox Interactivemod%имя мода%) и создаем папку events в корне каталога. Затем создаем пустой текстовый файл с названием, в котором первое слово это тег страны события маленькими буквами, затем нижнее подчеркивание, затем название вашей страны. Пример: ger_Germany, sov_SovietUnion

Заходим в созданный нами файл. Добавляем в самом начале переменную, отвечающую за обнаружение игрой этого фала в дальнейшем:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Я использую исходники моего мода (Extended Asia mod), поэтому у меня в переменной прописано raj. Вы же прописываете тег вашей страны малыми буквами. Пример — ger, sov, rus, usa.

Затем копируем и вставляем туда структуру ивента:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

В данном коде country event обозначает начало и конец ивента, id — номер ивента, title — название, desc — описание, picture — картинка ивента, option — вариант ответа на ивент.

Прописываем номер, название, описание ивента:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Первый ивент всегда имеет номер 1, а название и описание — это приставка к номеру (t или d). Не прописывайте название ивента словами — оно указывается в файлах локализации!

Теперь добавляем картинку события. Открываем папку с игрой (место, куда вы ее установили), заходим в папку gfxevent_pictures и выбираем нужную вам картинку с помощью Paint.net. Затем копируем ее название, открываем файла ивента и записываем в строку picture такой код:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

где picture = GFX_ это обязательная часть кода, а следующее за ней предложение — название вашей картинки.

Если же вам не нравится данные парадоксами картики ивентов, вы вполне можете добавить свою. Для этого создаем в корне мода папку gfx, в ней папку event_pictures, затем копируем в нее любую понравившуюся из файлов игры картинку ивента и меняем в ней изображение на свое. Также необходимо ее переименовать — например, report_event_test_event1. Теперь заходим в файл ивента и пишем там следующее:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Теперь добавим опцию, или вариант ответа на ивент. Допустим, этот ивент отвечает за независимость Индии от англичан. В нем должно быть два варианта ответа — либо смена правительства, либо гражданская война. Вот как это выглядит в коде:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Все предельно просто. Осталось только добавит условие срабатывания события. Делается это через команду trigger:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Триггер вставляется перед опцией. Вот так выглядит весь код:

Войдите или зарегистрируйтесь, чтобы увидеть скрытое содержимое.

Вот так. В следующем гайде поговорим о файлах локализации.

GRAF_RAGE

Интерфейс. Как это работает ?

Для начала надо бы знать пару нюансов:

  1. Полностью изменить или удалить все элементы интерфейса простому разработчику модификаций не получится, так как скрипты интерфейса привязаны к файлам движка игры. Доступ непосредственно к движку Клаузвиц имеют лишь разработчики игры, ну или прошаренные хакеры. Благо, вы можете спрятать ненужные вам элементы, делая их не видимыми, или менять их позицию.
  2. Любой интерфейс подразумевает за собой использование графических редакторов, например, Paint.net, Photoshop и т. д.

Основные файлы и принципы

Основные группы файлов по интерфейсу находятся:

  1. …Hearts of Iron IVinterface (инициализация переменных .gfx и скрипты графических элементов .gui). Этими файлами описываем наши элементы интерфейса, их позицию, функцию, привязываем к расширению экрана и т. д. Открываются с обычным Notepad, Notepad++ и подобными.

Интерфейс Hearts of Iron. Как это работает?, изображение №1

Интерфейс Hearts of Iron. Как это работает?, изображение №1

2. …Hearts of Iron IVgfxinterface (текстуры в .dds формате). Здесь находятся все текстурки интерфейса игры. Именно их и надо редактировать с графическими редакторами.

Интерфейс Hearts of Iron. Как это работает?, изображение №2

Интерфейс Hearts of Iron. Как это работает?, изображение №2

Теперь мы можем редактировать, к примеру, окно выбора стран country_selection_bg.dds

Интерфейс Hearts of Iron. Как это работает?, изображение №3

Интерфейс Hearts of Iron. Как это работает?, изображение №3

Открываем этот файл. Рисуем, копируем, что хотим. Можете соблюдать местоположение всех элементов, как значки, текст и т. п., но это будет вас ограничивать в фантазии. Правда, не придётся играться с .gfx и .gui.

В общем, если кнопки, картинки и текст остается в том же положении и не мешает вам, хватает попросту сохранить файл в ваш мод.

…Hearts of Iron IVmodgfxinterfacecountry_selection_bg.dds

С таким настройками:

8.8.8.8 ARGB 32 bpp цветовой код

8.8.8.8 ARGB 32 bpp цветовой код

Также стоит соблюдать Alpha канал. Эта функция отображает только ту часть рисунка, которая вам необходима

Интерфейс Hearts of Iron. Как это работает?, изображение №5

Интерфейс Hearts of Iron. Как это работает?, изображение №5
Интерфейс Hearts of Iron. Как это работает?, изображение №6
Интерфейс Hearts of Iron. Как это работает?, изображение №6

Что белое — то будет видно, что серое — то прозрачно, что черное — невидимое. Сохраняйте все файлы с альфа каналом (save as > .dds > Normal Map Setting).

Интерфейс Hearts of Iron. Как это работает?, изображение №7

Интерфейс Hearts of Iron. Как это работает?, изображение №7

Всё, у вас первая ваша текстура.

Оригинальный интерфейс

Вы неизбежно захотите своё с блэкджеком и куртизанками, поэтому учимся на примере того же country_selection_bg.dds менять позиции элементов. Для этого находим в каких файлах он прописан. Вы можете открыть все файлы с Notepad++ Hearts of Iron IVinterface и пробить название текстурки в Find.

Интерфейс Hearts of Iron. Как это работает?, изображение №8

Интерфейс Hearts of Iron. Как это работает?, изображение №8
Интерфейс Hearts of Iron. Как это работает?, изображение №9
Интерфейс Hearts of Iron. Как это работает?, изображение №9

Как видим текстура выбора стран прописана в этих файлах.

Интерфейс Hearts of Iron. Как это работает?, изображение №10

Интерфейс Hearts of Iron. Как это работает?, изображение №10

Забираем их к себе в мод и открываем.

…Hearts of Iron IVmodinterface

По сути, .gfx прописываются текстуры, которые используются в интерфейсе. Они обозначаются переменной, которую вы можете привязать к скрипту в файлах .gui.

Интерфейс Hearts of Iron. Как это работает?, изображение №11

Интерфейс Hearts of Iron. Как это работает?, изображение №11

Группа переменных спрайтов, имя переменной GFX_country_selection_bg, местонахождение самого графического файла gfx/interface/country_selection_bg.tga и эффект (допустим блеск, как у фокусов).

Когда вы хотите внедрить что-то новое, не поверху старых, совершенно новую картинку, она должна быть прописана здесь по такому же принципу.

Скрипты в файлах .gui уже интереснее.

Интерфейс Hearts of Iron. Как это работает?, изображение №12

Интерфейс Hearts of Iron. Как это работает?, изображение №12

Контейнер containerWindowType — это вся группа интерфейса, в нашем случае, это окно выбора стран. Видно по названию, gamesetup_interesting_countries_window.

Изучим весь фрагмент:

Спойлер

containerWindowType = { //группа окна
name =»gamesetup_interesting_countries_window»//название
size = { width=1225 height=717 } //резолюция
Orientation = center //привязка к окну, будет в центре
origo = center //привязка к координатам
clipping = no //без вырезанных частей
moveable = yes //можно ли двигать окно? Да.
instantTextBoxType = { //кусок текста
name = «title» //название
position = { x = 435 y = 12 } //позиция текста
textureFile = «» //текстура, ее нет, так как это текст
font = «hoi_24header» //шрифт, на котором написан текст
borderSize = {x = 0 y = 0} //рамка, ее нет
text = «FE_SELECT_COUNTRY» //вызов переменной из локализации, видимый текст
maxWidth = 340 //максимальная длина текста
maxHeight = 30 //максимальная высота
format = centre //текст по центру
}
background = { //дополнительные текстуры на верху основной
name = «single_player_country_bg»
quadTextureSprite =»GFX_country_selection_bg»
}
ButtonType = { //категория кнопки
name = «back_button» //кнопка обратно
position = { x = -158 y = -52 } //ее позиция
quadTextureSprite =»GFX_button_148x34″ //ее текстурка
buttonText = «BACK» //ее текст
buttonFont = «hoi_18mbs» //ее шрифт
Orientation = «CENTER_DOWN» //ее привязка местоположения
clicksound = click_close //звук при нажатии
oversound = ui_menu_over //после нажатия
shortcut = «ESCAPE» //вызов скрипта при нажатии
}

Спойлер

containerWindowType = { //контейнер в контейнере (окно на окне)
name =»countries» //выбор стран
position = { x = 15 y = 45 }
size = { width = -15 height = 120}
gridboxType = { //сетка, функция для разного числа стран, допустим хотите поместить в мод 6 мажорных стран, а позже 8 и т. д.
name =»countries_grid»
position = { x = 0 y = 0 }
size = { width = 100% height = 100% }
slotsize = { width = 150 height = 0 } //размер сетки в 150 пикселей
add_horizontal = yes //добавлять новую страну горизонтально, ванильная настройка, можете менять
max_slots_vertical = 1 //одна полоса
format = «UPPER_LEFT» //привязка слева наверху
}
}

Думаю, по этим фрагментам постепенно начинаете понимать суть. Возможно, вам возник вопрос, что значит эта привязка и ориентация? Может интерфейс гей? (тонкая шутка) Это обозначает местоположение нулевой координаты.

Представьте, вы на тетраде по математике нарисовали оси X и Y, их начало нулевая координата. Наверх и вправо — положительные числа, вниз и влево — отрицательные. Каждое окно привязано к такой координате. Почему? Это сделано из-за разного расширения мониторов пользователей. Если у вас 4К монитор, вам, скорее всего, всё будет отображаться красиво, и все кнопки и текст будет на правильном месте, но на стареньком мониторе 640 на 800 будет выглядеть коряво. По этой причине многие элементы имеют свою относительную систему координат.

Привязка orientation:

  • CENTER (0, 0 в центре экрана)
  • CENTER_DOWN (в центре внизу)
  • CENTER_UP (в центре наверху)
  • UPPER_LEFT (наверху слева)
  • LOWER_LEFT (внизу слева)
  • UPPER_RIGHT (наверху справа)
  • LOWER_RIGHT (внизу справа)

Проще говоря, если у вас size = { width=1225 height=717 } и кнопка Orientation CENTER_DOWN, то нулевое положение такой кнопки в центре внизу (общая координата X=613, Y=0, относительная координата без определения отображается как нулевая). Да, это может путать вас, но есть, как есть. Поиграетесь с этим положением и поймете, как это работает.

Некоторые элементы можно просто удалить. Например, какую-то картинку или текст в глубине двойного контейнера, или спрятать с функцией hide_position, или обозначить координату (X=10000, Y=10000) за расширением экрана (не рекомендую, но так делают).

Создание модов для Hearts of Iron IV — это процесс, который требует некоторых технических знаний и умения работать с редакторами и программами. Однако, с достаточным количеством терпения и желания, пошаговая инструкция и онлайн-ресурсы могут помочь вам создать свой собственный мод в игре.

Шаг 1: Устанавливаем необходимое ПО

Для создания мода для Hearts of Iron IV нужно установить несколько программ и утилит:
— Hearts of Iron IV (конечно же)
— Notepad++ (программа для редактирования текстовых файлов)
— Paint.net или Adobe Photoshop (программа для создания изображений и редактирования)
— HOI4 modding tool — этот инструмент поможет вам создавать основные элементы мода, редактировать локализацию, и добавлять новые страны, технологии, и события в игру.

Шаг 2: Создаем папку мода

Для того, чтобы создать новый мод нужно создать папку с именем мода в папке с модами Hearts of Iron 4, в папке «Мои Документы/Paradox Interactive/Hearts of Iron IV/mod». Название этой папки и будет именем вашего мода.

Шаг 3: Редактируем .mod файл

Создадим файл с расширением .mod в новой папке и используем его для написания информации о моде. Это название мода, описание, версия игры, необходимые зависимости (если есть), а так же категория мода. Содержание файла будет выглядеть так:

name = «Название мода»
path = «mod/название мода»
supported_version = «версия игры»
remote_file_id =
tags = {}

Шаг 4: Настраиваем Локализацию

В моделе нужно настроить локализацию. Локализация — это процесс перевода или адаптации мода для разных языков. Для этого мы создадим папку локализации в папке мода, и внутри папки создадим файлы .yml для каждого языка. Язык чтобы был записан в кодировке UTF-8.

Шаг 5: Создаем графические элементы

Для создания нового интерфейса, иконок, гербов и прочих необходимых графических элементов нужно воспользоваться программой для редактирования графики, например Paint.net, и создать необходимые текстуры. Для загрузки этих текстур используйте папку «gfx», а для вывода их в игре — файлы .gui.

Шаг 6: Редактируем и создаём события

События – мощный инструмент моддинга в игре Hеarts of Iron IV. Они могут добавлять новые страны, изменять мировые события или добавлять новые игровые механики. Создавать и редактировать события нужно с помощью text editor — сохранять файл .txt в папку событий мода. Текст файла должен быть написан с использованием специальной синтаксической конструкции, небольшим тегом, которые позволяют игре понимать, что это за событие и какое ему назначение.

Шаг 7: Создаем новые технологии и единицы

Можно создать новые единицы войск, армейские модели и технологии. Используйте файлы .txt, чтобы создать новые юниты и модели. Небольшой модификатор изменит параметры юнита, такие как количество жизни или скорость движения, а модификатор слово UNIX позволит добавлять новые единицы в страны. После сохранения файлов и добавления их в папку HOI4 моды, нужно добавить технологию через файл .txt и добавить соответствующий файл в папку Technologа.

Шаг 8: Тестируем мод и оптимизируем его

Когда мод готов в теории, мы начинаем с его тестирования в игре. Не все ошибки всегда можно заметить с первого раза, поэтому для тестирования можно и нужно привлекать игроков в beta-версии модов. Если возникла ошибка, в лучшем случае, вы ее сможете исправить, однако в худшем случае, можете выпустить новую версию мода.

Кратко говоря, для создания мода для Hearts of Iron IV нужно изучить синтаксис файлов .txt, настроить локализацию, редактировать .mod файл и загружать графические файлы. Создание мода затратно по времени, но после освоения, может стать очень веселым, захватывающим и награждающим занятием, которое улучшит игру для других игроков.

Понравилась статья? Поделить с друзьями:
  • Руководство для снайпера дота
  • Руководства по эксплуатации джип чероки
  • Руководство по радиосвязи часть 2 новое 2016
  • Должностная инструкция врача косметолога медицинского центра
  • Комплекс при похмелье super um инструкция по применению