-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
553 lines (465 loc) · 11.5 KB
/
main.go
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
package main
import (
_ "embed"
"errors"
"fmt"
"goldutil/goldsrc"
"goldutil/qmap"
"goldutil/set"
"goldutil/sprite"
"goldutil/wad"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"github.com/urfave/cli/v2"
)
var Version = "unknown version"
func main() {
var app = newApp()
if err := app.Run(os.Args); err != nil {
// HACK: -h will panic.
if err.Error() != "flag: help requested" {
panic(err)
}
}
}
//nolint:funlen // descriptions
func newApp() *cli.App {
cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
_ = doHelp(nil)
}
return &cli.App{
Version: Version,
Commands: []*cli.Command{
{
Name: "help",
Action: doHelp,
},
{
Name: "nod",
Subcommands: []*cli.Command{
{
Name: "export",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "original-positions",
},
&cli.StringFlag{
Name: "input-format",
Value: "valve",
},
},
Action: doNodExport,
},
},
},
{
Name: "map",
Subcommands: []*cli.Command{
{
Name: "export",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "cleanup-tb",
Value: false,
},
},
Action: doMapExport,
},
{
Name: "graph",
Action: doMapGraph,
},
},
},
{
Name: "spr",
Subcommands: []*cli.Command{
{
Name: "info",
Action: doSpriteInfo,
},
{
Name: "extract",
Flags: []cli.Flag{
&cli.StringFlag{Name: "dir"},
},
Action: doSpriteExtract,
},
{
Name: "create",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "out",
Required: true,
},
&cli.StringFlag{
Name: "type",
Value: "parallel",
},
&cli.StringFlag{
Name: "format",
Value: "normal",
},
},
Action: doSpriteCreate,
},
},
},
{
Name: "wad",
Subcommands: []*cli.Command{
{
Name: "create",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "out",
Required: true,
},
},
Action: doWADCreate,
},
{
Name: "extract",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "dir",
Required: true,
},
},
Action: doWADExtract,
},
{
Name: "info",
Action: doWADInfo,
},
},
},
{
Name: "bsp",
Subcommands: []*cli.Command{
{
Name: "remap-materials",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "verbose",
},
&cli.StringFlag{
Name: "original-materials",
Value: "valve/sound/materials.txt",
Required: true,
},
&cli.StringFlag{
Name: "replacement-materials",
Value: "valve_addon/sound/materials.txt",
Required: true,
},
&cli.StringFlag{
Name: "out",
Required: true,
},
},
Action: doBSPRemapMaterials,
},
{
Name: "info",
Action: doBSPInfo,
},
},
},
},
}
}
func doSpriteExtract(cCtx *cli.Context) error {
path := cCtx.Args().Get(0)
if path == "" {
return errors.New("expected one argument: the .spr to parse and extract")
}
spr, err := sprite.NewFromFile(path)
if err != nil {
return fmt.Errorf("unable to open sprite: %w", err)
}
return extractSprite(spr, cCtx.String("dir"), filepath.Base(path))
}
func doSpriteCreate(cCtx *cli.Context) error {
typ, ok := map[string]sprite.Type{
"parallel-upright": sprite.ParallelUpright,
"facing-upright": sprite.FacingUpright,
"parallel": sprite.Parallel,
"oriented": sprite.Oriented,
"parallel-oriented": sprite.ParallelOriented,
}[cCtx.String("type")]
if !ok {
return errors.New("unrecognize sprite type")
}
format, ok := map[string]sprite.TextureFormat{
"normal": sprite.Normal,
"additive": sprite.Additive,
"index-alpha": sprite.IndexAlpha,
"alpha-test": sprite.AlphaTest,
}[cCtx.String("format")]
if !ok {
return errors.New("unrecognize texture format")
}
spr, err := createSprite(typ, format, cCtx.Args().Slice())
if err != nil {
return fmt.Errorf("unable to create sprite: %w", err)
}
dest, err := os.OpenFile(cCtx.String("out"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("unable to open dest SPR for writing: %w", err)
}
if err := spr.Write(dest); err != nil {
return fmt.Errorf("unable to write to destination SPR: %w", err)
}
if err := dest.Close(); err != nil {
return fmt.Errorf("unable to finalize writing to destination SPR: %w", err)
}
return nil
}
func doSpriteInfo(cCtx *cli.Context) error {
path := cCtx.Args().Get(0)
if path == "" {
return errors.New("expected one argument: the .spr to parse and display")
}
spr, err := sprite.NewFromFile(path)
if err != nil {
return fmt.Errorf("unable to open sprite: %w", err)
}
fmt.Println(spr.String())
return nil
}
func doMapGraph(cCtx *cli.Context) error {
path := cCtx.Args().Get(0)
if path == "" {
return errors.New("expected one argument: the .map to parse and graph")
}
qm, err := qmap.LoadFromFile(path)
if err != nil {
return fmt.Errorf("unable to read from map: %w", err)
}
GraphQMap(qm, os.Stdout)
return nil
}
func doMapExport(cCtx *cli.Context) error {
qm, err := loadMap(cCtx.Args().Get(0))
if err != nil {
return fmt.Errorf("unable to read from map: %w", err)
}
clean, err := exportQMap(qm, cCtx.Bool("cleanup-tb"))
if err != nil {
return fmt.Errorf("unable to export map: %w", err)
}
fmt.Print(clean.String())
return nil
}
func loadMap(path string) (qmap.QMap, error) {
if path == "" {
return qmap.LoadFromReader(os.Stdin)
} else {
return qmap.LoadFromFile(path)
}
}
func doWADExtract(cCtx *cli.Context) error {
var dir = cCtx.String("dir")
stat, err := os.Stat(dir)
if err != nil {
return fmt.Errorf("unable to use destination directory: %w", err)
}
if err == nil && !stat.IsDir() {
return errors.New("output directory paths exists but is not a directory")
}
wad3, err := wad.NewFromFile(cCtx.Args().Get(0))
if err != nil {
return fmt.Errorf("unable to open and parse WAD file: %w", err)
}
return extractWAD(wad3, dir)
}
func doWADInfo(cCtx *cli.Context) error {
wad3, err := wad.NewFromFile(cCtx.Args().Get(0))
if err != nil {
return fmt.Errorf("unable to open and parse WAD file: %w", err)
}
fmt.Println(wad3.String())
return nil
}
func doWADCreate(cCtx *cli.Context) error {
input, err := collectPaths(cCtx.Args().Slice(), "*.png")
if err != nil {
return fmt.Errorf("unable to collect paths: %w", err)
}
return createWAD(cCtx.String("out"), input)
}
// Returns the paths when they're files, and the pattern-matching files inside
// them if they're directories.
func collectPaths(input []string, pattern string) ([]string, error) {
ret := make([]string, 0, len(input))
for _, path := range input {
stat, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("could not stat '%s': %w", path, err)
}
if !stat.IsDir() {
ret = append(ret, path)
continue
}
matches, err := filepath.Glob(filepath.Join(path, pattern))
if err != nil {
return nil, fmt.Errorf("unable to glob dir '%s': %w", path, err)
}
ret = append(ret, matches...)
}
ret = dedupeStrs(ret)
sort.Strings(ret)
return ret, nil
}
func dedupeStrs(in []string) []string {
var (
ret = make([]string, 0, len(in))
seen = set.NewPresenceSet[string](len(in))
)
for _, v := range in {
if seen.Has(v) {
continue
}
ret = append(ret, v)
seen.Set(v)
}
return ret
}
func doBSPRemapMaterials(cCtx *cli.Context) error {
source, err := goldsrc.LoadMaterialsFromFile(cCtx.String("original-materials"))
if err != nil {
return fmt.Errorf("unable to load original-materials: %w", err)
}
replacement, err := goldsrc.LoadMaterialsFromFile(cCtx.String("replacement-materials"))
if err != nil {
return fmt.Errorf("unable to load replacement-materials: %w", err)
}
if source.IsEmpty() || replacement.IsEmpty() {
return errors.New("no materials in source or replacement list")
}
bsp, err := goldsrc.LoadBSPFromFile(cCtx.Args().Get(0))
if err != nil {
return fmt.Errorf("unable to load BSP: %w", err)
}
var (
verbose = cCtx.Bool("verbose")
remapper = goldsrc.NewMaterialsRemapper(source)
)
mapping, err := remapper.ReMap(bsp.Textures.Textures, replacement)
if err != nil {
return fmt.Errorf("unable to remap materials: %w", err)
}
for i, tex := range bsp.Textures.Textures {
mapTo, ok := mapping[tex.Name]
if !ok {
continue
}
if verbose {
fmt.Printf(
"Remapping %-15s to %s\n",
strings.ToUpper(tex.Name.String()),
strings.ToUpper(mapTo.String()),
)
}
bsp.Textures.Textures[i].Name = mapTo
}
if err := bsp.WriteToFile(cCtx.String("out")); err != nil {
return fmt.Errorf("unable to write BSP: %w", err)
}
if cCtx.Bool("verbose") {
remapper.PrintAvailable()
}
return nil
}
func doBSPInfo(cCtx *cli.Context) error {
bsp, err := goldsrc.LoadBSPFromFile(cCtx.Args().Get(0))
if err != nil {
return fmt.Errorf("unable to load BSP: %w", err)
}
fmt.Print(bsp.String())
return nil
}
//go:embed goldutil.1
var manPage string
func doHelp(cCtx *cli.Context) error {
if runtime.GOOS == "windows" {
return errors.New("man page is only available on *NIX operating systems, see https://l-p.github.io/goldutil/ instead")
}
var cmd = exec.Command("man", "-l", "-")
stdin, err := cmd.StdinPipe()
if err != nil {
return fmt.Errorf("unable to obtain man stdin: %w", err)
}
go func() {
defer stdin.Close()
if _, err := io.WriteString(stdin, manPage); err != nil {
panic("unable to write to man stdin")
}
}()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("unable to run man: %w", err)
}
return nil
}
func doNodExport(cCtx *cli.Context) error {
format, ok := map[string]goldsrc.NodeFormat{
"valve": goldsrc.NodeFormatValve,
"decay": goldsrc.NodeFormatDecay,
}[cCtx.String("input-format")]
if !ok {
return errors.New("unrecognize .nod format")
}
f, err := os.Open(cCtx.Args().Get(0))
if err != nil {
return fmt.Errorf("unable to open file for reading: %w", err)
}
defer f.Close()
nodes, links, err := goldsrc.ReadNodes(f, format)
if err != nil {
return fmt.Errorf("unable to read nodes: %w", err)
}
var (
original = cCtx.Bool("original-positions")
entities = make([]qmap.Entity, 0, len(nodes)+len(links))
)
for i, v := range nodes {
entities = append(entities, qmap.NewEntity(map[string]string{
qmap.KClass: v.ClassName(),
qmap.KOrigin: v.Position(original).String(),
qmap.KName: fmt.Sprintf("node#%d", i),
}))
}
for linkTypeBitID := 0; linkTypeBitID <= goldsrc.LinkTypeBitMax; linkTypeBitID++ {
entities = append(entities, qmap.NewEntity(map[string]string{
qmap.KClass: "func_group",
"_tb_type": "_tb_layer",
"_tb_name": fmt.Sprintf("hull#%d links (%s)", linkTypeBitID, goldsrc.LinkTypeName(linkTypeBitID)),
"_tb_id": strconv.Itoa(linkTypeBitID + 1),
"_tb_layer_sort_index": strconv.Itoa(linkTypeBitID + 1),
}))
for _, v := range links {
if (v.LinkInfo & (1 << linkTypeBitID)) == 0 {
continue
}
src := entities[v.SrcNode]
src.SetProperty("target", fmt.Sprintf("node#%d", v.DstNode))
src.SetProperty("_tb_layer", strconv.Itoa(linkTypeBitID+1))
entities = append(entities, src)
}
}
var out qmap.QMap
for _, v := range entities {
out.AddEntity(v)
}
fmt.Println(out.String())
return nil
}