summaryrefslogtreecommitdiffstats
path: root/src/studio.cpp
blob: 275bfba2a256a978ddaf1a58c915449dd7b295cc (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
// studio.cpp — colour static props at the StudioRender level.
//
// Dynamic props are tinted through their client entity's m_clrRender (see
// esp.cpp). Map-static props have no entity: the engine's static-prop manager
// calls IStudioRender::DrawModelStaticProp, and the colour modulation used for
// the draw comes from IStudioRender::SetColorModulation. Hook both on the
// interface object so the prop colour is substituted only while a prop model
// is being drawn.
//
// VStudioRender025 vtable (verified against studiorender.so's
// CStudioRenderContext vtable at .data.rel.ro):
//   27 = SetColorModulation(float const*)
//   28 = SetAlphaModulation(float)
//   30 = DrawModelStaticProp(const DrawModelInfo_t&, const matrix3x4_t&, int)
// (The 2013 SDK header lists these five slots earlier; this build's layout
// has additional methods before them.)

#include "hl2h.h"
#include <cstdio>
#include <cstring>
#include <dlfcn.h>
#include <string>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

namespace {

using SetColorFn = void (*)(void *, const float *);
using SetAlphaFn = void (*)(void *, float);
using DrawStaticFn = void (*)(void *, void *, void *, int);
// DrawModel takes (this, results, info, boneToWorld, flexWeights,
// flexDelayedWeights, modelOrigin, flags). The modelOrigin argument is a
// `const Vector &`, so it arrives as a pointer; omitting it shifts flags into
// modelOrigin and leaves flags as caller stack garbage.
using DrawModelFn = void (*)(void *, void *, void *, void *, void *, void *,
                             const void *, int);
using DrawArrayFn = void (*)(void *, void *, int, void *, int, int);

SetColorFn g_orig_set_color = nullptr;
SetAlphaFn g_orig_set_alpha = nullptr;
DrawStaticFn g_orig_draw_static = nullptr;
DrawModelFn g_orig_draw_model = nullptr;
DrawArrayFn g_orig_draw_array = nullptr;

bool g_install_tried = false;
bool g_installed = false;
int g_prop_depth = 0;
int g_static_calls = 0;
int g_static_props = 0;

bool prop_tint_on() {
  return feature_active(FEAT_WORLD_TINT) && g_tint_prop_on;
}

void prop_color(float out[4]) {
  out[0] = (float)g_tint_prop_rgb[0] / 255.0f;
  out[1] = (float)g_tint_prop_rgb[1] / 255.0f;
  out[2] = (float)g_tint_prop_rgb[2] / 255.0f;
  out[3] = 1.0f;
}

// DrawModelInfo_t starts with studiohdr_t*; studiohdr_t::name is at +12
// (id, version, checksum, then char name[64]).
const char *info_model_name(void *info) {
  if (!info)
    return nullptr;
  void *hdr = *(void **)info;
  if (!hdr)
    return nullptr;
  // studiohdr_t::name is char[64]; scanning further would read the header's
  // length/eyeposition fields and could return a bogus "name".
  const char *name = (const char *)hdr + 12;
  size_t n = strnlen(name, 64);
  if (n < 7 || n >= 64)
    return nullptr;
  for (size_t i = 0; i < n; i++) {
    unsigned char c = (unsigned char)name[i];
    if (c < 0x20 || c > 0x7e)
      return nullptr;
  }
  return name;
}

bool is_prop_model(const char *name) {
  if (!name)
    return false;
  // studiohdr_t::name is the short model name with Windows separators, e.g.
  // "props_junk\wood_crate002a.mdl" (the "models/" prefix is stripped).
  if (strncmp(name, "models/", 7) == 0 || strncmp(name, "models\\", 7) == 0)
    name += 7;
  if (strncmp(name, "props_skybox", 12) == 0 ||
      strncmp(name, "props\\skybox", 13) == 0)
    return false; // distant 3D-skybox props
  return strncmp(name, "props/", 6) == 0 ||
         strncmp(name, "props\\", 6) == 0 ||
         strncmp(name, "props_", 6) == 0;
}

void hook_set_color(void *self, const float *color) {
  if (g_prop_depth > 0 && prop_tint_on()) {
    float c[4];
    prop_color(c);
    g_orig_set_color(self, c);
    return;
  }
  g_orig_set_color(self, color);
}

void hook_set_alpha(void *self, float alpha) {
  if (g_prop_depth > 0 && prop_tint_on()) {
    g_orig_set_alpha(self, 1.0f);
    return;
  }
  g_orig_set_alpha(self, alpha);
}


void hook_draw_model(void *self, void *results, void *info, void *bone,
                     void *flex, void *flex_delayed, const void *model_origin,
                     int flags) {
  const char *model = info_model_name(info);
  bool prop = prop_tint_on() && is_prop_model(model);
  if (prop) {
    float c[4];
    prop_color(c);
    g_orig_set_color(self, c);
    g_prop_depth++;
  }
  g_orig_draw_model(self, results, info, bone, flex, flex_delayed,
                    model_origin, flags);
  if (prop) {
    g_prop_depth--;
    // Don't leave the prop tint bound: models drawn without an explicit
    // SetColorModulation would inherit it.
    const float white[4] = {1.0f, 1.0f, 1.0f, 1.0f};
    g_orig_set_color(self, white);
  }
}

void hook_draw_array(void *self, void *info, int count, void *instances,
                     int stride, int flags) {
  const char *model = info_model_name(info);
  bool prop = prop_tint_on() && is_prop_model(model);
  if (prop)
    g_prop_depth++;
  g_orig_draw_array(self, info, count, instances, stride, flags);
  if (prop)
    g_prop_depth--;
}

void hook_draw_static_prop(void *self, void *info, void *model_to_world,
                           int flags) {
  const char *model = info_model_name(info);
  bool prop = prop_tint_on() && is_prop_model(model);
  g_static_calls++;
  if (prop)
    g_static_props++;
  if (g_static_calls <= 3)
    logf("studio: static draw model=\"%s\" prop=%d", model ? model : "?",
         (int)prop);
  if (g_static_calls == 500)
    logf("studio: static draws=%d prop_draws=%d", g_static_calls,
         g_static_props);
  if (prop)
    g_prop_depth++;
  g_orig_draw_static(self, info, model_to_world, flags);
  if (prop) {
    g_prop_depth--;
    const float white[4] = {1.0f, 1.0f, 1.0f, 1.0f};
    g_orig_set_color(self, white);
  }
}

std::string loaded_module_path(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;
}

// ---------------------------------------------------------------------------
// chams: force a flat material on NPC draws
// ---------------------------------------------------------------------------
//
// IVModelRender::DrawModelExecute is called once per model. For NPC entities
// we force models/debug/debugwhite, optionally with MATERIAL_VAR_IGNOREZ for
// the through-wall pass, and draw twice. IVModelRender::ForcedMaterialOverride
// is slot 1; DrawModelExecute is slot 19 in VEngineModel016.

using ModelExecFn = void (*)(void *, const void *, const void *, void *);
using ForceOverrideFn = void (*)(void *, void *, int);

void *g_modelrender = nullptr;
ModelExecFn g_orig_model_exec = nullptr;
ForceOverrideFn g_force_override = nullptr;
void *g_style_mats[8] = {};

// The engine forces a material for special passes (shadow depth, reflections)
// and clears it again. Without tracking that, the chams pass could not tell
// "no override" from "engine override in progress": it hijacked the shadow pass
// with chams materials and then cleared the engine's override for every model
// drawn afterwards.
static ForceOverrideFn g_real_force_override = nullptr;
static void *g_current_override = nullptr;

static void hkdForceOverride(void *self, void *mat, int type) {
  g_current_override = mat;
  if (g_real_force_override)
    g_real_force_override(self, mat, type);
}

const char *chams_material_name(int idx) {
  switch (idx) {
  case 1: return "debug/debugwireframe";
  case 2:
  case 5: return "debug/debugtranslucentmodelhulls";
  case 3:
  case 4:
  case 6:
  default: return "debug/debugtranslucentsinglecolor";
  }
}

// Never call FindMaterial here: this runs inside DrawModelExecute, where
// loading a material can crash the material system. chams_preload fills the
// cache from outer_draw instead.
void *style_material(int idx) {
  if (idx < 0) idx = 0;
  if (idx > 6) idx = 6;
  if (g_style_mats[idx])
    return g_style_mats[idx];
  if (g_style_mats[3])
    return g_style_mats[3];
  return nullptr;
}

void chams_color(void *mat, float r, float g, float b) {
  using ColorFn = void (*)(void *, float, float, float);
  using FindVarFn = void *(*)(void *, const char *, bool *, bool);
  using SetVec3Fn = void (*)(void *, float, float, float);
  bool found = false;
  void *var = vfunc<FindVarFn>(mat, 11)(mat, "$color", &found, false);
  if (var)
    vfunc<SetVec3Fn>(var, 11)(var, r, g, b);
  found = false;
  var = vfunc<FindVarFn>(mat, 11)(mat, "$color2", &found, false);
  if (var)
    vfunc<SetVec3Fn>(var, 11)(var, r, g, b);
  vfunc<ColorFn>(mat, 28)(mat, r, g, b);
}

void chams_alpha(void *mat, float a) {
  using FindVarFn = void *(*)(void *, const char *, bool *, bool);
  using SetFloatFn = void (*)(void *, float);
  bool found = false;
  void *var = vfunc<FindVarFn>(mat, 11)(mat, "$alpha", &found, false);
  if (var)
    vfunc<SetFloatFn>(var, 3)(var, a);
}

void chams_apply(void *mat, bool ignorez, int style, bool force_white,
                 const int *rgb, bool znearer) {
  using FlagFn = void (*)(void *, int, bool);
  bool additive = style == 2 || style == 5;
  float r = force_white ? 1.0f : (float)rgb[0] / 255.0f;
  float g = force_white ? 1.0f : (float)rgb[1] / 255.0f;
  float b = force_white ? 1.0f : (float)rgb[2] / 255.0f;
  chams_color(mat, r, g, b);
  chams_alpha(mat, (float)rgb[3] / 255.0f);
  {
    // Entity-style alpha fade; UnlitGeneric takes translucency from the base
    // texture/vertex alpha, so $alpha alone is not enough.
    using AlphaFn = void (*)(void *, float);
    vfunc<AlphaFn>(mat, 27)(mat, (float)rgb[3] / 255.0f);
  }
  // 0 Flat, 1 Wireframe, 2 Additive, 3 Solid, 4 White, 5 Fullbright
  // (additive white glow), 6 Glow outline (solid base; the wireframe overlay
  // is a second draw with ZNEARER so its contour is not hidden by the base).
  // Styles 2/5 use debug/debugtranslucentmodelhulls, whose VMT already has
  // $additive; ADDITIVE on debugtranslucentsinglecolor did nothing.
  vfunc<FlagFn>(mat, 29)(mat, 1 << 15 /* IGNOREZ */, ignorez);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 10 /* ZNEARER */, znearer);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 28 /* WIREFRAME */, style == 1);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 7 /* ADDITIVE */, additive);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 12 /* FLAT */, style == 0);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 6 /* SELFILLUM */, style == 5);
}

