Skip to content

Instantly share code, notes, and snippets.

@bisqwit
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bisqwit/9121711 to your computer and use it in GitHub Desktop.
Save bisqwit/9121711 to your computer and use it in GitHub Desktop.
Portal 2 Puzzlemaker Map Merger. It combines two maps into one map. You will need the PHP interpreter commandline version to run it (/usr/bin/php).
<?php
/* PORTAL 2 PUZZLEMAKER MAP MERGER - VERSION 1.0.0 (2014-02-20)
* COPYRIGHT (C) 2013,2014 Joel Yliluoma - http://iki.fi/bisqwit/
* Source code license: MIT
*/
/* PUT YOUR SETTINGS HERE: */
// Filenames for the input and output maps
define('INPUT1', 'input1.p2c');
define('INPUT2', 'input2.p2c');
define('OUTPUT', 'merged.p2c');
// Title for the output map
define('NEW_TITLE', 'Merged map');
// Where to position the input maps within the output map.
define('INPUT1_POSITION', '0 0 0');
define('INPUT2_POSITION', '11 16 0');
/* Notes:
* Compatible only with Version 12 and Version 14 maps!
* The entry and exit from the first map will be copied in the output map.
* The entry and exit from the second map will be replaced with laser emitters.
* The merger will not check whether any objects overlap or whether they are
* placed in illegal positions. That's your job.
* The maximum dimension of the outputted map is 27x27x27.
* This is a limit of the Puzzlemaker, not of this program.
* A map larger than that will load, but promptly crash Portal 2.
* Some walls on the edges may turn out portalable/wrong
* where they should not.
* If you need to rotate one of the maps, do so by moving the entrance
* door to another wall in Puzzlemaker. This will effectively cause
* the Puzzlemaker to rotate the entire map.
* This merger is not bothered by custom elements
* from add-ons like BEE2. They will work just fine.
*/
/* BEGIN SOURCE CODE - DON'T CHANGE ANYTHING AFTER THIS PART */
/*
The MIT License (MIT)
Copyright (c) 2013,2014 Joel Yliluoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Help function for Parse_DataTable()
function ParseInto(&$result, $table, &$first)
{
$end = count($table);
while($first < $end)
{
if($table[$first][0] == '/') { ++$first; continue; }
//'{'
if($table[$first] == '}') { ++$first; return; }
#if(!is_int(str_replace('"', '', $table[$first])))
$key = str_replace('"', '', $table[$first]);
#else
# $key = $table[$first];
++$first;
if($key == 'DefualtValue') $key = 'DefaultValue';
if($table[$first] == '{') // '}'
{
++$first;
if(isset($result[$key]) || $key == 'SubType'
|| $key == 'Surface'
|| $key == 'Point'
|| $key == 'Item'
)
{
if(isset($result[$key]) && !isset($result[$key][0]))
$result[$key] = Array( $result[$key] );
$n = @count($result[$key]);
ParseInto($result[$key][$n], $table, $first);
}
else
ParseInto($result[$key], $table, $first);
}
else
{
$result[$key] = str_replace('"', '', $table[$first++]);
}
}
ksort($result);
}
// Parse an ItemData file (either editoritems.txt or science/*.test)
function Parse_DataTable($data)
{
$data = str_replace("\r", "", $data);
$comment = "//[^\n]*\n";
$string = '"[^"]*"';
$parens = "[{}]";
$regexp = "@($comment)|($string)|($parens)@";
preg_match_all($regexp, $data, $mat);
$result = Array();
$idx = 0;
ParseInto($result, $mat[0], $idx);
if(isset($result['ItemData'])) $result = $result['ItemData'];
if(isset($result['Item'])) $result = $result['Item'];
return $result;
}
function EncodeArray($array, $indent)
{
$ind_str = str_pad('', $indent, "\t");
$ind_str2 = str_pad('', ++$indent, "\t");
$result = "{$ind_str}{\n";
$longest = 0;
foreach($array as $key => $data)
$longest = max($longest, strlen($key));
$longest = ($longest+8) & ~7;
foreach($array as $key => $data)
{
$key = preg_replace('/'.chr(0xA7).'[0-9]+$/', '', $key);
$result .= "{$ind_str2}\"$key\"";
$result .= str_pad('', $longest - strlen($key));
if(is_array($data))
{
$result .= "\n";
$result .= EncodeArray($data, $indent);
}
else
$result .= "\"$data\"\n";
}
$result .= "{$ind_str}}\n";
return $result;
}
class Puzzle
{
var $settings;
// voxels: name => list of coordinates
var $voxels;
// items
var $items;
// connections
var $connections;
function ReadPuzzle($string)
{
$data = Parse_DataTable($string);
$data = $data['portal2_puzzle'];
$this->settings = $data;
unset($this->settings['Voxels']);
unset($this->settings['Items']);
unset($this->settings['Connections']);
$this->items = $data['Items']['Item'];
$this->connections = $data['Connections']['Connection'];
printf("- Version %d map detected. Map version 14 works fine.\n", $data['Version']);
if($data['Version'] == 12) print "- Version 12 maps MAY work, but are untested.\n";
$this->voxels = Array();
foreach($data['Voxels'] as $name => $map)
{
if($name == 'Voxel') // Version 12
foreach($map as $voxel)
{
$p = explode(' ', $voxel['Position']);
foreach($voxel as $name => $value)
if($name != 'Position' && $value == '0')
$this->voxels[$name][] = $p;
}
else // Version 14
{
$this->ParseVoxelMap($this->voxels[$name], $map);
}
}
$this->RenumberItems(0);
$size0 = $this->settings['ChamberSize'];
$tmp = $this->UpdateChamberSize();
$size1 = $this->settings['ChamberSize'];
print "- Chamber size: $size1\n";
if($size0 != $size1)
{
print "- Oddly enough, the file header claims the size is {$size0}.\n";
}
printf("- %d items, %d connections\n", count($this->items), count($this->connections));
}
function ParseVoxelMap(&$target, $map)
{
foreach($map as $zname => $ynames)
{
$z = (int)substr($zname,1);
foreach($ynames as $yname => $xmap)
{
$y = (int)substr($yname,1);
$b = strlen($xmap);
for($a=1; $a<$b; ++$a)
if($xmap[$a] == '0')
$target[] = [ $a-1, $y, $z ];
}
}
}
function EncodeVoxels($array)
{
$size = $this->UpdateChamberSize();
$bitmap = Array();
foreach($array as $coords)
$bitmap[ $coords[2] ] [ $coords[1] ] [ $coords[0] ] = true;
$result = Array();
for($z = 0; $z <= $size[2]; ++$z)
{
$zlayer = @$bitmap[$z];
$ztarget = &$result["Z{$z}"];
for($y = 0; $y <= $size[1]; ++$y)
{
$ytarget = &$ztarget["Y{$y}"];
$ytarget = 'f';
$ylayer = @$zlayer[$y];
for($x = 0; $x <= $size[0]; ++$x)
{
$ytarget .= (isset($ylayer[$x]) ? '0' : '1');
}
}
}
return $result;
}
function EncodeEnumerated($key, $array)
{
$result = Array();
foreach($array as $k=>$v)
{
$result[ $key . chr(0xA7) . $k ] = $v;
}
return $result;
}
function RenumberItems($new_begin)
{
$old_begin = -1;
foreach($this->items as $item)
if($old_begin == -1 || $item['Index'] < $old_begin)
$old_begin = $item['Index'];
foreach($this->items as &$item)
$item['Index'] += ($new_begin - $old_begin);
foreach($this->connections as &$connection)
{
$connection['Sender'] += ($new_begin - $old_begin);
$connection['Receiver'] += ($new_begin - $old_begin);
}
#print_r($this->items);
}
function UpdateChamberSize()
{
$xmax = -1;
$ymax = -1;
$zmax = -1;
foreach($this->voxels as $name => $map)
foreach($map as $coords)
{
$xmax = max($xmax, $coords[0]);
$ymax = max($ymax, $coords[1]);
$zmax = max($zmax, $coords[2]);
}
foreach($this->items as $item)
{
$vpos = explode(' ', $item['VoxelPos']);
$xmax = max($xmax, (float)$vpos[0]);
$ymax = max($ymax, (float)$vpos[1]);
$zmax = max($zmax, (float)$vpos[2]);
}
$this->settings['ChamberSize'] = sprintf('%d %d %d', $xmax, $ymax, $zmax);
return [$xmax, $ymax, $zmax];
}
function UpdateModificationTime()
{
$this->settings['Timestamp_Modified'] = sprintf('0x%16X', time());
}
function Reposition($xdelta, $ydelta, $zdelta)
{
foreach($this->voxels as $name => &$map)
foreach($map as &$coords)
{
$coords[0] += $xdelta;
$coords[1] += $ydelta;
$coords[2] += $zdelta;
}
foreach($this->items as &$item)
{
$vpos = explode(' ', $item['VoxelPos']);
$item['VoxelPos'] = sprintf('%d %d %d', $vpos[0]+$xdelta, $vpos[1]+$ydelta, $vpos[2]+$zdelta);
}
}
function MergeWith($other)
{
$other->RenumberItems( count($this->items) );
foreach($other->voxels as $name => $map)
foreach($map as $coords)
$this->voxels[$name][] = $coords;
foreach($other->items as $item) $this->items[] = $item;
foreach($other->connections as $item) $this->connections[] = $item;
$this->settings['Title'] = NEW_TITLE;
}
function RemoveEntryExit()
{
foreach($this->items as $itemno => $item)
{
if($item['Type'] == 'ITEM_ENTRY_DOOR'
|| $item['Type'] == 'ITEM_COOP_ENTRY_DOOR'
|| $item['Type'] == 'ITEM_EXIT_DOOR'
|| $item['Type'] == 'ITEM_COOP_EXIT_DOOR')
{
if($item['Enabled'] == '0')
unset($this->items[$itemno]);
else
$this->items[$itemno]['Type'] = 'ITEM_LASER_EMITTER_CENTER';
}
}
}
function Dump()
{
$size = $this->UpdateChamberSize();
print "- Chamber size: {$this->settings['ChamberSize']}\n";
if($size[0] > 26
|| $size[1] > 26
|| $size[2] > 26)
{
print "- Warning: This map is too large! It will crash the Puzzlemaker.\n";
}
printf("- %d items, %d connections\n", count($this->items), count($this->connections));
$result = $this->settings;
$result['Version'] = 14;
$result['Voxels'] = Array();
foreach($this->voxels as $name => $map)
$result['Voxels'][$name] = $this->EncodeVoxels($map);
$result['Items'] = $this->EncodeEnumerated('Item', $this->items);
$result['Connections'] = $this->EncodeEnumerated('Connection', $this->connections);
return "\"portal2_puzzle\"\n" . EncodeArray($result, 0);
}
};
#ini_set('memory_limit', 1048576*2048);
printf("Reading %s...\n", INPUT1);
$p1 = new Puzzle;
$p1->ReadPuzzle( file_get_contents(INPUT1) );
printf("\nReading %s...\n", INPUT2);
$p2 = new Puzzle;
$p2->ReadPuzzle( file_get_contents(INPUT2) );
$p2->RemoveEntryExit();
$p = preg_split('/\\s+/', INPUT1_POSITION);
$p1->Reposition($p[0], $p[1], $p[2]);
$p = preg_split('/\\s+/', INPUT2_POSITION);
$p2->Reposition($p[0], $p[1], $p[2]);
$p1->MergeWith($p2);
printf("\nWriting %s...\n", OUTPUT);
file_put_contents(OUTPUT, $p1->Dump());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment