Compare commits

...

36 commits

Author SHA1 Message Date
Ralph Sennhauser
53d1ae00f1
Fix deleting last node in spline
The last node needs to have distance "0" to next node. Do the inverse of
when adding nodes.

Also add some basic tests covering this bug.

Fixes: #4659
Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-10 13:57:18 +02:00
Ralph Sennhauser
df72c1aad1
Support scroll-rotate in Atlas
Split mouse wheel scroll handling into horizontal and vertical. Keep
vertical scroll for zooming and use horizontal to rotate around the y
axis replicating the behaviour of the main game.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-10 09:00:07 +02:00
Dunedan
40ab70b804
Inline the pre-commit/action Github action
As the latest version of pre-commit is broken right now
(https://github.com/pre-commit/pre-commit/issues/3737) and the official
pre-commit Github action doesn't allow specifying an older pre-commit
version to use, this inlines the logic of the pre-commit action into our
action.
2026-08-09 07:20:49 +02:00
Stan
f90804c78f
Add macOS hint for game mode.
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
2026-08-07 14:09:25 +02:00
phosit
d6bdf51d83
Remove CStr::FromInt64$
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
For the usecase it's better to use `fmt::format`.
2026-08-06 18:03:05 +02:00
phosit
ae936e8177
Remove CStr::FromUInt
There is `std::to_string` which does the same. For most uses it's better
to use `fmt::format`.
2026-08-06 18:03:05 +02:00
phosit
06e199b12a
Remove CStr::FromInt
There is `std::to_string` which does the same. For most uses it's better
to use `fmt::format`.
2026-08-06 18:03:05 +02:00
ShadowOfHassen
84567e66c2 Fix catafalque aura typos
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-08-06 13:30:42 +02:00
Vladislav Belov
c4e7364802
Removes unused BuildColor4ub from ModelRenderer
We don't need to calculate shading on CPU since we always use shaders.

Refs: a9c27b412b
2026-08-06 11:32:02 +02:00
Vladislav Belov
867bdf318b
Fixes missing material reference in ModelRenderer
Missed in 18a16aa135
2026-08-06 10:31:16 +02:00
Vladislav Belov
e64a138f92
Fixes outdated state on disabling GPU skinning 2026-08-04 23:06:12 +02:00
Vladislav Belov
4a7b7e7df1
Removes smart pointers from ModelRenderer
We don't need to use pointers because we know lifetimes of all
renderers. And its list statically defined. A new renderer should follow
DOD and use a separate submission list with a separate inplace renderer.
2026-08-04 23:06:10 +02:00
Vladislav Belov
fa90ddc8b6
Refactors ModelRenderer and makes it closer to DOD
Separates submitted models and moder renderer and makes relations
explicit. Now it's clear that we don't need separate ModelRenderer and
ModelVertexRenderer.
2026-08-04 23:06:09 +02:00
Vladislav Belov
764a420797
Merges ModelRenderer and ShaderModelRenderer
We use only shaders to render models so we don't need a separate class.

BatchModelRenderer was renamed in 6bc33fe8bd.
m_Renderer became unused in 0346ba1b18.
2026-08-04 23:06:07 +02:00
Vladislav Belov
8a2bb10827
Renames ShaderModelRenderer instances 2026-08-04 23:06:06 +02:00
Vladislav Belov
af9d102126
Removes legacy logic of reused ModelRendererPtr
It became unused in 4a69e9117e.
2026-08-04 23:06:04 +02:00
Ralph Sennhauser
822092fcb4
Fix set camera tooltip in Atlas player section
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
Refs: fe192fe58f
Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-04 17:22:21 +02:00
Ralph Sennhauser
6e79dc2f70
Use dynamic events for Cinema Section
Replace static events with dynamic events and name delete path function
more aptly.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-04 17:04:22 +02:00
Dunedan
6fdcd68172
Update the actions used by the lint workflow
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-08-04 10:09:22 +02:00
Dunedan
e4f4030a5e
Update the actions used by the checkrefs workflow
The workaround for the authentication problems isn't necessary with the
new version of the checkout action anymore.
2026-08-04 10:09:09 +02:00
Ralph Sennhauser
2fb6347125
Delete .already-built file prior to new build
In case the build fails this will allow other Jenkins jobs to restore
the old working state themselves.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-03 20:54:04 +02:00
phosit
7aa756f6a4
Remove line numbers from cppcheck supression list
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
They have to be changed to ofthen when code gets moved.
2026-08-02 14:03:28 +02:00
phosit
e712601602
PreInitGame and InitGame in the Loader
This makes the frame before the simulation starts less stuttery. Doing
it in the Loader also allows to make the progressbar more acurate.
2026-08-02 14:03:28 +02:00
Dunedan
865ca4cd55
Update the pre-commit hooks
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
2026-08-01 16:19:18 +02:00
Dunedan
dcb7cef308
Update Github actions used for pre-commit action 2026-08-01 16:19:03 +02:00
vyordan
71be79791f Use turn_id_t (int32_t) for turn-count across simulation, network and replay
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
CSimulation2 used , CSimulation2Impl mixed /, and
CTurnManager used  for the same turn-count concept, forcing a
static_cast<int64_t> at the one place these types already met
(rejoin-test comparison).

Add  (alias for std::int32_t) in SimulationCommand.h and use
it consistently for every turn counter in CSimulation2/Impl,
CTurnManager and its subclasses (CLocalTurnManager,
CReplayTurnManager), CNetServerTurnManager/CNetClientTurnManager, and
the network wire format (m_Turn in CEndCommandBatchMessage,
CSimulationMessage, CSyncCheckMessage, CSyncErrorMessage, and
m_CurrentTurn in CLoadedGameMessage).

Turn *duration* fields (m_TurnLength, m_CommandDelay,
DEFAULT_TURN_LENGTH, COMMAND_DELAY_SP/MP, SetTurnLength,
GetSavedTurnLength return type) are left as u32 — they're milliseconds,
not a counter, and out of scope here.

Remaining turn_id_t vs size_t comparisons use std::cmp_equal or
explicit casts, matching the existing pattern in Simulation2.cpp.

Fixes #8718
2026-07-31 10:34:20 +02:00
Atrik
9ab89b01c2 Add Langbart to art credits
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-07-30 20:54:19 +02:00
Atrik
dcce6666ae Add missing garrison flag to some houses
Art work by @Langbart

Fixes #6911
2026-07-30 20:54:19 +02:00
Atrik
202bdb133a Add Atrik to art credits 2026-07-30 20:54:19 +02:00
Atrik
46981d2b90 Add missing garrison flag to German houses 2026-07-30 20:54:19 +02:00
Ralph Sennhauser
49c887b7ca
Don't nest Paths in Common settings
Doesn't make sense to have the Paths StaticBox inside the Common
settings StaticBox so make it a top-level item as well.

While at it dissolve nested constructors to make the creation of the
widgets more readable.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-07-30 18:43:24 +02:00
Atrik
91a37e32f6 Sort units spatially for freehand selection
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-07-30 17:19:39 +02:00
Atrik
139b08fe6d Add tests for SelectionBoxTargeting 2026-07-30 17:19:39 +02:00
Atrik
dc6da217fd Enable using SelectionBox for targeting
Introduce a new  input, a command handler and adapt
UnitAI to handle arrays of targets in a single order
2026-07-30 17:19:39 +02:00
Atrik
e41dd2d3a4 Add Math.clamp utility function 2026-07-30 17:19:39 +02:00
phosit
c7953026dd
Use switchPage in autostart
Autostart used `OpenChildPage` to open the loading page. Because it's
started as child page the program doesn't end when closing it.
2026-07-30 12:36:51 +02:00
111 changed files with 1882 additions and 813 deletions

View file

@ -11,7 +11,7 @@ jobs:
lfscheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Fetch the base branch
run: git fetch origin ${{ env.BASE_SHA }}
@ -24,27 +24,14 @@ jobs:
env:
GIT_LFS_SKIP_SMUDGE: "1"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.11"
- name: Add remote fork origin for LFS
run: |
PR_REPO="${{ gitea.event.pull_request.head.repo.full_name || gitea.repository }}"
git remote add ${{ gitea.actor }} https://gitea.wildfiregames.com/${PR_REPO}.git
- name: Workaround for authentication problem with LFS
# https://gitea.com/gitea/act_runner/issues/164
run: |
git config --local \
http.${{ gitea.server_url }}/${{ gitea.repository }}.git/info/lfs/objects/.extraheader ''
PR_REPO="${{ gitea.event.pull_request.head.repo.full_name || gitea.repository }}"
EXTRAHEADER="$(git config --get --local http.${{ gitea.server_url }}/.extraheader)"
git config --local \
http.${{ gitea.server_url }}/${PR_REPO}.git/info/lfs/objects/batch.extraheader \
'${EXTRAHEADER}'
git config --local \
http.${{ gitea.server_url }}/${PR_REPO}.git/info/lfs/objects/.extraheader ''
- name: Download necessary LFS assets
shell: sh {0}
run: |

View file

@ -12,7 +12,7 @@ jobs:
cppcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
# cache only works for items in workspace, so configure apt to allow for caching.
- name: Setup apt cache locations
@ -26,7 +26,7 @@ jobs:
- name: Cache apt pkg db and and deb files
id: apt-cache
uses: actions/cache@v4
uses: actions/cache@v6
with:
path: |
apt-cache
@ -49,11 +49,11 @@ jobs:
copyright:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
with:
fetch-depth: 100
- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: "3.11"
@ -66,10 +66,10 @@ jobs:
jenkinsfiles:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v7
with:
node-version: '20'

View file

@ -3,22 +3,27 @@ name: pre-commit
on:
- push
- pull_request
env:
PRE_COMMIT_VERSION: 4.6.0
jobs:
build:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.11"
- id: restore-pip-cache
uses: actions/cache/restore@v4
- uses: actions/cache@v6
with:
key: pip-cache-v1-${{ github.workflow }}
key: pip-cache-v1-${{github.workflow}}-${{env.pythonLocation}}-${{env.PRE_COMMIT_VERSION}}
path: ~/.cache/pip
- uses: pre-commit/action@v3.0.1
- uses: actions/cache/save@v4
if: steps.restore-pip-cache.outcome == 'success'
- run: python -m pip install pre-commit=="${{ env.PRE_COMMIT_VERSION }}"
shell: bash
- run: python -m pip freeze --local
shell: bash
- uses: actions/cache@v6
with:
key: pip-cache-v1-${{ github.workflow }}
path: ~/.cache/pip
path: ~/.cache/pre-commit
key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
- run: pre-commit run --show-diff-on-failure --color=always --all-files
shell: bash

View file

@ -34,7 +34,7 @@ repos:
\.patch$
)
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.12.9
rev: v0.16.0
hooks:
- id: ruff-check
args:
@ -56,7 +56,7 @@ repos:
files: ^binaries/
exclude: (^binaries/data/mods/(mod|public)/art/.*\.xml|\.dae$)
- repo: https://github.com/scop/pre-commit-shfmt
rev: v3.12.0-2
rev: v3.13.1-1
hooks:
- id: shfmt
args:
@ -67,7 +67,7 @@ repos:
hooks:
- id: shellcheck
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.45.0
rev: v0.47.0
hooks:
- id: markdownlint
language_version: 22.14.0
@ -77,13 +77,13 @@ repos:
^source/third_party/
)
- repo: https://github.com/adrienverge/yamllint
rev: v1.37.1
rev: v1.38.0
hooks:
- id: yamllint
args:
- --strict
- repo: https://github.com/eslint/eslint
rev: v9.39.2
rev: v10.8.0
hooks:
- id: eslint
language_version: 22.14.0

View file

@ -51,6 +51,18 @@
</textures>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_achaemenids.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -33,6 +33,18 @@
</textures>
</variant>
</group>
<group>
<variant frequency="1" name="ungarrisoned" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_celt.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -53,6 +53,18 @@
</textures>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_celt.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -134,6 +134,20 @@
</props>
</variant>
</group>
<group>
<variant frequency="1" name="ungarrisoned" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_germ.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -106,6 +106,18 @@
</props>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_iber.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -47,6 +47,18 @@
</textures>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_rome.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -43,6 +43,18 @@
</textures>
</variant>
</group>
<group>
<variant frequency="1" name="ungarrisoned" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_seleucids.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/sele/light_damage.xml"/>

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:995da95e21261ae0a2718baee69d76ae5f6823d21eaefaa708a89651f2099bb0
size 586243
oid sha256:ed243a229225ec51ee090588a63307cbd2efedecca06f4f1a0922a4d51ee3967
size 586427

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d8e022a3ac132a32061583743d1322fc8792cdd6e7be57857547a8ed3cefbed6
size 525300
oid sha256:3ce649aa943771357d7c19f48294af719c50ca14178c32be60992f17845d685d
size 525483

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:21971f20f5567f820e0f3fffdd21015e2a5ffaee309be7b6efc38d3fc56aecd3
size 503936
oid sha256:d1d867c2e9f3db233847da547c466325ba9f0a9e7478175281f3538cbb694709
size 504112

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:3c37b1b7f12a429cd07873d0fdb7cc8692f6578b3e5320a6be0e68420fb4688e
size 780868
oid sha256:cc9c95992889a4c2930a39bd20f7c86b73f7c7ddb3b36492650afae2ae424641
size 781051

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1230a92373c4e4684f791594efb35bb7d6c091377a11bd8f0daafd13816d04ec
size 56755
oid sha256:6779d6ca2067d6dd5594b3d2e5ef82d08de97ad058ce7084eb0bf8ae3290f4c2
size 56953

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:30a395c3b5a50214a689abe968ad15edb60212c3ea14041a2edc07295a4462c6
size 45317
oid sha256:9e6aca91d66df31b5820f39025c57937ce6a1593199b8a068722fdec5b0675f6
size 45523

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:ce554ad452cf75bd4dbb9da5de9830309a1dccf72f72f6a74475078af7f0e1c4
size 42851
oid sha256:07013561c7e46b020acbd03d4f371300c38d3e364c99a1e7bbcf7467aa8a34e6
size 43041

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:60f0614c1092395065c4ba8fe6bed64da873d38c579c9cbc400e9a9b8f30f3a8
size 272099
oid sha256:1416efa429cd64471d50e969c43ee723382c031c676414433f8fcd58176cfa77
size 272274

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c6e7d6264d7b3e03466bf1de58ab366a023120c6f78142aebc6570218a4803d9
size 274339
oid sha256:9f9e6debd5f2a9659e19e74b5826d3488167edb9a897ae1ed6e4db10742d94e8
size 274543

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:0624fc07116aa70c14527457fced3afcf7b36df1535bbf10250455e6254aeed6
size 372821
oid sha256:091d68b7800d9141e87ba8aaf0fa93c5bc7d260dd459774075de610ca34855e2
size 372997

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:6ef199b28b9d9ef19e0817b189d9e6f1e2f9861ca211890b8d714f9fe05f5c61
size 420601
oid sha256:c1413de5371443f1249d87fa40a821c880c749513a0347d9128a99472bec7b33
size 420808

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:adf219c08e65bd7a149726d325b6f2b4fd67effc3dd1bc211c3163774ac8308e
size 201143
oid sha256:8aba3f3dc5a909ddadd9af5e7abfe9094f55ed6c97b39e7f97b09dc1cb951f4d
size 201315

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f8c688df60c4880dc92b6898728d4cef443c86831a2a2e87e61dd44661b58240
size 205000
oid sha256:0c3298efebf687a07d4693d9014c51e1e870e95fb9d9024c9126b40adfec75a5
size 205172

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:9d86be00b7e911108e6666422a56eb061a996e6cf0bfe489d6c99f84be752444
size 216525
oid sha256:b97f6dff13f4639e746e1ce79c120169bccb2e09d4507dc900075cf85e788590
size 216697

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:5e258d0b3a7b5c3fe2275c2816c636b7478ee1051df31a2cbe2f516465c692f9
size 239166
oid sha256:8d764a2d5a712f53f08560504f6841ed00b5268fea2a283d2d5254d57ce1df76
size 239339

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:82ff53473c25d6e17aeb97f795b543df3ec1c423e8ecb8398d0d014beac57f4e
size 101895
oid sha256:dccc1521e6e626e75ac2f05d2c8b2c2963ee751da08a9e819e4c28954b19f01a
size 102099

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2377bddedc6251acbe8f03bf1820d368b21cbf88fc2783695ff31036af8ed4e3
size 82812
oid sha256:ae1042461639bca3d3d73fb3e723ca404c8a897ee0e2ad417af1eebb5849d23f
size 83027

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:b5f1530adecb42af05b6b81719a5c4d00fa06a5eff33f50eda8312ce2e0fcd5f
size 77866
oid sha256:b71b8848a0a2e503adbff9c1e09c06c1e76e16537f38af5b35395a04f11b365a
size 78066

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c393e007e24473c1332c7d0c3a8093e0b542974da00b51b853ee413e45818ade
size 91109
oid sha256:256b3864edc754955814d5eec113e73fded49525d2e855a1171a4e4b495ffcc4
size 91304

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e8fb0f356f48284704d81b601c7947f32e91995757e8c2fc390ecaf772fbd950
size 84604
oid sha256:4ef0415cce15f4d1ff4e342c23a995ee5081d21b7f84eb6c19fb89c1d63f84a7
size 84789

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7c2b0d0a461535e0802d2a07395afb4546515ef4d3ccc3eab18d55a0993bc165
size 184407
oid sha256:2ab540ad518de662ba9a4dbe4d0d0590b6ee0b771bc482073296c949ee33d571
size 184610

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:828e2e63b9686a601b3641be10f26e3b099ced5b8dc8d453ab94d41270f22b39
size 213385
oid sha256:39a6a575b8bbb0f82ed8cf4056e0df932a59fd6e3343005625b3b76644c6879c
size 213561

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4825c81a245ddae5637f3b2dee78f7749e27a48d2efa244bc95af075ddabcd1a
size 144598
oid sha256:93341f17ad185e28ce62a533f1db457aec4b69bb2f67c98e4b89e4bcf9503b6a
size 144784

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:427f9512af696afaae0721374a86ceb0e1432602013cb3dde818bfcd2791c163
size 212264
oid sha256:dc27dba302816891bb8f33bc65d9d68b2b330f946256aa966e5d684714af9fe2
size 212447

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:19ca2828e5e6b99065d3d901c1a90f1b73df065dc94b3a4b76b4e5804890c137
size 349847
oid sha256:270fe9095c3894fb448cb91668ad48d886088006c689f0efa148e8a78a3de043
size 350053

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:57039fff36fbba71de79b89614fea988a98bdc85b2bdc5ef88ce3a632da95a55
size 340693
oid sha256:977b2ffb5dc9cf0364d125f0b3dd17e1fb0cd482b5c96fbf7c61b6e6a030db86
size 340906

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:221eeca4ee2e46023d346e80c7a3b4b3852699e0c193e31fa58e0619e858f7a2
size 272252
oid sha256:f177172ef923455050064af60377f2e1b171ff4ec72fa9aa5fdc5c4c28000550
size 272435

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:afc01d8e7e7efc988b2f78b58cfb6b48b5453b8786609e9ce5db38bc617a7984
size 279942
oid sha256:acdaaf09848dc5cb7cf207c7bb535865aa4199a5a50609ca3b632ce5d88d95a2
size 280139

View file

@ -330,3 +330,20 @@ Math.euclidDistance3D = function(x1, y1, z1, x2, y2, z2)
{
return Math.sqrt(Math.euclidDistance3DSquared(x1, y1, z1, x2, y2, z2));
};
/**
* Clamps a value between a minimum and maximum range.
*
* @param {number} value - The value to clamp
* @param {number} min - Minimum allowed value
* @param {number} max - Maximum allowed value
* @returns {number} The clamped value (min <= result <= max)
*/
Math.clamp = function(value, min, max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
};

View file

@ -442,3 +442,17 @@ Vector3D.div = function(v, f)
{
return new Vector3D(v.x / f, v.y / f, v.z / f);
};
/**
* Linear interpolation between this vector and another.
* @param {Vector2D} v - The target vector.
* @param {number} t - Interpolation factor (0 = this, 1 = v).
* @returns {Vector2D} A new vector at the interpolated position.
*/
Vector2D.prototype.lerp = function(v, t)
{
return new Vector2D(
this.x + (v.x - this.x) * t,
this.y + (v.y - this.y) * t
);
};

View file

@ -72,6 +72,7 @@
"List": [
{ "nick": "Alexandermb", "name": "Daniel Morgado" },
{ "nick": "Athos" },
{ "nick": "Atrik" },
{ "nick": "Basshunter", "name": "Sebastián Gómez" },
{ "nick": "BigTiger", "name": "Nathanael P. Moore" },
{ "nick": "Brightgalrs", "name": "Robert D. Schultz" },
@ -80,6 +81,7 @@
{ "nick": "Enrique", "name": "Enrique Keykens Espolio" },
{ "nick": "Gen.Kenobi", "name": "Daniel Schubert" },
{ "nick": "Historicity", "name": "Shane" },
{ "nick": "Langbart" },
{ "nick": "Leyto", "name": "Valentin Levalet" },
{ "nick": "LordGood", "name": "Johnathan B. Good" },
{ "nick": "m7600" },

View file

@ -507,6 +507,49 @@ var unitFilters = {
}
};
// Choose, inside a list of entities, which ones are targetable foes for boxtargeting.
// We also filter out entities that aren't visible, or low priority like livestocks
function getTargetableEntities(ents)
{
const player = g_ViewedPlayer;
const simState = GetSimState();
const isEnemy = simState.players[player].isEnemy;
// Filter valid target candidates
const candidates = ents.filter(entity =>
{
const entState = GetEntityState(entity);
return entState &&
unitFilters.isUnit(entity) &&
entState.visibility != "hidden";
});
// Enemy players
const enemyPlayers = candidates.filter(entity =>
{
const entState = GetEntityState(entity);
return isEnemy[entState.player] && entState.player !== 0 && !hasClass(entState, "Domestic");
});
if (enemyPlayers.length > 0)
return enemyPlayers;
// Gaia
const gaiaUnits = candidates.filter(entity =>
{
const entState = GetEntityState(entity);
return entState.player === 0;
});
if (gaiaUnits.length > 0)
return gaiaUnits;
// Domestic animals
return candidates.filter(entity =>
{
const entState = GetEntityState(entity);
return hasClass(entState, "Domestic");
});
}
// Choose, inside a list of entities, which ones will be selected.
// We may use several entity filters, until one returns at least one element.
function getPreferredEntities(ents)
@ -572,16 +615,19 @@ function handleInputBeforeGui(ev, hoveredObject)
case INPUT_BANDBOXING:
{
const bandbox = Engine.GetGUIObjectByName("bandbox");
const isAttackMode = Engine.HotkeyIsPressed("session.attack") && !g_IsObserver;
switch (ev.type)
{
case "mousemotion":
{
const rect = updateBandbox(bandbox, ev, false);
const ents = Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], g_ViewedPlayer);
const preferredEntities = getPreferredEntities(ents);
g_Selection.setHighlightList(preferredEntities);
const player = isAttackMode ? -1 : g_ViewedPlayer;
const ents = Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], player);
const highlightEntities = isAttackMode ? getTargetableEntities(ents) : getPreferredEntities(ents);
g_Selection.setHighlightList(highlightEntities);
return false;
}
@ -589,6 +635,30 @@ function handleInputBeforeGui(ev, hoveredObject)
if (ev.button == SDL_BUTTON_LEFT)
{
const rect = updateBandbox(bandbox, ev, true);
if (isAttackMode)
{
// Box attack behavior
const ents = Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], -1);
// Filter to only enemy units
const enemyUnits = getTargetableEntities(ents);
// Get currently selected friendly units
const selectedUnits = g_Selection.toList();
if (selectedUnits.length && enemyUnits.length)
{
// Sort entities by position
const sortedCombattants = sortEntitiesForEngagement(selectedUnits, enemyUnits);
// Distribute attack orders
distributeAttackOrders(sortedCombattants.attackers, sortedCombattants.targets);
}
g_Selection.setHighlightList([]);
inputState = INPUT_NORMAL;
return true;
}
const ents = getPreferredEntities(Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], g_ViewedPlayer));
g_Selection.setHighlightList([]);
@ -1371,6 +1441,7 @@ function positionUnitsFreehandSelectionMouseUp(ev)
for (let i = 1; i < inputLine.length; ++i)
lengthOfLine += inputLine[i].distanceTo(inputLine[i - 1]);
// Filter units that can move
const selection = g_Selection.filter(ent => !!GetEntityState(ent).unitAI).sort((a, b) => a - b);
// Checking the line for a minimum length to save performance.
@ -1380,39 +1451,43 @@ function positionUnitsFreehandSelectionMouseUp(ev)
return !!action && doAction(action, ev);
}
// Even distribution of the units on the line.
let p0 = inputLine[0];
let entityDistribution = [p0];
const distanceBetweenEnts = lengthOfLine / (selection.length - 1);
let freeDist = -distanceBetweenEnts;
// Sort units by their projection onto the line direction (parallel sorting)
const sortedSelection = sortEntitiesAlongLine(selection, inputLine[0], inputLine[inputLine.length - 1], true);
for (let i = 1; i < inputLine.length; ++i)
const selectionCount = sortedSelection.length;
const targetPositions = [];
// Distribute units evenly along the polyline
for (let i = 0; i < selectionCount; ++i)
{
const p1 = inputLine[i];
freeDist += inputLine[i - 1].distanceTo(p1);
const t = i / (selectionCount - 1);
const targetDistance = t * lengthOfLine;
while (freeDist >= 0)
let accumulated = 0;
let targetPoint = inputLine[0];
for (let j = 1; j < inputLine.length; ++j)
{
p0 = Vector2D.sub(p0, p1).normalize().mult(freeDist).add(p1);
entityDistribution.push(p0);
freeDist -= distanceBetweenEnts;
const segStart = inputLine[j - 1];
const segEnd = inputLine[j];
const segLength = segEnd.distanceTo(segStart);
if (accumulated + segLength >= targetDistance)
{
// Interpolate within this segment
const remaining = targetDistance - accumulated;
const frac = remaining / segLength;
targetPoint = segStart.lerp(segEnd, frac);
break;
}
accumulated += segLength;
}
targetPositions.push(targetPoint);
}
// Rounding errors can lead to missing or too many points.
entityDistribution = entityDistribution.slice(0, selection.length);
entityDistribution = entityDistribution.concat(new Array(selection.length - entityDistribution.length).fill(inputLine[inputLine.length - 1]));
if (Vector2D.from3D(GetEntityState(selection[0]).position).distanceTo(entityDistribution[0]) +
Vector2D.from3D(GetEntityState(selection[selection.length - 1]).position).distanceTo(entityDistribution[selection.length - 1]) >
Vector2D.from3D(GetEntityState(selection[0]).position).distanceTo(entityDistribution[selection.length - 1]) +
Vector2D.from3D(GetEntityState(selection[selection.length - 1]).position).distanceTo(entityDistribution[0]))
entityDistribution.reverse();
Engine.PostNetworkCommand({
"type": isAttackMovePressed() ? "attack-walk-custom" : "walk-custom",
"entities": selection,
"targetPositions": entityDistribution.map(pos => pos.toFixed(2)),
"entities": sortedSelection,
"targetPositions": targetPositions.map(pos => pos.toFixed(2)),
"targetClasses": Engine.HotkeyIsPressed("session.attackmoveUnit") ? { "attack": ["Unit"] } : { "attack": ["Unit", "Structure"] },
"queued": Engine.HotkeyIsPressed("session.queue"),
"pushFront": Engine.HotkeyIsPressed("session.pushorderfront"),
@ -1420,9 +1495,10 @@ function positionUnitsFreehandSelectionMouseUp(ev)
});
// Add target markers with a minimum distance of 5 to each other.
const entitiesBetweenMarker = Math.ceil(5 / distanceBetweenEnts);
for (let i = 0; i < entityDistribution.length; i += entitiesBetweenMarker)
DrawTargetMarker({ "x": entityDistribution[i].x, "z": entityDistribution[i].y });
const stepDistance = lengthOfLine / (selectionCount - 1);
const entitiesBetweenMarker = Math.max(1, Math.ceil(5 / stepDistance));
for (let i = 0; i < targetPositions.length; i += entitiesBetweenMarker)
DrawTargetMarker({ "x": targetPositions[i].x, "z": targetPositions[i].y });
Engine.GuiInterfaceCall("PlaySound", {
"name": "order_walk",
@ -1929,3 +2005,108 @@ function clearSelection()
g_Selection.reset();
preSelectedAction = ACTION_NONE;
}
function distributeAttackOrders(attackers, targets)
{
if (targets.length < 1)
return;
// Play attack sounds from a sample of units in selection
const soundCount = Math.min(3, attackers.length);
for (let i = 0; i < soundCount; i++)
{
const t = soundCount === 1 ? 0 : i / (soundCount - 1);
const attackerIndex = Math.floor(t * (attackers.length - 1));
setTimeout(() =>
{
Engine.GuiInterfaceCall("PlaySound", {
"name": "order_attack",
"entity": attackers[attackerIndex]
});
}, i * 180);
}
Engine.PostNetworkCommand({
"type": "attack-group",
"entities": attackers,
"targets": targets,
"queued": Engine.HotkeyIsPressed("session.queue"),
"allowCapture": false
});
}
/**
* Sorts attackers and targets for left-to-right engagement across the battle line.
*
* Entities are sorted by their perpendicular distance to the line connecting the
* two army centers, creating natural pairings across the battle front.
*
* @param {number[]} attackers - Array of attacking entity IDs.
* @param {number[]} targets - Array of target entity IDs.
* @returns {Object} { attackers: number[], targets: number[] } - Both arrays sorted
* for cross-line engagement (targets automatically reversed).
*/
function sortEntitiesForEngagement(attackers, targets)
{
const getPosition = (id) => GetEntityState(id).position;
const computeAveragePosition = (entities) =>
{
if (entities.length === 0) return new Vector2D(0, 0);
const vectors = entities.map(id => Vector2D.from3D(getPosition(id)));
return Vector2D.average(vectors);
};
// Calculate the axis of engagement - the line between the groups' average positions
const avgAttackers = computeAveragePosition(attackers);
const avgTargets = computeAveragePosition(targets);
// Sort each group by perpendicular distance to the engagement line
const sortedAttackers = sortEntitiesAlongLine(attackers, avgAttackers, avgTargets);
const sortedTargets = sortEntitiesAlongLine(targets, avgAttackers, avgTargets);
// Reverse targets so the leftmost attacker pairs with leftmost target
return {
"attackers": sortedAttackers,
"targets": sortedTargets.reverse()
};
}
/**
* Sorts entity IDs by their projection onto a line's direction or perpendicular axis.
*
* @param {number[]} entities - Array of entity IDs.
* @param {Vector2D} lineStart - Start point of the reference line.
* @param {Vector2D} lineEnd - End point of the reference line.
* @param {boolean} sortByDirection - If true, sort by parallel projection (along line);
* If false, sort by perpendicular distance (default).
* @returns {number[]} Sorted entity IDs.
*/
function sortEntitiesAlongLine(entities, lineStart, lineEnd, sortByDirection = false)
{
const dir = lineEnd.sub(lineStart);
const length = dir.length();
if (length === 0)
return entities.slice();
// Choose basis vector: either parallel or perpendicular to the line
let basis;
if (sortByDirection)
basis = dir.mult(1 / length); // Unit direction vector
else
basis = new Vector2D(-dir.y, dir.x).normalize(); // Perpendicular
const withCoord = entities.map(id =>
{
const pos = GetEntityState(id).position;
const point2D = Vector2D.from3D(pos);
const rel = point2D.sub(lineStart);
const coord = rel.dot(basis); // Project onto basis vector
return { id, coord };
});
// Sort by that coordinate
withCoord.sort((a, b) => a.coord - b.coord);
return withCoord.map(item => item.id);
}

View file

@ -424,10 +424,42 @@ UnitAI.prototype.UnitFsmSpec = {
"Order.Attack": function(msg)
{
const type = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture);
if (!type)
return this.FinishOrder();
// Check if this is a group attack
const isGroupAttack = !!msg.data.targetArray;
// For group attacks with invalid initial target, find one from the array
if (isGroupAttack && (!msg.data.target || msg.data.target === INVALID_ENTITY))
{
if (!this.FindAndSetNextTarget(msg.data))
{
this.FinishOrder();
return ACCEPT_ORDER;
}
}
// Get the attack type for the current target
const type = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture);
if (!type)
{
// Current target can't be attacked
if (isGroupAttack)
{
if (this.FindAndSetNextTarget(msg.data))
{
msg.data.attackType = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture);
if (msg.data.attackType)
{
this.SetNextState("INDIVIDUAL.COMBAT.ATTACKING");
return ACCEPT_ORDER;
}
}
}
this.FinishOrder();
return ACCEPT_ORDER;
}
// Set attackType before range check
msg.data.attackType = type;
this.RememberTargetPosition();
@ -1366,6 +1398,12 @@ UnitAI.prototype.UnitFsmSpec = {
// Wait for individual members to finish
"enter": function(msg)
{
if (this.order.data.targetArray)
{
// For group attacks, we're done once we distributed targets
this.FinishOrder();
return true;
}
const target = this.order.data.target;
if (!this.CheckFormationTargetAttackRange(target))
{
@ -1602,6 +1640,26 @@ UnitAI.prototype.UnitFsmSpec = {
"INDIVIDUAL": {
"Attacked": function(msg)
{
// First, check if we have a group attack order and the attacker is in our target array
if (this.order?.type === "Attack" &&
this.order.data?.targetArray?.includes(msg.data.attacker))
{
// Switch to attack the entity that's attacking us
this.order.data.target = msg.data.attacker;
this.order.data.attackType = this.GetBestAttackAgainst(msg.data.attacker, this.order.data.allowCapture);
// Update the current target index
const currentIndex = this.order.data.targetArray.indexOf(msg.data.attacker);
if (currentIndex !== -1)
this.order.data.currentTargetIndex = currentIndex;
// Make sure we're in the right state to handle this
const currentState = this.GetCurrentState();
if (currentState === "INDIVIDUAL.IDLE" || currentState === "INDIVIDUAL.WALKING")
this.SetNextState("INDIVIDUAL.COMBAT.APPROACHING");
return;
}
if (this.GetStance().targetAttackersAlways || !this.order || !this.order.data || !this.order.data.force)
this.RespondToTargetedEntities([msg.data.attacker]);
},
@ -2150,6 +2208,35 @@ UnitAI.prototype.UnitFsmSpec = {
"Attacked": function(msg)
{
// Check if we're doing a group attack and the attacker is in our target array
if (!this.order.data.targetArray ||
!this.order.data.targetArray.includes(msg.data.attacker) ||
msg.data.attacker === this.order.data.target)
return;
// Switch to attack the entity that's attacking us
this.order.data.target = msg.data.attacker;
this.order.data.attackType = this.GetBestAttackAgainst(msg.data.attacker, this.order.data.allowCapture);
// Update the current target index
const currentIndex = this.order.data.targetArray.indexOf(msg.data.attacker);
if (currentIndex !== -1)
this.order.data.currentTargetIndex = currentIndex;
// Re-evaluate our approach to the new target
if (this.CheckTargetAttackRange(this.order.data.target, this.order.data.attackType))
{
if (this.CanUnpack())
{
this.PushOrderFront("Unpack", { "force": true });
return;
}
this.SetNextState("ATTACKING");
}
// Continue approaching the new target
else if (!this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType))
this.FinishOrder();
// If we're already in combat mode, ignore anyone else who's attacking us
// unless it's a melee attack since they may be blocking our way to the target
if (msg.data.type == "Melee" && (this.GetStance().targetAttackersAlways || !this.order.data.force))
@ -2209,7 +2296,23 @@ UnitAI.prototype.UnitFsmSpec = {
"MovementUpdate": function(msg)
{
if (msg.likelyFailure)
if (!msg.likelyFailure)
{
if (!this.CheckTargetAttackRange(this.order.data.target, this.order.data.attackType))
return;
if (this.CanUnpack())
{
this.PushOrderFront("Unpack", { "force": true });
return;
}
this.SetNextState("ATTACKING");
return;
}
// For group attacks, try next target instead of moving to last position
if (!this.order.data.targetArray || this.order.data.currentTargetIndex === undefined)
{
// This also handles hunting.
if (this.orderQueue.length > 1)
@ -2217,11 +2320,13 @@ UnitAI.prototype.UnitFsmSpec = {
this.FinishOrder();
return;
}
else if (!this.order.data.force || !this.order.data.lastPos)
if (!this.order.data.force || !this.order.data.lastPos)
{
this.SetNextState("COMBAT.FINDINGNEWTARGET");
return;
}
// If the order was forced, try moving to the target position,
// under the assumption that this is desirable if the target
// was somewhat far away - we'll likely end up closer to where
@ -2234,21 +2339,30 @@ UnitAI.prototype.UnitFsmSpec = {
return;
}
if (this.CheckTargetAttackRange(this.order.data.target, this.order.data.attackType))
// Handle group attack case
// Remove current unreachable target from array
const currentIndex = this.order.data.currentTargetIndex;
if (currentIndex < this.order.data.targetArray.length)
this.order.data.targetArray.splice(currentIndex, 1);
// Try to find next valid target
if (this.order.data.targetArray.length === 0 || !this.FindAndSetNextTarget(this.order.data))
{
if (this.CanUnpack())
{
this.PushOrderFront("Unpack", { "force": true });
return;
}
this.SetNextState("ATTACKING");
this.FinishOrder();
return;
}
else if (msg.likelySuccess)
// Try moving again,
// attack range uses a height-related formula and our actual max range might have changed.
if (!this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType))
this.FinishOrder();
},
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
// Try approaching the new target
if (this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType))
return;
// If we can't approach the new target either, remove it and continue
this.order.data.targetArray.splice(this.order.data.currentTargetIndex, 1);
if (this.order.data.targetArray.length === 0)
this.FinishOrder();
}
},
"ATTACKING": {
@ -2322,6 +2436,18 @@ UnitAI.prototype.UnitFsmSpec = {
"OutOfRange": function()
{
// Check if the target is garrisoned or in a turret (turreted entities cannot be attacked by melee units)
const cmpTargetUnitAI = Engine.QueryInterface(this.order.data.target, IID_UnitAI);
const isTargetGarrisoned = cmpTargetUnitAI && cmpTargetUnitAI.isGarrisoned;
const isTargetInTurret = cmpTargetUnitAI && cmpTargetUnitAI.IsTurret();
// If target is garrisoned or in a turret (and we're not ranged), treat as invalid
if (isTargetGarrisoned || (isTargetInTurret && this.order.data.attackType !== "Ranged"))
{
this.ProcessMessage("TargetInvalidated");
return;
}
if (this.ShouldChaseTargetedEntity(this.order.data.target, this.order.data.force))
{
if (this.CanPack())
@ -2332,11 +2458,53 @@ UnitAI.prototype.UnitFsmSpec = {
this.SetNextState("CHASING");
return;
}
// For group attacks, try next target instead of finding new ones
if (this.order.data.targetArray && this.order.data.currentTargetIndex !== undefined)
{
const currentIndex = this.order.data.currentTargetIndex;
// Remove current target since it's out of range and we can't chase
this.order.data.targetArray.splice(currentIndex, 1);
// Try to find next valid target in sequence
if (this.order.data.targetArray.length > 0 && this.FindAndSetNextTarget(this.order.data))
{
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
this.SetNextState("INDIVIDUAL.COMBAT.ATTACKING");
return;
}
}
this.SetNextState("FINDINGNEWTARGET");
},
"TargetInvalidated": function()
{
// For group attacks, remove current target and move to next in array
if (this.order.data.targetArray && this.order.data.currentTargetIndex !== undefined)
{
// Remove the current target from the array
const currentIndex = this.order.data.currentTargetIndex;
if (currentIndex < this.order.data.targetArray.length)
{
this.order.data.targetArray.splice(currentIndex, 1);
// If we have more targets, continue with the next one
if (this.order.data.targetArray.length > 0)
{
// Try to find next valid target in sequence
if (this.FindAndSetNextTarget(this.order.data))
{
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
this.SetNextState("INDIVIDUAL.COMBAT.ATTACKING");
return;
}
}
}
}
// No more targets or not a group attack - use original behavior
this.SetNextState("FINDINGNEWTARGET");
},
@ -2360,7 +2528,26 @@ UnitAI.prototype.UnitFsmSpec = {
"enter": function()
{
// Check if we are attacking a formation.
// First, check if we have pending targets in a group attack
if (this.order.data.targetArray && this.order.data.currentTargetIndex !== undefined)
{
// Try to find next valid target from the array
if (this.FindAndSetNextTarget(this.order.data))
{
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
this.SetNextState("COMBAT.ATTACKING");
return true;
}
// No valid targets in array - clean up and continue with normal behavior
this.order.data.targetArray = [];
this.order.data.currentTargetIndex = undefined;
}
if (!this.order.data.target)
return false;
// Try to find the formation the target was a part of.
let cmpFormation = Engine.QueryInterface(this.order.data.target, IID_Formation);
if (cmpFormation)
this.order.data.formationTarget = this.order.data.target;
@ -2468,6 +2655,12 @@ UnitAI.prototype.UnitFsmSpec = {
{
if (msg.likelyFailure)
{
// If this is a group attack with pending targets, try the next one
if (this.order.data.targetArray && this.order.data.targetArray.length > 0)
{
this.SetNextState("COMBAT.FINDINGNEWTARGET");
return;
}
// This also handles hunting.
if (this.orderQueue.length > 1)
{
@ -3887,6 +4080,9 @@ UnitAI.prototype.OnOwnershipChanged = function(msg)
UnitAI.prototype.OnDestroy = function()
{
// Clean up all group attack states before destruction
this.CleanupAllGroupAttackStates();
// Switch to an empty state to let states execute their leave handlers.
this.UnitFsm.SwitchToNextState(this, "");
@ -4093,6 +4289,9 @@ UnitAI.prototype.FsmStateNameChanged = function(state)
*/
UnitAI.prototype.FinishOrder = function()
{
// Clean up any group attack state before removing order
this.CleanupGroupAttackState(this.order);
if (!this.orderQueue.length)
{
const stack = new Error().stack.trimRight().replace(/^/mg, ' '); // indent each line
@ -4318,15 +4517,24 @@ UnitAI.prototype.ReplaceOrder = function(type, data)
const idx = this.orderQueue.findIndex(o => o.type == "LeaveFormation");
if (idx === -1)
{
// Clean up all queued orders before clearing them
this.CleanupAllGroupAttackStates();
this.orderQueue = [];
this.order = undefined;
}
else
{
// Clean up orders being discarded
for (let i = 0; i < idx; ++i)
this.CleanupGroupAttackState(this.orderQueue[i]);
this.orderQueue.splice(0, idx);
}
this.PushOrderFront(type, data);
}
else
{
// Clean up all queued orders before clearing them
this.CleanupAllGroupAttackStates();
this.orderQueue = [];
this.PushOrder(type, data);
}
@ -4405,6 +4613,7 @@ UnitAI.prototype.BackToWork = function()
if (this.IsTurret(cmpTurretable) && !cmpTurretable.LeaveTurret())
return false;
this.CleanupAllGroupAttackStates();
this.orderQueue = [];
this.AddOrders(this.workOrders);
@ -5060,6 +5269,9 @@ UnitAI.prototype.CheckTargetRange = function(target, iid, type)
*/
UnitAI.prototype.CheckTargetAttackRange = function(target, type)
{
if (!target || target === INVALID_ENTITY || !type)
return false;
// for formation members, the formation will take care of the range check
if (this.IsFormationMember())
{
@ -5793,6 +6005,75 @@ UnitAI.prototype.Attack = function(target, allowCapture = this.DEFAULT_CAPTURE,
this.AddOrder("Attack", order, queued, pushFront);
};
/**
* Adds a group attack order to the queue.
* Used when some unit(s) are ordered to attack multiple targets.
* Each unit receives the full target list (from Commands) but starts at a different position
* based on the startingIndex in the attacking group.
*
* @param {Array} targets - Array of target entity IDs to attack (pre-sorted by distance)
* @param {number} startingIndex - This unit's position in the attacking group (0-based)
* @param {number} unitCount - Total number of units in the attacking group
* @param {boolean} allowCapture - Whether capturing is allowed
* @param {boolean} queued - If true, add to end of queue instead of replacing current order
* @param {boolean} pushFront - If true, add to front of queue (interrupt current order)
*/
UnitAI.prototype.AttackGroup = function(targets, startingIndex, unitCount, allowCapture = this.DEFAULT_CAPTURE, queued = false, pushFront = false)
{
if (!targets?.length)
return;
// Check if adding these targets would exceed the limit
const currentTotal = this.CountTotalTargetsInQueue();
const newTargetCount = targets.length;
if (currentTotal + newTargetCount > this.MAX_TOTAL_TARGETS)
{
// Trim the targets to fit within the limit
const allowedNewTargets = Math.max(0, this.MAX_TOTAL_TARGETS - currentTotal);
if (allowedNewTargets === 0)
return;
// Trim the target array
targets = targets.slice(0, allowedNewTargets);
// If trimming results in no targets, just return
if (targets.length === 0)
return;
}
// If this unit is in a formation, move the formation controller out of the world
// This prevents the controller from staying at the coordinates where the units received the order
// That can potentially be far apart from where the fighting will occur.
// Result: The formation will reform into a more logical position once members are done (idle).
this.MoveFormationControllerOutOfWorld();
const stride = targets.length / unitCount;
const startIdx = Math.min(Math.round((startingIndex + 0.5) * stride), targets.length - 1);
const order = {
"force": true,
"allowCapture": allowCapture,
"targetArray": targets.slice(),
"target": INVALID_ENTITY,
"currentTargetIndex": startIdx,
"originalFirstTarget": targets[0],
};
this.RememberTargetPosition(order);
this.AddOrder("Attack", order, queued, pushFront);
};
UnitAI.prototype.MoveFormationControllerOutOfWorld = function()
{
if (!this.IsFormationMember() || !this.formationController)
return;
const cmpControllerPosition = Engine.QueryInterface(this.formationController, IID_Position);
if (cmpControllerPosition?.IsInWorld())
cmpControllerPosition.MoveOutOfWorld();
};
/**
* Adds garrison order to the queue, forced by the player.
*/
@ -6726,6 +7007,72 @@ UnitAI.prototype.AttackEntitiesByPreference = function(ents)
return this.RespondToTargetedEntities(entsWithoutPref);
};
UnitAI.prototype.FindAndSetNextTarget = function(data)
{
if (!this.EnsureValidTargetIndex(data))
return false;
const startIdx = data.currentTargetIndex;
const currentTarget = data.targetArray[startIdx];
// First check the starting target
if (this.CanAttack(currentTarget) && this.CheckTargetVisible(currentTarget))
return this.SetNextTarget(data, startIdx);
// Search forward using find
const forwardFound = data.targetArray
.slice(startIdx + 1)
.findIndex((target, i) =>
this.CanAttack(target) && this.CheckTargetVisible(target)
);
if (forwardFound !== -1)
return this.SetNextTarget(data, startIdx + 1 + forwardFound);
// Search backward using find
const backwardFound = data.targetArray
.slice(0, startIdx)
.reverse()
.findIndex((target, i) =>
this.CanAttack(target) && this.CheckTargetVisible(target)
);
if (backwardFound !== -1)
{
// Convert reverse index back to original index
const originalIndex = startIdx - 1 - backwardFound;
return this.SetNextTarget(data, originalIndex);
}
return false;
};
UnitAI.prototype.SetNextTarget = function(data, index)
{
const target = data.targetArray[index];
data.target = target;
data.attackType = this.GetBestAttackAgainst(target, data.allowCapture);
data.currentTargetIndex = index;
return true;
};
UnitAI.prototype.EnsureValidTargetIndex = function(data)
{
if (!data.targetArray || data.currentTargetIndex === undefined)
return false;
// If array is empty, clear the index
if (data.targetArray.length === 0)
{
data.currentTargetIndex = undefined;
return false;
}
data.currentTargetIndex = Math.clamp(data.currentTargetIndex, 0, data.targetArray.length - 1);
return true;
};
/**
* Call UnitAI.funcname(args) on all formation members.
* @param resetFinishedEntities - If true, call ResetFinishedEntities first.
@ -6837,6 +7184,50 @@ UnitAI.prototype.ResetObstructionMitigationFlag = function()
delete this.obstructionMitigationAttempted;
};
/**
* Counts the total number of target entities across all queued orders.
* This includes targetArray from group attacks and single targets.
* Each target reference is counted separately, even if the same entity
* appears in multiple orders or in both targetArray and target.
* @returns {number} - Total number of target entity references in the order queue
*/
UnitAI.prototype.CountTotalTargetsInQueue = function()
{
let total = 0;
for (const order of this.orderQueue)
{
if (order.data)
{
// Count group attack targets
if (order.data.targetArray && Array.isArray(order.data.targetArray))
total += order.data.targetArray.length;
// Add single target for consistency
if (order.data.target && order.data.target !== INVALID_ENTITY)
total++;
}
}
return total;
};
UnitAI.prototype.CleanupGroupAttackState = function(order)
{
if (order?.data?.targetArray)
{
delete order.data.targetArray;
delete order.data.currentTargetIndex;
}
};
UnitAI.prototype.CleanupAllGroupAttackStates = function()
{
for (const order of this.orderQueue)
this.CleanupGroupAttackState(order);
};
// Maximum number of target entities allowed across all queued orders
UnitAI.prototype.MAX_TOTAL_TARGETS = 1000;
UnitAI.prototype.UnitFsm = new FSM(UnitAI.prototype.UnitFsmSpec);
Engine.RegisterComponentType(IID_UnitAI, "UnitAI", UnitAI);

View file

@ -138,6 +138,7 @@ function TestFormationExiting(mode)
"ResetActiveQuery": function(id) { if (mode == 0) return []; return [enemy]; },
"DisableActiveQuery": function(id) { },
"GetEntityFlagMask": function(identifier) { },
"GetLosVisibility": (ent, player) => "visible"
});
AddMock(SYSTEM_ENTITY, IID_TemplateManager, {
@ -319,8 +320,11 @@ function TestMoveIntoFormationWhileAttacking()
"ResetActiveQuery": function(id) { return [enemy]; },
"DisableActiveQuery": function(id) { },
"GetEntityFlagMask": function(identifier) { },
"GetLosVisibility": (target, player) => "visible",
"GetLosVisibilityPosition": (x, z, player) => "visible"
});
AddMock(SYSTEM_ENTITY, IID_TemplateManager, {
"GetCurrentTemplateName": function(ent) { return "special/formations/line_closed"; },
});
@ -406,6 +410,10 @@ function TestMoveIntoFormationWhileAttacking()
"GetHitpoints": function() { return 40; },
});
AddMock(enemy, IID_Ownership, {
"GetOwner": () => 2 // Different player ID (enemy)
});
const controllerFormation = ConstructComponent(controller, "Formation", {
"FormationShape": "square",
"ShiftRows": "false",
@ -421,6 +429,10 @@ function TestMoveIntoFormationWhileAttacking()
"DefaultStance": "aggressive"
});
AddMock(controller, IID_Ownership, {
"GetOwner": () => 1
});
AddMock(controller, IID_Position, {
"GetTurretParent": () => INVALID_ENTITY,
"JumpTo": function(x, z) { this.x = x; this.z = z; },
@ -458,7 +470,7 @@ function TestMoveIntoFormationWhileAttacking()
controllerFormation.SetMembers(units);
controllerAI.Attack(enemy, []);
controllerAI.Attack(enemy);
for (const ent of unitAIs)
TS_ASSERT_EQUALS(unitAI.fsmStateName, "INDIVIDUAL.COMBAT.ATTACKING");
@ -889,4 +901,362 @@ function TestAttemptObstructionMitigation()
})();
}
TestAttemptObstructionMitigation();
TestAttemptObstructionMitigation();
function TestFindAndSetNextTargetBehavior()
{
ResetState();
const attacker = 10;
const targets = [20, 21, 22, 23, 24]; // Multiple targets for comprehensive testing
// Basic mocks needed for unitAI creation
AddMock(SYSTEM_ENTITY, IID_Timer, {
"SetInterval": () => {},
"SetTimeout": () => {}
});
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"CreateActiveQuery": () => 1,
"EnableActiveQuery": () => {},
"ResetActiveQuery": () => [],
"DisableActiveQuery": () => {},
"GetEntityFlagMask": () => 0
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => false
});
// Create the unitAI component
const unitAI = ConstructComponent(attacker, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
AddMock(attacker, IID_Attack, {
"GetBestAttackAgainst": () => "Melee"
});
unitAI.OnCreate();
// Mock the visibility and attackability checks
unitAI.CanAttack = (target) =>
{
// Target 21 is always unattackable (e.g., garrisoned, dead, etc.)
return target !== 21;
};
unitAI.CheckTargetVisible = (target) =>
{
// Target 22 is always not visible
return target !== 22;
};
// First target is valid
(function()
{
const data = {
"targetArray": [20, 21, 22, 23, 24],
"currentTargetIndex": 0, // Currently targeting 20
"target": 20,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(data.target, 20);
TS_ASSERT_EQUALS(data.currentTargetIndex, 0);
})();
// End of array behavior
(function()
{
const data = {
"targetArray": [18, 19, 20, 21, 22],
"currentTargetIndex": 2, // Currently targeting 22
"allowCapture": false
};
// 21 and 22 are invalid, should go backward and find 20
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(data.target, 20); // Should be assigned targetArray[initialTarget - 1]
})();
// No valid targets found
(function()
{
const data = {
"targetArray": [21, 22], // Both are invalid (21 unattackable, 22 not visible)
"currentTargetIndex": 0,
"target": 21,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(!found);
TS_ASSERT_EQUALS(data.target, 21); // Should remain unchanged
TS_ASSERT_EQUALS(data.currentTargetIndex, 0);
})();
// Empty target array
(function()
{
const data = {
"targetArray": [],
"currentTargetIndex": 0,
"target": 20,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(!found);
TS_ASSERT_EQUALS(data.target, 20); // Should remain unchanged
TS_ASSERT_EQUALS(data.currentTargetIndex, void 0); // Should nullify currentTargetIndex
})();
// Current target is last in array
(function()
{
const data = {
"targetArray": [20, 21, 22, 23, 24],
"currentTargetIndex": 4, // Currently targeting 24 (last element)
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(data.target, 24); // Should remain unchanged
TS_ASSERT_EQUALS(data.currentTargetIndex, 4);
})();
// Single invalid target
(function()
{
const data = {
"targetArray": [21], // Only one target, which is invalid
"currentTargetIndex": 0,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(!found);
})();
// Verify if we don't do more calls then necessary
(function()
{
const searchOrder = [];
unitAI.CanAttack = (target) =>
{
searchOrder.push(target);
return target == 20;
};
unitAI.CheckTargetVisible = (target) => true; // All visible
const data = {
"targetArray": [20, 21, 22, 23],
"currentTargetIndex": 1, // Currently targeting 21
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(searchOrder.length, 4); // Should find at 20 (4 calls)
})();
}
TestFindAndSetNextTargetBehavior();
function TestAttackGroupBehavior()
{
ResetState();
const attacker1 = 100;
const attacker2 = 101;
const targets = [200, 201, 202, 203, 204];
// Basic mocks needed for unitAI creation
AddMock(SYSTEM_ENTITY, IID_Timer, {
"SetInterval": () => {},
"SetTimeout": () => {}
});
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"CreateActiveQuery": () => 1,
"EnableActiveQuery": () => {},
"ResetActiveQuery": () => [],
"DisableActiveQuery": () => {},
"GetEntityFlagMask": () => 0
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => false
});
// Create two unitAI components
const unitAI1 = ConstructComponent(attacker1, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
const unitAI2 = ConstructComponent(attacker2, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
AddMock(attacker1, IID_Attack, {
"GetBestAttackAgainst": () => "Melee"
});
AddMock(attacker2, IID_Attack, {
"GetBestAttackAgainst": () => "Melee"
});
unitAI1.OnCreate();
unitAI2.OnCreate();
// Basic AttackGroup distribution
(function()
{
let orderAdded1 = null;
let orderAdded2 = null;
// Mock AddOrder to capture what orders are created
unitAI1.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded1 = { type, data, queued, pushFront };
};
unitAI2.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded2 = { type, data, queued, pushFront };
};
// Call AttackGroup for both units
unitAI1.AttackGroup(targets, 0, 2, false, false, false);
unitAI2.AttackGroup(targets, 1, 2, false, false, false);
// Verify unit1's order
TS_ASSERT(orderAdded1);
TS_ASSERT_EQUALS(orderAdded1.type, "Attack");
TS_ASSERT_EQUALS(orderAdded1.data.targetArray.length, 5);
TS_ASSERT_EQUALS(orderAdded1.data.target, INVALID_ENTITY);
// Unit 0 should start at position 1 ==> Math.round((0 + 0.5) * 2.5) = Math.round(1.25) = 1
TS_ASSERT_EQUALS(orderAdded1.data.currentTargetIndex, 1);
// Verify unit2's order
TS_ASSERT(orderAdded2);
TS_ASSERT_EQUALS(orderAdded2.type, "Attack");
TS_ASSERT_EQUALS(orderAdded2.data.targetArray.length, 5);
TS_ASSERT_EQUALS(orderAdded2.data.target, INVALID_ENTITY);
// Unit 1 should start at position 4 ==> Math.round((1 + 0.5) * 2.5) = Math.round(3.75) = 4
TS_ASSERT_EQUALS(orderAdded2.data.currentTargetIndex, 4);
})();
// More units than targets
(function()
{
let orderAdded1 = null;
let orderAdded2 = null;
let orderAdded3 = null;
const unitAI3 = ConstructComponent(102, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
AddMock(102, IID_Attack, { "GetBestAttackAgainst": () => "Melee" });
unitAI3.OnCreate();
unitAI1.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded1 = { type, data, queued, pushFront };
};
unitAI2.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded2 = { type, data, queued, pushFront };
};
unitAI3.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded3 = { type, data, queued, pushFront };
};
const smallTargets = [300, 301];
unitAI1.AttackGroup(smallTargets, 0, 3, true, true, false);
unitAI2.AttackGroup(smallTargets, 1, 3, true, true, false);
unitAI3.AttackGroup(smallTargets, 2, 3, true, true, false);
// Verify distribution when more units than targets
TS_ASSERT(orderAdded1);
TS_ASSERT_EQUALS(orderAdded1.data.currentTargetIndex, 0); // 0 * 2 / 3 = 0
TS_ASSERT_EQUALS(orderAdded1.data.allowCapture, true);
TS_ASSERT_EQUALS(orderAdded1.queued, true);
TS_ASSERT(orderAdded2);
TS_ASSERT_EQUALS(orderAdded2.data.currentTargetIndex, 1); // 1 * 2 / 3 = 0.66, round = 1
TS_ASSERT(orderAdded2.data.currentTargetIndex < smallTargets.length);
TS_ASSERT(orderAdded3);
TS_ASSERT_EQUALS(orderAdded3.data.currentTargetIndex, 1); // 2 * 2 / 3 = 1.33, round = 1
TS_ASSERT(orderAdded3.data.currentTargetIndex < smallTargets.length);
})();
// Edge case - single target
(function()
{
let orderAdded = null;
unitAI1.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded = { type, data, queued, pushFront };
};
const singleTarget = [400];
unitAI1.AttackGroup(singleTarget, 0, 1, false, false, true);
TS_ASSERT(orderAdded);
TS_ASSERT_EQUALS(orderAdded.data.targetArray.length, 1);
TS_ASSERT_EQUALS(orderAdded.data.currentTargetIndex, 0);
TS_ASSERT_EQUALS(orderAdded.pushFront, true);
})();
// Empty targets array should do nothing
(function()
{
let callCount = 0;
unitAI1.AddOrder = () => { callCount++; };
unitAI1.AttackGroup([], 0, 1);
TS_ASSERT_EQUALS(callCount, 0);
unitAI1.AttackGroup(null, 0, 1);
TS_ASSERT_EQUALS(callCount, 0);
unitAI1.AttackGroup(undefined, 0, 1);
TS_ASSERT_EQUALS(callCount, 0);
})();
// Verify RememberTargetPosition is called
(function()
{
let rememberedOrder = null;
unitAI1.RememberTargetPosition = (order) =>
{
rememberedOrder = order;
};
unitAI1.AddOrder = () => {};
const testTargets = [500, 501];
unitAI1.AttackGroup(testTargets, 0, 1);
TS_ASSERT(rememberedOrder);
TS_ASSERT_EQUALS(rememberedOrder.targetArray.length, 2);
})();
}
TestAttackGroupBehavior();

View file

@ -8,5 +8,5 @@
{ "value": "Researcher/TechCostMultiplier/metal", "multiply": 0.9 }
],
"auraName": "Economic Fortune",
"auraDescription": "Solon brought in a new system of weights and measures, fathers were encouraged to find trades for their sons.\nEconomic technologies 10% resource costs."
"auraDescription": "Solon brought in a new system of weights and measures, and fathers were encouraged to find trades for their sons.\nEconomic technologies 10% resource costs."
}

View file

@ -5,5 +5,5 @@
{ "value": "TerritoryInfluence/Radius", "multiply": 1.2 }
],
"auraName": "Territorial Expansion",
"auraDescription": "At its height, the Empire's borders spanned from the Fergana Valley in the west, to Korea in the east, and to northern Vietnam in the south.\nTerritory influence bonus +20%."
"auraDescription": "At its height, the Empire's borders spanned from the Fergana Valley in the west to Korea in the east and to northern Vietnam in the south.\nTerritory influence bonus +20%."
}

View file

@ -7,5 +7,5 @@
{ "value": "Resistance/Entity/Damage/Crush", "add": 1 }
],
"auraName": "Founder and Defender of the Republic",
"auraDescription": "Brutus was one of the key figures in the overthrow of the monarchy and the founding of the Roman Republic. Later, as consul he led a Roman army to victory against the Etruscan King Tarquinius who sought to retake the throne.\nHumans and Siege Engines +1 crush, hack, pierce resistance."
"auraDescription": "Brutus was one of the key figures in the overthrow of the monarchy and the founding of the Roman Republic. Later, as consul, he led a Roman army to victory against the Etruscan King Tarquinius who sought to retake the throne.\nHumans and Siege Engines +1 crush, hack, and pierce resistance."
}

View file

@ -179,6 +179,28 @@ var g_Commands = {
});
},
"attack-group": function(player, cmd, data)
{
const unitAIs = data.entities.flatMap(ent =>
{
const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
const cmpAttack = Engine.QueryInterface(ent, IID_Attack);
// Check if unit can move and has attack capability
const canAttack = cmpAttack && cmpAttack.GetAttackTypes().length > 0;
return (cmpUnitAI && cmpUnitAI.AbleToMove() && canAttack) ? [cmpUnitAI] : [];
});
if (!unitAIs.length || !cmd.targets?.length)
return;
// Pass the entire target array and unit count to each UnitAI
unitAIs.forEach((cmpUnitAI, index) =>
{
cmpUnitAI.AttackGroup(cmd.targets, index, unitAIs.length, cmd.allowCapture, cmd.queued, cmd.pushFront);
});
},
"patrol": function(player, cmd, data)
{
const ents = data.entities.length;

View file

@ -33,6 +33,8 @@ echo "Building cpp-httplib..."
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -33,6 +33,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -49,6 +49,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -49,6 +49,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -36,6 +36,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -56,6 +56,8 @@ echo "Building SpiderMonkey..."
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
OS="${OS:=$(uname -s)}"

View file

@ -33,6 +33,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -33,6 +33,7 @@ ignore = [
"ANN",
"C90",
"COM812",
"CPY001",
"D10",
"EM",
"FIX002",

View file

@ -53,25 +53,6 @@ public:
void SetElevation(float f);
void SetRotation(float f);
/**
* Calculate brightness of a point of a unit with the given normal vector,
* for rendering with CPU lighting.
* The resulting color contains both ambient and diffuse light.
* To cope with sun overbrightness, the color is scaled by 0.5.
*
* @param normal normal vector (must have length 1)
*/
RGBColor EvaluateUnitScaled(const CVector3D& normal) const
{
float dot = -normal.Dot(m_SunDir);
RGBColor color = m_AmbientColor;
if (dot > 0)
color += m_SunColor * dot;
return color * 0.5f;
}
// Comparison operators
bool operator==(const CLightEnv& o) const
{

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -69,7 +69,7 @@ CObjectBase::CObjectBase(CObjectManager& objectManager, CActorDef& actorDef, u8
m_Properties.m_FloatOnWater = false;
// Remove leading art/actors/ & include quality level.
m_Identifier = m_ActorDef.m_Pathname.string8().substr(11) + CStr::FromInt(m_QualityLevel);
m_Identifier = fmt::format("{}{}", m_ActorDef.m_Pathname.string8().substr(11), m_QualityLevel);
}
std::unique_ptr<CObjectBase> CObjectBase::CopyWithQuality(u8 newQualityLevel) const

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -156,7 +156,8 @@ bool ResolveIncludesImpl(
it = includeCache.emplace(path, std::move(includeContent)).first;
}
// We need to insert #line directives to have correct line numbers in errors.
chunks.emplace_back(lineDirective + "1\n" + it->second + "\n" + lineDirective + CStr::FromUInt(line + 1) + "\n");
chunks.emplace_back(fmt::format("{}1\n{}\n{}{}\n", lineDirective, it->second, lineDirective,
line + 1));
processedParts.emplace_back(currentPart.substr(0, lineStart));
if (!ResolveIncludesImpl(chunks.back(), includeCache, includeCallback, chunks, processedParts))
return false;

View file

@ -755,7 +755,7 @@ void CGUI::Xeromyces_ReadObject(const XMBData& xmb, XMBElement element, IGUIObje
// Check if name isn't set, generate an internal name in that case.
if (!NameSet)
{
object->SetName("__internal(" + CStr::FromInt(m_InternalNameNumber) + ")");
object->SetName(fmt::format("__internal({})", m_InternalNameNumber));
++m_InternalNameNumber;
}
@ -977,7 +977,7 @@ void CGUI::Xeromyces_ReadRepeat(const XMBData& xmb, XMBElement element, IGUIObje
for (int n = 0; n < count; ++n)
{
NameSubst.emplace_back(var, "[" + CStr::FromInt(n) + "]");
NameSubst.emplace_back(var, fmt::format("[{}]", n));
XERO_ITER_EL(element, child)
{

View file

@ -247,6 +247,8 @@ void TNSpline::RemoveNode(const int index)
if (m_NodeCount == 0 || index > m_NodeCount - 1)
return;
if (index > 0)
std::swap(m_Nodes[index].Distance, m_Nodes[index - 1].Distance);
m_MaxDistance -= m_Nodes[index].Distance;
m_Nodes.erase(m_Nodes.begin() + index);
--m_NodeCount;

View file

@ -0,0 +1,120 @@
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "lib/self_test.h"
#include "maths/Fixed.h"
#include "maths/NUSpline.h"
#define TS_ASSERT_VEC_EQUALS(v, x, y, z) \
TS_ASSERT_EQUALS(v.X, x); \
TS_ASSERT_EQUALS(v.Y, y); \
TS_ASSERT_EQUALS(v.Z, z);
class TestNUSpline : public CxxTest::TestSuite
{
public:
void test_TNSAddNode()
{
TNSpline spline{};
CFixedVector3D p0{fixed::FromInt(0), fixed::FromInt(0), fixed::FromInt(0)};
CFixedVector3D r0{fixed::FromInt(1), fixed::FromInt(1), fixed::FromInt(1)};
fixed d0 = fixed::FromInt(33);
CFixedVector3D p1{fixed::FromInt(1), fixed::FromInt(1), fixed::FromInt(1)};
CFixedVector3D r1{fixed::FromInt(2), fixed::FromInt(2), fixed::FromInt(2)};
fixed d1 = fixed::FromInt(4);
CFixedVector3D p2{fixed::FromInt(2), fixed::FromInt(2), fixed::FromInt(2)};
CFixedVector3D r2{fixed::FromInt(3), fixed::FromInt(3), fixed::FromInt(3)};
fixed d2 = fixed::FromInt(12);
spline.AddNode(p0, r0, d0);
spline.AddNode(p1, r1, d1);
spline.AddNode(p2, r2, d2);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(0.f), 0, 0, 0);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(0.25f), 1, 1, 1);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(1.f), 2, 2, 2);
TS_ASSERT_EQUALS(spline.GetMaxDistance(), fixed::FromInt(16));
}
void test_TNSInsertNode()
{
TNSpline spline{};
CFixedVector3D p0{fixed::FromInt(0), fixed::FromInt(0), fixed::FromInt(0)};
CFixedVector3D r0{fixed::FromInt(1), fixed::FromInt(1), fixed::FromInt(1)};
fixed d0 = fixed::FromInt(4);
CFixedVector3D p1{fixed::FromInt(1), fixed::FromInt(1), fixed::FromInt(1)};
CFixedVector3D r1{fixed::FromInt(2), fixed::FromInt(2), fixed::FromInt(2)};
fixed d1 = fixed::FromInt(33);
CFixedVector3D p2{fixed::FromInt(2), fixed::FromInt(2), fixed::FromInt(2)};
CFixedVector3D r2{fixed::FromInt(3), fixed::FromInt(3), fixed::FromInt(3)};
fixed d2 = fixed::FromInt(12);
spline.InsertNode(0, p1, r1, d1);
spline.InsertNode(0, p0, r0, d0);
spline.InsertNode(2, p2, r2, d2);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(0.f), 0, 0, 0);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(0.25f), 1, 1, 1);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(1.f), 2, 2, 2);
TS_ASSERT_EQUALS(spline.GetMaxDistance(), fixed::FromInt(16));
}
void test_TNSRemoveNode()
{
TNSpline spline{};
CFixedVector3D p0{fixed::FromInt(0), fixed::FromInt(0), fixed::FromInt(0)};
CFixedVector3D r0{fixed::FromInt(1), fixed::FromInt(1), fixed::FromInt(1)};
fixed d0 = fixed::FromInt(33);
CFixedVector3D p1{fixed::FromInt(1), fixed::FromInt(1), fixed::FromInt(1)};
CFixedVector3D r1{fixed::FromInt(2), fixed::FromInt(2), fixed::FromInt(2)};
fixed d1 = fixed::FromInt(4);
CFixedVector3D p2{fixed::FromInt(2), fixed::FromInt(2), fixed::FromInt(2)};
CFixedVector3D r2{fixed::FromInt(3), fixed::FromInt(3), fixed::FromInt(3)};
fixed d2 = fixed::FromInt(12);
spline.AddNode(p0, r0, d0);
spline.AddNode(p1, r1, d1);
spline.AddNode(p2, r2, d2);
spline.RemoveNode(2);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(0.f), 0, 0, 0);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(1.f), 1, 1, 1);
TS_ASSERT_EQUALS(spline.GetMaxDistance(), fixed::FromInt(4));
spline.RemoveNode(0);
TS_ASSERT_EQUALS(spline.GetMaxDistance(), fixed::FromInt(0));
spline.AddNode(p2, r2, d2);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(0.f), 1, 1, 1);
TS_ASSERT_VEC_EQUALS(spline.GetPosition(1.f), 2, 2, 2);
TS_ASSERT_EQUALS(spline.GetMaxDistance(), fixed::FromInt(12));
}
};

View file

@ -63,7 +63,7 @@ void CNetClientTurnManager::PostCommand(JS::HandleValue data)
// TODO: we should do this when the server stops sending our commands back to us
}
void CNetClientTurnManager::NotifyFinishedOwnCommands(u32 turn)
void CNetClientTurnManager::NotifyFinishedOwnCommands(turn_id_t turn)
{
NETCLIENTTURN_LOG("NotifyFinishedOwnCommands(%d)\n", turn);
@ -79,7 +79,7 @@ void CNetClientTurnManager::NotifyFinishedOwnCommands(u32 turn)
m_NetClient.SendMessage(&msg);
}
void CNetClientTurnManager::NotifyFinishedUpdate(u32 turn, const UpdateCallback&)
void CNetClientTurnManager::NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback&)
{
bool quick = !TurnNeedsFullHash(turn);
std::string hash;
@ -110,10 +110,10 @@ void CNetClientTurnManager::OnDestroyConnection()
void CNetClientTurnManager::OnSimulationMessage(CSimulationMessage* msg)
{
// Command received from the server - store it for later execution
AddCommand(msg->m_Client, msg->m_Player, msg->m_Data, msg->m_Turn);
AddCommand(msg->m_Client, msg->m_Player, msg->m_Data, static_cast<turn_id_t>(msg->m_Turn));
}
void CNetClientTurnManager::OnSyncError(u32 turn, const CStr& expectedHash, const std::vector<CSyncErrorMessage::S_m_PlayerNames>& playerNames)
void CNetClientTurnManager::OnSyncError(turn_id_t turn, const CStr& expectedHash, const std::vector<CSyncErrorMessage::S_m_PlayerNames>& playerNames)
{
CStr expectedHashHex(Hexify(expectedHash));
NETCLIENTTURN_LOG("OnSyncError(%d, %hs)\n", turn, expectedHashHex.c_str());

View file

@ -49,12 +49,12 @@ public:
*/
void OnDestroyConnection();
void OnSyncError(u32 turn, const CStr& expectedHash, const std::vector<CSyncErrorMessage::S_m_PlayerNames>& playerNames);
void OnSyncError(turn_id_t turn, const CStr& expectedHash, const std::vector<CSyncErrorMessage::S_m_PlayerNames>& playerNames);
private:
void NotifyFinishedOwnCommands(u32 turn) override;
void NotifyFinishedOwnCommands(turn_id_t turn) override;
void NotifyFinishedUpdate(u32 turn, const UpdateCallback& sendEventToAll) override;
void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll) override;
CNetClient& m_NetClient;
};