void chams_reset(void *mat) {
  using FlagFn = void (*)(void *, int, bool);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 15, false);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 10, false);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 28, false);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 7, false);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 12, false);
  vfunc<FlagFn>(mat, 29)(mat, 1 << 6, false);
  chams_color(mat, 1.0f, 1.0f, 1.0f);
  chams_alpha(mat, 1.0f);
  // AlphaModulate is applied per-entity, separate from $alpha, and was left at
  // the last chams alpha. Styles 0/3/4/6 share one material, so a translucent
  // pass permanently half-faded it for every later draw.
  using AlphaFn = void (*)(void *, float);
  vfunc<AlphaFn>(mat, 27)(mat, 1.0f);
}

// Model draws take their final alpha from IVRenderView::SetBlend; material
// $alpha alone is ignored by UnlitGeneric. Save/restore it around our passes.
float chams_get_blend() {
  if (!g_iface.renderview)
    return 1.0f;
  using GetFn = float (*)(void *);
  return vfunc<GetFn>(g_iface.renderview, 5)(g_iface.renderview);
}

void chams_set_blend(float a) {
  if (!g_iface.renderview)
    return;
  using SetFn = void (*)(void *, float);
  vfunc<SetFn>(g_iface.renderview, 4)(g_iface.renderview, a);
}

