6 use POSIX qw/floor ceil/;
8 my @lumpname = qw/entities textures planes nodes leafs leaffaces leafbrushes models brushes brushsides vertices triangles effects faces lightmaps lightgrid pvs advertisements/;
9 my %lumpid = map { $lumpname[$_] => $_ } 0..@lumpname-1;
15 if(!@ARGV || $ARGV[0] eq '-h' || $ARGV[0] eq '--help')
19 $0 filename.bsp [operations...]
23 -i print info about the BSP file
24 -xlumpname extract a lump (see -i)
28 -dlumpname delete a lump (see -i)
29 -rlumpname replace a lump (see -i) by the data from standard input
30 -gfilename.tga save the lightgrid as filename.tga (debugging)
31 -Gratio scale down the lightgrid to reduce BSP file size
32 -ljpgNNN externalize the lightmaps as JPEG, quality NNN (number from 1 to 100)
33 -lpng externalize the lightmaps as PNG
34 -ltga externalize the lightmaps as TGA
35 -mMESSAGE set the BSP file comment message
36 -Sfrom=to replace a texture (shader) by name (already replaced shaders are not touched)
39 -o actually apply the changes to the BSP
40 -ofilename2.bsp save the changes to a new BSP file
47 or die "invalid input file name (must be a .bsp): $fn";
52 read $fh, my $header, 8;
54 die "Invalid BSP format"
55 if $header ne "IBSP\x2e\x00\x00\x00";
59 read $fh, my $lump, 8;
60 my ($offset, $length) = unpack "VV", $lump;
62 push @bsp, [$offset, $length, undef];
67 my ($offset, $length, $data) = @$_;
69 read $fh, $data, $length;
70 length $data == $length
71 or die "Incomplete BSP lump at $offset\n";
81 my ($lump, @fields) = @_;
93 if(/^(\w*)=(.*?)(\d*)$/)
100 push @decoders, sub { ($item->{$f} = $data[$idx++]) =~ s/\0//g; };
104 push @decoders, sub { $item->{$f} = $data[$idx++]; };
108 push @decoders, sub { $item->{$f} = [ map { $data[$idx++] } 1..$n ]; };
113 my $itemlen = length pack $spec, ();
114 my $len = length $lump;
116 die "Invalid lump size: $len not divisible by $itemlen"
119 my $items = $len / $itemlen;
122 @data = unpack $spec, substr $lump, $_ * $itemlen, $itemlen;
125 $_->() for @decoders;
126 push @decoded, $item;
133 my ($items, @fields) = @_;
145 if(/^(\w*)=(.*?)(\d*)$/)
152 push @encoders, sub { $data .= pack $spec, $item->{$f}; };
156 push @encoders, sub { $data .= pack $spec, $item->{$f}; };
160 push @encoders, sub { $data .= pack $spec, @{$item->{$f}}; };
168 $_->() for @encoders;
174 sub EncodeDirection(@)
176 my ($x, $y, $z) = @_;
179 map { ($_ / 0.02454369260617025967) & 0xFF }
181 atan2(sqrt($x * $x + $y * $y), $z),
187 sub DecodeDirection($)
191 my ($pitch, $yaw) = map { $_ * 0.02454369260617025967 } @$dir; # maps 256 to 2pi
194 cos($yaw) * sin($pitch),
195 sin($yaw) * sin($pitch),
200 sub IntervalIntersection($$$$)
202 my ($a, $al, $b, $bl) = @_;
203 my $a0 = $a - 0.5 * $al;
204 my $a1 = $a + 0.5 * $al;
205 my $b0 = $b - 0.5 * $bl;
206 my $b1 = $b + 0.5 * $bl;
207 my $left = ($a0 > $b0) ? $a0 : $b0;
208 my $right = ($a1 > $b1) ? $b1 : $a1;
209 die "Non-intersecting intervals $a $al $b $bl"
211 return $right - $left;
214 sub BoxIntersection(@)
216 my ($x, $y, $z, $w, $h, $d, $x2, $y2, $z2, $w2, $h2, $d2) = @_;
218 IntervalIntersection($x, $w, $x2, $w2)
220 IntervalIntersection($y, $h, $y2, $h2)
222 IntervalIntersection($z, $d, $z2, $d2);
231 my $msgalign = [0, 3, 2, 1]->[length($msg) % 4];
232 my $total = 17 * 8 + 8 + length($msg) + $msgalign;
236 my $nl = length $bsp[$_]->[2];
237 my $align = [0, 3, 2, 1]->[$nl % 4];
238 $total += $nl + $align;
239 print "BSP lump $_ ($lumpname[$_]): offset $bsp[$_]->[0] length $bsp[$_]->[1] newlength $nl\n";
240 my $endpos = $bsp[$_]->[0] + $bsp[$_]->[1];
241 $max = $endpos if $max < $endpos;
243 print "BSP file size will change from $max to $total bytes\n";
245 elsif(/^-d(.+)$/) # delete a lump
247 my $id = $lumpid{$1};
248 die "invalid lump $1 to remove"
252 elsif(/^-r(.+)$/) # replace a lump
254 my $id = $lumpid{$1};
255 die "invalid lump $1 to replace"
257 $bsp[$id]->[2] = do { undef local $/; scalar <STDIN>; };
259 elsif(/^-m(.*)$/) # change the message
263 elsif(/^-l(jpg|png|tga)(\d+)?$/) # externalize lightmaps (deleting the internal ones)
268 my $faces = $bsp[$lumpid{faces}]->[2];
269 my $lightmaps = $bsp[$lumpid{lightmaps}]->[2];
270 my @values = DecodeLump $faces,
271 qw/texture=V effect=V type=V vertex=V n_vertexes=V meshvert=V n_meshverts=V lm_index=V lm_start=f2 lm_size=f2 lm_origin=f3 lm_vec_0=f3 lm_vec_1=f3 normal=f3 size=V2/;
275 my $l = $_->{lm_index};
276 next if $l >= 2**31; # signed
283 $lightmaps{$_+1} = $lightmaps{$_} for keys %lightmaps;
285 for(sort { $a <=> $b } keys %lightmaps)
287 print STDERR "Lightmap $_ was used $lightmaps{$_} times\n";
289 # export that lightmap
290 my $lmsize = 128 * 128 * 3;
291 next if length $lightmaps < ($_ + 1) * $lmsize;
292 my $lmdata = substr $lightmaps, $_ * $lmsize, $lmsize;
293 my $img = Image::Magick->new(size => '128x128', depth => 8, magick => 'RGB');
294 $img->BlobToImage($lmdata);
295 my $outfn = sprintf "%s/lm_%04d.$ext", $basename, $_;
297 $img->Set(quality => $quality)
299 my $err = $img->Write($outfn);
302 print STDERR "Wrote $outfn\n";
305 # nullify the lightmap lump
306 $bsp[$lumpid{lightmaps}]->[2] = "";
308 elsif(/^-g(.+)$/) # export light grid as an image (for debugging)
311 my @models = DecodeLump $bsp[$lumpid{models}]->[2],
312 qw/mins=f3 maxs=f3 face=V n_faces=V brush=V n_brushes=V/;
313 my $entities = $bsp[$lumpid{entities}]->[2];
314 my @entitylines = split /\r?\n/, $entities;
315 my $gridsize = "64 64 128";
319 /^\s*"_?gridsize"\s+"(.*)"$/
322 my @scale = map { 1 / $_ } split / /, $gridsize;
323 my @imins = map { ceil($models[0]{mins}[$_] * $scale[$_]) } 0..2;
324 my @imaxs = map { floor($models[0]{maxs}[$_] * $scale[$_]) } 0..2;
325 my @isize = map { $imaxs[$_] - $imins[$_] + 1 } 0..2;
326 my $isize = $isize[0] * $isize[1] * $isize[2];
327 my @gridcells = DecodeLump $bsp[$lumpid{lightgrid}]->[2],
328 qw/ambient=C3 directional=C3 dir=C2/;
329 die "Cannot decode light grid"
330 unless $isize == @gridcells;
332 # sum up the "ambient" light over all pixels
335 for my $y(0..$isize[1]-1)
337 for my $x(0..$isize[0]-1)
339 my ($r, $g, $b) = (0, 0, 0);
340 for my $z(0..$isize[2]-1)
342 my $cell = $gridcells[$x + $y * $isize[0] + $z * $isize[0] * $isize[1]];
343 $r += $cell->{ambient}->[0];
344 $g += $cell->{ambient}->[1];
345 $b += $cell->{ambient}->[2];
347 push @pixels, [$r, $g, $b];
348 $max = $r if $max < $r;
349 $max = $g if $max < $g;
350 $max = $b if $max < $b;
356 $pixeldata .= pack "CCC", map { 255 * $p->[$_] / $max } 0..2;
359 my $img = Image::Magick->new(size => sprintf("%dx%d", $isize[0], $isize[1]), depth => 8, magick => 'RGB');
360 $img->BlobToImage($pixeldata);
361 $img->Write($filename);
362 print STDERR "Wrote $filename\n";
364 elsif(/^-G(.+)$/) # decimate light grid
367 my $filter = 1; # 0 = nearest, 1 = box filter
369 my @models = DecodeLump $bsp[$lumpid{models}]->[2],
370 qw/mins=f3 maxs=f3 face=V n_faces=V brush=V n_brushes=V/;
371 my $entities = $bsp[$lumpid{entities}]->[2];
372 my @entitylines = split /\r?\n/, $entities;
373 my $gridsize = "64 64 128";
374 my $gridsizeindex = undef;
375 for(0..@entitylines-1)
377 my $l = $entitylines[$_];
379 if($l =~ /^\s*"_?gridsize"\s+"(.*)"$/)
385 my @scale = map { 1 / $_ } split / /, $gridsize;
386 my @imins = map { ceil($models[0]{mins}[$_] * $scale[$_]) } 0..2;
387 my @imaxs = map { floor($models[0]{maxs}[$_] * $scale[$_]) } 0..2;
388 my @isize = map { $imaxs[$_] - $imins[$_] + 1 } 0..2;
389 my $isize = $isize[0] * $isize[1] * $isize[2];
390 my @gridcells = DecodeLump $bsp[$lumpid{lightgrid}]->[2],
391 qw/ambient=C3 directional=C3 dir=C2/;
392 die "Cannot decode light grid"
393 unless $isize == @gridcells;
395 # get the new grid size values
396 my @newscale = map { $_ / $decimate } @scale;
397 my $newgridsize = join " ", map { 1 / $_ } @newscale;
398 my @newimins = map { ceil($models[0]{mins}[$_] * $newscale[$_]) } 0..2;
399 my @newimaxs = map { floor($models[0]{maxs}[$_] * $newscale[$_]) } 0..2;
400 my @newisize = map { $newimaxs[$_] - $newimins[$_] + 1 } 0..2;
403 my @newgridcells = ();
404 for my $z($newimins[2]..$newimaxs[2])
406 # the coords are MIDPOINTS of the grid cells!
407 my @oldz = grep { $_ >= $imins[2] && $_ <= $imaxs[2] } floor(($z - 0.5) * $decimate + 0.5) .. ceil(($z + 0.5) * $decimate - 0.5);
408 my $innerz_raw = $z * $decimate;
409 my $innerz = floor($innerz_raw + 0.5);
410 $innerz = $imins[2] if $innerz < $imins[2];
411 $innerz = $imaxs[2] if $innerz > $imaxs[2];
412 for my $y($newimins[1]..$newimaxs[1])
414 my @oldy = grep { $_ >= $imins[1] && $_ <= $imaxs[1] } floor(($y - 0.5) * $decimate + 0.5) .. ceil(($y + 0.5) * $decimate - 0.5);
415 my $innery_raw = $y * $decimate;
416 my $innery = floor($innery_raw + 0.5);
417 $innery = $imins[1] if $innery < $imins[1];
418 $innery = $imaxs[1] if $innery > $imaxs[1];
419 for my $x($newimins[0]..$newimaxs[0])
421 my @oldx = grep { $_ >= $imins[0] && $_ <= $imaxs[0] } floor(($x - 0.5) * $decimate + 0.5) .. ceil(($x + 0.5) * $decimate - 0.5);
422 my $innerx_raw = $x * $decimate;
423 my $innerx = floor($innerx_raw + 0.5);
424 $innerx = $imins[0] if $innerx < $imins[0];
425 $innerx = $imaxs[0] if $innerx > $imaxs[0];
431 my $innercell = $gridcells[($innerx - $imins[0]) + $isize[0] * ($innery - $imins[1]) + $isize[0] * $isize[1] * ($innerz - $imins[2])];
438 my $cell = $gridcells[($X - $imins[0]) + $isize[0] * ($Y - $imins[1]) + $isize[0] * $isize[1] * ($Z - $imins[2])];
440 my $cellweight = BoxIntersection(
442 map { $_ * $decimate } $x, $y, $z, 1, 1, 1
445 $dir[$_] += $cellweight * $cell->{directional}->[$_] for 0..2;
446 $amb[$_] += $cellweight * $cell->{ambient}->[$_] for 0..2;
447 my @norm = DecodeDirection $cell->{dir};
448 $vec[$_] += $cellweight * $norm[$_] for 0..2;
449 $weight += $cellweight;
455 $dir[$_] /= $weight for 0..2;
456 $dir[$_] *= $filter for 0..2;
457 $dir[$_] += (1 - $filter) * $innercell->{directional}->[$_] for 0..2;
459 $amb[$_] /= $weight for 0..2;
460 $amb[$_] *= $filter for 0..2;
461 $amb[$_] += (1 - $filter) * $innercell->{ambient}->[$_] for 0..2;
463 my @norm = DecodeDirection $innercell->{dir};
464 $vec[$_] /= $weight for 0..2;
465 $vec[$_] *= $filter for 0..2;
466 $vec[$_] += (1 - $filter) * $norm[$_] for 0..2;
470 directional => \@dir,
471 dir => EncodeDirection @norm
475 push @newgridcells, $innercell;
480 $bsp[$lumpid{lightgrid}]->[2] = EncodeLump \@newgridcells,
481 qw/ambient=C3 directional=C3 dir=C2/;
482 splice @entitylines, $gridsizeindex, 1, ()
483 if defined $gridsizeindex;
484 splice @entitylines, 1, 0, qq{"gridsize" "$newgridsize"};
485 $bsp[$lumpid{entities}]->[2] = join "\n", @entitylines;
487 elsif(/^-x(.+)$/) # extract lump to stdout
489 my $id = $lumpid{$1};
490 die "invalid lump $1 to extract"
492 print $bsp[$id]->[2];
494 elsif(/^-S(.*)=(.*)$/)
499 my @l = DecodeLump $bsp[$lumpid{textures}]->[2], qw/name=a64 flags=V contents=V/;
502 next if $replaced[$_];
503 if($l[$_]->{name} eq $from)
506 $l[$_]->{name} = $to;
509 $bsp[$lumpid{textures}]->[2] = EncodeLump \@l, qw/name=a64 flags=V contents=V/;
513 for(DecodeLump $bsp[$lumpid{textures}]->[2], qw/name=a64 flags=V contents=V/)
515 print "$_->{name}\n";
518 elsif(/^-o(.+)?$/) # write the final BSP file
522 if not defined $outfile;
523 open my $fh, ">", $outfile
524 or die "$outfile: $!";
526 my $msgalign = [0, 3, 2, 1]->[length($msg) % 4];
527 my $pos = 17 * 8 + tell($fh) + length($msg) + $msgalign;
530 my $align = [0, 3, 2, 1]->[length($_->[2]) % 4];
532 $_->[1] = length $_->[2];
533 $pos += $_->[1] + $align;
534 print $fh pack "VV", $_->[0], $_->[1];
537 print $fh "\x00" x $msgalign;
540 my $align = [0, 3, 2, 1]->[length($_->[2]) % 4];
542 print $fh "\x00" x $align;
545 print STDERR "Wrote $outfile\n";
549 die "Invalid option: $_";
555 # decimate light grid
556 # edit lightmaps/grid