View file

@ -88,7 +88,7 @@ CStr CNetMessage::ToString() const
if (GetType() == NMT_INVALID)
return "MESSAGE_TYPE_NONE { Undefined Message }";
else
return "Unknown Message " + CStr::FromInt(GetType());
return fmt::format("Unknown Message {}", static_cast<int>(GetType()));
}
CNetMessage* CNetMessageFactory::CreateMessage(const void* pData,

View file

@ -139,7 +139,7 @@ public:
u32 m_Client;
i32 m_Player;
u32 m_Turn;
i32 m_Turn;
JS::PersistentRooted<JS::Value> m_Data;
private:
const Script::Interface& m_ScriptInterface;

View file

@ -150,7 +150,7 @@ u8* CSimulationMessage::Serialize(u8* pBuffer) const
CBufferBinarySerializer serializer(m_ScriptInterface, pos);
serializer.NumberU32_Unbounded("client", m_Client);
serializer.NumberI32_Unbounded("player", m_Player);
serializer.NumberU32_Unbounded("turn", m_Turn);
serializer.NumberI32_Unbounded("turn", m_Turn);
serializer.ScriptVal("command", const_cast<JS::PersistentRootedValue*>(&m_Data));
return serializer.GetBuffer();
@ -165,7 +165,7 @@ const u8* CSimulationMessage::Deserialize(const u8* pStart, const u8* pEnd)
CStdDeserializer deserializer(m_ScriptInterface, stream);
deserializer.NumberU32_Unbounded("client", m_Client);
deserializer.NumberI32_Unbounded("player", m_Player);
deserializer.NumberU32_Unbounded("turn", m_Turn);
deserializer.NumberI32_Unbounded("turn", m_Turn);
deserializer.ScriptVal("command", &m_Data);
return pEnd;
}
@ -177,7 +177,7 @@ size_t CSimulationMessage::GetSerializedLength() const
CLengthBinarySerializer serializer(m_ScriptInterface);
serializer.NumberU32_Unbounded("client", m_Client);
serializer.NumberI32_Unbounded("player", m_Player);
serializer.NumberU32_Unbounded("turn", m_Turn);
serializer.NumberI32_Unbounded("turn", m_Turn);
// TODO: The cast can probably be removed if and when ScriptVal can take a JS::HandleValue instead of
// a JS::MutableHandleValue (relies on JSAPI change). Also search for other casts like this one in that case.

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -27,7 +27,7 @@
#define PS_PROTOCOL_MAGIC 0x5073013f // 'P', 's', 0x01, '?'
#define PS_PROTOCOL_MAGIC_RESPONSE 0x50630121 // 'P', 'c', 0x01, '!'
#define PS_PROTOCOL_VERSION 0x01010019 // Arbitrary protocol
#define PS_PROTOCOL_VERSION 0x0101001A // Arbitrary protocol
#define PS_DEFAULT_PORT 0x5073 // 'P', 's'
// Set when lobby authentication is required. Used in the SrvHandshakeResponseMessage.
@ -231,7 +231,7 @@ START_NMT_CLASS_(ClientPaused, NMT_CLIENT_PAUSED)
END_NMT_CLASS()
START_NMT_CLASS_(LoadedGame, NMT_LOADED_GAME)
NMT_FIELD_INT(m_CurrentTurn, u32, 4)
NMT_FIELD_INT(m_CurrentTurn, i32, 4)
END_NMT_CLASS()
START_NMT_CLASS_(GameStart, NMT_GAME_START)
@ -243,17 +243,17 @@ START_NMT_CLASS_(GameSavedStart, NMT_SAVED_GAME_START)
END_NMT_CLASS()
START_NMT_CLASS_(EndCommandBatch, NMT_END_COMMAND_BATCH)
NMT_FIELD_INT(m_Turn, u32, 4)
NMT_FIELD_INT(m_Turn, i32, 4)
NMT_FIELD_INT(m_TurnLength, u32, 2)
END_NMT_CLASS()
START_NMT_CLASS_(SyncCheck, NMT_SYNC_CHECK)
NMT_FIELD_INT(m_Turn, u32, 4)
NMT_FIELD_INT(m_Turn, i32, 4)
NMT_FIELD(CStr, m_Hash)
END_NMT_CLASS()
START_NMT_CLASS_(SyncError, NMT_SYNC_ERROR)
NMT_FIELD_INT(m_Turn, u32, 4)
NMT_FIELD_INT(m_Turn, i32, 4)
NMT_FIELD(CStr, m_HashExpected)
NMT_START_ARRAY(m_PlayerNames)
NMT_FIELD(CStrW, m_Name)