void hkdModelExecute(void *self, const void *state, const void *info,
                     void *bone) {
  if (!g_orig_model_exec)
    return;
  if (!init_live()) {
    g_orig_model_exec(self, state, info, bone);
    return;
  }
  // Shadow-depth/reflection passes arrive with a material already forced. Let
  // them draw normally instead of substituting chams.
  if (g_current_override) {
    g_orig_model_exec(self, state, info, bone);
    return;
  }
  if (feature_active(FEAT_CHAMS) && info && g_force_override) {
    // ModelRenderInfo_t::entity_index is at 0x30 on 32-bit.
    int idx = *(const int *)((const char *)info + 0x30);
    if (idx > 0 && idx <= 8192) {
      bool is_vm = g_chams_viewmodel && esp_is_viewmodel_index(idx);
      ChamsGroup *grp = nullptr;
      if (!is_vm) {
        int rel = esp_npc_relation(idx);
        if (rel >= 0)
          grp = rel == 0 ? &g_chams_hostile
                         : rel == 1 ? &g_chams_neutral : &g_chams_friendly;
      }
      if (is_vm || grp) {
        auto draw_pass = [&](int style, const int *rgb,
                             bool ignorez) -> bool {
          if (style < 0) style = 0;
          if (style > 6) style = 6;
          void *mat = style_material(style);
          bool alpha = rgb[3] < 255;
          if (alpha && g_style_mats[7] &&
              (style == 0 || style == 3 || style == 4 || style == 6))
            mat = g_style_mats[7];
          if (!mat)
            return false;
          bool white = style == 4 || style == 5;
          // Wireframe lines use a brighter tint so they stay readable over a
          // solid fill.
          int wrgb[4];
          const int *use_rgb = rgb;
          if (style == 1) {
            for (int i = 0; i < 3; i++)
              wrgb[i] = (rgb[i] + 255) / 2;
            wrgb[3] = rgb[3];
            use_rgb = wrgb;
          }
          chams_apply(mat, ignorez, style, white, use_rgb, false);
          chams_set_blend((float)use_rgb[3] / 255.0f);
          g_force_override(self, mat, 0 /* OVERRIDE_NORMAL */);
          g_orig_model_exec(self, state, info, bone);
          if (style == 6) {
            // Solid base plus a wireframe contour pass for depth.
            void *wire = g_style_mats[1];
            if (wire && wire != mat) {
              int crgb[4] = {(rgb[0] + 255) / 2, (rgb[1] + 255) / 2,
                             (rgb[2] + 255) / 2, rgb[3]};
              chams_apply(wire, ignorez, 1, false, crgb, true);
              chams_set_blend((float)crgb[3] / 255.0f);
              g_force_override(self, wire, 0);
              g_orig_model_exec(self, state, info, bone);
              chams_reset(wire);
            }
          }
          chams_reset(mat);
          return true;
        };
        float old_blend = chams_get_blend();
        bool did = false;
        if (is_vm) {
          did = draw_pass(g_chams_vm_mat, g_chams_vm_rgb, false);
        } else {
          if (grp->inv_on)
            did |= draw_pass(grp->inv_mat, grp->inv_rgb, true);
          if (grp->vis_on) {
            // A wireframe visible pass leaves gaps, so the through-wall fill
            // would show inside the visible silhouette. Fill it first.
            if (grp->inv_on && grp->vis_mat == 1)
              did |= draw_pass(3, grp->vis_rgb, false);
            did |= draw_pass(grp->vis_mat, grp->vis_rgb, false);
          }
        }
        if (did) {
          g_force_override(self, nullptr, 0);
          chams_set_blend(old_blend);
          return;
        }
      }
    }
  }
  g_orig_model_exec(self, state, info, bone);
}

} // namespace

