summaryrefslogtreecommitdiffstats
path: root/src/world.cpp
blob: 391ab1a88361ef775c780d568f44d95445ad3e12 (plain) (blame)
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
// world.cpp — world/sky material colour modulation.
//
// Same mechanism Amalgam uses for its "World modulation": walk every material
// in the material system and call IMaterial::ColorModulate on the ones whose
// texture group is the world (or the skybox). This multiplies the material's
// albedo; it does not touch lightmaps, so it is cheap and does not recompile
// shaders.
//
// HL2's materialsystem.so registers "VMaterialSystem080" (the SDK 2013 name
// for the modern layout) and exports CreateInterface, so the interface is
// obtained exactly like VClient017/VGUI_Surface030 elsewhere in this cheat.
//
// Vtable slots are taken from the 2013 SDK headers:
//   IMaterialSystem: FirstMaterial=73 NextMaterial=74 InvalidMaterial=75
//                    GetMaterial=76 GetNumMaterials=77
//   IMaterial:       GetName=0 GetTextureGroupName=1 ColorModulate=28

#include "hl2h.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dlfcn.h>

namespace {

constexpr int MATSYS_FirstMaterial = 73;
constexpr int MATSYS_NextMaterial = 74;
constexpr int MATSYS_InvalidMaterial = 75;
constexpr int MATSYS_GetMaterial = 76;
constexpr int MATSYS_GetNumMaterials = 77;

constexpr int MAT_GetName = 0;
constexpr int MAT_GetTextureGroupName = 1;
constexpr int MAT_ColorModulate = 28;

constexpr const char *GROUP_WORLD = "World textures";
constexpr const char *GROUP_SKYBOX = "SkyBox textures";

void *g_matsys = nullptr;
bool g_matsys_tried = false;
bool g_matsys_failed = false;
bool g_matsys_logged = false;

// Last state handed to the material system. Colour changes are applied when
// this differs from the desired state, so the all-material walk runs only on
// toggles/colour edits/level changes, never every frame.
struct Tint {
  bool valid;
  int world_r, world_g, world_b;
  int sky_r, sky_g, sky_b;
  int prop_r, prop_g, prop_b;
};
Tint g_applied{false, 255, 255, 255, 255, 255, 255, 255, 255, 255};

// Static props and prop_physics share their model materials; every stock HL2
// map prop lives under models/props*, which keeps NPC/player/weapon materials
// out of the prop pass.
bool is_prop_material(const char *name) {
  return name && strncmp(name, "models/props", 12) == 0;
}

struct MatCalls {
  using FirstFn = unsigned short (*)(void *);
  using NextFn = unsigned short (*)(void *, unsigned short);
  using InvalidFn = unsigned short (*)(void *);
  using GetFn = void *(*)(void *, unsigned short);
  using CountFn = int (*)(void *);
  using NameFn = const char *(*)(void *);
  using GroupFn = const char *(*)(void *);
  using ModulateFn = void (*)(void *, float, float, float);
};

// Reject obviously bogus strings returned by a mis-mapped vtable slot instead
// of walking thousands of materials with garbage pointers.
bool plausible_name(const char *s) {
  if (!s || !*s)
    return false;
  size_t n = strnlen(s, 512);
  if (n == 0 || n >= 512)
    return false;
  for (size_t i = 0; i < n; i++) {
    unsigned char c = (unsigned char)s[i];
    if (c < 0x20 || c == 0x7f)
      return false;
  }
  return true;
}

std::string find_loaded_module(const char *needle) {
  FILE *maps = fopen("/proc/self/maps", "r");
  if (!maps)
    return {};
  char line[1024];
  std::string found;
  while (fgets(line, sizeof(line), maps)) {
    char *p = strchr(line, '/');
    if (!p)
      continue;
    size_t pl = strlen(p);
    while (pl && (p[pl - 1] == '\n' || p[pl - 1] == '\r'))
      p[--pl] = 0;
    if (!strstr(p, needle) || !strstr(p, ".so"))
      continue;
    found = p;
    if (!strstr(p, "(deleted)"))
      break;
  }
  fclose(maps);
  return found;
}

void *material_system() {
  if (g_matsys_tried)
    return g_matsys;
  g_matsys_tried = true;

  std::string path = find_loaded_module("materialsystem");
  void *h = nullptr;
  if (!path.empty())
    h = dlopen(path.c_str(), RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
  // The engine always dlopens the module by name; NOLOAD only attaches to the
  // already-mapped copy, so we never spawn a second material system.
  if (!h)
    h = dlopen("materialsystem.so", RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
  if (!h) {
    g_matsys_failed = true;
    logf("tint: materialsystem.so not loaded");
    return nullptr;
  }
  auto cf = (CreateInterfaceFn)dlsym(h, "CreateInterface");
  if (!cf) {
    g_matsys_failed = true;
    logf("tint: materialsystem CreateInterface missing");
    return nullptr;
  }
  static const char *names[] = {"VMaterialSystem080", "VMaterialSystem082",
                                "VMaterialSystem081", nullptr};
  for (const char **n = names; *n; n++) {
    int ret = 0;
    void *ms = cf(*n, &ret);
    if (!ms)
      continue;
    g_matsys = ms;
    logf("tint: %s = %p via %s", *n, ms,
         path.empty() ? "materialsystem.so" : path.c_str());
    return ms;
  }
  g_matsys_failed = true;
  logf("tint: material system interface not exposed");
  return nullptr;
}

// Push one colour pair over all materials. Groups that are off get white so a
// previously tinted world is restored.
bool apply_tint(int world_r, int world_g, int world_b, int sky_r, int sky_g,
                int sky_b, int prop_r, int prop_g, int prop_b) {
  void *ms = material_system();
  if (!ms)
    return false;

  auto invalid = vfunc<MatCalls::InvalidFn>(ms, MATSYS_InvalidMaterial);
  auto first = vfunc<MatCalls::FirstFn>(ms, MATSYS_FirstMaterial);
  auto next = vfunc<MatCalls::NextFn>(ms, MATSYS_NextMaterial);
  auto get = vfunc<MatCalls::GetFn>(ms, MATSYS_GetMaterial);
  auto count = vfunc<MatCalls::CountFn>(ms, MATSYS_GetNumMaterials);

  int total = count(ms);
  if (total <= 0 || total > 200000) {
    logf("tint: GetNumMaterials() = %d (unexpected; disabled)", total);
    g_matsys_failed = true;
    toastf(TOAST_ERROR, "World tint: material system layout mismatch");
    return false;
  }

  float wr = world_r / 255.0f, wg = world_g / 255.0f, wb = world_b / 255.0f;
  float sr = sky_r / 255.0f, sg = sky_g / 255.0f, sb = sky_b / 255.0f;
  float pr = prop_r / 255.0f, pg = prop_g / 255.0f, pb = prop_b / 255.0f;

  unsigned short inv = invalid(ms);
  int seen = 0, world_hits = 0, sky_hits = 0, prop_hits = 0;
  for (unsigned short h = first(ms); h != inv; h = next(ms, h)) {
    if (++seen > total + 16) {
      logf("tint: material walk runaway (%d > %d); stopped", seen, total);
      break;
    }
    void *mat = get(ms, h);
    if (!mat)
      continue;
    auto name_fn = vfunc<MatCalls::NameFn>(mat, MAT_GetName);
    auto group_fn = vfunc<MatCalls::GroupFn>(mat, MAT_GetTextureGroupName);
    auto mod_fn = vfunc<MatCalls::ModulateFn>(mat, MAT_ColorModulate);
    const char *name = name_fn(mat);
    const char *group = group_fn(mat);
    if (!plausible_name(name) || !plausible_name(group))
      continue;
    // The first material's name also validates the IMaterial vtable mapping
    // before we poke any colour state.
    if (!g_matsys_logged) {
      g_matsys_logged = true;
      logf("tint: first material \"%s\" group \"%s\"", name, group);
    }
    bool is_world = strncmp(group, GROUP_WORLD, strlen(GROUP_WORLD)) == 0;
    bool is_sky = strncmp(group, GROUP_SKYBOX, strlen(GROUP_SKYBOX)) == 0 ||
                  strstr(name, "sky") != nullptr;
    if (is_world && !strstr(name, "sky")) {
      mod_fn(mat, wr, wg, wb);
      world_hits++;
    } else if (is_sky) {
      mod_fn(mat, sr, sg, sb);
      sky_hits++;
    } else if (is_prop_material(name)) {
      mod_fn(mat, pr, pg, pb);
      prop_hits++;
    }
  }
  logf("tint: applied world=%d(%d,%d,%d) sky=%d(%d,%d,%d) props=%d(%d,%d,%d) "
       "of %d materials",
       world_hits, world_r, world_g, world_b, sky_hits, sky_r, sky_g, sky_b,
       prop_hits, prop_r, prop_g, prop_b, total);
  return true;
}

} // namespace

void world_tint_invalidate() { g_applied.valid = false; }

void world_tint_update() {
  bool on = feature_active(FEAT_WORLD_TINT);
  bool world_on = on && g_tint_world_on;
  bool sky_on = on && g_tint_sky_on;
  bool prop_on = on && g_tint_prop_on;

  int wr = world_on ? g_tint_world_rgb[0] : 255;
  int wg = world_on ? g_tint_world_rgb[1] : 255;
  int wb = world_on ? g_tint_world_rgb[2] : 255;
  int sr = sky_on ? g_tint_sky_rgb[0] : 255;
  int sg = sky_on ? g_tint_sky_rgb[1] : 255;
  int sb = sky_on ? g_tint_sky_rgb[2] : 255;
  int pr = prop_on ? g_tint_prop_rgb[0] : 255;
  int pg = prop_on ? g_tint_prop_rgb[1] : 255;
  int pb = prop_on ? g_tint_prop_rgb[2] : 255;

  bool white = wr == 255 && wg == 255 && wb == 255 && sr == 255 &&
               sg == 255 && sb == 255 && pr == 255 && pg == 255 && pb == 255;
  if (g_applied.valid && g_applied.world_r == wr && g_applied.world_g == wg &&
      g_applied.world_b == wb && g_applied.sky_r == sr &&
      g_applied.sky_g == sg && g_applied.sky_b == sb &&
      g_applied.prop_r == pr && g_applied.prop_g == pg &&
      g_applied.prop_b == pb)
    return;
  // Nothing was ever tinted and nothing is requested: no need to walk the
  // material list just to write white over white.
  if (!g_applied.valid && white) {
    g_applied = {true, wr, wg, wb, sr, sg, sb, pr, pg, pb};
    return;
  }
  if (g_matsys_failed && !world_on && !sky_on && !prop_on) {
    g_applied = {true, wr, wg, wb, sr, sg, sb, pr, pg, pb};
    return;
  }
  if (!apply_tint(wr, wg, wb, sr, sg, sb, pr, pg, pb)) {
    if (g_matsys_failed)
      g_applied = {true, wr, wg, wb, sr, sg, sb, pr, pg, pb};
    return;
  }
  g_applied = {true, wr, wg, wb, sr, sg, sb, pr, pg, pb};
}

// ---------------------------------------------------------------------------
// Fog override (engine console commands; no render hooks)
// ---------------------------------------------------------------------------

namespace {

struct FogState {
  bool valid;
  bool on;
  bool disable;
  int r, g, b;
  int start, end;
  bool skybox;
};
FogState g_fog_applied{false, false, false, 0, 0, 0, 0, 0, false};

} // namespace

void fog_invalidate() { g_fog_applied.valid = false; }

void fog_update() {
  bool on = feature_active(FEAT_FOG);
  bool disable = on && g_fog_disable;
  int r = g_fog_rgb[0], g = g_fog_rgb[1], b = g_fog_rgb[2];
  int start = g_fog_start;
  int end = g_fog_end;
  if (end <= start)
    end = start + 1;
  bool skybox = on && g_fog_skybox;

  if (g_fog_applied.valid && g_fog_applied.on == on &&
      g_fog_applied.disable == disable && g_fog_applied.r == r &&
      g_fog_applied.g == g && g_fog_applied.b == b &&
      g_fog_applied.start == start && g_fog_applied.end == end &&
      g_fog_applied.skybox == skybox)
    return;

  if (!on) {
    if (g_fog_applied.valid && g_fog_applied.on)
      console_cmd("fog_override 0");
    g_fog_applied = {true, false, false, 0, 0, 0, 0, 0, false};
    return;
  }

  console_cmd("fog_override 1");
  char cmd[128];
  if (disable) {
    console_cmd("fog_enable 0");
    if (skybox)
      console_cmd("fog_enableskybox 0");
  } else {
    console_cmd("fog_enable 1");
    snprintf(cmd, sizeof(cmd), "fog_color %d %d %d", r, g, b);
    console_cmd(cmd);
    snprintf(cmd, sizeof(cmd), "fog_start %d", start);
    console_cmd(cmd);
    snprintf(cmd, sizeof(cmd), "fog_end %d", end);
    console_cmd(cmd);
    if (skybox) {
      console_cmd("fog_enableskybox 1");
      snprintf(cmd, sizeof(cmd), "fog_colorskybox %d %d %d", r, g, b);
      console_cmd(cmd);
      snprintf(cmd, sizeof(cmd), "fog_startskybox %d", start);
      console_cmd(cmd);
      snprintf(cmd, sizeof(cmd), "fog_endskybox %d", end);
      console_cmd(cmd);
    } else {
      console_cmd("fog_enableskybox 0");
    }
  }
  g_fog_applied = {true, on, disable, r, g, b, start, end, skybox};
  logf("fog: %s colour=(%d,%d,%d) start=%d end=%d skybox=%d", disable ? "off"
       : "on", r, g, b, start, end, (int)skybox);
}

// ---------------------------------------------------------------------------
// Skybox image (skybox.png from the config directory)
// ---------------------------------------------------------------------------

namespace {

struct PngImage {
  void *opaque;
  uint32_t version, width, height, format, flags, colormap_entries,
      warning_or_error;
  char message[64];
};

bool load_png_rgba(const char *path, std::vector<unsigned char> &pixels,
                   int &w, int &h) {
  static void *lib = nullptr;
  static bool tried = false;
  if (!tried) {
    tried = true;
    lib = dlopen("libpng16.so.16", RTLD_LAZY | RTLD_GLOBAL);
    if (!lib)
      lib = dlopen("libpng16.so", RTLD_LAZY | RTLD_GLOBAL);
  }
  if (!lib) {
    logf("skybox: libpng16 not available");
    return false;
  }
  using BeginFn = int (*)(PngImage *, const char *);
  using FinishFn = int (*)(PngImage *, void *, void *, int32_t, void *);
  using FreeFn = void (*)(PngImage *);
  static BeginFn begin =
      (BeginFn)dlsym(lib, "png_image_begin_read_from_file");
  static FinishFn finish = (FinishFn)dlsym(lib, "png_image_finish_read");
  static FreeFn free_img = (FreeFn)dlsym(lib, "png_image_free");
  if (!begin || !finish || !free_img) {
    logf("skybox: libpng16 simplified API missing");
    return false;
  }

  PngImage img{};
  img.version = 1;   // PNG_IMAGE_VERSION
  img.format = 0x03; // PNG_FORMAT_RGBA
  if (!begin(&img, path)) {
    logf("skybox: cannot open %s (%s)", path,
         img.message[0] ? img.message : "read error");
    return false;
  }
  if (img.width == 0 || img.height == 0 || img.width > 8192 ||
      img.height > 8192) {
    logf("skybox: %s has unsupported size %ux%u", path, img.width, img.height);
    free_img(&img);
    return false;
  }
  pixels.assign((size_t)img.width * img.height * 4, 255);
  if (!finish(&img, nullptr, pixels.data(), 0, nullptr)) {
    logf("skybox: cannot decode %s (%s)", path,
         img.message[0] ? img.message : "decode error");
    pixels.clear();
    free_img(&img);
    return false;
  }
  w = (int)img.width;
  h = (int)img.height;
  free_img(&img);
  return true;
}

std::vector<unsigned char> g_sky_pixels;
int g_sky_px_w = 0, g_sky_px_h = 0;

// ITextureRegenerator has two virtuals: RegenerateTextureBits then Release.
// This build has no IMaterialSystem::CreateTextureFromBits (its interface stops
// at GetDisplayDeviceName), so the pixels are uploaded through a procedural
// texture + regenerator instead.
class SkyRegenerator {
public:
  virtual void RegenerateTextureBits(void *texture, void *vtf, void *rect) {
    (void)texture;
    (void)rect;
    if (!vtf || g_sky_pixels.empty())
      return;
    using IntFn = int (*)(void *);
    using PitchFn = int (*)(void *, int);
    using DataFn = unsigned char *(*)(void *, int, int, int);
    // IVTFTexture vtable: dtor takes 2 slots, then Init, so Width=15,
    // Height=16, RowSizeInBytes=19, ImageData(frame,face,mip)=39.
    int w = vfunc<IntFn>(vtf, 15)(vtf);            // IVTFTexture::Width
    int h = vfunc<IntFn>(vtf, 16)(vtf);            // IVTFTexture::Height
    if (w <= 0 || h <= 0)
      return;
    int pitch = vfunc<PitchFn>(vtf, 19)(vtf, 0);   // RowSizeInBytes(0)
    unsigned char *dst = vfunc<DataFn>(vtf, 39)(vtf, 0, 0, 0); // ImageData
    if (!dst || pitch <= 0)
      return;
    int rows = h < g_sky_px_h ? h : g_sky_px_h;
    int src_stride = g_sky_px_w * 4;
    int copy = w * 4;
    if (copy > src_stride)
      copy = src_stride;
    for (int y = 0; y < rows; y++) {
      const unsigned char *src =
          g_sky_pixels.data() + (size_t)y * (size_t)src_stride;
      memcpy(dst + (size_t)y * (size_t)pitch, src, (size_t)copy);
    }
  }
  virtual void Release() {}
};

SkyRegenerator g_sky_regenerator;

void *g_sky_tex = nullptr;
bool g_sky_tex_tried = false;
bool g_sky_applied = false;
bool g_sky_reload = false;
double g_sky_retry_at = 0.0;
bool g_sky_fail_logged = false;

struct SkyOrig {
  std::string material;
  std::string var;
  std::string value; // fallback if the original texture pointer is gone
  void *texture;
};
std::vector<SkyOrig> g_sky_orig;

double now_sec() {
  struct timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);
  return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
}

bool is_sky_material(const char *name, const char *group) {
  if (!plausible_name(name) || !plausible_name(group))
    return false;
  return strncmp(group, GROUP_SKYBOX, strlen(GROUP_SKYBOX)) == 0 ||
         strncmp(name, "skybox/", 7) == 0;
}

void record_orig(const char *material, const char *var, const char *value,
                 void *texture) {
  if (!material || !var)
    return;
  for (auto &r : g_sky_orig) {
    if (r.material == material && r.var == var)
      return;
  }
  g_sky_orig.push_back(
      {material, var, value ? value : "", texture});
}

int apply_sky_texture() {
  void *ms = material_system();
  if (!ms || !g_sky_tex)
    return 0;
  auto invalid = vfunc<MatCalls::InvalidFn>(ms, MATSYS_InvalidMaterial);
  auto first = vfunc<MatCalls::FirstFn>(ms, MATSYS_FirstMaterial);
  auto next = vfunc<MatCalls::NextFn>(ms, MATSYS_NextMaterial);
  auto get = vfunc<MatCalls::GetFn>(ms, MATSYS_GetMaterial);
  auto count = vfunc<MatCalls::CountFn>(ms, MATSYS_GetNumMaterials);
  int total = count(ms);
  if (total <= 0 || total > 200000)
    return 0;
  unsigned short inv = invalid(ms);
  int seen = 0, hits = 0;
  for (unsigned short h = first(ms); h != inv; h = next(ms, h)) {
    if (++seen > total + 16)
      break;
    void *mat = get(ms, h);
    if (!mat)
      continue;
    const char *name = vfunc<MatCalls::NameFn>(mat, MAT_GetName)(mat);
    const char *group =
        vfunc<MatCalls::GroupFn>(mat, MAT_GetTextureGroupName)(mat);
    if (!is_sky_material(name, group))
      continue;
    using FindVarFn = void *(*)(void *, const char *, bool *, bool);
    using GetStrFn = const char *(*)(void *);
    using SetTexFn = void (*)(void *, void *);
    auto find_var = vfunc<FindVarFn>(mat, 11); // IMaterial::FindVar

    static const char *vars[] = {"$basetexture", "$hdrbasetexture",
                                 "$hdrcompressedtexture", nullptr};
    for (int vi = 0; vars[vi]; vi++) {
      bool found = false;
      void *var = find_var(mat, vars[vi], &found, false);
      if (!found || !var)
        continue;
      using GetTexFn = void *(*)(void *);
      auto vget = vfunc<GetStrFn>(var, 6);      // GetStringValue
      auto vgettex = vfunc<GetTexFn>(var, 0);   // GetTextureValue
      auto vset = vfunc<SetTexFn>(var, 14);     // SetTextureValue
      const char *orig = vget(var);
      void *orig_tex = vgettex(var);
      record_orig(name, vars[vi], orig, orig_tex);
      vset(var, g_sky_tex);
      if (vi == 0)
        hits++;
    }
  }
  return hits;
}

void restore_sky_texture() {
  if (g_sky_orig.empty()) {
    g_sky_applied = false;
    return;
  }
  void *ms = material_system();
  if (!ms) {
    g_sky_orig.clear();
    g_sky_applied = false;
    return;
  }
  auto invalid = vfunc<MatCalls::InvalidFn>(ms, MATSYS_InvalidMaterial);
  auto first = vfunc<MatCalls::FirstFn>(ms, MATSYS_FirstMaterial);
  auto next = vfunc<MatCalls::NextFn>(ms, MATSYS_NextMaterial);
  auto get = vfunc<MatCalls::GetFn>(ms, MATSYS_GetMaterial);
  auto count = vfunc<MatCalls::CountFn>(ms, MATSYS_GetNumMaterials);
  int total = count(ms);
  if (total <= 0 || total > 200000) {
    g_sky_orig.clear();
    g_sky_applied = false;
    return;
  }
  using FindVarFn = void *(*)(void *, const char *, bool *, bool);
  using SetStrFn = void (*)(void *, const char *);
  using SetTexFn = void (*)(void *, void *);
  unsigned short inv = invalid(ms);
  int seen = 0;
  for (unsigned short h = first(ms); h != inv; h = next(ms, h)) {
    if (++seen > total + 16)
      break;
    void *mat = get(ms, h);
    if (!mat)
      continue;
    const char *name = vfunc<MatCalls::NameFn>(mat, MAT_GetName)(mat);
    const char *group =
        vfunc<MatCalls::GroupFn>(mat, MAT_GetTextureGroupName)(mat);
    if (!is_sky_material(name, group))
      continue;
    for (auto &r : g_sky_orig) {
      if (r.material != name)
        continue;
      bool found = false;
      void *var = vfunc<FindVarFn>(mat, 11)(mat, r.var.c_str(), &found, false);
      if (!found || !var)
        continue;
      if (r.texture)
        vfunc<SetTexFn>(var, 14)(var, r.texture); // back to the map texture
      else if (!r.value.empty())
        vfunc<SetStrFn>(var, 5)(var, r.value.c_str());
    }
  }
  g_sky_orig.clear();
  g_sky_applied = false;
}

void load_sky_texture() {
  g_sky_tex_tried = true;
  void *ms = material_system();
  if (!ms) {
    logf("skybox: material system unavailable");
    return;
  }
  std::vector<unsigned char> pixels;
  int w = 0, h = 0;
  const char *path = config_file_cstr("skybox.png");
  if (!load_png_rgba(path, pixels, w, h)) {
    if (!g_sky_fail_logged) {
      g_sky_fail_logged = true;
      toastf(TOAST_ERROR, "Skybox image missing or unreadable: %s", path);
    }
    return;
  }
  g_sky_pixels.swap(pixels);
  g_sky_px_w = w;
  g_sky_px_h = h;

  // The procedural texture keeps its own copy through the regenerator, which
  // is called on Download() and again on device restore.
  using CreateProcFn = void *(*)(void *, const char *, const char *, int, int,
                                 int, int);
  g_sky_tex = vfunc<CreateProcFn>(ms, 81)(
      ms, "hl2hake/skybox", GROUP_SKYBOX, w, h, 0 /* RGBA8888 */,
      0x10C /* CLAMPS|CLAMPT|NOMIP */);
  if (!g_sky_tex) {
    logf("skybox: CreateProceduralTexture failed for %dx%d", w, h);
    return;
  }
  using SetRegenFn = void (*)(void *, void *);
  using DownloadFn = void (*)(void *, void *, int);
  vfunc<SetRegenFn>(g_sky_tex, 12)(g_sky_tex, &g_sky_regenerator);
  vfunc<DownloadFn>(g_sky_tex, 13)(g_sky_tex, nullptr, 0);
  g_sky_fail_logged = false;
  logf("skybox: image %s (%dx%d) uploaded", path, w, h);
}

} // namespace

void skybox_invalidate() {
  // Level change: re-apply on the new map. Keep the captured originals: with
  // the same skybox the same material objects (still showing our texture) are
  // reused, and the saved texture pointers are what lets us restore them.
  g_sky_applied = false;
  g_sky_retry_at = 0.0;
}

void skybox_reload_image() {
  restore_sky_texture();
  g_sky_tex = nullptr;
  g_sky_tex_tried = false;
  g_sky_reload = true;
  g_sky_retry_at = 0.0;
  g_sky_fail_logged = false;
}

void skybox_update() {
  bool on = feature_active(FEAT_SKYBOX);
  if (!on) {
    if (g_sky_applied || !g_sky_orig.empty())
      restore_sky_texture();
    return;
  }
  if (g_sky_reload) {
    g_sky_reload = false;
    restore_sky_texture();
  }
  if (g_sky_applied)
    return;
  double now = now_sec();
  if (now < g_sky_retry_at)
    return;
  if (!g_sky_tex && !g_sky_tex_tried)
    load_sky_texture();
  if (!g_sky_tex) {
    // The sky materials may not be loaded yet (menu, level transition). Try
    // again in a moment; the PNG itself is only re-read on Reload.
    g_sky_retry_at = now + 1.0;
    return;
  }
  int hits = apply_sky_texture();
  if (hits > 0) {
    g_sky_applied = true;
    logf("skybox: image applied to %d sky materials", hits);
  } else {
    g_sky_retry_at = now + 1.0;
  }
}