View file

@ -49,10 +49,12 @@
#include "scriptinterface/Context.h"
#include "scriptinterface/Interface.h"
#include "scriptinterface/Request.h"
#include "simulation2/helpers/SimulationCommand.h"
#include "simulation2/system/TurnManager.h"
#include <algorithm>
#include <cstring>
#include <fmt/format.h>
#include <functional>
#include <iterator>
#include <memory>
@ -69,6 +71,10 @@
#include <miniupnpc/upnperrors.h>
#endif
#if FMT_VERSION >= 80000
#include <fmt/xchar.h>
#endif
/**
* Number of peers to allocate for the enet host.
* Limited by ENET_PROTOCOL_MAXIMUM_PEER_ID (4096).
@ -1172,9 +1178,9 @@ bool CNetServerWorker::OnSimulationCommand(CNetServerSession* session, CFsmEvent
server.Multicast(message, { NSS_INGAME });
// Save all the received commands
if (server.m_SavedCommands.size() < message->m_Turn + 1)
server.m_SavedCommands.resize(message->m_Turn + 1);
server.m_SavedCommands[message->m_Turn].push_back(*message);
if (server.m_SavedCommands.size() < static_cast<size_t>(message->m_Turn) + 1)
server.m_SavedCommands.resize(static_cast<size_t>(message->m_Turn) + 1);
server.m_SavedCommands[static_cast<size_t>(message->m_Turn)].push_back(*message);
// TODO: we shouldn't send the message back to the client that first sent it
return true;
@ -1396,14 +1402,14 @@ bool CNetServerWorker::OnJoinSyncingLoadedGame(CNetServerSession* session, CFsmE
CLoadedGameMessage* message = (CLoadedGameMessage*)event->GetParamRef();
u32 turn = message->m_CurrentTurn;
u32 readyTurn = server.m_ServerTurnManager->GetReadyTurn();
turn_id_t turn = message->m_CurrentTurn;
turn_id_t readyTurn = server.m_ServerTurnManager->GetReadyTurn();
// Send them all commands received since their saved state,
// and turn-ended messages for any turns that have already been processed
for (size_t i = turn + 1; i < std::max(readyTurn+1, (u32)server.m_SavedCommands.size()); ++i)
for (turn_id_t i = turn + 1; i < std::max(readyTurn + 1, static_cast<turn_id_t>(server.m_SavedCommands.size())); ++i)
{
if (i < server.m_SavedCommands.size())
if (static_cast<size_t>(i) < server.m_SavedCommands.size())
for (size_t j = 0; j < server.m_SavedCommands[i].size(); ++j)
session->SendMessage(&server.m_SavedCommands[i][j]);
@ -1640,7 +1646,7 @@ CStrW CNetServerWorker::DeduplicatePlayerName(const CStrW& original)
if (unique)
return name;
name = original + L" (" + CStrW::FromUInt(id++) + L")";
name = fmt::format(L"{}({})", original, id++);
}
}

View file

@ -27,6 +27,7 @@
#include "network/NetServerSession.h"
#include "ps/CLogger.h"
#include "ps/ConfigDB.h"
#include "simulation2/helpers/SimulationCommand.h"
#include "simulation2/system/TurnManager.h"
#include <limits>
@ -50,7 +51,7 @@ CNetServerTurnManager::CNetServerTurnManager(CNetServerWorker& server)
m_SavedTurnLengths.push_back(m_TurnLength);
}
void CNetServerTurnManager::NotifyFinishedClientCommands(CNetServerSession& session, u32 turn)
void CNetServerTurnManager::NotifyFinishedClientCommands(CNetServerSession& session, turn_id_t turn)
{
int client = session.GetHostID();
@ -105,11 +106,11 @@ void CNetServerTurnManager::CheckClientsReady()
msg.m_Turn = m_ReadyTurn;
m_NetServer.Multicast(&msg, { NSS_INGAME });
ENSURE(m_SavedTurnLengths.size() == m_ReadyTurn);
ENSURE(std::cmp_equal(m_SavedTurnLengths.size(), m_ReadyTurn));
m_SavedTurnLengths.push_back(m_TurnLength);
}
void CNetServerTurnManager::NotifyFinishedClientUpdate(CNetServerSession& session, u32 turn, const CStr& hash)
void CNetServerTurnManager::NotifyFinishedClientUpdate(CNetServerSession& session, turn_id_t turn, const CStr& hash)
{
int client = session.GetHostID();
@ -138,13 +139,13 @@ void CNetServerTurnManager::NotifyFinishedClientUpdate(CNetServerSession& sessio
m_ClientStateHashes[turn][client] = hash;
// Find the newest turn which we know all clients have simulated
u32 newest = std::numeric_limits<u32>::max();
turn_id_t newest = std::numeric_limits<turn_id_t>::max();
for (const std::pair<const int, Client>& clientData : m_ClientsData)
if (clientData.second.simulatedTurn < newest)
newest = clientData.second.simulatedTurn;
// For every set of state hashes that all clients have simulated, check for OOS
for (const std::pair<const u32, std::map<int, std::string>>& clientStateHash : m_ClientStateHashes)
for (const std::pair<const turn_id_t, std::map<int, std::string>>& clientStateHash : m_ClientStateHashes)
{
if (clientStateHash.first > newest)
break;
@ -187,7 +188,7 @@ void CNetServerTurnManager::NotifyFinishedClientUpdate(CNetServerSession& sessio
m_ClientStateHashes.erase(m_ClientStateHashes.begin(), m_ClientStateHashes.lower_bound(newest+1));
}
void CNetServerTurnManager::InitialiseClient(int client, u32 turn, bool observer)
void CNetServerTurnManager::InitialiseClient(int client, turn_id_t turn, bool observer)
{
NETSERVERTURN_LOG("InitialiseClient(client=%d, turn=%d)\n", client, turn);
@ -206,7 +207,7 @@ void CNetServerTurnManager::UninitialiseClient(int client)
bool checkOOS = m_ClientsData[client].isOOS;
m_ClientsData.erase(client);
for (std::pair<const u32, std::map<int, std::string>>& clientStateHash : m_ClientStateHashes)
for (std::pair<const turn_id_t, std::map<int, std::string>>& clientStateHash : m_ClientStateHashes)
clientStateHash.second.erase(client);
// Check whether we're ready for the next turn now that we're not
@ -228,8 +229,8 @@ void CNetServerTurnManager::SetTurnLength(u32 msecs)
m_TurnLength = msecs;
}
u32 CNetServerTurnManager::GetSavedTurnLength(u32 turn)
u32 CNetServerTurnManager::GetSavedTurnLength(turn_id_t turn)
{
ENSURE(turn <= m_ReadyTurn);
return m_SavedTurnLengths.at(turn);
return m_SavedTurnLengths.at(static_cast<size_t>(turn));
}

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -21,6 +21,7 @@
#include "lib/code_annotation.h"
#include "lib/types.h"
#include "ps/CStr.h"
#include "simulation2/helpers/SimulationCommand.h"
#include <map>
#include <string>
@ -44,15 +45,15 @@ class CNetServerTurnManager
public:
CNetServerTurnManager(CNetServerWorker& server);
void NotifyFinishedClientCommands(CNetServerSession& session, u32 turn);
void NotifyFinishedClientCommands(CNetServerSession& session, turn_id_t turn);
void NotifyFinishedClientUpdate(CNetServerSession& session, u32 turn, const CStr& hash);
void NotifyFinishedClientUpdate(CNetServerSession& session, turn_id_t turn, const CStr& hash);
/**
* Inform the turn manager of a new client
* @param observer - whether this client is an observer.
*/
void InitialiseClient(int client, u32 turn, bool observer);
void InitialiseClient(int client, turn_id_t turn, bool observer);
/**
* Inform the turn manager that a previously-initialised client has left the game.
@ -65,13 +66,13 @@ public:
* Returns the latest turn for which all clients are ready;
* they will have already been told to execute this turn.
*/
u32 GetReadyTurn() { return m_ReadyTurn; }
turn_id_t GetReadyTurn() { return m_ReadyTurn; }
/**
* Returns the turn length that was used for the given turn.
* Requires turn <= GetReadyTurn().
*/
u32 GetSavedTurnLength(u32 turn);
u32 GetSavedTurnLength(turn_id_t turn);
private:
void CheckClientsReady();
@ -80,9 +81,9 @@ private:
{
CStrW playerName;
// Latest turn for which all commands have been received.
u32 readyTurn;
turn_id_t readyTurn;
// Last known simulated turn.
u32 simulatedTurn;
turn_id_t simulatedTurn;
bool isObserver;
bool isOOS = false;
};
@ -93,10 +94,10 @@ private:
bool m_HasSyncError = false;
// Map of turn -> {Client ID -> state hash}; old indexes <= min(m_ClientsSimulated) are deleted
std::map<u32, std::map<int, std::string>> m_ClientStateHashes;
std::map<turn_id_t, std::map<int, std::string>> m_ClientStateHashes;
/// The latest turn for which we have received all commands from all clients
u32 m_ReadyTurn;
turn_id_t m_ReadyTurn;
// Current turn length
u32 m_TurnLength;

