1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
|
# Launch System
## Overview
MeshMC's launch system orchestrates the process of starting a Minecraft game instance. It involves account authentication, component resolution, file preparation, JVM argument assembly, and process management. The launch system is built around a step-based pipeline that allows individual phases to be executed, paused, and resumed.
## Launch Architecture
### Key Classes
| Class | File | Purpose |
|---|---|---|
| `LaunchController` | `launcher/LaunchController.{h,cpp}` | High-level orchestrator, UI interaction |
| `LaunchTask` | `launcher/launch/LaunchTask.{h,cpp}` | Step pipeline executor |
| `LaunchStep` | `launcher/launch/LaunchStep.{h,cpp}` | Abstract step interface |
| `DirectJavaLaunch` | `minecraft/launch/DirectJavaLaunch.{h,cpp}` | JVM process spawner |
| `MeshMCPartLaunch` | `minecraft/launch/MeshMCPartLaunch.{h,cpp}` | Java-wrapped launcher |
| `LoggedProcess` | `launcher/LoggedProcess.{h,cpp}` | QProcess wrapper with logging |
| `LogModel` | `launcher/launch/LogModel.{h,cpp}` | Game log data model |
## LaunchController
`LaunchController` extends `Task` and handles the user-facing launch flow:
```cpp
class LaunchController : public Task
{
Q_OBJECT
public:
void executeTask() override;
void setInstance(InstancePtr instance);
void setOnline(bool online);
void setProfiler(BaseProfilerFactory* profiler);
void setParentWidget(QWidget* widget);
void setServerToJoin(MinecraftServerTargetPtr serverToJoin);
void setAccountToUse(MinecraftAccountPtr accountToUse);
bool abort() override;
private:
void login();
void launchInstance();
void decideAccount();
private slots:
void readyForLaunch();
void onSucceeded();
void onFailed(QString reason);
void onProgressRequested(Task* task);
private:
BaseProfilerFactory* m_profiler = nullptr;
bool m_online = true;
InstancePtr m_instance;
QWidget* m_parentWidget = nullptr;
InstanceWindow* m_console = nullptr;
MinecraftAccountPtr m_accountToUse = nullptr;
MinecraftServerTargetPtr m_serverToJoin;
};
```
### Launch Flow
```
LaunchController::executeTask()
│
├── decideAccount()
│ ├── If m_accountToUse is set → use it
│ ├── Else → get default account from AccountList
│ └── If no account → prompt user with ProfileSelectDialog
│
├── login()
│ ├── If online → authenticate via MSASilent (token refresh)
│ │ ├── On success → launchInstance()
│ │ └── On failure → fall back to MSAInteractive (browser login)
│ └── If offline → create offline AuthSession → launchInstance()
│
└── launchInstance()
├── instance->createUpdateTask(mode) → update game files if needed
├── instance->createLaunchTask(session, server) → build step pipeline
├── Connect LaunchTask signals to controller slots
└── LaunchTask::start()
```
### Account Decision (`decideAccount()`)
The account selection priority:
1. Explicitly provided `m_accountToUse` (from command line or UI)
2. Default account from `AccountList::defaultAccount()`
3. User prompt via `ProfileSelectDialog` if no default is set
### Authentication (`login()`)
For online mode:
1. Attempt `MSASilent` (token refresh using existing tokens)
2. If refresh fails, prompt for `MSAInteractive` (browser-based OAuth2 login)
3. On success, an `AuthSession` is created containing:
- Access token
- Player UUID
- Player name
- User type
For offline mode:
- An `AuthSession` is created with a dummy token
- The player name comes from the account profile
## LaunchTask
`LaunchTask` is the central pipeline executor:
```cpp
class LaunchTask : public Task
{
Q_OBJECT
public:
enum State { NotStarted, Running, Waiting, Failed, Aborted, Finished };
static shared_qobject_ptr<LaunchTask> create(InstancePtr inst);
void appendStep(shared_qobject_ptr<LaunchStep> step);
void prependStep(shared_qobject_ptr<LaunchStep> step);
void setCensorFilter(QMap<QString, QString> filter);
InstancePtr instance();
void setPid(qint64 pid);
qint64 pid();
void executeTask() override;
void proceed();
bool abort() override;
bool canAbort() const override;
shared_qobject_ptr<LogModel> getLogModel();
signals:
void log(QString text, MessageLevel::Enum level);
void readyForLaunch();
void requestProgress(Task* task);
void requestLogging();
};
```
### Step Execution Model
Steps are executed sequentially:
```
Step 0: executeTask() → completes → advance
Step 1: executeTask() → completes → advance
Step 2: executeTask() → emits readyForLaunch() → WAIT
User clicks "Launch" in console → proceed()
Step 3: executeTask() → starts JVM process → RUNNING
Process exits → completes → advance
Step N: finalize() called in reverse order
```
Each step can:
- **Complete immediately** — call `emitSucceeded()` to advance
- **Pause** — emit `readyForLaunch()` to wait for user interaction
- **Fail** — call `emitFailed()` to abort the pipeline
- **Run persistently** — stay active until an external event (process exit)
### Censor Filter
The `setCensorFilter()` method installs a string replacement map that redacts sensitive information from logs:
```cpp
void LaunchTask::setCensorFilter(QMap<QString, QString> filter);
```
`MinecraftInstance` populates this with:
- Access token → `<ACCESS TOKEN>`
- Client token → `<CLIENT TOKEN>`
- Player UUID → `<PROFILE ID>`
## LaunchStep
Abstract base class for individual launch steps:
```cpp
class LaunchStep : public Task
{
Q_OBJECT
public:
explicit LaunchStep(LaunchTask* parent)
: Task(nullptr), m_parent(parent) { bind(parent); }
signals:
void logLines(QStringList lines, MessageLevel::Enum level);
void logLine(QString line, MessageLevel::Enum level);
void readyForLaunch();
void progressReportingRequest();
public slots:
virtual void proceed() {}
virtual void finalize() {}
protected:
LaunchTask* m_parent;
};
```
## Minecraft Launch Steps
### Step Pipeline Construction
`MinecraftInstance::createLaunchTask()` builds the step pipeline for a Minecraft launch:
```cpp
shared_qobject_ptr<LaunchTask>
MinecraftInstance::createLaunchTask(AuthSessionPtr session,
MinecraftServerTargetPtr serverToJoin)
{
auto task = LaunchTask::create(std::dynamic_pointer_cast<MinecraftInstance>(
shared_from_this()));
// Step order:
task->appendStep(make_shared<VerifyJavaInstall>(task.get()));
task->appendStep(make_shared<CreateGameFolders>(task.get()));
task->appendStep(make_shared<ScanModFolders>(task.get()));
task->appendStep(make_shared<ExtractNatives>(task.get()));
task->appendStep(make_shared<ModMinecraftJar>(task.get()));
task->appendStep(make_shared<ReconstructAssets>(task.get()));
task->appendStep(make_shared<ClaimAccount>(task.get()));
task->appendStep(make_shared<PrintInstanceInfo>(task.get()));
// Choose launch method
auto method = launchMethod();
if (method == "LauncherPart") {
auto step = make_shared<MeshMCPartLaunch>(task.get());
step->setAuthSession(session);
step->setServerToJoin(serverToJoin);
task->appendStep(step);
} else {
auto step = make_shared<DirectJavaLaunch>(task.get());
step->setAuthSession(session);
step->setServerToJoin(serverToJoin);
task->appendStep(step);
}
// Set up censor filter
task->setCensorFilter(createCensorFilterFromSession(session));
return task;
}
```
### VerifyJavaInstall (`minecraft/launch/VerifyJavaInstall.h`)
Validates that the configured Java installation exists and is compatible:
- Checks that the Java binary exists at the configured path
- Verifies Java version meets minimum requirements
- Fails with descriptive error if Java is missing or incompatible
### CreateGameFolders (`minecraft/launch/CreateGameFolders.h`)
Ensures required directory structure exists:
- `.minecraft/` game directory
- `mods/`, `resourcepacks/`, `saves/` subdirectories
- `libraries/` for instance-local libraries
- `natives/` for platform-specific native libraries
### ScanModFolders (`minecraft/launch/ScanModFolders.h`)
Scans mod directories and updates the mod list:
- Enumerates `.minecraft/mods/` for loader mods
- Enumerates `.minecraft/coremods/` for core mods (Forge legacy)
- Updates the instance's mod models
### ExtractNatives (`minecraft/launch/ExtractNatives.h`)
Extracts platform-specific native libraries from JAR files:
- Iterates through native libraries in the `LaunchProfile`
- Extracts `.so` (Linux), `.dll` (Windows), or `.dylib` (macOS) files
- Places them in the `natives/` directory within the instance
### ModMinecraftJar (`minecraft/launch/ModMinecraftJar.h`)
Applies jar mods to the Minecraft game JAR:
- If jar mods are present in the component list, creates a modified JAR
- Overlays jar mod contents onto the vanilla JAR
- Stores the modified JAR for use by the launcher
### ReconstructAssets (`minecraft/launch/ReconstructAssets.h`)
Handles legacy asset management:
- For older Minecraft versions that use the "legacy" asset system
- Copies assets from the shared cache to the instance's `resources/` directory
- Modern versions use the asset index system and skip this step
### ClaimAccount (`minecraft/launch/ClaimAccount.h`)
Marks the account as in-use for this launch session:
- Prevents the same account from being used in concurrent launches
- Releases the claim when the game exits
### PrintInstanceInfo (`minecraft/launch/PrintInstanceInfo.h`)
Logs debug information to the console:
- Instance name and ID
- Minecraft version
- Java path and version
- JVM arguments
- Classpath
- Native library path
- Working directory
### DirectJavaLaunch (`minecraft/launch/DirectJavaLaunch.h`)
The primary launch step that spawns the JVM process:
```cpp
class DirectJavaLaunch : public LaunchStep
{
Q_OBJECT
public:
explicit DirectJavaLaunch(LaunchTask* parent);
virtual void executeTask();
virtual bool abort();
virtual void proceed();
virtual bool canAbort() const { return true; }
void setWorkingDirectory(const QString& wd);
void setAuthSession(AuthSessionPtr session);
void setServerToJoin(MinecraftServerTargetPtr serverToJoin);
private slots:
void on_state(LoggedProcess::State state);
private:
LoggedProcess m_process;
QString m_command;
AuthSessionPtr m_session;
MinecraftServerTargetPtr m_serverToJoin;
};
```
This step:
1. Assembles the full Java command line
2. Sets the working directory to the game root
3. Configures environment variables
4. Spawns the process via `LoggedProcess`
5. Connects to `on_state()` for process lifecycle events
6. Emits `readyForLaunch()` — the pipeline pauses until the user confirms
7. On `proceed()`, the process starts
8. Monitors the process until exit
### MeshMCPartLaunch (`minecraft/launch/MeshMCPartLaunch.h`)
Alternative launch method using MeshMC's Java-side launcher component:
- Writes launch parameters to a temporary file
- Starts the Java-side launcher (`libraries/launcher/`) which reads the parameters
- The Java launcher handles classpath assembly and game startup
- Provides additional launch customization capabilities
## JVM Argument Assembly
`MinecraftInstance` assembles JVM arguments through several methods:
### `javaArguments()`
Returns the complete list of JVM arguments:
```cpp
QStringList MinecraftInstance::javaArguments() const;
```
Components:
1. **Memory settings** — `-Xms<min>m -Xmx<max>m`
2. **Permission size** — `-XX:PermSize=<size>` (for older JVMs)
3. **Custom JVM args** — user-specified in instance/global settings
4. **System properties** — `-D` flags for various launchwrapper parameters
### `getClassPath()`
Builds the Java classpath:
```cpp
QStringList MinecraftInstance::getClassPath() const;
```
Sources:
1. Libraries from the resolved `LaunchProfile`
2. Maven files
3. Main game JAR (possibly modified by jar mods)
4. Instance-local libraries
### `getMainClass()`
Returns the Java main class:
```cpp
QString MinecraftInstance::getMainClass() const;
```
This comes from the resolved `LaunchProfile`, which may be:
- `net.minecraft.client.main.Main` — vanilla
- `net.minecraftforge.fml.launching.FMLClientLaunchProvider` — Forge
- `net.fabricmc.loader.impl.launch.knot.KnotClient` — Fabric
- `org.quiltmc.loader.impl.launch.knot.KnotClient` — Quilt
### `processMinecraftArgs()`
Template-expands game arguments:
```cpp
QStringList MinecraftInstance::processMinecraftArgs(
AuthSessionPtr account,
MinecraftServerTargetPtr serverToJoin) const;
```
Template variables replaced:
| Variable | Replacement |
|---|---|
| `${auth_player_name}` | Player name |
| `${auth_session}` | Session token |
| `${auth_uuid}` | Player UUID |
| `${auth_access_token}` | Access token |
| `${version_name}` | Minecraft version |
| `${game_directory}` | Game root path |
| `${assets_root}` | Assets directory path |
| `${assets_index_name}` | Asset index ID |
| `${user_type}` | Account type |
| `${version_type}` | Version type (release/snapshot) |
Additional server join arguments:
- `--server <address>` and `--port <port>` (if `serverToJoin` is set)
## LoggedProcess
`LoggedProcess` wraps `QProcess` with structured logging:
```cpp
class LoggedProcess : public QProcess
{
Q_OBJECT
public:
enum State {
NotRunning,
Starting,
FailedToStart,
Running,
Finished,
Crashed,
Aborted
};
explicit LoggedProcess(QObject* parent = 0);
State state() const;
int exitCode() const;
qint64 processId() const;
void setDetachable(bool detachable);
signals:
void log(QStringList lines, MessageLevel::Enum level);
void stateChanged(LoggedProcess::State state);
public slots:
void kill();
private slots:
void on_stdErr();
void on_stdOut();
void on_exit(int exit_code, QProcess::ExitStatus status);
void on_error(QProcess::ProcessError error);
void on_stateChange(QProcess::ProcessState);
};
```
Features:
- Captures `stdout` and `stderr` separately
- Splits output into lines
- Emits structured log events with message levels
- Handles line buffering for partial reads (`m_err_leftover`, `m_out_leftover`)
- Tracks process state transitions
- Supports detachable processes
## LogModel
`LogModel` stores game log output for display:
```cpp
class LogModel : public QAbstractListModel
{
Q_OBJECT
};
```
Used by `LogPage` and `InstanceWindow` to display real-time game output with color coding based on `MessageLevel::Enum`:
| Level | Color | Examples |
|---|---|---|
| `Unknown` | Default | Unclassified output |
| `StdOut` | Default | Normal game output |
| `StdErr` | Red | Error output |
| `Info` | Default | Informational messages |
| `Warning` | Yellow | Warning messages |
| `Error` | Red | Error messages |
| `Fatal` | Dark Red | Fatal/crash messages |
| `MeshMC` | Blue | Launcher messages |
## Server Join
`MinecraftServerTarget` carries server join information:
```cpp
struct MinecraftServerTarget {
QString address;
quint16 port;
static MinecraftServerTargetPtr parse(const QString& fullAddress);
};
```
When `--server` is provided on the command line or configured in instance settings:
- The server address/port is parsed
- Passed to `LaunchController::setServerToJoin()`
- Forwarded to `DirectJavaLaunch::setServerToJoin()`
- Appended as `--server` and `--port` to Minecraft's arguments
## Profiler Integration
Profiler tools hook into the launch pipeline:
```cpp
class BaseProfilerFactory {
public:
virtual BaseProfiler* createProfiler(InstancePtr instance, QObject* parent) = 0;
virtual bool check(QString* error) = 0;
virtual QString name() const = 0;
};
```
When a profiler is selected:
1. `LaunchController` creates the profiler via the factory
2. The profiler adds its own steps or arguments to the launch
3. JProfiler: opens profiling session via JProfiler's agent
4. JVisualVM: launches alongside the game process
## Process Environment
`MinecraftInstance::createEnvironment()` constructs the `QProcessEnvironment` for the game:
```cpp
QProcessEnvironment MinecraftInstance::createEnvironment() override;
```
This includes:
- System environment (inherited)
- `INST_NAME` — instance name
- `INST_ID` — instance ID
- `INST_DIR` — instance root directory
- `INST_MC_DIR` — game directory
- `INST_JAVA` — Java binary path
- `INST_JAVA_ARGS` — JVM arguments
- Native library path (`LD_LIBRARY_PATH` / `PATH` / `DYLD_LIBRARY_PATH`)
## Custom Commands
Instances support custom commands that execute at specific lifecycle points:
| Command | When | Purpose |
|---|---|---|
| `PreLaunchCommand` | Before JVM starts | Custom setup scripts |
| `PostExitCommand` | After JVM exits | Cleanup scripts |
| `WrapperCommand` | Wraps the JVM command | e.g., `gamemoderun` or `mangohud` |
These are configured per-instance (with override gate) or globally.
|