static double chams_now() {
  timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);
  return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}

// The base-game model debug materials are opaque. Drop a tiny VMT with
// $model + $translucent into the game's custom/materials folders so the alpha
// channel in the colour picker has something to drive. Written from a
// constructor too, so it exists before the material system scans its paths.
// Only our own hl2hake folder is touched.
static void chams_mkdirs(const std::string &path) {
  std::string cur;
  for (size_t i = 0; i < path.size(); i++) {
    cur += path[i];
    if (path[i] == '/')
      mkdir(cur.c_str(), 0755);
  }
  mkdir(path.c_str(), 0755);
}

static bool chams_write_vmt_at(const std::string &dir) {
  chams_mkdirs(dir);
  std::string path = dir + "/translucent.vmt";
  FILE *f = fopen(path.c_str(), "w");
  if (!f)
    return false;
  fputs("\"UnlitGeneric\"\n"
        "{\n"
        "    \"$basetexture\" \"sprites/white\"\n"
        "    \"$color\" \"[1 1 1]\"\n"
        "    \"$alpha\" \"1\"\n"
        "    \"$translucent\" \"1\"\n"
        "    \"$model\" \"1\"\n"
        "    \"$nocull\" \"1\"\n"
        "    \"%noToolTexture\" \"1\"\n"
        "}\n",
        f);
  fclose(f);
  return true;
}