View file

@ -19,6 +19,7 @@
#include "NetStats.h"
#include <fmt/format.h>
#include <string>
enum
@ -77,7 +78,7 @@ const std::vector<ProfileColumn>& CNetStatsTable::GetColumns()
std::lock_guard<std::mutex> lock(m_Mutex);
for (size_t i = 0; i < m_LatchedData.size(); ++i)
m_ColumnDescriptions.push_back(ProfileColumn("Peer "+CStr::FromUInt(i), 80));
m_ColumnDescriptions.push_back(ProfileColumn(fmt::format("Peer {}", i), 80));
}
return m_ColumnDescriptions;
@ -95,7 +96,7 @@ CStr CNetStatsTable::GetCellText(size_t row, size_t col)
#define ROW(id, title, member) \
case id: \
if (col == 0) return title; \
if (m_Peer) return CStr::FromUInt(m_Peer->member); \
if (m_Peer) return std::to_string(m_Peer->member); \
return "???"
switch(row)
@ -129,7 +130,7 @@ void CNetStatsTable::LatchHostState(const ENetHost& host)
std::lock_guard<std::mutex> lock(m_Mutex);
#define ROW(id, title, member) \
m_LatchedData[i].push_back(CStr::FromUInt(host.peers[i].member));
m_LatchedData[i].push_back(std::to_string(host.peers[i].member));
m_LatchedData.clear();
m_LatchedData.resize(host.peerCount);

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -25,7 +25,7 @@
static inline CStr NetMessageStringConvert(u32 arg)
{
return CStr::FromUInt(arg);
return std::to_string(arg);
}
static inline CStr NetMessageStringConvert(const CStr8& arg)

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2021 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -202,27 +202,6 @@ CStr CStr::Repeat(const CStr& str, size_t reps)
// Construction from numbers:
CStr CStr::FromInt(int n)
{
tstringstream<StrBase> ss;
ss << n;
return ss.str();
}
CStr CStr::FromUInt(unsigned int n)
{
tstringstream<StrBase> ss;
ss << n;
return ss.str();
}
CStr CStr::FromInt64(i64 n)
{
tstringstream<StrBase> ss;
ss << n;
return ss.str();
}
CStr CStr::FromDouble(double n)
{
tstringstream<StrBase> ss;

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -95,9 +95,6 @@ public:
// Conversions:
static CStr FromInt(int n);
static CStr FromUInt(unsigned int n);
static CStr FromInt64(i64 n);
static CStr FromDouble(double n);
/**

View file

@ -90,7 +90,6 @@ CGame::CGame(bool replayLog, const SimulationDebugOptions debugOptions):
m_SimRate(1.0f),
m_PlayerID(-1),
m_ViewedPlayerID(-1),
m_IsSavedGame(false),
m_IsVisualReplay(false),
m_ReplayStream(NULL)
{
@ -224,7 +223,7 @@ void CGame::RegisterInit(const JS::HandleValue attribs, const std::string& saved
const Script::Interface& scriptInterface = m_Simulation2->GetScriptInterface();
Script::Request rq(scriptInterface);
m_IsSavedGame = !savedState.empty();
const bool isSavedGame{!savedState.empty()};
m_Simulation2->SetInitAttributes(attribs);
@ -285,7 +284,7 @@ void CGame::RegisterInit(const JS::HandleValue attribs, const std::string& saved
co_return g_Renderer.GetSceneRenderer().GetWaterManager().LoadWaterTextures();
}, L"LoadWaterTextures", 80);
if (m_IsSavedGame)
if (isSavedGame)
PS::Loader::Register(std::bind_front(
[](CGame* game, const std::string& state) -> PS::Loader::Task
{
@ -298,13 +297,32 @@ void CGame::RegisterInit(const JS::HandleValue attribs, const std::string& saved
co_return game->LoadVisualReplayData();
}, this), L"Loading visual replay data", 1000);
// Call the script function InitGame only for new games, not saved games
if (!isSavedGame)
{
// Perform some simulation initializations (replace skirmish entities, explore territories, etc.)
// that needs to be done before setting up the AI and shouldn't be done in Atlas
if (!g_AtlasGameLoop->running)
{
PS::Loader::Register(std::bind_front([](CGame* game) -> PS::Loader::Task
{
game->m_Simulation2->PreInitGame();
co_return 0;
}, this), L"PreInitGame", 5000);
}
PS::Loader::Register(std::bind_front([](CGame* game) -> PS::Loader::Task
{
game->m_Simulation2->InitGame();
co_return 0;
}, this), L"InitGame", 4000);
}
PS::Loader::EndRegistering();
}
int CGame::LoadInitialState(const std::string& savedState)
{
ENSURE(m_IsSavedGame);
std::stringstream stream(savedState);
bool ok = m_Simulation2->DeserializeState(stream);
@ -324,17 +342,6 @@ int CGame::LoadInitialState(const std::string& savedState)
**/
PSRETURN CGame::ReallyStartGame()
{
// Call the script function InitGame only for new games, not saved games
if (!m_IsSavedGame)
{
// Perform some simulation initializations (replace skirmish entities, explore territories, etc.)
// that needs to be done before setting up the AI and shouldn't be done in Atlas
if (!g_AtlasGameLoop->running)
m_Simulation2->PreInitGame();
m_Simulation2->InitGame();
}
// We need to do an initial Interpolate call to set up all the models etc,
// because Update might never interpolate (e.g. if the game starts paused)
// and we could end up rendering before having set up any models (so they'd

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -226,7 +226,6 @@ private:
std::vector<CColor> m_PlayerColors;
int LoadInitialState(const std::string& savedState);
bool m_IsSavedGame; // true if loading a saved game; false for a new game
bool m_CheatsEnabled;

View file

@ -826,7 +826,7 @@ bool Autostart(const CmdLineArgs& args)
Script::GetPropertyInt(rq, pageData, 1, &pageArgs);
Script::StructuredClone clonedpageArgs{Script::WriteStructuredClone(rq, pageArgs)};
g_GUI->OpenChildPage(pageName, std::move(clonedpageArgs));
g_GUI->SwitchPage(pageName, &scriptInterface, pageArgs);
return true;
}

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -27,6 +27,7 @@
#include <SDL_keycode.h>
#include <algorithm>
#include <cstring>
#include <fmt/format.h>
#include <string>
#include <unordered_map>
#include <utility>
@ -122,7 +123,7 @@ CStr FindScancodeName(SDL_Scancode scancode)
const char* name = SDL_GetScancodeName(scancode);
// Some scancodes have no name, but we must have something to save/load/recognize it, so parse it as SYM_XX
if (strlen(name) == 0)
return CStr("SYM_") + CStr::FromInt(scancode);
return fmt::format("SYM_{}", static_cast<int>(scancode));
return name;
}
@ -221,7 +222,7 @@ CStr FindKeyName(SDL_Scancode scancode)
return name;
// Else, show something regardless, so the player knows it's at least recognized.
return CStr("SYM_") + CStr::FromInt(scancode);
return fmt::format("SYM_{}", static_cast<int>(scancode));
}

View file

