newgrf_station.cpp

Go to the documentation of this file.
00001 /* $Id: newgrf_station.cpp 16059 2009-04-14 21:07:33Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 #include "variables.h"
00007 #include "landscape.h"
00008 #include "debug.h"
00009 #include "station_map.h"
00010 #include "newgrf_commons.h"
00011 #include "newgrf_station.h"
00012 #include "newgrf_spritegroup.h"
00013 #include "newgrf_sound.h"
00014 #include "town.h"
00015 #include "newgrf_town.h"
00016 #include "gfx_func.h"
00017 #include "date_func.h"
00018 #include "company_func.h"
00019 #include "animated_tile_func.h"
00020 #include "functions.h"
00021 #include "tunnelbridge_map.h"
00022 #include "spritecache.h"
00023 
00024 #include "table/strings.h"
00025 
00026 static StationClass _station_classes[STAT_CLASS_MAX];
00027 
00028 enum {
00029   MAX_SPECLIST = 255,
00030 };
00031 
00037 void ResetStationClasses()
00038 {
00039   for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
00040     _station_classes[i].id = 0;
00041     _station_classes[i].name = STR_EMPTY;
00042     _station_classes[i].stations = 0;
00043 
00044     free(_station_classes[i].spec);
00045     _station_classes[i].spec = NULL;
00046   }
00047 
00048   /* Set up initial data */
00049   _station_classes[0].id = 'DFLT';
00050   _station_classes[0].name = STR_STAT_CLASS_DFLT;
00051   _station_classes[0].stations = 1;
00052   _station_classes[0].spec = MallocT<StationSpec*>(1);
00053   _station_classes[0].spec[0] = NULL;
00054 
00055   _station_classes[1].id = 'WAYP';
00056   _station_classes[1].name = STR_STAT_CLASS_WAYP;
00057   _station_classes[1].stations = 1;
00058   _station_classes[1].spec = MallocT<StationSpec*>(1);
00059   _station_classes[1].spec[0] = NULL;
00060 }
00061 
00067 StationClassID AllocateStationClass(uint32 cls)
00068 {
00069   for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
00070     if (_station_classes[i].id == cls) {
00071       /* ClassID is already allocated, so reuse it. */
00072       return i;
00073     } else if (_station_classes[i].id == 0) {
00074       /* This class is empty, so allocate it to the ClassID. */
00075       _station_classes[i].id = cls;
00076       return i;
00077     }
00078   }
00079 
00080   grfmsg(2, "StationClassAllocate: already allocated %d classes, using default", STAT_CLASS_MAX);
00081   return STAT_CLASS_DFLT;
00082 }
00083 
00085 void SetStationClassName(StationClassID sclass, StringID name)
00086 {
00087   assert(sclass < STAT_CLASS_MAX);
00088   _station_classes[sclass].name = name;
00089 }
00090 
00092 StringID GetStationClassName(StationClassID sclass)
00093 {
00094   assert(sclass < STAT_CLASS_MAX);
00095   return _station_classes[sclass].name;
00096 }
00097 
00102 uint GetNumStationClasses()
00103 {
00104   uint i;
00105   for (i = 0; i < STAT_CLASS_MAX && _station_classes[i].id != 0; i++) {}
00106   return i;
00107 }
00108 
00114 uint GetNumCustomStations(StationClassID sclass)
00115 {
00116   assert(sclass < STAT_CLASS_MAX);
00117   return _station_classes[sclass].stations;
00118 }
00119 
00124 void SetCustomStationSpec(StationSpec *statspec)
00125 {
00126   StationClass *station_class;
00127   int i;
00128 
00129   /* If the station has already been allocated, don't reallocate it. */
00130   if (statspec->allocated) return;
00131 
00132   assert(statspec->sclass < STAT_CLASS_MAX);
00133   station_class = &_station_classes[statspec->sclass];
00134 
00135   i = station_class->stations++;
00136   station_class->spec = ReallocT(station_class->spec, station_class->stations);
00137 
00138   station_class->spec[i] = statspec;
00139   statspec->allocated = true;
00140 }
00141 
00148 const StationSpec *GetCustomStationSpec(StationClassID sclass, uint station)
00149 {
00150   assert(sclass < STAT_CLASS_MAX);
00151   if (station < _station_classes[sclass].stations)
00152     return _station_classes[sclass].spec[station];
00153 
00154   /* If the custom station isn't defined any more, then the GRF file
00155    * probably was not loaded. */
00156   return NULL;
00157 }
00158 
00166 const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx, int *index)
00167 {
00168   uint j;
00169 
00170   for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
00171     for (j = 0; j < _station_classes[i].stations; j++) {
00172       const StationSpec *statspec = _station_classes[i].spec[j];
00173       if (statspec == NULL) continue;
00174       if (statspec->grffile->grfid == grfid && statspec->localidx == localidx) {
00175         if (index != NULL) *index = j;
00176         return statspec;
00177       }
00178     }
00179   }
00180 
00181   return NULL;
00182 }
00183 
00184 
00185 /* Evaluate a tile's position within a station, and return the result a bitstuffed format.
00186  * if not centred: .TNLcCpP, if centred: .TNL..CP
00187  * T = Tile layout number (GetStationGfx), N = Number of platforms, L = Length of platforms
00188  * C = Current platform number from start, c = from end
00189  * P = Position along platform from start, p = from end
00190  * if centred, C/P start from the centre and c/p are not available.
00191  */
00192 uint32 GetPlatformInfo(Axis axis, byte tile, int platforms, int length, int x, int y, bool centred)
00193 {
00194   uint32 retval = 0;
00195 
00196   if (axis == AXIS_X) {
00197     Swap(platforms, length);
00198     Swap(x, y);
00199   }
00200 
00201   /* Limit our sizes to 4 bits */
00202   platforms = min(15, platforms);
00203   length    = min(15, length);
00204   x = min(15, x);
00205   y = min(15, y);
00206   if (centred) {
00207     x -= platforms / 2;
00208     y -= length / 2;
00209     SB(retval,  0, 4, y & 0xF);
00210     SB(retval,  4, 4, x & 0xF);
00211   } else {
00212     SB(retval,  0, 4, y);
00213     SB(retval,  4, 4, length - y - 1);
00214     SB(retval,  8, 4, x);
00215     SB(retval, 12, 4, platforms - x - 1);
00216   }
00217   SB(retval, 16, 4, length);
00218   SB(retval, 20, 4, platforms);
00219   SB(retval, 24, 4, tile);
00220 
00221   return retval;
00222 }
00223 
00224 
00225 /* Find the end of a railway station, from the tile, in the direction of delta.
00226  * If check_type is set, we stop if the custom station type changes.
00227  * If check_axis is set, we stop if the station direction changes.
00228  */
00229 static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
00230 {
00231   bool waypoint;
00232   byte orig_type = 0;
00233   Axis orig_axis = AXIS_X;
00234 
00235   waypoint = IsTileType(tile, MP_RAILWAY);
00236 
00237   if (waypoint) {
00238     if (check_axis) orig_axis = GetWaypointAxis(tile);
00239   } else {
00240     if (check_type) orig_type = GetCustomStationSpecIndex(tile);
00241     if (check_axis) orig_axis = GetRailStationAxis(tile);
00242   }
00243 
00244   while (true) {
00245     TileIndex new_tile = TILE_ADD(tile, delta);
00246 
00247     if (waypoint) {
00248       if (!IsRailWaypointTile(new_tile)) break;
00249       if (check_axis && GetWaypointAxis(new_tile) != orig_axis) break;
00250     } else {
00251       if (!IsRailwayStationTile(new_tile)) break;
00252       if (check_type && GetCustomStationSpecIndex(new_tile) != orig_type) break;
00253       if (check_axis && GetRailStationAxis(new_tile) != orig_axis) break;
00254     }
00255 
00256     tile = new_tile;
00257   }
00258   return tile;
00259 }
00260 
00261 
00262 static uint32 GetPlatformInfoHelper(TileIndex tile, bool check_type, bool check_axis, bool centred)
00263 {
00264   int tx = TileX(tile);
00265   int ty = TileY(tile);
00266   int sx = TileX(FindRailStationEnd(tile, TileDiffXY(-1,  0), check_type, check_axis));
00267   int sy = TileY(FindRailStationEnd(tile, TileDiffXY( 0, -1), check_type, check_axis));
00268   int ex = TileX(FindRailStationEnd(tile, TileDiffXY( 1,  0), check_type, check_axis)) + 1;
00269   int ey = TileY(FindRailStationEnd(tile, TileDiffXY( 0,  1), check_type, check_axis)) + 1;
00270   Axis axis = IsTileType(tile, MP_RAILWAY) ? GetWaypointAxis(tile) : GetRailStationAxis(tile);
00271 
00272   tx -= sx; ex -= sx;
00273   ty -= sy; ey -= sy;
00274 
00275   return GetPlatformInfo(axis, IsTileType(tile, MP_RAILWAY) ? 2 : GetStationGfx(tile), ex, ey, tx, ty, centred);
00276 }
00277 
00278 
00279 static uint32 GetRailContinuationInfo(TileIndex tile)
00280 {
00281   /* Tile offsets and exit dirs for X axis */
00282   static const Direction x_dir[8] = { DIR_SW, DIR_NE, DIR_SE, DIR_NW, DIR_S, DIR_E, DIR_W, DIR_N };
00283   static const DiagDirection x_exits[8] = { DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SW, DIAGDIR_NE };
00284 
00285   /* Tile offsets and exit dirs for Y axis */
00286   static const Direction y_dir[8] = { DIR_SE, DIR_NW, DIR_SW, DIR_NE, DIR_S, DIR_W, DIR_E, DIR_N };
00287   static const DiagDirection y_exits[8] = { DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SE, DIAGDIR_NW };
00288 
00289   Axis axis = IsTileType(tile, MP_RAILWAY) ? GetWaypointAxis(tile) : GetRailStationAxis(tile);
00290 
00291   /* Choose appropriate lookup table to use */
00292   const Direction *dir = axis == AXIS_X ? x_dir : y_dir;
00293   const DiagDirection *diagdir = axis == AXIS_X ? x_exits : y_exits;
00294 
00295   uint32 res = 0;
00296   uint i;
00297 
00298   for (i = 0; i < lengthof(x_dir); i++, dir++, diagdir++) {
00299     TileIndex neighbour_tile = tile + TileOffsByDir(*dir);
00300     TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile, TRANSPORT_RAIL, 0));
00301     if (trackbits != TRACK_BIT_NONE) {
00302       /* If there is any track on the tile, set the bit in the second byte */
00303       SetBit(res, i + 8);
00304 
00305       /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
00306        * with the next tile because the ramp is not going in the right direction. */
00307       if (IsTileType(neighbour_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(neighbour_tile) != *diagdir) {
00308         continue;
00309       }
00310 
00311       /* If any track reaches our exit direction, set the bit in the lower byte */
00312       if (trackbits & DiagdirReachesTracks(*diagdir)) SetBit(res, i);
00313     }
00314   }
00315 
00316   return res;
00317 }
00318 
00319 
00320 /* Station Resolver Functions */
00321 static uint32 StationGetRandomBits(const ResolverObject *object)
00322 {
00323   const Station *st = object->u.station.st;
00324   const TileIndex tile = object->u.station.tile;
00325   return (st == NULL ? 0 : st->random_bits) | (tile == INVALID_TILE ? 0 : GetStationTileRandomBits(tile) << 16);
00326 }
00327 
00328 
00329 static uint32 StationGetTriggers(const ResolverObject *object)
00330 {
00331   const Station *st = object->u.station.st;
00332   return st == NULL ? 0 : st->waiting_triggers;
00333 }
00334 
00335 
00336 static void StationSetTriggers(const ResolverObject *object, int triggers)
00337 {
00338   Station *st = (Station*)object->u.station.st;
00339   assert(st != NULL);
00340   st->waiting_triggers = triggers;
00341 }
00342 
00348 static struct {
00349   uint32 v40;
00350   uint32 v41;
00351   uint32 v45;
00352   uint32 v46;
00353   uint32 v47;
00354   uint32 v49;
00355   uint8 valid;
00356 } _svc;
00357 
00358 static uint32 StationGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
00359 {
00360   const Station *st = object->u.station.st;
00361   TileIndex tile = object->u.station.tile;
00362 
00363   if (object->scope == VSG_SCOPE_PARENT) {
00364     /* Pass the request on to the town of the station */
00365     const Town *t;
00366 
00367     if (st != NULL) {
00368       t = st->town;
00369     } else if (tile != INVALID_TILE) {
00370       t = ClosestTownFromTile(tile, UINT_MAX);
00371     } else {
00372       *available = false;
00373       return UINT_MAX;
00374     }
00375 
00376     return TownGetVariable(variable, parameter, available, t);
00377   }
00378 
00379   if (st == NULL) {
00380     /* Station does not exist, so we're in a purchase list */
00381     switch (variable) {
00382       case 0x40:
00383       case 0x41:
00384       case 0x46:
00385       case 0x47:
00386       case 0x49: return 0x2110000;        // Platforms, tracks & position
00387       case 0x42: return 0;                // Rail type (XXX Get current type from GUI?)
00388       case 0x43: return _current_company; // Station owner
00389       case 0x44: return 2;                // PBS status
00390       case 0xFA: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
00391     }
00392 
00393     *available = false;
00394     return UINT_MAX;
00395   }
00396 
00397   switch (variable) {
00398     /* Calculated station variables */
00399     case 0x40:
00400       if (!HasBit(_svc.valid, 0)) { _svc.v40 = GetPlatformInfoHelper(tile, false, false, false); SetBit(_svc.valid, 0); }
00401       return _svc.v40;
00402 
00403     case 0x41:
00404       if (!HasBit(_svc.valid, 1)) { _svc.v41 = GetPlatformInfoHelper(tile, true,  false, false); SetBit(_svc.valid, 1); }
00405       return _svc.v41;
00406 
00407     case 0x42: return GetTerrainType(tile) | (GetRailType(tile) << 8);
00408     case 0x43: return st->owner; // Station owner
00409     case 0x44:
00410       if (IsRailWaypointTile(tile)) {
00411         return GetDepotWaypointReservation(tile) ? 7 : 4;
00412       } else {
00413         return GetRailwayStationReservation(tile) ? 7 : 4; // PBS status
00414       }
00415     case 0x45:
00416       if (!HasBit(_svc.valid, 2)) { _svc.v45 = GetRailContinuationInfo(tile); SetBit(_svc.valid, 2); }
00417       return _svc.v45;
00418 
00419     case 0x46:
00420       if (!HasBit(_svc.valid, 3)) { _svc.v46 = GetPlatformInfoHelper(tile, false, false, true); SetBit(_svc.valid, 3); }
00421       return _svc.v46;
00422 
00423     case 0x47:
00424       if (!HasBit(_svc.valid, 4)) { _svc.v47 = GetPlatformInfoHelper(tile, true,  false, true); SetBit(_svc.valid, 4); }
00425       return _svc.v47;
00426 
00427     case 0x48: { // Accepted cargo types
00428       CargoID cargo_type;
00429       uint32 value = 0;
00430 
00431       for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
00432         if (HasBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::PICKUP)) SetBit(value, cargo_type);
00433       }
00434       return value;
00435     }
00436     case 0x49:
00437       if (!HasBit(_svc.valid, 5)) { _svc.v49 = GetPlatformInfoHelper(tile, false, true, false); SetBit(_svc.valid, 5); }
00438       return _svc.v49;
00439 
00440     case 0x4A: // Animation frame of tile
00441       return GetStationAnimationFrame(tile);
00442 
00443     /* Variables which use the parameter */
00444     /* Variables 0x60 to 0x65 are handled separately below */
00445     case 0x66: // Animation frame of nearby tile
00446       if (parameter != 0) tile = GetNearbyTile(parameter, tile);
00447       return st->TileBelongsToRailStation(tile) ? GetStationAnimationFrame(tile) : UINT_MAX;
00448 
00449     case 0x67: { // Land info of nearby tile
00450       Axis axis = GetRailStationAxis(tile);
00451 
00452       if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
00453 
00454       Slope tileh = GetTileSlope(tile, NULL);
00455       bool swap = (axis == AXIS_Y && HasBit(tileh, SLOPE_W) != HasBit(tileh, SLOPE_E));
00456 
00457       return GetNearbyTileInformation(tile) ^ (swap ? SLOPE_EW : 0);
00458     }
00459 
00460     case 0x68: { // Station info of nearby tiles
00461       TileIndex nearby_tile = GetNearbyTile(parameter, tile);
00462 
00463       if (!IsRailwayStationTile(nearby_tile)) return 0xFFFFFFFF;
00464 
00465       uint32 grfid = st->speclist[GetCustomStationSpecIndex(tile)].grfid;
00466       bool perpendicular = GetRailStationAxis(tile) != GetRailStationAxis(nearby_tile);
00467       bool same_station = st->TileBelongsToRailStation(nearby_tile);
00468       uint32 res = GB(GetStationGfx(nearby_tile), 1, 2) << 12 | !!perpendicular << 11 | !!same_station << 10;
00469 
00470       if (IsCustomStationSpecIndex(nearby_tile)) {
00471         const StationSpecList ssl = GetStationByTile(nearby_tile)->speclist[GetCustomStationSpecIndex(nearby_tile)];
00472         res |= 1 << (ssl.grfid != grfid ? 9 : 8) | ssl.localidx;
00473       }
00474       return res;
00475     }
00476 
00477     /* General station properties */
00478     case 0x82: return 50;
00479     case 0x84: return st->string_id;
00480     case 0x86: return 0;
00481     case 0x8A: return st->had_vehicle_of_type;
00482     case 0xF0: return st->facilities;
00483     case 0xF1: return st->airport_type;
00484     case 0xF2: return st->truck_stops->status;
00485     case 0xF3: return st->bus_stops->status;
00486     case 0xF6: return st->airport_flags;
00487     case 0xF7: return GB(st->airport_flags, 8, 8);
00488     case 0xFA: return Clamp(st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
00489   }
00490 
00491   /* Handle cargo variables with parameter, 0x60 to 0x65 */
00492   if (variable >= 0x60 && variable <= 0x65) {
00493     CargoID c = GetCargoTranslation(parameter, object->u.station.statspec->grffile);
00494 
00495     if (c == CT_INVALID) return 0;
00496     const GoodsEntry *ge = &st->goods[c];
00497 
00498     switch (variable) {
00499       case 0x60: return min(ge->cargo.Count(), 4095);
00500       case 0x61: return ge->days_since_pickup;
00501       case 0x62: return ge->rating;
00502       case 0x63: return ge->cargo.DaysInTransit();
00503       case 0x64: return ge->last_speed | (ge->last_age << 8);
00504       case 0x65: return GB(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 3;
00505     }
00506   }
00507 
00508   /* Handle cargo variables (deprecated) */
00509   if (variable >= 0x8C && variable <= 0xEC) {
00510     const GoodsEntry *g = &st->goods[GB(variable - 0x8C, 3, 4)];
00511     switch (GB(variable - 0x8C, 0, 3)) {
00512       case 0: return g->cargo.Count();
00513       case 1: return GB(min(g->cargo.Count(), 4095), 0, 4) | (GB(g->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 7);
00514       case 2: return g->days_since_pickup;
00515       case 3: return g->rating;
00516       case 4: return g->cargo.Source();
00517       case 5: return g->cargo.DaysInTransit();
00518       case 6: return g->last_speed;
00519       case 7: return g->last_age;
00520     }
00521   }
00522 
00523   DEBUG(grf, 1, "Unhandled station property 0x%X", variable);
00524 
00525   *available = false;
00526   return UINT_MAX;
00527 }
00528 
00529 
00530 static const SpriteGroup *StationResolveReal(const ResolverObject *object, const SpriteGroup *group)
00531 {
00532   const Station *st = object->u.station.st;
00533   const StationSpec *statspec = object->u.station.statspec;
00534   uint set;
00535 
00536   uint cargo = 0;
00537   CargoID cargo_type = object->u.station.cargo_type;
00538 
00539   if (st == NULL || statspec->sclass == STAT_CLASS_WAYP) {
00540     return group->g.real.loading[0];
00541   }
00542 
00543   switch (cargo_type) {
00544     case CT_INVALID:
00545     case CT_DEFAULT_NA:
00546     case CT_PURCHASE:
00547       cargo = 0;
00548       break;
00549 
00550     case CT_DEFAULT:
00551       for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
00552         cargo += st->goods[cargo_type].cargo.Count();
00553       }
00554       break;
00555 
00556     default:
00557       cargo = st->goods[cargo_type].cargo.Count();
00558       break;
00559   }
00560 
00561   if (HasBit(statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->trainst_w + st->trainst_h);
00562   cargo = min(0xfff, cargo);
00563 
00564   if (cargo > statspec->cargo_threshold) {
00565     if (group->g.real.num_loading > 0) {
00566       set = ((cargo - statspec->cargo_threshold) * group->g.real.num_loading) / (4096 - statspec->cargo_threshold);
00567       return group->g.real.loading[set];
00568     }
00569   } else {
00570     if (group->g.real.num_loaded > 0) {
00571       set = (cargo * group->g.real.num_loaded) / (statspec->cargo_threshold + 1);
00572       return group->g.real.loaded[set];
00573     }
00574   }
00575 
00576   return group->g.real.loading[0];
00577 }
00578 
00579 
00580 static void NewStationResolver(ResolverObject *res, const StationSpec *statspec, const Station *st, TileIndex tile)
00581 {
00582   res->GetRandomBits = StationGetRandomBits;
00583   res->GetTriggers   = StationGetTriggers;
00584   res->SetTriggers   = StationSetTriggers;
00585   res->GetVariable   = StationGetVariable;
00586   res->ResolveReal   = StationResolveReal;
00587 
00588   res->u.station.st       = st;
00589   res->u.station.statspec = statspec;
00590   res->u.station.tile     = tile;
00591 
00592   res->callback        = CBID_NO_CALLBACK;
00593   res->callback_param1 = 0;
00594   res->callback_param2 = 0;
00595   res->last_value      = 0;
00596   res->trigger         = 0;
00597   res->reseed          = 0;
00598   res->count           = 0;
00599   res->grffile         = (statspec != NULL ? statspec->grffile : NULL);
00600 }
00601 
00602 static const SpriteGroup *ResolveStation(ResolverObject *object)
00603 {
00604   const SpriteGroup *group;
00605   CargoID ctype = CT_DEFAULT_NA;
00606 
00607   if (object->u.station.st == NULL) {
00608     /* No station, so we are in a purchase list */
00609     ctype = CT_PURCHASE;
00610   } else {
00611     /* Pick the first cargo that we have waiting */
00612     for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
00613       const CargoSpec *cs = GetCargo(cargo);
00614       if (cs->IsValid() && object->u.station.statspec->spritegroup[cargo] != NULL &&
00615           !object->u.station.st->goods[cargo].cargo.Empty()) {
00616         ctype = cargo;
00617         break;
00618       }
00619     }
00620   }
00621 
00622   group = object->u.station.statspec->spritegroup[ctype];
00623   if (group == NULL) {
00624     ctype = CT_DEFAULT;
00625     group = object->u.station.statspec->spritegroup[ctype];
00626   }
00627 
00628   if (group == NULL) return NULL;
00629 
00630   /* Remember the cargo type we've picked */
00631   object->u.station.cargo_type = ctype;
00632 
00633   /* Invalidate all cached vars */
00634   _svc.valid = 0;
00635 
00636   return Resolve(group, object);
00637 }
00638 
00639 SpriteID GetCustomStationRelocation(const StationSpec *statspec, const Station *st, TileIndex tile)
00640 {
00641   const SpriteGroup *group;
00642   ResolverObject object;
00643 
00644   NewStationResolver(&object, statspec, st, tile);
00645 
00646   group = ResolveStation(&object);
00647   if (group == NULL || group->type != SGT_RESULT) return 0;
00648   return group->g.result.sprite - 0x42D;
00649 }
00650 
00651 
00652 SpriteID GetCustomStationGroundRelocation(const StationSpec *statspec, const Station *st, TileIndex tile)
00653 {
00654   const SpriteGroup *group;
00655   ResolverObject object;
00656 
00657   NewStationResolver(&object, statspec, st, tile);
00658   if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
00659     object.callback_param1 = 1; // Indicate we are resolving the ground sprite
00660   }
00661 
00662   group = ResolveStation(&object);
00663   if (group == NULL || group->type != SGT_RESULT) return 0;
00664   return group->g.result.sprite - 0x42D;
00665 }
00666 
00667 
00668 uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, const Station *st, TileIndex tile)
00669 {
00670   const SpriteGroup *group;
00671   ResolverObject object;
00672 
00673   NewStationResolver(&object, statspec, st, tile);
00674 
00675   object.callback        = callback;
00676   object.callback_param1 = param1;
00677   object.callback_param2 = param2;
00678 
00679   group = ResolveStation(&object);
00680   if (group == NULL || group->type != SGT_CALLBACK) return CALLBACK_FAILED;
00681   return group->g.callback.result;
00682 }
00683 
00684 
00692 int AllocateSpecToStation(const StationSpec *statspec, Station *st, bool exec)
00693 {
00694   uint i;
00695 
00696   if (statspec == NULL || st == NULL) return 0;
00697 
00698   for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
00699     if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
00700   }
00701 
00702   if (i == MAX_SPECLIST) {
00703     /* As final effort when the spec list is already full...
00704      * try to find the same spec and return that one. This might
00705      * result in slighty "wrong" (as per specs) looking stations,
00706      * but it's fairly unlikely that one reaches the limit anyways.
00707      */
00708     for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
00709       if (st->speclist[i].spec == statspec) return i;
00710     }
00711 
00712     return -1;
00713   }
00714 
00715   if (exec) {
00716     if (i >= st->num_specs) {
00717       st->num_specs = i + 1;
00718       st->speclist = ReallocT(st->speclist, st->num_specs);
00719 
00720       if (st->num_specs == 2) {
00721         /* Initial allocation */
00722         st->speclist[0].spec     = NULL;
00723         st->speclist[0].grfid    = 0;
00724         st->speclist[0].localidx = 0;
00725       }
00726     }
00727 
00728     st->speclist[i].spec     = statspec;
00729     st->speclist[i].grfid    = statspec->grffile->grfid;
00730     st->speclist[i].localidx = statspec->localidx;
00731   }
00732 
00733   return i;
00734 }
00735 
00736 
00742 void DeallocateSpecFromStation(Station *st, byte specindex)
00743 {
00744   /* specindex of 0 (default) is never freeable */
00745   if (specindex == 0) return;
00746 
00747   /* Check all tiles over the station to check if the specindex is still in use */
00748   BEGIN_TILE_LOOP(tile, st->trainst_w, st->trainst_h, st->train_tile) {
00749     if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st->index && IsRailwayStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
00750       return;
00751     }
00752   } END_TILE_LOOP(tile, st->trainst_w, st->trainst_h, st->train_tile)
00753 
00754   /* This specindex is no longer in use, so deallocate it */
00755   st->speclist[specindex].spec     = NULL;
00756   st->speclist[specindex].grfid    = 0;
00757   st->speclist[specindex].localidx = 0;
00758 
00759   /* If this was the highest spec index, reallocate */
00760   if (specindex == st->num_specs - 1) {
00761     for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--) {}
00762 
00763     if (st->num_specs > 1) {
00764       st->speclist = ReallocT(st->speclist, st->num_specs);
00765     } else {
00766       free(st->speclist);
00767       st->num_specs = 0;
00768       st->speclist  = NULL;
00769       st->cached_anim_triggers = 0;
00770       return;
00771     }
00772   }
00773 
00774   StationUpdateAnimTriggers(st);
00775 }
00776 
00786 bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
00787 {
00788   const StationSpec *statspec;
00789   const DrawTileSprites *sprites;
00790   const DrawTileSeqStruct *seq;
00791   const RailtypeInfo *rti = GetRailTypeInfo(railtype);
00792   SpriteID relocation;
00793   SpriteID image;
00794   SpriteID palette = COMPANY_SPRITE_COLOUR(_local_company);
00795   uint tile = 2;
00796 
00797   statspec = GetCustomStationSpec(sclass, station);
00798   if (statspec == NULL) return false;
00799 
00800   relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE);
00801 
00802   if (HasBit(statspec->callbackmask, CBM_STATION_SPRITE_LAYOUT)) {
00803     uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, NULL, INVALID_TILE);
00804     if (callback != CALLBACK_FAILED) tile = callback;
00805   }
00806 
00807   if (statspec->renderdata == NULL) {
00808     sprites = GetStationTileLayout(STATION_RAIL, tile + axis);
00809   } else {
00810     sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
00811   }
00812 
00813   image = sprites->ground.sprite;
00814   SpriteID pal = sprites->ground.pal;
00815   if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
00816     image += GetCustomStationGroundRelocation(statspec, NULL, INVALID_TILE);
00817     image += rti->custom_ground_offset;
00818   } else {
00819     image += rti->total_offset;
00820   }
00821 
00822   DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
00823 
00824   Point child_offset = {0, 0};
00825 
00826   foreach_draw_tile_seq(seq, sprites->seq) {
00827     image = seq->image.sprite;
00828     if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
00829       image += rti->total_offset;
00830     } else {
00831       image += relocation;
00832     }
00833 
00834     pal = SpriteLayoutPaletteTransform(image, seq->image.pal, palette);
00835 
00836     if ((byte)seq->delta_z != 0x80) {
00837       Point pt = RemapCoords(seq->delta_x, seq->delta_y, seq->delta_z);
00838       DrawSprite(image, pal, x + pt.x, y + pt.y);
00839 
00840       const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
00841       child_offset.x = pt.x + spr->x_offs;
00842       child_offset.y = pt.y + spr->y_offs;
00843     } else {
00844       /* For stations and original spritelayouts delta_x and delta_y are signed */
00845       DrawSprite(image, pal, x + child_offset.x + seq->delta_x, y + child_offset.y + seq->delta_y);
00846     }
00847   }
00848 
00849   return true;
00850 }
00851 
00852 
00853 const StationSpec *GetStationSpec(TileIndex t)
00854 {
00855   const Station *st;
00856   uint specindex;
00857 
00858   if (!IsCustomStationSpecIndex(t)) return NULL;
00859 
00860   st = GetStationByTile(t);
00861   specindex = GetCustomStationSpecIndex(t);
00862   return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
00863 }
00864 
00865 
00866 /* Check if a rail station tile is traversable.
00867  * XXX This could be cached (during build) in the map array to save on all the dereferencing */
00868 bool IsStationTileBlocked(TileIndex tile)
00869 {
00870   const StationSpec *statspec = GetStationSpec(tile);
00871 
00872   return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
00873 }
00874 
00875 /* Check if a rail station tile is electrifiable.
00876  * XXX This could be cached (during build) in the map array to save on all the dereferencing */
00877 bool IsStationTileElectrifiable(TileIndex tile)
00878 {
00879   const StationSpec *statspec = GetStationSpec(tile);
00880 
00881   return
00882     statspec == NULL ||
00883     HasBit(statspec->pylons, GetStationGfx(tile)) ||
00884     !HasBit(statspec->wires, GetStationGfx(tile));
00885 }
00886 
00887 void AnimateStationTile(TileIndex tile)
00888 {
00889   const StationSpec *ss = GetStationSpec(tile);
00890   if (ss == NULL) return;
00891 
00892   const Station *st = GetStationByTile(tile);
00893 
00894   uint8 animation_speed = ss->anim_speed;
00895 
00896   if (HasBit(ss->callbackmask, CBM_STATION_ANIMATION_SPEED)) {
00897     uint16 callback = GetStationCallback(CBID_STATION_ANIMATION_SPEED, 0, 0, ss, st, tile);
00898     if (callback != CALLBACK_FAILED) animation_speed = Clamp(callback & 0xFF, 0, 16);
00899   }
00900 
00901   if (_tick_counter % (1 << animation_speed) != 0) return;
00902 
00903   uint8 frame      = GetStationAnimationFrame(tile);
00904   uint8 num_frames = ss->anim_frames;
00905 
00906   bool frame_set_by_callback = false;
00907 
00908   if (HasBit(ss->callbackmask, CBM_STATION_ANIMATION_NEXT_FRAME)) {
00909     uint32 param = HasBit(ss->flags, SSF_CB141_RANDOM_BITS) ? Random() : 0;
00910     uint16 callback = GetStationCallback(CBID_STATION_ANIM_NEXT_FRAME, param, 0, ss, st, tile);
00911 
00912     if (callback != CALLBACK_FAILED) {
00913       frame_set_by_callback = true;
00914 
00915       switch (callback & 0xFF) {
00916         case 0xFF:
00917           DeleteAnimatedTile(tile);
00918           break;
00919 
00920         case 0xFE:
00921           frame_set_by_callback = false;
00922           break;
00923 
00924         default:
00925           frame = callback & 0xFF;
00926           break;
00927       }
00928 
00929       /* If the lower 7 bits of the upper byte of the callback
00930        * result are not empty, it is a sound effect. */
00931       if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
00932     }
00933   }
00934 
00935   if (!frame_set_by_callback) {
00936     if (frame < num_frames) {
00937       frame++;
00938     } else if (frame == num_frames && HasBit(ss->anim_status, 0)) {
00939       /* This animation loops, so start again from the beginning */
00940       frame = 0;
00941     } else {
00942       /* This animation doesn't loop, so stay here */
00943       DeleteAnimatedTile(tile);
00944     }
00945   }
00946 
00947   SetStationAnimationFrame(tile, frame);
00948   MarkTileDirtyByTile(tile);
00949 }
00950 
00951 
00952 static void ChangeStationAnimationFrame(const StationSpec *ss, const Station *st, TileIndex tile, uint16 random_bits, StatAnimTrigger trigger, CargoID cargo_type)
00953 {
00954   uint16 callback = GetStationCallback(CBID_STATION_ANIM_START_STOP, (random_bits << 16) | Random(), (uint8)trigger | (cargo_type << 8), ss, st, tile);
00955   if (callback == CALLBACK_FAILED) return;
00956 
00957   switch (callback & 0xFF) {
00958     case 0xFD: /* Do nothing. */         break;
00959     case 0xFE: AddAnimatedTile(tile);    break;
00960     case 0xFF: DeleteAnimatedTile(tile); break;
00961     default:
00962       SetStationAnimationFrame(tile, callback);
00963       AddAnimatedTile(tile);
00964       break;
00965   }
00966 
00967   /* If the lower 7 bits of the upper byte of the callback
00968    * result are not empty, it is a sound effect. */
00969   if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
00970 }
00971 
00972 enum TriggerArea {
00973   TA_TILE,
00974   TA_PLATFORM,
00975   TA_WHOLE,
00976 };
00977 
00978 struct TileArea {
00979   TileIndex tile;
00980   uint8 w;
00981   uint8 h;
00982 
00983   TileArea(const Station *st, TileIndex tile, TriggerArea ta)
00984   {
00985     switch (ta) {
00986       default: NOT_REACHED();
00987 
00988       case TA_TILE:
00989         this->tile = tile;
00990         this->w    = 1;
00991         this->h    = 1;
00992         break;
00993 
00994       case TA_PLATFORM: {
00995         TileIndex start, end;
00996         Axis axis = GetRailStationAxis(tile);
00997         TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(axis));
00998 
00999         for (end = tile; IsRailwayStationTile(end + delta) && IsCompatibleTrainStationTile(tile, end + delta); end += delta) { /* Nothing */ }
01000         for (start = tile; IsRailwayStationTile(start - delta) && IsCompatibleTrainStationTile(tile, start - delta); start -= delta) { /* Nothing */ }
01001 
01002         this->tile = start;
01003         this->w = TileX(end) - TileX(start) + 1;
01004         this->h = TileY(end) - TileY(start) + 1;
01005         break;
01006       }
01007 
01008       case TA_WHOLE:
01009         this->tile = st->train_tile;
01010         this->w    = st->trainst_w + 1;
01011         this->h    = st->trainst_h + 1;
01012         break;
01013     }
01014   }
01015 };
01016 
01017 void StationAnimationTrigger(const Station *st, TileIndex tile, StatAnimTrigger trigger, CargoID cargo_type)
01018 {
01019   /* List of coverage areas for each animation trigger */
01020   static const TriggerArea tas[] = {
01021     TA_TILE, TA_WHOLE, TA_WHOLE, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM, TA_WHOLE
01022   };
01023 
01024   /* Get Station if it wasn't supplied */
01025   if (st == NULL) st = GetStationByTile(tile);
01026 
01027   /* Check the cached animation trigger bitmask to see if we need
01028    * to bother with any further processing. */
01029   if (!HasBit(st->cached_anim_triggers, trigger)) return;
01030 
01031   uint16 random_bits = Random();
01032   TileArea area = TileArea(st, tile, tas[trigger]);
01033 
01034   for (uint y = 0; y < area.h; y++) {
01035     for (uint x = 0; x < area.w; x++) {
01036       if (st->TileBelongsToRailStation(area.tile)) {
01037         const StationSpec *ss = GetStationSpec(area.tile);
01038         if (ss != NULL && HasBit(ss->anim_triggers, trigger)) {
01039           CargoID cargo;
01040           if (cargo_type == CT_INVALID) {
01041             cargo = CT_INVALID;
01042           } else {
01043             cargo = GetReverseCargoTranslation(cargo_type, ss->grffile);
01044           }
01045           ChangeStationAnimationFrame(ss, st, area.tile, random_bits, trigger, cargo);
01046         }
01047       }
01048       area.tile += TileDiffXY(1, 0);
01049     }
01050     area.tile += TileDiffXY(-area.w, 1);
01051   }
01052 }
01053 
01058 void StationUpdateAnimTriggers(Station *st)
01059 {
01060   st->cached_anim_triggers = 0;
01061 
01062   /* Combine animation trigger bitmask for all station specs
01063    * of this station. */
01064   for (uint i = 0; i < st->num_specs; i++) {
01065     const StationSpec *ss = st->speclist[i].spec;
01066     if (ss != NULL) st->cached_anim_triggers |= ss->anim_triggers;
01067   }
01068 }

Generated on Wed Dec 23 20:12:50 2009 for OpenTTD by  doxygen 1.5.6