static std::string chams_game_arg() {
  FILE *f = fopen("/proc/self/cmdline", "rb");
  if (!f)
    return std::string();
  std::string data;
  int c;
  while ((c = fgetc(f)) != EOF)
    data += (char)c;
  fclose(f);
  size_t pos = 0;
  while (pos < data.size()) {
    size_t end = data.find('\0', pos);
    if (end == std::string::npos)
      end = data.size();
    if (data.compare(pos, end - pos, "-game") == 0) {
      size_t n = end + 1;
      size_t e2 = data.find('\0', n);
      if (e2 == std::string::npos)
        e2 = data.size();
      return data.substr(n, e2 - n);
    }
    pos = end + 1;
  }
  return std::string();
}

static void chams_write_translucent_vmt() {
  static bool done = false;
  if (done)
    return;
  char cwd[4096];
  ssize_t n = readlink("/proc/self/cwd", cwd, sizeof(cwd) - 1);
  if (n <= 0)
    return;
  cwd[n] = 0;
  std::string root(cwd);
  std::string mod = chams_game_arg();
  if (mod.empty())
    mod = "hl2";
  std::string base = (!mod.empty() && mod[0] == '/') ? mod : root + "/" + mod;
  // Only write when this really is a Source game directory (the wrapper
  // processes also preload us, from the repo directory).
  if (access((base + "/gameinfo.txt").c_str(), R_OK) != 0)
    return;
  bool ok = false;
  ok |= chams_write_vmt_at(base + "/custom/hl2hake/materials/hl2hake");
  ok |= chams_write_vmt_at(base + "/materials/hl2hake");
  done = ok;
}

__attribute__((constructor)) static void chams_early_vmt() {
  chams_write_translucent_vmt();
}

// Called from outer_draw (outside the model draw) so FindMaterial can load
// the style VMTs. The render hook only reads the cached pointers.
void chams_preload() {
  static double last = 0.0;
  double now = chams_now();
  if (now - last < 1.5)
    return;
  last = now;
  using RefFn = void (*)(void *);
  for (int i = 0; i < 7; i++) {
    if (g_style_mats[i])
      continue;
    const char *name = chams_material_name(i);
    // Styles 0/3/4/6 and 2/5 resolve to the same material. Reuse the pointer
    // and reference it only once instead of incrementing the shared material
    // up to four times.
    void *m = nullptr;
    for (int j = 0; j < 7; j++) {
      if (g_style_mats[j] && strcmp(chams_material_name(j), name) == 0) {
        m = g_style_mats[j];
        break;
      }
    }
    bool fresh = m == nullptr;
    if (!m)
      m = world_find_material(name);
    if (m) {
      // FindMaterial can hand back an unreferenced material; the engine warns
      // ("bad reference count 0") and may reset its vars when it is bound.
      if (fresh)
        vfunc<RefFn>(m, 12)(m); // IMaterial::IncrementReferenceCount
      g_style_mats[i] = m;
      logf("chams: preloaded style %d %s = %p%s", i, name, m,
           fresh ? "" : " (shared)");
    }
  }
  if (!g_style_mats[7]) {
    chams_write_translucent_vmt();
    void *m = world_find_material("hl2hake/translucent");
    if (m) {
      using RefFn = void (*)(void *);
      vfunc<RefFn>(m, 12)(m);
      g_style_mats[7] = m;
      logf("chams: preloaded translucent material = %p", m);
    }
  }
}

void chams_init() {
  if (g_modelrender || !g_iface.modelrender) {
    if (!g_iface.modelrender)
      logf("chams: VEngineModel016 unavailable");
    return;
  }
  void **vt = *(void ***)g_iface.modelrender;
  if (!vt) {
    logf("chams: model render has no vtable");
    return;
  }
  g_real_force_override = (ForceOverrideFn)vt[1];
  g_force_override = g_real_force_override;
  g_orig_model_exec = (ModelExecFn)vt[19];
  if (!mod_engine().contains((uintptr_t)g_force_override) ||
      !mod_engine().contains((uintptr_t)g_orig_model_exec)) {
    logf("chams: implausible vtable entries override=%p draw=%p",
         (void *)g_force_override, (void *)g_orig_model_exec);
    return;
  }
  VtablePatch patches[] = {
      {1, (void *)&hkdForceOverride,
       reinterpret_cast<void **>(&g_real_force_override)}, // track forced passes
      {19, (void *)&hkdModelExecute,
       reinterpret_cast<void **>(&g_orig_model_exec)},
  };
  if (!hooks_install_vtable(g_iface.modelrender, 32, patches, 2)) {
    logf("chams: vtable patch failed");
    return;
  }
  g_modelrender = g_iface.modelrender;
  logf("chams: IVModelRender %p hooked (draw=%p override=%p)", g_modelrender,
       (void *)g_orig_model_exec, (void *)g_force_override);
}

void studio_props_init() {
  if (g_install_tried)
    return;
  g_install_tried = true;

  std::string path = loaded_module_path("studiorender");
  void *h = nullptr;
  if (!path.empty())
    h = dlopen(path.c_str(), RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
  if (!h)
    h = dlopen("studiorender.so", RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
  if (!h) {
    logf("studio: studiorender.so not loaded");
    return;
  }
  auto cf = (CreateInterfaceFn)dlsym(h, "CreateInterface");
  if (!cf) {
    logf("studio: studiorender CreateInterface missing");
    return;
  }
  void *sr = cf("VStudioRender025", nullptr);
  if (!sr) {
    logf("studio: VStudioRender025 not exposed");
    return;
  }

  void **old_vt = *(void ***)sr;
  if (!old_vt) {
    logf("studio: interface has no vtable");
    return;
  }
  VtablePatch patches[] = {
      {27, (void *)&hook_set_color,
       reinterpret_cast<void **>(&g_orig_set_color)},
      {28, (void *)&hook_set_alpha,
       reinterpret_cast<void **>(&g_orig_set_alpha)},
      {29, (void *)&hook_draw_model,
       reinterpret_cast<void **>(&g_orig_draw_model)},
      {30, (void *)&hook_draw_static_prop,
       reinterpret_cast<void **>(&g_orig_draw_static)},
      {46, (void *)&hook_draw_array,
       reinterpret_cast<void **>(&g_orig_draw_array)},
  };
  if (!hooks_install_vtable(sr, 49, patches, 5)) {
    logf("studio: vtable patch failed");
    return;
  }
  g_installed = true;
  logf("studio: IStudioRender %p hooked (color=%p draw=%p static=%p "
       "array=%p)", sr, (void *)g_orig_set_color, (void *)g_orig_draw_model,
       (void *)g_orig_draw_static, (void *)g_orig_draw_array);
}