@ -517,7 +517,7 @@ void rewriteBuffer(u8* buffer, u32& bufferSize)
std::string basic = attrib;
std::map<std::string, double>::iterator time_attrib = time_per_attribute.find(attrib);
if (time_attrib != time_per_attribute.end())
basic += " " + CStr::FromInt(1000000*time_attrib->second) + "us";
basic = fmt::format("{} {}us", basic, 1000000 * time_attrib->second);
u32 length = static_cast<u32>(basic.size());
memcpy(buffer + writePos, &length, sizeof(length));

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -44,6 +44,7 @@
#include <cstring>
#include <ctime>
#include <deque>
#include <fmt/format.h>
#include <fstream>
#include <memory>
#include <mutex>
@ -337,7 +338,7 @@ private:
{
long code = -1;
curl_easy_getinfo(m_Curl, CURLINFO_RESPONSE_CODE, &code);
SetStatus("completed:" + CStr::FromInt(code));
SetStatus(fmt::format("completed:{}", code));
// Check for success code
if (code == 200)
@ -360,7 +361,7 @@ private:
if (errorString.empty())
errorString = curl_easy_strerror(err);
SetStatus("failed:" + CStr::FromInt(err) + ":" + errorString);
SetStatus(fmt::format("failed:{}:{}", static_cast<int>(err), errorString));
}
// We got an unhandled return code or a connection failure;
@ -385,12 +386,12 @@ private:
r += "user_id=";
AppendEscaped(r, m_UserID);
r += "&time=" + CStr::FromInt64(report.m_Time);
r = fmt::format("{}&time={}", std::move(r), report.m_Time);
r += "&type=";
AppendEscaped(r, report.m_Type);
r += "&version=" + CStr::FromInt(report.m_Version);
r = fmt::format("{}&version={}", std::move(r), report.m_Version);
r += "&data=";
AppendEscaped(r, report.m_Data);
@ -529,7 +530,7 @@ bool CUserReporter::IsReportingEnabled()
void CUserReporter::SetReportingEnabled(bool enabled)
{
CStr val = CStr::FromInt(enabled ? REPORTER_VERSION : 0);
const std::string val{std::to_string(enabled ? REPORTER_VERSION : 0)};
g_ConfigDB.SetValueString(CFG_USER, "userreport.enabledversion", val);
g_ConfigDB.WriteValueToFile(CFG_USER, "userreport.enabledversion", val);

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -33,7 +33,7 @@ namespace Renderer::Backend { class IDeviceCommandContext; }
* This computes and binds per-vertex data; the modifier is responsible
* for setting any shader uniforms etc.
*/
class CPUSkinnedModelVertexRenderer : public ModelVertexRenderer
class CPUSkinnedModelVertexRenderer final : public ModelVertexRenderer
{
public:
CPUSkinnedModelVertexRenderer();

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -34,7 +34,7 @@ namespace Renderer::Backend { class IShaderProgram; }
* This computes and binds per-vertex data; the modifier is responsible
* for setting any shader uniforms etc.
*/
class GPUSkinnedModelModelRenderer : public ModelVertexRenderer
class GPUSkinnedModelModelRenderer final : public ModelVertexRenderer
{
public:
GPUSkinnedModelModelRenderer();

View file

@ -34,7 +34,7 @@ struct InstancingModelRendererInternals;
* This computes and binds per-vertex data; the modifier is responsible
* for setting any shader uniforms etc (including the instancing transform).
*/
class InstancingModelRenderer : public ModelVertexRenderer
class InstancingModelRenderer final : public ModelVertexRenderer
{
public:
InstancingModelRenderer();

View file

@ -102,15 +102,11 @@ CMaterial::Pass GetMaterialPassFromCullGroup(const int cullGroup, const ERenderM
}
void ModelRenderer::Init()
{
}
// Helper function to copy object-space position and normal vectors into arrays.
// static
void ModelRenderer::CopyPositionAndNormals(
const CModelDefPtr& mdef,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal)
const CModelDefPtr& mdef,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal)
{
size_t numVertices = mdef->GetNumVertices();
SModelVertex* vertices = mdef->GetVertices();
@ -122,11 +118,11 @@ void ModelRenderer::CopyPositionAndNormals(
}
}
// Helper function to transform position and normal vectors into world-space.
// static
void ModelRenderer::BuildPositionAndNormals(
CModel* model,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal)
CModel* model,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal)
{
CModelDefPtr mdef = model->GetModelDef();
size_t numVertices = mdef->GetNumVertices();
@ -160,43 +156,16 @@ void ModelRenderer::BuildPositionAndNormals(
}
}
// Helper function for lighting
void ModelRenderer::BuildColor4ub(
CModel* model,
const VertexArrayIterator<CVector3D>& Normal,
const VertexArrayIterator<SColor4ub>& Color)
{
PROFILE("lighting vertices");
CModelDefPtr mdef = model->GetModelDef();
size_t numVertices = mdef->GetNumVertices();
const CLightEnv& lightEnv = g_Renderer.GetSceneRenderer().GetLightEnv();
CColor shadingColor = model->GetShadingColor();
for (size_t j = 0; j < numVertices; ++j)
{
RGBColor tempcolor = lightEnv.EvaluateUnitScaled(Normal[j]);
tempcolor.X *= shadingColor.r;
tempcolor.Y *= shadingColor.g;
tempcolor.Z *= shadingColor.b;
Color[j] = ConvertRGBColorTo4ub(tempcolor);
}
}
// static
void ModelRenderer::GenTangents(const CModelDefPtr& mdef, std::vector<float>& newVertices, bool gpuSkinning)
{
MikkTSpace ms(mdef, newVertices, gpuSkinning);
ms.Generate();
}
// Copy UV coordinates
// static
void ModelRenderer::BuildUV(
const CModelDefPtr& mdef,
const VertexArrayIterator<float[2]>& UV,
int UVset)
const CModelDefPtr& mdef, const VertexArrayIterator<float[2]>& UV, int UVset)
{
const size_t numVertices = mdef->GetNumVertices();
const size_t numberOfUVPerVertex = mdef->GetNumUVsPerVertex();
@ -209,11 +178,9 @@ void ModelRenderer::BuildUV(
}
}
// Build default indices array.
// static
void ModelRenderer::BuildIndices(
const CModelDefPtr& mdef,
const VertexArrayIterator<u16>& Indices)
const CModelDefPtr& mdef, const VertexArrayIterator<u16>& Indices)
{
size_t idxidx = 0;
SModelFace* faces = mdef->GetFaces();
@ -227,105 +194,6 @@ void ModelRenderer::BuildIndices(
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// ShaderModelRenderer implementation
/**
* Internal data of the ShaderModelRenderer.
*
* Separated into the source file to increase implementation hiding (and to
* avoid some causes of recompiles).
*/
struct ShaderModelRenderer::ShaderModelRendererInternals
{
ShaderModelRendererInternals(ShaderModelRenderer* r) : m_Renderer(r) { }
/// Back-link to "our" renderer
ShaderModelRenderer* m_Renderer;
/// ModelVertexRenderer used for vertex transformations
ModelVertexRendererPtr vertexRenderer;
/// List of submitted models for rendering in this frame
std::vector<CModel*> submissions[CSceneRenderer::CULL_MAX];
};
// Construction/Destruction
ShaderModelRenderer::ShaderModelRenderer(ModelVertexRendererPtr vertexrenderer)
{
m = new ShaderModelRendererInternals(this);
m->vertexRenderer = vertexrenderer;
}
ShaderModelRenderer::~ShaderModelRenderer()
{
delete m;
}
// Submit one model.
void ShaderModelRenderer::Submit(int cullGroup, CModel* model)
{
CModelRData* rdata = (CModelRData*)model->GetRenderData();
// Ensure model data is valid
const void* key = m->vertexRenderer.get();
if (!rdata || rdata->GetKey() != key)
{
model->InvalidatePosition();
rdata = m->vertexRenderer->CreateModelData(key, model);
model->SetRenderData(rdata);
model->SetDirty(~0u);
}
m->submissions[cullGroup].push_back(model);
}
// Call update for all submitted models and enter the rendering phase
void ShaderModelRenderer::PrepareModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
{
for (int cullGroup = 0; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
for (CModel* model : m->submissions[cullGroup])
{
model->ValidatePosition();
CModelRData* rdata = static_cast<CModelRData*>(model->GetRenderData());
ENSURE(rdata->GetKey() == m->vertexRenderer.get());
}
m->vertexRenderer->UpdateModelsData(deviceCommandContext, m->submissions[cullGroup]);
for (CModel* model : m->submissions[cullGroup])
{
CModelRData* rdata = static_cast<CModelRData*>(model->GetRenderData());
rdata->m_UpdateFlags = 0;
}
}
}
void ShaderModelRenderer::UploadModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
{
for (int cullGroup = 0; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
m->vertexRenderer->UploadModelsData(deviceCommandContext, m->submissions[cullGroup]);
}
}
// Clear the submissions list
void ShaderModelRenderer::EndFrame()
{
for (int cullGroup = 0; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
m->submissions[cullGroup].clear();
}
// Helper structs for ShaderModelRenderer::Render():
struct SMRSortByDistItem
@ -413,12 +281,12 @@ struct SMRCompareTechBucket
}
};
void ShaderModelRenderer::Render(
void ModelRenderer::Render(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
const RenderModifierPtr& modifier, const CShaderDefines& context,
int cullGroup, int flags, const ERenderMode renderMode)
ModelVertexRenderer& modelVertexRenderer, RenderModifier& modifier, const CShaderDefines& context,
int cullGroup, int flags, const ERenderMode renderMode, std::span<CModel*> submissions)
{
if (m->submissions[cullGroup].empty())
if (submissions.empty())
return;
CMatrix3D worldToCam;
@ -429,7 +297,7 @@ void ShaderModelRenderer::Render(
/*
* Rendering approach:
*
* m->submissions contains the list of CModels to render.
* submissions contains the list of CModels to render.
*
* The data we need to render a model is:
* - CShaderTechnique
@ -497,10 +365,9 @@ void ShaderModelRenderer::Render(
{
PROFILE3("bucketing by material");
for (size_t i = 0; i < m->submissions[cullGroup].size(); ++i)
for (CModel* model : submissions)
{
CModel* model = m->submissions[cullGroup][i];
const CMaterial material{model->GetMaterial()};
const CMaterial& material{model->GetMaterial()};
const CShaderDefines& defines{material.GetShaderDefines()};
const CStrIntern shaderEffect{material.GetShaderEffect(materialPass)};
SMRMaterialBucketKey key(shaderEffect, defines);
@ -683,7 +550,7 @@ void ShaderModelRenderer::Render(
Renderer::Backend::IShaderProgram* shader = currentTech->GetShader(pass);
modifier->BeginPass(deviceCommandContext, shader);
modifier.BeginPass(deviceCommandContext, shader);
// TODO: Use a more generic approach to handle bound queries.
bool boundTime = false;
@ -753,7 +620,7 @@ void ShaderModelRenderer::Render(
if (newModeldef != currentModeldef)
{
currentModeldef = newModeldef;
m->vertexRenderer->PrepareModelDef(deviceCommandContext, *currentModeldef);
modelVertexRenderer.PrepareModelDef(deviceCommandContext, *currentModeldef);
}
// Bind all uniforms when any change
@ -813,12 +680,12 @@ void ShaderModelRenderer::Render(
}
}
modifier->PrepareModel(deviceCommandContext, model);
modifier.PrepareModel(deviceCommandContext, model);
CModelRData* rdata = static_cast<CModelRData*>(model->GetRenderData());
ENSURE(rdata->GetKey() == m->vertexRenderer.get());
ENSURE(rdata->GetKey() == &modelVertexRenderer);
m->vertexRenderer->RenderModel(deviceCommandContext, shader, model, rdata);
modelVertexRenderer.RenderModel(deviceCommandContext, shader, model, rdata);
}
}

View file

@ -30,6 +30,7 @@
#include "lib/types.h"
#include <memory>
#include <span>
#include <vector>
class CModel;
@ -39,17 +40,8 @@ namespace Renderer::Backend { class IDeviceCommandContext; }
struct SColor4ub;
template <typename T> class VertexArrayIterator;
class RenderModifier;
typedef std::shared_ptr<RenderModifier> RenderModifierPtr;
class LitRenderModifier;
typedef std::shared_ptr<LitRenderModifier> LitRenderModifierPtr;
class ModelVertexRenderer;
typedef std::shared_ptr<ModelVertexRenderer> ModelVertexRendererPtr;
class ModelRenderer;
typedef std::shared_ptr<ModelRenderer> ModelRendererPtr;
class RenderModifier;
/**
* Class CModelRData: Render data that is maintained per CModel.
@ -83,25 +75,12 @@ private:
/**
* Class ModelRenderer: Abstract base class for all model renders.
* ModelRenderer renders a per-frame list of models. It loads the appropriate
* shaders for rendering each model, and that batches by shader technique (and
* by mesh and texture).
*
* A ModelRenderer manages a per-frame list of models.
*
* It is supposed to be derived in order to create new ways in which
* the per-frame list of models can be managed (for batching, for
* transparent rendering, etc.) or potentially for rarely used special
* effects.
*
* A typical ModelRenderer will delegate vertex transformation/setup
* to a ModelVertexRenderer.
* It will delegate fragment stage setup to a RenderModifier.
*
* For most purposes, you should use a BatchModelRenderer with
* specialized ModelVertexRenderer and RenderModifier implementations.
*
* It is suggested that a derived class implement the provided generic
* Render function, however in some cases it may be necessary to supply
* a Render function with a different prototype.
* ModelRenderer delegates vertex transformation/setup to a
* ModelVertexRenderer. It delegates fragment stage setup to a RenderModifier.
*
* ModelRenderer also contains a number of static helper functions
* for building vertex arrays.
@ -109,61 +88,10 @@ private:
class ModelRenderer
{
public:
ModelRenderer() { }
virtual ~ModelRenderer() { }
/**
* Initialise global settings.
* Should be called before using the class.
*/
static void Init();
/**
* Submit: Submit a model for rendering this frame.
*
* preconditions : The model must not have been submitted to any
* ModelRenderer in this frame. Submit may only be called
* after EndFrame and before PrepareModels.
*
* @param model The model that will be added to the list of models
* submitted this frame.
*/
virtual void Submit(int cullGroup, CModel* model) = 0;
/**
* PrepareModels: Calculate renderer data for all previously
* submitted models.
*
* Must be called before any rendering calls and after all models
* for this frame have been submitted.
*/
virtual void PrepareModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext) = 0;
/**
* Upload renderer data for all previously submitted models to backend.
*
* Must be called before any rendering calls and after all models
* for this frame have been prepared.
*/
virtual void UploadModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext) = 0;
/**
* EndFrame: Remove all models from the list of submitted
* models.
*/
virtual void EndFrame() = 0;
/**
* Render: Render submitted models, using the given RenderModifier to setup
* the fragment stage.
*
* @note It is suggested that derived model renderers implement and use
* this Render functions. However, a highly specialized model renderer
* may need to "disable" this function and provide its own Render function
* with a different prototype.
*
* preconditions : PrepareModels must be called after all models have been
* submitted and before calling Render.
*
@ -172,10 +100,10 @@ public:
* If flags is non-zero, only models that contain flags in their
* CModel::GetFlags() are rendered.
*/
virtual void Render(
void Render(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
const RenderModifierPtr& modifier, const CShaderDefines& context,
int cullGroup, int flags, const ERenderMode renderMode) = 0;
ModelVertexRenderer& modelVertexRenderer, RenderModifier& modifier, const CShaderDefines& context,
int cullGroup, int flags, const ERenderMode renderMode, std::span<CModel*> submissions);
/**
* CopyPositionAndNormals: Copy unanimated object-space vertices and
@ -190,9 +118,9 @@ public:
* The array behind the iterator must be as large as the Position array.
*/
static void CopyPositionAndNormals(
const CModelDefPtr& mdef,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal);
const CModelDefPtr& mdef,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal);
/**
* BuildPositionAndNormals: Build animated vertices and normals,
@ -209,25 +137,9 @@ public:
* the Position array.
*/
static void BuildPositionAndNormals(
CModel* model,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal);
/**
* BuildColor4ub: Build lighting colors for the given model,
* based on previously calculated world space normals.
*
* @param model The model that is to be lit.
* @param Normal Array of the model's normal vectors, animated and
* transformed into world space.
* @param Color Points to the array that will receive the lit vertex color.
* The array behind the iterator must large enough to hold
* model->GetModelDef()->GetNumVertices() vertices.
*/
static void BuildColor4ub(
CModel* model,
const VertexArrayIterator<CVector3D>& Normal,
const VertexArrayIterator<SColor4ub>& Color);
CModel* model,
const VertexArrayIterator<CVector3D>& Position,
const VertexArrayIterator<CVector3D>& Normal);
/**
* BuildUV: Copy UV coordinates into the given vertex array.
@ -238,9 +150,9 @@ public:
* mdef->GetNumVertices() vertices.
*/
static void BuildUV(
const CModelDefPtr& mdef,
const VertexArrayIterator<float[2]>& UV,
int UVset);
const CModelDefPtr& mdef,
const VertexArrayIterator<float[2]>& UV,
int UVset);
/**
* BuildIndices: Create the indices array for the given CModelDef.
@ -250,8 +162,7 @@ public:
* mdef->GetNumFaces()*3 elements.
*/
static void BuildIndices(
const CModelDefPtr& mdef,
const VertexArrayIterator<u16>& Indices);
const CModelDefPtr& mdef, const VertexArrayIterator<u16>& Indices);
/**
* GenTangents: Generate tangents for the given CModelDef.
@ -263,33 +174,4 @@ public:
static void GenTangents(const CModelDefPtr& mdef, std::vector<float>& newVertices, bool gpuSkinning);
};
/**
* Implementation of ModelRenderer that loads the appropriate shaders for
* rendering each model, and that batches by shader technique (and by mesh and texture).
*/
class ShaderModelRenderer : public ModelRenderer
{
friend struct ShaderModelRendererInternals;
public:
ShaderModelRenderer(ModelVertexRendererPtr vertexrender);
~ShaderModelRenderer() override;
// Batching implementations
void Submit(int cullGroup, CModel* model) override;
void PrepareModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext) override;
void UploadModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext) override;
void EndFrame() override;
void Render(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
const RenderModifierPtr& modifier, const CShaderDefines& context,
int cullGroup, int flags, const ERenderMode renderMode) override;
private:
struct ShaderModelRendererInternals;
ShaderModelRendererInternals* m;
};
#endif // INCLUDED_MODELRENDERER

View file

@ -62,7 +62,6 @@
#include "ps/VideoMode.h"
#include "ps/World.h"
#include "renderer/DebugRenderer.h"
#include "renderer/ModelRenderer.h"
#include "renderer/PostprocManager.h"
#include "renderer/RenderingOptions.h"
#include "renderer/SceneRenderer.h"
@ -456,7 +455,6 @@ CRenderer::CRenderer(Renderer::Backend::IDevice* device)
ModelDefActivateFastImpl();
ColorActivateFastImpl();
ModelRenderer::Init();
}
CRenderer::~CRenderer()

View file

