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 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
|
/*
* File: maps.cc
* Summary: Functions used to create vaults.
* Written by: Linley Henzell
*/
#include "AppHdr.h"
#include "maps.h"
#include <cstring>
#include <cstdlib>
#include <algorithm>
#ifndef TARGET_COMPILER_VC
#include <unistd.h>
#endif
#include "coordit.h"
#include "dbg-maps.h"
#include "dungeon.h"
#include "env.h"
#include "enum.h"
#include "files.h"
#include "flood_find.h"
#ifdef USE_TILE
#include "initfile.h"
#endif
#include "libutil.h"
#include "message.h"
#include "mapdef.h"
#include "mon-util.h"
#include "mon-place.h"
#include "coord.h"
#include "random.h"
#include "state.h"
#include "tags.h"
#include "terrain.h"
static int write_vault(map_def &mdef,
vault_placement &,
bool check_place);
static int apply_vault_definition(
map_def &def,
vault_placement &,
bool check_place);
static bool resolve_map(map_def &def);
// Globals: Use unwind_var to modify!
// Checks whether a map place is valid.
map_place_check_t map_place_valid = map_safe_vault_place;
// If non-empty, any floating vault's @ exit must land on these point.
point_vector map_anchor_points;
//////////////////////////////////////////////////////////////////////////
// New style vault definitions
static map_vector vdefs;
// Parameter array that vault code can use.
string_vector map_parameters;
dgn_map_parameters::dgn_map_parameters(const std::string &astring)
: mpar(map_parameters)
{
map_parameters.push_back(astring);
}
dgn_map_parameters::dgn_map_parameters(const string_vector ¶meters)
: mpar(map_parameters)
{
map_parameters = parameters;
}
/* ******************** BEGIN PUBLIC FUNCTIONS ******************* */
// Remember (!!!) - if a member of the monster array isn't specified
// within a vault subroutine, assume that it holds a random monster
// -- only in cases of explicit monsters assignment have I listed
// out random monster insertion {dlb}
// Make sure that vault_n, where n is a number, is a vault which can be put
// anywhere, while other vault names are for specific level ranges, etc.
int vault_main( vault_placement &place, const map_def *vault,
bool check_place)
{
#ifdef DEBUG_DIAGNOSTICS
mprf(MSGCH_DIAGNOSTICS, "Generating level: %s (%d,%d)",
vault->name.c_str(), place.pos.x, place.pos.y);
if (crawl_state.map_stat_gen)
mapgen_report_map_try(*vault);
#endif
// Return value of MAP_NONE forces dungeon.cc to regenerate the
// level, except for branch entry vaults where dungeon.cc just
// rejects the vault and places a vanilla entry.
return (write_vault( const_cast<map_def&>(*vault), place, check_place ));
}
static int write_vault(map_def &mdef,
vault_placement &place,
bool check_place)
{
mdef.load();
// Copy the map so we can monkey with it.
place.map = mdef;
place.map.original = &mdef;
// Try so many times to place the map. This will always succeed
// unless there are conflicting map placements in 'avoid', or there
// is a map validate Lua hook that keeps rejecting the map.
int tries = 25;
while (tries-- > 0)
{
if (!resolve_map(place.map))
continue;
// Must set size here, or minivaults will not be placed correctly.
place.size = place.map.size();
place.orient = apply_vault_definition(place.map,
place, check_place);
if (place.orient != MAP_NONE)
return (place.orient);
}
return (MAP_NONE);
}
static bool resolve_map_lua(map_def &map)
{
map.reinit();
std::string err = map.run_lua(true);
if (!err.empty())
{
#ifdef DEBUG_DIAGNOSTICS
if (crawl_state.map_stat_gen)
mapgen_report_error(map, err);
#endif
mprf(MSGCH_ERROR, "Lua error: %s", err.c_str());
return (false);
}
map.fixup();
err = map.resolve();
if (!err.empty())
{
mprf(MSGCH_ERROR, "Error: %s", err.c_str());
return (false);
}
if (!map.test_lua_validate(false))
return (false);
return (true);
}
// Mirror the map if appropriate, resolve substitutable symbols (?),
static bool resolve_map(map_def &map)
{
if (!resolve_map_lua(map))
return (false);
// Don't bother flipping or rotating 1x1 subvaults.
// This just cuts down on level generation message spam.
if (map.map.width() == map.map.height() && map.map.width() == 1)
return (true);
// Mirroring is possible for any map that does not explicitly forbid it.
// Note that mirroring also flips the orientation.
if (coinflip())
map.hmirror();
if (coinflip())
map.vmirror();
// The map may also refuse to be rotated.
if (coinflip())
map.rotate(coinflip());
return (true);
}
bool resolve_subvault(map_def &map)
{
ASSERT(map.is_subvault());
if (!map.is_subvault())
return false;
if (!resolve_map_lua(map))
return false;
int width = map.subvault_width();
int height = map.subvault_height();
bool can_rot = (map.map.width() <= height && map.map.height() <= width);
bool must_rot = (map.map.width() > width || map.map.height() > height);
// Too big, whether or not it is rotated.
if (must_rot && !can_rot)
return false;
if (must_rot || can_rot && coinflip())
{
bool dir = coinflip();
map.rotate(dir);
// Update post-rotation dimensions.
width = map.subvault_width();
height = map.subvault_height();
}
// Inexact fits with dimensions flipped will get rotated above.
bool exact_fit = (map.map.height() == height && map.map.width() == width);
if (!exact_fit)
{
if (coinflip())
map.hmirror();
if (coinflip())
map.vmirror();
// The map may have refused to have been rotated, so verify dimensions.
bool valid = (map.map.width() <= width && map.map.height() <= height);
return (valid);
}
// Don't bother flipping or rotating 1x1 subvaults.
// This just cuts down on level generation message spam.
if (exact_fit && width == height && width == 1)
return (true);
// Count original mismatches. If mirroring the map causes more cells to
// not be written, then don't mirror. This allows oddly shaped subvaults
// to be fit correctly into a parent vault that specifies the exact same
// shape.
const coord_def svplace(0, 0);
// 0 - normal
// 1 - flip horz
// 2 - flip vert + horz
// 3 - flip vert
int mismatch[4];
// Mirror map in all directions to find best fit.
mismatch[0] = map.subvault_mismatch_count(svplace);
map.hmirror();
mismatch[1] = map.subvault_mismatch_count(svplace);
map.vmirror();
mismatch[2] = map.subvault_mismatch_count(svplace);
map.hmirror();
mismatch[3] = map.subvault_mismatch_count(svplace);
int min_mismatch = std::min(mismatch[0], mismatch[1]);
min_mismatch = std::min(min_mismatch, mismatch[2]);
min_mismatch = std::min(min_mismatch, mismatch[3]);
// Pick a mirror combination with the minimum number of mismatches.
int idx = random2(4);
while (mismatch[idx] != min_mismatch)
idx = (idx + 1) % 4;
// Flip the map (currently vmirror'd) to the correct orientation.
if (idx == 0)
{
map.vmirror();
}
else if (idx == 1)
{
map.vmirror();
map.hmirror();
}
else if (idx == 2)
{
map.hmirror();
}
ASSERT(map.subvault_mismatch_count(svplace) == min_mismatch);
// We already know this is an exact fit, so this is a success.
return (true);
}
void fit_region_into_map_bounds(coord_def &pos, const coord_def &size,
int margin)
{
const int X_1(X_BOUND_1 + margin);
const int X_2(X_BOUND_2 - margin);
const int Y_1(Y_BOUND_1 + margin);
const int Y_2(Y_BOUND_2 - margin);
ASSERT(size.x <= (X_2 - X_1 + 1) && size.y <= (Y_2 - Y_1 + 1));
if (pos.x < X_1)
pos.x = X_1;
if (pos.y < Y_1)
pos.y = Y_1;
if (pos.x + size.x - 1 > X_2)
pos.x = X_2 - size.x + 1;
if (pos.y + size.y - 1 > Y_2)
pos.y = Y_2 - size.y + 1;
}
// Used for placement of vaults.
static bool _may_overwrite_feature(const coord_def p,
bool water_ok, bool wall_ok = true)
{
// If there's a mask specifying where vaults can be placed, don't
// allow stepping outside it.
if (Vault_Placement_Mask && !(*Vault_Placement_Mask)(p))
return (false);
// If in the abyss, the placement mask is the only check necessary
// for terrain; we must still check that we're not overwriting
// items.
if (Vault_Placement_Mask && player_in_level_area(LEVEL_ABYSS))
{
return (igrd(p) == NON_ITEM);
}
const dungeon_feature_type grid = grd(p);
// Deep water grids may be overwritten if water_ok == true.
if (grid == DNGN_DEEP_WATER)
return (water_ok);
// Handle all other non-LOS blocking grids here.
if (!feat_is_opaque(grid)
&& grid != DNGN_FLOOR
&& grid != DNGN_SHALLOW_WATER
&& grid != DNGN_OPEN_DOOR
&& grid != DNGN_SECRET_DOOR
&& !feat_is_closed_door(grid))
{
return (false);
}
if (feat_is_wall(grid) || grid == DNGN_TREE)
return (wall_ok);
// Otherwise, feel free to clobber this feature.
return (true);
}
bool map_safe_vault_place(const map_def &map,
const coord_def &c,
const coord_def &size)
{
if (size.zero())
return (true);
const bool water_ok =
map.has_tag("water_ok") || player_in_branch(BRANCH_SWAMP);
const std::vector<std::string> &lines = map.map.get_lines();
for (rectangle_iterator ri(c, c + size - 1); ri; ++ri)
{
const coord_def cp(*ri);
const coord_def dp(cp - c);
if (lines[dp.y][dp.x] == ' ')
continue;
// Also check adjacent squares for collisions, because being next
// to another vault may block off one of this vault's exits.
for (int y = -1; y <= 1; ++y)
for (int x = -1; x <= 1; ++x)
{
const coord_def vp(x + cp.x, y + cp.y);
if (map_bounds(vp) && (env.level_map_mask(vp) & MMT_VAULT))
return (false);
}
// Don't overwrite features other than floor, rock wall, doors,
// nor water, if !water_ok.
if (!_may_overwrite_feature(cp, water_ok))
return (false);
// Don't overwrite monsters or items, either!
if (monster_at(cp) || igrd(cp) != NON_ITEM)
return (false);
}
return (true);
}
static bool _connected_minivault_place(const coord_def &c,
const vault_placement &place)
{
if (place.size.zero())
return (true);
// Must not be completely isolated.
const bool water_ok = place.map.has_tag("water_ok");
const std::vector<std::string> &lines = place.map.map.get_lines();
for (rectangle_iterator ri(c, c + place.size - 1); ri; ++ri)
{
const coord_def &ci(*ri);
if (lines[ci.y - c.y][ci.x - c.x] == ' ')
continue;
if (_may_overwrite_feature(ci, water_ok, false))
return (true);
}
return (false);
}
static coord_def _find_minivault_place(
const vault_placement &place,
bool check_place)
{
// [ds] The margin around the edges of the map where the minivault
// won't be placed. Purely arbitrary as far as I can see.
const int margin = MAPGEN_BORDER * 2;
// Find a target area which can be safely overwritten.
for (int tries = 0; tries < 600; ++tries)
{
coord_def v1(random_range( margin, GXM - margin - place.size.x ),
random_range( margin, GYM - margin - place.size.y ));
if (check_place && !map_place_valid(place.map, v1, place.size))
{
#ifdef DEBUG_MINIVAULT_PLACEMENT
mprf(MSGCH_DIAGNOSTICS,
"Skipping (%d,%d): not safe to place map",
v1.x, v1.y);
#endif
continue;
}
if (!_connected_minivault_place(v1, place))
{
#ifdef DEBUG_MINIVAULT_PLACEMENT
mprf(MSGCH_DIAGNOSTICS,
"Skipping (%d,%d): not a good minivault place (tags: %s)",
v1.x, v1.y, place.map.tags.c_str());
#endif
continue;
}
return (v1);
}
return (coord_def(-1, -1));
}
static bool apply_vault_grid(map_def &def,
vault_placement &place,
bool check_place)
{
const map_lines &ml = def.map;
const int orient = def.orient;
const coord_def size(ml.size());
coord_def start(0, 0);
if (orient == MAP_SOUTH || orient == MAP_SOUTHEAST
|| orient == MAP_SOUTHWEST)
{
start.y = GYM - size.y;
}
if (orient == MAP_EAST || orient == MAP_NORTHEAST
|| orient == MAP_SOUTHEAST)
{
start.x = GXM - size.x;
}
// Handle maps aligned along cardinals that are smaller than
// the corresponding map dimension.
if ((orient == MAP_NORTH || orient == MAP_SOUTH
|| orient == MAP_ENCOMPASS)
&& size.x < GXM)
{
start.x = (GXM - size.x) / 2;
}
if ((orient == MAP_EAST || orient == MAP_WEST
|| orient == MAP_ENCOMPASS)
&& size.y < GYM)
{
start.y = (GYM - size.y) / 2;
}
// Floating maps can go anywhere, ask the map_def to suggest a place.
if (orient == MAP_FLOAT)
{
const bool minivault = def.has_tag("minivault");
if (map_bounds(place.pos))
{
start = place.pos - size / 2;
fit_region_into_map_bounds(start, size, minivault ? 2 : 0);
}
else if (minivault)
{
start = _find_minivault_place(place, check_place);
if (map_bounds(start))
fit_region_into_map_bounds(start, size, 2);
}
else
start = def.float_place();
}
if (!map_bounds(start))
return (false);
if (check_place && !map_place_valid(def, start, size))
{
dprf("Bad vault place: (%d,%d) dim (%d,%d)",
start.x, start.y, size.x, size.y);
return (false);
}
place.pos = start;
place.size = size;
return (true);
}
static int apply_vault_definition(
map_def &def,
vault_placement &place,
bool check_place)
{
if (!apply_vault_grid(def, place, check_place))
return (MAP_NONE);
int orient = def.orient;
if (orient == MAP_NONE)
orient = MAP_NORTH;
return (orient);
}
///////////////////////////////////////////////////////////////////////////
// Map lookups
template <typename I>
static bool map_has_no_tags(const map_def &map, I begin, I end)
{
for ( ; begin != end; ++begin)
if (map.has_tag(*begin))
return (false);
return (true);
}
static bool vault_unforbidden(const map_def &map)
{
return (you.uniq_map_names.find(map.name) == you.uniq_map_names.end()
&& (env.level_uniq_maps.find(map.name) ==
env.level_uniq_maps.end())
&& map_has_no_tags(map, you.uniq_map_tags.begin(),
you.uniq_map_tags.end())
&& map_has_no_tags(map, env.level_uniq_map_tags.begin(),
env.level_uniq_map_tags.end()));
}
static bool map_matches_layout_type(const map_def &map)
{
return (env.level_layout_type.empty()
|| !map.has_tag_prefix("layout_")
|| map.has_tag("layout_" + env.level_layout_type));
}
const map_def *find_map_by_name(const std::string &name)
{
for (unsigned i = 0, size = vdefs.size(); i < size; ++i)
if (vdefs[i].name == name)
return (&vdefs[i]);
return (NULL);
}
// Discards Lua code loaded by all maps to reduce memory use. If any stripped
// map is reused, its data will be reloaded from the .dsc
void strip_all_maps()
{
for (unsigned i = 0, size = vdefs.size(); i < size; ++i)
vdefs[i].strip();
}
std::vector<std::string> find_map_matches(const std::string &name)
{
std::vector<std::string> matches;
for (unsigned i = 0, size = vdefs.size(); i < size; ++i)
if (vdefs[i].name.find(name) != std::string::npos)
matches.push_back(vdefs[i].name);
return (matches);
}
mapref_vector find_maps_for_tag(const std::string tag,
bool check_depth,
bool check_used)
{
mapref_vector maps;
level_id place = level_id::current();
for (unsigned i = 0, size = vdefs.size(); i < size; ++i)
{
const map_def &mapdef = vdefs[i];
if (mapdef.has_tag(tag)
&& !mapdef.has_tag("dummy")
&& (!check_depth || !mapdef.has_depth()
|| mapdef.is_usable_in(place))
&& (!check_used || vault_unforbidden(mapdef)))
{
maps.push_back(&mapdef);
}
}
return (maps);
}
int weight_map_vector (std::vector<map_def> maps)
{
int weights = 0;
for (std::vector<map_def>::iterator mi = maps.begin(); mi != maps.end(); ++mi)
weights += mi->weight;
return (weights);
}
struct map_selector
{
private:
enum select_type
{
PLACE,
DEPTH,
DEPTH_AND_CHANCE,
TAG,
};
public:
bool accept(const map_def &md) const;
void announce(const map_def *map) const;
bool valid() const
{
return (sel == TAG || place.is_valid());
}
static map_selector by_place(const level_id &_place, bool _mini)
{
return map_selector(map_selector::PLACE, _place, "", _mini, false);
}
static map_selector by_depth(const level_id &_place, bool _mini)
{
return map_selector(map_selector::DEPTH, _place, "", _mini, true);
}
static map_selector by_depth_chance(const level_id &_place)
{
return map_selector(map_selector::DEPTH_AND_CHANCE, _place, "", false,
true);
}
static map_selector by_tag(const std::string &_tag,
bool _check_depth,
bool _check_chance,
const level_id &_place = level_id::current())
{
map_selector msel = map_selector(map_selector::TAG, _place, _tag,
false, _check_depth);
msel.ignore_chance = !_check_chance;
return (msel);
}
private:
map_selector(select_type _typ, const level_id &_pl,
const std::string &_tag,
bool _mini, bool _check_depth)
: ignore_chance(false), preserve_dummy(false),
sel(_typ), place(_pl), tag(_tag),
mini(_mini), check_depth(_check_depth),
check_layout(sel == DEPTH && place == level_id::current())
{
if (_typ == PLACE)
ignore_chance = true;
}
bool depth_selectable(const map_def &) const;
public:
bool ignore_chance;
bool preserve_dummy;
const select_type sel;
const level_id place;
const std::string tag;
const bool mini;
const bool check_depth;
const bool check_layout;
};
bool map_selector::depth_selectable(const map_def &mapdef) const
{
return (!mapdef.place.is_valid()
&& mapdef.is_usable_in(place)
// Some tagged levels cannot be selected as random
// maps in a specific depth:
&& !mapdef.has_tag_suffix("entry")
&& !mapdef.has_tag("unrand")
&& !mapdef.has_tag("place_unique")
&& !mapdef.has_tag("tutorial")
&& (!mapdef.has_tag_prefix("temple_")
|| mapdef.has_tag_prefix("uniq_altar_"))
&& (!check_layout || map_matches_layout_type(mapdef)));
}
bool map_selector::accept(const map_def &mapdef) const
{
switch (sel)
{
case PLACE:
return (mapdef.is_minivault() == mini
&& mapdef.place == place
&& (!mapdef.has_tag("tutorial")
|| crawl_state.game_is_tutorial())
&& map_matches_layout_type(mapdef)
&& vault_unforbidden(mapdef));
case DEPTH:
return (mapdef.is_minivault() == mini
&& (!mapdef.chance || !mapdef.chance_priority)
&& depth_selectable(mapdef)
&& vault_unforbidden(mapdef));
case DEPTH_AND_CHANCE:
return (// Only vaults with valid chance and chance priority
(mapdef.chance > 0 && mapdef.chance_priority > 0)
&& depth_selectable(mapdef)
&& vault_unforbidden(mapdef));
case TAG:
return (mapdef.has_tag(tag)
&& (!check_depth || !mapdef.has_depth()
|| mapdef.is_usable_in(place))
&& map_matches_layout_type(mapdef)
&& vault_unforbidden(mapdef));
default:
return (false);
}
}
void map_selector::announce(const map_def *vault) const
{
#ifdef DEBUG_DIAGNOSTICS
if (vault)
{
if (sel == DEPTH_AND_CHANCE)
{
mprf(MSGCH_DIAGNOSTICS,
"[CHANCE+DEPTH] Found map %s for %s (%d:%d)",
vault->name.c_str(), place.describe().c_str(),
vault->chance_priority, vault->chance);
}
else
{
const char *format =
sel == PLACE? "[PLACE] Found map %s for %s" :
sel == DEPTH? "[DEPTH] Found random map %s for %s" :
"[TAG] Found map %s tagged '%s'";
mprf(MSGCH_DIAGNOSTICS, format,
vault->name.c_str(),
sel == TAG? tag.c_str() : place.describe().c_str());
}
}
#endif
}
static std::string _vault_chance_tag(const map_def &map)
{
if (map.has_tag_prefix("chance_"))
{
const std::vector<std::string> tags = map.get_tags();
for (int i = 0, size = tags.size(); i < size; ++i)
{
if (tags[i].find("chance_") == 0)
return (tags[i]);
}
}
return ("");
}
typedef std::vector<unsigned> vault_indices;
static vault_indices _eligible_maps_for_selector(const map_selector &sel)
{
vault_indices eligible;
if (sel.valid())
{
for (unsigned i = 0, size = vdefs.size(); i < size; ++i)
if (sel.accept(vdefs[i]))
eligible.push_back(i);
}
return (eligible);
}
static const map_def *_random_map_by_selector(const map_selector &sel);
static bool _vault_chance_new(const map_def &map,
std::set<std::string> &chance_tags)
{
if (map.chance > 0)
{
// There may be several alternatives for a portal
// vault that want to be governed by one common
// CHANCE. In this case each vault will use a
// CHANCE, and a common chance_xxx tag. Pick the
// first such vault for the chance roll. Note that
// at this point we ignore chance_priority.
const std::string tag = _vault_chance_tag(map);
if (chance_tags.find(tag) == chance_tags.end())
{
if (!tag.empty())
chance_tags.insert(tag);
return (true);
}
}
return (false);
}
class vault_chance_roll_iterator
{
public:
vault_chance_roll_iterator(const mapref_vector &_maps)
: maps(_maps), current(_maps.begin()), end(_maps.end())
{
find_valid();
}
operator bool () const { return current != end; }
const map_def *operator * () const { return *current; }
const map_def *operator -> () const { return *current; }
vault_chance_roll_iterator &operator ++ ()
{
++current;
find_valid();
return (*this);
}
vault_chance_roll_iterator operator ++ (int)
{
vault_chance_roll_iterator copy(*this);
operator ++ ();
return (copy);
}
private:
void find_valid()
{
while (current != end && random2(CHANCE_ROLL) >= (*current)->chance)
++current;
}
private:
const std::vector<const map_def *> &maps;
mapref_vector::const_iterator current;
mapref_vector::const_iterator end;
};
static const map_def *_resolve_chance_vault(const map_selector &sel,
const map_def *map)
{
const std::string chance_tag = _vault_chance_tag(*map);
// If this map has a chance_ tag, convert the search into
// a lookup for that tag.
if (!chance_tag.empty())
{
map_selector msel = map_selector::by_tag(chance_tag,
sel.check_depth,
false,
sel.place);
return _random_map_by_selector(msel);
}
return (map);
}
static mapref_vector
_random_chance_maps_in_list(const map_selector &sel,
const vault_indices &filtered)
{
// Vaults that are eligible and have >0 chance.
mapref_vector chance;
mapref_vector chosen_chances;
typedef std::set<std::string> tag_set;
tag_set chance_tags;
for (unsigned f = 0, size = filtered.size(); f < size; ++f)
{
const int i = filtered[f];
if (!sel.ignore_chance && _vault_chance_new(vdefs[i], chance_tags))
chance.push_back(&vdefs[i]);
}
for (vault_chance_roll_iterator vc(chance); vc; ++vc)
if (const map_def *chosen = _resolve_chance_vault(sel, *vc))
{
chosen_chances.push_back(chosen);
sel.announce(chosen);
}
return (chosen_chances);
}
static const map_def *
_random_map_in_list(const map_selector &sel,
const vault_indices &filtered)
{
const map_def *chosen_map = NULL;
int rollsize = 0;
// First build a list of vaults that could be used:
mapref_vector eligible;
// Vaults that are eligible and have >0 chance.
mapref_vector chance;
typedef std::set<std::string> tag_set;
tag_set chance_tags;
for (unsigned f = 0, size = filtered.size(); f < size; ++f)
{
const int i = filtered[f];
if (!sel.ignore_chance && vdefs[i].chance)
{
if (_vault_chance_new(vdefs[i], chance_tags))
chance.push_back(&vdefs[i]);
}
else
{
eligible.push_back(&vdefs[i]);
}
}
for (vault_chance_roll_iterator vc(chance); vc; ++vc)
if (const map_def *chosen = _resolve_chance_vault(sel, *vc))
{
chosen_map = chosen;
break;
}
if (!chosen_map)
{
int absdepth = 0;
if (sel.place.level_type == LEVEL_DUNGEON && sel.place.is_valid())
absdepth = sel.place.absdepth();
for (mapref_vector::const_iterator i = eligible.begin();
i != eligible.end(); ++i)
{
const map_def &map(**i);
const int weight = map.weight
+ absdepth * map.weight_depth_mult / map.weight_depth_div;
if (weight <= 0)
continue;
rollsize += weight;
if (rollsize && x_chance_in_y(weight, rollsize))
chosen_map = ↦
}
}
if (!sel.preserve_dummy && chosen_map
&& chosen_map->has_tag("dummy"))
{
chosen_map = NULL;
}
sel.announce(chosen_map);
return (chosen_map);
}
static const map_def *_random_map_by_selector(const map_selector &sel)
{
const vault_indices filtered = _eligible_maps_for_selector(sel);
return _random_map_in_list(sel, filtered);
}
// Returns a map for which PLACE: matches the given place.
const map_def *random_map_for_place(const level_id &place, bool minivault)
{
return _random_map_by_selector(map_selector::by_place(place, minivault));
}
const map_def *random_map_in_depth(const level_id &place, bool want_minivault)
{
return _random_map_by_selector(
map_selector::by_depth(place, want_minivault));
}
mapref_vector random_chance_maps_in_depth(const level_id &place)
{
map_selector sel = map_selector::by_depth_chance(place);
const vault_indices eligible = _eligible_maps_for_selector(sel);
return _random_chance_maps_in_list(sel, eligible);
}
const map_def *random_map_for_tag(const std::string &tag,
bool check_depth,
bool check_chance)
{
return _random_map_by_selector(
map_selector::by_tag(tag, check_depth, check_chance));
}
int map_count()
{
return (vdefs.size());
}
int map_count_for_tag(const std::string &tag,
bool check_depth)
{
return _eligible_maps_for_selector(
map_selector::by_tag(tag, check_depth, false)).size();
}
/////////////////////////////////////////////////////////////////////////////
// Reading maps from .des files.
// All global preludes.
std::vector<dlua_chunk> global_preludes;
// Map-specific prelude.
dlua_chunk lc_global_prelude("global_prelude");
std::string lc_desfile;
map_def lc_map;
level_range lc_range;
depth_ranges lc_default_depths;
bool lc_run_global_prelude = true;
map_load_info_t lc_loaded_maps;
std::set<std::string> map_files_read;
extern int yylineno;
void reset_map_parser()
{
lc_map.init();
lc_range.reset();
lc_default_depths.clear();
lc_global_prelude.clear();
yylineno = 1;
lc_run_global_prelude = true;
}
////////////////////////////////////////////////////////////////////////////
static bool checked_des_index_dir = false;
static std::string _des_cache_dir(const std::string &relpath = "")
{
return catpath(savedir_versioned_path("des"), relpath);
}
static void check_des_index_dir()
{
if (checked_des_index_dir)
return;
std::string desdir = _des_cache_dir();
if (!check_mkdir("Data file cache", &desdir, true))
end(1, true, "Can't create data file cache: %s", desdir.c_str());
checked_des_index_dir = true;
}
std::string get_descache_path(const std::string &file,
const std::string &ext)
{
const std::string basename =
change_file_extension(get_base_filename(file), ext);
return _des_cache_dir(basename);
}
static bool verify_file_version(const std::string &file)
{
FILE *fp = fopen(file.c_str(), "rb");
if (!fp)
return (false);
reader inf(fp);
const long ver = unmarshallInt(inf);
fclose(fp);
return (ver == MAP_CACHE_VERSION);
}
static bool verify_map_index(const std::string &base)
{
return verify_file_version(base + ".idx");
}
static bool verify_map_full(const std::string &base)
{
return verify_file_version(base + ".dsc");
}
static bool load_map_index(const std::string &base)
{
// If there's a global prelude, load that first.
{
FILE *fp = fopen((base + ".lux").c_str(), "rb");
if (fp)
{
reader inf(fp);
lc_global_prelude.read(inf);
fclose(fp);
global_preludes.push_back( lc_global_prelude );
}
}
FILE* fp = fopen((base + ".idx").c_str(), "rb");
if (!fp)
end(1, true, "Unable to read %s", (base + ".idx").c_str());
reader inf(fp);
// Discard version (it's been checked by verify_map_index).
(void) unmarshallInt(inf);
const int nmaps = unmarshallShort(inf);
const int nexist = vdefs.size();
vdefs.resize( nexist + nmaps, map_def() );
for (int i = 0; i < nmaps; ++i)
{
map_def &vdef(vdefs[nexist + i]);
vdef.read_index(inf);
vdef.description = unmarshallString(inf);
vdef.set_file(base);
lc_loaded_maps[vdef.name] = vdef.place_loaded_from;
vdef.place_loaded_from.clear();
}
fclose(fp);
return (true);
}
static bool load_map_cache(const std::string &filename)
{
check_des_index_dir();
const std::string descache_base = get_descache_path(filename, "");
file_lock deslock(descache_base + ".lk", "rb", false);
std::string file_idx = descache_base + ".idx";
std::string file_dsc = descache_base + ".dsc";
if (is_newer(filename, file_idx) || is_newer(filename, file_dsc))
return (false);
#ifdef USE_TILE
// When the executable is rebuilt for tiles, it's possible that
// the tile enums have changed, breaking old cache files.
// So, conservatively regenerate cache files after rebuilding.
{
std::string exe_path = SysEnv.crawl_base + FILE_SEPARATOR
+ SysEnv.crawl_exe;
if (is_newer(exe_path, file_idx) || is_newer(exe_path, file_dsc))
return (false);
}
#endif
if (!verify_map_index(descache_base) || !verify_map_full(descache_base))
return (false);
return load_map_index(descache_base);
}
static void write_map_prelude(const std::string &filebase)
{
const std::string luafile = filebase + ".lux";
if (lc_global_prelude.empty())
{
unlink(luafile.c_str());
return;
}
FILE *fp = fopen(luafile.c_str(), "wb");
writer outf(fp);
lc_global_prelude.write(outf);
fclose(fp);
}
static void write_map_full(const std::string &filebase, size_t vs, size_t ve)
{
const std::string cfile = filebase + ".dsc";
FILE *fp = fopen(cfile.c_str(), "wb");
if (!fp)
end(1, true, "Unable to open %s for writing", cfile.c_str());
writer outf(fp);
marshallInt(outf, MAP_CACHE_VERSION);
for (size_t i = vs; i < ve; ++i)
vdefs[i].write_full(outf);
fclose(fp);
}
static void write_map_index(const std::string &filebase, size_t vs, size_t ve)
{
const std::string cfile = filebase + ".idx";
FILE *fp = fopen(cfile.c_str(), "wb");
if (!fp)
end(1, true, "Unable to open %s for writing", cfile.c_str());
writer outf(fp);
marshallInt(outf, MAP_CACHE_VERSION);
marshallShort(outf, ve > vs? ve - vs : 0);
for (size_t i = vs; i < ve; ++i)
{
vdefs[i].write_index(outf);
marshallString(outf, vdefs[i].description);
vdefs[i].place_loaded_from.clear();
vdefs[i].strip();
}
fclose(fp);
}
static void write_map_cache(const std::string &filename, size_t vs, size_t ve)
{
check_des_index_dir();
const std::string descache_base = get_descache_path(filename, "");
file_lock deslock(descache_base + ".lk", "wb");
write_map_prelude(descache_base);
write_map_full(descache_base, vs, ve);
write_map_index(descache_base, vs, ve);
}
static void parse_maps(const std::string &s)
{
const std::string base = get_base_filename(s);
if (map_files_read.find(base) != map_files_read.end())
return;
map_files_read.insert(base);
if (load_map_cache(s))
return;
FILE *dat = fopen(s.c_str(), "r");
if (!dat)
end(1, true, "Failed to open %s for reading", s.c_str());
reset_map_parser();
extern int yyparse(void);
extern FILE *yyin;
yyin = dat;
const size_t file_start = vdefs.size();
yyparse();
fclose(dat);
global_preludes.push_back( lc_global_prelude );
write_map_cache(s, file_start, vdefs.size());
}
void read_map(const std::string &file)
{
parse_maps( lc_desfile = datafile_path(file) );
// Clean up cached environments.
dlua.callfn("dgn_flush_map_environments", 0, 0);
// Force GC to prevent heap from swelling unnecessarily.
dlua.gc();
}
void read_maps()
{
if (dlua.execfile("clua/loadmaps.lua", true, true, true))
end(1, false, "Lua error: %s", dlua.error.c_str());
lc_loaded_maps.clear();
sanity_check_maps();
}
// If a .dsc file has been changed under the running Crawl, discard
// all map knowledge and reload maps. This will not affect maps that
// have already been used, but it might trigger exciting happenings if
// the new maps fail sanity checks or remove maps that the game
// expects to be present.
void reread_maps()
{
dprf("reread_maps:: discarding %u existing maps",
vdefs.size());
// BOOM!
vdefs.clear();
map_files_read.clear();
read_maps();
}
void add_parsed_map( const map_def &md )
{
map_def map = md;
map.fixup();
vdefs.push_back( map );
}
void run_map_preludes()
{
for (int i = 0, size = global_preludes.size(); i < size; ++i)
{
dlua_chunk &chunk = global_preludes[i];
if (!chunk.empty())
{
if (chunk.load_call(dlua, NULL))
mprf(MSGCH_ERROR, "Lua error: %s", chunk.orig_error().c_str());
}
}
for (int i = 0, size = vdefs.size(); i < size; ++i)
{
if (!vdefs[i].prelude.empty())
{
std::string err = vdefs[i].run_lua(true);
if (!err.empty())
mprf(MSGCH_ERROR, "Lua error (map %s): %s",
vdefs[i].name.c_str(), err.c_str());
}
}
}
const map_def *map_by_index(int index)
{
return (&vdefs[index]);
}
void sanity_check_maps()
{
dlua.execfile("clua/sanity.lua", true, true);
}
///////////////////////////////////////////////////////////////////////////
// Debugging code
#ifdef DEBUG_DIAGNOSTICS
typedef std::pair<std::string, int> weighted_map_name;
typedef std::vector<weighted_map_name> weighted_map_names;
static weighted_map_names mg_find_random_vaults(
const level_id &place, bool wantmini)
{
weighted_map_names wms;
if (!place.is_valid())
return (wms);
typedef std::map<std::string, int> map_count_t;
map_count_t map_counts;
map_selector sel = map_selector::by_depth(place, wantmini);
sel.preserve_dummy = true;
no_messages mx;
vault_indices filtered = _eligible_maps_for_selector(sel);
for (int i = 0; i < 10000; ++i)
{
const map_def *map(_random_map_in_list(sel, filtered));
if (!map)
map_counts["(none)"]++;
else
map_counts[map->name]++;
}
for (map_count_t::const_iterator i = map_counts.begin();
i != map_counts.end(); ++i)
{
wms.push_back(*i);
}
return (wms);
}
static bool weighted_map_more_likely(
const weighted_map_name &a,
const weighted_map_name &b)
{
return (a.second > b.second);
}
static void mg_report_random_vaults(
FILE *outf, const level_id &place, bool wantmini)
{
weighted_map_names wms = mg_find_random_vaults(place, wantmini);
std::sort(wms.begin(), wms.end(), weighted_map_more_likely);
int weightsum = 0;
for (int i = 0, size = wms.size(); i < size; ++i)
weightsum += wms[i].second;
std::string line;
for (int i = 0, size = wms.size(); i < size; ++i)
{
std::string curr =
make_stringf("%s (%.2f%%)",
wms[i].first.c_str(),
100.0 * wms[i].second / weightsum);
if (i < size - 1)
curr += ", ";
if (line.length() + curr.length() > 80u)
{
fprintf(outf, "%s\n", line.c_str());
line.clear();
}
line += curr;
}
if (!line.empty())
fprintf(outf, "%s\n", line.c_str());
}
void mg_report_random_maps(FILE *outf, const level_id &place)
{
fprintf(outf, "---------------- Mini\n");
mg_report_random_vaults(outf, place, true);
fprintf(outf, "------------- Regular\n");
mg_report_random_vaults(outf, place, false);
}
#endif
|