@ -212,17 +212,17 @@ void CRenderingOptions::ReadConfigAndSetupHooks()
m_ConfigHooks->Setup("silhouettes", m_Silhouettes);
m_ConfigHooks->Setup("gpuskinning", [this]() {
const Renderer::Backend::IDevice::Capabilities& capabilities{
g_VideoMode.GetBackendDevice()->GetCapabilities()};
if (!g_ConfigDB.Get("gpuskinning", false))
return;
if (capabilities.computeShaders && capabilities.storage)
m_GPUSkinning = true;
else
if (g_ConfigDB.Get("gpuskinning", false))
{
m_GPUSkinning = false;
LOGMESSAGE("GPU skinning isn't supported on the current hardware.");
const Renderer::Backend::IDevice::Capabilities& capabilities{
g_VideoMode.GetBackendDevice()->GetCapabilities()};
if (capabilities.computeShaders && capabilities.storage)
m_GPUSkinning = true;
else
{
m_GPUSkinning = false;
LOGMESSAGE("GPU skinning isn't supported on the current hardware.");
}
}
if (CRenderer::IsInitialised())

View file

@ -68,6 +68,7 @@
#include <algorithm>
#include <cmath>
#include <optional>
struct SScreenRect
{
@ -115,78 +116,192 @@ public:
SilhouetteRenderer silhouetteRenderer;
/// Various model renderers
// Various model renderers
struct Models
{
// NOTE: The current renderer design (with ModelRenderer, ModelVertexRenderer,
// RenderModifier, etc) is mostly a relic of an older design that implemented
// the different materials and rendering modes through extensive subclassing
// and hooking objects together in various combinations.
// The new design uses the CShaderManager API to abstract away the details
// of rendering, and uses a data-driven approach to materials, so there are
// now a small number of generic subclasses instead of many specialised subclasses,
// but most of the old infrastructure hasn't been refactored out yet and leads to
// some unwanted complexity.
// Submitted models are split on two axes:
// - Normal vs Transp[arent] - alpha-blended models are stored in a separate
// - Opaque vs Transparent - alpha-blended models are stored in a separate
// list so we can draw them above/below the alpha-blended water plane correctly
// - Skinned vs Unskinned - with hardware lighting we don't need to
// duplicate mesh data per model instance (except for skinned models),
// so non-skinned models get different ModelVertexRenderers
// - Skinned vs Unskinned - we don't need to duplicate mesh data per
// model instance (except for skinned models), so non-skinned models
// get different ModelVertexRenderers
ModelRendererPtr NormalSkinned;
ModelRendererPtr NormalUnskinned; // == NormalSkinned if unskinned shader instancing not supported
ModelRendererPtr TranspSkinned;
ModelRendererPtr TranspUnskinned; // == TranspSkinned if unskinned shader instancing not supported
struct Submissions
{
std::vector<CModel*> submissions[CSceneRenderer::CULL_MAX];
};
ModelVertexRendererPtr VertexRendererShader;
ModelVertexRendererPtr VertexInstancingShader;
ModelVertexRendererPtr VertexGPUSkinningShader;
// Unskinned submissions should be prepared and rendered with
// VertexInstancingShader. Skinned - with Vertex*SkinningShader
// depending on whether GPU skinning is enabled.
Submissions OpaqueSkinned;
Submissions OpaqueUnskinned;
Submissions TransparentSkinned;
Submissions TransparentUnskinned;
LitRenderModifierPtr ModShader;
ModelRenderer modelRenderer;
InstancingModelRenderer VertexInstancingShader;
CPUSkinnedModelVertexRenderer VertexCPUSkinningShader;
// We can't create GPU skinning renderer for renderer devices without
// its support.
std::optional<GPUSkinnedModelModelRenderer> VertexGPUSkinningShader;
ShaderRenderModifier ModShader;
bool GPUSkinningEnabled{false};
} Model;
CShaderDefines globalContext;
/**
* Upload renderer data for all previously submitted models to backend.
*
* Must be called before any rendering calls and after all models
* for this frame have been prepared.
*/
void UploadModels(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
{
PROFILE3("upload models");
ModelVertexRenderer& modelVertexSkinningRenderer{
Model.GPUSkinningEnabled
? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
: static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
modelVertexSkinningRenderer.UploadModelsData(deviceCommandContext, Model.OpaqueSkinned.submissions[cullGroup]);
modelVertexSkinningRenderer.UploadModelsData(deviceCommandContext, Model.TransparentSkinned.submissions[cullGroup]);
}
for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
Model.VertexInstancingShader.UploadModelsData(deviceCommandContext, Model.OpaqueUnskinned.submissions[cullGroup]);
Model.VertexInstancingShader.UploadModelsData(deviceCommandContext, Model.TransparentUnskinned.submissions[cullGroup]);
}
}
/**
* PrepareModels: Calculate renderer data for all previously
* submitted models.
*
* Must be called before any rendering calls and after all models
* for this frame have been submitted.
*/
void PrepareModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
{
PROFILE3("prepare models");
ModelVertexRenderer& modelVertexSkinningRenderer{
Model.GPUSkinningEnabled
? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
: static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
PrepareModels(deviceCommandContext, modelVertexSkinningRenderer, Model.OpaqueSkinned.submissions[cullGroup]);
PrepareModels(deviceCommandContext, modelVertexSkinningRenderer, Model.TransparentSkinned.submissions[cullGroup]);
}
for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
PrepareModels(deviceCommandContext, Model.VertexInstancingShader, Model.OpaqueUnskinned.submissions[cullGroup]);
PrepareModels(deviceCommandContext, Model.VertexInstancingShader, Model.TransparentUnskinned.submissions[cullGroup]);
}
}
void PrepareModels(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext, ModelVertexRenderer& modelVertexRenderer, std::span<CModel*> submissions)
{
for (CModel* model : submissions)
{
model->ValidatePosition();
CModelRData* rdata = static_cast<CModelRData*>(model->GetRenderData());
ENSURE(rdata->GetKey() == &modelVertexRenderer);
}
modelVertexRenderer.UpdateModelsData(deviceCommandContext, submissions);
for (CModel* model : submissions)
{
CModelRData* rdata = static_cast<CModelRData*>(model->GetRenderData());
rdata->m_UpdateFlags = 0;
}
}
/**
* Submit: Submit a model for rendering this frame.
*
* preconditions : The model must not have been submitted to any
* ModelRenderer in this frame. Submit may only be called
* after EndFrame and before PrepareModels.
*
* @param model The model that will be added to the list of models
* submitted this frame.
*/
void Submit(const int cullGroup, ModelVertexRenderer& modelVertexRenderer, Models::Submissions& submissions, CModel* model)
{
CModelRData* rdata{static_cast<CModelRData*>(model->GetRenderData())};
// Ensure model data is valid.
// TODO: using a pointer as a key is unsafe.
const void* key{&modelVertexRenderer};
if (!rdata || rdata->GetKey() != key)
{
model->InvalidatePosition();
rdata = modelVertexRenderer.CreateModelData(key, model);
model->SetRenderData(rdata);
model->SetDirty(~0u);
}
submissions.submissions[cullGroup].push_back(model);
}
/**
* Renders all non-alpha-blended models with the given context.
*/
void CallModelRenderers(
void CallOpaqueModelRenderers(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
const CShaderDefines& context, int cullGroup, int flags, const ERenderMode renderMode)
{
CShaderDefines contextSkinned = context;
if (g_RenderingOptions.GetGPUSkinning())
contextSkinned.Add(str_USE_INSTANCING, str_1);
Model.NormalSkinned->Render(deviceCommandContext, Model.ModShader, contextSkinned, cullGroup, flags, renderMode);
ModelVertexRenderer& modelVertexSkinningRenderer{
Model.GPUSkinningEnabled
? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
: static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
if (Model.NormalUnskinned != Model.NormalSkinned)
{
CShaderDefines contextUnskinned = context;
contextUnskinned.Add(str_USE_INSTANCING, str_1);
Model.NormalUnskinned->Render(deviceCommandContext, Model.ModShader, contextUnskinned, cullGroup, flags, renderMode);
}
CShaderDefines contextSkinned = context;
if (Model.GPUSkinningEnabled)
contextSkinned.Add(str_USE_INSTANCING, str_1);
Model.modelRenderer.Render(deviceCommandContext, modelVertexSkinningRenderer, Model.ModShader, contextSkinned, cullGroup, flags, renderMode, Model.OpaqueSkinned.submissions[cullGroup]);
CShaderDefines contextUnskinned = context;
contextUnskinned.Add(str_USE_INSTANCING, str_1);
Model.modelRenderer.Render(deviceCommandContext, Model.VertexInstancingShader, Model.ModShader, contextUnskinned, cullGroup, flags, renderMode, Model.OpaqueUnskinned.submissions[cullGroup]);
}
/**
* Renders all alpha-blended models with the given context.
*/
void CallTranspModelRenderers(
void CallTransparentModelRenderers(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
const CShaderDefines& context, int cullGroup, int flags, const ERenderMode renderMode)
{
CShaderDefines contextSkinned = context;
if (g_RenderingOptions.GetGPUSkinning())
contextSkinned.Add(str_USE_INSTANCING, str_1);
Model.TranspSkinned->Render(deviceCommandContext, Model.ModShader, contextSkinned, cullGroup, flags, renderMode);
ModelVertexRenderer& modelVertexSkinningRenderer{
Model.GPUSkinningEnabled
? static_cast<ModelVertexRenderer&>(*Model.VertexGPUSkinningShader)
: static_cast<ModelVertexRenderer&>(Model.VertexCPUSkinningShader)};
if (Model.TranspUnskinned != Model.TranspSkinned)
{
CShaderDefines contextUnskinned = context;
contextUnskinned.Add(str_USE_INSTANCING, str_1);
Model.TranspUnskinned->Render(deviceCommandContext, Model.ModShader, contextUnskinned, cullGroup, flags, renderMode);
}
CShaderDefines contextSkinned = context;
if (Model.GPUSkinningEnabled)
contextSkinned.Add(str_USE_INSTANCING, str_1);
Model.modelRenderer.Render(deviceCommandContext, modelVertexSkinningRenderer, Model.ModShader, contextSkinned, cullGroup, flags, renderMode, Model.TransparentSkinned.submissions[cullGroup]);
CShaderDefines contextUnskinned = context;
contextUnskinned.Add(str_USE_INSTANCING, str_1);
Model.modelRenderer.Render(deviceCommandContext, Model.VertexInstancingShader, Model.ModShader, contextUnskinned, cullGroup, flags, renderMode, Model.TransparentUnskinned.submissions[cullGroup]);
}
};
@ -239,26 +354,12 @@ void CSceneRenderer::ReloadShaders([[maybe_unused]] Renderer::Backend::IDevice*
m->globalContext.Add(str_RENDER_DEBUG_MODE,
RenderDebugModeEnum::ToString(g_RenderingOptions.GetRenderDebugMode()));
m->Model.ModShader = LitRenderModifierPtr(new ShaderRenderModifier());
m->Model.VertexRendererShader = ModelVertexRendererPtr(new CPUSkinnedModelVertexRenderer());
m->Model.VertexInstancingShader = ModelVertexRendererPtr(new InstancingModelRenderer());
if (g_RenderingOptions.GetGPUSkinning())
m->Model.GPUSkinningEnabled = g_RenderingOptions.GetGPUSkinning();
if (m->Model.GPUSkinningEnabled)
{
m->Model.VertexGPUSkinningShader = ModelVertexRendererPtr(new GPUSkinnedModelModelRenderer());
m->Model.NormalSkinned = ModelRendererPtr(new ShaderModelRenderer(m->Model.VertexGPUSkinningShader));
m->Model.TranspSkinned = ModelRendererPtr(new ShaderModelRenderer(m->Model.VertexGPUSkinningShader));
if (!m->Model.VertexGPUSkinningShader.has_value())
m->Model.VertexGPUSkinningShader.emplace();
}
else
{
m->Model.VertexGPUSkinningShader.reset();
m->Model.NormalSkinned = ModelRendererPtr(new ShaderModelRenderer(m->Model.VertexRendererShader));
m->Model.TranspSkinned = ModelRendererPtr(new ShaderModelRenderer(m->Model.VertexRendererShader));
}
m->Model.NormalUnskinned = ModelRendererPtr(new ShaderModelRenderer(m->Model.VertexInstancingShader));
m->Model.TranspUnskinned = ModelRendererPtr(new ShaderModelRenderer(m->Model.VertexInstancingShader));
}
void CSceneRenderer::Initialize()
@ -282,8 +383,8 @@ void CSceneRenderer::Resize(int /*width*/, int /*height*/)
void CSceneRenderer::BeginFrame()
{
// choose model renderers for this frame
m->Model.ModShader->SetShadowMap(&m->shadow);
m->Model.ModShader->SetLightEnv(m_LightEnv);
m->Model.ModShader.SetShadowMap(&m->shadow);
m->Model.ModShader.SetLightEnv(m_LightEnv);
}
void CSceneRenderer::SetSimulation(CSimulation2* simulation)
@ -315,12 +416,12 @@ void CSceneRenderer::RenderShadowMap(
{
PROFILE("render models");
m->CallModelRenderers(deviceCommandContext, {}, cullGroup, ModelFlag::CAST_SHADOWS, ERenderMode::SOLID);
m->CallOpaqueModelRenderers(deviceCommandContext, {}, cullGroup, ModelFlag::CAST_SHADOWS, ERenderMode::SOLID);
}
{
PROFILE("render transparent models");
m->CallTranspModelRenderers(deviceCommandContext, {}, cullGroup, ModelFlag::CAST_SHADOWS, ERenderMode::SOLID);
m->CallTransparentModelRenderers(deviceCommandContext, {}, cullGroup, ModelFlag::CAST_SHADOWS, ERenderMode::SOLID);
}
}
@ -363,10 +464,10 @@ void CSceneRenderer::RenderModels(
const ERenderMode modelRenderMode{
m_ModelRenderMode == WIREFRAME ? WIREFRAME : SOLID};
m->CallModelRenderers(deviceCommandContext, context, cullGroup, flags, modelRenderMode);
m->CallOpaqueModelRenderers(deviceCommandContext, context, cullGroup, flags, modelRenderMode);
if (m_ModelRenderMode == EDGED_FACES)
m->CallModelRenderers(deviceCommandContext, {}, cullGroup, flags, EDGED_FACES);
m->CallOpaqueModelRenderers(deviceCommandContext, {}, cullGroup, flags, EDGED_FACES);
}
void CSceneRenderer::RenderTransparentModels(
@ -388,13 +489,13 @@ void CSceneRenderer::RenderTransparentModels(
m_ModelRenderMode == WIREFRAME ? WIREFRAME : SOLID};
if (transparentMode == TRANSPARENT || transparentMode == TRANSPARENT_OPAQUE)
m->CallTranspModelRenderers(deviceCommandContext, contextOpaque, cullGroup, flags, modelRenderMode);
m->CallTransparentModelRenderers(deviceCommandContext, contextOpaque, cullGroup, flags, modelRenderMode);
if (transparentMode == TRANSPARENT || transparentMode == TRANSPARENT_BLEND)
m->CallTranspModelRenderers(deviceCommandContext, contextBlend, cullGroup, flags, modelRenderMode);
m->CallTransparentModelRenderers(deviceCommandContext, contextBlend, cullGroup, flags, modelRenderMode);
if (m_ModelRenderMode == EDGED_FACES)
m->CallTranspModelRenderers(deviceCommandContext, {}, cullGroup, flags, EDGED_FACES);
m->CallTransparentModelRenderers(deviceCommandContext, {}, cullGroup, flags, EDGED_FACES);
}
// SetObliqueFrustumClipping: change the near plane to the given clip plane (in world space)
@ -709,24 +810,24 @@ void CSceneRenderer::RenderSilhouettes(
{
PROFILE("render model occluders");
m->CallModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_OCCLUDER, 0, ERenderMode::SOLID);
m->CallOpaqueModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_OCCLUDER, 0, ERenderMode::SOLID);
}
{
PROFILE("render transparent occluders");
m->CallTranspModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_OCCLUDER, 0, ERenderMode::SOLID);
m->CallTransparentModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_OCCLUDER, 0, ERenderMode::SOLID);
}
// Since we can't sort, we'll use the stencil buffer to ensure we only draw
// a pixel once (using the color of whatever model happens to be drawn first).
{
PROFILE("render model casters");
m->CallModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_CASTER, 0, ERenderMode::SOLID);
m->CallOpaqueModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_CASTER, 0, ERenderMode::SOLID);
}
{
PROFILE("render transparent casters");
m->CallTranspModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_CASTER, 0, ERenderMode::SOLID);
m->CallTransparentModelRenderers(deviceCommandContext, {}, CULL_SILHOUETTE_CASTER, 0, ERenderMode::SOLID);
}
}
@ -770,15 +871,7 @@ void CSceneRenderer::PrepareSubmissions(
CShaderDefines context = m->globalContext;
// Prepare model renderers
{
PROFILE3("prepare models");
m->Model.NormalSkinned->PrepareModels(deviceCommandContext);
m->Model.TranspSkinned->PrepareModels(deviceCommandContext);
if (m->Model.NormalUnskinned != m->Model.NormalSkinned)
m->Model.NormalUnskinned->PrepareModels(deviceCommandContext);
if (m->Model.TranspUnskinned != m->Model.TranspSkinned)
m->Model.TranspUnskinned->PrepareModels(deviceCommandContext);
}
m->PrepareModels(deviceCommandContext);
m->terrainRenderer.PrepareForRendering();
@ -786,15 +879,7 @@ void CSceneRenderer::PrepareSubmissions(
m->particleRenderer.PrepareForRendering(context);
{
PROFILE3("upload models");
m->Model.NormalSkinned->UploadModels(deviceCommandContext);
m->Model.TranspSkinned->UploadModels(deviceCommandContext);
if (m->Model.NormalUnskinned != m->Model.NormalSkinned)
m->Model.NormalUnskinned->UploadModels(deviceCommandContext);
if (m->Model.TranspUnskinned != m->Model.TranspSkinned)
m->Model.TranspUnskinned->UploadModels(deviceCommandContext);
}
m->UploadModels(deviceCommandContext);
m->overlayRenderer.Upload(deviceCommandContext);
@ -908,13 +993,13 @@ void CSceneRenderer::EndFrame()
m->particleRenderer.EndFrame();
m->silhouetteRenderer.EndFrame();
// Finish model renderers
m->Model.NormalSkinned->EndFrame();
m->Model.TranspSkinned->EndFrame();
if (m->Model.NormalUnskinned != m->Model.NormalSkinned)
m->Model.NormalUnskinned->EndFrame();
if (m->Model.TranspUnskinned != m->Model.TranspSkinned)
m->Model.TranspUnskinned->EndFrame();
for (int cullGroup{0}; cullGroup < CSceneRenderer::CULL_MAX; ++cullGroup)
{
m->Model.OpaqueSkinned.submissions[cullGroup].clear();
m->Model.TransparentSkinned.submissions[cullGroup].clear();
m->Model.OpaqueUnskinned.submissions[cullGroup].clear();
m->Model.TransparentUnskinned.submissions[cullGroup].clear();
}
}
void CSceneRenderer::DisplayFrustum(Renderer::Backend::IDeviceCommandContext& deviceCommandContext)
@ -1029,21 +1114,25 @@ void CSceneRenderer::SubmitNonRecursive(CModel* model)
m->shadow.AddShadowCasterBound(cascade, model->GetWorldBounds());
}
bool requiresSkinning = (model->GetModelDef()->GetNumBones() != 0);
const bool requiresSkinning{model->GetModelDef()->GetNumBones() != 0};
ModelVertexRenderer& modelVertexSkinningRenderer{
m->Model.GPUSkinningEnabled
? static_cast<ModelVertexRenderer&>(*m->Model.VertexGPUSkinningShader)
: static_cast<ModelVertexRenderer&>(m->Model.VertexCPUSkinningShader)};
if (model->GetMaterial().UsesAlphaBlending())
{
if (requiresSkinning)
m->Model.TranspSkinned->Submit(m_CurrentCullGroup, model);
m->Submit(m_CurrentCullGroup, modelVertexSkinningRenderer, m->Model.TransparentSkinned, model);
else
m->Model.TranspUnskinned->Submit(m_CurrentCullGroup, model);
m->Submit(m_CurrentCullGroup, m->Model.VertexInstancingShader, m->Model.TransparentUnskinned, model);
}
else
{
if (requiresSkinning)
m->Model.NormalSkinned->Submit(m_CurrentCullGroup, model);
m->Submit(m_CurrentCullGroup, modelVertexSkinningRenderer, m->Model.OpaqueSkinned, model);
else
m->Model.NormalUnskinned->Submit(m_CurrentCullGroup, model);
m->Submit(m_CurrentCullGroup, m->Model.VertexInstancingShader, m->Model.OpaqueUnskinned, model);
}
}

View file

@ -90,21 +90,21 @@ CStr CScriptStatsTable::GetCellText(size_t row, size_t col)
if (col == 0)
return "max nominal heap bytes";
uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetGeneralJSContext(), JSGC_MAX_BYTES);
return CStr::FromUInt(n);
return std::to_string(n);
}
case Row_Bytes:
{
if (col == 0)
return "allocated bytes";
uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetGeneralJSContext(), JSGC_BYTES);
return CStr::FromUInt(n);
return std::to_string(n);
}
case Row_NumberGC:
{
if (col == 0)
return "number of GCs";
uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetGeneralJSContext(), JSGC_NUMBER);
return CStr::FromUInt(n);
return std::to_string(n);
}
default:
return "???";
@ -116,4 +116,4 @@ AbstractProfileTable* CScriptStatsTable::GetChild(size_t /*row*/)
return 0;
}
} // namespace Script
} // namespace Script

View file

@ -92,13 +92,13 @@ public:
return serializationTestOption ? serializationTestOption->turn :
std::max(CConfigDB::GetIfInitialised("serializationtest", -1), -1);
}()},
m_RejoinTestTurn{[&]() -> std::optional<int>
m_RejoinTestTurn{[&]() -> std::optional<turn_id_t>
{
const auto* rejoinTestOption{
std::get_if<SimulationDebugOptions::RejoinTest>(&debugOptions.test)};
if (rejoinTestOption)
return rejoinTestOption->turn;
const int configVal{CConfigDB::GetIfInitialised("rejointest", -1)};
const turn_id_t configVal{CConfigDB::GetIfInitialised("rejointest", -1)};
if (configVal >= 0)
return configVal;
return std::nullopt;
@ -163,17 +163,17 @@ public:
std::set<VfsPath> m_LoadedScripts;
uint32_t m_TurnNumber;
turn_id_t m_TurnNumber;
bool m_EnableOOSLog{false};
OsPath m_OOSLogPath;
// Functions and data for the serialization test mode: (see Update() for relevant comments)
std::optional<int> m_SerializationTestTurn;
std::optional<turn_id_t> m_SerializationTestTurn;
bool m_TestingSerialization{false};
bool m_EnableSerializationTest{false};
std::optional<int> m_RejoinTestTurn;
std::optional<turn_id_t> m_RejoinTestTurn;
bool m_TestingRejoin{false};
// Secondary simulation (NB: order matters for destruction).
@ -383,7 +383,7 @@ void CSimulation2Impl::InitRNGSeedAI()
void CSimulation2Impl::Update(int turnLength, const std::vector<SimulationCommand>& commands)
{
PROFILE3("sim update");
PROFILE2_ATTR("turn %d", (int)m_TurnNumber);
PROFILE2_ATTR("turn %d", m_TurnNumber);
fixed turnLengthFixed = fixed::FromInt(turnLength) / 1000;
@ -408,11 +408,11 @@ void CSimulation2Impl::Update(int turnLength, const std::vector<SimulationComman
const Script::Interface& scriptInterface = m_ComponentManager.GetScriptInterface();
const bool startSerializationTest = m_SerializationTestTurn.has_value() &&
std::cmp_equal(m_SerializationTestTurn.value(), m_TurnNumber);
m_SerializationTestTurn.value() == m_TurnNumber;
if (startSerializationTest)
m_TestingSerialization = true;
const bool startRejoinTest = m_RejoinTestTurn.has_value() &&
static_cast<int64_t>(m_RejoinTestTurn.value()) == m_TurnNumber;
m_RejoinTestTurn.value() == m_TurnNumber;
if (startRejoinTest)
m_TestingRejoin = true;
@ -891,11 +891,11 @@ bool CSimulation2::DeserializeState(std::istream& stream)
return m->m_ComponentManager.DeserializeState(stream);
}
void CSimulation2::ActivateRejoinTest(int turn)
void CSimulation2::ActivateRejoinTest(turn_id_t turn)
{
if (m->m_RejoinTestTurn.has_value())
return;
LOGMESSAGERENDER("Rejoin test will activate in %i turns", turn - m->m_TurnNumber);
LOGMESSAGERENDER("Rejoin test will activate in %d turns", turn - m->m_TurnNumber);
m->m_RejoinTestTurn = turn;
}

View file

@ -22,6 +22,7 @@
#include "lib/file/vfs/vfs_path.h"
#include "lib/status.h"
#include "ps/Loader.h"
#include "simulation2/helpers/SimulationCommand.h"
#include "simulation2/system/DebugOptions.h"
#include "simulation2/system/Entity.h"
@ -240,7 +241,7 @@ public:
/**
* Activate the rejoin-test feature for turn @param turn.
*/
void ActivateRejoinTest(int turn);
void ActivateRejoinTest(turn_id_t turn);
std::string GenerateSchema();

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -24,6 +24,12 @@
#include <js/TypeDecls.h>
#include <js/Value.h>
/**
* At 1000 turns/second, a 32-bit counter would overflow in ~49 days.
* No overflow checks are needed.
*/
using turn_id_t = std::int32_t;
struct JSContext;
/**

View file

@ -42,12 +42,12 @@ void CLocalTurnManager::PostCommand(JS::HandleValue data)
AddCommand(m_ClientId, m_PlayerId, data, m_CurrentTurn + m_CommandDelay);
}
void CLocalTurnManager::NotifyFinishedOwnCommands(u32 turn)
void CLocalTurnManager::NotifyFinishedOwnCommands(turn_id_t turn)
{
FinishedAllCommands(turn, m_TurnLength);
}
void CLocalTurnManager::NotifyFinishedUpdate(u32 /*turn*/, const UpdateCallback&)
void CLocalTurnManager::NotifyFinishedUpdate(turn_id_t /*turn*/, const UpdateCallback&)
{
#if 0 // this hurts performance and is only useful for verifying log replays
std::string hash;

View file

@ -41,9 +41,9 @@ public:
void PostCommand(player_id_t playerid, JS::HandleValue data);
protected:
void NotifyFinishedOwnCommands(u32 turn) override;
void NotifyFinishedOwnCommands(turn_id_t turn) override;
void NotifyFinishedUpdate(u32 turn, const UpdateCallback& sendEventToAll) override;
void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll) override;
};
#endif // INCLUDED_LOCALTURNMANAGER

View file

@ -47,18 +47,18 @@ CReplayTurnManager::CReplayTurnManager(CSimulation2& simulation, IReplayLogger&
{
}
void CReplayTurnManager::StoreReplayCommand(u32 turn, int player, const std::string& command)
void CReplayTurnManager::StoreReplayCommand(turn_id_t turn, int player, const std::string& command)
{
// Using the pair we make sure that commands per turn will be processed in the correct order
m_ReplayCommands[turn].emplace_back(player, command);
}
void CReplayTurnManager::StoreReplayHash(u32 turn, const std::string& hash, bool quick)
void CReplayTurnManager::StoreReplayHash(turn_id_t turn, const std::string& hash, bool quick)
{
m_ReplayHash[turn] = std::make_pair(hash, quick);
}
void CReplayTurnManager::StoreReplayTurnLength(u32 turn, u32 turnLength)
void CReplayTurnManager::StoreReplayTurnLength(turn_id_t turn, u32 turnLength)
{
m_ReplayTurnLengths[turn] = turnLength;
@ -67,12 +67,12 @@ void CReplayTurnManager::StoreReplayTurnLength(u32 turn, u32 turnLength)
m_TurnLength = m_ReplayTurnLengths[0];
}
void CReplayTurnManager::StoreFinalReplayTurn(u32 turn)
void CReplayTurnManager::StoreFinalReplayTurn(turn_id_t turn)
{
m_FinalTurn = turn;
}
void CReplayTurnManager::NotifyFinishedUpdate(u32 turn, const UpdateCallback& sendEventToAll)
void CReplayTurnManager::NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll)
{
if (turn == 1 && m_FinalTurn == 0)
sendEventToAll(EventNameReplayFinished, std::nullopt);
@ -83,7 +83,7 @@ void CReplayTurnManager::NotifyFinishedUpdate(u32 turn, const UpdateCallback& se
DoTurn(turn, sendEventToAll);
// Compare hash if it exists in the replay and if we didn't have an OOS already
std::map<u32, std::pair<std::string, bool>>::iterator turnHashIt = m_ReplayHash.find(turn);
std::map<turn_id_t, std::pair<std::string, bool>>::iterator turnHashIt = m_ReplayHash.find(turn);
if (m_HasSyncError || turnHashIt == m_ReplayHash.end())
return;
@ -119,9 +119,9 @@ void CReplayTurnManager::NotifyFinishedUpdate(u32 turn, const UpdateCallback& se
sendEventToAll(EventNameReplayOutOfSync, paramData);
}
void CReplayTurnManager::DoTurn(u32 turn, const UpdateCallback& sendEventToAll)
void CReplayTurnManager::DoTurn(turn_id_t turn, const UpdateCallback& sendEventToAll)
{
debug_printf("Executing turn %u of %u\n", turn, m_FinalTurn);
debug_printf("Executing turn %d of %d\n", turn, m_FinalTurn);
m_TurnLength = m_ReplayTurnLengths[turn];

View file

@ -40,18 +40,18 @@ class CReplayTurnManager : public CLocalTurnManager
public:
CReplayTurnManager(CSimulation2& simulation, IReplayLogger& replay);
void StoreReplayCommand(u32 turn, int player, const std::string& command);
void StoreReplayCommand(turn_id_t turn, int player, const std::string& command);
void StoreReplayTurnLength(u32 turn, u32 turnLength);
void StoreReplayTurnLength(turn_id_t turn, u32 turnLength);
void StoreReplayHash(u32 turn, const std::string& hash, bool quick);
void StoreReplayHash(turn_id_t turn, const std::string& hash, bool quick);
void StoreFinalReplayTurn(u32 turn);
void StoreFinalReplayTurn(turn_id_t turn);
private:
void NotifyFinishedUpdate(u32 turn, const UpdateCallback& sendEventToAll) override;
void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll) override;
void DoTurn(u32 turn, const UpdateCallback& sendEventToAll);
void DoTurn(turn_id_t turn, const UpdateCallback& sendEventToAll);
static const CStr EventNameReplayFinished;
static const CStr EventNameReplayOutOfSync;
@ -59,13 +59,13 @@ private:
bool m_HasSyncError = false;
// Contains the commands of every player on each turn
std::map<u32, std::vector<std::pair<player_id_t, std::string>>> m_ReplayCommands;
std::map<turn_id_t, std::vector<std::pair<player_id_t, std::string>>> m_ReplayCommands;
// Contains the length of every turn
std::map<u32, u32> m_ReplayTurnLengths;
std::map<turn_id_t, u32> m_ReplayTurnLengths;
// Contains all replay hash values and weather or not the quick hash method was used
std::map<u32, std::pair<std::string, bool>> m_ReplayHash;
std::map<turn_id_t, std::pair<std::string, bool>> m_ReplayHash;
};
#endif // INCLUDED_REPLAYTURNMANAGER

View file

@ -48,14 +48,14 @@ const CStr CTurnManager::EventNameSavegameLoaded = "SavegameLoaded";
CTurnManager::CTurnManager(CSimulation2& simulation, u32 defaultTurnLength, u32 commandDelay, int clientId, IReplayLogger& replay)
: m_Simulation2(simulation), m_CurrentTurn(0), m_CommandDelay(commandDelay), m_ReadyTurn(commandDelay - 1), m_TurnLength(defaultTurnLength),
m_PlayerId(-1), m_ClientId(clientId), m_DeltaSimTime(0), m_Replay(replay),
m_FinalTurn(std::numeric_limits<u32>::max()), m_TimeWarpNumTurns(0)
m_FinalTurn(std::numeric_limits<turn_id_t>::max()), m_TimeWarpNumTurns(0)
{
Script::Request rq(m_Simulation2.GetScriptInterface());
m_QuickSaveMetadata.init(rq.cx);
m_QueuedCommands.resize(1);
}
void CTurnManager::ResetState(u32 newCurrentTurn, u32 newReadyTurn)
void CTurnManager::ResetState(turn_id_t newCurrentTurn, turn_id_t newReadyTurn)
{
m_CurrentTurn = newCurrentTurn;
m_ReadyTurn = newReadyTurn;
@ -141,7 +141,7 @@ bool CTurnManager::Update(float simFrameLength, size_t maxTurns, const UpdateCal
// Put all the client commands into a single list, in a globally consistent order
std::vector<SimulationCommand> commands;
for (std::pair<const u32, std::vector<SimulationCommand>>& p : m_QueuedCommands[0])
for (std::pair<const turn_id_t, std::vector<SimulationCommand>>& p : m_QueuedCommands[0])
commands.insert(commands.end(), std::make_move_iterator(p.second.begin()), std::make_move_iterator(p.second.end()));
m_QueuedCommands.pop_front();
@ -184,7 +184,7 @@ bool CTurnManager::UpdateFastForward()
// Put all the client commands into a single list, in a globally consistent order
std::vector<SimulationCommand> commands;
for (std::pair<const u32, std::vector<SimulationCommand>>& p : m_QueuedCommands[0])
for (std::pair<const turn_id_t, std::vector<SimulationCommand>>& p : m_QueuedCommands[0])
commands.insert(commands.end(), std::make_move_iterator(p.second.begin()), std::make_move_iterator(p.second.end()));
m_QueuedCommands.pop_front();
@ -214,7 +214,7 @@ void CTurnManager::Interpolate(float simFrameLength, float realFrameLength)
m_Simulation2.Interpolate(simFrameLength, offset, realFrameLength);
}
void CTurnManager::AddCommand(int client, int player, JS::HandleValue data, u32 turn)
void CTurnManager::AddCommand(int client, int player, JS::HandleValue data, turn_id_t turn)
{
NETTURN_LOG("AddCommand(client=%d player=%d turn=%d current=%d, ready=%d)\n", client, player, turn, m_CurrentTurn, m_ReadyTurn);
@ -239,7 +239,7 @@ void CTurnManager::AddCommand(int client, int player, JS::HandleValue data, u32
m_QueuedCommands[turn - (m_CurrentTurn+1)][client].emplace_back(player, rq.cx, data);
}
void CTurnManager::FinishedAllCommands(u32 turn, u32 turnLength)
void CTurnManager::FinishedAllCommands(turn_id_t turn, u32 turnLength)
{
NETTURN_LOG("FinishedAllCommands(%d, %d)\n", turn, turnLength);
@ -248,7 +248,7 @@ void CTurnManager::FinishedAllCommands(u32 turn, u32 turnLength)
m_TurnLength = turnLength;
}
bool CTurnManager::TurnNeedsFullHash(u32 turn) const
bool CTurnManager::TurnNeedsFullHash(turn_id_t turn) const
{
// Check immediately for errors caused by e.g. inconsistent game versions
// (The hash is computed after the first sim update, so we start at turn == 1)

View file

@ -101,7 +101,7 @@ public:
virtual ~CTurnManager() { }
void ResetState(u32 newCurrentTurn, u32 newReadyTurn);
void ResetState(turn_id_t newCurrentTurn, turn_id_t newReadyTurn);
/**
* Set the current user's player ID, which will be added into command messages.
@ -146,7 +146,7 @@ public:
* Called when all commands for a given turn have been received.
* This allows Update to progress to that turn.
*/
void FinishedAllCommands(u32 turn, u32 turnLength);
void FinishedAllCommands(turn_id_t turn, u32 turnLength);
/**
* Enables the recording of state snapshots every @p numTurns,
@ -163,52 +163,52 @@ public:
void QuickSave(JS::HandleValue GUIMetadata);
std::optional<JS::Value> TryQuickLoad();
u32 GetCurrentTurn() const { return m_CurrentTurn; }
turn_id_t GetCurrentTurn() const { return m_CurrentTurn; }
/**
* @return how many turns are ready to be computed.
* (used to detect players/observers that fall behind the live game.
*/
u32 GetPendingTurns() const { return m_ReadyTurn - m_CurrentTurn; }
turn_id_t GetPendingTurns() const { return m_ReadyTurn - m_CurrentTurn; }
protected:
/**
* Store a command to be executed at a given turn.
*/
void AddCommand(int client, int player, JS::HandleValue data, u32 turn);
void AddCommand(int client, int player, JS::HandleValue data, turn_id_t turn);
/**
* Called when this client has finished sending all its commands scheduled for the given turn.
*/
virtual void NotifyFinishedOwnCommands(u32 turn) = 0;
virtual void NotifyFinishedOwnCommands(turn_id_t turn) = 0;
/**
* Called when this client has finished a simulation update.
*/
virtual void NotifyFinishedUpdate(u32 turn, const UpdateCallback& sendEventToAll) = 0;
virtual void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll) = 0;
/**
* Returns whether we should compute a complete state hash for the given turn,
* instead of a quick less-complete hash.
*/
bool TurnNeedsFullHash(u32 turn) const;
bool TurnNeedsFullHash(turn_id_t turn) const;
CSimulation2& m_Simulation2;
/// The turn that we have most recently executed
u32 m_CurrentTurn;
turn_id_t m_CurrentTurn;
// Current command delay (commands are scheduled for m_CurrentTurn + m_CommandDelay)
u32 m_CommandDelay;
/// The latest turn for which we have received all commands from all clients
u32 m_ReadyTurn;
turn_id_t m_ReadyTurn;
// Current turn length
u32 m_TurnLength;
/// Commands queued at each turn (index 0 is for m_CurrentTurn+1)
std::deque<std::map<u32, std::vector<SimulationCommand>>> m_QueuedCommands;
std::deque<std::map<turn_id_t, std::vector<SimulationCommand>>> m_QueuedCommands;
int m_PlayerId;
uint m_ClientId;
@ -220,7 +220,7 @@ protected:
IReplayLogger& m_Replay;
// The number of the last turn that is allowed to be executed (used for replays)
u32 m_FinalTurn;
turn_id_t m_FinalTurn;
private:
size_t m_TimeWarpNumTurns; // 0 if disabled

Some files were not shown because too many files have changed in this diff Show more