summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHenry Wilson <m3henry@googlemail.com>2019-04-10 22:07:06 +0100
committerMichael Lutz <michi@icosahedron.de>2019-04-10 23:22:20 +0200
commit7c8e7c6b6e16d4a26259a676db32d8776b99817e (patch)
tree99f134b7e66367cf11e10bc5061896eab4a3264f
parent3b4f224c0bc50e7248050d4bcbb6d83fd510c1cc (diff)
downloadopenttd-7c8e7c6b6e16d4a26259a676db32d8776b99817e.tar.xz
Codechange: Use null pointer literal instead of the NULL macro
-rw-r--r--src/ai/ai_config.cpp10
-rw-r--r--src/ai/ai_core.cpp42
-rw-r--r--src/ai/ai_gui.cpp60
-rw-r--r--src/ai/ai_info.cpp12
-rw-r--r--src/ai/ai_info.hpp2
-rw-r--r--src/ai/ai_instance.cpp6
-rw-r--r--src/ai/ai_scanner.cpp12
-rw-r--r--src/ai/ai_scanner.hpp4
-rw-r--r--src/aircraft_cmd.cpp76
-rw-r--r--src/aircraft_gui.cpp2
-rw-r--r--src/airport.cpp8
-rw-r--r--src/airport_gui.cpp6
-rw-r--r--src/articulated_vehicles.cpp24
-rw-r--r--src/autoreplace.cpp22
-rw-r--r--src/autoreplace_cmd.cpp84
-rw-r--r--src/autoreplace_func.h4
-rw-r--r--src/base_consist.cpp2
-rw-r--r--src/base_consist.h2
-rw-r--r--src/base_media_base.h12
-rw-r--r--src/base_media_func.h46
-rw-r--r--src/base_station_base.h2
-rw-r--r--src/blitter/32bpp_anim.cpp2
-rw-r--r--src/blitter/32bpp_anim.hpp4
-rw-r--r--src/blitter/8bpp_optimized.cpp8
-rw-r--r--src/blitter/factory.hpp14
-rw-r--r--src/blitter/null.hpp2
-rw-r--r--src/bmp.cpp6
-rw-r--r--src/bootstrap_gui.cpp10
-rw-r--r--src/bridge_gui.cpp4
-rw-r--r--src/build_vehicle_gui.cpp18
-rw-r--r--src/cargoaction.cpp14
-rw-r--r--src/cargopacket.cpp14
-rw-r--r--src/cargopacket.h2
-rw-r--r--src/cargotype.h2
-rw-r--r--src/cheat_gui.cpp10
-rw-r--r--src/clear_cmd.cpp10
-rw-r--r--src/command.cpp10
-rw-r--r--src/command_func.h4
-rw-r--r--src/command_type.h8
-rw-r--r--src/company_base.h6
-rw-r--r--src/company_cmd.cpp42
-rw-r--r--src/company_gui.cpp22
-rw-r--r--src/console.cpp46
-rw-r--r--src/console_cmds.cpp70
-rw-r--r--src/console_gui.cpp30
-rw-r--r--src/console_internal.h2
-rw-r--r--src/core/alloc_func.hpp24
-rw-r--r--src/core/alloc_type.hpp2
-rw-r--r--src/core/kdtree.hpp10
-rw-r--r--src/core/mem_func.hpp4
-rw-r--r--src/core/pool_func.hpp28
-rw-r--r--src/core/pool_type.hpp28
-rw-r--r--src/core/smallmatrix_type.hpp10
-rw-r--r--src/core/sort_func.hpp4
-rw-r--r--src/crashlog.cpp50
-rw-r--r--src/crashlog.h2
-rw-r--r--src/date_gui.cpp4
-rw-r--r--src/debug.cpp12
-rw-r--r--src/dedicated.cpp6
-rw-r--r--src/depend/depend.cpp50
-rw-r--r--src/depot_cmd.cpp6
-rw-r--r--src/depot_gui.cpp74
-rw-r--r--src/disaster_vehicle.cpp24
-rw-r--r--src/dock_gui.cpp16
-rw-r--r--src/driver.cpp22
-rw-r--r--src/driver.h6
-rw-r--r--src/economy.cpp46
-rw-r--r--src/effectvehicle.cpp2
-rw-r--r--src/elrail.cpp6
-rw-r--r--src/engine.cpp34
-rw-r--r--src/engine_base.h6
-rw-r--r--src/error.h4
-rw-r--r--src/error_gui.cpp8
-rw-r--r--src/fileio.cpp152
-rw-r--r--src/fileio_func.h8
-rw-r--r--src/fios.cpp74
-rw-r--r--src/fios.h6
-rw-r--r--src/fios_gui.cpp32
-rw-r--r--src/fontcache.cpp62
-rw-r--r--src/fontcache.h2
-rw-r--r--src/fontdetection.cpp94
-rw-r--r--src/game/game_config.cpp4
-rw-r--r--src/game/game_core.cpp62
-rw-r--r--src/game/game_info.cpp8
-rw-r--r--src/game/game_info.hpp2
-rw-r--r--src/game/game_instance.cpp4
-rw-r--r--src/game/game_scanner.cpp10
-rw-r--r--src/game/game_scanner.hpp4
-rw-r--r--src/game/game_text.cpp40
-rw-r--r--src/game/game_text.hpp2
-rw-r--r--src/gamelog.cpp74
-rw-r--r--src/genworld.cpp14
-rw-r--r--src/genworld.h4
-rw-r--r--src/genworld_gui.cpp14
-rw-r--r--src/gfx.cpp28
-rw-r--r--src/gfx_func.h8
-rw-r--r--src/gfx_layout.cpp60
-rw-r--r--src/gfx_layout.h2
-rw-r--r--src/gfxinit.cpp26
-rw-r--r--src/goal.cpp4
-rw-r--r--src/goal_base.h2
-rw-r--r--src/goal_gui.cpp6
-rw-r--r--src/graph_gui.cpp2
-rw-r--r--src/ground_vehicle.cpp6
-rw-r--r--src/ground_vehicle.hpp4
-rw-r--r--src/group_cmd.cpp38
-rw-r--r--src/group_gui.cpp14
-rw-r--r--src/heightmap.cpp42
-rw-r--r--src/highscore.cpp4
-rw-r--r--src/highscore_gui.cpp6
-rw-r--r--src/hotkeys.cpp16
-rw-r--r--src/hotkeys.h4
-rw-r--r--src/industry_cmd.cpp68
-rw-r--r--src/industry_gui.cpp50
-rw-r--r--src/ini.cpp14
-rw-r--r--src/ini_load.cpp62
-rw-r--r--src/ini_type.h14
-rw-r--r--src/intro_gui.cpp6
-rw-r--r--src/landscape.cpp52
-rw-r--r--src/landscape.h8
-rw-r--r--src/linkgraph/linkgraph_gui.cpp8
-rw-r--r--src/linkgraph/linkgraphjob.cpp8
-rw-r--r--src/linkgraph/linkgraphjob.h4
-rw-r--r--src/linkgraph/mcf.cpp22
-rw-r--r--src/linkgraph/refresh.cpp22
-rw-r--r--src/main_gui.cpp18
-rw-r--r--src/map.cpp12
-rw-r--r--src/misc/binaryheap.hpp2
-rw-r--r--src/misc/blob.hpp12
-rw-r--r--src/misc/countedptr.hpp32
-rw-r--r--src/misc/dbg_helpers.h4
-rw-r--r--src/misc/fixedsizearray.hpp2
-rw-r--r--src/misc/getoptdata.cpp14
-rw-r--r--src/misc/getoptdata.h24
-rw-r--r--src/misc/hashtable.hpp38
-rw-r--r--src/misc_cmd.cpp2
-rw-r--r--src/misc_gui.cpp50
-rw-r--r--src/mixer.cpp8
-rw-r--r--src/music.cpp38
-rw-r--r--src/music/allegro_m.cpp16
-rw-r--r--src/music/bemidi.cpp2
-rw-r--r--src/music/cocoa_m.cpp28
-rw-r--r--src/music/dmusic.cpp58
-rw-r--r--src/music/extmidi.cpp12
-rw-r--r--src/music/fluidsynth.cpp14
-rw-r--r--src/music/midifile.cpp14
-rw-r--r--src/music/null_m.h2
-rw-r--r--src/music/os2_m.cpp4
-rw-r--r--src/music/qtmidi.cpp18
-rw-r--r--src/music/win32_m.cpp2
-rw-r--r--src/network/core/address.cpp24
-rw-r--r--src/network/core/address.h2
-rw-r--r--src/network/core/host.cpp8
-rw-r--r--src/network/core/packet.cpp14
-rw-r--r--src/network/core/tcp.cpp38
-rw-r--r--src/network/core/tcp.h2
-rw-r--r--src/network/core/tcp_admin.cpp2
-rw-r--r--src/network/core/tcp_connect.cpp2
-rw-r--r--src/network/core/tcp_content.cpp14
-rw-r--r--src/network/core/tcp_game.cpp4
-rw-r--r--src/network/core/tcp_game.h6
-rw-r--r--src/network/core/tcp_http.cpp30
-rw-r--r--src/network/core/tcp_http.h10
-rw-r--r--src/network/core/tcp_listen.h2
-rw-r--r--src/network/core/udp.cpp8
-rw-r--r--src/network/core/udp.h2
-rw-r--r--src/network/network.cpp46
-rw-r--r--src/network/network_admin.cpp18
-rw-r--r--src/network/network_chat_gui.cpp12
-rw-r--r--src/network/network_client.cpp60
-rw-r--r--src/network/network_command.cpp38
-rw-r--r--src/network/network_content.cpp64
-rw-r--r--src/network/network_content.h2
-rw-r--r--src/network/network_content_gui.cpp34
-rw-r--r--src/network/network_func.h2
-rw-r--r--src/network/network_gamelist.cpp36
-rw-r--r--src/network/network_gui.cpp80
-rw-r--r--src/network/network_internal.h4
-rw-r--r--src/network/network_server.cpp112
-rw-r--r--src/network/network_udp.cpp36
-rw-r--r--src/newgrf.cpp396
-rw-r--r--src/newgrf_airport.cpp26
-rw-r--r--src/newgrf_airporttiles.cpp14
-rw-r--r--src/newgrf_airporttiles.h6
-rw-r--r--src/newgrf_animation_base.h2
-rw-r--r--src/newgrf_canal.cpp4
-rw-r--r--src/newgrf_cargo.cpp4
-rw-r--r--src/newgrf_class_func.h12
-rw-r--r--src/newgrf_commons.cpp34
-rw-r--r--src/newgrf_commons.h6
-rw-r--r--src/newgrf_config.cpp112
-rw-r--r--src/newgrf_config.h8
-rw-r--r--src/newgrf_debug_gui.cpp46
-rw-r--r--src/newgrf_engine.cpp98
-rw-r--r--src/newgrf_engine.h6
-rw-r--r--src/newgrf_generic.cpp10
-rw-r--r--src/newgrf_gui.cpp224
-rw-r--r--src/newgrf_house.cpp20
-rw-r--r--src/newgrf_industries.cpp32
-rw-r--r--src/newgrf_industries.h4
-rw-r--r--src/newgrf_industrytiles.cpp20
-rw-r--r--src/newgrf_object.cpp34
-rw-r--r--src/newgrf_object.h2
-rw-r--r--src/newgrf_railtype.cpp24
-rw-r--r--src/newgrf_railtype.h2
-rw-r--r--src/newgrf_sound.cpp6
-rw-r--r--src/newgrf_spritegroup.cpp18
-rw-r--r--src/newgrf_spritegroup.h6
-rw-r--r--src/newgrf_station.cpp98
-rw-r--r--src/newgrf_station.h2
-rw-r--r--src/newgrf_storage.h10
-rw-r--r--src/newgrf_text.cpp50
-rw-r--r--src/newgrf_text.h4
-rw-r--r--src/newgrf_town.cpp6
-rw-r--r--src/newgrf_townname.cpp30
-rw-r--r--src/news_func.h4
-rw-r--r--src/news_gui.cpp104
-rw-r--r--src/news_type.h2
-rw-r--r--src/object.h2
-rw-r--r--src/object_cmd.cpp24
-rw-r--r--src/object_gui.cpp20
-rw-r--r--src/openttd.cpp136
-rw-r--r--src/order_backup.cpp18
-rw-r--r--src/order_base.h10
-rw-r--r--src/order_cmd.cpp156
-rw-r--r--src/order_gui.cpp40
-rw-r--r--src/os/macosx/crashlog_osx.cpp16
-rw-r--r--src/os/macosx/splash.cpp16
-rw-r--r--src/os/macosx/string_osx.cpp34
-rw-r--r--src/os/os2/os2.cpp8
-rw-r--r--src/os/unix/crashlog_unix.cpp2
-rw-r--r--src/os/unix/unix.cpp14
-rw-r--r--src/os/windows/crashlog_win.cpp42
-rw-r--r--src/os/windows/string_uniscribe.cpp46
-rw-r--r--src/os/windows/win32.cpp82
-rw-r--r--src/osk_gui.cpp10
-rw-r--r--src/pathfinder/follow_track.hpp18
-rw-r--r--src/pathfinder/npf/aystar.cpp18
-rw-r--r--src/pathfinder/npf/npf.cpp32
-rw-r--r--src/pathfinder/npf/queue.cpp62
-rw-r--r--src/pathfinder/pf_performance_timer.hpp6
-rw-r--r--src/pathfinder/yapf/nodelist.hpp20
-rw-r--r--src/pathfinder/yapf/yapf_base.hpp28
-rw-r--r--src/pathfinder/yapf/yapf_common.hpp6
-rw-r--r--src/pathfinder/yapf/yapf_costcache.hpp2
-rw-r--r--src/pathfinder/yapf/yapf_costrail.hpp8
-rw-r--r--src/pathfinder/yapf/yapf_node.hpp2
-rw-r--r--src/pathfinder/yapf/yapf_node_rail.hpp12
-rw-r--r--src/pathfinder/yapf/yapf_rail.cpp36
-rw-r--r--src/pathfinder/yapf/yapf_road.cpp10
-rw-r--r--src/pathfinder/yapf/yapf_ship.cpp12
-rw-r--r--src/pbs.cpp36
-rw-r--r--src/pbs.h2
-rw-r--r--src/querystring_gui.h6
-rw-r--r--src/rail.h4
-rw-r--r--src/rail_cmd.cpp62
-rw-r--r--src/rail_gui.cpp60
-rw-r--r--src/road.cpp2
-rw-r--r--src/road_cmd.cpp38
-rw-r--r--src/road_gui.cpp16
-rw-r--r--src/roadstop.cpp40
-rw-r--r--src/roadveh.h2
-rw-r--r--src/roadveh_cmd.cpp64
-rw-r--r--src/roadveh_gui.cpp6
-rw-r--r--src/safeguards.h2
-rw-r--r--src/saveload/afterload.cpp80
-rw-r--r--src/saveload/ai_sl.cpp10
-rw-r--r--src/saveload/airport_sl.cpp4
-rw-r--r--src/saveload/animated_tile_sl.cpp2
-rw-r--r--src/saveload/autoreplace_sl.cpp2
-rw-r--r--src/saveload/cargomonitor_sl.cpp4
-rw-r--r--src/saveload/cargopacket_sl.cpp2
-rw-r--r--src/saveload/cheat_sl.cpp2
-rw-r--r--src/saveload/company_sl.cpp32
-rw-r--r--src/saveload/depot_sl.cpp2
-rw-r--r--src/saveload/economy_sl.cpp16
-rw-r--r--src/saveload/engine_sl.cpp10
-rw-r--r--src/saveload/game_sl.cpp32
-rw-r--r--src/saveload/gamelog_sl.cpp8
-rw-r--r--src/saveload/goal_sl.cpp2
-rw-r--r--src/saveload/group_sl.cpp2
-rw-r--r--src/saveload/industry_sl.cpp10
-rw-r--r--src/saveload/labelmaps_sl.cpp2
-rw-r--r--src/saveload/linkgraph_sl.cpp8
-rw-r--r--src/saveload/map_sl.cpp22
-rw-r--r--src/saveload/misc_sl.cpp6
-rw-r--r--src/saveload/newgrf_sl.cpp6
-rw-r--r--src/saveload/object_sl.cpp4
-rw-r--r--src/saveload/oldloader.cpp20
-rw-r--r--src/saveload/oldloader.h14
-rw-r--r--src/saveload/oldloader_sl.cpp32
-rw-r--r--src/saveload/order_sl.cpp8
-rw-r--r--src/saveload/saveload.cpp122
-rw-r--r--src/saveload/saveload.h16
-rw-r--r--src/saveload/saveload_filter.h2
-rw-r--r--src/saveload/signs_sl.cpp2
-rw-r--r--src/saveload/station_sl.cpp20
-rw-r--r--src/saveload/storage_sl.cpp2
-rw-r--r--src/saveload/story_sl.cpp4
-rw-r--r--src/saveload/strings_sl.cpp8
-rw-r--r--src/saveload/subsidy_sl.cpp2
-rw-r--r--src/saveload/town_sl.cpp4
-rw-r--r--src/saveload/vehicle_sl.cpp62
-rw-r--r--src/saveload/waypoint_sl.cpp14
-rw-r--r--src/screenshot.cpp24
-rw-r--r--src/script/api/script_basestation.cpp6
-rw-r--r--src/script/api/script_basestation.hpp2
-rw-r--r--src/script/api/script_bridge.cpp8
-rw-r--r--src/script/api/script_cargo.cpp2
-rw-r--r--src/script/api/script_client.cpp14
-rw-r--r--src/script/api/script_company.cpp10
-rw-r--r--src/script/api/script_company.hpp4
-rw-r--r--src/script/api/script_controller.cpp4
-rw-r--r--src/script/api/script_engine.cpp6
-rw-r--r--src/script/api/script_error.hpp2
-rw-r--r--src/script/api/script_event.cpp10
-rw-r--r--src/script/api/script_event_types.cpp24
-rw-r--r--src/script/api/script_gamesettings.cpp2
-rw-r--r--src/script/api/script_goal.cpp18
-rw-r--r--src/script/api/script_goal.hpp10
-rw-r--r--src/script/api/script_group.cpp8
-rw-r--r--src/script/api/script_group.hpp2
-rw-r--r--src/script/api/script_industry.cpp2
-rw-r--r--src/script/api/script_industrytype.cpp6
-rw-r--r--src/script/api/script_list.cpp12
-rw-r--r--src/script/api/script_list.hpp4
-rw-r--r--src/script/api/script_log.cpp4
-rw-r--r--src/script/api/script_marine.cpp6
-rw-r--r--src/script/api/script_news.cpp2
-rw-r--r--src/script/api/script_news.hpp2
-rw-r--r--src/script/api/script_object.cpp12
-rw-r--r--src/script/api/script_object.hpp2
-rw-r--r--src/script/api/script_order.cpp26
-rw-r--r--src/script/api/script_rail.cpp12
-rw-r--r--src/script/api/script_road.cpp8
-rw-r--r--src/script/api/script_sign.cpp8
-rw-r--r--src/script/api/script_sign.hpp4
-rw-r--r--src/script/api/script_station.cpp6
-rw-r--r--src/script/api/script_stationlist.cpp12
-rw-r--r--src/script/api/script_story_page.cpp14
-rw-r--r--src/script/api/script_story_page.hpp4
-rw-r--r--src/script/api/script_text.cpp20
-rw-r--r--src/script/api/script_text.hpp4
-rw-r--r--src/script/api/script_tile.cpp20
-rw-r--r--src/script/api/script_town.cpp14
-rw-r--r--src/script/api/script_town.hpp4
-rw-r--r--src/script/api/script_tunnel.cpp4
-rw-r--r--src/script/api/script_vehicle.cpp24
-rw-r--r--src/script/api/script_vehicle.hpp2
-rw-r--r--src/script/api/script_vehiclelist.cpp2
-rw-r--r--src/script/api/script_waypoint.cpp2
-rw-r--r--src/script/api/script_waypointlist.cpp2
-rw-r--r--src/script/api/script_window.cpp6
-rw-r--r--src/script/script_config.cpp38
-rw-r--r--src/script/script_config.hpp8
-rw-r--r--src/script/script_info.cpp18
-rw-r--r--src/script/script_info.hpp24
-rw-r--r--src/script/script_info_dummy.cpp4
-rw-r--r--src/script/script_instance.cpp90
-rw-r--r--src/script/script_instance.hpp2
-rw-r--r--src/script/script_scanner.cpp24
-rw-r--r--src/script/script_scanner.hpp2
-rw-r--r--src/script/script_storage.hpp8
-rw-r--r--src/script/squirrel.cpp30
-rw-r--r--src/script/squirrel.hpp6
-rw-r--r--src/script/squirrel_class.hpp10
-rw-r--r--src/script/squirrel_helper.hpp26
-rw-r--r--src/script/squirrel_std.cpp4
-rw-r--r--src/settings.cpp156
-rw-r--r--src/settings_gui.cpp104
-rw-r--r--src/settingsgen/settingsgen.cpp64
-rw-r--r--src/ship_cmd.cpp14
-rw-r--r--src/signal.cpp16
-rw-r--r--src/signs_cmd.cpp2
-rw-r--r--src/signs_gui.cpp22
-rw-r--r--src/smallmap_gui.cpp28
-rw-r--r--src/sortlist_type.h8
-rw-r--r--src/sound.cpp20
-rw-r--r--src/sound/allegro_s.cpp16
-rw-r--r--src/sound/cocoa_s.cpp16
-rw-r--r--src/sound/null_s.h2
-rw-r--r--src/sound/sdl_s.cpp2
-rw-r--r--src/sound/win32_s.cpp12
-rw-r--r--src/sound/xaudio2_s.cpp8
-rw-r--r--src/sprite.cpp2
-rw-r--r--src/spritecache.cpp34
-rw-r--r--src/spritecache.h2
-rw-r--r--src/station.cpp14
-rw-r--r--src/station_cmd.cpp202
-rw-r--r--src/station_func.h2
-rw-r--r--src/station_gui.cpp62
-rw-r--r--src/statusbar_gui.cpp8
-rw-r--r--src/story.cpp4
-rw-r--r--src/story_base.h4
-rw-r--r--src/story_gui.cpp36
-rw-r--r--src/strgen/strgen.cpp34
-rw-r--r--src/strgen/strgen.h2
-rw-r--r--src/strgen/strgen_base.cpp110
-rw-r--r--src/string.cpp30
-rw-r--r--src/string_func.h6
-rw-r--r--src/stringfilter.cpp16
-rw-r--r--src/stringfilter_type.h4
-rw-r--r--src/strings.cpp134
-rw-r--r--src/strings_func.h22
-rw-r--r--src/subsidy.cpp4
-rw-r--r--src/subsidy_base.h2
-rw-r--r--src/table/airport_defaults.h6
-rw-r--r--src/table/bridge_land.h2
-rw-r--r--src/table/build_industry.h60
-rw-r--r--src/table/cargo_const.h2
-rw-r--r--src/table/newgrf_debug_data.h76
-rw-r--r--src/table/railtypes.h16
-rw-r--r--src/table/roadveh_movement.h66
-rw-r--r--src/table/station_land.h2
-rw-r--r--src/tar_type.h2
-rw-r--r--src/terraform_cmd.cpp8
-rw-r--r--src/terraform_gui.cpp16
-rw-r--r--src/terraform_gui.h2
-rw-r--r--src/textbuf.cpp12
-rw-r--r--src/textbuf_type.h2
-rw-r--r--src/textfile_gui.cpp28
-rw-r--r--src/tgp.cpp14
-rw-r--r--src/thread.h4
-rw-r--r--src/tile_cmd.h12
-rw-r--r--src/tile_map.cpp12
-rw-r--r--src/tile_map.h8
-rw-r--r--src/tilematrix_type.hpp2
-rw-r--r--src/timetable_cmd.cpp20
-rw-r--r--src/timetable_gui.cpp28
-rw-r--r--src/toolbar_gui.cpp62
-rw-r--r--src/town.h6
-rw-r--r--src/town_cmd.cpp88
-rw-r--r--src/town_gui.cpp24
-rw-r--r--src/townname.cpp10
-rw-r--r--src/townname_func.h4
-rw-r--r--src/train.h8
-rw-r--r--src/train_cmd.cpp262
-rw-r--r--src/train_gui.cpp28
-rw-r--r--src/tree_cmd.cpp22
-rw-r--r--src/tunnelbridge_cmd.cpp58
-rw-r--r--src/vehicle.cpp220
-rw-r--r--src/vehicle_base.h52
-rw-r--r--src/vehicle_cmd.cpp58
-rw-r--r--src/vehicle_func.h2
-rw-r--r--src/vehicle_gui.cpp88
-rw-r--r--src/vehiclelist.cpp12
-rw-r--r--src/video/allegro_v.cpp14
-rw-r--r--src/video/dedicated_v.cpp24
-rw-r--r--src/video/null_v.cpp4
-rw-r--r--src/video/sdl_v.cpp62
-rw-r--r--src/video/win32_v.cpp78
-rw-r--r--src/viewport.cpp74
-rw-r--r--src/viewport_func.h8
-rw-r--r--src/viewport_gui.cpp4
-rw-r--r--src/void_cmd.cpp10
-rw-r--r--src/water_cmd.cpp24
-rw-r--r--src/waypoint_cmd.cpp28
-rw-r--r--src/waypoint_gui.cpp6
-rw-r--r--src/widget.cpp264
-rw-r--r--src/widget_type.h4
-rw-r--r--src/widgets/dropdown.cpp8
-rw-r--r--src/window.cpp292
-rw-r--r--src/window_gui.h36
463 files changed, 5674 insertions, 5674 deletions
diff --git a/src/ai/ai_config.cpp b/src/ai/ai_config.cpp
index a78281478..93db57158 100644
--- a/src/ai/ai_config.cpp
+++ b/src/ai/ai_config.cpp
@@ -31,7 +31,7 @@ ScriptConfigItem _start_date_config = {
AI::START_NEXT_DEVIATION,
30,
SCRIPTCONFIG_NONE,
- NULL,
+ nullptr,
false
};
@@ -52,7 +52,7 @@ AIConfig::AIConfig(const AIConfig *config) : ScriptConfig(config)
} else {
config = &_settings_game.ai_config[company];
}
- if (*config == NULL) *config = new AIConfig();
+ if (*config == nullptr) *config = new AIConfig();
return *config;
}
@@ -69,7 +69,7 @@ ScriptInfo *AIConfig::FindInfo(const char *name, int version, bool force_exact_m
bool AIConfig::ResetInfo(bool force_exact_match)
{
this->info = (ScriptInfo *)AI::FindInfo(this->name, force_exact_match ? this->version : -1, force_exact_match);
- return this->info != NULL;
+ return this->info != nullptr;
}
void AIConfig::PushExtraConfigList()
@@ -90,7 +90,7 @@ void AIConfig::ClearConfigList()
int AIConfig::GetSetting(const char *name) const
{
- if (this->info == NULL) {
+ if (this->info == nullptr) {
SettingValueList::const_iterator it = this->settings.find(name);
if (it == this->settings.end()) {
assert(strcmp("start_date", name) == 0);
@@ -111,7 +111,7 @@ int AIConfig::GetSetting(const char *name) const
void AIConfig::SetSetting(const char *name, int value)
{
- if (this->info == NULL) {
+ if (this->info == nullptr) {
if (strcmp("start_date", name) != 0) return;
value = Clamp(value, AI::START_NEXT_MIN, AI::START_NEXT_MAX);
diff --git a/src/ai/ai_core.cpp b/src/ai/ai_core.cpp
index ff2fc286a..cc2eb42c8 100644
--- a/src/ai/ai_core.cpp
+++ b/src/ai/ai_core.cpp
@@ -26,8 +26,8 @@
#include "../safeguards.h"
/* static */ uint AI::frame_counter = 0;
-/* static */ AIScannerInfo *AI::scanner_info = NULL;
-/* static */ AIScannerLibrary *AI::scanner_library = NULL;
+/* static */ AIScannerInfo *AI::scanner_info = nullptr;
+/* static */ AIScannerLibrary *AI::scanner_library = nullptr;
/* static */ bool AI::CanStartNew()
{
@@ -44,9 +44,9 @@
AIConfig *config = AIConfig::GetConfig(company, AIConfig::SSS_FORCE_GAME);
AIInfo *info = config->GetInfo();
- if (info == NULL || (rerandomise_ai && config->IsRandom())) {
+ if (info == nullptr || (rerandomise_ai && config->IsRandom())) {
info = AI::scanner_info->SelectRandomAI();
- assert(info != NULL);
+ assert(info != nullptr);
/* Load default data and store the name in the settings */
config->Change(info->GetName(), -1, false, true);
}
@@ -56,7 +56,7 @@
Company *c = Company::Get(company);
c->ai_info = info;
- assert(c->ai_instance == NULL);
+ assert(c->ai_instance == nullptr);
c->ai_instance = new AIInstance();
c->ai_instance->Initialize(info);
@@ -111,8 +111,8 @@
Company *c = Company::Get(company);
delete c->ai_instance;
- c->ai_instance = NULL;
- c->ai_info = NULL;
+ c->ai_instance = nullptr;
+ c->ai_info = nullptr;
cur_company.Restore();
@@ -164,10 +164,10 @@
/* static */ void AI::Initialize()
{
- if (AI::scanner_info != NULL) AI::Uninitialize(true);
+ if (AI::scanner_info != nullptr) AI::Uninitialize(true);
AI::frame_counter = 0;
- if (AI::scanner_info == NULL) {
+ if (AI::scanner_info == nullptr) {
TarScanner::DoScan(TarScanner::AI);
AI::scanner_info = new AIScannerInfo();
AI::scanner_info->Initialize();
@@ -187,17 +187,17 @@
} else {
delete AI::scanner_info;
delete AI::scanner_library;
- AI::scanner_info = NULL;
- AI::scanner_library = NULL;
+ AI::scanner_info = nullptr;
+ AI::scanner_library = nullptr;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
- if (_settings_game.ai_config[c] != NULL) {
+ if (_settings_game.ai_config[c] != nullptr) {
delete _settings_game.ai_config[c];
- _settings_game.ai_config[c] = NULL;
+ _settings_game.ai_config[c] = nullptr;
}
- if (_settings_newgame.ai_config[c] != NULL) {
+ if (_settings_newgame.ai_config[c] != nullptr) {
delete _settings_newgame.ai_config[c];
- _settings_newgame.ai_config[c] = NULL;
+ _settings_newgame.ai_config[c] = nullptr;
}
}
}
@@ -209,10 +209,10 @@
* the AIConfig. If not, remove the AI from the list (which will assign
* a random new AI on reload). */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
- if (_settings_game.ai_config[c] != NULL && _settings_game.ai_config[c]->HasScript()) {
+ if (_settings_game.ai_config[c] != nullptr && _settings_game.ai_config[c]->HasScript()) {
if (!_settings_game.ai_config[c]->ResetInfo(true)) {
DEBUG(script, 0, "After a reload, the AI by the name '%s' was no longer found, and removed from the list.", _settings_game.ai_config[c]->GetName());
- _settings_game.ai_config[c]->Change(NULL);
+ _settings_game.ai_config[c]->Change(nullptr);
if (Company::IsValidAiID(c)) {
/* The code belonging to an already running AI was deleted. We can only do
* one thing here to keep everything sane and that is kill the AI. After
@@ -226,10 +226,10 @@
Company::Get(c)->ai_info = _settings_game.ai_config[c]->GetInfo();
}
}
- if (_settings_newgame.ai_config[c] != NULL && _settings_newgame.ai_config[c]->HasScript()) {
+ if (_settings_newgame.ai_config[c] != nullptr && _settings_newgame.ai_config[c]->HasScript()) {
if (!_settings_newgame.ai_config[c]->ResetInfo(false)) {
DEBUG(script, 0, "After a reload, the AI by the name '%s' was no longer found, and removed from the list.", _settings_newgame.ai_config[c]->GetName());
- _settings_newgame.ai_config[c]->Change(NULL);
+ _settings_newgame.ai_config[c]->Change(nullptr);
}
}
}
@@ -283,7 +283,7 @@
{
if (!_networking || _network_server) {
Company *c = Company::GetIfValid(company);
- assert(c != NULL && c->ai_instance != NULL);
+ assert(c != nullptr && c->ai_instance != nullptr);
Backup<CompanyByte> cur_company(_current_company, company, FILE_LINE);
c->ai_instance->Save();
@@ -297,7 +297,7 @@
{
if (!_networking || _network_server) {
Company *c = Company::GetIfValid(company);
- assert(c != NULL && c->ai_instance != NULL);
+ assert(c != nullptr && c->ai_instance != nullptr);
Backup<CompanyByte> cur_company(_current_company, company, FILE_LINE);
c->ai_instance->Load(version);
diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp
index eaf2a9d83..4932c0f61 100644
--- a/src/ai/ai_gui.cpp
+++ b/src/ai/ai_gui.cpp
@@ -139,13 +139,13 @@ struct AIListWindow : public Window {
break;
}
case WID_AIL_INFO_BG: {
- AIInfo *selected_info = NULL;
+ AIInfo *selected_info = nullptr;
ScriptInfoList::const_iterator it = this->info_list->begin();
- for (int i = 1; selected_info == NULL && it != this->info_list->end(); i++, it++) {
+ for (int i = 1; selected_info == nullptr && it != this->info_list->end(); i++, it++) {
if (this->selected == i - 1) selected_info = static_cast<AIInfo *>((*it).second);
}
/* Some info about the currently selected AI. */
- if (selected_info != NULL) {
+ if (selected_info != nullptr) {
int y = r.top + WD_FRAMERECT_TOP;
SetDParamStr(0, selected_info->GetAuthor());
DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_AUTHOR);
@@ -153,7 +153,7 @@ struct AIListWindow : public Window {
SetDParam(0, selected_info->GetVersion());
DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_VERSION);
y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
- if (selected_info->GetURL() != NULL) {
+ if (selected_info->GetURL() != nullptr) {
SetDParamStr(0, selected_info->GetURL());
DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, y, STR_AI_LIST_URL);
y += FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL;
@@ -172,7 +172,7 @@ struct AIListWindow : public Window {
void ChangeAI()
{
if (this->selected == -1) {
- GetConfig(slot)->Change(NULL);
+ GetConfig(slot)->Change(nullptr);
} else {
ScriptInfoList::const_iterator it = this->info_list->begin();
for (int i = 0; i < this->selected; i++) it++;
@@ -407,7 +407,7 @@ struct AISettingsWindow : public Window {
} else {
DrawArrowButtons(buttons_left, y + button_y_offset, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + (this->clicked_increase != rtl) : 0, editable && current_value > config_item.min_value, editable && current_value < config_item.max_value);
}
- if (config_item.labels != NULL && config_item.labels->Contains(current_value)) {
+ if (config_item.labels != nullptr && config_item.labels->Contains(current_value)) {
SetDParam(idx++, STR_JUST_RAW_STRING);
SetDParamStr(idx++, config_item.labels->Find(current_value)->second);
} else {
@@ -805,7 +805,7 @@ struct AIConfigWindow : public Window {
*/
static bool IsEditable(CompanyID slot)
{
- if (slot == OWNER_DEITY) return _game_mode != GM_NORMAL || Game::GetInstance() != NULL;
+ if (slot == OWNER_DEITY) return _game_mode != GM_NORMAL || Game::GetInstance() != nullptr;
if (_game_mode != GM_NORMAL) {
return slot > 0 && slot <= GetGameSettings().difficulty.max_no_competitors;
@@ -825,7 +825,7 @@ struct AIConfigWindow : public Window {
case WID_AIC_GAMELIST: {
StringID text = STR_AI_CONFIG_NONE;
- if (GameConfig::GetConfig()->GetInfo() != NULL) {
+ if (GameConfig::GetConfig()->GetInfo() != nullptr) {
SetDParamStr(0, GameConfig::GetConfig()->GetInfo()->GetName());
text = STR_JUST_RAW_STRING;
}
@@ -843,7 +843,7 @@ struct AIConfigWindow : public Window {
if ((_game_mode != GM_NORMAL && i == 0) || (_game_mode == GM_NORMAL && Company::IsValidHumanID(i))) {
text = STR_AI_CONFIG_HUMAN_PLAYER;
- } else if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != NULL) {
+ } else if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != nullptr) {
SetDParamStr(0, AIConfig::GetConfig((CompanyID)i)->GetInfo()->GetName());
text = STR_JUST_RAW_STRING;
} else {
@@ -861,7 +861,7 @@ struct AIConfigWindow : public Window {
void OnClick(Point pt, int widget, int click_count) override
{
if (widget >= WID_AIC_TEXTFILE && widget < WID_AIC_TEXTFILE + TFT_END) {
- if (this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot) == NULL) return;
+ if (this->selected_slot == INVALID_COMPANY || GetConfig(this->selected_slot) == nullptr) return;
ShowScriptTextfileWindow((TextfileType)(widget - WID_AIC_TEXTFILE), this->selected_slot);
return;
@@ -928,7 +928,7 @@ struct AIConfigWindow : public Window {
if (!_network_available) {
ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
} else {
- ShowNetworkContentListWindow(NULL, CONTENT_TYPE_AI, CONTENT_TYPE_GAME);
+ ShowNetworkContentListWindow(nullptr, CONTENT_TYPE_AI, CONTENT_TYPE_GAME);
}
break;
}
@@ -955,7 +955,7 @@ struct AIConfigWindow : public Window {
this->SetWidgetDisabledState(WID_AIC_MOVE_DOWN, this->selected_slot == OWNER_DEITY || this->selected_slot == INVALID_COMPANY || !IsEditable((CompanyID)(this->selected_slot + 1)));
for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
- this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == INVALID_COMPANY || (GetConfig(this->selected_slot)->GetTextfile(tft, this->selected_slot) == NULL));
+ this->SetWidgetDisabledState(WID_AIC_TEXTFILE + tft, this->selected_slot == INVALID_COMPANY || (GetConfig(this->selected_slot)->GetTextfile(tft, this->selected_slot) == nullptr));
}
}
};
@@ -1024,7 +1024,7 @@ struct AIDebugWindow : public Window {
{
if (ai_debug_company == OWNER_DEITY) {
GameInstance *game = Game::GetInstance();
- return game == NULL || game->IsDead();
+ return game == nullptr || game->IsDead();
}
return !Company::IsValidAiID(ai_debug_company) || Company::Get(ai_debug_company)->ai_instance->IsDead();
}
@@ -1038,7 +1038,7 @@ struct AIDebugWindow : public Window {
{
switch (company) {
case INVALID_COMPANY: return false;
- case OWNER_DEITY: return Game::GetInstance() != NULL;
+ case OWNER_DEITY: return Game::GetInstance() != nullptr;
default: return Company::IsValidAiID(company);
}
}
@@ -1063,7 +1063,7 @@ struct AIDebugWindow : public Window {
}
/* If no AI is available, see if there is a game script. */
- if (Game::GetInstance() != NULL) ChangeToAI(OWNER_DEITY);
+ if (Game::GetInstance() != nullptr) ChangeToAI(OWNER_DEITY);
}
/**
@@ -1140,7 +1140,7 @@ struct AIDebugWindow : public Window {
/* Set button colour for Game Script. */
GameInstance *game = Game::GetInstance();
- bool valid = game != NULL;
+ bool valid = game != nullptr;
bool dead = valid && game->IsDead();
bool paused = valid && game->IsPaused();
@@ -1154,7 +1154,7 @@ struct AIDebugWindow : public Window {
ScriptLog::LogData *log = this->GetLogPointer();
- int scroll_count = (log == NULL) ? 0 : log->used;
+ int scroll_count = (log == nullptr) ? 0 : log->used;
if (this->vscroll->GetCount() != scroll_count) {
this->vscroll->SetCount(scroll_count);
@@ -1162,7 +1162,7 @@ struct AIDebugWindow : public Window {
this->SetWidgetDirty(WID_AID_SCROLLBAR);
}
- if (log == NULL) return;
+ if (log == nullptr) return;
/* Detect when the user scrolls the window. Enable autoscroll when the
* bottom-most line becomes visible. */
@@ -1188,7 +1188,7 @@ struct AIDebugWindow : public Window {
case WID_AID_NAME_TEXT:
if (ai_debug_company == OWNER_DEITY) {
const GameInfo *info = Game::GetInfo();
- assert(info != NULL);
+ assert(info != nullptr);
SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
SetDParamStr(1, info->GetName());
SetDParam(2, info->GetVersion());
@@ -1196,7 +1196,7 @@ struct AIDebugWindow : public Window {
SetDParam(0, STR_EMPTY);
} else {
const AIInfo *info = Company::Get(ai_debug_company)->ai_info;
- assert(info != NULL);
+ assert(info != nullptr);
SetDParam(0, STR_AI_DEBUG_NAME_AND_VERSION);
SetDParamStr(1, info->GetName());
SetDParam(2, info->GetVersion());
@@ -1212,12 +1212,12 @@ struct AIDebugWindow : public Window {
switch (widget) {
case WID_AID_LOG_PANEL: {
ScriptLog::LogData *log = this->GetLogPointer();
- if (log == NULL) return;
+ if (log == nullptr) return;
int y = this->top_offset;
for (int i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < log->used; i++) {
int pos = (i + log->pos + 1 - log->used + log->count) % log->count;
- if (log->lines[pos] == NULL) break;
+ if (log->lines[pos] == nullptr) break;
TextColour colour;
switch (log->type[pos]) {
@@ -1357,7 +1357,7 @@ struct AIDebugWindow : public Window {
/* Get the log instance of the active company */
ScriptLog::LogData *log = this->GetLogPointer();
- if (log != NULL) {
+ if (log != nullptr) {
this->break_string_filter.ResetState();
this->break_string_filter.AddLine(log->lines[log->pos]);
if (this->break_string_filter.GetState()) {
@@ -1385,8 +1385,8 @@ struct AIDebugWindow : public Window {
this->SelectValidDebugCompany();
- ScriptLog::LogData *log = ai_debug_company != INVALID_COMPANY ? this->GetLogPointer() : NULL;
- this->vscroll->SetCount((log == NULL) ? 0 : log->used);
+ ScriptLog::LogData *log = ai_debug_company != INVALID_COMPANY ? this->GetLogPointer() : nullptr;
+ this->vscroll->SetCount((log == nullptr) ? 0 : log->used);
/* Update company buttons */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
@@ -1394,7 +1394,7 @@ struct AIDebugWindow : public Window {
this->SetWidgetLoweredState(i + WID_AID_COMPANY_BUTTON_START, ai_debug_company == i);
}
- this->SetWidgetDisabledState(WID_AID_SCRIPT_GAME, Game::GetGameInstance() == NULL);
+ this->SetWidgetDisabledState(WID_AID_SCRIPT_GAME, Game::GetGameInstance() == nullptr);
this->SetWidgetLoweredState(WID_AID_SCRIPT_GAME, ai_debug_company == OWNER_DEITY);
this->SetWidgetLoweredState(WID_AID_BREAK_STR_ON_OFF_BTN, this->break_check_enabled);
@@ -1437,7 +1437,7 @@ static EventState AIDebugGlobalHotkeys(int hotkey)
{
if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
Window *w = ShowAIDebugWindow(INVALID_COMPANY);
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -1530,14 +1530,14 @@ Window *ShowAIDebugWindow(CompanyID show_company)
{
if (!_networking || _network_server) {
AIDebugWindow *w = (AIDebugWindow *)BringWindowToFrontById(WC_AI_DEBUG, 0);
- if (w == NULL) w = new AIDebugWindow(&_ai_debug_desc, 0);
+ if (w == nullptr) w = new AIDebugWindow(&_ai_debug_desc, 0);
if (show_company != INVALID_COMPANY) w->ChangeToAI(show_company);
return w;
} else {
ShowErrorMessage(STR_ERROR_AI_DEBUG_SERVER_ONLY, INVALID_STRING_ID, WL_INFO);
}
- return NULL;
+ return nullptr;
}
/**
@@ -1563,7 +1563,7 @@ void ShowAIDebugWindowIfAIError()
}
GameInstance *g = Game::GetGameInstance();
- if (g != NULL && g->IsDead()) {
+ if (g != nullptr && g->IsDead()) {
ShowAIDebugWindow(OWNER_DEITY);
}
}
diff --git a/src/ai/ai_info.cpp b/src/ai/ai_info.cpp
index 62ddb2344..af7ae5729 100644
--- a/src/ai/ai_info.cpp
+++ b/src/ai/ai_info.cpp
@@ -65,8 +65,8 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
/* static */ SQInteger AIInfo::Constructor(HSQUIRRELVM vm)
{
/* Get the AIInfo */
- SQUserPointer instance = NULL;
- if (SQ_FAILED(sq_getinstanceup(vm, 2, &instance, 0)) || instance == NULL) return sq_throwerror(vm, "Pass an instance of a child class of AIInfo to RegisterAI");
+ SQUserPointer instance = nullptr;
+ if (SQ_FAILED(sq_getinstanceup(vm, 2, &instance, 0)) || instance == nullptr) return sq_throwerror(vm, "Pass an instance of a child class of AIInfo to RegisterAI");
AIInfo *info = (AIInfo *)instance;
SQInteger res = ScriptInfo::Constructor(vm, info);
@@ -100,7 +100,7 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
}
/* Remove the link to the real instance, else it might get deleted by RegisterAI() */
- sq_setinstanceup(vm, 2, NULL);
+ sq_setinstanceup(vm, 2, nullptr);
/* Register the AI to the base system */
info->GetScanner()->RegisterScript(info);
return 0;
@@ -112,7 +112,7 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
SQUserPointer instance;
sq_getinstanceup(vm, 2, &instance, 0);
AIInfo *info = (AIInfo *)instance;
- info->api_version = NULL;
+ info->api_version = nullptr;
SQInteger res = ScriptInfo::Constructor(vm, info);
if (res != 0) return res;
@@ -122,7 +122,7 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
info->api_version = stredup(buf);
/* Remove the link to the real instance, else it might get deleted by RegisterAI() */
- sq_setinstanceup(vm, 2, NULL);
+ sq_setinstanceup(vm, 2, nullptr);
/* Register the AI to the base system */
static_cast<AIScannerInfo *>(info->GetScanner())->SetDummyAI(info);
return 0;
@@ -131,7 +131,7 @@ template <> const char *GetClassName<AIInfo, ST_AI>() { return "AIInfo"; }
AIInfo::AIInfo() :
min_loadable_version(0),
use_as_random(false),
- api_version(NULL)
+ api_version(nullptr)
{
}
diff --git a/src/ai/ai_info.hpp b/src/ai/ai_info.hpp
index 51cfb7d8a..ddf1edc6c 100644
--- a/src/ai/ai_info.hpp
+++ b/src/ai/ai_info.hpp
@@ -59,7 +59,7 @@ private:
/** All static information from an AI library like name, version, etc. */
class AILibrary : public ScriptInfo {
public:
- AILibrary() : ScriptInfo(), category(NULL) {};
+ AILibrary() : ScriptInfo(), category(nullptr) {};
~AILibrary();
/**
diff --git a/src/ai/ai_instance.cpp b/src/ai/ai_instance.cpp
index c03e74599..f5f5904c0 100644
--- a/src/ai/ai_instance.cpp
+++ b/src/ai/ai_instance.cpp
@@ -216,10 +216,10 @@ void AIInstance::Died()
ShowAIDebugWindow(_current_company);
const AIInfo *info = AIConfig::GetConfig(_current_company, AIConfig::SSS_FORCE_GAME)->GetInfo();
- if (info != NULL) {
+ if (info != nullptr) {
ShowErrorMessage(STR_ERROR_AI_PLEASE_REPORT_CRASH, INVALID_STRING_ID, WL_WARNING);
- if (info->GetURL() != NULL) {
+ if (info->GetURL() != nullptr) {
ScriptLog::Info("Please report the error to the following URL:");
ScriptLog::Info(info->GetURL());
}
@@ -258,7 +258,7 @@ void CcAI(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
* when the company does not exist anymore.
*/
const Company *c = Company::GetIfValid(_current_company);
- if (c == NULL || c->ai_instance == NULL) return;
+ if (c == nullptr || c->ai_instance == nullptr) return;
c->ai_instance->DoCommandCallback(result, tile, p1, p2);
c->ai_instance->Continue();
diff --git a/src/ai/ai_scanner.cpp b/src/ai/ai_scanner.cpp
index 5f16de3f9..1d0fed188 100644
--- a/src/ai/ai_scanner.cpp
+++ b/src/ai/ai_scanner.cpp
@@ -23,7 +23,7 @@
AIScannerInfo::AIScannerInfo() :
ScriptScanner(),
- info_dummy(NULL)
+ info_dummy(nullptr)
{
}
@@ -94,14 +94,14 @@ AIInfo *AIScannerInfo::SelectRandomAI() const
AIInfo *AIScannerInfo::FindInfo(const char *nameParam, int versionParam, bool force_exact_match)
{
- if (this->info_list.size() == 0) return NULL;
- if (nameParam == NULL) return NULL;
+ if (this->info_list.size() == 0) return nullptr;
+ if (nameParam == nullptr) return nullptr;
char ai_name[1024];
strecpy(ai_name, nameParam, lastof(ai_name));
strtolower(ai_name);
- AIInfo *info = NULL;
+ AIInfo *info = nullptr;
int version = -1;
if (versionParam == -1) {
@@ -110,7 +110,7 @@ AIInfo *AIScannerInfo::FindInfo(const char *nameParam, int versionParam, bool fo
/* If we didn't find a match AI, maybe the user included a version */
char *e = strrchr(ai_name, '.');
- if (e == NULL) return NULL;
+ if (e == nullptr) return nullptr;
*e = '\0';
e++;
versionParam = atoi(e);
@@ -165,7 +165,7 @@ AILibrary *AIScannerLibrary::FindLibrary(const char *library, int version)
/* Check if the library + version exists */
ScriptInfoList::iterator iter = this->info_list.find(library_name);
- if (iter == this->info_list.end()) return NULL;
+ if (iter == this->info_list.end()) return nullptr;
return static_cast<AILibrary *>((*iter).second);
}
diff --git a/src/ai/ai_scanner.hpp b/src/ai/ai_scanner.hpp
index dafc340be..2e0532d00 100644
--- a/src/ai/ai_scanner.hpp
+++ b/src/ai/ai_scanner.hpp
@@ -32,7 +32,7 @@ public:
* @param nameParam The name of the AI.
* @param versionParam The version of the AI, or -1 if you want the latest.
* @param force_exact_match Only match name+version, never latest.
- * @return NULL if no match found, otherwise the AI that matched.
+ * @return nullptr if no match found, otherwise the AI that matched.
*/
class AIInfo *FindInfo(const char *nameParam, int versionParam, bool force_exact_match);
@@ -60,7 +60,7 @@ public:
* Find a library in the pool.
* @param library The library name to find.
* @param version The version the library should have.
- * @return The library if found, NULL otherwise.
+ * @return The library if found, nullptr otherwise.
*/
class AILibrary *FindLibrary(const char *library, int version);
diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp
index 99c86d6e1..409daf789 100644
--- a/src/aircraft_cmd.cpp
+++ b/src/aircraft_cmd.cpp
@@ -143,7 +143,7 @@ static StationID FindNearestHangar(const Aircraft *v)
if (v->acache.cached_max_range_sqr != 0) {
/* Check if our current destination can be reached from the depot airport. */
const Station *cur_dest = GetTargetAirportIfValid(v);
- if (cur_dest != NULL && DistanceSquare(st->airport.tile, cur_dest->airport.tile) > v->acache.cached_max_range_sqr) continue;
+ if (cur_dest != nullptr && DistanceSquare(st->airport.tile, cur_dest->airport.tile) > v->acache.cached_max_range_sqr) continue;
}
if (distance < best || index == INVALID_STATION) {
best = distance;
@@ -295,7 +295,7 @@ CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, const Engine *
v->cargo_type = e->GetDefaultCargoType();
u->cargo_type = CT_MAIL;
- v->name = NULL;
+ v->name = nullptr;
v->last_station_visited = INVALID_STATION;
v->last_loading_station = INVALID_STATION;
@@ -379,7 +379,7 @@ bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination,
{
const Station *st = GetTargetAirportIfValid(this);
/* If the station is not a valid airport or if it has no hangars */
- if (st == NULL || !CanVehicleUseStation(this, st) || !st->airport.HasHangar()) {
+ if (st == nullptr || !CanVehicleUseStation(this, st) || !st->airport.HasHangar()) {
/* the aircraft has to search for a hangar on its own */
StationID station = FindNearestHangar(this);
@@ -388,8 +388,8 @@ bool Aircraft::FindClosestDepot(TileIndex *location, DestinationID *destination,
st = Station::Get(station);
}
- if (location != NULL) *location = st->xy;
- if (destination != NULL) *destination = st->index;
+ if (location != nullptr) *location = st->xy;
+ if (destination != nullptr) *destination = st->index;
return true;
}
@@ -408,7 +408,7 @@ static void CheckIfAircraftNeedsService(Aircraft *v)
const Station *st = Station::Get(v->current_order.GetDestination());
- assert(st != NULL);
+ assert(st != nullptr);
/* only goto depot if the target airport has a depot */
if (st->airport.HasHangar() && CanVehicleUseStation(v, st)) {
@@ -531,7 +531,7 @@ void SetAircraftPosition(Aircraft *v, int x, int y, int z)
u->UpdatePositionAndViewport();
u = u->Next();
- if (u != NULL) {
+ if (u != nullptr) {
u->x_pos = x;
u->y_pos = y;
u->z_pos = z + ROTOR_Z_OFFSET;
@@ -552,7 +552,7 @@ void HandleAircraftEnterHangar(Aircraft *v)
Aircraft *u = v->Next();
u->vehstatus |= VS_HIDDEN;
u = u->Next();
- if (u != NULL) {
+ if (u != nullptr) {
u->vehstatus |= VS_HIDDEN;
u->cur_speed = 0;
}
@@ -725,8 +725,8 @@ void GetAircraftFlightLevelBounds(const Vehicle *v, int *min_level, int *max_lev
/* Make faster planes fly higher so that they can overtake slower ones */
base_altitude += min(20 * (v->vcache.cached_max_speed / 200) - 90, 0);
- if (min_level != NULL) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
- if (max_level != NULL) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
+ if (min_level != nullptr) *min_level = base_altitude + AIRCRAFT_MIN_FLYING_ALTITUDE;
+ if (max_level != nullptr) *max_level = base_altitude + AIRCRAFT_MAX_FLYING_ALTITUDE;
}
/**
@@ -801,8 +801,8 @@ template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
*/
static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
{
- assert(v != NULL);
- assert(apc != NULL);
+ assert(v != nullptr);
+ assert(apc != nullptr);
/* In the case the station doesn't exit anymore, set target tile 0.
* It doesn't hurt much, aircraft will go to next order, nearest hangar
@@ -810,7 +810,7 @@ static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc,
TileIndex tile = 0;
const Station *st = Station::GetIfValid(v->targetairport);
- if (st != NULL) {
+ if (st != nullptr) {
/* Make sure we don't go to INVALID_TILE if the airport has been removed. */
tile = (st->airport.tile != INVALID_TILE) ? st->airport.tile : st->xy;
}
@@ -844,13 +844,13 @@ static bool AircraftController(Aircraft *v)
{
int count;
- /* NULL if station is invalid */
+ /* nullptr if station is invalid */
const Station *st = Station::GetIfValid(v->targetairport);
/* INVALID_TILE if there is no station */
TileIndex tile = INVALID_TILE;
Direction rotation = DIR_N;
uint size_x = 1, size_y = 1;
- if (st != NULL) {
+ if (st != nullptr) {
if (st->airport.tile != INVALID_TILE) {
tile = st->airport.tile;
rotation = st->airport.rotation;
@@ -864,7 +864,7 @@ static bool AircraftController(Aircraft *v)
const AirportFTAClass *afc = tile == INVALID_TILE ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
/* prevent going to INVALID_TILE if airport is deleted. */
- if (st == NULL || st->airport.tile == INVALID_TILE) {
+ if (st == nullptr || st->airport.tile == INVALID_TILE) {
/* Jump into our "holding pattern" state machine if possible */
if (v->pos >= afc->nofelements) {
v->pos = v->previous_pos = AircraftGetEntryPoint(v, afc, DIR_N);
@@ -904,7 +904,7 @@ static bool AircraftController(Aircraft *v)
v->tile = 0;
int z_dest;
- GetAircraftFlightLevelBounds(v, &z_dest, NULL);
+ GetAircraftFlightLevelBounds(v, &z_dest, nullptr);
/* Reached altitude? */
if (v->z_pos >= z_dest) {
@@ -921,7 +921,7 @@ static bool AircraftController(Aircraft *v)
if (amd.flag & AMED_HELI_LOWER) {
SetBit(v->flags, VAF_HELI_DIRECT_DESCENT);
- if (st == NULL) {
+ if (st == nullptr) {
/* FIXME - AircraftController -> if station no longer exists, do not land
* helicopter will circle until sign disappears, then go to next order
* what to do when it is the only order left, right now it just stays in 1 place */
@@ -1127,7 +1127,7 @@ static bool HandleCrashedAircraft(Aircraft *v)
Station *st = GetTargetAirportIfValid(v);
/* make aircraft crash down to the ground */
- if (v->crashed_counter < 500 && st == NULL && ((v->crashed_counter % 3) == 0) ) {
+ if (v->crashed_counter < 500 && st == nullptr && ((v->crashed_counter % 3) == 0) ) {
int z = GetSlopePixelZ(Clamp(v->x_pos, 0, MapMaxX() * TILE_SIZE), Clamp(v->y_pos, 0, MapMaxY() * TILE_SIZE));
v->z_pos -= 1;
if (v->z_pos == z) {
@@ -1158,7 +1158,7 @@ static bool HandleCrashedAircraft(Aircraft *v)
/* clear runway-in on all airports, set by crashing plane
* small airports use AIRPORT_BUSY, city airports use RUNWAY_IN_OUT_block, etc.
* but they all share the same number */
- if (st != NULL) {
+ if (st != nullptr) {
CLRBITS(st->airport.flags, RUNWAY_IN_block);
CLRBITS(st->airport.flags, RUNWAY_IN_OUT_block); // commuter airport
CLRBITS(st->airport.flags, RUNWAY_IN2_block); // intercontinental
@@ -1232,7 +1232,7 @@ void HandleMissingAircraftOrders(Aircraft *v)
* actually stops.
*/
const Station *st = GetTargetAirportIfValid(v);
- if (st == NULL) {
+ if (st == nullptr) {
Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
CommandCost ret = DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_SEND_VEHICLE_TO_DEPOT);
cur_company.Restore();
@@ -1288,17 +1288,17 @@ static void CrashAirplane(Aircraft *v)
v->Next()->cargo.Truncate();
const Station *st = GetTargetAirportIfValid(v);
StringID newsitem;
- if (st == NULL) {
+ if (st == nullptr) {
newsitem = STR_NEWS_PLANE_CRASH_OUT_OF_FUEL;
} else {
SetDParam(1, st->index);
newsitem = STR_NEWS_AIRCRAFT_CRASH;
}
- AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
- Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == NULL ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
+ AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
+ Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, st == nullptr ? ScriptEventVehicleCrashed::CRASH_AIRCRAFT_NO_AIRPORT : ScriptEventVehicleCrashed::CRASH_PLANE_LANDING));
- AddVehicleNewsItem(newsitem, NT_ACCIDENT, v->index, st != NULL ? st->index : INVALID_STATION);
+ AddVehicleNewsItem(newsitem, NT_ACCIDENT, v->index, st != nullptr ? st->index : INVALID_STATION);
ModifyStationRatingAround(v->tile, v->owner, -160, 30);
if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
@@ -1392,8 +1392,8 @@ void AircraftNextAirportPos_and_Order(Aircraft *v)
}
const Station *st = GetTargetAirportIfValid(v);
- const AirportFTAClass *apc = st == NULL ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
- Direction rotation = st == NULL ? DIR_N : st->airport.rotation;
+ const AirportFTAClass *apc = st == nullptr ? GetAirport(AT_DUMMY) : st->airport.GetFTA();
+ Direction rotation = st == nullptr ? DIR_N : st->airport.rotation;
v->pos = v->previous_pos = AircraftGetEntryPoint(v, apc, rotation);
}
@@ -1418,7 +1418,7 @@ void AircraftLeaveHangar(Aircraft *v, Direction exit_dir)
/* Rotor blades */
u = u->Next();
- if (u != NULL) {
+ if (u != nullptr) {
u->vehstatus &= ~VS_HIDDEN;
u->cur_speed = 80;
}
@@ -1605,7 +1605,7 @@ static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
* it is possible to choose from multiple landing runways, so loop until a free one is found */
byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
const AirportFTA *current = apc->layout[v->pos].next;
- while (current != NULL) {
+ while (current != nullptr) {
if (current->heading == landingtype) {
/* save speed before, since if AirportHasBlock is false, it resets them to 0
* we don't want that for plane in air
@@ -1761,7 +1761,7 @@ static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
v->previous_pos = v->pos; // save previous location
/* there is only one choice to move to */
- if (current->next == NULL) {
+ if (current->next == nullptr) {
if (AirportSetBlocks(v, current, apc)) {
v->pos = current->next_position;
UpdateAircraftCache(v);
@@ -1780,7 +1780,7 @@ static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
return false;
}
current = current->next;
- } while (current != NULL);
+ } while (current != nullptr);
DEBUG(misc, 0, "[Ap] cannot move further on Airport! (pos %d state %d) for vehicle %d", v->pos, v->state, v->index);
NOT_REACHED();
@@ -1830,7 +1830,7 @@ static bool AirportSetBlocks(Aircraft *v, const AirportFTA *current_pos, const A
* this means more blocks should be checked/set */
const AirportFTA *current = current_pos;
if (current == reference) current = current->next;
- while (current != NULL) {
+ while (current != nullptr) {
if (current->heading == current_pos->heading && current->block != 0) {
airport_flags |= current->block;
break;
@@ -1938,7 +1938,7 @@ static bool AirportFindFreeTerminal(Aircraft *v, const AirportFTAClass *apc)
const Station *st = Station::Get(v->targetairport);
const AirportFTA *temp = apc->layout[v->pos].next;
- while (temp != NULL) {
+ while (temp != nullptr) {
if (temp->heading == 255) {
if (!(st->airport.flags & temp->block)) {
/* read which group do we want to go to?
@@ -2037,9 +2037,9 @@ static bool AircraftEventHandler(Aircraft *v, int loop)
/* Check the distance to the next destination. This code works because the target
* airport is only updated after take off and not on the ground. */
Station *cur_st = Station::GetIfValid(v->targetairport);
- Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : NULL;
+ Station *next_st = v->current_order.IsType(OT_GOTO_STATION) || v->current_order.IsType(OT_GOTO_DEPOT) ? Station::GetIfValid(v->current_order.GetDestination()) : nullptr;
- if (cur_st != NULL && cur_st->airport.tile != INVALID_TILE && next_st != NULL && next_st->airport.tile != INVALID_TILE) {
+ if (cur_st != nullptr && cur_st->airport.tile != INVALID_TILE && next_st != nullptr && next_st->airport.tile != INVALID_TILE) {
uint dist = DistanceSquare(cur_st->airport.tile, next_st->airport.tile);
AircraftHandleDestTooFar(v, dist > v->acache.cached_max_range_sqr);
}
@@ -2077,16 +2077,16 @@ bool Aircraft::Tick()
* Returns aircraft's target station if v->target_airport
* is a valid station with airport.
* @param v vehicle to get target airport for
- * @return pointer to target station, NULL if invalid
+ * @return pointer to target station, nullptr if invalid
*/
Station *GetTargetAirportIfValid(const Aircraft *v)
{
assert(v->type == VEH_AIRCRAFT);
Station *st = Station::GetIfValid(v->targetairport);
- if (st == NULL) return NULL;
+ if (st == nullptr) return nullptr;
- return st->airport.tile == INVALID_TILE ? NULL : st;
+ return st->airport.tile == INVALID_TILE ? nullptr : st;
}
/**
diff --git a/src/aircraft_gui.cpp b/src/aircraft_gui.cpp
index 6693b1f8a..76121a5dd 100644
--- a/src/aircraft_gui.cpp
+++ b/src/aircraft_gui.cpp
@@ -36,7 +36,7 @@ void DrawAircraftDetails(const Aircraft *v, int left, int right, int y)
int y_offset = (v->Next()->cargo_cap != 0) ? -(FONT_HEIGHT_NORMAL + 1): 0;
Money feeder_share = 0;
- for (const Aircraft *u = v; u != NULL; u = u->Next()) {
+ for (const Aircraft *u = v; u != nullptr; u = u->Next()) {
if (u->IsNormalAircraft()) {
SetDParam(0, u->engine_type);
SetDParam(1, u->build_year);
diff --git a/src/airport.cpp b/src/airport.cpp
index 7985e017a..15e18035f 100644
--- a/src/airport.cpp
+++ b/src/airport.cpp
@@ -46,7 +46,7 @@
* @param delta_z Height of the airport above the land.
*/
#define HELIPORT(name, num_helipads, delta_z) \
- AIRPORT_GENERIC(name, NULL, num_helipads, AirportFTAClass::HELICOPTERS, delta_z)
+ AIRPORT_GENERIC(name, nullptr, num_helipads, AirportFTAClass::HELICOPTERS, delta_z)
AIRPORT(country, 0, true)
AIRPORT(city, 0, false)
@@ -58,7 +58,7 @@ HELIPORT(helidepot, 1, 0)
AIRPORT(intercontinental, 2, false)
HELIPORT(helistation, 3, 0)
HELIPORT(oilrig, 1, 54)
-AIRPORT_GENERIC(dummy, NULL, 0, AirportFTAClass::ALL, 0)
+AIRPORT_GENERIC(dummy, nullptr, 0, AirportFTAClass::ALL, 0)
#undef HELIPORT
#undef AIRPORT
@@ -135,7 +135,7 @@ AirportFTAClass::~AirportFTAClass()
{
for (uint i = 0; i < nofelements; i++) {
AirportFTA *current = layout[i].next;
- while (current != NULL) {
+ while (current != nullptr) {
AirportFTA *next = current->next;
free(current);
current = next;
@@ -195,7 +195,7 @@ static AirportFTA *AirportBuildAutomata(uint nofelements, const AirportFTAbuildu
current = current->next;
internalcounter++;
}
- current->next = NULL;
+ current->next = nullptr;
internalcounter++;
}
return FAutomata;
diff --git a/src/airport_gui.cpp b/src/airport_gui.cpp
index d170b0cbb..8e436f1cb 100644
--- a/src/airport_gui.cpp
+++ b/src/airport_gui.cpp
@@ -161,7 +161,7 @@ static EventState AirportToolbarGlobalHotkeys(int hotkey)
{
if (_game_mode != GM_NORMAL || !CanBuildVehicleInfrastructure(VEH_AIRCRAFT)) return ES_NOT_HANDLED;
Window *w = ShowBuildAirToolbar();
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -198,11 +198,11 @@ static WindowDesc _air_toolbar_desc(
*
* If the terraform toolbar is linked to the toolbar, that window is also opened.
*
- * @return newly opened airport toolbar, or NULL if the toolbar could not be opened.
+ * @return newly opened airport toolbar, or nullptr if the toolbar could not be opened.
*/
Window *ShowBuildAirToolbar()
{
- if (!Company::IsValidID(_local_company)) return NULL;
+ if (!Company::IsValidID(_local_company)) return nullptr;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
return AllocateWindowDescFront<BuildAirToolbarWindow>(&_air_toolbar_desc, TRANSPORT_AIR);
diff --git a/src/articulated_vehicles.cpp b/src/articulated_vehicles.cpp
index 62ab5b096..e7956f539 100644
--- a/src/articulated_vehicles.cpp
+++ b/src/articulated_vehicles.cpp
@@ -31,9 +31,9 @@ static const uint MAX_ARTICULATED_PARTS = 100; ///< Maximum of articulated parts
* @param mirrored Returns whether the part shall be flipped.
* @return engine to add or INVALID_ENGINE
*/
-static EngineID GetNextArticulatedPart(uint index, EngineID front_type, Vehicle *front = NULL, bool *mirrored = NULL)
+static EngineID GetNextArticulatedPart(uint index, EngineID front_type, Vehicle *front = nullptr, bool *mirrored = nullptr)
{
- assert(front == NULL || front->engine_type == front_type);
+ assert(front == nullptr || front->engine_type == front_type);
const Engine *front_engine = Engine::Get(front_type);
@@ -44,12 +44,12 @@ static EngineID GetNextArticulatedPart(uint index, EngineID front_type, Vehicle
/* 8 bits, bit 7 for mirroring */
callback = GB(callback, 0, 8);
if (callback == 0xFF) return INVALID_ENGINE;
- if (mirrored != NULL) *mirrored = HasBit(callback, 7);
+ if (mirrored != nullptr) *mirrored = HasBit(callback, 7);
callback = GB(callback, 0, 7);
} else {
/* 15 bits, bit 14 for mirroring */
if (callback == 0x7FFF) return INVALID_ENGINE;
- if (mirrored != NULL) *mirrored = HasBit(callback, 14);
+ if (mirrored != nullptr) *mirrored = HasBit(callback, 14);
callback = GB(callback, 0, 14);
}
@@ -80,7 +80,7 @@ uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
* either, so it doesn't matter how many articulated parts there are. */
if (!Vehicle::CanAllocateItem()) return 0;
- Vehicle *v = NULL;
+ Vehicle *v = nullptr;
if (!purchase_window) {
v = new Vehicle();
v->engine_type = engine_type;
@@ -108,7 +108,7 @@ static inline uint16 GetVehicleDefaultCapacity(EngineID engine, CargoID *cargo_t
{
const Engine *e = Engine::Get(engine);
CargoID cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
- if (cargo_type != NULL) *cargo_type = cargo;
+ if (cargo_type != nullptr) *cargo_type = cargo;
if (cargo == CT_INVALID) return 0;
return e->GetDisplayDefaultCapacity();
}
@@ -290,15 +290,15 @@ bool IsArticulatedVehicleCarryingDifferentCargoes(const Vehicle *v, CargoID *car
if (v->cargo_type != CT_INVALID && v->GetEngine()->CanCarryCargo()) {
if (first_cargo == CT_INVALID) first_cargo = v->cargo_type;
if (first_cargo != v->cargo_type) {
- if (cargo_type != NULL) *cargo_type = CT_INVALID;
+ if (cargo_type != nullptr) *cargo_type = CT_INVALID;
return true;
}
}
- v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL;
- } while (v != NULL);
+ v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr;
+ } while (v != nullptr);
- if (cargo_type != NULL) *cargo_type = first_cargo;
+ if (cargo_type != nullptr) *cargo_type = first_cargo;
return false;
}
@@ -330,8 +330,8 @@ void CheckConsistencyOfArticulatedVehicle(const Vehicle *v)
assert(v->cargo_type < NUM_CARGO);
real_default_capacity[v->cargo_type] += v->cargo_cap;
- v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL;
- } while (v != NULL);
+ v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr;
+ } while (v != nullptr);
/* Check whether the vehicle carries more cargoes than expected */
bool carries_more = false;
diff --git a/src/autoreplace.cpp b/src/autoreplace.cpp
index 3b7f73972..968bfe91c 100644
--- a/src/autoreplace.cpp
+++ b/src/autoreplace.cpp
@@ -29,11 +29,11 @@ static EngineRenew *GetEngineReplacement(EngineRenewList erl, EngineID engine, G
{
EngineRenew *er = (EngineRenew *)erl;
- while (er != NULL) {
+ while (er != nullptr) {
if (er->from == engine && GroupIsInGroup(group, er->group_id)) return er;
er = er->next;
}
- return NULL;
+ return nullptr;
}
/**
@@ -46,12 +46,12 @@ void RemoveAllEngineReplacement(EngineRenewList *erl)
EngineRenew *er = (EngineRenew *)(*erl);
EngineRenew *next;
- while (er != NULL) {
+ while (er != nullptr) {
next = er->next;
delete er;
er = next;
}
- *erl = NULL; // Empty list
+ *erl = nullptr; // Empty list
}
/**
@@ -66,12 +66,12 @@ void RemoveAllEngineReplacement(EngineRenewList *erl)
EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group, bool *replace_when_old)
{
const EngineRenew *er = GetEngineReplacement(erl, engine, group);
- if (er == NULL && (group == DEFAULT_GROUP || (Group::IsValidID(group) && !Group::Get(group)->replace_protection))) {
+ if (er == nullptr && (group == DEFAULT_GROUP || (Group::IsValidID(group) && !Group::Get(group)->replace_protection))) {
/* We didn't find anything useful in the vehicle's own group so we will try ALL_GROUP */
er = GetEngineReplacement(erl, engine, ALL_GROUP);
}
- if (replace_when_old != NULL) *replace_when_old = er == NULL ? false : er->replace_when_old;
- return er == NULL ? INVALID_ENGINE : er->to;
+ if (replace_when_old != nullptr) *replace_when_old = er == nullptr ? false : er->replace_when_old;
+ return er == nullptr ? INVALID_ENGINE : er->to;
}
/**
@@ -88,7 +88,7 @@ CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, Engi
{
/* Check if the old vehicle is already in the list */
EngineRenew *er = GetEngineReplacement(*erl, old_engine, group);
- if (er != NULL) {
+ if (er != nullptr) {
if (flags & DC_EXEC) {
er->to = new_engine;
er->replace_when_old = replace_when_old;
@@ -122,12 +122,12 @@ CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, Engi
CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, GroupID group, DoCommandFlag flags)
{
EngineRenew *er = (EngineRenew *)(*erl);
- EngineRenew *prev = NULL;
+ EngineRenew *prev = nullptr;
- while (er != NULL) {
+ while (er != nullptr) {
if (er->from == engine && er->group_id == group) {
if (flags & DC_EXEC) {
- if (prev == NULL) { // First element
+ if (prev == nullptr) { // First element
/* The second becomes the new first element */
*erl = (EngineRenewList)er->next;
} else {
diff --git a/src/autoreplace_cmd.cpp b/src/autoreplace_cmd.cpp
index 7a8a7fefd..45cf83f30 100644
--- a/src/autoreplace_cmd.cpp
+++ b/src/autoreplace_cmd.cpp
@@ -98,9 +98,9 @@ bool CheckAutoreplaceValidity(EngineID from, EngineID to, CompanyID company)
*/
void CheckCargoCapacity(Vehicle *v)
{
- assert(v == NULL || v->First() == v);
+ assert(v == nullptr || v->First() == v);
- for (Vehicle *src = v; src != NULL; src = src->Next()) {
+ for (Vehicle *src = v; src != nullptr; src = src->Next()) {
assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
/* Do we need to more cargo away? */
@@ -108,7 +108,7 @@ void CheckCargoCapacity(Vehicle *v)
/* We need to move a particular amount. Try that on the other vehicles. */
uint to_spread = src->cargo.TotalCount() - src->cargo_cap;
- for (Vehicle *dest = v; dest != NULL && to_spread != 0; dest = dest->Next()) {
+ for (Vehicle *dest = v; dest != nullptr && to_spread != 0; dest = dest->Next()) {
assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
if (dest->cargo.TotalCount() >= dest->cargo_cap || dest->cargo_type != src->cargo_type) continue;
@@ -135,7 +135,7 @@ static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chai
{
assert(!part_of_chain || new_head->IsPrimaryVehicle());
/* Loop through source parts */
- for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
+ for (Vehicle *src = old_veh; src != nullptr; src = src->Next()) {
assert(src->cargo.TotalCount() == src->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !src->IsArticulatedPart()) {
/* Skip vehicles, which do not belong to old_veh */
@@ -145,7 +145,7 @@ static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chai
if (src->cargo_type >= NUM_CARGO || src->cargo.TotalCount() == 0) continue;
/* Find free space in the new chain */
- for (Vehicle *dest = new_head; dest != NULL && src->cargo.TotalCount() > 0; dest = dest->Next()) {
+ for (Vehicle *dest = new_head; dest != nullptr && src->cargo.TotalCount() > 0; dest = dest->Next()) {
assert(dest->cargo.TotalCount() == dest->cargo.ActionCount(VehicleCargoList::MTA_KEEP));
if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !dest->IsArticulatedPart()) {
/* Skip vehicles, which do not belong to new_head */
@@ -216,7 +216,7 @@ static CargoID GetNewCargoTypeForReplace(Vehicle *v, EngineID engine_type, bool
/* the old engine didn't have cargo capacity, but the new one does
* now we will figure out what cargo the train is carrying and refit to fit this */
- for (v = v->First(); v != NULL; v = v->Next()) {
+ for (v = v->First(); v != nullptr; v = v->Next()) {
if (!v->GetEngine()->CanCarryCargo()) continue;
/* Now we found a cargo type being carried on the train and we will see if it is possible to carry to this one */
if (HasBit(available_cargo_types, v->cargo_type)) return v->cargo_type;
@@ -280,7 +280,7 @@ static CommandCost GetNewEngineType(const Vehicle *v, const Company *c, bool alw
*/
static CommandCost BuildReplacementVehicle(Vehicle *old_veh, Vehicle **new_vehicle, bool part_of_chain)
{
- *new_vehicle = NULL;
+ *new_vehicle = nullptr;
/* Shall the vehicle be replaced? */
const Company *c = Company::Get(_current_company);
@@ -330,14 +330,14 @@ static inline CommandCost CmdStartStopVehicle(const Vehicle *v, bool evaluate_ca
/**
* Issue a train vehicle move command
* @param v The vehicle to move
- * @param after The vehicle to insert 'v' after, or NULL to start new chain
+ * @param after The vehicle to insert 'v' after, or nullptr to start new chain
* @param flags the command flags to use
* @param whole_chain move all vehicles following 'v' (true), or only 'v' (false)
* @return success or error
*/
static inline CommandCost CmdMoveVehicle(const Vehicle *v, const Vehicle *after, DoCommandFlag flags, bool whole_chain)
{
- return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != NULL ? after->index : INVALID_VEHICLE, flags | DC_NO_CARGO_CAP_CHECK, CMD_MOVE_RAIL_VEHICLE);
+ return DoCommand(0, v->index | (whole_chain ? 1 : 0) << 20, after != nullptr ? after->index : INVALID_VEHICLE, flags | DC_NO_CARGO_CAP_CHECK, CMD_MOVE_RAIL_VEHICLE);
}
/**
@@ -395,11 +395,11 @@ static CommandCost ReplaceFreeUnit(Vehicle **single_unit, DoCommandFlag flags, b
CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
/* Build and refit replacement vehicle */
- Vehicle *new_v = NULL;
+ Vehicle *new_v = nullptr;
cost.AddCost(BuildReplacementVehicle(old_v, &new_v, false));
/* Was a new vehicle constructed? */
- if (cost.Succeeded() && new_v != NULL) {
+ if (cost.Succeeded() && new_v != nullptr) {
*nothing_to_do = false;
if ((flags & DC_EXEC) != 0) {
@@ -449,17 +449,17 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;
int num_units = 0; ///< Number of units in the chain
- for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;
+ for (Train *w = Train::From(old_head); w != nullptr; w = w->GetNextUnit()) num_units++;
Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
- Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
+ Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or nullptr if no replacement
Money *new_costs = MallocT<Money>(num_units); ///< Costs for buying and refitting the new vehicles
/* Collect vehicles and build replacements
* Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
int i;
Train *w;
- for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
+ for (w = Train::From(old_head), i = 0; w != nullptr; w = w->GetNextUnit(), i++) {
assert(i < num_units);
old_vehs[i] = w;
@@ -468,41 +468,41 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
if (cost.Failed()) break;
new_costs[i] = ret.GetCost();
- if (new_vehs[i] != NULL) *nothing_to_do = false;
+ if (new_vehs[i] != nullptr) *nothing_to_do = false;
}
- Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
+ Train *new_head = (new_vehs[0] != nullptr ? new_vehs[0] : old_vehs[0]);
/* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
if (cost.Succeeded()) {
/* Separate the head, so we can start constructing the new chain */
Train *second = Train::From(old_head)->GetNextUnit();
- if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
+ if (second != nullptr) cost.AddCost(CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true));
- assert(Train::From(new_head)->GetNextUnit() == NULL);
+ assert(Train::From(new_head)->GetNextUnit() == nullptr);
/* Append engines to the new chain
* We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
* That way we also have less trouble when exceeding the unitnumber limit.
* OTOH the vehicle attach callback is more expensive this way :s */
- Train *last_engine = NULL; ///< Shall store the last engine unit after this step
+ Train *last_engine = nullptr; ///< Shall store the last engine unit after this step
if (cost.Succeeded()) {
for (int i = num_units - 1; i > 0; i--) {
- Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
+ Train *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;
- if (new_vehs[i] != NULL) {
+ if (new_vehs[i] != nullptr) {
/* Move the old engine to a separate row with DC_AUTOREPLACE. Else
* moving the wagon in front may fail later due to unitnumber limit.
* (We have to attach wagons without DC_AUTOREPLACE.) */
- CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
+ CmdMoveVehicle(old_vehs[i], nullptr, DC_EXEC | DC_AUTOREPLACE, false);
}
- if (last_engine == NULL) last_engine = append;
+ if (last_engine == nullptr) last_engine = append;
cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
if (cost.Failed()) break;
}
- if (last_engine == NULL) last_engine = new_head;
+ if (last_engine == nullptr) last_engine = new_head;
}
/* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
@@ -513,8 +513,8 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
*/
if (cost.Succeeded()) {
for (int i = num_units - 1; i > 0; i--) {
- assert(last_engine != NULL);
- Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
+ assert(last_engine != nullptr);
+ Vehicle *append = (new_vehs[i] != nullptr ? new_vehs[i] : old_vehs[i]);
if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
/* Insert wagon after 'last_engine' */
@@ -524,7 +524,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
* to the train becoming too long, or the train becoming longer
* would move the vehicle to the empty vehicle chain. */
if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
- CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
+ CmdMoveVehicle(append, nullptr, DC_EXEC | DC_AUTOREPLACE, false);
break;
}
@@ -543,7 +543,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
for (int i = 1; i < num_units; i++) {
Vehicle *wagon = new_vehs[i];
- if (wagon == NULL) continue;
+ if (wagon == nullptr) continue;
if (wagon->First() == new_head) break;
assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);
@@ -551,7 +551,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
/* Sell wagon */
CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
assert(ret.Succeeded());
- new_vehs[i] = NULL;
+ new_vehs[i] = nullptr;
/* Revert the money subtraction when the vehicle was built.
* This value is different from the sell value, esp. because of refitting */
@@ -572,7 +572,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
for (int i = 0; i < num_units; i++) {
Vehicle *w = old_vehs[i];
/* Is the vehicle again part of the new chain?
- * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
+ * Note: We cannot test 'new_vehs[i] != nullptr' as wagon removal might cause to remove both */
if (w->First() == new_head) continue;
if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);
@@ -582,8 +582,8 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
* it from failing due to engine limits. */
cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
if ((flags & DC_EXEC) != 0) {
- old_vehs[i] = NULL;
- if (i == 0) old_head = NULL;
+ old_vehs[i] = nullptr;
+ if (i == 0) old_head = nullptr;
}
}
@@ -596,9 +596,9 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
if ((flags & DC_EXEC) == 0) {
/* Separate the head, so we can reattach the old vehicles */
Train *second = Train::From(old_head)->GetNextUnit();
- if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
+ if (second != nullptr) CmdMoveVehicle(second, nullptr, DC_EXEC | DC_AUTOREPLACE, true);
- assert(Train::From(old_head)->GetNextUnit() == NULL);
+ assert(Train::From(old_head)->GetNextUnit() == nullptr);
for (int i = num_units - 1; i > 0; i--) {
CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
@@ -610,9 +610,9 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
/* Finally undo buying of new vehicles */
if ((flags & DC_EXEC) == 0) {
for (int i = num_units - 1; i >= 0; i--) {
- if (new_vehs[i] != NULL) {
+ if (new_vehs[i] != nullptr) {
DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
- new_vehs[i] = NULL;
+ new_vehs[i] = nullptr;
}
}
}
@@ -622,11 +622,11 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
free(new_costs);
} else {
/* Build and refit replacement vehicle */
- Vehicle *new_head = NULL;
+ Vehicle *new_head = nullptr;
cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));
/* Was a new vehicle constructed? */
- if (cost.Succeeded() && new_head != NULL) {
+ if (cost.Succeeded() && new_head != nullptr) {
*nothing_to_do = false;
/* The new vehicle is constructed, now take over orders and everything... */
@@ -666,7 +666,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL) return CMD_ERROR;
+ if (v == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -690,12 +690,12 @@ CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1
/* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
Vehicle *w = v;
bool any_replacements = false;
- while (w != NULL) {
+ while (w != nullptr) {
EngineID e;
CommandCost cost = GetNewEngineType(w, c, false, e);
if (cost.Failed()) return cost;
any_replacements |= (e != INVALID_ENGINE);
- w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
+ w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : nullptr);
}
CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
@@ -756,7 +756,7 @@ CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1
CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Company *c = Company::GetIfValid(_current_company);
- if (c == NULL) return CMD_ERROR;
+ if (c == nullptr) return CMD_ERROR;
EngineID old_engine_type = GB(p2, 0, 16);
EngineID new_engine_type = GB(p2, 16, 16);
diff --git a/src/autoreplace_func.h b/src/autoreplace_func.h
index 3a6fc83a8..22287cd8c 100644
--- a/src/autoreplace_func.h
+++ b/src/autoreplace_func.h
@@ -16,7 +16,7 @@
#include "company_base.h"
void RemoveAllEngineReplacement(EngineRenewList *erl);
-EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group, bool *replace_when_old = NULL);
+EngineID EngineReplacement(EngineRenewList erl, EngineID engine, GroupID group, bool *replace_when_old = nullptr);
CommandCost AddEngineReplacement(EngineRenewList *erl, EngineID old_engine, EngineID new_engine, GroupID group, bool replace_when_old, DoCommandFlag flags);
CommandCost RemoveEngineReplacement(EngineRenewList *erl, EngineID engine, GroupID group, DoCommandFlag flags);
@@ -38,7 +38,7 @@ static inline void RemoveAllEngineReplacementForCompany(Company *c)
* @return The engine type to replace with, or INVALID_ENGINE if no
* replacement is in the list.
*/
-static inline EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old = NULL)
+static inline EngineID EngineReplacementForCompany(const Company *c, EngineID engine, GroupID group, bool *replace_when_old = nullptr)
{
return EngineReplacement(c->engine_renew_list, engine, group, replace_when_old);
}
diff --git a/src/base_consist.cpp b/src/base_consist.cpp
index 200512786..7abb083f7 100644
--- a/src/base_consist.cpp
+++ b/src/base_consist.cpp
@@ -30,7 +30,7 @@ void BaseConsist::CopyConsistPropertiesFrom(const BaseConsist *src)
if (this == src) return;
free(this->name);
- this->name = src->name != NULL ? stredup(src->name) : NULL;
+ this->name = src->name != nullptr ? stredup(src->name) : nullptr;
this->current_order_time = src->current_order_time;
this->lateness_counter = src->lateness_counter;
diff --git a/src/base_consist.h b/src/base_consist.h
index 3679afd35..8e1bc93e7 100644
--- a/src/base_consist.h
+++ b/src/base_consist.h
@@ -31,7 +31,7 @@ struct BaseConsist {
uint16 vehicle_flags; ///< Used for gradual loading and other miscellaneous things (@see VehicleFlags enum)
- BaseConsist() : name(NULL) {}
+ BaseConsist() : name(nullptr) {}
virtual ~BaseConsist();
void CopyConsistPropertiesFrom(const BaseConsist *src);
diff --git a/src/base_media_base.h b/src/base_media_base.h
index 565540155..1e251b36a 100644
--- a/src/base_media_base.h
+++ b/src/base_media_base.h
@@ -118,9 +118,9 @@ struct BaseSet {
* @param isocode the isocode to search for
* @return the description
*/
- const char *GetDescription(const char *isocode = NULL) const
+ const char *GetDescription(const char *isocode = nullptr) const
{
- if (isocode != NULL) {
+ if (isocode != nullptr) {
/* First the full ISO code */
for (const auto &pair : this->description) {
if (strcmp(pair.first, isocode) == 0) return pair.second;
@@ -151,17 +151,17 @@ struct BaseSet {
/**
* Search a textfile file next to this base media.
* @param type The type of the textfile to search for.
- * @return The filename for the textfile, \c NULL otherwise.
+ * @return The filename for the textfile, \c nullptr otherwise.
*/
const char *GetTextfile(TextfileType type) const
{
for (uint i = 0; i < NUM_FILES; i++) {
const char *textfile = ::GetTextfile(type, BASESET_DIR, this->files[i].filename);
- if (textfile != NULL) {
+ if (textfile != nullptr) {
return textfile;
}
}
- return NULL;
+ return nullptr;
}
};
@@ -231,7 +231,7 @@ template <class Tbase_set> /* static */ Tbase_set *BaseMedia<Tbase_set>::duplica
* @param ci The content info to compare it to.
* @param md5sum Should the MD5 checksum be tested as well?
* @param s The list with sets.
- * @return The filename of the first file of the base set, or \c NULL if there is no match.
+ * @return The filename of the first file of the base set, or \c nullptr if there is no match.
*/
template <class Tbase_set>
const char *TryGetBaseSetFile(const ContentInfo *ci, bool md5sum, const Tbase_set *s);
diff --git a/src/base_media_func.h b/src/base_media_func.h
index ed954360a..42d5cad2f 100644
--- a/src/base_media_func.h
+++ b/src/base_media_func.h
@@ -23,7 +23,7 @@
*/
#define fetch_metadata(name) \
item = metadata->GetItem(name, false); \
- if (item == NULL || StrEmpty(item->value)) { \
+ if (item == nullptr || StrEmpty(item->value)) { \
DEBUG(grf, 0, "Base " SET_TYPE "set detail loading: %s field missing.", name); \
DEBUG(grf, 0, " Is %s readable for the user running OpenTTD?", full_filename); \
return false; \
@@ -50,7 +50,7 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
this->description[stredup("")] = stredup(item->value);
/* Add the translations of the descriptions too. */
- for (const IniItem *item = metadata->item; item != NULL; item = item->next) {
+ for (const IniItem *item = metadata->item; item != nullptr; item = item->next) {
if (strncmp("description.", item->name, 12) != 0) continue;
this->description[stredup(item->name + 12)] = stredup(item->value);
@@ -65,7 +65,7 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
this->version = atoi(item->value);
item = metadata->GetItem("fallback", false);
- this->fallback = (item != NULL && strcmp(item->value, "0") != 0 && strcmp(item->value, "false") != 0);
+ this->fallback = (item != nullptr && strcmp(item->value, "0") != 0 && strcmp(item->value, "false") != 0);
/* For each of the file types we want to find the file, MD5 checksums and warning messages. */
IniGroup *files = ini->GetGroup("files");
@@ -75,14 +75,14 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
MD5File *file = &this->files[i];
/* Find the filename first. */
item = files->GetItem(BaseSet<T, Tnum_files, Tsearch_in_tars>::file_names[i], false);
- if (item == NULL || (item->value == NULL && !allow_empty_filename)) {
+ if (item == nullptr || (item->value == nullptr && !allow_empty_filename)) {
DEBUG(grf, 0, "No " SET_TYPE " file for: %s (in %s)", BaseSet<T, Tnum_files, Tsearch_in_tars>::file_names[i], full_filename);
return false;
}
const char *filename = item->value;
- if (filename == NULL) {
- file->filename = NULL;
+ if (filename == nullptr) {
+ file->filename = nullptr;
/* If we list no file, that file must be valid */
this->valid_files++;
this->found_files++;
@@ -93,7 +93,7 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
/* Then find the MD5 checksum */
item = md5s->GetItem(filename, false);
- if (item == NULL || item->value == NULL) {
+ if (item == nullptr || item->value == nullptr) {
DEBUG(grf, 0, "No MD5 checksum specified for: %s (in %s)", filename, full_filename);
return false;
}
@@ -119,8 +119,8 @@ bool BaseSet<T, Tnum_files, Tsearch_in_tars>::FillSetDetails(IniFile *ini, const
/* Then find the warning message when the file's missing */
item = origin->GetItem(filename, false);
- if (item == NULL) item = origin->GetItem("default", false);
- if (item == NULL) {
+ if (item == nullptr) item = origin->GetItem("default", false);
+ if (item == nullptr) {
DEBUG(grf, 1, "No origin warning message specified for: %s", filename);
file->missing_warning = stredup("");
} else {
@@ -163,21 +163,21 @@ bool BaseMedia<Tbase_set>::AddFile(const char *filename, size_t basepath_length,
char *path = stredup(filename + basepath_length);
char *psep = strrchr(path, PATHSEPCHAR);
- if (psep != NULL) {
+ if (psep != nullptr) {
psep[1] = '\0';
} else {
*path = '\0';
}
if (set->FillSetDetails(ini, path, filename)) {
- Tbase_set *duplicate = NULL;
- for (Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) {
+ Tbase_set *duplicate = nullptr;
+ for (Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != nullptr; c = c->next) {
if (strcmp(c->name, set->name) == 0 || c->shortname == set->shortname) {
duplicate = c;
break;
}
}
- if (duplicate != NULL) {
+ if (duplicate != nullptr) {
/* The more complete set takes precedence over the version number. */
if ((duplicate->valid_files == set->valid_files && duplicate->version >= set->version) ||
duplicate->valid_files > set->valid_files) {
@@ -205,7 +205,7 @@ bool BaseMedia<Tbase_set>::AddFile(const char *filename, size_t basepath_length,
}
} else {
Tbase_set **last = &BaseMedia<Tbase_set>::available_sets;
- while (*last != NULL) last = &(*last)->next;
+ while (*last != nullptr) last = &(*last)->next;
*last = set;
ret = true;
@@ -238,7 +238,7 @@ template <class Tbase_set>
return true;
}
- for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != NULL; s = s->next) {
+ for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
if (strcmp(name, s->name) == 0) {
BaseMedia<Tbase_set>::used_set = s;
CheckExternalFiles();
@@ -258,7 +258,7 @@ template <class Tbase_set>
/* static */ char *BaseMedia<Tbase_set>::GetSetsList(char *p, const char *last)
{
p += seprintf(p, last, "List of " SET_TYPE " sets:\n");
- for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != NULL; s = s->next) {
+ for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
p += seprintf(p, last, "%18s: %s", s->name, s->GetDescription());
int invalid = s->GetNumInvalid();
if (invalid != 0) {
@@ -281,7 +281,7 @@ template <class Tbase_set>
template <class Tbase_set> const char *TryGetBaseSetFile(const ContentInfo *ci, bool md5sum, const Tbase_set *s)
{
- for (; s != NULL; s = s->next) {
+ for (; s != nullptr; s = s->next) {
if (s->GetNumMissing() != 0) continue;
if (s->shortname != ci->unique_id) continue;
@@ -296,14 +296,14 @@ template <class Tbase_set> const char *TryGetBaseSetFile(const ContentInfo *ci,
}
if (memcmp(md5, ci->md5sum, sizeof(md5)) == 0) return s->files[0].filename;
}
- return NULL;
+ return nullptr;
}
template <class Tbase_set>
/* static */ bool BaseMedia<Tbase_set>::HasSet(const ContentInfo *ci, bool md5sum)
{
- return (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::available_sets) != NULL) ||
- (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::duplicate_sets) != NULL);
+ return (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::available_sets) != nullptr) ||
+ (TryGetBaseSetFile(ci, md5sum, BaseMedia<Tbase_set>::duplicate_sets) != nullptr);
}
/**
@@ -314,7 +314,7 @@ template <class Tbase_set>
/* static */ int BaseMedia<Tbase_set>::GetNumSets()
{
int n = 0;
- for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != NULL; s = s->next) {
+ for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
if (s != BaseMedia<Tbase_set>::used_set && s->GetNumMissing() != 0) continue;
n++;
}
@@ -329,7 +329,7 @@ template <class Tbase_set>
/* static */ int BaseMedia<Tbase_set>::GetIndexOfUsedSet()
{
int n = 0;
- for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != NULL; s = s->next) {
+ for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
if (s == BaseMedia<Tbase_set>::used_set) return n;
if (s->GetNumMissing() != 0) continue;
n++;
@@ -344,7 +344,7 @@ template <class Tbase_set>
template <class Tbase_set>
/* static */ const Tbase_set *BaseMedia<Tbase_set>::GetSet(int index)
{
- for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != NULL; s = s->next) {
+ for (const Tbase_set *s = BaseMedia<Tbase_set>::available_sets; s != nullptr; s = s->next) {
if (s != BaseMedia<Tbase_set>::used_set && s->GetNumMissing() != 0) continue;
if (index == 0) return s;
index--;
diff --git a/src/base_station_base.h b/src/base_station_base.h
index 8af01f8a7..d7a67bd65 100644
--- a/src/base_station_base.h
+++ b/src/base_station_base.h
@@ -220,7 +220,7 @@ struct SpecializedStation : public BaseStation {
*/
static inline T *GetIfValid(size_t index)
{
- return IsValidID(index) ? Get(index) : NULL;
+ return IsValidID(index) ? Get(index) : nullptr;
}
/**
diff --git a/src/blitter/32bpp_anim.cpp b/src/blitter/32bpp_anim.cpp
index 27b1fbd5b..293ebb173 100644
--- a/src/blitter/32bpp_anim.cpp
+++ b/src/blitter/32bpp_anim.cpp
@@ -414,7 +414,7 @@ void Blitter_32bppAnim::CopyToBuffer(const void *video, void *dst, int width, in
uint32 *udst = (uint32 *)dst;
const uint32 *src = (const uint32 *)video;
- if (this->anim_buf == NULL) return;
+ if (this->anim_buf == nullptr) return;
const uint16 *anim_line = this->ScreenToAnimOffset((const uint32 *)video) + this->anim_buf;
diff --git a/src/blitter/32bpp_anim.hpp b/src/blitter/32bpp_anim.hpp
index f8fd89281..ea6623493 100644
--- a/src/blitter/32bpp_anim.hpp
+++ b/src/blitter/32bpp_anim.hpp
@@ -26,8 +26,8 @@ protected:
public:
Blitter_32bppAnim() :
- anim_buf(NULL),
- anim_alloc(NULL),
+ anim_buf(nullptr),
+ anim_alloc(nullptr),
anim_buf_width(0),
anim_buf_height(0),
anim_buf_pitch(0)
diff --git a/src/blitter/8bpp_optimized.cpp b/src/blitter/8bpp_optimized.cpp
index 0f07e7c7b..21bca67e1 100644
--- a/src/blitter/8bpp_optimized.cpp
+++ b/src/blitter/8bpp_optimized.cpp
@@ -167,7 +167,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::Sprite *sprite, Alloca
uint trans = 0;
uint pixels = 0;
uint last_colour = 0;
- byte *count_dst = NULL;
+ byte *count_dst = nullptr;
/* Store the scaled image */
const SpriteLoader::CommonPixel *src = &sprite[i].data[y * sprite[i].width];
@@ -176,11 +176,11 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::Sprite *sprite, Alloca
uint colour = src++->m;
if (last_colour == 0 || colour == 0 || pixels == 255) {
- if (count_dst != NULL) {
+ if (count_dst != nullptr) {
/* Write how many non-transparent bytes we get */
*count_dst = pixels;
pixels = 0;
- count_dst = NULL;
+ count_dst = nullptr;
}
/* As long as we find transparency bytes, keep counting */
if (colour == 0 && trans != 255) {
@@ -206,7 +206,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::Sprite *sprite, Alloca
}
}
- if (count_dst != NULL) *count_dst = pixels;
+ if (count_dst != nullptr) *count_dst = pixels;
/* Write line-ending */
*dst = 0; dst++;
diff --git a/src/blitter/factory.hpp b/src/blitter/factory.hpp
index 01faca68f..5def16ea5 100644
--- a/src/blitter/factory.hpp
+++ b/src/blitter/factory.hpp
@@ -48,7 +48,7 @@ private:
*/
static Blitter **GetActiveBlitter()
{
- static Blitter *s_blitter = NULL;
+ static Blitter *s_blitter = nullptr;
return &s_blitter;
}
@@ -58,8 +58,8 @@ protected:
* @param name The name of the blitter.
* @param description A longer description for the blitter.
* @param usable Whether the blitter is usable (on the current computer). For example for disabling SSE blitters when the CPU can't handle them.
- * @pre name != NULL.
- * @pre description != NULL.
+ * @pre name != nullptr.
+ * @pre description != nullptr.
* @pre There is no blitter registered with this name.
*/
BlitterFactory(const char *name, const char *description, bool usable = true) :
@@ -96,7 +96,7 @@ public:
static Blitter *SelectBlitter(const char *name)
{
BlitterFactory *b = GetBlitterFactory(name);
- if (b == NULL) return NULL;
+ if (b == nullptr) return nullptr;
Blitter *newb = b->CreateInstance();
delete *GetActiveBlitter();
@@ -109,7 +109,7 @@ public:
/**
* Get the blitter factory with the given name.
* @param name the blitter factory to select.
- * @return The blitter factory, or NULL when there isn't one with the wanted name.
+ * @return The blitter factory, or nullptr when there isn't one with the wanted name.
*/
static BlitterFactory *GetBlitterFactory(const char *name)
{
@@ -128,7 +128,7 @@ public:
}
#endif /* defined(WITH_COCOA) */
#endif /* defined(DEDICATED) */
- if (GetBlitters().size() == 0) return NULL;
+ if (GetBlitters().size() == 0) return nullptr;
const char *bname = (StrEmpty(name)) ? default_blitter : name;
Blitters::iterator it = GetBlitters().begin();
@@ -138,7 +138,7 @@ public:
return b;
}
}
- return NULL;
+ return nullptr;
}
/**
diff --git a/src/blitter/null.hpp b/src/blitter/null.hpp
index 8dc98646c..dff4992cc 100644
--- a/src/blitter/null.hpp
+++ b/src/blitter/null.hpp
@@ -21,7 +21,7 @@ public:
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override {};
void DrawColourMappingRect(void *dst, int width, int height, PaletteID pal) override {};
Sprite *Encode(const SpriteLoader::Sprite *sprite, AllocatorProc *allocator) override;
- void *MoveTo(void *video, int x, int y) override { return NULL; };
+ void *MoveTo(void *video, int x, int y) override { return nullptr; };
void SetPixel(void *video, int x, int y, uint8 colour) override {};
void DrawRect(void *video, int width, int height, uint8 colour) override {};
void DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8 colour, int width, int dash) override {};
diff --git a/src/bmp.cpp b/src/bmp.cpp
index 1033d89f1..a121782be 100644
--- a/src/bmp.cpp
+++ b/src/bmp.cpp
@@ -319,7 +319,7 @@ static inline bool BmpRead24(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
bool BmpReadHeader(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint32 header_size;
- assert(info != NULL);
+ assert(info != nullptr);
MemSetT(info, 0);
/* Reading BMP header */
@@ -390,7 +390,7 @@ bool BmpReadHeader(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
*/
bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
- assert(info != NULL && data != NULL);
+ assert(info != nullptr && data != nullptr);
data->bitmap = CallocT<byte>(info->width * info->height * ((info->bpp == 24) ? 3 : 1));
@@ -413,7 +413,7 @@ bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
void BmpDestroyData(BmpData *data)
{
- assert(data != NULL);
+ assert(data != nullptr);
free(data->palette);
free(data->bitmap);
}
diff --git a/src/bootstrap_gui.cpp b/src/bootstrap_gui.cpp
index b6fb35bff..d62a2266f 100644
--- a/src/bootstrap_gui.cpp
+++ b/src/bootstrap_gui.cpp
@@ -40,7 +40,7 @@ static const struct NWidgetPart _background_widgets[] = {
* Window description for the background window to prevent smearing.
*/
static WindowDesc _background_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_BOOTSTRAP, WC_NONE,
0,
_background_widgets, lengthof(_background_widgets)
@@ -73,7 +73,7 @@ static const NWidgetPart _nested_boostrap_download_status_window_widgets[] = {
/** Window description for the download window */
static WindowDesc _bootstrap_download_status_window_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_MODAL,
_nested_boostrap_download_status_window_widgets, lengthof(_nested_boostrap_download_status_window_widgets)
@@ -118,7 +118,7 @@ static const NWidgetPart _bootstrap_query_widgets[] = {
/** The window description for the query. */
static WindowDesc _bootstrap_query_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_CONFIRM_POPUP_QUERY, WC_NONE,
0,
_bootstrap_query_widgets, lengthof(_bootstrap_query_widgets)
@@ -214,7 +214,7 @@ public:
*/
bool HandleBootstrap()
{
- if (BaseGraphics::GetUsedSet() != NULL) return true;
+ if (BaseGraphics::GetUsedSet() != nullptr) return true;
/* No user interface, bail out with an error. */
if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) goto failure;
@@ -255,7 +255,7 @@ bool HandleBootstrap()
if (_exit_game) return false;
/* Try to probe the graphics. Should work this time. */
- if (!BaseGraphics::SetSet(NULL)) goto failure;
+ if (!BaseGraphics::SetSet(nullptr)) goto failure;
/* Finally we can continue heading for the menu. */
_game_mode = GM_MENU;
diff --git a/src/bridge_gui.cpp b/src/bridge_gui.cpp
index f6f47276c..c272cb9ec 100644
--- a/src/bridge_gui.cpp
+++ b/src/bridge_gui.cpp
@@ -392,7 +392,7 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo
StringID errmsg = INVALID_STRING_ID;
CommandCost ret = DoCommand(end, start, type, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)) | DC_QUERY_COST, CMD_BUILD_BRIDGE);
- GUIBridgeList *bl = NULL;
+ GUIBridgeList *bl = nullptr;
if (ret.Failed()) {
errmsg = ret.GetErrorMessage();
} else {
@@ -427,7 +427,7 @@ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transpo
}
}
- if (bl != NULL && bl->size() != 0) {
+ if (bl != nullptr && bl->size() != 0) {
new BuildBridgeWindow(&_build_bridge_desc, start, end, type, bl);
} else {
delete bl;
diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp
index b671efde7..bb30f78e5 100644
--- a/src/build_vehicle_gui.cpp
+++ b/src/build_vehicle_gui.cpp
@@ -833,7 +833,7 @@ static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_
*/
static uint ShowAdditionalText(int left, int right, int y, EngineID engine)
{
- uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL);
+ uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, nullptr);
if (callback == CALLBACK_FAILED || callback == 0x400) return y;
const GRFFile *grffile = Engine::Get(engine)->GetGRF();
if (callback > 0x400) {
@@ -1180,7 +1180,7 @@ struct BuildVehicleWindow : Window {
if (!this->listview_mode) {
/* Query for cost and refitted capacity */
- CommandCost ret = DoCommand(this->window_number, this->sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), NULL);
+ CommandCost ret = DoCommand(this->window_number, this->sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), nullptr);
if (ret.Succeeded()) {
this->te.cost = ret.GetCost() - e->GetCost();
this->te.capacity = _returned_refit_capacity;
@@ -1316,7 +1316,7 @@ struct BuildVehicleWindow : Window {
this->eng_list.clear();
- const Station *st = this->listview_mode ? NULL : Station::GetByTile(this->window_number);
+ const Station *st = this->listview_mode ? nullptr : Station::GetByTile(this->window_number);
/* Make list of all available planes.
* Also check to see if the previously selected plane is still available,
@@ -1408,8 +1408,8 @@ struct BuildVehicleWindow : Window {
break;
case WID_BV_SHOW_HIDE: {
- const Engine *e = (this->sel_engine == INVALID_ENGINE) ? NULL : Engine::Get(this->sel_engine);
- if (e != NULL) {
+ const Engine *e = (this->sel_engine == INVALID_ENGINE) ? nullptr : Engine::Get(this->sel_engine);
+ if (e != nullptr) {
DoCommandP(0, 0, this->sel_engine | (e->IsHidden(_current_company) ? 0 : (1u << 31)), CMD_SET_VEHICLE_VISIBILITY);
}
break;
@@ -1477,8 +1477,8 @@ struct BuildVehicleWindow : Window {
break;
case WID_BV_SHOW_HIDE: {
- const Engine *e = (this->sel_engine == INVALID_ENGINE) ? NULL : Engine::Get(this->sel_engine);
- if (e != NULL && e->IsHidden(_local_company)) {
+ const Engine *e = (this->sel_engine == INVALID_ENGINE) ? nullptr : Engine::Get(this->sel_engine);
+ if (e != nullptr && e->IsHidden(_local_company)) {
SetDParam(0, STR_BUY_VEHICLE_TRAIN_SHOW_TOGGLE_BUTTON + this->vehicle_type);
} else {
SetDParam(0, STR_BUY_VEHICLE_TRAIN_HIDE_TOGGLE_BUTTON + this->vehicle_type);
@@ -1567,9 +1567,9 @@ struct BuildVehicleWindow : Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
- DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), NULL, str);
+ DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), nullptr, str);
}
void OnDropdownSelect(int widget, int index) override
diff --git a/src/cargoaction.cpp b/src/cargoaction.cpp
index 96ddc3708..afc1b0fff 100644
--- a/src/cargoaction.cpp
+++ b/src/cargoaction.cpp
@@ -121,7 +121,7 @@ bool CargoDelivery::operator()(CargoPacket *cp)
bool CargoLoad::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) return false;
+ if (cp_new == nullptr) return false;
cp_new->SetLoadPlace(this->load_place);
this->source->RemoveFromCache(cp_new, cp_new->Count());
this->destination->Append(cp_new, VehicleCargoList::MTA_KEEP);
@@ -136,7 +136,7 @@ bool CargoLoad::operator()(CargoPacket *cp)
bool CargoReservation::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) return false;
+ if (cp_new == nullptr) return false;
cp_new->SetLoadPlace(this->load_place);
this->source->reserved_count += cp_new->Count();
this->source->RemoveFromCache(cp_new, cp_new->Count());
@@ -152,7 +152,7 @@ bool CargoReservation::operator()(CargoPacket *cp)
bool CargoReturn::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) cp_new = cp;
+ if (cp_new == nullptr) cp_new = cp;
assert(cp_new->Count() <= this->destination->reserved_count);
this->source->RemoveFromMeta(cp_new, VehicleCargoList::MTA_LOAD, cp_new->Count());
this->destination->reserved_count -= cp_new->Count();
@@ -168,7 +168,7 @@ bool CargoReturn::operator()(CargoPacket *cp)
bool CargoTransfer::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) return false;
+ if (cp_new == nullptr) return false;
this->source->RemoveFromMeta(cp_new, VehicleCargoList::MTA_TRANSFER, cp_new->Count());
/* No transfer credits here as they were already granted during Stage(). */
this->destination->Append(cp_new, cp_new->NextStation());
@@ -183,7 +183,7 @@ bool CargoTransfer::operator()(CargoPacket *cp)
bool CargoShift::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) cp_new = cp;
+ if (cp_new == nullptr) cp_new = cp;
this->source->RemoveFromMeta(cp_new, VehicleCargoList::MTA_KEEP, cp_new->Count());
this->destination->Append(cp_new, VehicleCargoList::MTA_KEEP);
return cp_new == cp;
@@ -197,7 +197,7 @@ bool CargoShift::operator()(CargoPacket *cp)
bool StationCargoReroute::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) cp_new = cp;
+ if (cp_new == nullptr) cp_new = cp;
StationID next = this->ge->GetVia(cp_new->SourceStation(), this->avoid, this->avoid2);
assert(next != this->avoid && next != this->avoid2);
if (this->source != this->destination) {
@@ -220,7 +220,7 @@ bool StationCargoReroute::operator()(CargoPacket *cp)
bool VehicleCargoReroute::operator()(CargoPacket *cp)
{
CargoPacket *cp_new = this->Preprocess(cp);
- if (cp_new == NULL) cp_new = cp;
+ if (cp_new == nullptr) cp_new = cp;
if (cp_new->NextStation() == this->avoid || cp_new->NextStation() == this->avoid2) {
cp->SetNextStation(this->ge->GetVia(cp_new->SourceStation(), this->avoid, this->avoid2));
}
diff --git a/src/cargopacket.cpp b/src/cargopacket.cpp
index 9e699d6f4..2147783c8 100644
--- a/src/cargopacket.cpp
+++ b/src/cargopacket.cpp
@@ -86,11 +86,11 @@ CargoPacket::CargoPacket(uint16 count, byte days_in_transit, StationID source, T
/**
* Split this packet in two and return the split off part.
* @param new_size Size of the split part.
- * @return Split off part, or NULL if no packet could be allocated!
+ * @return Split off part, or nullptr if no packet could be allocated!
*/
CargoPacket *CargoPacket::Split(uint new_size)
{
- if (!CargoPacket::CanAllocateItem()) return NULL;
+ if (!CargoPacket::CanAllocateItem()) return nullptr;
Money fs = this->FeederShare(new_size);
CargoPacket *cp_new = new CargoPacket(new_size, this->days_in_transit, this->source, this->source_xy, this->loaded_at_xy, fs, this->source_type, this->source_id);
@@ -248,12 +248,12 @@ template <class Tinst, class Tcont>
* @param cp Cargo packet to add.
* @param action Either MTA_KEEP if you want to add the packet directly or MTA_LOAD
* if you want to reserve it first.
- * @pre cp != NULL
+ * @pre cp != nullptr
* @pre action == MTA_LOAD || (action == MTA_KEEP && this->designation_counts[MTA_LOAD] == 0)
*/
void VehicleCargoList::Append(CargoPacket *cp, MoveToAction action)
{
- assert(cp != NULL);
+ assert(cp != nullptr);
assert(action == MTA_LOAD ||
(action == MTA_KEEP && this->action_counts[MTA_LOAD] == 0));
this->AddToMeta(cp, action);
@@ -689,11 +689,11 @@ uint VehicleCargoList::Reroute(uint max_move, VehicleCargoList *dest, StationID
* @note Do not use the cargo packet anymore after it has been appended to this CargoList!
* @param next the next hop
* @param cp the cargo packet to add
- * @pre cp != NULL
+ * @pre cp != nullptr
*/
void StationCargoList::Append(CargoPacket *cp, StationID next)
{
- assert(cp != NULL);
+ assert(cp != nullptr);
this->AddToCache(cp);
StationCargoPacketMap::List &list = this->packets[next];
@@ -776,7 +776,7 @@ uint StationCargoList::Truncate(uint max_move, StationCargoAmountMap *cargo_per_
uint prev_count = this->count;
uint moved = 0;
uint loop = 0;
- bool do_count = cargo_per_source != NULL;
+ bool do_count = cargo_per_source != nullptr;
while (max_move > moved) {
for (Iterator it(this->packets.begin()); it != this->packets.end();) {
CargoPacket *cp = *it;
diff --git a/src/cargopacket.h b/src/cargopacket.h
index 0ed4fd9bb..435432797 100644
--- a/src/cargopacket.h
+++ b/src/cargopacket.h
@@ -549,7 +549,7 @@ public:
uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next);
uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next);
- uint Truncate(uint max_move = UINT_MAX, StationCargoAmountMap *cargo_per_source = NULL);
+ uint Truncate(uint max_move = UINT_MAX, StationCargoAmountMap *cargo_per_source = nullptr);
uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge);
/**
diff --git a/src/cargotype.h b/src/cargotype.h
index 71cd932bb..b35eef965 100644
--- a/src/cargotype.h
+++ b/src/cargotype.h
@@ -152,7 +152,7 @@ static inline bool IsCargoInClass(CargoID c, CargoClass cc)
return (CargoSpec::Get(c)->classes & cc) != 0;
}
-#define FOR_ALL_CARGOSPECS_FROM(var, start) for (size_t cargospec_index = start; var = NULL, cargospec_index < CargoSpec::GetArraySize(); cargospec_index++) \
+#define FOR_ALL_CARGOSPECS_FROM(var, start) for (size_t cargospec_index = start; var = nullptr, cargospec_index < CargoSpec::GetArraySize(); cargospec_index++) \
if ((var = CargoSpec::Get(cargospec_index))->IsValid())
#define FOR_ALL_CARGOSPECS(var) FOR_ALL_CARGOSPECS_FROM(var, 0)
diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp
index e6bfc8c0a..2cd8b90f0 100644
--- a/src/cheat_gui.cpp
+++ b/src/cheat_gui.cpp
@@ -186,9 +186,9 @@ struct CheatEntry {
static const CheatEntry _cheats_ui[] = {
{SLE_INT32, STR_CHEAT_MONEY, &_money_cheat_amount, &_cheats.money.been_used, &ClickMoneyCheat },
{SLE_UINT8, STR_CHEAT_CHANGE_COMPANY, &_local_company, &_cheats.switch_company.been_used, &ClickChangeCompanyCheat },
- {SLE_BOOL, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, NULL },
- {SLE_BOOL, STR_CHEAT_CROSSINGTUNNELS, &_cheats.crossing_tunnels.value, &_cheats.crossing_tunnels.been_used, NULL },
- {SLE_BOOL, STR_CHEAT_NO_JETCRASH, &_cheats.no_jetcrash.value, &_cheats.no_jetcrash.been_used, NULL },
+ {SLE_BOOL, STR_CHEAT_EXTRA_DYNAMITE, &_cheats.magic_bulldozer.value, &_cheats.magic_bulldozer.been_used, nullptr },
+ {SLE_BOOL, STR_CHEAT_CROSSINGTUNNELS, &_cheats.crossing_tunnels.value, &_cheats.crossing_tunnels.been_used, nullptr },
+ {SLE_BOOL, STR_CHEAT_NO_JETCRASH, &_cheats.no_jetcrash.value, &_cheats.no_jetcrash.been_used, nullptr },
{SLE_BOOL, STR_CHEAT_SETUP_PROD, &_cheats.setup_prod.value, &_cheats.setup_prod.been_used, &ClickSetProdCheat },
{SLE_UINT8, STR_CHEAT_EDIT_MAX_HL, &_settings_game.construction.max_heightlevel, &_cheats.edit_max_hl.been_used, &ClickChangeMaxHlCheat },
{SLE_INT32, STR_CHEAT_CHANGE_DATE, &_cur_year, &_cheats.change_date.been_used, &ClickChangeDateCheat },
@@ -365,7 +365,7 @@ struct CheatWindow : Window {
switch (ce->type) {
case SLE_BOOL:
value ^= 1;
- if (ce->proc != NULL) ce->proc(value, 0);
+ if (ce->proc != nullptr) ce->proc(value, 0);
break;
default:
@@ -393,7 +393,7 @@ struct CheatWindow : Window {
void OnQueryTextFinished(char *str) override
{
/* Was 'cancel' pressed or nothing entered? */
- if (str == NULL || StrEmpty(str)) return;
+ if (str == nullptr || StrEmpty(str)) return;
const CheatEntry *ce = &_cheats_ui[clicked_widget];
int oldvalue = (int32)ReadValue(ce->variable, ce->type);
diff --git a/src/clear_cmd.cpp b/src/clear_cmd.cpp
index c4aeb3a52..bfe5c66b3 100644
--- a/src/clear_cmd.cpp
+++ b/src/clear_cmd.cpp
@@ -389,15 +389,15 @@ extern const TileTypeProcs _tile_type_clear_procs = {
DrawTile_Clear, ///< draw_tile_proc
GetSlopePixelZ_Clear, ///< get_slope_z_proc
ClearTile_Clear, ///< clear_tile_proc
- NULL, ///< add_accepted_cargo_proc
+ nullptr, ///< add_accepted_cargo_proc
GetTileDesc_Clear, ///< get_tile_desc_proc
GetTileTrackStatus_Clear, ///< get_tile_track_status_proc
- NULL, ///< click_tile_proc
- NULL, ///< animate_tile_proc
+ nullptr, ///< click_tile_proc
+ nullptr, ///< animate_tile_proc
TileLoop_Clear, ///< tile_loop_proc
ChangeTileOwner_Clear, ///< change_tile_owner_proc
- NULL, ///< add_produced_cargo_proc
- NULL, ///< vehicle_enter_tile_proc
+ nullptr, ///< add_produced_cargo_proc
+ nullptr, ///< vehicle_enter_tile_proc
GetFoundation_Clear, ///< get_foundation_proc
TerraformTile_Clear, ///< terraform_tile_proc
};
diff --git a/src/command.cpp b/src/command.cpp
index b914563fc..7f5dd4309 100644
--- a/src/command.cpp
+++ b/src/command.cpp
@@ -361,7 +361,7 @@ static const Command _command_proc_table[] = {
};
/*!
- * This function range-checks a cmd, and checks if the cmd is not NULL
+ * This function range-checks a cmd, and checks if the cmd is not nullptr
*
* @param cmd The integer value of a command
* @return true if the command is valid (and got a CommandProc function)
@@ -370,7 +370,7 @@ bool IsValidCommand(uint32 cmd)
{
cmd &= CMD_ID_MASK;
- return cmd < lengthof(_command_proc_table) && _command_proc_table[cmd].proc != NULL;
+ return cmd < lengthof(_command_proc_table) && _command_proc_table[cmd].proc != nullptr;
}
/*!
@@ -594,7 +594,7 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallbac
ShowCostOrIncomeAnimation(x, y, GetSlopePixelZ(x, y), res.GetCost());
}
- if (!estimate_only && !only_sending && callback != NULL) {
+ if (!estimate_only && !only_sending && callback != nullptr) {
callback(res, tile, p1, p2);
}
@@ -637,7 +637,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd,
CommandProc *proc = _command_proc_table[cmd_id].proc;
/* Shouldn't happen, but you never know when someone adds
* NULLs to the _command_proc_table. */
- assert(proc != NULL);
+ assert(proc != nullptr);
/* Command flags are used internally */
CommandFlags cmd_flags = GetCommandFlags(cmd);
@@ -750,7 +750,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd,
/* update last build coordinate of company. */
if (tile != 0) {
Company *c = Company::GetIfValid(_current_company);
- if (c != NULL) c->last_build_coordinate = tile;
+ if (c != nullptr) c->last_build_coordinate = tile;
}
SubtractMoneyFromCompany(res2);
diff --git a/src/command_func.h b/src/command_func.h
index ea42f25d3..7a6b6d6bb 100644
--- a/src/command_func.h
+++ b/src/command_func.h
@@ -34,10 +34,10 @@ static const CommandCost CMD_ERROR = CommandCost(INVALID_STRING_ID);
*/
#define return_cmd_error(errcode) return CommandCost(errcode);
-CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const char *text = NULL);
+CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const char *text = nullptr);
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags);
-bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback = NULL, const char *text = NULL, bool my_cmd = true);
+bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback = nullptr, const char *text = nullptr, bool my_cmd = true);
bool DoCommandP(const CommandContainer *container, bool my_cmd = true);
CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd, bool estimate_only);
diff --git a/src/command_type.h b/src/command_type.h
index 650a8987a..95b6c0d62 100644
--- a/src/command_type.h
+++ b/src/command_type.h
@@ -36,25 +36,25 @@ public:
/**
* Creates a command cost return with no cost and no error
*/
- CommandCost() : expense_type(INVALID_EXPENSES), cost(0), message(INVALID_STRING_ID), success(true), textref_stack_grffile(NULL), textref_stack_size(0) {}
+ CommandCost() : expense_type(INVALID_EXPENSES), cost(0), message(INVALID_STRING_ID), success(true), textref_stack_grffile(nullptr), textref_stack_size(0) {}
/**
* Creates a command return value the is failed with the given message
*/
- explicit CommandCost(StringID msg) : expense_type(INVALID_EXPENSES), cost(0), message(msg), success(false), textref_stack_grffile(NULL), textref_stack_size(0) {}
+ explicit CommandCost(StringID msg) : expense_type(INVALID_EXPENSES), cost(0), message(msg), success(false), textref_stack_grffile(nullptr), textref_stack_size(0) {}
/**
* Creates a command cost with given expense type and start cost of 0
* @param ex_t the expense type
*/
- explicit CommandCost(ExpensesType ex_t) : expense_type(ex_t), cost(0), message(INVALID_STRING_ID), success(true), textref_stack_grffile(NULL), textref_stack_size(0) {}
+ explicit CommandCost(ExpensesType ex_t) : expense_type(ex_t), cost(0), message(INVALID_STRING_ID), success(true), textref_stack_grffile(nullptr), textref_stack_size(0) {}
/**
* Creates a command return value with the given start cost and expense type
* @param ex_t the expense type
* @param cst the initial cost of this command
*/
- CommandCost(ExpensesType ex_t, const Money &cst) : expense_type(ex_t), cost(cst), message(INVALID_STRING_ID), success(true), textref_stack_grffile(NULL), textref_stack_size(0) {}
+ CommandCost(ExpensesType ex_t, const Money &cst) : expense_type(ex_t), cost(cst), message(INVALID_STRING_ID), success(true), textref_stack_grffile(nullptr), textref_stack_size(0) {}
/**
diff --git a/src/company_base.h b/src/company_base.h
index 9d2bc9000..309130f59 100644
--- a/src/company_base.h
+++ b/src/company_base.h
@@ -98,7 +98,7 @@ struct CompanyProperties {
// TODO: Change some of these member variables to use relevant INVALID_xxx constants
CompanyProperties()
- : name_2(0), name_1(0), name(NULL), president_name_1(0), president_name_2(0), president_name(NULL),
+ : name_2(0), name_1(0), name(nullptr), president_name_1(0), president_name_2(0), president_name(nullptr),
face(0), money(0), money_fraction(0), current_loan(0), colour(0), block_preview(0),
location_of_HQ(0), last_build_coordinate(0), share_owners(), inaugurated_year(0),
months_of_bankruptcy(0), bankrupt_asked(0), bankrupt_timeout(0), bankrupt_value(0),
@@ -137,7 +137,7 @@ struct Company : CompanyPool::PoolItem<&_company_pool>, CompanyProperties {
static inline bool IsValidAiID(size_t index)
{
const Company *c = Company::GetIfValid(index);
- return c != NULL && c->is_ai;
+ return c != nullptr && c->is_ai;
}
/**
@@ -149,7 +149,7 @@ struct Company : CompanyPool::PoolItem<&_company_pool>, CompanyProperties {
static inline bool IsValidHumanID(size_t index)
{
const Company *c = Company::GetIfValid(index);
- return c != NULL && !c->is_ai;
+ return c != nullptr && !c->is_ai;
}
/**
diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp
index df0588f91..3cf55cf1e 100644
--- a/src/company_cmd.cpp
+++ b/src/company_cmd.cpp
@@ -193,7 +193,7 @@ bool CheckCompanyHasMoney(CommandCost &cost)
{
if (cost.GetCost() > 0) {
const Company *c = Company::GetIfValid(_current_company);
- if (c != NULL && cost.GetCost() > c->money) {
+ if (c != nullptr && cost.GetCost() > c->money) {
SetDParam(0, cost.GetCost());
cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
return false;
@@ -239,7 +239,7 @@ static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
void SubtractMoneyFromCompany(CommandCost cost)
{
Company *c = Company::GetIfValid(_current_company);
- if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
+ if (c != nullptr) SubtractMoneyFromAnyCompany(c, cost);
}
/**
@@ -353,7 +353,7 @@ static void GenerateCompanyName(Company *c)
StringID str;
uint32 strp;
- if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
+ if (t->name == nullptr && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
strp = t->townnameparts;
@@ -539,7 +539,7 @@ void ResetCompanyLivery(Company *c)
*/
Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
{
- if (!Company::CanAllocateItem()) return NULL;
+ if (!Company::CanAllocateItem()) return nullptr;
/* we have to generate colour before this company is valid */
Colours colour = GenerateCompanyColour();
@@ -548,7 +548,7 @@ Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
if (company == INVALID_COMPANY) {
c = new Company(STR_SV_UNNAMED, is_ai);
} else {
- if (Company::IsValidID(company)) return NULL;
+ if (Company::IsValidID(company)) return nullptr;
c = new (company) Company(STR_SV_UNNAMED, is_ai);
}
@@ -670,7 +670,7 @@ static void HandleBankruptcyTakeover(Company *c)
/* Did we ask everyone for bankruptcy? If so, bail out. */
if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
- Company *c2, *best = NULL;
+ Company *c2, *best = nullptr;
int32 best_performance = -1;
/* Ask the company with the highest performance history first */
@@ -706,7 +706,7 @@ void OnTick_Companies()
if (_game_mode == GM_EDITOR) return;
Company *c = Company::GetIfValid(_cur_company_tick_index);
- if (c != NULL) {
+ if (c != nullptr) {
if (c->name_1 != 0) GenerateCompanyName(c);
if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
}
@@ -759,14 +759,14 @@ void CompaniesYearlyLoop()
/**
* Fill the CompanyNewsInformation struct with the required data.
* @param c the current company.
- * @param other the other company (use \c NULL if not relevant).
+ * @param other the other company (use \c nullptr if not relevant).
*/
void CompanyNewsInformation::FillData(const Company *c, const Company *other)
{
SetDParam(0, c->index);
GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
- if (other == NULL) {
+ if (other == nullptr) {
*this->other_company_name = '\0';
} else {
SetDParam(0, other->index);
@@ -832,8 +832,8 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
/* When replaying the client ID is not a valid client; there
* are actually no clients at all. However, the company has to
* be created, otherwise we cannot rerun the game properly.
- * So only allow a NULL client info in that case. */
- if (ci == NULL) return CommandCost();
+ * So only allow a nullptr client info in that case. */
+ if (ci == nullptr) return CommandCost();
#endif /* NOT DEBUG_DUMP_COMMANDS */
/* Delete multiplayer progress bar */
@@ -842,7 +842,7 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
Company *c = DoStartupNewCompany(false);
/* A new company could not be created, revert to being a spectator */
- if (c == NULL) {
+ if (c == nullptr) {
if (_network_server) {
ci->client_playas = COMPANY_SPECTATOR;
NetworkUpdateClientInfo(ci->client_id);
@@ -874,7 +874,7 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
Company *c = DoStartupNewCompany(true, company_id);
- if (c != NULL) NetworkServerNewCompany(c, NULL);
+ if (c != nullptr) NetworkServerNewCompany(c, nullptr);
break;
}
@@ -883,7 +883,7 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (reason >= CRR_END) return CMD_ERROR;
Company *c = Company::GetIfValid(company_id);
- if (c == NULL) return CMD_ERROR;
+ if (c == nullptr) return CMD_ERROR;
if (!(flags & DC_EXEC)) return CommandCost();
@@ -1055,7 +1055,7 @@ static bool IsUniqueCompanyName(const char *name)
const Company *c;
FOR_ALL_COMPANIES(c) {
- if (c->name != NULL && strcmp(c->name, name) == 0) return false;
+ if (c->name != nullptr && strcmp(c->name, name) == 0) return false;
}
return true;
@@ -1082,7 +1082,7 @@ CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (flags & DC_EXEC) {
Company *c = Company::Get(_current_company);
free(c->name);
- c->name = reset ? NULL : stredup(text);
+ c->name = reset ? nullptr : stredup(text);
MarkWholeScreenDirty();
CompanyAdminUpdate(c);
}
@@ -1100,7 +1100,7 @@ static bool IsUniquePresidentName(const char *name)
const Company *c;
FOR_ALL_COMPANIES(c) {
- if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
+ if (c->president_name != nullptr && strcmp(c->president_name, name) == 0) return false;
}
return true;
@@ -1129,11 +1129,11 @@ CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, u
free(c->president_name);
if (reset) {
- c->president_name = NULL;
+ c->president_name = nullptr;
} else {
c->president_name = stredup(text);
- if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
+ if (c->name_1 == STR_SV_UNNAMED && c->name == nullptr) {
char buf[80];
seprintf(buf, lastof(buf), "%s Transport", text);
@@ -1150,13 +1150,13 @@ CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, u
/**
* Get the service interval for the given company and vehicle type.
- * @param c The company, or NULL for client-default settings.
+ * @param c The company, or nullptr for client-default settings.
* @param type The vehicle type to get the interval for.
* @return The service interval.
*/
int CompanyServiceInterval(const Company *c, VehicleType type)
{
- const VehicleDefaultSettings *vds = (c == NULL) ? &_settings_client.company.vehicle : &c->settings.vehicle;
+ const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN: return vds->servint_trains;
diff --git a/src/company_gui.cpp b/src/company_gui.cpp
index 1c23a1251..ef3fcd5a3 100644
--- a/src/company_gui.cpp
+++ b/src/company_gui.cpp
@@ -569,7 +569,7 @@ private:
{
uint32 used_colours = 0;
const Company *c;
- const Livery *livery, *default_livery = NULL;
+ const Livery *livery, *default_livery = nullptr;
bool primary = widget == WID_SCL_PRI_COL_DROPDOWN;
byte default_col;
@@ -603,7 +603,7 @@ private:
}
DropDownList list;
- if (default_livery != NULL) {
+ if (default_livery != nullptr) {
/* Add COLOUR_END to put the colour out of range, but also allow us to show what the default is */
default_col = (primary ? default_livery->colour1 : default_livery->colour2) + COLOUR_END;
list.emplace_back(new DropDownListColourItem(default_col, false));
@@ -612,13 +612,13 @@ private:
list.emplace_back(new DropDownListColourItem(i, HasBit(used_colours, i)));
}
- byte sel = (default_livery == NULL || HasBit(livery->in_use, primary ? 0 : 1)) ? (primary ? livery->colour1 : livery->colour2) : default_col;
+ byte sel = (default_livery == nullptr || HasBit(livery->in_use, primary ? 0 : 1)) ? (primary ? livery->colour1 : livery->colour2) : default_col;
ShowDropDownList(this, std::move(list), sel, widget);
}
static int CDECL GroupNameSorter(const Group * const *a, const Group * const *b)
{
- static const Group *last_group[2] = { NULL, NULL };
+ static const Group *last_group[2] = { nullptr, nullptr };
static char last_name[2][64] = { "", "" };
if (*a != last_group[0]) {
@@ -1100,7 +1100,7 @@ static WindowDesc _select_company_livery_desc(
void ShowCompanyLiveryWindow(CompanyID company, GroupID group)
{
SelectCompanyLiveryWindow *w = (SelectCompanyLiveryWindow *)BringWindowToFrontById(WC_COMPANY_COLOUR, company);
- if (w == NULL) {
+ if (w == nullptr) {
new SelectCompanyLiveryWindow(&_select_company_livery_desc, company, group);
} else if (group != INVALID_GROUP) {
w->SetSelectedGroup(company, group);
@@ -1711,10 +1711,10 @@ public:
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
/* Set a new company manager face number */
if (!StrEmpty(str)) {
- this->face = strtoul(str, NULL, 10);
+ this->face = strtoul(str, nullptr, 10);
ScaleAllCompanyManagerFaceBits(this->face);
ShowErrorMessage(STR_FACE_FACECODE_SET, INVALID_STRING_ID, WL_INFO);
this->UpdateData();
@@ -2633,17 +2633,17 @@ struct CompanyWindow : Window
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
switch (this->query_widget) {
default: NOT_REACHED();
case WID_C_PRESIDENT_NAME:
- DoCommandP(0, 0, 0, CMD_RENAME_PRESIDENT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_PRESIDENT), NULL, str);
+ DoCommandP(0, 0, 0, CMD_RENAME_PRESIDENT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_PRESIDENT), nullptr, str);
break;
case WID_C_COMPANY_NAME:
- DoCommandP(0, 0, 0, CMD_RENAME_COMPANY | CMD_MSG(STR_ERROR_CAN_T_CHANGE_COMPANY_NAME), NULL, str);
+ DoCommandP(0, 0, 0, CMD_RENAME_COMPANY | CMD_MSG(STR_ERROR_CAN_T_CHANGE_COMPANY_NAME), nullptr, str);
break;
case WID_C_COMPANY_JOIN:
@@ -2796,7 +2796,7 @@ static const NWidgetPart _nested_buy_company_widgets[] = {
};
static WindowDesc _buy_company_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUY_COMPANY, WC_NONE,
WDF_CONSTRUCTION,
_nested_buy_company_widgets, lengthof(_nested_buy_company_widgets)
diff --git a/src/console.cpp b/src/console.cpp
index c7f24a9dc..eedf604ba 100644
--- a/src/console.cpp
+++ b/src/console.cpp
@@ -32,7 +32,7 @@ FILE *_iconsole_output_file;
void IConsoleInit()
{
- _iconsole_output_file = NULL;
+ _iconsole_output_file = nullptr;
_redirect_console_to_client = INVALID_CLIENT_ID;
_redirect_console_to_admin = INVALID_ADMIN_ID;
@@ -43,14 +43,14 @@ void IConsoleInit()
static void IConsoleWriteToLogFile(const char *string)
{
- if (_iconsole_output_file != NULL) {
+ if (_iconsole_output_file != nullptr) {
/* if there is an console output file ... also print it there */
const char *header = GetLogPrefix();
if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
fclose(_iconsole_output_file);
- _iconsole_output_file = NULL;
+ _iconsole_output_file = nullptr;
IConsolePrintF(CC_DEFAULT, "cannot write to log file");
}
}
@@ -58,10 +58,10 @@ static void IConsoleWriteToLogFile(const char *string)
bool CloseConsoleLogIfActive()
{
- if (_iconsole_output_file != NULL) {
+ if (_iconsole_output_file != nullptr) {
IConsolePrintF(CC_DEFAULT, "file output complete");
fclose(_iconsole_output_file);
- _iconsole_output_file = NULL;
+ _iconsole_output_file = nullptr;
return true;
}
@@ -203,22 +203,22 @@ bool GetArgumentInteger(uint32 *value, const char *arg)
template<class T>
void IConsoleAddSorted(T **base, T *item_new)
{
- if (*base == NULL) {
+ if (*base == nullptr) {
*base = item_new;
return;
}
- T *item_before = NULL;
+ T *item_before = nullptr;
T *item = *base;
/* The list is alphabetically sorted, insert the new item at the correct location */
- while (item != NULL) {
+ while (item != nullptr) {
if (strcmp(item->name, item_new->name) > 0) break; // insert here
item_before = item;
item = item->next;
}
- if (item_before == NULL) {
+ if (item_before == nullptr) {
*base = item_new;
} else {
item_before->next = item_new;
@@ -251,7 +251,7 @@ void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *
{
IConsoleCmd *item_new = MallocT<IConsoleCmd>(1);
item_new->name = RemoveUnderscores(stredup(name));
- item_new->next = NULL;
+ item_new->next = nullptr;
item_new->proc = proc;
item_new->hook = hook;
@@ -261,16 +261,16 @@ void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *
/**
* Find the command pointed to by its string
* @param name command to be found
- * @return return Cmdstruct of the found command, or NULL on failure
+ * @return return Cmdstruct of the found command, or nullptr on failure
*/
IConsoleCmd *IConsoleCmdGet(const char *name)
{
IConsoleCmd *item;
- for (item = _iconsole_cmds; item != NULL; item = item->next) {
+ for (item = _iconsole_cmds; item != nullptr; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
- return NULL;
+ return nullptr;
}
/**
@@ -280,7 +280,7 @@ IConsoleCmd *IConsoleCmdGet(const char *name)
*/
void IConsoleAliasRegister(const char *name, const char *cmd)
{
- if (IConsoleAliasGet(name) != NULL) {
+ if (IConsoleAliasGet(name) != nullptr) {
IConsoleError("an alias with this name already exists; insertion aborted");
return;
}
@@ -289,7 +289,7 @@ void IConsoleAliasRegister(const char *name, const char *cmd)
char *cmd_aliased = stredup(cmd);
IConsoleAlias *item_new = MallocT<IConsoleAlias>(1);
- item_new->next = NULL;
+ item_new->next = nullptr;
item_new->cmdline = cmd_aliased;
item_new->name = new_alias;
@@ -299,17 +299,17 @@ void IConsoleAliasRegister(const char *name, const char *cmd)
/**
* Find the alias pointed to by its string
* @param name alias to be found
- * @return return Aliasstruct of the found alias, or NULL on failure
+ * @return return Aliasstruct of the found alias, or nullptr on failure
*/
IConsoleAlias *IConsoleAliasGet(const char *name)
{
IConsoleAlias *item;
- for (item = _iconsole_aliases; item != NULL; item = item->next) {
+ for (item = _iconsole_aliases; item != nullptr; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
- return NULL;
+ return nullptr;
}
/**
* An alias is just another name for a command, or for more commands
@@ -478,7 +478,7 @@ void IConsoleCmdExec(const char *cmdstr)
}
}
- for (uint i = 0; i < lengthof(tokens) && tokens[i] != NULL; i++) {
+ for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
}
@@ -489,12 +489,12 @@ void IConsoleCmdExec(const char *cmdstr)
*/
RemoveUnderscores(tokens[0]);
IConsoleCmd *cmd = IConsoleCmdGet(tokens[0]);
- if (cmd != NULL) {
- ConsoleHookResult chr = (cmd->hook == NULL ? CHR_ALLOW : cmd->hook(true));
+ if (cmd != nullptr) {
+ ConsoleHookResult chr = (cmd->hook == nullptr ? CHR_ALLOW : cmd->hook(true));
switch (chr) {
case CHR_ALLOW:
if (!cmd->proc(t_index, tokens)) { // index started with 0
- cmd->proc(0, NULL); // if command failed, give help
+ cmd->proc(0, nullptr); // if command failed, give help
}
return;
@@ -505,7 +505,7 @@ void IConsoleCmdExec(const char *cmdstr)
t_index--;
IConsoleAlias *alias = IConsoleAliasGet(tokens[0]);
- if (alias != NULL) {
+ if (alias != nullptr) {
IConsoleAliasExec(alias, t_index, &tokens[1]);
return;
}
diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp
index 7a7d4827d..2b74f1d00 100644
--- a/src/console_cmds.cpp
+++ b/src/console_cmds.cpp
@@ -349,7 +349,7 @@ DEF_CONSOLE_CMD(ConLoad)
const char *file = argv[1];
_console_file_list.ValidateFileList();
const FiosItem *item = _console_file_list.FindItem(file);
- if (item != NULL) {
+ if (item != nullptr) {
if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
_switch_mode = SM_LOAD_GAME;
_file_to_saveload.SetMode(item->type);
@@ -378,7 +378,7 @@ DEF_CONSOLE_CMD(ConRemove)
const char *file = argv[1];
_console_file_list.ValidateFileList();
const FiosItem *item = _console_file_list.FindItem(file);
- if (item != NULL) {
+ if (item != nullptr) {
if (!FiosDelete(item->name)) {
IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file);
}
@@ -420,7 +420,7 @@ DEF_CONSOLE_CMD(ConChangeDirectory)
const char *file = argv[1];
_console_file_list.ValidateFileList(true);
const FiosItem *item = _console_file_list.FindItem(file);
- if (item != NULL) {
+ if (item != nullptr) {
switch (item->type) {
case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
FiosBrowseTo(item);
@@ -448,7 +448,7 @@ DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
_console_file_list.ValidateFileList(true);
_console_file_list.InvalidateFileList();
- FiosGetDescText(&path, NULL);
+ FiosGetDescText(&path, nullptr);
IConsolePrint(CC_DEFAULT, path);
return true;
}
@@ -474,7 +474,7 @@ static bool ConKickOrBan(const char *argv, bool ban)
{
uint n;
- if (strchr(argv, '.') == NULL && strchr(argv, ':') == NULL) { // banning with ID
+ if (strchr(argv, '.') == nullptr && strchr(argv, ':') == nullptr) { // banning with ID
ClientID client_id = (ClientID)atoi(argv);
/* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
@@ -487,7 +487,7 @@ static bool ConKickOrBan(const char *argv, bool ban)
}
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci == NULL) {
+ if (ci == nullptr) {
IConsoleError("Invalid client");
return true;
}
@@ -688,7 +688,7 @@ DEF_CONSOLE_CMD(ConClientNickChange)
return true;
}
- if (NetworkClientInfo::GetByClientID(client_id) == NULL) {
+ if (NetworkClientInfo::GetByClientID(client_id) == nullptr) {
IConsoleError("Invalid client");
return true;
}
@@ -759,7 +759,7 @@ DEF_CONSOLE_CMD(ConMoveClient)
CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
/* check the client exists */
- if (ci == NULL) {
+ if (ci == nullptr) {
IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
return true;
}
@@ -887,8 +887,8 @@ DEF_CONSOLE_CMD(ConNetworkConnect)
if (argc < 2) return false;
if (_networking) NetworkDisconnect(); // we are in network-mode, first close it!
- const char *port = NULL;
- const char *company = NULL;
+ const char *port = nullptr;
+ const char *company = nullptr;
char *ip = argv[1];
/* Default settings: default port and new company */
uint16 rport = NETWORK_DEFAULT_PORT;
@@ -897,7 +897,7 @@ DEF_CONSOLE_CMD(ConNetworkConnect)
ParseConnectionString(&company, &port, ip);
IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip);
- if (company != NULL) {
+ if (company != nullptr) {
join_as = (CompanyID)atoi(company);
IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as);
@@ -908,7 +908,7 @@ DEF_CONSOLE_CMD(ConNetworkConnect)
join_as--;
}
}
- if (port != NULL) {
+ if (port != nullptr) {
rport = atoi(port);
IConsolePrintF(CC_DEFAULT, " port: %s", port);
}
@@ -933,7 +933,7 @@ DEF_CONSOLE_CMD(ConExec)
FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
- if (script_file == NULL) {
+ if (script_file == nullptr) {
if (argc == 2 || atoi(argv[2]) != 0) IConsoleError("script file not found");
return true;
}
@@ -941,7 +941,7 @@ DEF_CONSOLE_CMD(ConExec)
_script_running = true;
char cmdline[ICON_CMDLN_SIZE];
- while (_script_running && fgets(cmdline, sizeof(cmdline), script_file) != NULL) {
+ while (_script_running && fgets(cmdline, sizeof(cmdline), script_file) != nullptr) {
/* Remove newline characters from the executing script */
for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
if (*cmdptr == '\n' || *cmdptr == '\r') {
@@ -992,7 +992,7 @@ DEF_CONSOLE_CMD(ConScript)
IConsolePrintF(CC_DEFAULT, "file output started to: %s", argv[1]);
_iconsole_output_file = fopen(argv[1], "ab");
- if (_iconsole_output_file == NULL) IConsoleError("could not open file");
+ if (_iconsole_output_file == nullptr) IConsoleError("could not open file");
}
return true;
@@ -1031,7 +1031,7 @@ DEF_CONSOLE_CMD(ConNewGame)
return true;
}
- StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], NULL, 10) : GENERATE_NEW_SEED);
+ StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], nullptr, 10) : GENERATE_NEW_SEED);
return true;
}
@@ -1283,7 +1283,7 @@ DEF_CONSOLE_CMD(ConRescanNewGRF)
return true;
}
- ScanNewGRFFiles(NULL);
+ ScanNewGRFFiles(nullptr);
return true;
}
@@ -1326,7 +1326,7 @@ DEF_CONSOLE_CMD(ConAlias)
if (argc < 3) return false;
alias = IConsoleAliasGet(argv[1]);
- if (alias == NULL) {
+ if (alias == nullptr) {
IConsoleAliasRegister(argv[1], argv[2]);
} else {
free(alias->cmdline);
@@ -1348,7 +1348,7 @@ DEF_CONSOLE_CMD(ConScreenShot)
if (argc > 3) return false;
ScreenshotType type = SC_VIEWPORT;
- const char *name = NULL;
+ const char *name = nullptr;
if (argc > 1) {
if (strcmp(argv[1], "big") == 0) {
@@ -1386,7 +1386,7 @@ DEF_CONSOLE_CMD(ConInfoCmd)
if (argc < 2) return false;
const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
- if (cmd == NULL) {
+ if (cmd == nullptr) {
IConsoleError("the given command was not found");
return true;
}
@@ -1394,7 +1394,7 @@ DEF_CONSOLE_CMD(ConInfoCmd)
IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
- if (cmd->hook != NULL) IConsoleWarning("command is hooked");
+ if (cmd->hook != nullptr) IConsoleWarning("command is hooked");
return true;
}
@@ -1452,16 +1452,16 @@ DEF_CONSOLE_CMD(ConHelp)
RemoveUnderscores(argv[1]);
cmd = IConsoleCmdGet(argv[1]);
- if (cmd != NULL) {
- cmd->proc(0, NULL);
+ if (cmd != nullptr) {
+ cmd->proc(0, nullptr);
return true;
}
alias = IConsoleAliasGet(argv[1]);
- if (alias != NULL) {
+ if (alias != nullptr) {
cmd = IConsoleCmdGet(alias->cmdline);
- if (cmd != NULL) {
- cmd->proc(0, NULL);
+ if (cmd != nullptr) {
+ cmd->proc(0, nullptr);
return true;
}
IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
@@ -1491,9 +1491,9 @@ DEF_CONSOLE_CMD(ConListCommands)
return true;
}
- for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != NULL; cmd = cmd->next) {
- if (argv[1] == NULL || strstr(cmd->name, argv[1]) != NULL) {
- if (cmd->hook == NULL || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
+ for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != nullptr; cmd = cmd->next) {
+ if (argv[1] == nullptr || strstr(cmd->name, argv[1]) != nullptr) {
+ if (cmd->hook == nullptr || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
}
}
@@ -1507,8 +1507,8 @@ DEF_CONSOLE_CMD(ConListAliases)
return true;
}
- for (const IConsoleAlias *alias = _iconsole_aliases; alias != NULL; alias = alias->next) {
- if (argv[1] == NULL || strstr(alias->name, argv[1]) != NULL) {
+ for (const IConsoleAlias *alias = _iconsole_aliases; alias != nullptr; alias = alias->next) {
+ if (argv[1] == nullptr || strstr(alias->name, argv[1]) != nullptr) {
IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
}
}
@@ -1717,8 +1717,8 @@ static void OutputContentState(const ContentInfo *const ci)
DEF_CONSOLE_CMD(ConContent)
{
- static ContentCallback *cb = NULL;
- if (cb == NULL) {
+ static ContentCallback *cb = nullptr;
+ if (cb == nullptr) {
cb = new ConsoleContentCallback();
_network_content_client.AddCallback(cb);
}
@@ -1776,7 +1776,7 @@ DEF_CONSOLE_CMD(ConContent)
if (strcasecmp(argv[1], "state") == 0) {
IConsolePrintF(CC_WHITE, "id, type, state, name");
for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
- if (argc > 2 && strcasestr((*iter)->name, argv[2]) == NULL) continue;
+ if (argc > 2 && strcasestr((*iter)->name, argv[2]) == nullptr) continue;
OutputContentState(*iter);
}
return true;
@@ -1841,7 +1841,7 @@ DEF_CONSOLE_CMD(ConListSettings)
if (argc > 2) return false;
- IConsoleListSettings((argc == 2) ? argv[1] : NULL);
+ IConsoleListSettings((argc == 2) ? argv[1] : nullptr);
return true;
}
diff --git a/src/console_gui.cpp b/src/console_gui.cpp
index 3ee13946f..2cb02ff56 100644
--- a/src/console_gui.cpp
+++ b/src/console_gui.cpp
@@ -78,7 +78,7 @@ struct IConsoleLine {
static const IConsoleLine *Get(uint index)
{
const IConsoleLine *item = IConsoleLine::front;
- while (index != 0 && item != NULL) {
+ while (index != 0 && item != nullptr) {
index--;
item = item->previous;
}
@@ -96,14 +96,14 @@ struct IConsoleLine {
static bool Truncate()
{
IConsoleLine *cur = IConsoleLine::front;
- if (cur == NULL) return false;
+ if (cur == nullptr) return false;
int count = 1;
- for (IConsoleLine *item = cur->previous; item != NULL; count++, cur = item, item = item->previous) {
+ for (IConsoleLine *item = cur->previous; item != nullptr; count++, cur = item, item = item->previous) {
if (item->time > _settings_client.gui.console_backlog_timeout &&
count > _settings_client.gui.console_backlog_length) {
delete item;
- cur->previous = NULL;
+ cur->previous = nullptr;
return true;
}
@@ -119,12 +119,12 @@ struct IConsoleLine {
static void Reset()
{
delete IConsoleLine::front;
- IConsoleLine::front = NULL;
+ IConsoleLine::front = nullptr;
IConsoleLine::size = 0;
}
};
-/* static */ IConsoleLine *IConsoleLine::front = NULL;
+/* static */ IConsoleLine *IConsoleLine::front = nullptr;
/* static */ int IConsoleLine::size = 0;
@@ -162,7 +162,7 @@ static const struct NWidgetPart _nested_console_window_widgets[] = {
};
static WindowDesc _console_window_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_CONSOLE, WC_NONE,
0,
_nested_console_window_widgets, lengthof(_nested_console_window_widgets)
@@ -207,7 +207,7 @@ struct IConsoleWindow : Window
GfxFillRect(0, 0, this->width - 1, this->height - 1, PC_BLACK);
int ypos = this->height - this->line_height;
- for (const IConsoleLine *print = IConsoleLine::Get(IConsoleWindow::scroll); print != NULL; print = print->previous) {
+ for (const IConsoleLine *print = IConsoleLine::Get(IConsoleWindow::scroll); print != nullptr; print = print->previous) {
SetDParamStr(0, print->buffer);
ypos = DrawStringMultiLine(5, right, -this->line_height, ypos, STR_JUST_RAW_STRING, print->colour, SA_LEFT | SA_BOTTOM | SA_FORCE) - ICON_LINE_SPACING;
if (ypos < 0) break;
@@ -287,7 +287,7 @@ struct IConsoleWindow : Window
const char *cmd = IConsoleHistoryAdd(_iconsole_cmdline.buf);
IConsoleClearCommand();
- if (cmd != NULL) IConsoleCmdExec(cmd);
+ if (cmd != nullptr) IConsoleCmdExec(cmd);
break;
}
@@ -335,7 +335,7 @@ struct IConsoleWindow : Window
const char *GetMarkedText(size_t *length) const override
{
- if (_iconsole_cmdline.markend == 0) return NULL;
+ if (_iconsole_cmdline.markend == 0) return nullptr;
*length = _iconsole_cmdline.markend - _iconsole_cmdline.markpos;
return _iconsole_cmdline.buf + _iconsole_cmdline.markpos;
@@ -364,7 +364,7 @@ struct IConsoleWindow : Window
{
int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
- if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return NULL;
+ if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return nullptr;
return GetCharAtPosition(_iconsole_cmdline.buf, pt.x - delta);
}
@@ -459,10 +459,10 @@ static const char *IConsoleHistoryAdd(const char *cmd)
while (IsWhitespace(*cmd)) cmd++;
/* Do not put empty command in history */
- if (StrEmpty(cmd)) return NULL;
+ if (StrEmpty(cmd)) return nullptr;
/* Do not put in history if command is same as previous */
- if (_iconsole_history[0] == NULL || strcmp(_iconsole_history[0], cmd) != 0) {
+ if (_iconsole_history[0] == nullptr || strcmp(_iconsole_history[0], cmd) != 0) {
free(_iconsole_history[ICON_HISTORY_SIZE - 1]);
memmove(&_iconsole_history[1], &_iconsole_history[0], sizeof(_iconsole_history[0]) * (ICON_HISTORY_SIZE - 1));
_iconsole_history[0] = stredup(cmd);
@@ -479,10 +479,10 @@ static const char *IConsoleHistoryAdd(const char *cmd)
*/
static void IConsoleHistoryNavigate(int direction)
{
- if (_iconsole_history[0] == NULL) return; // Empty history
+ if (_iconsole_history[0] == nullptr) return; // Empty history
_iconsole_historypos = Clamp(_iconsole_historypos + direction, -1, ICON_HISTORY_SIZE - 1);
- if (direction > 0 && _iconsole_history[_iconsole_historypos] == NULL) _iconsole_historypos--;
+ if (direction > 0 && _iconsole_history[_iconsole_historypos] == nullptr) _iconsole_historypos--;
if (_iconsole_historypos == -1) {
_iconsole_cmdline.DeleteAll();
diff --git a/src/console_internal.h b/src/console_internal.h
index 1b63b26f0..4c07a96f2 100644
--- a/src/console_internal.h
+++ b/src/console_internal.h
@@ -69,7 +69,7 @@ extern IConsoleAlias *_iconsole_aliases; ///< List of registered aliases.
void IConsoleClearBuffer();
/* Commands */
-void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook = NULL);
+void IConsoleCmdRegister(const char *name, IConsoleCmdProc *proc, IConsoleHook *hook = nullptr);
void IConsoleAliasRegister(const char *name, const char *cmd);
IConsoleCmd *IConsoleCmdGet(const char *name);
IConsoleAlias *IConsoleAliasGet(const char *name);
diff --git a/src/core/alloc_func.hpp b/src/core/alloc_func.hpp
index c33e73301..c4ea1f561 100644
--- a/src/core/alloc_func.hpp
+++ b/src/core/alloc_func.hpp
@@ -53,23 +53,23 @@ static inline void CheckAllocationConstraints(size_t num_elements)
* @note the memory contains garbage data (i.e. possibly non-zero values).
* @tparam T the type of the variable(s) to allocation.
* @param num_elements the number of elements to allocate of the given type.
- * @return NULL when num_elements == 0, non-NULL otherwise.
+ * @return nullptr when num_elements == 0, non-nullptr otherwise.
*/
template <typename T>
static inline T *MallocT(size_t num_elements)
{
/*
* MorphOS cannot handle 0 elements allocations, or rather that always
- * returns NULL. So we do that for *all* allocations, thus causing it
+ * returns nullptr. So we do that for *all* allocations, thus causing it
* to behave the same on all OSes.
*/
- if (num_elements == 0) return NULL;
+ if (num_elements == 0) return nullptr;
/* Ensure the size does not overflow. */
CheckAllocationConstraints<T>(num_elements);
T *t_ptr = (T*)malloc(num_elements * sizeof(T));
- if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
+ if (t_ptr == nullptr) MallocError(num_elements * sizeof(T));
return t_ptr;
}
@@ -81,20 +81,20 @@ static inline T *MallocT(size_t num_elements)
* @note the memory contains all zero values.
* @tparam T the type of the variable(s) to allocation.
* @param num_elements the number of elements to allocate of the given type.
- * @return NULL when num_elements == 0, non-NULL otherwise.
+ * @return nullptr when num_elements == 0, non-nullptr otherwise.
*/
template <typename T>
static inline T *CallocT(size_t num_elements)
{
/*
* MorphOS cannot handle 0 elements allocations, or rather that always
- * returns NULL. So we do that for *all* allocations, thus causing it
+ * returns nullptr. So we do that for *all* allocations, thus causing it
* to behave the same on all OSes.
*/
- if (num_elements == 0) return NULL;
+ if (num_elements == 0) return nullptr;
T *t_ptr = (T*)calloc(num_elements, sizeof(T));
- if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
+ if (t_ptr == nullptr) MallocError(num_elements * sizeof(T));
return t_ptr;
}
@@ -107,26 +107,26 @@ static inline T *CallocT(size_t num_elements)
* @tparam T the type of the variable(s) to allocation.
* @param t_ptr the previous allocation to extend/shrink.
* @param num_elements the number of elements to allocate of the given type.
- * @return NULL when num_elements == 0, non-NULL otherwise.
+ * @return nullptr when num_elements == 0, non-nullptr otherwise.
*/
template <typename T>
static inline T *ReallocT(T *t_ptr, size_t num_elements)
{
/*
* MorphOS cannot handle 0 elements allocations, or rather that always
- * returns NULL. So we do that for *all* allocations, thus causing it
+ * returns nullptr. So we do that for *all* allocations, thus causing it
* to behave the same on all OSes.
*/
if (num_elements == 0) {
free(t_ptr);
- return NULL;
+ return nullptr;
}
/* Ensure the size does not overflow. */
CheckAllocationConstraints<T>(num_elements);
t_ptr = (T*)realloc(static_cast<void *>(t_ptr), num_elements * sizeof(T));
- if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
+ if (t_ptr == nullptr) ReallocError(num_elements * sizeof(T));
return t_ptr;
}
diff --git a/src/core/alloc_type.hpp b/src/core/alloc_type.hpp
index 5ea812b0e..685ff9890 100644
--- a/src/core/alloc_type.hpp
+++ b/src/core/alloc_type.hpp
@@ -73,7 +73,7 @@ private:
public:
/** Create a new buffer */
- ReusableBuffer() : buffer(NULL), count(0) {}
+ ReusableBuffer() : buffer(nullptr), count(0) {}
/** Clear the buffer */
~ReusableBuffer() { free(this->buffer); }
diff --git a/src/core/kdtree.hpp b/src/core/kdtree.hpp
index 154f27fc5..c7f66ebff 100644
--- a/src/core/kdtree.hpp
+++ b/src/core/kdtree.hpp
@@ -108,11 +108,11 @@ class Kdtree {
std::vector<T> elements = this->FreeSubtree(this->root);
elements.push_back(root_element);
- if (include_element != NULL) {
+ if (include_element != nullptr) {
elements.push_back(*include_element);
initial_count++;
}
- if (exclude_element != NULL) {
+ if (exclude_element != nullptr) {
typename std::vector<T>::iterator removed = std::remove(elements.begin(), elements.end(), *exclude_element);
elements.erase(removed, elements.end());
initial_count--;
@@ -377,7 +377,7 @@ public:
*/
void Rebuild()
{
- this->Rebuild(NULL, NULL);
+ this->Rebuild(nullptr, nullptr);
}
/**
@@ -390,7 +390,7 @@ public:
if (this->Count() == 0) {
this->root = this->AddNode(element);
} else {
- if (!this->IsUnbalanced() || !this->Rebuild(&element, NULL)) {
+ if (!this->IsUnbalanced() || !this->Rebuild(&element, nullptr)) {
this->InsertRecursive(element, this->root, 0);
this->IncrementUnbalanced();
}
@@ -408,7 +408,7 @@ public:
{
size_t count = this->Count();
if (count == 0) return;
- if (!this->IsUnbalanced() || !this->Rebuild(NULL, &element)) {
+ if (!this->IsUnbalanced() || !this->Rebuild(nullptr, &element)) {
/* If the removed element is the root node, this modifies this->root */
this->root = this->RemoveRecursive(element, this->root, 0);
this->IncrementUnbalanced();
diff --git a/src/core/mem_func.hpp b/src/core/mem_func.hpp
index 687871164..5b3fe4cab 100644
--- a/src/core/mem_func.hpp
+++ b/src/core/mem_func.hpp
@@ -78,7 +78,7 @@ static inline int MemCmpT(const T *ptr1, const T *ptr2, size_t num = 1)
template <typename T>
static inline void MemReverseT(T *ptr1, T *ptr2)
{
- assert(ptr1 != NULL && ptr2 != NULL);
+ assert(ptr1 != nullptr && ptr2 != nullptr);
assert(ptr1 < ptr2);
do {
@@ -95,7 +95,7 @@ static inline void MemReverseT(T *ptr1, T *ptr2)
template <typename T>
static inline void MemReverseT(T *ptr, size_t num)
{
- assert(ptr != NULL);
+ assert(ptr != nullptr);
MemReverseT(ptr, ptr + (num - 1));
}
diff --git a/src/core/pool_func.hpp b/src/core/pool_func.hpp
index 64af17564..ee4999286 100644
--- a/src/core/pool_func.hpp
+++ b/src/core/pool_func.hpp
@@ -39,8 +39,8 @@ DEFINE_POOL_METHOD(inline)::Pool(const char *name) :
checked(0),
#endif /* OTTD_ASSERT */
cleaning(false),
- data(NULL),
- alloc_cache(NULL)
+ data(nullptr),
+ alloc_cache(nullptr)
{ }
/**
@@ -71,7 +71,7 @@ DEFINE_POOL_METHOD(inline size_t)::FindFirstFree()
size_t index = this->first_free;
for (; index < this->first_unused; index++) {
- if (this->data[index] == NULL) return index;
+ if (this->data[index] == nullptr) return index;
}
if (index < this->size) {
@@ -96,17 +96,17 @@ DEFINE_POOL_METHOD(inline size_t)::FindFirstFree()
* @param size size of item
* @param index index of item
* @pre index < this->size
- * @pre this->Get(index) == NULL
+ * @pre this->Get(index) == nullptr
*/
DEFINE_POOL_METHOD(inline void *)::AllocateItem(size_t size, size_t index)
{
- assert(this->data[index] == NULL);
+ assert(this->data[index] == nullptr);
this->first_unused = max(this->first_unused, index + 1);
this->items++;
Titem *item;
- if (Tcache && this->alloc_cache != NULL) {
+ if (Tcache && this->alloc_cache != nullptr) {
assert(sizeof(Titem) == size);
item = (Titem *)this->alloc_cache;
this->alloc_cache = this->alloc_cache->next;
@@ -164,7 +164,7 @@ DEFINE_POOL_METHOD(void *)::GetNew(size_t size, size_t index)
if (index >= this->size) this->ResizeFor(index);
- if (this->data[index] != NULL) {
+ if (this->data[index] != nullptr) {
SlErrorCorruptFmt("%s index " PRINTF_SIZE " already in use", this->name, index);
}
@@ -174,13 +174,13 @@ DEFINE_POOL_METHOD(void *)::GetNew(size_t size, size_t index)
/**
* Deallocates memory used by this index and marks item as free
* @param index item to deallocate
- * @pre unit is allocated (non-NULL)
- * @note 'delete NULL' doesn't cause call of this function, so it is safe
+ * @pre unit is allocated (non-nullptr)
+ * @note 'delete nullptr' doesn't cause call of this function, so it is safe
*/
DEFINE_POOL_METHOD(void)::FreeItem(size_t index)
{
assert(index < this->size);
- assert(this->data[index] != NULL);
+ assert(this->data[index] != nullptr);
if (Tcache) {
AllocCache *ac = (AllocCache *)this->data[index];
ac->next = this->alloc_cache;
@@ -188,7 +188,7 @@ DEFINE_POOL_METHOD(void)::FreeItem(size_t index)
} else {
free(this->data[index]);
}
- this->data[index] = NULL;
+ this->data[index] = nullptr;
this->first_free = min(this->first_free, index);
this->items--;
if (!this->cleaning) Titem::PostDestructor(index);
@@ -199,16 +199,16 @@ DEFINE_POOL_METHOD(void)::CleanPool()
{
this->cleaning = true;
for (size_t i = 0; i < this->first_unused; i++) {
- delete this->Get(i); // 'delete NULL;' is very valid
+ delete this->Get(i); // 'delete nullptr;' is very valid
}
assert(this->items == 0);
free(this->data);
this->first_unused = this->first_free = this->size = 0;
- this->data = NULL;
+ this->data = nullptr;
this->cleaning = false;
if (Tcache) {
- while (this->alloc_cache != NULL) {
+ while (this->alloc_cache != nullptr) {
AllocCache *ac = this->alloc_cache;
this->alloc_cache = ac->next;
free(ac);
diff --git a/src/core/pool_type.hpp b/src/core/pool_type.hpp
index 38f314ebb..61dd29213 100644
--- a/src/core/pool_type.hpp
+++ b/src/core/pool_type.hpp
@@ -91,7 +91,7 @@ struct Pool : PoolBase {
size_t size; ///< Current allocated size
size_t first_free; ///< No item with index lower than this is free (doesn't say anything about this one!)
size_t first_unused; ///< This and all higher indexes are free (doesn't say anything about first_unused-1 !)
- size_t items; ///< Number of used indexes (non-NULL)
+ size_t items; ///< Number of used indexes (non-nullptr)
#ifdef OTTD_ASSERT
size_t checked; ///< Number of items we checked for
#endif /* OTTD_ASSERT */
@@ -115,13 +115,13 @@ struct Pool : PoolBase {
}
/**
- * Tests whether given index can be used to get valid (non-NULL) Titem
+ * Tests whether given index can be used to get valid (non-nullptr) Titem
* @param index index to examine
- * @return true if PoolItem::Get(index) will return non-NULL pointer
+ * @return true if PoolItem::Get(index) will return non-nullptr pointer
*/
inline bool IsValidID(size_t index)
{
- return index < this->first_unused && this->Get(index) != NULL;
+ return index < this->first_unused && this->Get(index) != nullptr;
}
/**
@@ -150,7 +150,7 @@ struct Pool : PoolBase {
* Allocates space for new Titem
* @param size size of Titem
* @return pointer to allocated memory
- * @note can never fail (return NULL), use CanAllocate() to check first!
+ * @note can never fail (return nullptr), use CanAllocate() to check first!
*/
inline void *operator new(size_t size)
{
@@ -164,7 +164,7 @@ struct Pool : PoolBase {
*/
inline void operator delete(void *p)
{
- if (p == NULL) return;
+ if (p == nullptr) return;
Titem *pn = (Titem *)p;
assert(pn == Tpool->Get(pn->index));
Tpool->FreeItem(pn->index);
@@ -175,7 +175,7 @@ struct Pool : PoolBase {
* @param size size of Titem
* @param index index of item
* @return pointer to allocated memory
- * @note can never fail (return NULL), use CanAllocate() to check first!
+ * @note can never fail (return nullptr), use CanAllocate() to check first!
* @pre index has to be unused! Else it will crash
*/
inline void *operator new(size_t size, size_t index)
@@ -228,9 +228,9 @@ struct Pool : PoolBase {
}
/**
- * Tests whether given index can be used to get valid (non-NULL) Titem
+ * Tests whether given index can be used to get valid (non-nullptr) Titem
* @param index index to examine
- * @return true if PoolItem::Get(index) will return non-NULL pointer
+ * @return true if PoolItem::Get(index) will return non-nullptr pointer
*/
static inline bool IsValidID(size_t index)
{
@@ -252,11 +252,11 @@ struct Pool : PoolBase {
* Returns Titem with given index
* @param index of item to get
* @return pointer to Titem
- * @note returns NULL for invalid index
+ * @note returns nullptr for invalid index
*/
static inline Titem *GetIfValid(size_t index)
{
- return index < Tpool->first_unused ? Tpool->Get(index) : NULL;
+ return index < Tpool->first_unused ? Tpool->Get(index) : nullptr;
}
/**
@@ -282,7 +282,7 @@ struct Pool : PoolBase {
* Dummy function called after destructor of each member.
* If you want to use it, override it in PoolItem's subclass.
* @param index index of deleted item
- * @note when this function is called, PoolItem::Get(index) == NULL.
+ * @note when this function is called, PoolItem::Get(index) == nullptr.
* @note it's called only when !CleaningPool()
*/
static inline void PostDestructor(size_t index) { }
@@ -314,8 +314,8 @@ private:
};
#define FOR_ALL_ITEMS_FROM(type, iter, var, start) \
- for (size_t iter = start; var = NULL, iter < type::GetPoolSize(); iter++) \
- if ((var = type::Get(iter)) != NULL)
+ for (size_t iter = start; var = nullptr, iter < type::GetPoolSize(); iter++) \
+ if ((var = type::Get(iter)) != nullptr)
#define FOR_ALL_ITEMS(type, iter, var) FOR_ALL_ITEMS_FROM(type, iter, var, 0)
diff --git a/src/core/smallmatrix_type.hpp b/src/core/smallmatrix_type.hpp
index cd4dee4e3..faa531d5f 100644
--- a/src/core/smallmatrix_type.hpp
+++ b/src/core/smallmatrix_type.hpp
@@ -46,13 +46,13 @@ protected:
public:
- SmallMatrix() : data(NULL), width(0), height(0), capacity(0) {}
+ SmallMatrix() : data(nullptr), width(0), height(0), capacity(0) {}
/**
* Copy constructor.
* @param other The other matrix to copy.
*/
- SmallMatrix(const SmallMatrix &other) : data(NULL), width(0), height(0), capacity(0)
+ SmallMatrix(const SmallMatrix &other) : data(nullptr), width(0), height(0), capacity(0)
{
this->Assign(other);
}
@@ -112,7 +112,7 @@ public:
this->width = 0;
this->capacity = 0;
free(this->data);
- this->data = NULL;
+ this->data = nullptr;
}
/**
@@ -216,8 +216,8 @@ public:
inline void Resize(uint new_width, uint new_height)
{
uint new_capacity = new_width * new_height;
- T *new_data = NULL;
- void (*copy)(T *dest, const T *src, size_t count) = NULL;
+ T *new_data = nullptr;
+ void (*copy)(T *dest, const T *src, size_t count) = nullptr;
if (new_capacity > this->capacity) {
/* If the data doesn't fit into current capacity, resize and copy ... */
new_data = MallocT<T>(new_capacity);
diff --git a/src/core/sort_func.hpp b/src/core/sort_func.hpp
index f3ac73a66..d557d24bd 100644
--- a/src/core/sort_func.hpp
+++ b/src/core/sort_func.hpp
@@ -53,8 +53,8 @@ static inline void GSortT(T *base, size_t num, int (CDECL *comparator)(const T*,
{
if (num < 2) return;
- assert(base != NULL);
- assert(comparator != NULL);
+ assert(base != nullptr);
+ assert(comparator != nullptr);
T *a = base;
T *b = base + 1;
diff --git a/src/crashlog.cpp b/src/crashlog.cpp
index add5c5204..531b5c64c 100644
--- a/src/crashlog.cpp
+++ b/src/crashlog.cpp
@@ -70,9 +70,9 @@
#include "safeguards.h"
-/* static */ const char *CrashLog::message = NULL;
-/* static */ char *CrashLog::gamelog_buffer = NULL;
-/* static */ const char *CrashLog::gamelog_last = NULL;
+/* static */ const char *CrashLog::message = nullptr;
+/* static */ char *CrashLog::gamelog_buffer = nullptr;
+/* static */ const char *CrashLog::gamelog_last = nullptr;
char *CrashLog::LogCompiler(char *buffer, const char *last) const
{
@@ -168,18 +168,18 @@ char *CrashLog::LogConfiguration(char *buffer, const char *last) const
" Sound driver: %s\n"
" Sound set: %s (%u)\n"
" Video driver: %s\n\n",
- BlitterFactory::GetCurrentBlitter() == NULL ? "none" : BlitterFactory::GetCurrentBlitter()->GetName(),
- BaseGraphics::GetUsedSet() == NULL ? "none" : BaseGraphics::GetUsedSet()->name,
- BaseGraphics::GetUsedSet() == NULL ? UINT32_MAX : BaseGraphics::GetUsedSet()->version,
- _current_language == NULL ? "none" : _current_language->file,
- MusicDriver::GetInstance() == NULL ? "none" : MusicDriver::GetInstance()->GetName(),
- BaseMusic::GetUsedSet() == NULL ? "none" : BaseMusic::GetUsedSet()->name,
- BaseMusic::GetUsedSet() == NULL ? UINT32_MAX : BaseMusic::GetUsedSet()->version,
+ BlitterFactory::GetCurrentBlitter() == nullptr ? "none" : BlitterFactory::GetCurrentBlitter()->GetName(),
+ BaseGraphics::GetUsedSet() == nullptr ? "none" : BaseGraphics::GetUsedSet()->name,
+ BaseGraphics::GetUsedSet() == nullptr ? UINT32_MAX : BaseGraphics::GetUsedSet()->version,
+ _current_language == nullptr ? "none" : _current_language->file,
+ MusicDriver::GetInstance() == nullptr ? "none" : MusicDriver::GetInstance()->GetName(),
+ BaseMusic::GetUsedSet() == nullptr ? "none" : BaseMusic::GetUsedSet()->name,
+ BaseMusic::GetUsedSet() == nullptr ? UINT32_MAX : BaseMusic::GetUsedSet()->version,
_networking ? (_network_server ? "server" : "client") : "no",
- SoundDriver::GetInstance() == NULL ? "none" : SoundDriver::GetInstance()->GetName(),
- BaseSounds::GetUsedSet() == NULL ? "none" : BaseSounds::GetUsedSet()->name,
- BaseSounds::GetUsedSet() == NULL ? UINT32_MAX : BaseSounds::GetUsedSet()->version,
- VideoDriver::GetInstance() == NULL ? "none" : VideoDriver::GetInstance()->GetName()
+ SoundDriver::GetInstance() == nullptr ? "none" : SoundDriver::GetInstance()->GetName(),
+ BaseSounds::GetUsedSet() == nullptr ? "none" : BaseSounds::GetUsedSet()->name,
+ BaseSounds::GetUsedSet() == nullptr ? UINT32_MAX : BaseSounds::GetUsedSet()->version,
+ VideoDriver::GetInstance() == nullptr ? "none" : VideoDriver::GetInstance()->GetName()
);
buffer += seprintf(buffer, last,
@@ -197,14 +197,14 @@ char *CrashLog::LogConfiguration(char *buffer, const char *last) const
buffer += seprintf(buffer, last, "AI Configuration (local: %i) (current: %i):\n", (int)_local_company, (int)_current_company);
const Company *c;
FOR_ALL_COMPANIES(c) {
- if (c->ai_info == NULL) {
+ if (c->ai_info == nullptr) {
buffer += seprintf(buffer, last, " %2i: Human\n", (int)c->index);
} else {
buffer += seprintf(buffer, last, " %2i: %s (v%d)\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
}
}
- if (Game::GetInfo() != NULL) {
+ if (Game::GetInfo() != nullptr) {
buffer += seprintf(buffer, last, " GS: %s (v%d)\n", Game::GetInfo()->GetName(), Game::GetInfo()->GetVersion());
}
buffer += seprintf(buffer, last, "\n");
@@ -263,7 +263,7 @@ char *CrashLog::LogLibraries(char *buffer, const char *last) const
#endif
#ifdef WITH_PNG
- buffer += seprintf(buffer, last, " PNG: %s\n", png_get_libpng_ver(NULL));
+ buffer += seprintf(buffer, last, " PNG: %s\n", png_get_libpng_ver(nullptr));
#endif /* WITH_PNG */
#ifdef WITH_SDL
@@ -312,7 +312,7 @@ char *CrashLog::LogRecentNews(char *buffer, const char *last) const
{
buffer += seprintf(buffer, last, "Recent news messages:\n");
- for (NewsItem *news = _oldest_news; news != NULL; news = news->next) {
+ for (NewsItem *news = _oldest_news; news != nullptr; news = news->next) {
YearMonthDay ymd;
ConvertDateToYMD(news->date, &ymd);
buffer += seprintf(buffer, last, "(%i-%02i-%02i) StringID: %u, Type: %u, Ref1: %u, %u, Ref2: %u, %u\n",
@@ -331,7 +331,7 @@ char *CrashLog::LogRecentNews(char *buffer, const char *last) const
*/
char *CrashLog::FillCrashLog(char *buffer, const char *last) const
{
- time_t cur_time = time(NULL);
+ time_t cur_time = time(nullptr);
buffer += seprintf(buffer, last, "*** OpenTTD Crash Report ***\n\n");
buffer += seprintf(buffer, last, "Crash at: %s", asctime(gmtime(&cur_time)));
@@ -369,7 +369,7 @@ bool CrashLog::WriteCrashLog(const char *buffer, char *filename, const char *fil
seprintf(filename, filename_last, "%scrash.log", _personal_dir);
FILE *file = FioFOpenFile(filename, "w", NO_DIRECTORY);
- if (file == NULL) return false;
+ if (file == nullptr) return false;
size_t len = strlen(buffer);
size_t written = fwrite(buffer, 1, len, file);
@@ -396,7 +396,7 @@ bool CrashLog::WriteSavegame(char *filename, const char *filename_last) const
{
/* If the map array doesn't exist, saving will fail too. If the map got
* initialised, there is a big chance the rest is initialised too. */
- if (_m == NULL) return false;
+ if (_m == nullptr) return false;
try {
GamelogEmergency();
@@ -421,7 +421,7 @@ bool CrashLog::WriteSavegame(char *filename, const char *filename_last) const
bool CrashLog::WriteScreenshot(char *filename, const char *filename_last) const
{
/* Don't draw when we have invalid screen size */
- if (_screen.width < 1 || _screen.height < 1 || _screen.dst_ptr == NULL) return false;
+ if (_screen.width < 1 || _screen.height < 1 || _screen.dst_ptr == nullptr) return false;
bool res = MakeScreenshot(SC_CRASHLOG, "crash");
if (res) strecpy(filename, _full_screenshot_name, filename_last);
@@ -504,7 +504,7 @@ bool CrashLog::MakeCrashLog() const
*/
/* static */ void CrashLog::AfterCrashLogCleanup()
{
- if (MusicDriver::GetInstance() != NULL) MusicDriver::GetInstance()->Stop();
- if (SoundDriver::GetInstance() != NULL) SoundDriver::GetInstance()->Stop();
- if (VideoDriver::GetInstance() != NULL) VideoDriver::GetInstance()->Stop();
+ if (MusicDriver::GetInstance() != nullptr) MusicDriver::GetInstance()->Stop();
+ if (SoundDriver::GetInstance() != nullptr) SoundDriver::GetInstance()->Stop();
+ if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
}
diff --git a/src/crashlog.h b/src/crashlog.h
index b9bc8afa2..03acdc5aa 100644
--- a/src/crashlog.h
+++ b/src/crashlog.h
@@ -48,7 +48,7 @@ protected:
* Writes actually encountered error to the buffer.
* @param buffer The begin where to write at.
* @param last The last position in the buffer to write to.
- * @param message Message passed to use for possible errors. Can be NULL.
+ * @param message Message passed to use for possible errors. Can be nullptr.
* @return the position of the \c '\0' character after the buffer.
*/
virtual char *LogError(char *buffer, const char *last, const char *message) const = 0;
diff --git a/src/date_gui.cpp b/src/date_gui.cpp
index 900e42bd7..86c09087c 100644
--- a/src/date_gui.cpp
+++ b/src/date_gui.cpp
@@ -148,7 +148,7 @@ struct SetDateWindow : Window {
break;
case WID_SD_SET_DATE:
- if (this->callback != NULL) this->callback(this, ConvertYMDToDate(this->date.year, this->date.month, this->date.day));
+ if (this->callback != nullptr) this->callback(this, ConvertYMDToDate(this->date.year, this->date.month, this->date.day));
delete this;
break;
}
@@ -197,7 +197,7 @@ static const NWidgetPart _nested_set_date_widgets[] = {
/** Description of the date setting window. */
static WindowDesc _set_date_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_SET_DATE, WC_NONE,
0,
_nested_set_date_widgets, lengthof(_nested_set_date_widgets)
diff --git a/src/debug.cpp b/src/debug.cpp
index 422f73038..c300c9fac 100644
--- a/src/debug.cpp
+++ b/src/debug.cpp
@@ -120,14 +120,14 @@ static void debug_print(const char *dbg, const char *buf)
}
if (strcmp(dbg, "desync") == 0) {
static FILE *f = FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR);
- if (f == NULL) return;
+ if (f == nullptr) return;
fprintf(f, "%s%s\n", GetLogPrefix(), buf);
fflush(f);
#ifdef RANDOM_DEBUG
} else if (strcmp(dbg, "random") == 0) {
static FILE *f = FioFOpenFile("random-out.log", "wb", AUTOSAVE_DIR);
- if (f == NULL) return;
+ if (f == nullptr) return;
fprintf(f, "%s\n", buf);
fflush(f);
@@ -200,7 +200,7 @@ void SetDebugString(const char *s)
while (*s >= 'a' && *s <= 'z') s++;
/* check debugging levels */
- p = NULL;
+ p = nullptr;
for (i = debug_level; i != endof(debug_level); ++i) {
if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
p = i->level;
@@ -211,7 +211,7 @@ void SetDebugString(const char *s)
if (*s == '=') s++;
v = strtoul(s, &end, 0);
s = end;
- if (p != NULL) {
+ if (p != nullptr) {
*p = v;
} else {
ShowInfoF("Unknown debug level '%.*s'", (int)(s - t), t);
@@ -246,13 +246,13 @@ const char *GetDebugString()
/**
* Get the prefix for logs; if show_date_in_logs is enabled it returns
* the date, otherwise it returns nothing.
- * @return the prefix for logs (do not free), never NULL
+ * @return the prefix for logs (do not free), never nullptr
*/
const char *GetLogPrefix()
{
static char _log_prefix[24];
if (_settings_client.gui.show_date_in_logs) {
- time_t cur_time = time(NULL);
+ time_t cur_time = time(nullptr);
strftime(_log_prefix, sizeof(_log_prefix), "[%Y-%m-%d %H:%M:%S] ", localtime(&cur_time));
} else {
*_log_prefix = '\0';
diff --git a/src/dedicated.cpp b/src/dedicated.cpp
index 141a91720..2ceab0752 100644
--- a/src/dedicated.cpp
+++ b/src/dedicated.cpp
@@ -11,8 +11,8 @@
#include "stdafx.h"
-char *_log_file = NULL; ///< File to reroute output of a forked OpenTTD to
-FILE *_log_fd = NULL; ///< File to reroute output of a forked OpenTTD to
+char *_log_file = nullptr; ///< File to reroute output of a forked OpenTTD to
+FILE *_log_fd = nullptr; ///< File to reroute output of a forked OpenTTD to
#if defined(UNIX)
@@ -41,7 +41,7 @@ void DedicatedFork()
case 0: { // We're the child
/* Open the log-file to log all stuff too */
_log_fd = fopen(_log_file, "a");
- if (_log_fd == NULL) {
+ if (_log_fd == nullptr) {
perror("Unable to open logfile");
exit(1);
}
diff --git a/src/depend/depend.cpp b/src/depend/depend.cpp
index 9f8de891b..76c186265 100644
--- a/src/depend/depend.cpp
+++ b/src/depend/depend.cpp
@@ -54,7 +54,7 @@
*
* Copies the source string to the destination buffer with respect of the
* terminating null-character and the last pointer to the last element in
- * the destination buffer. If the last pointer is set to NULL no boundary
+ * the destination buffer. If the last pointer is set to nullptr no boundary
* check is performed.
*
* @note usage: strecpy(dst, src, lastof(dst));
@@ -85,7 +85,7 @@ char *strecpy(char *dst, const char *src, const char *last)
*
* Appends the source string to the destination string with respect of the
* terminating null-character and and the last pointer to the last element
- * in the destination buffer. If the last pointer is set to NULL no
+ * in the destination buffer. If the last pointer is set to nullptr no
* boundary check is performed.
*
* @note usage: strecat(dst, src, lastof(dst));
@@ -163,13 +163,13 @@ public:
File(const char *filename)
{
this->fp = fopen(filename, "r");
- if (this->fp == NULL) {
+ if (this->fp == nullptr) {
fprintf(stdout, "Could not open %s for reading\n", filename);
exit(1);
}
this->dirname = strdup(filename);
char *last = strrchr(this->dirname, '/');
- if (last != NULL) {
+ if (last != nullptr) {
*last = '\0';
} else {
*this->dirname = '\0';
@@ -247,7 +247,7 @@ public:
* Create the lexer and fill the keywords table.
* @param file the file to read from.
*/
- Lexer(const File *file) : file(file), current_char('\0'), string(NULL), token(TOKEN_UNKNOWN)
+ Lexer(const File *file) : file(file), current_char('\0'), string(nullptr), token(TOKEN_UNKNOWN)
{
this->keywords["define"] = TOKEN_DEFINE;
this->keywords["defined"] = TOKEN_DEFINED;
@@ -293,7 +293,7 @@ public:
/**
* Read the currenty processed string.
- * @return the string, can be NULL.
+ * @return the string, can be nullptr.
*/
const char *GetString() const
{
@@ -308,7 +308,7 @@ public:
{
for (;;) {
free(this->string);
- this->string = NULL;
+ this->string = nullptr;
this->token = TOKEN_UNKNOWN;
switch (this->current_char) {
@@ -503,7 +503,7 @@ private:
* @param dirname the directory to look in.
* @param filename the file to look for.
* @param local whether to look locally (in dirname) for the file.
- * @return the absolute path, or NULL if the file doesn't exist.
+ * @return the absolute path, or nullptr if the file doesn't exist.
*/
const char *GeneratePath(const char *dirname, const char *filename, bool local)
{
@@ -517,7 +517,7 @@ const char *GeneratePath(const char *dirname, const char *filename, bool local)
while (*p == '.') {
if (*(++p) == '.') {
char *s = strrchr(path, '/');
- if (s != NULL) *s = '\0';
+ if (s != nullptr) *s = '\0';
p += 2;
}
}
@@ -535,7 +535,7 @@ const char *GeneratePath(const char *dirname, const char *filename, bool local)
while (*p == '.') {
if (*(++p) == '.') {
char *s = strrchr(path, '/');
- if (s != NULL) *s = '\0';
+ if (s != nullptr) *s = '\0';
p += 2;
}
}
@@ -545,7 +545,7 @@ const char *GeneratePath(const char *dirname, const char *filename, bool local)
if (access(path, R_OK) == 0) return strdup(path);
}
- return NULL;
+ return nullptr;
}
/**
@@ -730,7 +730,7 @@ void ScanFile(const char *filename, const char *ext, bool header, bool verbose)
break;
}
const char *h = GeneratePath(file.GetDirname(), lexer.GetString(), lexer.GetToken() == TOKEN_LOCAL);
- if (h != NULL) {
+ if (h != nullptr) {
StringMap::iterator it = _headers.find(h);
if (it == _headers.end()) {
it = (_headers.insert(StringMapItem(strdup(h), new StringSet()))).first;
@@ -745,7 +745,7 @@ void ScanFile(const char *filename, const char *ext, bool header, bool verbose)
char path[PATH_MAX];
strecpy(path, filename, lastof(path));
*(strrchr(path, '.')) = '\0';
- strecat(path, ext != NULL ? ext : ".o", lastof(path));
+ strecat(path, ext != nullptr ? ext : ".o", lastof(path));
curfile = _files.find(path);
if (curfile == _files.end()) {
curfile = (_files.insert(StringMapItem(strdup(path), new StringSet()))).first;
@@ -909,9 +909,9 @@ void ScanFile(const char *filename, const char *ext, bool header, bool verbose)
int main(int argc, char *argv[])
{
bool ignorenext = true;
- char *filename = NULL;
- char *ext = NULL;
- char *delimiter = NULL;
+ char *filename = nullptr;
+ char *ext = nullptr;
+ char *delimiter = nullptr;
bool append = false;
bool verbose = false;
@@ -936,25 +936,25 @@ int main(int argc, char *argv[])
/* Define */
if (strncmp(argv[i], "-D", 2) == 0) {
char *p = strchr(argv[i], '=');
- if (p != NULL) *p = '\0';
+ if (p != nullptr) *p = '\0';
_defines.insert(strdup(&argv[i][2]));
continue;
}
/* Output file */
if (strncmp(argv[i], "-f", 2) == 0) {
- if (filename != NULL) continue;
+ if (filename != nullptr) continue;
filename = strdup(&argv[i][2]);
continue;
}
/* Object file extension */
if (strncmp(argv[i], "-o", 2) == 0) {
- if (ext != NULL) continue;
+ if (ext != nullptr) continue;
ext = strdup(&argv[i][2]);
continue;
}
/* Starting string delimiter */
if (strncmp(argv[i], "-s", 2) == 0) {
- if (delimiter != NULL) continue;
+ if (delimiter != nullptr) continue;
delimiter = strdup(&argv[i][2]);
continue;
}
@@ -966,22 +966,22 @@ int main(int argc, char *argv[])
}
/* Default output file is Makefile */
- if (filename == NULL) filename = strdup("Makefile");
+ if (filename == nullptr) filename = strdup("Makefile");
/* Default delimiter string */
- if (delimiter == NULL) delimiter = strdup("# DO NOT DELETE");
+ if (delimiter == nullptr) delimiter = strdup("# DO NOT DELETE");
char backup[PATH_MAX];
strecpy(backup, filename, lastof(backup));
strecat(backup, ".bak", lastof(backup));
- char *content = NULL;
+ char *content = nullptr;
long size = 0;
/* Read in the current file; so we can overwrite everything from the
* end of non-depend data marker down till the end. */
FILE *src = fopen(filename, "rb");
- if (src != NULL) {
+ if (src != nullptr) {
fseek(src, 0, SEEK_END);
if ((size = ftell(src)) < 0) {
fprintf(stderr, "Could not read %s\n", filename);
@@ -1009,7 +1009,7 @@ int main(int argc, char *argv[])
/* Then append it to the real file. */
src = fopen(backup, "r");
- while (fgets(content, size, src) != NULL) {
+ while (fgets(content, size, src) != nullptr) {
fputs(content, dst);
if (!strncmp(content, delimiter, strlen(delimiter))) found_delimiter = true;
if (!append && found_delimiter) break;
diff --git a/src/depot_cmd.cpp b/src/depot_cmd.cpp
index 5101b7c2c..710878b28 100644
--- a/src/depot_cmd.cpp
+++ b/src/depot_cmd.cpp
@@ -33,7 +33,7 @@ static bool IsUniqueDepotName(const char *name)
const Depot *d;
FOR_ALL_DEPOTS(d) {
- if (d->name != NULL && strcmp(d->name, name) == 0) return false;
+ if (d->name != nullptr && strcmp(d->name, name) == 0) return false;
}
return true;
@@ -51,7 +51,7 @@ static bool IsUniqueDepotName(const char *name)
CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Depot *d = Depot::GetIfValid(p1);
- if (d == NULL) return CMD_ERROR;
+ if (d == nullptr) return CMD_ERROR;
CommandCost ret = CheckTileOwnership(d->xy);
if (ret.Failed()) return ret;
@@ -67,7 +67,7 @@ CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
free(d->name);
if (reset) {
- d->name = NULL;
+ d->name = nullptr;
MakeDefaultName(d);
} else {
d->name = stredup(text);
diff --git a/src/depot_gui.cpp b/src/depot_gui.cpp
index ffab68536..021195127 100644
--- a/src/depot_gui.cpp
+++ b/src/depot_gui.cpp
@@ -133,16 +133,16 @@ static void TrainDepotMoveVehicle(const Vehicle *wagon, VehicleID sel, const Veh
if (v == wagon) return;
- if (wagon == NULL) {
- if (head != NULL) wagon = head->Last();
+ if (wagon == nullptr) {
+ if (head != nullptr) wagon = head->Last();
} else {
wagon = wagon->Previous();
- if (wagon == NULL) return;
+ if (wagon == nullptr) return;
}
if (wagon == v) return;
- DoCommandP(v->tile, v->index | (_ctrl_pressed ? 1 : 0) << 20, wagon == NULL ? INVALID_VEHICLE : wagon->index, CMD_MOVE_RAIL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_MOVE_VEHICLE));
+ DoCommandP(v->tile, v->index | (_ctrl_pressed ? 1 : 0) << 20, wagon == nullptr ? INVALID_VEHICLE : wagon->index, CMD_MOVE_RAIL_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_MOVE_VEHICLE));
}
static VehicleCellSize _base_block_sizes_depot[VEH_COMPANY_END]; ///< Cell size for vehicle images in the depot view.
@@ -228,7 +228,7 @@ void InitDepotWindowBlockSizes()
if (!e->IsEnabled()) continue;
uint w = TRAININFO_DEFAULT_VEHICLE_WIDTH;
- if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
+ if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
w = e->GetGRF()->traininfo_vehicle_width;
if (w != VEHICLEINFO_FULL_VEHICLE_WIDTH) {
/* Hopeless.
@@ -279,7 +279,7 @@ struct DepotWindow : Window {
this->unitnumber_digits = 2;
this->CreateNestedTree();
- this->hscroll = (this->type == VEH_TRAIN ? this->GetScrollbar(WID_D_H_SCROLL) : NULL);
+ this->hscroll = (this->type == VEH_TRAIN ? this->GetScrollbar(WID_D_H_SCROLL) : nullptr);
this->vscroll = this->GetScrollbar(WID_D_V_SCROLL);
/* Don't show 'rename button' of aircraft hangar */
this->GetWidget<NWidgetStacked>(WID_D_SHOW_RENAME)->SetDisplayedPlane(type == VEH_AIRCRAFT ? SZSP_NONE : 0);
@@ -469,8 +469,8 @@ struct DepotWindow : Window {
/* Clicking on 'line' / 'block' without a vehicle */
if (this->type == VEH_TRAIN) {
/* End the dragging */
- d->head = NULL;
- d->wagon = NULL;
+ d->head = nullptr;
+ d->wagon = nullptr;
return MODE_DRAG_VEHICLE;
} else {
return MODE_ERROR; // empty block, so no vehicle is selected
@@ -490,7 +490,7 @@ struct DepotWindow : Window {
wagon = true;
}
- const Train *v = NULL;
+ const Train *v = nullptr;
if (this->type == VEH_TRAIN) {
v = Train::From(*veh);
d->head = d->wagon = v;
@@ -525,12 +525,12 @@ struct DepotWindow : Window {
x -= this->header_width;
/* find the vehicle in this row that was clicked */
- for (; v != NULL; v = v->Next()) {
+ for (; v != nullptr; v = v->Next()) {
x -= v->GetDisplayImageWidth();
if (x < 0) break;
}
- d->wagon = (v != NULL ? v->GetFirstEnginePart() : NULL);
+ d->wagon = (v != nullptr ? v->GetFirstEnginePart() : nullptr);
return MODE_DRAG_VEHICLE;
}
@@ -542,8 +542,8 @@ struct DepotWindow : Window {
*/
void DepotClick(int x, int y)
{
- GetDepotVehiclePtData gdvp = { NULL, NULL };
- const Vehicle *v = NULL;
+ GetDepotVehiclePtData gdvp = { nullptr, nullptr };
+ const Vehicle *v = nullptr;
DepotGUIAction mode = this->GetVehicleFromDepotWndPt(x, y, &v, &gdvp);
if (this->type == VEH_TRAIN) v = gdvp.wagon;
@@ -553,14 +553,14 @@ struct DepotWindow : Window {
return;
case MODE_DRAG_VEHICLE: { // start dragging of vehicle
- if (v != NULL && VehicleClicked(v)) return;
+ if (v != nullptr && VehicleClicked(v)) return;
VehicleID sel = this->sel;
if (this->type == VEH_TRAIN && sel != INVALID_VEHICLE) {
this->sel = INVALID_VEHICLE;
TrainDepotMoveVehicle(v, sel, gdvp.head);
- } else if (v != NULL) {
+ } else if (v != nullptr) {
SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
SetMouseCursorVehicle(v, EIT_IN_DEPOT);
_cursor.vehchain = _ctrl_pressed;
@@ -728,7 +728,7 @@ struct DepotWindow : Window {
uint max_width = ScaleGUITrad(VEHICLEINFO_FULL_VEHICLE_WIDTH);
for (uint num = 0; num < this->vehicle_list.size(); num++) {
uint width = 0;
- for (const Train *v = Train::From(this->vehicle_list[num]); v != NULL; v = v->Next()) {
+ for (const Train *v = Train::From(this->vehicle_list[num]); v != nullptr; v = v->Next()) {
width += v->GetDisplayImageWidth();
}
max_width = max(max_width, width);
@@ -839,24 +839,24 @@ struct DepotWindow : Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
/* Do depot renaming */
- DoCommandP(0, GetDepotIndex(this->window_number), 0, CMD_RENAME_DEPOT | CMD_MSG(STR_ERROR_CAN_T_RENAME_DEPOT), NULL, str);
+ DoCommandP(0, GetDepotIndex(this->window_number), 0, CMD_RENAME_DEPOT | CMD_MSG(STR_ERROR_CAN_T_RENAME_DEPOT), nullptr, str);
}
bool OnRightClick(Point pt, int widget) override
{
if (widget != WID_D_MATRIX) return false;
- GetDepotVehiclePtData gdvp = { NULL, NULL };
- const Vehicle *v = NULL;
+ GetDepotVehiclePtData gdvp = { nullptr, nullptr };
+ const Vehicle *v = nullptr;
NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_D_MATRIX);
DepotGUIAction mode = this->GetVehicleFromDepotWndPt(pt.x - nwi->pos_x, pt.y - nwi->pos_y, &v, &gdvp);
if (this->type == VEH_TRAIN) v = gdvp.wagon;
- if (v == NULL || mode != MODE_DRAG_VEHICLE) return false;
+ if (v == nullptr || mode != MODE_DRAG_VEHICLE) return false;
CargoArray capacity, loaded;
@@ -865,7 +865,7 @@ struct DepotWindow : Window {
/* loop through vehicle chain and collect cargoes */
uint num = 0;
- for (const Vehicle *w = v; w != NULL; w = w->Next()) {
+ for (const Vehicle *w = v; w != nullptr; w = w->Next()) {
if (w->cargo_cap > 0 && w->cargo_type < NUM_CARGO) {
capacity[w->cargo_type] += w->cargo_cap;
loaded [w->cargo_type] += w->cargo.StoredCount();
@@ -910,7 +910,7 @@ struct DepotWindow : Window {
{
if (_ctrl_pressed) {
/* Share-clone, do not open new viewport, and keep tool active */
- DoCommandP(this->window_number, v->index, 1, CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN + v->type), NULL);
+ DoCommandP(this->window_number, v->index, 1, CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN + v->type), nullptr);
} else {
/* Copy-clone, open viewport for new vehicle, and deselect the tool (assume player wants to changs things on new vehicle) */
if (DoCommandP(this->window_number, v->index, 0, CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN + v->type), CcCloneVehicle)) {
@@ -965,20 +965,20 @@ struct DepotWindow : Window {
}
NWidgetBase *matrix = this->GetWidget<NWidgetBase>(widget);
- const Vehicle *v = NULL;
- GetDepotVehiclePtData gdvp = {NULL, NULL};
+ const Vehicle *v = nullptr;
+ GetDepotVehiclePtData gdvp = {nullptr, nullptr};
if (this->GetVehicleFromDepotWndPt(pt.x - matrix->pos_x, pt.y - matrix->pos_y, &v, &gdvp) != MODE_DRAG_VEHICLE) return;
VehicleID new_vehicle_over = INVALID_VEHICLE;
- if (gdvp.head != NULL) {
- if (gdvp.wagon == NULL && gdvp.head->Last()->index != this->sel) { // ..at the end of the train.
+ if (gdvp.head != nullptr) {
+ if (gdvp.wagon == nullptr && gdvp.head->Last()->index != this->sel) { // ..at the end of the train.
/* NOTE: As a wagon can't be moved at the begin of a train, head index isn't used to mark a drag-and-drop
* destination inside a train. This head index is then used to indicate that a wagon is inserted at
* the end of the train.
*/
new_vehicle_over = gdvp.head->index;
- } else if (gdvp.wagon != NULL && gdvp.head != gdvp.wagon &&
+ } else if (gdvp.wagon != nullptr && gdvp.head != gdvp.wagon &&
gdvp.wagon->index != this->sel &&
gdvp.wagon->Previous()->index != this->sel) { // ..over an existing wagon.
new_vehicle_over = gdvp.wagon->index;
@@ -995,7 +995,7 @@ struct DepotWindow : Window {
{
switch (widget) {
case WID_D_MATRIX: {
- const Vehicle *v = NULL;
+ const Vehicle *v = nullptr;
VehicleID sel = this->sel;
this->sel = INVALID_VEHICLE;
@@ -1003,20 +1003,20 @@ struct DepotWindow : Window {
NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_D_MATRIX);
if (this->type == VEH_TRAIN) {
- GetDepotVehiclePtData gdvp = { NULL, NULL };
+ GetDepotVehiclePtData gdvp = { nullptr, nullptr };
if (this->GetVehicleFromDepotWndPt(pt.x - nwi->pos_x, pt.y - nwi->pos_y, &v, &gdvp) == MODE_DRAG_VEHICLE && sel != INVALID_VEHICLE) {
- if (gdvp.wagon != NULL && gdvp.wagon->index == sel && _ctrl_pressed) {
+ if (gdvp.wagon != nullptr && gdvp.wagon->index == sel && _ctrl_pressed) {
DoCommandP(Vehicle::Get(sel)->tile, Vehicle::Get(sel)->index, true,
CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE));
- } else if (gdvp.wagon == NULL || gdvp.wagon->index != sel) {
+ } else if (gdvp.wagon == nullptr || gdvp.wagon->index != sel) {
this->vehicle_over = INVALID_VEHICLE;
TrainDepotMoveVehicle(gdvp.wagon, sel, gdvp.head);
- } else if (gdvp.head != NULL && gdvp.head->IsFrontEngine()) {
+ } else if (gdvp.head != nullptr && gdvp.head->IsFrontEngine()) {
ShowVehicleViewWindow(gdvp.head);
}
}
- } else if (this->GetVehicleFromDepotWndPt(pt.x - nwi->pos_x, pt.y - nwi->pos_y, &v, NULL) == MODE_DRAG_VEHICLE && v != NULL && sel == v->index) {
+ } else if (this->GetVehicleFromDepotWndPt(pt.x - nwi->pos_x, pt.y - nwi->pos_y, &v, nullptr) == MODE_DRAG_VEHICLE && v != nullptr && sel == v->index) {
ShowVehicleViewWindow(v);
}
break;
@@ -1052,7 +1052,7 @@ struct DepotWindow : Window {
this->RaiseWidget(WID_D_SELL);
this->SetWidgetDirty(WID_D_SELL);
}
- if (this->nested_array[WID_D_SELL] != NULL && !this->IsWidgetDisabled(WID_D_SELL_CHAIN)) {
+ if (this->nested_array[WID_D_SELL] != nullptr && !this->IsWidgetDisabled(WID_D_SELL_CHAIN)) {
this->RaiseWidget(WID_D_SELL_CHAIN);
this->SetWidgetDirty(WID_D_SELL_CHAIN);
}
@@ -1098,7 +1098,7 @@ static void DepotSellAllConfirmationCallback(Window *win, bool confirmed)
*/
void ShowDepotWindow(TileIndex tile, VehicleType type)
{
- if (BringWindowToFrontById(WC_VEHICLE_DEPOT, tile) != NULL) return;
+ if (BringWindowToFrontById(WC_VEHICLE_DEPOT, tile) != nullptr) return;
WindowDesc *desc;
switch (type) {
@@ -1126,7 +1126,7 @@ void DeleteDepotHighlightOfVehicle(const Vehicle *v)
if (_special_mouse_mode != WSM_DRAGDROP) return;
w = dynamic_cast<DepotWindow*>(FindWindowById(WC_VEHICLE_DEPOT, v->tile));
- if (w != NULL) {
+ if (w != nullptr) {
if (w->sel == v->index) ResetObjectToPlace();
}
}
diff --git a/src/disaster_vehicle.cpp b/src/disaster_vehicle.cpp
index 64ebcd3fa..f934ca3e6 100644
--- a/src/disaster_vehicle.cpp
+++ b/src/disaster_vehicle.cpp
@@ -137,11 +137,11 @@ DisasterVehicle::DisasterVehicle(int x, int y, Direction direction, DisasterSubT
case ST_HELICOPTER:
case ST_BIG_UFO:
case ST_BIG_UFO_DESTROYER:
- GetAircraftFlightLevelBounds(this, &this->z_pos, NULL);
+ GetAircraftFlightLevelBounds(this, &this->z_pos, nullptr);
break;
case ST_HELICOPTER_ROTORS:
- GetAircraftFlightLevelBounds(this, &this->z_pos, NULL);
+ GetAircraftFlightLevelBounds(this, &this->z_pos, nullptr);
this->z_pos += ROTOR_Z_OFFSET;
break;
@@ -190,7 +190,7 @@ void DisasterVehicle::UpdatePosition(int x, int y, int z)
this->UpdatePositionAndViewport();
DisasterVehicle *u = this->Next();
- if (u != NULL) {
+ if (u != nullptr) {
int safe_x = Clamp(x, 0, MapMaxX() * TILE_SIZE);
int safe_y = Clamp(y - 1, 0, MapMaxY() * TILE_SIZE);
@@ -203,7 +203,7 @@ void DisasterVehicle::UpdatePosition(int x, int y, int z)
u->UpdateImage();
u->UpdatePositionAndViewport();
- if ((u = u->Next()) != NULL) {
+ if ((u = u->Next()) != nullptr) {
u->x_pos = x;
u->y_pos = y;
u->z_pos = z + ROTOR_Z_OFFSET;
@@ -357,7 +357,7 @@ static bool DisasterTick_Ufo(DisasterVehicle *v)
} else {
/* Target a vehicle */
RoadVehicle *u = RoadVehicle::Get(v->dest_tile);
- assert(u != NULL && u->type == VEH_ROAD && u->IsFrontEngine());
+ assert(u != nullptr && u->type == VEH_ROAD && u->IsFrontEngine());
uint dist = Delta(v->x_pos, u->x_pos) + Delta(v->y_pos, u->y_pos);
@@ -748,16 +748,16 @@ static void Disaster_Airplane_Init()
{
if (!Vehicle::CanAllocateItem(2)) return;
- Industry *i, *found = NULL;
+ Industry *i, *found = nullptr;
FOR_ALL_INDUSTRIES(i) {
if ((GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_AIRPLANE_ATTACKS) &&
- (found == NULL || Chance16(1, 2))) {
+ (found == nullptr || Chance16(1, 2))) {
found = i;
}
}
- if (found == NULL) return;
+ if (found == nullptr) return;
/* Start from the bottom (south side) of the map */
int x = (MapSizeX() + 9) * TILE_SIZE - 1;
@@ -774,16 +774,16 @@ static void Disaster_Helicopter_Init()
{
if (!Vehicle::CanAllocateItem(3)) return;
- Industry *i, *found = NULL;
+ Industry *i, *found = nullptr;
FOR_ALL_INDUSTRIES(i) {
if ((GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_CHOPPER_ATTACKS) &&
- (found == NULL || Chance16(1, 2))) {
+ (found == nullptr || Chance16(1, 2))) {
found = i;
}
}
- if (found == NULL) return;
+ if (found == nullptr) return;
int x = -16 * (int)TILE_SIZE;
int y = TileY(found->location.tile) * TILE_SIZE + 37;
@@ -966,7 +966,7 @@ void ReleaseDisastersTargetingVehicle(VehicleID vehicle)
/* Revert to target-searching */
v->current_order.SetDestination(0);
v->dest_tile = RandomTile();
- GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
+ GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
v->age = 0;
}
}
diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp
index f5ebd1f7f..95989dc03 100644
--- a/src/dock_gui.cpp
+++ b/src/dock_gui.cpp
@@ -60,7 +60,7 @@ void CcPlaySound_SPLAT_WATER(const CommandCost &result, TileIndex tile, uint32 p
* @param[out] tile_to The tile till where to show a selection for the aqueduct.
* @return The other end of the aqueduct, or otherwise a tile in line with the aqueduct to cause the right error message.
*/
-static TileIndex GetOtherAqueductEnd(TileIndex tile_from, TileIndex *tile_to = NULL)
+static TileIndex GetOtherAqueductEnd(TileIndex tile_from, TileIndex *tile_to = nullptr)
{
int z;
DiagDirection dir = GetInclinedSlopeDirection(GetTileSlope(tile_from, &z));
@@ -83,7 +83,7 @@ static TileIndex GetOtherAqueductEnd(TileIndex tile_from, TileIndex *tile_to = N
if (length > max_length) break;
if (GetTileMaxZ(endtile) > z) {
- if (tile_to != NULL) *tile_to = endtile;
+ if (tile_to != nullptr) *tile_to = endtile;
break;
}
}
@@ -287,7 +287,7 @@ static EventState DockToolbarGlobalHotkeys(int hotkey)
{
if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
Window *w = ShowBuildDocksToolbar();
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -341,11 +341,11 @@ static WindowDesc _build_docks_toolbar_desc(
*
* If the terraform toolbar is linked to the toolbar, that window is also opened.
*
- * @return newly opened water toolbar, or NULL if the toolbar could not be opened.
+ * @return newly opened water toolbar, or nullptr if the toolbar could not be opened.
*/
Window *ShowBuildDocksToolbar()
{
- if (!Company::IsValidID(_local_company)) return NULL;
+ if (!Company::IsValidID(_local_company)) return nullptr;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
return AllocateWindowDescFront<BuildDocksToolbarWindow>(&_build_docks_toolbar_desc, TRANSPORT_WATER);
@@ -382,7 +382,7 @@ static WindowDesc _build_docks_scen_toolbar_desc(
/**
* Open the build water toolbar window for the scenario editor.
*
- * @return newly opened water toolbar, or NULL if the toolbar could not be opened.
+ * @return newly opened water toolbar, or nullptr if the toolbar could not be opened.
*/
Window *ShowBuildDocksScenToolbar()
{
@@ -475,7 +475,7 @@ static const NWidgetPart _nested_build_dock_station_widgets[] = {
};
static WindowDesc _build_dock_station_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUILD_STATION, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_build_dock_station_widgets, lengthof(_nested_build_dock_station_widgets)
@@ -568,7 +568,7 @@ static const NWidgetPart _nested_build_docks_depot_widgets[] = {
};
static WindowDesc _build_docks_depot_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_build_docks_depot_widgets, lengthof(_nested_build_docks_depot_widgets)
diff --git a/src/driver.cpp b/src/driver.cpp
index 825c489b9..390fb381e 100644
--- a/src/driver.cpp
+++ b/src/driver.cpp
@@ -41,10 +41,10 @@ const char *GetDriverParam(const char * const *parm, const char *name)
{
size_t len;
- if (parm == NULL) return NULL;
+ if (parm == nullptr) return nullptr;
len = strlen(name);
- for (; *parm != NULL; parm++) {
+ for (; *parm != nullptr; parm++) {
const char *p = *parm;
if (strncmp(p, name, len) == 0) {
@@ -52,7 +52,7 @@ const char *GetDriverParam(const char * const *parm, const char *name)
if (p[len] == '\0') return p + len;
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -63,7 +63,7 @@ const char *GetDriverParam(const char * const *parm, const char *name)
*/
bool GetDriverParamBool(const char * const *parm, const char *name)
{
- return GetDriverParam(parm, name) != NULL;
+ return GetDriverParam(parm, name) != nullptr;
}
/**
@@ -76,7 +76,7 @@ bool GetDriverParamBool(const char * const *parm, const char *name)
int GetDriverParamInt(const char * const *parm, const char *name, int def)
{
const char *p = GetDriverParam(parm, name);
- return p != NULL ? atoi(p) : def;
+ return p != nullptr ? atoi(p) : def;
}
/**
@@ -120,8 +120,8 @@ bool DriverFactoryBase::SelectDriverImpl(const char *name, Driver::Type type)
Driver *newd = d->CreateInstance();
*GetActiveDriver(type) = newd;
- const char *err = newd->Start(NULL);
- if (err == NULL) {
+ const char *err = newd->Start(nullptr);
+ if (err == nullptr) {
DEBUG(driver, 1, "Successfully probed %s driver '%s'", GetDriverTypeName(type), d->name);
delete oldd;
return true;
@@ -141,8 +141,8 @@ bool DriverFactoryBase::SelectDriverImpl(const char *name, Driver::Type type)
/* Extract the driver name and put parameter list in parm */
strecpy(buffer, name, lastof(buffer));
parm = strchr(buffer, ':');
- parms[0] = NULL;
- if (parm != NULL) {
+ parms[0] = nullptr;
+ if (parm != nullptr) {
uint np = 0;
/* Tokenize the parm. */
do {
@@ -150,7 +150,7 @@ bool DriverFactoryBase::SelectDriverImpl(const char *name, Driver::Type type)
if (np < lengthof(parms) - 1) parms[np++] = parm;
while (*parm != '\0' && *parm != ',') parm++;
} while (*parm == ',');
- parms[np] = NULL;
+ parms[np] = nullptr;
}
/* Find this driver */
@@ -168,7 +168,7 @@ bool DriverFactoryBase::SelectDriverImpl(const char *name, Driver::Type type)
Driver *newd = d->CreateInstance();
const char *err = newd->Start(parms);
- if (err != NULL) {
+ if (err != nullptr) {
delete newd;
usererror("Unable to load driver '%s'. The error was: %s", d->name, err);
}
diff --git a/src/driver.h b/src/driver.h
index 12ca4474d..af387b5d8 100644
--- a/src/driver.h
+++ b/src/driver.h
@@ -26,7 +26,7 @@ public:
/**
* Start this driver.
* @param parm Parameters passed to the driver.
- * @return NULL if everything went okay, otherwise an error message.
+ * @return nullptr if everything went okay, otherwise an error message.
*/
virtual const char *Start(const char * const *parm) = 0;
@@ -86,7 +86,7 @@ private:
*/
static Driver **GetActiveDriver(Driver::Type type)
{
- static Driver *s_driver[3] = { NULL, NULL, NULL };
+ static Driver *s_driver[3] = { nullptr, nullptr, nullptr };
return &s_driver[type];
}
@@ -116,7 +116,7 @@ public:
{
for (Driver::Type dt = Driver::DT_BEGIN; dt < Driver::DT_END; dt++) {
Driver *driver = *GetActiveDriver(dt);
- if (driver != NULL) driver->Stop();
+ if (driver != nullptr) driver->Stop();
}
}
diff --git a/src/economy.cpp b/src/economy.cpp
index 07dec815a..8fc717956 100644
--- a/src/economy.cpp
+++ b/src/economy.cpp
@@ -401,7 +401,7 @@ void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
FOR_ALL_VEHICLES(v) {
if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
if (new_owner == INVALID_OWNER) {
- if (v->Previous() == NULL) delete v;
+ if (v->Previous() == nullptr) delete v;
} else {
if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
@@ -476,7 +476,7 @@ void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
}
/* Invalidate the vehicle's cargo payment "owner cache". */
- if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
+ if (v->cargo_payment != nullptr) v->cargo_payment->owner = nullptr;
}
}
@@ -959,7 +959,7 @@ Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift
if (index >= PR_END) return 0;
Money cost = _price[index] * cost_factor;
- if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
+ if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
if (shift >= 0) {
cost <<= shift;
@@ -1180,7 +1180,7 @@ CargoPayment::~CargoPayment()
{
if (this->CleaningPool()) return;
- this->front->cargo_payment = NULL;
+ this->front->cargo_payment = nullptr;
if (this->visual_profit == 0 && this->visual_transfer == 0) return;
@@ -1211,7 +1211,7 @@ CargoPayment::~CargoPayment()
*/
void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
{
- if (this->owner == NULL) {
+ if (this->owner == nullptr) {
this->owner = Company::Get(this->front->owner);
}
@@ -1259,7 +1259,7 @@ void PrepareUnload(Vehicle *front_v)
/* Start unloading at the first possible moment */
front_v->load_unload_ticks = 1;
- assert(front_v->cargo_payment == NULL);
+ assert(front_v->cargo_payment == nullptr);
/* One CargoPayment per vehicle and the vehicle limit equals the
* limit in number of CargoPayments. Can't go wrong. */
assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
@@ -1267,9 +1267,9 @@ void PrepareUnload(Vehicle *front_v)
front_v->cargo_payment = new CargoPayment(front_v);
StationIDStack next_station = front_v->GetNextStoppingStation();
- if (front_v->orders.list == NULL || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
+ if (front_v->orders.list == nullptr || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
Station *st = Station::Get(front_v->last_station_visited);
- for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
+ for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
const GoodsEntry *ge = &st->goods[v->cargo_type];
if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
v->cargo.Stage(
@@ -1300,7 +1300,7 @@ static uint GetLoadAmount(Vehicle *v)
if (_settings_game.order.gradual_loading) {
uint16 cb_load_amount = CALLBACK_FAILED;
- if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
+ if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
/* Use callback 36 */
cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
} else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
@@ -1336,8 +1336,8 @@ static uint GetLoadAmount(Vehicle *v)
template<class Taction>
bool IterateVehicleParts(Vehicle *v, Taction action)
{
- for (Vehicle *w = v; w != NULL;
- w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL) {
+ for (Vehicle *w = v; w != nullptr;
+ w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
if (!action(w)) return false;
if (w->type == VEH_TRAIN) {
Train *train = Train::From(w);
@@ -1564,8 +1564,8 @@ static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft,
/* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
* In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
* a vehicle belongs to already has the right cargo. */
- bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == NULL;
- for (Vehicle *v = u; v != NULL; v = v->Next()) {
+ bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
+ for (Vehicle *v = u; v != nullptr; v = v->Next()) {
assert(v->cargo_cap >= v->cargo.RemainingCount());
/* Exclude various ways in which the vehicle might not be the head of an equivalent of
@@ -1577,7 +1577,7 @@ static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft,
(must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
IterateVehicleParts(v, ReserveCargoAction(st, next_station));
}
- if (consist_capleft == NULL || v->cargo_cap == 0) continue;
+ if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
(*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
}
}
@@ -1618,9 +1618,9 @@ static void LoadUnloadVehicle(Vehicle *front)
bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
CargoArray consist_capleft;
if (_settings_game.order.improved_load && use_autorefit ?
- front->cargo_payment == NULL : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
+ front->cargo_payment == nullptr : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
ReserveConsist(st, front,
- (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL,
+ (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
&next_station);
}
@@ -1652,7 +1652,7 @@ static void LoadUnloadVehicle(Vehicle *front)
CargoPayment *payment = front->cargo_payment;
uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
- for (Vehicle *v = front; v != NULL; v = v->Next()) {
+ for (Vehicle *v = front; v != nullptr; v = v->Next()) {
if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
if (v->cargo_cap == 0) continue;
artic_part++;
@@ -1664,7 +1664,7 @@ static void LoadUnloadVehicle(Vehicle *front)
uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count;
bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
- assert(payment != NULL);
+ assert(payment != nullptr);
payment->SetCargo(v->cargo_type);
if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
@@ -1916,7 +1916,7 @@ void LoadUnloadStation(Station *st)
/* No vehicle is here... */
if (st->loading_vehicles.empty()) return;
- Vehicle *last_loading = NULL;
+ Vehicle *last_loading = nullptr;
std::list<Vehicle *>::iterator iter;
/* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
@@ -1936,7 +1936,7 @@ void LoadUnloadStation(Station *st)
* consist in a station which is not allowed to load yet because its
* load_unload_ticks is still not 0.
*/
- if (last_loading == NULL) return;
+ if (last_loading == nullptr) return;
for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
Vehicle *v = *iter;
@@ -2018,7 +2018,7 @@ CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1,
/* Check if buying shares is allowed (protection against modified clients)
* Cannot buy own shares */
- if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
+ if (c == nullptr || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
/* Protect new companies from hostile takeovers */
if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
@@ -2068,7 +2068,7 @@ CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1
Company *c = Company::GetIfValid(target_company);
/* Cannot sell own shares */
- if (c == NULL || _current_company == target_company) return CMD_ERROR;
+ if (c == nullptr || _current_company == target_company) return CMD_ERROR;
/* Check if selling shares is allowed (protection against modified clients).
* However, we must sell shares of companies being closed down. */
@@ -2107,7 +2107,7 @@ CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
{
CompanyID target_company = (CompanyID)p1;
Company *c = Company::GetIfValid(target_company);
- if (c == NULL) return CMD_ERROR;
+ if (c == nullptr) return CMD_ERROR;
/* Disable takeovers when not asked */
if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
diff --git a/src/effectvehicle.cpp b/src/effectvehicle.cpp
index 4d8f58acb..76c06a181 100644
--- a/src/effectvehicle.cpp
+++ b/src/effectvehicle.cpp
@@ -595,7 +595,7 @@ assert_compile(lengthof(_effect_transparency_options) == EV_END);
*/
EffectVehicle *CreateEffectVehicle(int x, int y, int z, EffectVehicleType type)
{
- if (!Vehicle::CanAllocateItem()) return NULL;
+ if (!Vehicle::CanAllocateItem()) return nullptr;
EffectVehicle *v = new EffectVehicle();
v->subtype = type;
diff --git a/src/elrail.cpp b/src/elrail.cpp
index 9fdfb57a3..b3f447ef8 100644
--- a/src/elrail.cpp
+++ b/src/elrail.cpp
@@ -82,7 +82,7 @@ static inline TLG GetTLG(TileIndex t)
/**
* Finds which Electrified Rail Bits are present on a given tile.
* @param t tile to check
- * @param override pointer to PCP override, can be NULL
+ * @param override pointer to PCP override, can be nullptr
* @return trackbits of tile if it is electrified
*/
static TrackBits GetRailTrackBitsUniversal(TileIndex t, byte *override)
@@ -101,7 +101,7 @@ static TrackBits GetRailTrackBitsUniversal(TileIndex t, byte *override)
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(t) != TRANSPORT_RAIL) return TRACK_BIT_NONE;
if (!HasRailCatenary(GetRailType(t))) return TRACK_BIT_NONE;
- if (override != NULL && (IsTunnel(t) || GetTunnelBridgeLength(t, GetOtherBridgeEnd(t)) > 0)) {
+ if (override != nullptr && (IsTunnel(t) || GetTunnelBridgeLength(t, GetOtherBridgeEnd(t)) > 0)) {
*override = 1 << GetTunnelBridgeDirection(t);
}
return DiagDirToDiagTrackBits(GetTunnelBridgeDirection(t));
@@ -326,7 +326,7 @@ static void DrawRailCatenaryRailway(const TileInfo *ti)
/* Here's one of the main headaches. GetTileSlope does not correct for possibly
* existing foundataions, so we do have to do that manually later on.*/
tileh[TS_NEIGHBOUR] = GetTileSlope(neighbour);
- trackconfig[TS_NEIGHBOUR] = GetRailTrackBitsUniversal(neighbour, NULL);
+ trackconfig[TS_NEIGHBOUR] = GetRailTrackBitsUniversal(neighbour, nullptr);
wireconfig[TS_NEIGHBOUR] = MaskWireBits(neighbour, trackconfig[TS_NEIGHBOUR]);
if (IsTunnelTile(neighbour) && i != GetTunnelBridgeDirection(neighbour)) wireconfig[TS_NEIGHBOUR] = trackconfig[TS_NEIGHBOUR] = TRACK_BIT_NONE;
diff --git a/src/engine.cpp b/src/engine.cpp
index 044faa571..3e2a7d2d7 100644
--- a/src/engine.cpp
+++ b/src/engine.cpp
@@ -69,9 +69,9 @@ assert_compile(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_i
const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];
Engine::Engine() :
- name(NULL),
+ name(nullptr),
overrides_count(0),
- overrides(NULL)
+ overrides(nullptr)
{
}
@@ -162,7 +162,7 @@ bool Engine::IsEnabled() const
uint32 Engine::GetGRFID() const
{
const GRFFile *file = this->GetGRF();
- return file == NULL ? 0 : file->grfid;
+ return file == nullptr ? 0 : file->grfid;
}
/**
@@ -199,28 +199,28 @@ bool Engine::CanCarryCargo() const
/**
* Determines capacity of a given vehicle from scratch.
* For aircraft the main capacity is determined. Mail might be present as well.
- * @param v Vehicle of interest; NULL in purchase list
+ * @param v Vehicle of interest; nullptr in purchase list
* @param mail_capacity returns secondary cargo (mail) capacity of aircraft
* @return Capacity
*/
uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
{
- assert(v == NULL || this->index == v->engine_type);
- if (mail_capacity != NULL) *mail_capacity = 0;
+ assert(v == nullptr || this->index == v->engine_type);
+ if (mail_capacity != nullptr) *mail_capacity = 0;
if (!this->CanCarryCargo()) return 0;
bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
CargoID default_cargo = this->GetDefaultCargoType();
- CargoID cargo_type = (v != NULL) ? v->cargo_type : default_cargo;
+ CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
- if (mail_capacity != NULL && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
+ if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
*mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);
}
/* Check the refit capacity callback if we are not in the default configuration, or if we are using the new multiplier algorithm. */
if (HasBit(this->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) &&
- (new_multipliers || default_cargo != cargo_type || (v != NULL && v->cargo_subtype != 0))) {
+ (new_multipliers || default_cargo != cargo_type || (v != nullptr && v->cargo_subtype != 0))) {
uint16 callback = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, this->index, v);
if (callback != CALLBACK_FAILED) return callback;
}
@@ -233,7 +233,7 @@ uint Engine::DetermineCapacity(const Vehicle *v, uint16 *mail_capacity) const
capacity = GetEngineProperty(this->index, PROP_TRAIN_CARGO_CAPACITY, this->u.rail.capacity, v);
/* In purchase list add the capacity of the second head. Always use the plain property for this. */
- if (v == NULL && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
+ if (v == nullptr && this->u.rail.railveh_type == RAILVEH_MULTIHEAD) capacity += this->u.rail.capacity;
break;
case VEH_ROAD:
@@ -869,7 +869,7 @@ void ClearEnginesHiddenFlagOfCompany(CompanyID cid)
CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Engine *e = Engine::GetIfValid(GB(p2, 0, 31));
- if (e == NULL || _current_company >= MAX_COMPANIES) return CMD_ERROR;
+ if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR;
if (!IsEngineBuildable(e->index, e->type, _current_company)) return CMD_ERROR;
if ((flags & DC_EXEC) != 0) {
@@ -893,7 +893,7 @@ CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32
CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Engine *e = Engine::GetIfValid(p1);
- if (e == NULL || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
+ if (e == nullptr || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR;
if (flags & DC_EXEC) AcceptEnginePreview(p1, _current_company);
@@ -1021,7 +1021,7 @@ static bool IsUniqueEngineName(const char *name)
const Engine *e;
FOR_ALL_ENGINES(e) {
- if (e->name != NULL && strcmp(e->name, name) == 0) return false;
+ if (e->name != nullptr && strcmp(e->name, name) == 0) return false;
}
return true;
@@ -1039,7 +1039,7 @@ static bool IsUniqueEngineName(const char *name)
CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Engine *e = Engine::GetIfValid(p1);
- if (e == NULL) return CMD_ERROR;
+ if (e == nullptr) return CMD_ERROR;
bool reset = StrEmpty(text);
@@ -1052,7 +1052,7 @@ CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
free(e->name);
if (reset) {
- e->name = NULL;
+ e->name = nullptr;
} else {
e->name = stredup(text);
}
@@ -1077,7 +1077,7 @@ bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
const Engine *e = Engine::GetIfValid(engine);
/* check if it's an engine that is in the engine array */
- if (e == NULL) return false;
+ if (e == nullptr) return false;
/* check if it's an engine of specified type */
if (e->type != type) return false;
@@ -1113,7 +1113,7 @@ bool IsEngineRefittable(EngineID engine)
const Engine *e = Engine::GetIfValid(engine);
/* check if it's an engine that is in the engine array */
- if (e == NULL) return false;
+ if (e == nullptr) return false;
if (!e->CanCarryCargo()) return false;
diff --git a/src/engine_base.h b/src/engine_base.h
index aaf88d945..ad41f52f2 100644
--- a/src/engine_base.h
+++ b/src/engine_base.h
@@ -83,7 +83,7 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
return this->info.cargo_type;
}
- uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity = NULL) const;
+ uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity = nullptr) const;
bool CanCarryCargo() const;
@@ -98,9 +98,9 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
* @return The default capacity
* @see GetDefaultCargoType
*/
- uint GetDisplayDefaultCapacity(uint16 *mail_capacity = NULL) const
+ uint GetDisplayDefaultCapacity(uint16 *mail_capacity = nullptr) const
{
- return this->DetermineCapacity(NULL, mail_capacity);
+ return this->DetermineCapacity(nullptr, mail_capacity);
}
Money GetRunningCost() const;
diff --git a/src/error.h b/src/error.h
index 597b62efb..fe1ed659e 100644
--- a/src/error.h
+++ b/src/error.h
@@ -43,7 +43,7 @@ protected:
public:
ErrorMessageData(const ErrorMessageData &data);
~ErrorMessageData();
- ErrorMessageData(StringID summary_msg, StringID detailed_msg, uint duration = 0, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = NULL, uint textref_stack_size = 0, const uint32 *textref_stack = NULL);
+ ErrorMessageData(StringID summary_msg, StringID detailed_msg, uint duration = 0, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = nullptr, uint textref_stack_size = 0, const uint32 *textref_stack = nullptr);
/** Check whether error window shall display a company manager face */
bool HasFace() const { return face != INVALID_COMPANY; }
@@ -56,7 +56,7 @@ public:
void ScheduleErrorMessage(const ErrorMessageData &data);
-void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = NULL, uint textref_stack_size = 0, const uint32 *textref_stack = NULL);
+void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x = 0, int y = 0, const GRFFile *textref_stack_grffile = nullptr, uint textref_stack_size = 0, const uint32 *textref_stack = nullptr);
void ClearErrorMessages();
void ShowFirstError();
void UnshowCriticalError();
diff --git a/src/error_gui.cpp b/src/error_gui.cpp
index 47bca2638..1fa83db16 100644
--- a/src/error_gui.cpp
+++ b/src/error_gui.cpp
@@ -76,7 +76,7 @@ ErrorMessageData::ErrorMessageData(const ErrorMessageData &data)
{
*this = data;
for (size_t i = 0; i < lengthof(this->strings); i++) {
- if (this->strings[i] != NULL) {
+ if (this->strings[i] != nullptr) {
this->strings[i] = stredup(this->strings[i]);
this->decode_params[i] = (size_t)this->strings[i];
}
@@ -357,7 +357,7 @@ void ShowFirstError()
void UnshowCriticalError()
{
ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
- if (_window_system_initialized && w != NULL) {
+ if (_window_system_initialized && w != nullptr) {
if (w->IsCritical()) _error_list.push_front(*w);
_window_system_initialized = false;
delete w;
@@ -377,7 +377,7 @@ void UnshowCriticalError()
*/
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x, int y, const GRFFile *textref_stack_grffile, uint textref_stack_size, const uint32 *textref_stack)
{
- assert(textref_stack_size == 0 || (textref_stack_grffile != NULL && textref_stack != NULL));
+ assert(textref_stack_size == 0 || (textref_stack_grffile != nullptr && textref_stack != nullptr));
if (summary_msg == STR_NULL) summary_msg = STR_EMPTY;
if (wl != WL_INFO) {
@@ -408,7 +408,7 @@ void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel
data.CopyOutDParams();
ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0);
- if (w != NULL && w->IsCritical()) {
+ if (w != nullptr && w->IsCritical()) {
/* A critical error is currently shown. */
if (wl == WL_CRITICAL) {
/* Push another critical error in the queue of errors,
diff --git a/src/fileio.cpp b/src/fileio.cpp
index caaa0fed5..6980e6d8f 100644
--- a/src/fileio.cpp
+++ b/src/fileio.cpp
@@ -99,7 +99,7 @@ void FioSeekTo(size_t pos, int mode)
static void FioRestoreFile(int slot)
{
/* Do we still have the file open, or should we reopen it? */
- if (_fio.handles[slot] == NULL) {
+ if (_fio.handles[slot] == nullptr) {
DEBUG(misc, 6, "Restoring file '%s' in slot '%d' from disk", _fio.filenames[slot], slot);
FioOpenFile(slot, _fio.filenames[slot]);
}
@@ -120,7 +120,7 @@ void FioSeekToFile(uint8 slot, size_t pos)
FioRestoreFile(slot);
#endif /* LIMITED_FDS */
f = _fio.handles[slot];
- assert(f != NULL);
+ assert(f != nullptr);
_fio.cur_fh = f;
_fio.filename = _fio.filenames[slot];
FioSeekTo(pos, SEEK_SET);
@@ -196,13 +196,13 @@ void FioReadBlock(void *ptr, size_t size)
*/
static inline void FioCloseFile(int slot)
{
- if (_fio.handles[slot] != NULL) {
+ if (_fio.handles[slot] != nullptr) {
fclose(_fio.handles[slot]);
free(_fio.shortnames[slot]);
- _fio.shortnames[slot] = NULL;
+ _fio.shortnames[slot] = nullptr;
- _fio.handles[slot] = NULL;
+ _fio.handles[slot] = nullptr;
#if defined(LIMITED_FDS)
_fio.open_handles--;
#endif /* LIMITED_FDS */
@@ -229,7 +229,7 @@ static void FioFreeHandle()
slot = -1;
/* Find the file that is used the least */
for (i = 0; i < lengthof(_fio.handles); i++) {
- if (_fio.handles[i] != NULL && _fio.usage_count[i] < count) {
+ if (_fio.handles[i] != nullptr && _fio.usage_count[i] < count) {
count = _fio.usage_count[i];
slot = i;
}
@@ -255,7 +255,7 @@ void FioOpenFile(int slot, const char *filename, Subdirectory subdir)
FioFreeHandle();
#endif /* LIMITED_FDS */
f = FioFOpenFile(filename, "rb", subdir);
- if (f == NULL) usererror("Cannot open file '%s'", filename);
+ if (f == nullptr) usererror("Cannot open file '%s'", filename);
long pos = ftell(f);
if (pos < 0) usererror("Cannot read file '%s'", filename);
@@ -265,9 +265,9 @@ void FioOpenFile(int slot, const char *filename, Subdirectory subdir)
/* Store the filename without path and extension */
const char *t = strrchr(filename, PATHSEPCHAR);
- _fio.shortnames[slot] = stredup(t == NULL ? filename : t);
+ _fio.shortnames[slot] = stredup(t == nullptr ? filename : t);
char *t2 = strrchr(_fio.shortnames[slot], '.');
- if (t2 != NULL) *t2 = '\0';
+ if (t2 != nullptr) *t2 = '\0';
strtolower(_fio.shortnames[slot]);
#if defined(LIMITED_FDS)
@@ -312,7 +312,7 @@ static TarLinkList _tar_linklist[NUM_SUBDIRS]; ///< List of directory links
bool FioCheckFileExists(const char *filename, Subdirectory subdir)
{
FILE *f = FioFOpenFile(filename, "rb", subdir);
- if (f == NULL) return false;
+ if (f == nullptr) return false;
FioFCloseFile(f);
return true;
@@ -351,7 +351,7 @@ char *FioGetFullPath(char *buf, const char *last, Searchpath sp, Subdirectory su
* @param last End of the destination buffer.
* @param subdir Subdirectory to try.
* @param filename Filename to look for.
- * @return \a buf containing the path if the path was found, else \c NULL.
+ * @return \a buf containing the path if the path was found, else \c nullptr.
*/
char *FioFindFullPath(char *buf, const char *last, Subdirectory subdir, const char *filename)
{
@@ -369,7 +369,7 @@ char *FioFindFullPath(char *buf, const char *last, Subdirectory subdir, const ch
#endif
}
- return NULL;
+ return nullptr;
}
char *FioAppendDirectory(char *buf, const char *last, Searchpath sp, Subdirectory subdir)
@@ -407,7 +407,7 @@ static FILE *FioFOpenFileSp(const char *filename, const char *mode, Searchpath s
wchar_t Lmode[5];
MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode, lengthof(Lmode));
#endif
- FILE *f = NULL;
+ FILE *f = nullptr;
char buf[MAX_PATH];
if (subdir == NO_DIRECTORY) {
@@ -417,16 +417,16 @@ static FILE *FioFOpenFileSp(const char *filename, const char *mode, Searchpath s
}
#if defined(_WIN32)
- if (mode[0] == 'r' && GetFileAttributes(OTTD2FS(buf)) == INVALID_FILE_ATTRIBUTES) return NULL;
+ if (mode[0] == 'r' && GetFileAttributes(OTTD2FS(buf)) == INVALID_FILE_ATTRIBUTES) return nullptr;
#endif
f = fopen(buf, mode);
#if !defined(_WIN32)
- if (f == NULL && strtolower(buf + ((subdir == NO_DIRECTORY) ? 0 : strlen(_searchpaths[sp]) - 1))) {
+ if (f == nullptr && strtolower(buf + ((subdir == NO_DIRECTORY) ? 0 : strlen(_searchpaths[sp]) - 1))) {
f = fopen(buf, mode);
}
#endif
- if (f != NULL && filesize != NULL) {
+ if (f != nullptr && filesize != nullptr) {
/* Find the size of the file */
fseek(f, 0, SEEK_END);
*filesize = ftell(f);
@@ -438,21 +438,21 @@ static FILE *FioFOpenFileSp(const char *filename, const char *mode, Searchpath s
/**
* Opens a file from inside a tar archive.
* @param entry The entry to open.
- * @param[out] filesize If not \c NULL, size of the opened file.
- * @return File handle of the opened file, or \c NULL if the file is not available.
+ * @param[out] filesize If not \c nullptr, size of the opened file.
+ * @return File handle of the opened file, or \c nullptr if the file is not available.
* @note The file is read from within the tar file, and may not return \c EOF after reading the whole file.
*/
FILE *FioFOpenFileTar(TarFileListEntry *entry, size_t *filesize)
{
FILE *f = fopen(entry->tar_filename, "rb");
- if (f == NULL) return f;
+ if (f == nullptr) return f;
if (fseek(f, entry->position, SEEK_SET) < 0) {
fclose(f);
- return NULL;
+ return nullptr;
}
- if (filesize != NULL) *filesize = entry->size;
+ if (filesize != nullptr) *filesize = entry->size;
return f;
}
@@ -460,22 +460,22 @@ FILE *FioFOpenFileTar(TarFileListEntry *entry, size_t *filesize)
* Opens a OpenTTD file somewhere in a personal or global directory.
* @param filename Name of the file to open.
* @param subdir Subdirectory to open.
- * @return File handle of the opened file, or \c NULL if the file is not available.
+ * @return File handle of the opened file, or \c nullptr if the file is not available.
*/
FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize)
{
- FILE *f = NULL;
+ FILE *f = nullptr;
Searchpath sp;
assert(subdir < NUM_SUBDIRS || subdir == NO_DIRECTORY);
FOR_ALL_SEARCHPATHS(sp) {
f = FioFOpenFileSp(filename, mode, sp, subdir, filesize);
- if (f != NULL || subdir == NO_DIRECTORY) break;
+ if (f != nullptr || subdir == NO_DIRECTORY) break;
}
/* We can only use .tar in case of data-dir, and read-mode */
- if (f == NULL && mode[0] == 'r' && subdir != NO_DIRECTORY) {
+ if (f == nullptr && mode[0] == 'r' && subdir != NO_DIRECTORY) {
static const uint MAX_RESOLVED_LENGTH = 2 * (100 + 100 + 155) + 1; // Enough space to hold two filenames plus link. See 'TarHeader'.
char resolved_name[MAX_RESOLVED_LENGTH];
@@ -508,11 +508,11 @@ FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir,
/* Sometimes a full path is given. To support
* the 'subdirectory' must be 'removed'. */
- if (f == NULL && subdir != NO_DIRECTORY) {
+ if (f == nullptr && subdir != NO_DIRECTORY) {
switch (subdir) {
case BASESET_DIR:
f = FioFOpenFile(filename, mode, OLD_GM_DIR, filesize);
- if (f != NULL) break;
+ if (f != nullptr) break;
FALLTHROUGH;
case NEWGRF_DIR:
f = FioFOpenFile(filename, mode, OLD_DATA_DIR, filesize);
@@ -536,7 +536,7 @@ void FioCreateDirectory(const char *name)
/* Ignore directory creation errors; they'll surface later on, and most
* of the time they are 'directory already exists' errors anyhow. */
#if defined(_WIN32)
- CreateDirectory(OTTD2FS(name), NULL);
+ CreateDirectory(OTTD2FS(name), nullptr);
#elif defined(OS2) && !defined(__INNOTEK_LIBC__)
mkdir(OTTD2FS(name));
#else
@@ -573,7 +573,7 @@ bool AppendPathSeparator(char *buf, const char *last)
const char *FioTarFirstDir(const char *tarname, Subdirectory subdir)
{
TarList::iterator it = _tar_list[subdir].find(tarname);
- if (it == _tar_list[subdir].end()) return NULL;
+ if (it == _tar_list[subdir].end()) return nullptr;
return (*it).second.dirname;
}
@@ -675,7 +675,7 @@ bool TarScanner::AddFile(Subdirectory sd, const char *filename)
bool TarScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
{
/* No tar within tar. */
- assert(tar_filename == NULL);
+ assert(tar_filename == nullptr);
/* The TAR-header, repeated for every file */
struct TarHeader {
@@ -708,11 +708,11 @@ bool TarScanner::AddFile(const char *filename, size_t basepath_length, const cha
* a number of reasons we cannot open the file.
* Most common case is when we simply have not
* been given read access. */
- if (f == NULL) return false;
+ if (f == nullptr) return false;
const char *dupped_filename = stredup(filename);
_tar_list[this->subdir][filename].filename = dupped_filename;
- _tar_list[this->subdir][filename].dirname = NULL;
+ _tar_list[this->subdir][filename].dirname = nullptr;
TarLinkList links; ///< Temporary list to collect links
@@ -801,13 +801,13 @@ bool TarScanner::AddFile(const char *filename, size_t basepath_length, const cha
* Note: The destination of links must not contain any directory-links. */
strecpy(dest, name, lastof(dest));
char *destpos = strrchr(dest, PATHSEPCHAR);
- if (destpos == NULL) destpos = dest;
+ if (destpos == nullptr) destpos = dest;
*destpos = '\0';
char *pos = link;
while (*pos != '\0') {
char *next = strchr(pos, PATHSEPCHAR);
- if (next == NULL) {
+ if (next == nullptr) {
next = pos + strlen(pos);
} else {
/* Terminate the substring up to the path separator character. */
@@ -826,7 +826,7 @@ bool TarScanner::AddFile(const char *filename, size_t basepath_length, const cha
/* Truncate 'dest' after last PATHSEPCHAR.
* This assumes that the truncated part is a real directory and not a link. */
destpos = strrchr(dest, PATHSEPCHAR);
- if (destpos == NULL) destpos = dest;
+ if (destpos == nullptr) destpos = dest;
*destpos = '\0';
} else {
/* Append at end of 'dest' */
@@ -856,7 +856,7 @@ bool TarScanner::AddFile(const char *filename, size_t basepath_length, const cha
/* Store the first directory name we detect */
DEBUG(misc, 6, "Found dir in tar: %s", name);
- if (_tar_list[this->subdir][filename].dirname == NULL) _tar_list[this->subdir][filename].dirname = stredup(name);
+ if (_tar_list[this->subdir][filename].dirname == nullptr) _tar_list[this->subdir][filename].dirname = stredup(name);
break;
default:
@@ -911,13 +911,13 @@ bool ExtractTar(const char *tar_filename, Subdirectory subdir)
const char *dirname = (*it).second.dirname;
/* The file doesn't have a sub directory! */
- if (dirname == NULL) return false;
+ if (dirname == nullptr) return false;
char filename[MAX_PATH];
strecpy(filename, tar_filename, lastof(filename));
char *p = strrchr(filename, PATHSEPCHAR);
/* The file's path does not have a separator? */
- if (p == NULL) return false;
+ if (p == nullptr) return false;
p++;
strecpy(p, dirname, lastof(filename));
@@ -934,14 +934,14 @@ bool ExtractTar(const char *tar_filename, Subdirectory subdir)
/* First open the file in the .tar. */
size_t to_copy = 0;
FILE *in = FioFOpenFileTar(&(*it2).second, &to_copy);
- if (in == NULL) {
+ if (in == nullptr) {
DEBUG(misc, 6, "Extracting %s failed; could not open %s", filename, tar_filename);
return false;
}
/* Now open the 'output' file. */
FILE *out = fopen(filename, "wb");
- if (out == NULL) {
+ if (out == nullptr) {
DEBUG(misc, 6, "Extracting %s failed; could not open %s", filename, filename);
fclose(in);
return false;
@@ -993,12 +993,12 @@ static bool ChangeWorkingDirectoryToExecutable(const char *exe)
bool success = false;
#ifdef WITH_COCOA
char *app_bundle = strchr(tmp, '.');
- while (app_bundle != NULL && strncasecmp(app_bundle, ".app", 4) != 0) app_bundle = strchr(&app_bundle[1], '.');
+ while (app_bundle != nullptr && strncasecmp(app_bundle, ".app", 4) != 0) app_bundle = strchr(&app_bundle[1], '.');
- if (app_bundle != NULL) *app_bundle = '\0';
+ if (app_bundle != nullptr) *app_bundle = '\0';
#endif /* WITH_COCOA */
char *s = strrchr(tmp, PATHSEPCHAR);
- if (s != NULL) {
+ if (s != nullptr) {
*s = '\0';
if (chdir(tmp) != 0) {
DEBUG(misc, 0, "Directory with the binary does not exist?");
@@ -1022,13 +1022,13 @@ static bool ChangeWorkingDirectoryToExecutable(const char *exe)
bool DoScanWorkingDirectory()
{
/* No working directory, so nothing to do. */
- if (_searchpaths[SP_WORKING_DIR] == NULL) return false;
+ if (_searchpaths[SP_WORKING_DIR] == nullptr) return false;
/* Working directory is root, so do nothing. */
if (strcmp(_searchpaths[SP_WORKING_DIR], PATHSEP) == 0) return false;
/* No personal/home directory, so the working directory won't be that. */
- if (_searchpaths[SP_PERSONAL_DIR] == NULL) return true;
+ if (_searchpaths[SP_PERSONAL_DIR] == nullptr) return true;
char tmp[MAX_PATH];
seprintf(tmp, lastof(tmp), "%s%s", _searchpaths[SP_WORKING_DIR], PERSONAL_DIR);
@@ -1044,7 +1044,7 @@ void DetermineBasePaths(const char *exe)
{
char tmp[MAX_PATH];
#if defined(WITH_XDG_BASEDIR) && defined(WITH_PERSONAL_DIR)
- const char *xdg_data_home = xdgDataHome(NULL);
+ const char *xdg_data_home = xdgDataHome(nullptr);
seprintf(tmp, lastof(tmp), "%s" PATHSEP "%s", xdg_data_home,
PERSONAL_DIR[0] == '.' ? &PERSONAL_DIR[1] : PERSONAL_DIR);
free(xdg_data_home);
@@ -1053,7 +1053,7 @@ void DetermineBasePaths(const char *exe)
_searchpaths[SP_PERSONAL_DIR_XDG] = stredup(tmp);
#endif
#if defined(OS2) || !defined(WITH_PERSONAL_DIR)
- _searchpaths[SP_PERSONAL_DIR] = NULL;
+ _searchpaths[SP_PERSONAL_DIR] = nullptr;
#else
#ifdef __HAIKU__
BPath path;
@@ -1065,17 +1065,17 @@ void DetermineBasePaths(const char *exe)
* variables in any way. It can also contain all kinds of
* unvalidated data we rather not want internally. */
const char *homedir = getenv("HOME");
- if (homedir != NULL) {
+ if (homedir != nullptr) {
homedir = stredup(homedir);
}
- if (homedir == NULL) {
+ if (homedir == nullptr) {
const struct passwd *pw = getpwuid(getuid());
- homedir = (pw == NULL) ? NULL : stredup(pw->pw_dir);
+ homedir = (pw == nullptr) ? nullptr : stredup(pw->pw_dir);
}
#endif
- if (homedir != NULL) {
+ if (homedir != nullptr) {
ValidateString(homedir);
seprintf(tmp, lastof(tmp), "%s" PATHSEP "%s", homedir, PERSONAL_DIR);
AppendPathSeparator(tmp, lastof(tmp));
@@ -1083,7 +1083,7 @@ void DetermineBasePaths(const char *exe)
_searchpaths[SP_PERSONAL_DIR] = stredup(tmp);
free(homedir);
} else {
- _searchpaths[SP_PERSONAL_DIR] = NULL;
+ _searchpaths[SP_PERSONAL_DIR] = nullptr;
}
#endif
@@ -1092,10 +1092,10 @@ void DetermineBasePaths(const char *exe)
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_SHARED_DIR] = stredup(tmp);
#else
- _searchpaths[SP_SHARED_DIR] = NULL;
+ _searchpaths[SP_SHARED_DIR] = nullptr;
#endif
- if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0';
+ if (getcwd(tmp, MAX_PATH) == nullptr) *tmp = '\0';
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_WORKING_DIR] = stredup(tmp);
@@ -1103,14 +1103,14 @@ void DetermineBasePaths(const char *exe)
/* Change the working directory to that one of the executable */
if (ChangeWorkingDirectoryToExecutable(exe)) {
- if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0';
+ if (getcwd(tmp, MAX_PATH) == nullptr) *tmp = '\0';
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_BINARY_DIR] = stredup(tmp);
} else {
- _searchpaths[SP_BINARY_DIR] = NULL;
+ _searchpaths[SP_BINARY_DIR] = nullptr;
}
- if (_searchpaths[SP_WORKING_DIR] != NULL) {
+ if (_searchpaths[SP_WORKING_DIR] != nullptr) {
/* Go back to the current working directory. */
if (chdir(_searchpaths[SP_WORKING_DIR]) != 0) {
DEBUG(misc, 0, "Failed to return to working directory!");
@@ -1118,7 +1118,7 @@ void DetermineBasePaths(const char *exe)
}
#if !defined(GLOBAL_DATA_DIR)
- _searchpaths[SP_INSTALLATION_DIR] = NULL;
+ _searchpaths[SP_INSTALLATION_DIR] = nullptr;
#else
seprintf(tmp, lastof(tmp), "%s", GLOBAL_DATA_DIR);
AppendPathSeparator(tmp, lastof(tmp));
@@ -1128,7 +1128,7 @@ void DetermineBasePaths(const char *exe)
extern void cocoaSetApplicationBundleDir();
cocoaSetApplicationBundleDir();
#else
- _searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
+ _searchpaths[SP_APPLICATION_BUNDLE_DIR] = nullptr;
#endif
}
#endif /* defined(_WIN32) */
@@ -1148,7 +1148,7 @@ void DeterminePaths(const char *exe)
#if defined(WITH_XDG_BASEDIR) && defined(WITH_PERSONAL_DIR)
char config_home[MAX_PATH];
- const char *xdg_config_home = xdgConfigHome(NULL);
+ const char *xdg_config_home = xdgConfigHome(nullptr);
seprintf(config_home, lastof(config_home), "%s" PATHSEP "%s", xdg_config_home,
PERSONAL_DIR[0] == '.' ? &PERSONAL_DIR[1] : PERSONAL_DIR);
free(xdg_config_home);
@@ -1163,19 +1163,19 @@ void DeterminePaths(const char *exe)
}
char *config_dir;
- if (_config_file != NULL) {
+ if (_config_file != nullptr) {
config_dir = stredup(_config_file);
char *end = strrchr(config_dir, PATHSEPCHAR);
- if (end == NULL) {
+ if (end == nullptr) {
config_dir[0] = '\0';
} else {
end[1] = '\0';
}
} else {
char personal_dir[MAX_PATH];
- if (FioFindFullPath(personal_dir, lastof(personal_dir), BASE_DIR, "openttd.cfg") != NULL) {
+ if (FioFindFullPath(personal_dir, lastof(personal_dir), BASE_DIR, "openttd.cfg") != nullptr) {
char *end = strrchr(personal_dir, PATHSEPCHAR);
- if (end != NULL) end[1] = '\0';
+ if (end != nullptr) end[1] = '\0';
config_dir = stredup(personal_dir);
_config_file = str_fmt("%sopenttd.cfg", config_dir);
} else {
@@ -1187,14 +1187,14 @@ void DeterminePaths(const char *exe)
SP_PERSONAL_DIR, SP_BINARY_DIR, SP_WORKING_DIR, SP_SHARED_DIR, SP_INSTALLATION_DIR
};
- config_dir = NULL;
+ config_dir = nullptr;
for (uint i = 0; i < lengthof(new_openttd_cfg_order); i++) {
if (IsValidSearchPath(new_openttd_cfg_order[i])) {
config_dir = stredup(_searchpaths[new_openttd_cfg_order[i]]);
break;
}
}
- assert(config_dir != NULL);
+ assert(config_dir != nullptr);
#endif
_config_file = str_fmt("%sopenttd.cfg", config_dir);
}
@@ -1277,27 +1277,27 @@ void SanitizeFilename(char *filename)
* @param filename Name of the file to load.
* @param[out] lenp Length of loaded data.
* @param maxsize Maximum size to load.
- * @return Pointer to new memory containing the loaded data, or \c NULL if loading failed.
+ * @return Pointer to new memory containing the loaded data, or \c nullptr if loading failed.
* @note If \a maxsize less than the length of the file, loading fails.
*/
void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize)
{
FILE *in = fopen(filename, "rb");
- if (in == NULL) return NULL;
+ if (in == nullptr) return nullptr;
fseek(in, 0, SEEK_END);
size_t len = ftell(in);
fseek(in, 0, SEEK_SET);
if (len > maxsize) {
fclose(in);
- return NULL;
+ return nullptr;
}
byte *mem = MallocT<byte>(len + 1);
mem[len] = 0;
if (fread(mem, len, 1, in) != 1) {
fclose(in);
free(mem);
- return NULL;
+ return nullptr;
}
fclose(in);
@@ -1309,14 +1309,14 @@ void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize)
* Helper to see whether a given filename matches the extension.
* @param extension The extension to look for.
* @param filename The filename to look in for the extension.
- * @return True iff the extension is NULL, or the filename ends with it.
+ * @return True iff the extension is nullptr, or the filename ends with it.
*/
static bool MatchesExtension(const char *extension, const char *filename)
{
- if (extension == NULL) return true;
+ if (extension == nullptr) return true;
const char *ext = strrchr(filename, extension[0]);
- return ext != NULL && strcasecmp(ext, extension) == 0;
+ return ext != nullptr && strcasecmp(ext, extension) == 0;
}
/**
@@ -1337,9 +1337,9 @@ static uint ScanPath(FileScanner *fs, const char *extension, const char *path, s
struct dirent *dirent;
DIR *dir;
- if (path == NULL || (dir = ttd_opendir(path)) == NULL) return 0;
+ if (path == nullptr || (dir = ttd_opendir(path)) == nullptr) return 0;
- while ((dirent = readdir(dir)) != NULL) {
+ while ((dirent = readdir(dir)) != nullptr) {
const char *d_name = FS2OTTD(dirent->d_name);
char filename[MAX_PATH];
@@ -1355,7 +1355,7 @@ static uint ScanPath(FileScanner *fs, const char *extension, const char *path, s
num += ScanPath(fs, extension, filename, basepath_length, recursive);
} else if (S_ISREG(sb.st_mode)) {
/* File */
- if (MatchesExtension(extension, filename) && fs->AddFile(filename, basepath_length, NULL)) num++;
+ if (MatchesExtension(extension, filename) && fs->AddFile(filename, basepath_length, nullptr)) num++;
}
}
diff --git a/src/fileio_func.h b/src/fileio_func.h
index 8263b7872..dd3727df0 100644
--- a/src/fileio_func.h
+++ b/src/fileio_func.h
@@ -30,7 +30,7 @@ void FioSkipBytes(int n);
/**
* The search paths OpenTTD could search through.
* At least one of the slots has to be filled with a path.
- * NULL paths tell that there is no such path for the
+ * nullptr paths tell that there is no such path for the
* current operating system.
*/
extern const char *_searchpaths[NUM_SEARCHPATHS];
@@ -42,14 +42,14 @@ extern const char *_searchpaths[NUM_SEARCHPATHS];
*/
static inline bool IsValidSearchPath(Searchpath sp)
{
- return sp < NUM_SEARCHPATHS && _searchpaths[sp] != NULL;
+ return sp < NUM_SEARCHPATHS && _searchpaths[sp] != nullptr;
}
/** Iterator for all the search paths */
#define FOR_ALL_SEARCHPATHS(sp) for (sp = SP_FIRST_DIR; sp < NUM_SEARCHPATHS; sp++) if (IsValidSearchPath(sp))
void FioFCloseFile(FILE *f);
-FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize = NULL);
+FILE *FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize = nullptr);
bool FioCheckFileExists(const char *filename, Subdirectory subdir);
char *FioGetFullPath(char *buf, const char *last, Searchpath sp, Subdirectory subdir, const char *filename);
char *FioFindFullPath(char *buf, const char *last, Subdirectory subdir, const char *filename);
@@ -107,7 +107,7 @@ public:
ALL = BASESET | NEWGRF | AI | SCENARIO | GAME, ///< Scan for everything.
};
- bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename = NULL) override;
+ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename = nullptr) override;
bool AddFile(Subdirectory sd, const char *filename);
diff --git a/src/fios.cpp b/src/fios.cpp
index 54ad54b11..008f552e6 100644
--- a/src/fios.cpp
+++ b/src/fios.cpp
@@ -105,7 +105,7 @@ void FileList::BuildFileList(AbstractFileType abstract_filetype, SaveLoadOperati
* Find file information of a file by its name from the file list.
* @param file The filename to return information about. Can be the actual name
* or a numbered entry into the filename list.
- * @return The information on the file, or \c NULL if the file is not available.
+ * @return The information on the file, or \c nullptr if the file is not available.
*/
const FiosItem *FileList::FindItem(const char *file)
{
@@ -130,14 +130,14 @@ const FiosItem *FileList::FindItem(const char *file)
if (strcmp(long_file, item->title) == 0) return item;
}
- return NULL;
+ return nullptr;
}
/**
* Get descriptive texts. Returns the path and free space
* left on the device
* @param path string describing the path
- * @param total_free total free space in megabytes, optional (can be NULL)
+ * @param total_free total free space in megabytes, optional (can be nullptr)
* @return StringID describing the path (free space or failure)
*/
StringID FiosGetDescText(const char **path, uint64 *total_free)
@@ -149,7 +149,7 @@ StringID FiosGetDescText(const char **path, uint64 *total_free)
/**
* Browse to a new path based on the passed \a item, starting at #_fios_path.
* @param *item Item telling us what to do.
- * @return A filename w/path if we reached a file, otherwise \c NULL.
+ * @return A filename w/path if we reached a file, otherwise \c nullptr.
*/
const char *FiosBrowseTo(const FiosItem *item)
{
@@ -164,13 +164,13 @@ const char *FiosBrowseTo(const FiosItem *item)
break;
case FIOS_TYPE_PARENT: {
- /* Check for possible NULL ptr */
+ /* Check for possible nullptr ptr */
char *s = strrchr(_fios_path, PATHSEPCHAR);
- if (s != NULL && s != _fios_path) {
+ if (s != nullptr && s != _fios_path) {
s[0] = '\0'; // Remove last path separator character, so we can go up one level.
}
s = strrchr(_fios_path, PATHSEPCHAR);
- if (s != NULL) {
+ if (s != nullptr) {
s[1] = '\0'; // go up a directory
}
break;
@@ -194,13 +194,13 @@ const char *FiosBrowseTo(const FiosItem *item)
return item->name;
}
- return NULL;
+ return nullptr;
}
/**
* Construct a filename from its components in destination buffer \a buf.
* @param buf Destination buffer.
- * @param path Directory path, may be \c NULL.
+ * @param path Directory path, may be \c nullptr.
* @param name Filename.
* @param ext Filename extension (use \c "" for no extension).
* @param last Last element of buffer \a buf.
@@ -211,7 +211,7 @@ static void FiosMakeFilename(char *buf, const char *path, const char *name, cons
/* Don't append the extension if it is already there */
period = strrchr(name, '.');
- if (period != NULL && strcasecmp(period, ext) == 0) ext = "";
+ if (period != nullptr && strcasecmp(period, ext) == 0) ext = "";
seprintf(buf, last, "%s" PATHSEP "%s%s", path, name, ext);
}
@@ -288,7 +288,7 @@ public:
bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
{
const char *ext = strrchr(filename, '.');
- if (ext == NULL) return false;
+ if (ext == nullptr) return false;
char fios_title[64];
fios_title[0] = '\0'; // reset the title;
@@ -320,7 +320,7 @@ bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length, cons
const char *t = fios_title;
if (StrEmpty(fios_title)) {
t = strrchr(filename, PATHSEPCHAR);
- t = (t == NULL) ? filename : (t + 1);
+ t = (t == nullptr) ? filename : (t + 1);
}
strecpy(fios->title, t, lastof(fios->title));
str_validate(fios->title, lastof(fios->title));
@@ -357,8 +357,8 @@ static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *c
}
/* Show subdirectories */
- if ((dir = ttd_opendir(_fios_path)) != NULL) {
- while ((dirent = readdir(dir)) != NULL) {
+ if ((dir = ttd_opendir(_fios_path)) != nullptr) {
+ while ((dirent = readdir(dir)) != nullptr) {
strecpy(d_name, FS2OTTD(dirent->d_name), lastof(d_name));
/* found file must be directory, but not '.' or '..' */
@@ -390,9 +390,9 @@ static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *c
/* Show files */
FiosFileScanner scanner(fop, callback_proc, file_list);
if (subdir == NO_DIRECTORY) {
- scanner.Scan(NULL, _fios_path, false);
+ scanner.Scan(nullptr, _fios_path, false);
} else {
- scanner.Scan(NULL, subdir, true, true);
+ scanner.Scan(nullptr, subdir, true, true);
}
QSortT(file_list.Get(sort_start), file_list.Length() - sort_start, CompareFiosItems);
@@ -418,7 +418,7 @@ static void GetFileTitle(const char *file, char *title, const char *last, Subdir
strecat(buf, ".title", lastof(buf));
FILE *f = FioFOpenFile(buf, "r", subdir);
- if (f == NULL) return;
+ if (f == nullptr) return;
size_t read = fread(title, 1, last - title, f);
assert(title + read <= last);
@@ -432,8 +432,8 @@ static void GetFileTitle(const char *file, char *title, const char *last, Subdir
* @param fop Purpose of collecting the list.
* @param file Name of the file to check.
* @param ext A pointer to the extension identifier inside file
- * @param title Buffer if a callback wants to lookup the title of the file; NULL to skip the lookup
- * @param last Last available byte in buffer (to prevent buffer overflows); not used when title == NULL
+ * @param title Buffer if a callback wants to lookup the title of the file; nullptr to skip the lookup
+ * @param last Last available byte in buffer (to prevent buffer overflows); not used when title == nullptr
* @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
* @see FiosGetFileList
* @see FiosGetSavegameList
@@ -447,7 +447,7 @@ FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, co
* .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
/* Don't crash if we supply no extension */
- if (ext == NULL) return FIOS_TYPE_INVALID;
+ if (ext == nullptr) return FIOS_TYPE_INVALID;
if (strcasecmp(ext, ".sav") == 0) {
GetFileTitle(file, title, last, SAVE_DIR);
@@ -457,7 +457,7 @@ FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, co
if (fop == SLO_LOAD) {
if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 ||
strcasecmp(ext, ".sv2") == 0) {
- if (title != NULL) GetOldSaveGameName(file, title, last);
+ if (title != nullptr) GetOldSaveGameName(file, title, last);
return FIOS_TYPE_OLDFILE;
}
}
@@ -473,10 +473,10 @@ FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, co
*/
void FiosGetSavegameList(SaveLoadOperation fop, FileList &file_list)
{
- static char *fios_save_path = NULL;
- static char *fios_save_path_last = NULL;
+ static char *fios_save_path = nullptr;
+ static char *fios_save_path_last = nullptr;
- if (fios_save_path == NULL) {
+ if (fios_save_path == nullptr) {
fios_save_path = MallocT<char>(MAX_PATH);
fios_save_path_last = fios_save_path + MAX_PATH - 1;
FioGetDirectory(fios_save_path, fios_save_path_last, SAVE_DIR);
@@ -528,11 +528,11 @@ static FiosType FiosGetScenarioListCallback(SaveLoadOperation fop, const char *f
*/
void FiosGetScenarioList(SaveLoadOperation fop, FileList &file_list)
{
- static char *fios_scn_path = NULL;
- static char *fios_scn_path_last = NULL;
+ static char *fios_scn_path = nullptr;
+ static char *fios_scn_path_last = nullptr;
/* Copy the default path on first run or on 'New Game' */
- if (fios_scn_path == NULL) {
+ if (fios_scn_path == nullptr) {
fios_scn_path = MallocT<char>(MAX_PATH);
fios_scn_path_last = fios_scn_path + MAX_PATH - 1;
FioGetDirectory(fios_scn_path, fios_scn_path_last, SCENARIO_DIR);
@@ -599,10 +599,10 @@ static FiosType FiosGetHeightmapListCallback(SaveLoadOperation fop, const char *
*/
void FiosGetHeightmapList(SaveLoadOperation fop, FileList &file_list)
{
- static char *fios_hmap_path = NULL;
- static char *fios_hmap_path_last = NULL;
+ static char *fios_hmap_path = nullptr;
+ static char *fios_hmap_path_last = nullptr;
- if (fios_hmap_path == NULL) {
+ if (fios_hmap_path == nullptr) {
fios_hmap_path = MallocT<char>(MAX_PATH);
fios_hmap_path_last = fios_hmap_path + MAX_PATH - 1;
FioGetDirectory(fios_hmap_path, fios_hmap_path_last, HEIGHTMAP_DIR);
@@ -624,9 +624,9 @@ void FiosGetHeightmapList(SaveLoadOperation fop, FileList &file_list)
*/
const char *FiosGetScreenshotDir()
{
- static char *fios_screenshot_path = NULL;
+ static char *fios_screenshot_path = nullptr;
- if (fios_screenshot_path == NULL) {
+ if (fios_screenshot_path == nullptr) {
fios_screenshot_path = MallocT<char>(MAX_PATH);
FioGetDirectory(fios_screenshot_path, fios_screenshot_path + MAX_PATH - 1, SCREENSHOT_DIR);
}
@@ -676,7 +676,7 @@ public:
bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename) override
{
FILE *f = FioFOpenFile(filename, "r", SCENARIO_DIR);
- if (f == NULL) return false;
+ if (f == nullptr) return false;
ScenarioIdentifier id;
int fret = fscanf(f, "%i", &id.scenid);
@@ -695,7 +695,7 @@ public:
strecpy(basename, filename, lastof(basename));
*strrchr(basename, '.') = '\0';
f = FioFOpenFile(basename, "rb", SCENARIO_DIR, &size);
- if (f == NULL) return false;
+ if (f == nullptr) return false;
/* calculate md5sum */
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
@@ -718,7 +718,7 @@ static ScenarioScanner _scanner;
* Find a given scenario based on its unique ID.
* @param ci The content info to compare it to.
* @param md5sum Whether to look at the md5sum or the id.
- * @return The filename of the file, else \c NULL.
+ * @return The filename of the file, else \c nullptr.
*/
const char *FindScenario(const ContentInfo *ci, bool md5sum)
{
@@ -731,7 +731,7 @@ const char *FindScenario(const ContentInfo *ci, bool md5sum)
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -742,7 +742,7 @@ const char *FindScenario(const ContentInfo *ci, bool md5sum)
*/
bool HasScenario(const ContentInfo *ci, bool md5sum)
{
- return (FindScenario(ci, md5sum) != NULL);
+ return (FindScenario(ci, md5sum) != nullptr);
}
/**
diff --git a/src/fios.h b/src/fios.h
index 6ae0550d1..5688e88cf 100644
--- a/src/fios.h
+++ b/src/fios.h
@@ -48,8 +48,8 @@ struct LoadCheckData {
struct LoggedAction *gamelog_action; ///< Gamelog actions
uint gamelog_actions; ///< Number of gamelog actions
- LoadCheckData() : error_data(NULL), grfconfig(NULL),
- grf_compatibility(GLC_NOT_FOUND), gamelog_action(NULL), gamelog_actions(0)
+ LoadCheckData() : error_data(nullptr), grfconfig(nullptr),
+ grf_compatibility(GLC_NOT_FOUND), gamelog_action(nullptr), gamelog_actions(0)
{
this->Clear();
}
@@ -77,7 +77,7 @@ struct LoadCheckData {
*/
bool HasNewGrfs()
{
- return this->checkable && this->error == INVALID_STRING_ID && this->grfconfig != NULL;
+ return this->checkable && this->error == INVALID_STRING_ID && this->grfconfig != nullptr;
}
void Clear();
diff --git a/src/fios_gui.cpp b/src/fios_gui.cpp
index 7a194054f..c78271122 100644
--- a/src/fios_gui.cpp
+++ b/src/fios_gui.cpp
@@ -51,7 +51,7 @@ void LoadCheckData::Clear()
this->checkable = false;
this->error = INVALID_STRING_ID;
free(this->error_data);
- this->error_data = NULL;
+ this->error_data = nullptr;
this->map_size_x = this->map_size_y = 256; // Default for old savegames which do not store mapsize.
this->current_date = 0;
@@ -63,7 +63,7 @@ void LoadCheckData::Clear()
companies.clear();
GamelogFree(this->gamelog_action, this->gamelog_actions);
- this->gamelog_action = NULL;
+ this->gamelog_action = nullptr;
this->gamelog_actions = 0;
ClearGRFConfigList(&this->grfconfig);
@@ -273,7 +273,7 @@ private:
SaveLoadOperation fop; ///< File operation to perform.
FileList fios_items; ///< Save game list.
FiosItem o_dir;
- const FiosItem *selected; ///< Selected game in #fios_items, or \c NULL.
+ const FiosItem *selected; ///< Selected game in #fios_items, or \c nullptr.
Scrollbar *vscroll;
StringFilter string_filter; ///< Filter for available games.
@@ -417,7 +417,7 @@ public:
break;
case WID_SL_BACKGROUND: {
- static const char *path = NULL;
+ static const char *path = nullptr;
static StringID str = STR_ERROR_UNABLE_TO_READ_DRIVE;
static uint64 tot = 0;
@@ -461,7 +461,7 @@ public:
r.right - WD_FRAMERECT_RIGHT, r.top + FONT_HEIGHT_NORMAL * 2 + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM, PC_GREY);
DrawString(r.left, r.right, r.top + FONT_HEIGHT_NORMAL / 2 + WD_FRAMERECT_TOP, STR_SAVELOAD_DETAIL_CAPTION, TC_FROMSTRING, SA_HOR_CENTER);
- if (this->selected == NULL) break;
+ if (this->selected == nullptr) break;
uint y = r.top + FONT_HEIGHT_NORMAL * 2 + WD_PAR_VSEP_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
uint y_max = r.bottom - FONT_HEIGHT_NORMAL - WD_FRAMERECT_BOTTOM;
@@ -517,7 +517,7 @@ public:
if (y > y_max) break;
/* NewGrf compatibility */
- SetDParam(0, _load_check_data.grfconfig == NULL ? STR_NEWGRF_LIST_NONE :
+ SetDParam(0, _load_check_data.grfconfig == nullptr ? STR_NEWGRF_LIST_NONE :
STR_NEWGRF_LIST_ALL_FOUND + _load_check_data.grf_compatibility);
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_SAVELOAD_DETAIL_GRFSTATUS);
y += FONT_HEIGHT_NORMAL;
@@ -533,7 +533,7 @@ public:
for (auto &pair : _load_check_data.companies) {
SetDParam(0, pair.first + 1);
const CompanyProperties &c = *pair.second;
- if (c.name != NULL) {
+ if (c.name != nullptr) {
SetDParam(1, STR_JUST_RAW_STRING);
SetDParamStr(2, c.name);
} else {
@@ -607,7 +607,7 @@ public:
break;
case WID_SL_LOAD_BUTTON:
- if (this->selected != NULL && !_load_check_data.HasErrors()) {
+ if (this->selected != nullptr && !_load_check_data.HasErrors()) {
const char *name = FiosBrowseTo(this->selected);
_file_to_saveload.SetMode(this->selected->type);
_file_to_saveload.SetName(name);
@@ -652,7 +652,7 @@ public:
const FiosItem *file = this->fios_items.Get(y);
const char *name = FiosBrowseTo(file);
- if (name != NULL) {
+ if (name != nullptr) {
if (click_count == 1) {
if (this->selected != file) {
this->selected = file;
@@ -700,8 +700,8 @@ public:
assert(this->fop == SLO_LOAD);
switch (this->abstract_filetype) {
default: NOT_REACHED();
- case FT_SCENARIO: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_SCENARIO); break;
- case FT_HEIGHTMAP: ShowNetworkContentListWindow(NULL, CONTENT_TYPE_HEIGHTMAP); break;
+ case FT_SCENARIO: ShowNetworkContentListWindow(nullptr, CONTENT_TYPE_SCENARIO); break;
+ case FT_HEIGHTMAP: ShowNetworkContentListWindow(nullptr, CONTENT_TYPE_HEIGHTMAP); break;
}
}
break;
@@ -776,14 +776,14 @@ public:
switch (data) {
case SLIWD_RESCAN_FILES:
/* Rescan files */
- this->selected = NULL;
+ this->selected = nullptr;
_load_check_data.Clear();
if (!gui_scope) break;
_fios_path_changed = true;
this->fios_items.BuildFileList(this->abstract_filetype, this->fop);
this->vscroll->SetCount((uint)this->fios_items.Length());
- this->selected = NULL;
+ this->selected = nullptr;
_load_check_data.Clear();
/* We reset the files filtered */
@@ -799,12 +799,12 @@ public:
switch (this->abstract_filetype) {
case FT_HEIGHTMAP:
- this->SetWidgetDisabledState(WID_SL_LOAD_BUTTON, this->selected == NULL || _load_check_data.HasErrors());
+ this->SetWidgetDisabledState(WID_SL_LOAD_BUTTON, this->selected == nullptr || _load_check_data.HasErrors());
break;
case FT_SAVEGAME:
case FT_SCENARIO: {
- bool disabled = this->selected == NULL || _load_check_data.HasErrors();
+ bool disabled = this->selected == nullptr || _load_check_data.HasErrors();
if (!_settings_client.gui.UserIsAllowedToChangeNewGRFs()) {
disabled |= _load_check_data.HasNewGrfs() && _load_check_data.grf_compatibility == GLC_NOT_FOUND;
}
@@ -839,7 +839,7 @@ public:
if (&(this->fios_items[i]) == this->selected && this->fios_items_shown[i] == false) {
/* The selected element has been filtered out */
- this->selected = NULL;
+ this->selected = nullptr;
this->OnInvalidateData(SLIWD_SELECTION_CHANGES);
}
}
diff --git a/src/fontcache.cpp b/src/fontcache.cpp
index 82a441814..ac09a3e93 100644
--- a/src/fontcache.cpp
+++ b/src/fontcache.cpp
@@ -41,7 +41,7 @@ FontCache::FontCache(FontSize fs) : parent(FontCache::Get(fs)), fs(fs), height(_
ascender(_default_font_ascender[fs]), descender(_default_font_ascender[fs] - _default_font_height[fs]),
units_per_em(1)
{
- assert(this->parent == NULL || this->fs == this->parent->fs);
+ assert(this->parent == nullptr || this->fs == this->parent->fs);
FontCache::caches[this->fs] = this;
Layouter::ResetFontCache(this->fs);
}
@@ -84,7 +84,7 @@ public:
virtual int GetHeight() const;
virtual bool GetDrawGlyphShadow();
virtual GlyphID MapCharToGlyph(WChar key) { assert(IsPrintable(key)); return SPRITE_GLYPH | key; }
- virtual const void *GetFontTable(uint32 tag, size_t &length) { length = 0; return NULL; }
+ virtual const void *GetFontTable(uint32 tag, size_t &length) { length = 0; return nullptr; }
virtual const char *GetFontName() { return "sprite"; }
virtual bool IsBuiltInFont() { return true; }
};
@@ -93,7 +93,7 @@ public:
* Create a new sprite font cache.
* @param fs The font size to create the cache for.
*/
-SpriteFontCache::SpriteFontCache(FontSize fs) : FontCache(fs), glyph_to_spriteid_map(NULL)
+SpriteFontCache::SpriteFontCache(FontSize fs) : FontCache(fs), glyph_to_spriteid_map(nullptr)
{
this->InitializeUnicodeGlyphMap();
}
@@ -108,14 +108,14 @@ SpriteFontCache::~SpriteFontCache()
SpriteID SpriteFontCache::GetUnicodeGlyph(GlyphID key)
{
- if (this->glyph_to_spriteid_map[GB(key, 8, 8)] == NULL) return 0;
+ if (this->glyph_to_spriteid_map[GB(key, 8, 8)] == nullptr) return 0;
return this->glyph_to_spriteid_map[GB(key, 8, 8)][GB(key, 0, 8)];
}
void SpriteFontCache::SetUnicodeGlyph(GlyphID key, SpriteID sprite)
{
- if (this->glyph_to_spriteid_map == NULL) this->glyph_to_spriteid_map = CallocT<SpriteID*>(256);
- if (this->glyph_to_spriteid_map[GB(key, 8, 8)] == NULL) this->glyph_to_spriteid_map[GB(key, 8, 8)] = CallocT<SpriteID>(256);
+ if (this->glyph_to_spriteid_map == nullptr) this->glyph_to_spriteid_map = CallocT<SpriteID*>(256);
+ if (this->glyph_to_spriteid_map[GB(key, 8, 8)] == nullptr) this->glyph_to_spriteid_map[GB(key, 8, 8)] = CallocT<SpriteID>(256);
this->glyph_to_spriteid_map[GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
}
@@ -159,13 +159,13 @@ void SpriteFontCache::InitializeUnicodeGlyphMap()
*/
void SpriteFontCache::ClearGlyphToSpriteMap()
{
- if (this->glyph_to_spriteid_map == NULL) return;
+ if (this->glyph_to_spriteid_map == nullptr) return;
for (uint i = 0; i < 256; i++) {
free(this->glyph_to_spriteid_map[i]);
}
free(this->glyph_to_spriteid_map);
- this->glyph_to_spriteid_map = NULL;
+ this->glyph_to_spriteid_map = nullptr;
}
void SpriteFontCache::ClearFontCache()
@@ -258,7 +258,7 @@ public:
virtual bool IsBuiltInFont() { return false; }
};
-FT_Library _library = NULL;
+FT_Library _library = nullptr;
FreeTypeSettings _freetype;
@@ -271,9 +271,9 @@ static const byte SHADOW_COLOUR = 2;
* @param face The font that has to be loaded.
* @param pixels The number of pixels this font should be high.
*/
-FreeTypeFontCache::FreeTypeFontCache(FontSize fs, FT_Face face, int pixels) : FontCache(fs), face(face), req_size(pixels), glyph_to_sprite(NULL)
+FreeTypeFontCache::FreeTypeFontCache(FontSize fs, FT_Face face, int pixels) : FontCache(fs), face(face), req_size(pixels), glyph_to_sprite(nullptr)
{
- assert(face != NULL);
+ assert(face != nullptr);
this->SetFontSize(fs, face, pixels);
}
@@ -286,7 +286,7 @@ void FreeTypeFontCache::SetFontSize(FontSize fs, FT_Face face, int pixels)
pixels = scaled_height;
TT_Header *head = (TT_Header *)FT_Get_Sfnt_Table(this->face, ft_sfnt_head);
- if (head != NULL) {
+ if (head != nullptr) {
/* Font height is minimum height plus the difference between the default
* height for this font size and the small size. */
int diff = scaled_height - ScaleFontTrad(_default_font_height[FS_SMALL]);
@@ -338,7 +338,7 @@ void FreeTypeFontCache::SetFontSize(FontSize fs, FT_Face face, int pixels)
*/
static void LoadFreeTypeFont(FontSize fs)
{
- FreeTypeSubSetting *settings = NULL;
+ FreeTypeSubSetting *settings = nullptr;
switch (fs) {
default: NOT_REACHED();
case FS_SMALL: settings = &_freetype.small; break;
@@ -349,7 +349,7 @@ static void LoadFreeTypeFont(FontSize fs)
if (StrEmpty(settings->font)) return;
- if (_library == NULL) {
+ if (_library == nullptr) {
if (FT_Init_FreeType(&_library) != FT_Err_Ok) {
ShowInfoF("Unable to initialize FreeType, using sprite fonts instead");
return;
@@ -358,7 +358,7 @@ static void LoadFreeTypeFont(FontSize fs)
DEBUG(freetype, 2, "Initialized");
}
- FT_Face face = NULL;
+ FT_Face face = nullptr;
FT_Error error = FT_New_Face(_library, settings->font, 0, &face);
if (error != FT_Err_Ok) error = GetFontByFaceName(settings->font, &face);
@@ -384,7 +384,7 @@ static void LoadFreeTypeFont(FontSize fs)
}
}
- if (found != NULL) {
+ if (found != nullptr) {
error = FT_Set_Charmap(face, found);
if (error == FT_Err_Ok) goto found_face;
}
@@ -408,7 +408,7 @@ found_face:
FreeTypeFontCache::~FreeTypeFontCache()
{
FT_Done_Face(this->face);
- this->face = NULL;
+ this->face = nullptr;
this->ClearFontCache();
for (auto &iter : this->font_tables) {
@@ -422,12 +422,12 @@ FreeTypeFontCache::~FreeTypeFontCache()
void FreeTypeFontCache::ClearFontCache()
{
/* Font scaling might have changed, determine font size anew if it was automatically selected. */
- if (this->face != NULL) this->SetFontSize(this->fs, this->face, this->req_size);
+ if (this->face != nullptr) this->SetFontSize(this->fs, this->face, this->req_size);
- if (this->glyph_to_sprite == NULL) return;
+ if (this->glyph_to_sprite == nullptr) return;
for (int i = 0; i < 256; i++) {
- if (this->glyph_to_sprite[i] == NULL) continue;
+ if (this->glyph_to_sprite[i] == nullptr) continue;
for (int j = 0; j < 256; j++) {
if (this->glyph_to_sprite[i][j].duplicate) continue;
@@ -438,27 +438,27 @@ void FreeTypeFontCache::ClearFontCache()
}
free(this->glyph_to_sprite);
- this->glyph_to_sprite = NULL;
+ this->glyph_to_sprite = nullptr;
Layouter::ResetFontCache(this->fs);
}
FreeTypeFontCache::GlyphEntry *FreeTypeFontCache::GetGlyphPtr(GlyphID key)
{
- if (this->glyph_to_sprite == NULL) return NULL;
- if (this->glyph_to_sprite[GB(key, 8, 8)] == NULL) return NULL;
+ if (this->glyph_to_sprite == nullptr) return nullptr;
+ if (this->glyph_to_sprite[GB(key, 8, 8)] == nullptr) return nullptr;
return &this->glyph_to_sprite[GB(key, 8, 8)][GB(key, 0, 8)];
}
void FreeTypeFontCache::SetGlyphPtr(GlyphID key, const GlyphEntry *glyph, bool duplicate)
{
- if (this->glyph_to_sprite == NULL) {
+ if (this->glyph_to_sprite == nullptr) {
DEBUG(freetype, 3, "Allocating root glyph cache for size %u", this->fs);
this->glyph_to_sprite = CallocT<GlyphEntry*>(256);
}
- if (this->glyph_to_sprite[GB(key, 8, 8)] == NULL) {
+ if (this->glyph_to_sprite[GB(key, 8, 8)] == nullptr) {
DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), this->fs);
this->glyph_to_sprite[GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
}
@@ -497,7 +497,7 @@ const Sprite *FreeTypeFontCache::GetGlyph(GlyphID key)
/* Check for the glyph in our cache */
GlyphEntry *glyph = this->GetGlyphPtr(key);
- if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
+ if (glyph != nullptr && glyph->sprite != nullptr) return glyph->sprite;
FT_GlyphSlot slot = this->face->glyph;
@@ -535,7 +535,7 @@ const Sprite *FreeTypeFontCache::GetGlyph(GlyphID key)
};
Sprite *spr = BlitterFactory::GetCurrentBlitter()->Encode(&builtin_questionmark, AllocateFont);
- assert(spr != NULL);
+ assert(spr != nullptr);
new_glyph.sprite = spr;
new_glyph.width = spr->width + (this->fs != FS_NORMAL);
this->SetGlyphPtr(key, &new_glyph, false);
@@ -611,7 +611,7 @@ uint FreeTypeFontCache::GetGlyphWidth(GlyphID key)
if ((key & SPRITE_GLYPH) != 0) return this->parent->GetGlyphWidth(key);
GlyphEntry *glyph = this->GetGlyphPtr(key);
- if (glyph == NULL || glyph->sprite == NULL) {
+ if (glyph == nullptr || glyph->sprite == nullptr) {
this->GetGlyph(key);
glyph = this->GetGlyphPtr(key);
}
@@ -639,9 +639,9 @@ const void *FreeTypeFontCache::GetFontTable(uint32 tag, size_t &length)
}
FT_ULong len = 0;
- FT_Byte *result = NULL;
+ FT_Byte *result = nullptr;
- FT_Load_Sfnt_Table(this->face, tag, 0, NULL, &len);
+ FT_Load_Sfnt_Table(this->face, tag, 0, nullptr, &len);
if (len > 0) {
result = MallocT<FT_Byte>(len);
@@ -685,6 +685,6 @@ void UninitFreeType()
#ifdef WITH_FREETYPE
FT_Done_FreeType(_library);
- _library = NULL;
+ _library = nullptr;
#endif /* WITH_FREETYPE */
}
diff --git a/src/fontcache.h b/src/fontcache.h
index 1f5e56d92..9a08ba09f 100644
--- a/src/fontcache.h
+++ b/src/fontcache.h
@@ -147,7 +147,7 @@ public:
*/
inline bool HasParent()
{
- return this->parent != NULL;
+ return this->parent != nullptr;
}
/**
diff --git a/src/fontdetection.cpp b/src/fontdetection.cpp
index 4279d60f3..3a5893e11 100644
--- a/src/fontdetection.cpp
+++ b/src/fontdetection.cpp
@@ -53,7 +53,7 @@ const char *GetShortPath(const TCHAR *long_path)
#ifdef UNICODE
WCHAR short_path_w[MAX_PATH];
GetShortPathName(long_path, short_path_w, lengthof(short_path_w));
- WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, lengthof(short_path), NULL, NULL);
+ WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, lengthof(short_path), nullptr, nullptr);
#else
/* Technically not needed, but do it for consistency. */
GetShortPathName(long_path, short_path, lengthof(short_path));
@@ -101,7 +101,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
DWORD vbuflen = lengthof(vbuffer);
DWORD dbuflen = lengthof(dbuffer);
- ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
+ ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, nullptr, nullptr, (byte*)dbuffer, &dbuflen);
if (ret != ERROR_SUCCESS) goto registry_no_font_found;
/* The font names in the registry are of the following 3 forms:
@@ -114,16 +114,16 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
* by '&'. Our best bet will be to do substr match for the fontname
* and then let FreeType figure out which index to load */
s = _tcschr(vbuffer, _T('('));
- if (s != NULL) s[-1] = '\0';
+ if (s != nullptr) s[-1] = '\0';
- if (_tcschr(vbuffer, _T('&')) == NULL) {
+ if (_tcschr(vbuffer, _T('&')) == nullptr) {
if (_tcsicmp(vbuffer, font_namep) == 0) break;
} else {
- if (_tcsstr(vbuffer, font_namep) != NULL) break;
+ if (_tcsstr(vbuffer, font_namep) != nullptr) break;
}
}
- if (!SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
+ if (!SUCCEEDED(OTTDSHGetFolderPath(nullptr, CSIDL_FONTS, nullptr, SHGFP_TYPE_CURRENT, vbuffer))) {
DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
goto folder_error;
}
@@ -175,7 +175,7 @@ registry_no_font_found:
static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont)
{
static char font_name[MAX_PATH];
- const char *ret_font_name = NULL;
+ const char *ret_font_name = nullptr;
uint pos = 0;
HDC dc;
HGDIOBJ oldfont;
@@ -184,11 +184,11 @@ static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont)
uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset;
HFONT font = CreateFontIndirect(&logfont->elfLogFont);
- if (font == NULL) goto err1;
+ if (font == nullptr) goto err1;
- dc = GetDC(NULL);
+ dc = GetDC(nullptr);
oldfont = SelectObject(dc, font);
- dw = GetFontData(dc, 'eman', 0, NULL, 0);
+ dw = GetFontData(dc, 'eman', 0, nullptr, 0);
if (dw == GDI_ERROR) goto err2;
buf = MallocT<byte>(dw);
@@ -236,10 +236,10 @@ err3:
free(buf);
err2:
SelectObject(dc, oldfont);
- ReleaseDC(NULL, dc);
+ ReleaseDC(nullptr, dc);
DeleteObject(font);
err1:
- return ret_font_name == NULL ? WIDE_TO_MB((const TCHAR*)logfont->elfFullName) : ret_font_name;
+ return ret_font_name == nullptr ? WIDE_TO_MB((const TCHAR*)logfont->elfFullName) : ret_font_name;
}
class FontList {
@@ -249,10 +249,10 @@ protected:
uint capacity;
public:
- FontList() : fonts(NULL), items(0), capacity(0) { };
+ FontList() : fonts(nullptr), items(0), capacity(0) { };
~FontList() {
- if (this->fonts == NULL) return;
+ if (this->fonts == nullptr) return;
for (uint i = 0; i < this->items; i++) {
free(this->fonts[i]);
@@ -303,12 +303,12 @@ static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXT
FONTSIGNATURE fs;
memset(&fs, 0, sizeof(fs));
HFONT font = CreateFontIndirect(&logfont->elfLogFont);
- if (font != NULL) {
- HDC dc = GetDC(NULL);
+ if (font != nullptr) {
+ HDC dc = GetDC(nullptr);
HGDIOBJ oldfont = SelectObject(dc, font);
GetTextCharsetInfo(dc, &fs, 0);
SelectObject(dc, oldfont);
- ReleaseDC(NULL, dc);
+ ReleaseDC(nullptr, dc);
DeleteObject(font);
}
if ((fs.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (fs.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) return 1;
@@ -322,7 +322,7 @@ static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXT
strecpy(font_name + strlen(font_name) + 1, english_name, lastof(font_name));
/* Check whether we can actually load the font. */
- bool ft_init = _library != NULL;
+ bool ft_init = _library != nullptr;
bool found = false;
FT_Face face;
/* Init FreeType if needed. */
@@ -333,13 +333,13 @@ static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXT
if (!ft_init) {
/* Uninit FreeType if we did the init. */
FT_Done_FreeType(_library);
- _library = NULL;
+ _library = nullptr;
}
if (!found) return 1;
info->callback->SetFontNames(info->settings, font_name);
- if (info->callback->FindMissingGlyphs(NULL)) return 1;
+ if (info->callback->FindMissingGlyphs(nullptr)) return 1;
DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name);
return 0; // stop enumerating
}
@@ -362,9 +362,9 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
font.lfFaceName[0] = '\0';
font.lfPitchAndFamily = 0;
- HDC dc = GetDC(NULL);
+ HDC dc = GetDC(nullptr);
int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0);
- ReleaseDC(NULL, dc);
+ ReleaseDC(nullptr, dc);
return ret == 0;
}
@@ -400,14 +400,14 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
CFRelease(name);
/* Loop over all matches until we can get a path for one of them. */
- for (CFIndex i = 0; descs != NULL && i < CFArrayGetCount(descs) && os_err != noErr; i++) {
- CTFontRef font = CTFontCreateWithFontDescriptor((CTFontDescriptorRef)CFArrayGetValueAtIndex(descs, i), 0.0, NULL);
+ for (CFIndex i = 0; descs != nullptr && i < CFArrayGetCount(descs) && os_err != noErr; i++) {
+ CTFontRef font = CTFontCreateWithFontDescriptor((CTFontDescriptorRef)CFArrayGetValueAtIndex(descs, i), 0.0, nullptr);
CFURLRef fontURL = (CFURLRef)CTFontCopyAttribute(font, kCTFontURLAttribute);
if (CFURLGetFileSystemRepresentation(fontURL, true, file_path, lengthof(file_path))) os_err = noErr;
CFRelease(font);
CFRelease(fontURL);
}
- if (descs != NULL) CFRelease(descs);
+ if (descs != nullptr) CFRelease(descs);
} else
#endif
{
@@ -467,7 +467,7 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
/* Just copy the first part of the isocode. */
strecpy(lang, language_isocode, lastof(lang));
char *sep = strchr(lang, '_');
- if (sep != NULL) *sep = '\0';
+ if (sep != nullptr) *sep = '\0';
}
/* Create a font descriptor matching the wanted language and latin (english) glyphs. */
@@ -487,7 +487,7 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
CFRelease(mandatory_attribs);
CFRelease(lang_desc);
- for (CFIndex i = 0; descs != NULL && i < CFArrayGetCount(descs); i++) {
+ for (CFIndex i = 0; descs != nullptr && i < CFArrayGetCount(descs); i++) {
CTFontDescriptorRef font = (CTFontDescriptorRef)CFArrayGetValueAtIndex(descs, i);
/* Get font traits. */
@@ -515,13 +515,13 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
/* Save result. */
callback->SetFontNames(settings, name);
- if (!callback->FindMissingGlyphs(NULL)) {
+ if (!callback->FindMissingGlyphs(nullptr)) {
DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name);
result = true;
break;
}
}
- if (descs != NULL) CFRelease(descs);
+ if (descs != nullptr) CFRelease(descs);
} else
#endif
{
@@ -530,7 +530,7 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
* are available to the application. */
ATSFontIterator itr;
ATSFontRef font;
- ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsDefaultScope, &itr);
+ ATSFontIteratorCreate(kATSFontContextLocal, nullptr, nullptr, kATSOptionFlagsDefaultScope, &itr);
while (!result && ATSFontIteratorNext(itr, &font) == noErr) {
/* Get font name. */
char name[128];
@@ -545,14 +545,14 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
if (monospace != callback->Monospace()) continue;
/* We only want the base font and not bold or italic variants. */
- if (strstr(name, "Italic") != NULL || strstr(name, "Bold")) continue;
+ if (strstr(name, "Italic") != nullptr || strstr(name, "Bold")) continue;
/* Skip some inappropriate or ugly looking fonts that have better alternatives. */
if (name[0] == '.' || strncmp(name, "Apple Symbols", 13) == 0 || strncmp(name, "LastResort", 10) == 0) continue;
/* Save result. */
callback->SetFontNames(settings, name);
- if (!callback->FindMissingGlyphs(NULL)) {
+ if (!callback->FindMissingGlyphs(nullptr)) {
DEBUG(freetype, 2, "ATS-Font for %s: %s", language_isocode, name);
result = true;
break;
@@ -566,10 +566,10 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
/* For some OS versions, the font 'Arial Unicode MS' does not report all languages it
* supports. If we didn't find any other font, just try it, maybe we get lucky. */
callback->SetFontNames(settings, "Arial Unicode MS");
- result = !callback->FindMissingGlyphs(NULL);
+ result = !callback->FindMissingGlyphs(nullptr);
}
- callback->FindMissingGlyphs(NULL);
+ callback->FindMissingGlyphs(nullptr);
return result;
}
@@ -599,7 +599,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
/* Split & strip the font's style */
font_family = stredup(font_name);
font_style = strchr(font_family, ',');
- if (font_style != NULL) {
+ if (font_style != nullptr) {
font_style[0] = '\0';
font_style++;
while (*font_style == ' ' || *font_style == '\t') font_style++;
@@ -607,13 +607,13 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
/* Resolve the name and populate the information structure */
pat = FcNameParse((FcChar8*)font_family);
- if (font_style != NULL) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
+ if (font_style != nullptr) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
FcConfigSubstitute(0, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
fs = FcFontSetCreate();
match = FcFontMatch(0, pat, &result);
- if (fs != NULL && match != NULL) {
+ if (fs != nullptr && match != nullptr) {
int i;
FcChar8 *family;
FcChar8 *style;
@@ -627,7 +627,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
FcPatternGetString(fs->fonts[i], FC_STYLE, 0, &style) == FcResultMatch) {
/* The correct style? */
- if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
+ if (font_style != nullptr && strcasecmp(font_style, (char*)style) != 0) continue;
/* Font config takes the best shot, which, if the family name is spelled
* wrongly a 'random' font, so check whether the family name is the
@@ -660,29 +660,29 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
char lang[16];
seprintf(lang, lastof(lang), ":lang=%s", language_isocode);
char *split = strchr(lang, '_');
- if (split != NULL) *split = '\0';
+ if (split != nullptr) *split = '\0';
/* First create a pattern to match the wanted language. */
FcPattern *pat = FcNameParse((FcChar8*)lang);
/* We only want to know the filename. */
- FcObjectSet *os = FcObjectSetBuild(FC_FILE, FC_SPACING, FC_SLANT, FC_WEIGHT, NULL);
+ FcObjectSet *os = FcObjectSetBuild(FC_FILE, FC_SPACING, FC_SLANT, FC_WEIGHT, nullptr);
/* Get the list of filenames matching the wanted language. */
- FcFontSet *fs = FcFontList(NULL, pat, os);
+ FcFontSet *fs = FcFontList(nullptr, pat, os);
/* We don't need these anymore. */
FcObjectSetDestroy(os);
FcPatternDestroy(pat);
- if (fs != NULL) {
+ if (fs != nullptr) {
int best_weight = -1;
- const char *best_font = NULL;
+ const char *best_font = nullptr;
for (int i = 0; i < fs->nfont; i++) {
FcPattern *font = fs->fonts[i];
- FcChar8 *file = NULL;
+ FcChar8 *file = nullptr;
FcResult res = FcPatternGetString(font, FC_FILE, 0, &file);
- if (res != FcResultMatch || file == NULL) {
+ if (res != FcResultMatch || file == nullptr) {
continue;
}
@@ -701,7 +701,7 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
callback->SetFontNames(settings, (const char*)file);
- bool missing = callback->FindMissingGlyphs(NULL);
+ bool missing = callback->FindMissingGlyphs(nullptr);
DEBUG(freetype, 1, "Font \"%s\" misses%s glyphs", file, missing ? "" : " no");
if (!missing) {
@@ -710,7 +710,7 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i
}
}
- if (best_font != NULL) {
+ if (best_font != nullptr) {
ret = true;
callback->SetFontNames(settings, best_font);
InitFreeType(callback->Monospace());
diff --git a/src/game/game_config.cpp b/src/game/game_config.cpp
index 50cd5da4e..f96985ef7 100644
--- a/src/game/game_config.cpp
+++ b/src/game/game_config.cpp
@@ -25,7 +25,7 @@
} else {
config = &_settings_game.game_config;
}
- if (*config == NULL) *config = new GameConfig();
+ if (*config == nullptr) *config = new GameConfig();
return *config;
}
@@ -42,5 +42,5 @@ ScriptInfo *GameConfig::FindInfo(const char *name, int version, bool force_exact
bool GameConfig::ResetInfo(bool force_exact_match)
{
this->info = (ScriptInfo *)Game::FindInfo(this->name, force_exact_match ? this->version : -1, force_exact_match);
- return this->info != NULL;
+ return this->info != nullptr;
}
diff --git a/src/game/game_core.cpp b/src/game/game_core.cpp
index 7b05abb40..181e8b6bb 100644
--- a/src/game/game_core.cpp
+++ b/src/game/game_core.cpp
@@ -25,10 +25,10 @@
#include "../safeguards.h"
/* static */ uint Game::frame_counter = 0;
-/* static */ GameInfo *Game::info = NULL;
-/* static */ GameInstance *Game::instance = NULL;
-/* static */ GameScannerInfo *Game::scanner_info = NULL;
-/* static */ GameScannerLibrary *Game::scanner_library = NULL;
+/* static */ GameInfo *Game::info = nullptr;
+/* static */ GameInstance *Game::instance = nullptr;
+/* static */ GameScannerInfo *Game::scanner_info = nullptr;
+/* static */ GameScannerLibrary *Game::scanner_library = nullptr;
/* static */ void Game::GameLoop()
{
@@ -36,7 +36,7 @@
PerformanceMeasurer::SetInactive(PFE_GAMESCRIPT);
return;
}
- if (Game::instance == NULL) {
+ if (Game::instance == nullptr) {
PerformanceMeasurer::SetInactive(PFE_GAMESCRIPT);
return;
}
@@ -58,11 +58,11 @@
/* static */ void Game::Initialize()
{
- if (Game::instance != NULL) Game::Uninitialize(true);
+ if (Game::instance != nullptr) Game::Uninitialize(true);
Game::frame_counter = 0;
- if (Game::scanner_info == NULL) {
+ if (Game::scanner_info == nullptr) {
TarScanner::DoScan(TarScanner::GAME);
Game::scanner_info = new GameScannerInfo();
Game::scanner_info->Initialize();
@@ -73,14 +73,14 @@
/* static */ void Game::StartNew()
{
- if (Game::instance != NULL) return;
+ if (Game::instance != nullptr) return;
/* Clients shouldn't start GameScripts */
if (_networking && !_network_server) return;
GameConfig *config = GameConfig::GetConfig(GameConfig::SSS_FORCE_GAME);
GameInfo *info = config->GetInfo();
- if (info == NULL) return;
+ if (info == nullptr) return;
config->AnchorUnchangeableSettings();
@@ -101,8 +101,8 @@
Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
delete Game::instance;
- Game::instance = NULL;
- Game::info = NULL;
+ Game::instance = nullptr;
+ Game::info = nullptr;
cur_company.Restore();
@@ -111,33 +111,33 @@
} else {
delete Game::scanner_info;
delete Game::scanner_library;
- Game::scanner_info = NULL;
- Game::scanner_library = NULL;
+ Game::scanner_info = nullptr;
+ Game::scanner_library = nullptr;
- if (_settings_game.game_config != NULL) {
+ if (_settings_game.game_config != nullptr) {
delete _settings_game.game_config;
- _settings_game.game_config = NULL;
+ _settings_game.game_config = nullptr;
}
- if (_settings_newgame.game_config != NULL) {
+ if (_settings_newgame.game_config != nullptr) {
delete _settings_newgame.game_config;
- _settings_newgame.game_config = NULL;
+ _settings_newgame.game_config = nullptr;
}
}
}
/* static */ void Game::Pause()
{
- if (Game::instance != NULL) Game::instance->Pause();
+ if (Game::instance != nullptr) Game::instance->Pause();
}
/* static */ void Game::Unpause()
{
- if (Game::instance != NULL) Game::instance->Unpause();
+ if (Game::instance != nullptr) Game::instance->Unpause();
}
/* static */ bool Game::IsPaused()
{
- return Game::instance != NULL? Game::instance->IsPaused() : false;
+ return Game::instance != nullptr? Game::instance->IsPaused() : false;
}
/* static */ void Game::NewEvent(ScriptEvent *event)
@@ -152,7 +152,7 @@
}
/* Check if Game instance is alive */
- if (Game::instance == NULL) {
+ if (Game::instance == nullptr) {
event->Release();
return;
}
@@ -169,23 +169,23 @@
{
/* Check for both newgame as current game if we can reload the GameInfo inside
* the GameConfig. If not, remove the Game from the list. */
- if (_settings_game.game_config != NULL && _settings_game.game_config->HasScript()) {
+ if (_settings_game.game_config != nullptr && _settings_game.game_config->HasScript()) {
if (!_settings_game.game_config->ResetInfo(true)) {
DEBUG(script, 0, "After a reload, the GameScript by the name '%s' was no longer found, and removed from the list.", _settings_game.game_config->GetName());
- _settings_game.game_config->Change(NULL);
- if (Game::instance != NULL) {
+ _settings_game.game_config->Change(nullptr);
+ if (Game::instance != nullptr) {
delete Game::instance;
- Game::instance = NULL;
- Game::info = NULL;
+ Game::instance = nullptr;
+ Game::info = nullptr;
}
- } else if (Game::instance != NULL) {
+ } else if (Game::instance != nullptr) {
Game::info = _settings_game.game_config->GetInfo();
}
}
- if (_settings_newgame.game_config != NULL && _settings_newgame.game_config->HasScript()) {
+ if (_settings_newgame.game_config != nullptr && _settings_newgame.game_config->HasScript()) {
if (!_settings_newgame.game_config->ResetInfo(false)) {
DEBUG(script, 0, "After a reload, the GameScript by the name '%s' was no longer found, and removed from the list.", _settings_newgame.game_config->GetName());
- _settings_newgame.game_config->Change(NULL);
+ _settings_newgame.game_config->Change(nullptr);
}
}
}
@@ -206,7 +206,7 @@
/* static */ void Game::Save()
{
- if (Game::instance != NULL && (!_networking || _network_server)) {
+ if (Game::instance != nullptr && (!_networking || _network_server)) {
Backup<CompanyByte> cur_company(_current_company, OWNER_DEITY, FILE_LINE);
Game::instance->Save();
cur_company.Restore();
@@ -217,7 +217,7 @@
/* static */ void Game::Load(int version)
{
- if (Game::instance != NULL && (!_networking || _network_server)) {
+ if (Game::instance != nullptr && (!_networking || _network_server)) {
Backup<CompanyByte> cur_company(_current_company, OWNER_DEITY, FILE_LINE);
Game::instance->Load(version);
cur_company.Restore();
diff --git a/src/game/game_info.cpp b/src/game/game_info.cpp
index 0aa316174..d815e6fd2 100644
--- a/src/game/game_info.cpp
+++ b/src/game/game_info.cpp
@@ -55,8 +55,8 @@ template <> const char *GetClassName<GameInfo, ST_GS>() { return "GSInfo"; }
/* static */ SQInteger GameInfo::Constructor(HSQUIRRELVM vm)
{
/* Get the GameInfo */
- SQUserPointer instance = NULL;
- if (SQ_FAILED(sq_getinstanceup(vm, 2, &instance, 0)) || instance == NULL) return sq_throwerror(vm, "Pass an instance of a child class of GameInfo to RegisterGame");
+ SQUserPointer instance = nullptr;
+ if (SQ_FAILED(sq_getinstanceup(vm, 2, &instance, 0)) || instance == nullptr) return sq_throwerror(vm, "Pass an instance of a child class of GameInfo to RegisterGame");
GameInfo *info = (GameInfo *)instance;
SQInteger res = ScriptInfo::Constructor(vm, info);
@@ -82,7 +82,7 @@ template <> const char *GetClassName<GameInfo, ST_GS>() { return "GSInfo"; }
}
/* Remove the link to the real instance, else it might get deleted by RegisterGame() */
- sq_setinstanceup(vm, 2, NULL);
+ sq_setinstanceup(vm, 2, nullptr);
/* Register the Game to the base system */
info->GetScanner()->RegisterScript(info);
return 0;
@@ -91,7 +91,7 @@ template <> const char *GetClassName<GameInfo, ST_GS>() { return "GSInfo"; }
GameInfo::GameInfo() :
min_loadable_version(0),
is_developer_only(false),
- api_version(NULL)
+ api_version(nullptr)
{
}
diff --git a/src/game/game_info.hpp b/src/game/game_info.hpp
index a799ed7d6..8a2215d52 100644
--- a/src/game/game_info.hpp
+++ b/src/game/game_info.hpp
@@ -51,7 +51,7 @@ private:
/** All static information from an Game library like name, version, etc. */
class GameLibrary : public ScriptInfo {
public:
- GameLibrary() : ScriptInfo(), category(NULL) {};
+ GameLibrary() : ScriptInfo(), category(nullptr) {};
~GameLibrary();
/**
diff --git a/src/game/game_instance.cpp b/src/game/game_instance.cpp
index e2b377511..26a61a790 100644
--- a/src/game/game_instance.cpp
+++ b/src/game/game_instance.cpp
@@ -239,10 +239,10 @@ void GameInstance::Died()
ShowAIDebugWindow(OWNER_DEITY);
const GameInfo *info = Game::GetInfo();
- if (info != NULL) {
+ if (info != nullptr) {
ShowErrorMessage(STR_ERROR_AI_PLEASE_REPORT_CRASH, INVALID_STRING_ID, WL_WARNING);
- if (info->GetURL() != NULL) {
+ if (info->GetURL() != nullptr) {
ScriptLog::Info("Please report the error to the following URL:");
ScriptLog::Info(info->GetURL());
}
diff --git a/src/game/game_scanner.cpp b/src/game/game_scanner.cpp
index 38afdd135..862c867cf 100644
--- a/src/game/game_scanner.cpp
+++ b/src/game/game_scanner.cpp
@@ -35,14 +35,14 @@ void GameScannerInfo::RegisterAPI(class Squirrel *engine)
GameInfo *GameScannerInfo::FindInfo(const char *nameParam, int versionParam, bool force_exact_match)
{
- if (this->info_list.size() == 0) return NULL;
- if (nameParam == NULL) return NULL;
+ if (this->info_list.size() == 0) return nullptr;
+ if (nameParam == nullptr) return nullptr;
char game_name[1024];
strecpy(game_name, nameParam, lastof(game_name));
strtolower(game_name);
- GameInfo *info = NULL;
+ GameInfo *info = nullptr;
int version = -1;
if (versionParam == -1) {
@@ -51,7 +51,7 @@ GameInfo *GameScannerInfo::FindInfo(const char *nameParam, int versionParam, boo
/* If we didn't find a match Game script, maybe the user included a version */
char *e = strrchr(game_name, '.');
- if (e == NULL) return NULL;
+ if (e == nullptr) return nullptr;
*e = '\0';
e++;
versionParam = atoi(e);
@@ -106,7 +106,7 @@ GameLibrary *GameScannerLibrary::FindLibrary(const char *library, int version)
/* Check if the library + version exists */
ScriptInfoList::iterator iter = this->info_list.find(library_name);
- if (iter == this->info_list.end()) return NULL;
+ if (iter == this->info_list.end()) return nullptr;
return static_cast<GameLibrary *>((*iter).second);
}
diff --git a/src/game/game_scanner.hpp b/src/game/game_scanner.hpp
index 492545c2b..2530ec792 100644
--- a/src/game/game_scanner.hpp
+++ b/src/game/game_scanner.hpp
@@ -23,7 +23,7 @@ public:
* @param nameParam The name of the game script.
* @param versionParam The version of the game script, or -1 if you want the latest.
* @param force_exact_match Only match name+version, never latest.
- * @return NULL if no match found, otherwise the game script that matched.
+ * @return nullptr if no match found, otherwise the game script that matched.
*/
class GameInfo *FindInfo(const char *nameParam, int versionParam, bool force_exact_match);
@@ -44,7 +44,7 @@ public:
* Find a library in the pool.
* @param library The library name to find.
* @param version The version the library should have.
- * @return The library if found, NULL otherwise.
+ * @return The library if found, nullptr otherwise.
*/
class GameLibrary *FindLibrary(const char *library, int version);
diff --git a/src/game/game_text.cpp b/src/game/game_text.cpp
index 944bf82d1..bde2a5a69 100644
--- a/src/game/game_text.cpp
+++ b/src/game/game_text.cpp
@@ -63,11 +63,11 @@ void NORETURN CDECL strgen_fatal(const char *s, ...)
/**
* Create a new container for language strings.
* @param language The language name.
- * @param end If not NULL, terminate \a language at this position.
+ * @param end If not nullptr, terminate \a language at this position.
*/
LanguageStrings::LanguageStrings(const char *language, const char *end)
{
- this->language = stredup(language, end != NULL ? end - 1 : NULL);
+ this->language = stredup(language, end != nullptr ? end - 1 : nullptr);
}
/** Free everything. */
@@ -79,31 +79,31 @@ LanguageStrings::~LanguageStrings()
/**
* Read all the raw language strings from the given file.
* @param file The file to read from.
- * @return The raw strings, or NULL upon error.
+ * @return The raw strings, or nullptr upon error.
*/
std::unique_ptr<LanguageStrings> ReadRawLanguageStrings(const char *file)
{
try {
size_t to_read;
FILE *fh = FioFOpenFile(file, "rb", GAME_DIR, &to_read);
- if (fh == NULL) return NULL;
+ if (fh == nullptr) return nullptr;
FileCloser fhClose(fh);
const char *langname = strrchr(file, PATHSEPCHAR);
- if (langname == NULL) {
+ if (langname == nullptr) {
langname = file;
} else {
langname++;
}
/* Check for invalid empty filename */
- if (*langname == '.' || *langname == 0) return NULL;
+ if (*langname == '.' || *langname == 0) return nullptr;
std::unique_ptr<LanguageStrings> ret(new LanguageStrings(langname, strchr(langname, '.')));
char buffer[2048];
- while (to_read != 0 && fgets(buffer, sizeof(buffer), fh) != NULL) {
+ while (to_read != 0 && fgets(buffer, sizeof(buffer), fh) != nullptr) {
size_t len = strlen(buffer);
/* Remove trailing spaces/newlines from the string. */
@@ -122,7 +122,7 @@ std::unique_ptr<LanguageStrings> ReadRawLanguageStrings(const char *file)
return ret;
} catch (...) {
- return NULL;
+ return nullptr;
}
}
@@ -146,7 +146,7 @@ struct StringListReader : StringReader {
char *ReadLine(char *buffer, const char *last) override
{
- if (this->p == this->end) return NULL;
+ if (this->p == this->end) return nullptr;
strecpy(buffer, this->p->c_str(), last);
this->p++;
@@ -237,7 +237,7 @@ public:
if (strcmp(filename, exclude) == 0) return true;
auto ls = ReadRawLanguageStrings(filename);
- if (ls == NULL) return false;
+ if (ls == nullptr) return false;
gs->raw_strings.push_back(std::move(ls));
return true;
@@ -254,14 +254,14 @@ GameStrings *LoadTranslations()
char filename[512];
strecpy(filename, info->GetMainScript(), lastof(filename));
char *e = strrchr(filename, PATHSEPCHAR);
- if (e == NULL) return NULL;
+ if (e == nullptr) return nullptr;
e++; // Make 'e' point after the PATHSEPCHAR
strecpy(e, "lang" PATHSEP "english.txt", lastof(filename));
- if (!FioCheckFileExists(filename, GAME_DIR)) return NULL;
+ if (!FioCheckFileExists(filename, GAME_DIR)) return nullptr;
auto ls = ReadRawLanguageStrings(filename);
- if (ls == NULL) return NULL;
+ if (ls == nullptr) return nullptr;
GameStrings *gs = new GameStrings();
try {
@@ -274,7 +274,7 @@ GameStrings *LoadTranslations()
const char *tar_filename = info->GetTarFile();
TarList::iterator iter;
- if (tar_filename != NULL && (iter = _tar_list[GAME_DIR].find(tar_filename)) != _tar_list[GAME_DIR].end()) {
+ if (tar_filename != nullptr && (iter = _tar_list[GAME_DIR].find(tar_filename)) != _tar_list[GAME_DIR].end()) {
/* The main script is in a tar file, so find all files that
* are in the same tar and add them to the langfile scanner. */
TarFileList::iterator tar;
@@ -297,7 +297,7 @@ GameStrings *LoadTranslations()
return gs;
} catch (...) {
delete gs;
- return NULL;
+ return nullptr;
}
}
@@ -327,7 +327,7 @@ void GameStrings::Compile()
}
/** The currently loaded game strings. */
-GameStrings *_current_data = NULL;
+GameStrings *_current_data = nullptr;
/**
* Get the string pointer of a particular game string.
@@ -348,7 +348,7 @@ void RegisterGameTranslation(Squirrel *engine)
{
delete _current_data;
_current_data = LoadTranslations();
- if (_current_data == NULL) return;
+ if (_current_data == nullptr) return;
HSQUIRRELVM vm = engine->GetVM();
sq_pushroottable(vm);
@@ -373,19 +373,19 @@ void RegisterGameTranslation(Squirrel *engine)
*/
void ReconsiderGameScriptLanguage()
{
- if (_current_data == NULL) return;
+ if (_current_data == nullptr) return;
char temp[MAX_PATH];
strecpy(temp, _current_language->file, lastof(temp));
/* Remove the extension */
char *l = strrchr(temp, '.');
- assert(l != NULL);
+ assert(l != nullptr);
*l = '\0';
/* Skip the path */
char *language = strrchr(temp, PATHSEPCHAR);
- assert(language != NULL);
+ assert(language != nullptr);
language++;
for (auto &p : _current_data->compiled_strings) {
diff --git a/src/game/game_text.hpp b/src/game/game_text.hpp
index d199a5281..c662e28f4 100644
--- a/src/game/game_text.hpp
+++ b/src/game/game_text.hpp
@@ -23,7 +23,7 @@ struct LanguageStrings {
const char *language; ///< Name of the language (base filename).
StringList lines; ///< The lines of the file to pass into the parser/encoder.
- LanguageStrings(const char *language, const char *end = NULL);
+ LanguageStrings(const char *language, const char *end = nullptr);
~LanguageStrings();
};
diff --git a/src/gamelog.cpp b/src/gamelog.cpp
index 1698dadad..025d2ab8d 100644
--- a/src/gamelog.cpp
+++ b/src/gamelog.cpp
@@ -34,9 +34,9 @@ extern byte _sl_minor_version; ///< the minor savegame version, DO NOT USE!
static GamelogActionType _gamelog_action_type = GLAT_NONE; ///< action to record if anything changes
-LoggedAction *_gamelog_action = NULL; ///< first logged action
+LoggedAction *_gamelog_action = nullptr; ///< first logged action
uint _gamelog_actions = 0; ///< number of actions
-static LoggedAction *_current_action = NULL; ///< current action we are logging, NULL when there is no action active
+static LoggedAction *_current_action = nullptr; ///< current action we are logging, nullptr when there is no action active
/**
@@ -81,9 +81,9 @@ void GamelogStopAction()
{
assert(_gamelog_action_type != GLAT_NONE); // nobody should try to stop if there is no action in progress
- bool print = _current_action != NULL;
+ bool print = _current_action != nullptr;
- _current_action = NULL;
+ _current_action = nullptr;
_gamelog_action_type = GLAT_NONE;
if (print) GamelogPrintDebug(5);
@@ -114,9 +114,9 @@ void GamelogReset()
assert(_gamelog_action_type == GLAT_NONE);
GamelogFree(_gamelog_action, _gamelog_actions);
- _gamelog_action = NULL;
+ _gamelog_action = nullptr;
_gamelog_actions = 0;
- _current_action = NULL;
+ _current_action = nullptr;
}
/**
@@ -132,18 +132,18 @@ static char *PrintGrfInfo(char *buf, const char *last, uint grfid, const uint8 *
{
char txt[40];
- if (md5sum != NULL) {
+ if (md5sum != nullptr) {
md5sumToString(txt, lastof(txt), md5sum);
buf += seprintf(buf, last, "GRF ID %08X, checksum %s", BSWAP32(grfid), txt);
} else {
buf += seprintf(buf, last, "GRF ID %08X", BSWAP32(grfid));
}
- if (gc != NULL) {
+ if (gc != nullptr) {
buf += seprintf(buf, last, ", filename: %s (md5sum matches)", gc->filename);
} else {
gc = FindGRFConfig(grfid, FGCM_ANY);
- if (gc != NULL) {
+ if (gc != nullptr) {
buf += seprintf(buf, last, ", filename: %s (matches GRFID only)", gc->filename);
} else {
buf += seprintf(buf, last, ", unknown GRF");
@@ -273,7 +273,7 @@ void GamelogPrint(GamelogPrintProc *proc)
case GLCT_GRFREM: {
GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
buf += seprintf(buf, lastof(buffer), la->at == GLAT_LOAD ? "Missing NewGRF: " : "Removed NewGRF: ");
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfrem.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfrem.grfid, nullptr, gm != grf_names.End() ? gm->second.gc : nullptr);
if (gm == grf_names.End()) {
buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
} else {
@@ -299,7 +299,7 @@ void GamelogPrint(GamelogPrintProc *proc)
case GLCT_GRFPARAM: {
GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
buf += seprintf(buf, lastof(buffer), "GRF parameter changed: ");
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfparam.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfparam.grfid, nullptr, gm != grf_names.End() ? gm->second.gc : nullptr);
if (gm == grf_names.End()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
break;
}
@@ -308,7 +308,7 @@ void GamelogPrint(GamelogPrintProc *proc)
GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
buf += seprintf(buf, lastof(buffer), "GRF order changed: %08X moved %d places %s",
BSWAP32(lc->grfmove.grfid), abs(lc->grfmove.offset), lc->grfmove.offset >= 0 ? "down" : "up" );
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfmove.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfmove.grfid, nullptr, gm != grf_names.End() ? gm->second.gc : nullptr);
if (gm == grf_names.End()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
break;
}
@@ -321,7 +321,7 @@ void GamelogPrint(GamelogPrintProc *proc)
buf += seprintf(buf, lastof(buffer), "Rail vehicle changes length outside a depot: GRF ID %08X, internal ID 0x%X", BSWAP32(lc->grfbug.grfid), (uint)lc->grfbug.data);
break;
}
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfbug.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfbug.grfid, nullptr, gm != grf_names.End() ? gm->second.gc : nullptr);
if (gm == grf_names.End()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
break;
}
@@ -372,21 +372,21 @@ void GamelogPrintDebug(int level)
/**
* Allocates new LoggedChange and new LoggedAction if needed.
- * If there is no action active, NULL is returned.
+ * If there is no action active, nullptr is returned.
* @param ct type of change
- * @return new LoggedChange, or NULL if there is no action active
+ * @return new LoggedChange, or nullptr if there is no action active
*/
static LoggedChange *GamelogChange(GamelogChangeType ct)
{
- if (_current_action == NULL) {
- if (_gamelog_action_type == GLAT_NONE) return NULL;
+ if (_current_action == nullptr) {
+ if (_gamelog_action_type == GLAT_NONE) return nullptr;
_gamelog_action = ReallocT(_gamelog_action, _gamelog_actions + 1);
_current_action = &_gamelog_action[_gamelog_actions++];
_current_action->at = _gamelog_action_type;
_current_action->tick = _tick_counter;
- _current_action->change = NULL;
+ _current_action->change = nullptr;
_current_action->changes = 0;
}
@@ -416,7 +416,7 @@ void GamelogEmergency()
*/
bool GamelogTestEmergency()
{
- const LoggedChange *emergency = NULL;
+ const LoggedChange *emergency = nullptr;
const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
@@ -426,7 +426,7 @@ bool GamelogTestEmergency()
}
}
- return (emergency != NULL);
+ return (emergency != nullptr);
}
/**
@@ -437,7 +437,7 @@ void GamelogRevision()
assert(_gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_LOAD);
LoggedChange *lc = GamelogChange(GLCT_REVISION);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
memset(lc->revision.text, 0, sizeof(lc->revision.text));
strecpy(lc->revision.text, GetGamelogRevisionString(), lastof(lc->revision.text));
@@ -454,7 +454,7 @@ void GamelogMode()
assert(_gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_CHEAT);
LoggedChange *lc = GamelogChange(GLCT_MODE);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->mode.mode = _game_mode;
lc->mode.landscape = _settings_game.game_creation.landscape;
@@ -468,7 +468,7 @@ void GamelogOldver()
assert(_gamelog_action_type == GLAT_LOAD);
LoggedChange *lc = GamelogChange(GLCT_OLDVER);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->oldver.type = _savegame_type;
lc->oldver.version = (_savegame_type == SGT_OTTD ? ((uint32)_sl_version << 8 | _sl_minor_version) : _ttdp_version);
@@ -485,7 +485,7 @@ void GamelogSetting(const char *name, int32 oldval, int32 newval)
assert(_gamelog_action_type == GLAT_SETTING);
LoggedChange *lc = GamelogChange(GLCT_SETTING);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->setting.name = stredup(name);
lc->setting.oldval = oldval;
@@ -499,7 +499,7 @@ void GamelogSetting(const char *name, int32 oldval, int32 newval)
*/
void GamelogTestRevision()
{
- const LoggedChange *rev = NULL;
+ const LoggedChange *rev = nullptr;
const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
@@ -509,7 +509,7 @@ void GamelogTestRevision()
}
}
- if (rev == NULL || strcmp(rev->revision.text, GetGamelogRevisionString()) != 0 ||
+ if (rev == nullptr || strcmp(rev->revision.text, GetGamelogRevisionString()) != 0 ||
rev->revision.modified != _openttd_revision_modified ||
rev->revision.newgrf != _openttd_newgrf_version) {
GamelogRevision();
@@ -522,7 +522,7 @@ void GamelogTestRevision()
*/
void GamelogTestMode()
{
- const LoggedChange *mode = NULL;
+ const LoggedChange *mode = nullptr;
const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
@@ -532,7 +532,7 @@ void GamelogTestMode()
}
}
- if (mode == NULL || mode->mode.mode != _game_mode || mode->mode.landscape != _settings_game.game_creation.landscape) GamelogMode();
+ if (mode == nullptr || mode->mode.mode != _game_mode || mode->mode.landscape != _settings_game.game_creation.landscape) GamelogMode();
}
@@ -547,7 +547,7 @@ static void GamelogGRFBug(uint32 grfid, byte bug, uint64 data)
assert(_gamelog_action_type == GLAT_GRFBUG);
LoggedChange *lc = GamelogChange(GLCT_GRFBUG);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->grfbug.data = data;
lc->grfbug.grfid = grfid;
@@ -603,7 +603,7 @@ void GamelogGRFRemove(uint32 grfid)
assert(_gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_GRF);
LoggedChange *lc = GamelogChange(GLCT_GRFREM);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->grfrem.grfid = grfid;
}
@@ -619,7 +619,7 @@ void GamelogGRFAdd(const GRFConfig *newg)
if (!IsLoggableGrfConfig(newg)) return;
LoggedChange *lc = GamelogChange(GLCT_GRFADD);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->grfadd = newg->ident;
}
@@ -634,7 +634,7 @@ void GamelogGRFCompatible(const GRFIdentifier *newg)
assert(_gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_GRF);
LoggedChange *lc = GamelogChange(GLCT_GRFCOMPAT);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->grfcompat = *newg;
}
@@ -649,7 +649,7 @@ static void GamelogGRFMove(uint32 grfid, int32 offset)
assert(_gamelog_action_type == GLAT_GRF);
LoggedChange *lc = GamelogChange(GLCT_GRFMOVE);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->grfmove.grfid = grfid;
lc->grfmove.offset = offset;
@@ -665,7 +665,7 @@ static void GamelogGRFParameters(uint32 grfid)
assert(_gamelog_action_type == GLAT_GRF);
LoggedChange *lc = GamelogChange(GLCT_GRFPARAM);
- if (lc == NULL) return;
+ if (lc == nullptr) return;
lc->grfparam.grfid = grfid;
}
@@ -679,7 +679,7 @@ void GamelogGRFAddList(const GRFConfig *newg)
{
assert(_gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_LOAD);
- for (; newg != NULL; newg = newg->next) {
+ for (; newg != nullptr; newg = newg->next) {
GamelogGRFAdd(newg);
}
}
@@ -697,14 +697,14 @@ struct GRFList {
static GRFList *GenerateGRFList(const GRFConfig *grfc)
{
uint n = 0;
- for (const GRFConfig *g = grfc; g != NULL; g = g->next) {
+ for (const GRFConfig *g = grfc; g != nullptr; g = g->next) {
if (IsLoggableGrfConfig(g)) n++;
}
GRFList *list = (GRFList*)MallocT<byte>(sizeof(GRFList) + n * sizeof(GRFConfig*));
list->n = 0;
- for (const GRFConfig *g = grfc; g != NULL; g = g->next) {
+ for (const GRFConfig *g = grfc; g != nullptr; g = g->next) {
if (IsLoggableGrfConfig(g)) list->grf[list->n++] = g;
}
diff --git a/src/genworld.cpp b/src/genworld.cpp
index ee8768b62..f09b183e9 100644
--- a/src/genworld.cpp
+++ b/src/genworld.cpp
@@ -82,8 +82,8 @@ static void CleanupGeneration()
/* Show all vital windows again, because we have hidden them */
if (_gw.threaded && _game_mode != GM_MENU) ShowVitalWindows();
SetModalProgress(false);
- _gw.proc = NULL;
- _gw.abortp = NULL;
+ _gw.proc = nullptr;
+ _gw.abortp = nullptr;
_gw.threaded = false;
DeleteWindowByClass(WC_MODAL_PROGRESS);
@@ -171,7 +171,7 @@ static void _GenerateWorld()
if (_game_mode != GM_EDITOR) {
Game::StartNew();
- if (Game::GetInstance() != NULL) {
+ if (Game::GetInstance() != nullptr) {
SetGeneratingWorldProgress(GWP_RUNSCRIPT, 2500);
_generating_world = true;
for (i = 0; i < 2500; i++) {
@@ -192,7 +192,7 @@ static void _GenerateWorld()
SetGeneratingWorldProgress(GWP_GAME_START, 1);
/* Call any callback */
- if (_gw.proc != NULL) _gw.proc();
+ if (_gw.proc != nullptr) _gw.proc();
IncreaseGeneratingWorldProgress(GWP_GAME_START);
CleanupGeneration();
@@ -278,7 +278,7 @@ void HandleGeneratingWorldAbortion()
/* Clean up - in SE create an empty map, otherwise, go to intro menu */
_switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
- if (_gw.abortp != NULL) _gw.abortp();
+ if (_gw.abortp != nullptr) _gw.abortp();
CleanupGeneration();
@@ -302,7 +302,7 @@ void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_setti
_gw.size_y = size_y;
SetModalProgress(true);
_gw.abort = false;
- _gw.abortp = NULL;
+ _gw.abortp = nullptr;
_gw.lc = _local_company;
_gw.quit_thread = false;
_gw.threaded = true;
@@ -345,7 +345,7 @@ void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_setti
ShowGenerateWorldProgress();
/* Centre the view on the map */
- if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) {
+ if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) {
ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);
}
}
diff --git a/src/genworld.h b/src/genworld.h
index ce6b39bd9..56664bc0c 100644
--- a/src/genworld.h
+++ b/src/genworld.h
@@ -60,8 +60,8 @@ struct GenWorldInfo {
CompanyID lc; ///< The local_company before generating
uint size_x; ///< X-size of the map
uint size_y; ///< Y-size of the map
- GWDoneProc *proc; ///< Proc that is called when done (can be NULL)
- GWAbortProc *abortp; ///< Proc that is called when aborting (can be NULL)
+ GWDoneProc *proc; ///< Proc that is called when done (can be nullptr)
+ GWAbortProc *abortp; ///< Proc that is called when aborting (can be nullptr)
std::thread thread; ///< The thread we are in (joinable if a thread was created)
};
diff --git a/src/genworld_gui.cpp b/src/genworld_gui.cpp
index 53cc2d39e..550a193d7 100644
--- a/src/genworld_gui.cpp
+++ b/src/genworld_gui.cpp
@@ -442,7 +442,7 @@ struct GenerateLandscapeWindow : public Window {
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
- const StringID *strs = NULL;
+ const StringID *strs = nullptr;
switch (widget) {
case WID_GL_MAX_HEIGHTLEVEL_TEXT:
SetDParam(0, MAX_TILE_HEIGHT);
@@ -509,7 +509,7 @@ struct GenerateLandscapeWindow : public Window {
default:
return;
}
- if (strs != NULL) {
+ if (strs != nullptr) {
while (*strs != INVALID_STRING_ID) {
*size = maxdim(*size, GetStringBoundingBox(*strs++));
}
@@ -761,7 +761,7 @@ struct GenerateLandscapeWindow : public Window {
void OnQueryTextFinished(char *str) override
{
/* Was 'cancel' pressed? */
- if (str == NULL) return;
+ if (str == nullptr) return;
int32 value;
if (!StrEmpty(str)) {
@@ -808,14 +808,14 @@ struct GenerateLandscapeWindow : public Window {
};
static WindowDesc _generate_landscape_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_GENERATE_LANDSCAPE, WC_NONE,
0,
_nested_generate_landscape_widgets, lengthof(_nested_generate_landscape_widgets)
);
static WindowDesc _heightmap_load_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_GENERATE_LANDSCAPE, WC_NONE,
0,
_nested_heightmap_load_widgets, lengthof(_nested_heightmap_load_widgets)
@@ -1110,7 +1110,7 @@ static const NWidgetPart _nested_create_scenario_widgets[] = {
};
static WindowDesc _create_scenario_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_GENERATE_LANDSCAPE, WC_NONE,
0,
_nested_create_scenario_widgets, lengthof(_nested_create_scenario_widgets)
@@ -1138,7 +1138,7 @@ static const NWidgetPart _nested_generate_progress_widgets[] = {
static WindowDesc _generate_progress_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_MODAL_PROGRESS, WC_NONE,
0,
_nested_generate_progress_widgets, lengthof(_nested_generate_progress_widgets)
diff --git a/src/gfx.cpp b/src/gfx.cpp
index cb6aa4536..279dd35a8 100644
--- a/src/gfx.cpp
+++ b/src/gfx.cpp
@@ -53,8 +53,8 @@ static byte _stringwidth_table[FS_END][224]; ///< Cache containing width of ofte
DrawPixelInfo *_cur_dpi;
byte _colour_gradient[COLOUR_END][8];
-static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
-static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE, ZoomLevel zoom = ZOOM_LVL_NORMAL);
+static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = nullptr, SpriteID sprite_id = SPR_CURSOR_MOUSE);
+static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = nullptr, SpriteID sprite_id = SPR_CURSOR_MOUSE, ZoomLevel zoom = ZOOM_LVL_NORMAL);
static ReusableBuffer<uint8> _cursor_backup;
@@ -76,7 +76,7 @@ static const uint DIRTY_BLOCK_HEIGHT = 8;
static const uint DIRTY_BLOCK_WIDTH = 64;
static uint _dirty_bytes_per_line = 0;
-static byte *_dirty_blocks = NULL;
+static byte *_dirty_blocks = nullptr;
extern uint _dirty_block_colour;
void GfxScroll(int left, int top, int width, int height, int xo, int yo)
@@ -367,7 +367,7 @@ static int DrawLayoutLine(const ParagraphLayouter::Line &line, int y, int left,
truncation &= max_w < w; // Whether we need to do truncation.
int dot_width = 0; // Cache for the width of the dot.
- const Sprite *dot_sprite = NULL; // Cache for the sprite of the dot.
+ const Sprite *dot_sprite = nullptr; // Cache for the sprite of the dot.
if (truncation) {
/*
@@ -734,11 +734,11 @@ Point GetCharPosInString(const char *str, const char *ch, FontSize start_fontsiz
* @param str String to test.
* @param x Position relative to the start of the string.
* @param start_fontsize Font size to start the text with.
- * @return Pointer to the character at the position or NULL if there is no character at the position.
+ * @return Pointer to the character at the position or nullptr if there is no character at the position.
*/
const char *GetCharAtPosition(const char *str, int x, FontSize start_fontsize)
{
- if (x < 0) return NULL;
+ if (x < 0) return nullptr;
Layouter layout(str, INT32_MAX, TC_FROMSTRING, start_fontsize);
return layout.GetCharAtPosition(x);
@@ -768,7 +768,7 @@ Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
{
const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
- if (offset != NULL) {
+ if (offset != nullptr) {
offset->x = UnScaleByZoom(sprite->x_offs, zoom);
offset->y = UnScaleByZoom(sprite->y_offs, zoom);
}
@@ -874,7 +874,7 @@ static void GfxBlitter(const Sprite * const sprite, int x, int y, BlitterMode mo
x += sprite->x_offs;
y += sprite->y_offs;
- if (sub == NULL) {
+ if (sub == nullptr) {
/* No clipping. */
bp.skip_left = 0;
bp.skip_top = 0;
@@ -1011,7 +1011,7 @@ void DoPaletteAnimations()
uint i;
uint j;
- if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
+ if (blitter != nullptr && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
palette_animation_counter = 0;
}
@@ -1096,7 +1096,7 @@ void DoPaletteAnimations()
if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
}
- if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
+ if (blitter != nullptr && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
palette_animation_counter = old_tc;
} else {
if (memcmp(old_val, &_cur_palette.palette[PALETTE_ANIM_START], sizeof(old_val)) != 0 && _cur_palette.count_dirty == 0) {
@@ -1203,7 +1203,7 @@ void ScreenSizeChanged()
void UndrawMouseCursor()
{
/* Don't undraw the mouse cursor if the screen is not ready */
- if (_screen.dst_ptr == NULL) return;
+ if (_screen.dst_ptr == nullptr) return;
if (_cursor.visible) {
Blitter *blitter = BlitterFactory::GetCurrentBlitter();
@@ -1216,7 +1216,7 @@ void UndrawMouseCursor()
void DrawMouseCursor()
{
/* Don't draw the mouse cursor if the screen is not ready */
- if (_screen.dst_ptr == NULL) return;
+ if (_screen.dst_ptr == nullptr) return;
Blitter *blitter = BlitterFactory::GetCurrentBlitter();
@@ -1578,7 +1578,7 @@ static void SwitchAnimatedCursor()
{
const AnimCursor *cur = _cursor.animate_cur;
- if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
+ if (cur == nullptr || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
SetCursorSprite(cur->sprite, _cursor.sprite_seq[0].pal);
@@ -1628,7 +1628,7 @@ void SetMouseCursor(CursorID sprite, PaletteID pal)
void SetAnimatedMouseCursor(const AnimCursor *table)
{
_cursor.animate_list = table;
- _cursor.animate_cur = NULL;
+ _cursor.animate_cur = nullptr;
_cursor.sprite_seq[0].pal = PAL_NONE;
SwitchAnimatedCursor();
}
diff --git a/src/gfx_func.h b/src/gfx_func.h
index 2abbcd2a8..bbace3913 100644
--- a/src/gfx_func.h
+++ b/src/gfx_func.h
@@ -72,7 +72,7 @@ extern Dimension _cur_resolution;
extern Palette _cur_palette; ///< Current palette
void HandleKeypress(uint keycode, WChar key);
-void HandleTextInput(const char *str, bool marked = false, const char *caret = NULL, const char *insert_location = NULL, const char *replacement_end = NULL);
+void HandleTextInput(const char *str, bool marked = false, const char *caret = nullptr, const char *insert_location = nullptr, const char *replacement_end = nullptr);
void HandleCtrlChanged();
void HandleMouseEvents();
void UpdateWindows();
@@ -88,9 +88,9 @@ static const int DRAW_STRING_BUFFER = 2048;
void RedrawScreenRect(int left, int top, int right, int bottom);
void GfxScroll(int left, int top, int width, int height, int xo, int yo);
-Dimension GetSpriteSize(SpriteID sprid, Point *offset = NULL, ZoomLevel zoom = ZOOM_LVL_GUI);
-void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub = NULL);
-void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub = NULL, ZoomLevel zoom = ZOOM_LVL_GUI);
+Dimension GetSpriteSize(SpriteID sprid, Point *offset = nullptr, ZoomLevel zoom = ZOOM_LVL_GUI);
+void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub = nullptr);
+void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub = nullptr, ZoomLevel zoom = ZOOM_LVL_GUI);
/** How to align the to-be drawn text. */
enum StringAlignment {
diff --git a/src/gfx_layout.cpp b/src/gfx_layout.cpp
index ff176e81f..74a2a7759 100644
--- a/src/gfx_layout.cpp
+++ b/src/gfx_layout.cpp
@@ -174,7 +174,7 @@ public:
std::unique_ptr<const Line> NextLine(int max_width) override
{
icu::ParagraphLayout::Line *l = p->nextLine(max_width);
- return std::unique_ptr<const Line>(l == NULL ? NULL : new ICULine(l));
+ return std::unique_ptr<const Line>(l == nullptr ? nullptr : new ICULine(l));
}
};
@@ -208,10 +208,10 @@ public:
LEErrorCode status = LE_NO_ERROR;
/* ParagraphLayout does not copy "buff", so it must stay valid.
* "runs" is copied according to the ICU source, but the documentation does not specify anything, so this might break somewhen. */
- icu::ParagraphLayout *p = new icu::ParagraphLayout(buff, length, &runs, NULL, NULL, NULL, _current_text_dir == TD_RTL ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, false, status);
+ icu::ParagraphLayout *p = new icu::ParagraphLayout(buff, length, &runs, nullptr, nullptr, nullptr, _current_text_dir == TD_RTL ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, false, status);
if (status != LE_NO_ERROR) {
delete p;
- return NULL;
+ return nullptr;
}
return new ICUParagraphLayout(p);
@@ -234,7 +234,7 @@ public:
* visual runs.
*
* One constructs this class with the text that needs to be split into
- * lines. Then nextLine is called with the maximum width until NULL is
+ * lines. Then nextLine is called with the maximum width until nullptr is
* returned. Each nextLine call creates VisualRuns which contain the
* length of text that are to be drawn with the same font. In other
* words, the result of this class is a list of sub strings with their
@@ -358,9 +358,9 @@ FallbackParagraphLayout::FallbackVisualRun::FallbackVisualRun(FallbackVisualRun
this->glyph_to_char = other.glyph_to_char;
this->glyphs = other.glyphs;
- other.positions = NULL;
- other.glyph_to_char = NULL;
- other.glyphs = NULL;
+ other.positions = nullptr;
+ other.glyph_to_char = nullptr;
+ other.glyphs = nullptr;
}
/** Free all data. */
@@ -496,7 +496,7 @@ void FallbackParagraphLayout::Reflow()
/**
* Construct a new line with a maximum width.
* @param max_width The maximum width of the string.
- * @return A Line, or NULL when at the end of the paragraph.
+ * @return A Line, or nullptr when at the end of the paragraph.
*/
std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine(int max_width)
{
@@ -504,13 +504,13 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
* - split a line at a newline character, or at a space where we can break a line.
* - split for a visual run whenever a new line happens, or the font changes.
*/
- if (this->buffer == NULL) return NULL;
+ if (this->buffer == nullptr) return nullptr;
std::unique_ptr<FallbackLine> l(new FallbackLine());
if (*this->buffer == '\0') {
/* Only a newline. */
- this->buffer = NULL;
+ this->buffer = nullptr;
l->emplace_back(this->runs.front().second, this->buffer, 0, 0);
return std::move(l); // Not supposed to be needed, but clang-3.8 barfs otherwise.
}
@@ -526,7 +526,7 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
const WChar *next_run = this->buffer_begin + iter->first;
const WChar *begin = this->buffer;
- const WChar *last_space = NULL;
+ const WChar *last_space = nullptr;
const WChar *last_char;
int width = 0;
for (;;) {
@@ -534,7 +534,7 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
last_char = this->buffer;
if (c == '\0') {
- this->buffer = NULL;
+ this->buffer = nullptr;
break;
}
@@ -547,7 +547,7 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
next_run = this->buffer_begin + iter->first;
begin = this->buffer;
- last_space = NULL;
+ last_space = nullptr;
}
if (IsWhitespace(c)) last_space = this->buffer;
@@ -561,11 +561,11 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
if (width == char_width) {
/* The character is wider than allowed width; don't know
* what to do with this case... bail out! */
- this->buffer = NULL;
+ this->buffer = nullptr;
return std::move(l); // Not supposed to be needed, but clang-3.8 barfs otherwise.
}
- if (last_space == NULL) {
+ if (last_space == nullptr) {
/* No space has been found. Just terminate at our current
* location. This usually happens for languages that do not
* require spaces in strings, like Chinese, Japanese and
@@ -595,7 +595,7 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
/**
* Helper for getting a ParagraphLayouter of the given type.
*
- * @note In case no ParagraphLayouter could be constructed, line.layout will be NULL.
+ * @note In case no ParagraphLayouter could be constructed, line.layout will be nullptr.
* @param line The cache item to store our layouter in.
* @param str The string to create a layouter for.
* @param state The state of the font and color.
@@ -604,7 +604,7 @@ std::unique_ptr<const ParagraphLayouter::Line> FallbackParagraphLayout::NextLine
template <typename T>
static inline void GetLayouter(Layouter::LineCacheItem &line, const char *&str, FontState &state)
{
- if (line.buffer != NULL) free(line.buffer);
+ if (line.buffer != nullptr) free(line.buffer);
typename T::CharType *buff_begin = MallocT<typename T::CharType>(DRAW_STRING_BUFFER);
const typename T::CharType *buffer_last = buff_begin + DRAW_STRING_BUFFER;
@@ -679,7 +679,7 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
}
LineCacheItem& line = GetCachedParagraphLayout(str, lineend - str, state);
- if (line.layout != NULL) {
+ if (line.layout != nullptr) {
/* Line is in cache */
str = lineend + 1;
state = line.state_after;
@@ -693,7 +693,7 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
#ifdef WITH_ICU_LX
GetLayouter<ICUParagraphLayoutFactory>(line, str, state);
- if (line.layout == NULL) {
+ if (line.layout == nullptr) {
static bool warned = false;
if (!warned) {
DEBUG(misc, 0, "ICU layouter bailed on the font. Falling back to the fallback layouter");
@@ -706,9 +706,9 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
#endif
#ifdef WITH_UNISCRIBE
- if (line.layout == NULL) {
+ if (line.layout == nullptr) {
GetLayouter<UniscribeParagraphLayoutFactory>(line, str, state);
- if (line.layout == NULL) {
+ if (line.layout == nullptr) {
state = old_state;
str = old_str;
}
@@ -716,16 +716,16 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
#endif
#ifdef WITH_COCOA
- if (line.layout == NULL) {
+ if (line.layout == nullptr) {
GetLayouter<CoreTextParagraphLayoutFactory>(line, str, state);
- if (line.layout == NULL) {
+ if (line.layout == nullptr) {
state = old_state;
str = old_str;
}
}
#endif
- if (line.layout == NULL) {
+ if (line.layout == nullptr) {
GetLayouter<FallbackParagraphLayoutFactory>(line, str, state);
}
}
@@ -733,7 +733,7 @@ Layouter::Layouter(const char *str, int maxw, TextColour colour, FontSize fontsi
/* Move all lines into a local cache so we can reuse them later on more easily. */
for (;;) {
auto l = line.layout->NextLine(maxw);
- if (l == NULL) break;
+ if (l == nullptr) break;
this->push_back(std::move(l));
}
} while (c != '\0');
@@ -804,7 +804,7 @@ Point Layouter::GetCharPosition(const char *ch) const
/**
* Get the character that is at a position.
* @param x Position in the string.
- * @return Pointer to the character at the position or NULL if no character is at the position.
+ * @return Pointer to the character at the position or nullptr if no character is at the position.
*/
const char *Layouter::GetCharAtPosition(int x) const
{
@@ -835,7 +835,7 @@ const char *Layouter::GetCharAtPosition(int x) const
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -883,7 +883,7 @@ void Layouter::ResetFontCache(FontSize size)
*/
Layouter::LineCacheItem &Layouter::GetCachedParagraphLayout(const char *str, size_t len, const FontState &state)
{
- if (linecache == NULL) {
+ if (linecache == nullptr) {
/* Create linecache on first access to avoid trouble with initialisation order of static variables. */
linecache = new LineCache();
}
@@ -899,7 +899,7 @@ Layouter::LineCacheItem &Layouter::GetCachedParagraphLayout(const char *str, siz
*/
void Layouter::ResetLineCache()
{
- if (linecache != NULL) linecache->clear();
+ if (linecache != nullptr) linecache->clear();
}
/**
@@ -907,7 +907,7 @@ void Layouter::ResetLineCache()
*/
void Layouter::ReduceLineCache()
{
- if (linecache != NULL) {
+ if (linecache != nullptr) {
/* TODO LRU cache would be fancy, but not exactly necessary */
if (linecache->size() > 4096) ResetLineCache();
}
diff --git a/src/gfx_layout.h b/src/gfx_layout.h
index 104736611..053937647 100644
--- a/src/gfx_layout.h
+++ b/src/gfx_layout.h
@@ -177,7 +177,7 @@ public:
FontState state_after; ///< Font state after the line.
ParagraphLayouter *layout; ///< Layout of the line.
- LineCacheItem() : buffer(NULL), layout(NULL) {}
+ LineCacheItem() : buffer(nullptr), layout(nullptr) {}
~LineCacheItem() { delete layout; free(buffer); }
};
private:
diff --git a/src/gfxinit.cpp b/src/gfxinit.cpp
index 3613ce0d8..81cbd9121 100644
--- a/src/gfxinit.cpp
+++ b/src/gfxinit.cpp
@@ -120,7 +120,7 @@ static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl,
*/
void CheckExternalFiles()
{
- if (BaseGraphics::GetUsedSet() == NULL || BaseSounds::GetUsedSet() == NULL) return;
+ if (BaseGraphics::GetUsedSet() == nullptr || BaseSounds::GetUsedSet() == nullptr) return;
const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
@@ -265,7 +265,7 @@ static bool SwitchNewGRFBlitter()
*/
uint depth_wanted_by_base = BaseGraphics::GetUsedSet()->blitter == BLT_32BPP ? 32 : 8;
uint depth_wanted_by_grf = _support8bpp == S8BPP_NONE ? 32 : 8;
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND || HasBit(c->flags, GCF_INIT_ONLY)) continue;
if (c->palette & GRFP_BLT_32BPP) depth_wanted_by_grf = 32;
}
@@ -307,18 +307,18 @@ static bool SwitchNewGRFBlitter()
VideoDriver::GetInstance()->ReleaseBlitterLock();
return false;
}
- if (BlitterFactory::GetBlitterFactory(repl_blitter) == NULL) continue;
+ if (BlitterFactory::GetBlitterFactory(repl_blitter) == nullptr) continue;
DEBUG(misc, 1, "Switching blitter from '%s' to '%s'... ", cur_blitter, repl_blitter);
Blitter *new_blitter = BlitterFactory::SelectBlitter(repl_blitter);
- if (new_blitter == NULL) NOT_REACHED();
+ if (new_blitter == nullptr) NOT_REACHED();
DEBUG(misc, 1, "Successfully switched to %s.", repl_blitter);
break;
}
if (!VideoDriver::GetInstance()->AfterBlitterChange()) {
/* Failed to switch blitter, let's hope we can return to the old one. */
- if (BlitterFactory::SelectBlitter(cur_blitter) == NULL || !VideoDriver::GetInstance()->AfterBlitterChange()) usererror("Failed to reinitialize video driver. Specify a fixed blitter in the config");
+ if (BlitterFactory::SelectBlitter(cur_blitter) == nullptr || !VideoDriver::GetInstance()->AfterBlitterChange()) usererror("Failed to reinitialize video driver. Specify a fixed blitter in the config");
}
VideoDriver::GetInstance()->ReleaseBlitterLock();
@@ -362,7 +362,7 @@ bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path, const char *ful
/* Get optional blitter information. */
item = metadata->GetItem("blitter", false);
- this->blitter = (item != NULL && *item->value == '3') ? BLT_32BPP : BLT_8BPP;
+ this->blitter = (item != nullptr && *item->value == '3') ? BLT_32BPP : BLT_8BPP;
}
return ret;
}
@@ -380,7 +380,7 @@ bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path, const char *ful
{
size_t size = 0;
FILE *f = FioFOpenFile(file->filename, "rb", subdir, &size);
- if (f == NULL) return MD5File::CR_NO_FILE;
+ if (f == nullptr) return MD5File::CR_NO_FILE;
size_t max = GRFGetSizeOfDataSection(f);
@@ -404,7 +404,7 @@ MD5File::ChecksumResult MD5File::CheckMD5(Subdirectory subdir, size_t max_size)
size_t size;
FILE *f = FioFOpenFile(this->filename, "rb", subdir, &size);
- if (f == NULL) return CR_NO_FILE;
+ if (f == nullptr) return CR_NO_FILE;
size = min(size, max_size);
@@ -434,14 +434,14 @@ template <class T, size_t Tnum_files, bool Tsearch_in_tars>
template <class Tbase_set>
/* static */ bool BaseMedia<Tbase_set>::DetermineBestSet()
{
- if (BaseMedia<Tbase_set>::used_set != NULL) return true;
+ if (BaseMedia<Tbase_set>::used_set != nullptr) return true;
- const Tbase_set *best = NULL;
- for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) {
+ const Tbase_set *best = nullptr;
+ for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != nullptr; c = c->next) {
/* Skip unusable sets */
if (c->GetNumMissing() != 0) continue;
- if (best == NULL ||
+ if (best == nullptr ||
(best->fallback && !c->fallback) ||
best->valid_files < c->valid_files ||
(best->valid_files == c->valid_files && (
@@ -452,7 +452,7 @@ template <class Tbase_set>
}
BaseMedia<Tbase_set>::used_set = best;
- return BaseMedia<Tbase_set>::used_set != NULL;
+ return BaseMedia<Tbase_set>::used_set != nullptr;
}
template <class Tbase_set>
diff --git a/src/goal.cpp b/src/goal.cpp
index eba72b7f4..b545c84d2 100644
--- a/src/goal.cpp
+++ b/src/goal.cpp
@@ -93,7 +93,7 @@ CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
g->dst = p2;
g->company = company;
g->text = stredup(text);
- g->progress = NULL;
+ g->progress = nullptr;
g->completed = false;
if (g->company == INVALID_COMPANY) {
@@ -187,7 +187,7 @@ CommandCost CmdSetGoalProgress(TileIndex tile, DoCommandFlag flags, uint32 p1, u
Goal *g = Goal::Get(p1);
free(g->progress);
if (StrEmpty(text)) {
- g->progress = NULL;
+ g->progress = nullptr;
} else {
g->progress = stredup(text);
}
diff --git a/src/goal_base.h b/src/goal_base.h
index 7453196c8..f82afa5be 100644
--- a/src/goal_base.h
+++ b/src/goal_base.h
@@ -34,7 +34,7 @@ struct Goal : GoalPool::PoolItem<&_goal_pool> {
inline Goal() { }
/**
- * (Empty) destructor has to be defined else operator delete might be called with NULL parameter
+ * (Empty) destructor has to be defined else operator delete might be called with nullptr parameter
*/
inline ~Goal() { free(this->text); free(this->progress); }
};
diff --git a/src/goal_gui.cpp b/src/goal_gui.cpp
index 7c3e33004..758eae9ad 100644
--- a/src/goal_gui.cpp
+++ b/src/goal_gui.cpp
@@ -223,7 +223,7 @@ struct GoalListWindow : public Window {
}
case GC_PROGRESS:
- if (s->progress != NULL) {
+ if (s->progress != nullptr) {
SetDParamStr(0, s->progress);
StringID str = s->completed ? STR_GOALS_PROGRESS_COMPLETE : STR_GOALS_PROGRESS;
int progress_x = x;
@@ -282,7 +282,7 @@ struct GoalListWindow : public Window {
uint max_width = 0;
Goal *s;
FOR_ALL_GOALS(s) {
- if (s->progress != NULL) {
+ if (s->progress != nullptr) {
SetDParamStr(0, s->progress);
StringID str = s->completed ? STR_GOALS_PROGRESS_COMPLETE : STR_GOALS_PROGRESS;
uint str_width = GetStringBoundingBox(str).width;
@@ -473,7 +473,7 @@ static const NWidgetPart _nested_goal_question_widgets[] = {
};
static WindowDesc _goal_question_list_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_GOAL_QUESTION, WC_NONE,
WDF_CONSTRUCTION,
_nested_goal_question_widgets, lengthof(_nested_goal_question_widgets)
diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp
index 69bdb3b1f..5dc565dfe 100644
--- a/src/graph_gui.cpp
+++ b/src/graph_gui.cpp
@@ -595,7 +595,7 @@ public:
int numd = 0;
for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
c = Company::GetIfValid(k);
- if (c != NULL) {
+ if (c != nullptr) {
this->colours[numd] = _colour_gradient[c->colour][6];
for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
this->cost[numd][i] = (j >= c->num_valid_stat_ent) ? INVALID_DATAPOINT : GetGraphData(c, j);
diff --git a/src/ground_vehicle.cpp b/src/ground_vehicle.cpp
index 6fd8d7710..b94fb0e7b 100644
--- a/src/ground_vehicle.cpp
+++ b/src/ground_vehicle.cpp
@@ -30,7 +30,7 @@ void GroundVehicle<T, Type>::PowerChanged()
uint32 number_of_parts = 0;
uint16 max_track_speed = v->GetDisplayMaxSpeed();
- for (const T *u = v; u != NULL; u = u->Next()) {
+ for (const T *u = v; u != nullptr; u = u->Next()) {
uint32 current_power = u->GetPower() + u->GetPoweredPartPower(u);
total_power += current_power;
@@ -83,7 +83,7 @@ void GroundVehicle<T, Type>::CargoChanged()
assert(this->First() == this);
uint32 weight = 0;
- for (T *u = T::From(this); u != NULL; u = u->Next()) {
+ for (T *u = T::From(this); u != nullptr; u = u->Next()) {
uint32 current_weight = u->GetWeight();
weight += current_weight;
/* Slope steepness is in percent, result in N. */
@@ -198,7 +198,7 @@ bool GroundVehicle<T, Type>::IsChainInDepot() const
if (!IsDepotTypeTile(v->tile, (TransportType)Type) || v->cur_speed != 0) return false;
/* Check whether the rest is also already trying to enter the depot. */
- for (; v != NULL; v = v->Next()) {
+ for (; v != nullptr; v = v->Next()) {
if (!v->T::IsInDepot() || v->tile != this->tile) return false;
}
diff --git a/src/ground_vehicle.hpp b/src/ground_vehicle.hpp
index 25106ab1c..109257fe2 100644
--- a/src/ground_vehicle.hpp
+++ b/src/ground_vehicle.hpp
@@ -102,7 +102,7 @@ struct GroundVehicle : public SpecializedVehicle<T, Type> {
uint Crash(bool flooded) override
{
/* Crashed vehicles aren't going up or down */
- for (T *v = T::From(this); v != NULL; v = v->Next()) {
+ for (T *v = T::From(this); v != nullptr; v = v->Next()) {
ClrBit(v->gv_flags, GVF_GOINGUP_BIT);
ClrBit(v->gv_flags, GVF_GOINGDOWN_BIT);
}
@@ -117,7 +117,7 @@ struct GroundVehicle : public SpecializedVehicle<T, Type> {
{
int64 incl = 0;
- for (const T *u = T::From(this); u != NULL; u = u->Next()) {
+ for (const T *u = T::From(this); u != nullptr; u = u->Next()) {
if (HasBit(u->gv_flags, GVF_GOINGUP_BIT)) {
incl += u->gcache.cached_slope_resistance;
} else if (HasBit(u->gv_flags, GVF_GOINGDOWN_BIT)) {
diff --git a/src/group_cmd.cpp b/src/group_cmd.cpp
index 6939af88b..9915546eb 100644
--- a/src/group_cmd.cpp
+++ b/src/group_cmd.cpp
@@ -225,7 +225,7 @@ void GroupStatistics::Clear()
g->statistics.ClearAutoreplace();
}
- for (EngineRenewList erl = c->engine_renew_list; erl != NULL; erl = erl->next) {
+ for (EngineRenewList erl = c->engine_renew_list; erl != nullptr; erl = erl->next) {
const Engine *e = Engine::Get(erl->from);
GroupStatistics &stats = GroupStatistics::Get(company, erl->group_id, e->type);
if (!stats.autoreplace_defined) {
@@ -277,7 +277,7 @@ void PropagateChildLivery(const Group *g)
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->group_id == g->index && (!v->IsGroundVehicle() || v->IsFrontEngine())) {
- for (Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (Vehicle *u = v; u != nullptr; u = u->Next()) {
u->colourmap = PAL_NONE;
u->InvalidateNewGRFCache();
}
@@ -324,7 +324,7 @@ CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (!Group::CanAllocateItem()) return CMD_ERROR;
const Group *pg = Group::GetIfValid(GB(p2, 0, 16));
- if (pg != NULL) {
+ if (pg != nullptr) {
if (pg->owner != _current_company) return CMD_ERROR;
if (pg->vehicle_type != vt) return CMD_ERROR;
}
@@ -335,7 +335,7 @@ CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
g->vehicle_type = vt;
g->parent = INVALID_GROUP;
- if (pg == NULL) {
+ if (pg == nullptr) {
const Company *c = Company::Get(_current_company);
g->livery.colour1 = c->livery[LS_DEFAULT].colour1;
g->livery.colour2 = c->livery[LS_DEFAULT].colour2;
@@ -368,7 +368,7 @@ CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Group *g = Group::GetIfValid(p1);
- if (g == NULL || g->owner != _current_company) return CMD_ERROR;
+ if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
/* Remove all vehicles from the group */
DoCommand(0, p1, 0, flags, CMD_REMOVE_ALL_VEHICLES_GROUP);
@@ -424,7 +424,7 @@ CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
CommandCost CmdAlterGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Group *g = Group::GetIfValid(GB(p1, 0, 16));
- if (g == NULL || g->owner != _current_company) return CMD_ERROR;
+ if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
if (!HasBit(p1, 16)) {
/* Rename group */
@@ -438,13 +438,13 @@ CommandCost CmdAlterGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Delete the old name */
free(g->name);
/* Assign the new one */
- g->name = reset ? NULL : stredup(text);
+ g->name = reset ? nullptr : stredup(text);
}
} else {
/* Set group parent */
const Group *pg = Group::GetIfValid(GB(p2, 0, 16));
- if (pg != NULL) {
+ if (pg != nullptr) {
if (pg->owner != _current_company) return CMD_ERROR;
if (pg->vehicle_type != g->vehicle_type) return CMD_ERROR;
@@ -454,7 +454,7 @@ CommandCost CmdAlterGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
}
if (flags & DC_EXEC) {
- g->parent = (pg == NULL) ? INVALID_GROUP : pg->index;
+ g->parent = (pg == nullptr) ? INVALID_GROUP : pg->index;
GroupStatistics::UpdateAutoreplace(g->owner);
if (g->livery.in_use == 0) {
@@ -498,7 +498,7 @@ static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
case VEH_AIRCRAFT:
if (v->IsEngineCountable()) UpdateNumEngineGroup(v, v->group_id, new_g);
v->group_id = new_g;
- for (Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (Vehicle *u = v; u != nullptr; u = u->Next()) {
u->colourmap = PAL_NONE;
u->InvalidateNewGRFCache();
u->UpdateViewport(true);
@@ -526,7 +526,7 @@ CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, u
Vehicle *v = Vehicle::GetIfValid(GB(p2, 0, 20));
GroupID new_g = p1;
- if (v == NULL || (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP)) return CMD_ERROR;
+ if (v == nullptr || (!Group::IsValidID(new_g) && !IsDefaultGroupID(new_g) && new_g != NEW_GROUP)) return CMD_ERROR;
if (Group::IsValidID(new_g)) {
Group *g = Group::Get(new_g);
@@ -537,7 +537,7 @@ CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, u
if (new_g == NEW_GROUP) {
/* Create new group. */
- CommandCost ret = CmdCreateGroup(0, flags, v->type, 0, NULL);
+ CommandCost ret = CmdCreateGroup(0, flags, v->type, 0, nullptr);
if (ret.Failed()) return ret;
new_g = _new_group_id;
@@ -548,7 +548,7 @@ CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, u
if (HasBit(p2, 31)) {
/* Add vehicles in the shared order list as well. */
- for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
+ for (Vehicle *v2 = v->FirstShared(); v2 != nullptr; v2 = v2->NextShared()) {
if (v2->group_id != new_g) AddVehicleToGroup(v2, new_g);
}
}
@@ -592,7 +592,7 @@ CommandCost CmdAddSharedVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32
if (v->group_id != id_g) continue;
/* For each shared vehicles add it to the group */
- for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
+ for (Vehicle *v2 = v->FirstShared(); v2 != nullptr; v2 = v2->NextShared()) {
if (v2->group_id != id_g) DoCommand(tile, id_g, v2->index, flags, CMD_ADD_VEHICLE_GROUP, text);
}
}
@@ -620,7 +620,7 @@ CommandCost CmdRemoveAllVehiclesGroup(TileIndex tile, DoCommandFlag flags, uint3
GroupID old_g = p1;
Group *g = Group::GetIfValid(old_g);
- if (g == NULL || g->owner != _current_company) return CMD_ERROR;
+ if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
if (flags & DC_EXEC) {
Vehicle *v;
@@ -657,7 +657,7 @@ CommandCost CmdSetGroupLivery(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
bool primary = !HasBit(p2, 8);
Colours colour = Extract<Colours, 16, 8>(p2);
- if (g == NULL || g->owner != _current_company) return CMD_ERROR;
+ if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
if (colour >= COLOUR_END && colour != INVALID_COLOUR) return CMD_ERROR;
@@ -709,7 +709,7 @@ static void SetGroupReplaceProtection(Group *g, bool protect)
CommandCost CmdSetGroupReplaceProtection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Group *g = Group::GetIfValid(p1);
- if (g == NULL || g->owner != _current_company) return CMD_ERROR;
+ if (g == nullptr || g->owner != _current_company) return CMD_ERROR;
if (flags & DC_EXEC) {
if (HasBit(p2, 1)) {
@@ -750,7 +750,7 @@ void SetTrainGroupID(Train *v, GroupID new_g)
assert(v->IsFrontEngine() || IsDefaultGroupID(new_g));
- for (Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (Vehicle *u = v; u != nullptr; u = u->Next()) {
if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
u->group_id = new_g;
@@ -777,7 +777,7 @@ void UpdateTrainGroupID(Train *v)
assert(v->IsFrontEngine() || v->IsFreeWagon());
GroupID new_g = v->IsFrontEngine() ? v->group_id : (GroupID)DEFAULT_GROUP;
- for (Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (Vehicle *u = v; u != nullptr; u = u->Next()) {
if (u->IsEngineCountable()) UpdateNumEngineGroup(u, u->group_id, new_g);
u->group_id = new_g;
diff --git a/src/group_gui.cpp b/src/group_gui.cpp
index 22604fdf3..19e6b6e31 100644
--- a/src/group_gui.cpp
+++ b/src/group_gui.cpp
@@ -146,7 +146,7 @@ private:
/** Sort the groups by their name */
static int CDECL GroupNameSorter(const Group * const *a, const Group * const *b)
{
- static const Group *last_group[2] = { NULL, NULL };
+ static const Group *last_group[2] = { nullptr, nullptr };
static char last_name[2][64] = { "", "" };
if (*a != last_group[0]) {
@@ -780,7 +780,7 @@ public:
case WID_GL_REPLACE_PROTECTION: {
const Group *g = Group::GetIfValid(this->vli.index);
- if (g != NULL) {
+ if (g != nullptr) {
DoCommandP(0, this->vli.index, (g->replace_protection ? 0 : 1) | (_ctrl_pressed << 1), CMD_SET_GROUP_REPLACE_PROTECTION);
}
break;
@@ -841,7 +841,7 @@ public:
uint id_g = this->group_sb->GetScrolledRowFromWidget(pt.y, this, WID_GL_LIST_GROUP, 0, this->tiny_step_height);
GroupID new_g = id_g >= this->groups.size() ? NEW_GROUP : this->groups[id_g]->index;
- DoCommandP(0, new_g, vindex | (_ctrl_pressed ? 1 << 31 : 0), CMD_ADD_VEHICLE_GROUP | CMD_MSG(STR_ERROR_GROUP_CAN_T_ADD_VEHICLE), new_g == NEW_GROUP ? CcAddVehicleNewGroup : NULL);
+ DoCommandP(0, new_g, vindex | (_ctrl_pressed ? 1 << 31 : 0), CMD_ADD_VEHICLE_GROUP | CMD_MSG(STR_ERROR_GROUP_CAN_T_ADD_VEHICLE), new_g == NEW_GROUP ? CcAddVehicleNewGroup : nullptr);
break;
}
@@ -873,7 +873,7 @@ public:
void OnQueryTextFinished(char *str) override
{
- if (str != NULL) DoCommandP(0, this->group_rename, 0, CMD_ALTER_GROUP | CMD_MSG(STR_ERROR_GROUP_CAN_T_RENAME), NULL, str);
+ if (str != nullptr) DoCommandP(0, this->group_rename, 0, CMD_ALTER_GROUP | CMD_MSG(STR_ERROR_GROUP_CAN_T_RENAME), nullptr, str);
this->group_rename = INVALID_GROUP;
}
@@ -1033,7 +1033,7 @@ void ShowCompanyGroup(CompanyID company, VehicleType vehicle_type)
* Finds a group list window determined by vehicle type and owner
* @param vt vehicle type
* @param owner owner of groups
- * @return pointer to VehicleGroupWindow, NULL if not found
+ * @return pointer to VehicleGroupWindow, nullptr if not found
*/
static inline VehicleGroupWindow *FindVehicleGroupWindow(VehicleType vt, Owner owner)
{
@@ -1054,7 +1054,7 @@ void CcCreateGroup(const CommandCost &result, TileIndex tile, uint32 p1, uint32
assert(p1 <= VEH_AIRCRAFT);
VehicleGroupWindow *w = FindVehicleGroupWindow((VehicleType)p1, _current_company);
- if (w != NULL) w->ShowRenameGroupWindow(_new_group_id, true);
+ if (w != nullptr) w->ShowRenameGroupWindow(_new_group_id, true);
}
/**
@@ -1084,5 +1084,5 @@ void DeleteGroupHighlightOfVehicle(const Vehicle *v)
if (_special_mouse_mode != WSM_DRAGDROP) return;
VehicleGroupWindow *w = FindVehicleGroupWindow(v->type, v->owner);
- if (w != NULL) w->UnselectVehicle(v->index);
+ if (w != nullptr) w->UnselectVehicle(v->index);
}
diff --git a/src/heightmap.cpp b/src/heightmap.cpp
index 17bdbbf61..4609dceeb 100644
--- a/src/heightmap.cpp
+++ b/src/heightmap.cpp
@@ -47,7 +47,7 @@ static void ReadHeightmapPNGImageData(byte *map, png_structp png_ptr, png_infop
{
uint x, y;
byte gray_palette[256];
- png_bytep *row_pointers = NULL;
+ png_bytep *row_pointers = nullptr;
bool has_palette = png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_PALETTE;
uint channels = png_get_channels(png_ptr, info_ptr);
@@ -99,33 +99,33 @@ static void ReadHeightmapPNGImageData(byte *map, png_structp png_ptr, png_infop
/**
* Reads the heightmap and/or size of the heightmap from a PNG file.
- * If map == NULL only the size of the PNG is read, otherwise a map
+ * If map == nullptr only the size of the PNG is read, otherwise a map
* with grayscale pixels is allocated and assigned to *map.
*/
static bool ReadHeightmapPNG(const char *filename, uint *x, uint *y, byte **map)
{
FILE *fp;
- png_structp png_ptr = NULL;
- png_infop info_ptr = NULL;
+ png_structp png_ptr = nullptr;
+ png_infop info_ptr = nullptr;
fp = FioFOpenFile(filename, "rb", HEIGHTMAP_DIR);
- if (fp == NULL) {
+ if (fp == nullptr) {
ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_FILE_NOT_FOUND, WL_ERROR);
return false;
}
- png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- if (png_ptr == NULL) {
+ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
+ if (png_ptr == nullptr) {
ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_MISC, WL_ERROR);
fclose(fp);
return false;
}
info_ptr = png_create_info_struct(png_ptr);
- if (info_ptr == NULL || setjmp(png_jmpbuf(png_ptr))) {
+ if (info_ptr == nullptr || setjmp(png_jmpbuf(png_ptr))) {
ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_MISC, WL_ERROR);
fclose(fp);
- png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
@@ -134,14 +134,14 @@ static bool ReadHeightmapPNG(const char *filename, uint *x, uint *y, byte **map)
/* Allocate memory and read image, without alpha or 16-bit samples
* (result is either 8-bit indexed/grayscale or 24-bit RGB) */
png_set_packing(png_ptr);
- png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_PACKING | PNG_TRANSFORM_STRIP_ALPHA | PNG_TRANSFORM_STRIP_16, NULL);
+ png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_PACKING | PNG_TRANSFORM_STRIP_ALPHA | PNG_TRANSFORM_STRIP_16, nullptr);
/* Maps of wrong colour-depth are not used.
* (this should have been taken care of by stripping alpha and 16-bit samples on load) */
if ((png_get_channels(png_ptr, info_ptr) != 1) && (png_get_channels(png_ptr, info_ptr) != 3) && (png_get_bit_depth(png_ptr, info_ptr) != 8)) {
ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_PNGMAP_IMAGE_TYPE, WL_ERROR);
fclose(fp);
- png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
@@ -152,11 +152,11 @@ static bool ReadHeightmapPNG(const char *filename, uint *x, uint *y, byte **map)
if ((uint64)width * height >= (size_t)-1) {
ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_HEIGHTMAP_TOO_LARGE, WL_ERROR);
fclose(fp);
- png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
- if (map != NULL) {
+ if (map != nullptr) {
*map = MallocT<byte>(width * height);
ReadHeightmapPNGImageData(*map, png_ptr, info_ptr);
}
@@ -165,7 +165,7 @@ static bool ReadHeightmapPNG(const char *filename, uint *x, uint *y, byte **map)
*y = height;
fclose(fp);
- png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
+ png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return true;
}
@@ -180,7 +180,7 @@ static void ReadHeightmapBMPImageData(byte *map, BmpInfo *info, BmpData *data)
uint x, y;
byte gray_palette[256];
- if (data->palette != NULL) {
+ if (data->palette != nullptr) {
uint i;
bool all_gray = true;
@@ -229,7 +229,7 @@ static void ReadHeightmapBMPImageData(byte *map, BmpInfo *info, BmpData *data)
/**
* Reads the heightmap and/or size of the heightmap from a BMP file.
- * If map == NULL only the size of the BMP is read, otherwise a map
+ * If map == nullptr only the size of the BMP is read, otherwise a map
* with grayscale pixels is allocated and assigned to *map.
*/
static bool ReadHeightmapBMP(const char *filename, uint *x, uint *y, byte **map)
@@ -243,7 +243,7 @@ static bool ReadHeightmapBMP(const char *filename, uint *x, uint *y, byte **map)
memset(&data, 0, sizeof(data));
f = FioFOpenFile(filename, "rb", HEIGHTMAP_DIR);
- if (f == NULL) {
+ if (f == nullptr) {
ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_PNGMAP_FILE_NOT_FOUND, WL_ERROR);
return false;
}
@@ -265,7 +265,7 @@ static bool ReadHeightmapBMP(const char *filename, uint *x, uint *y, byte **map)
return false;
}
- if (map != NULL) {
+ if (map != nullptr) {
if (!BmpReadBitmap(&buffer, &info, &data)) {
ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_BMPMAP_IMAGE_TYPE, WL_ERROR);
fclose(f);
@@ -449,7 +449,7 @@ void FixSlopes()
* @param filename Name of the file to load.
* @param[out] x Length of the image.
* @param[out] y Height of the image.
- * @param[in,out] map If not \c NULL, destination to store the loaded block of image data.
+ * @param[in,out] map If not \c nullptr, destination to store the loaded block of image data.
* @return Whether loading was successful.
*/
static bool ReadHeightMap(DetailedFileType dft, const char *filename, uint *x, uint *y, byte **map)
@@ -478,7 +478,7 @@ static bool ReadHeightMap(DetailedFileType dft, const char *filename, uint *x, u
*/
bool GetHeightmapDimensions(DetailedFileType dft, const char *filename, uint *x, uint *y)
{
- return ReadHeightMap(dft, filename, x, y, NULL);
+ return ReadHeightMap(dft, filename, x, y, nullptr);
}
/**
@@ -491,7 +491,7 @@ bool GetHeightmapDimensions(DetailedFileType dft, const char *filename, uint *x,
void LoadHeightmap(DetailedFileType dft, const char *filename)
{
uint x, y;
- byte *map = NULL;
+ byte *map = nullptr;
if (!ReadHeightMap(dft, filename, &x, &y, &map)) {
free(map);
diff --git a/src/highscore.cpp b/src/highscore.cpp
index 86e4f5ae8..a69bdc46a 100644
--- a/src/highscore.cpp
+++ b/src/highscore.cpp
@@ -129,7 +129,7 @@ void SaveToHighScore()
{
FILE *fp = fopen(_highscore_file, "wb");
- if (fp != NULL) {
+ if (fp != nullptr) {
uint i;
HighScore *hs;
@@ -159,7 +159,7 @@ void LoadFromHighScore()
memset(_highscore_table, 0, sizeof(_highscore_table));
- if (fp != NULL) {
+ if (fp != nullptr) {
uint i;
HighScore *hs;
diff --git a/src/highscore_gui.cpp b/src/highscore_gui.cpp
index d6ea8c0c1..b0a93aac9 100644
--- a/src/highscore_gui.cpp
+++ b/src/highscore_gui.cpp
@@ -135,7 +135,7 @@ struct EndGameWindow : EndGameHighScoreBaseWindow {
Point pt = this->GetTopLeft(640, 480);
const Company *c = Company::GetIfValid(_local_company);
- if (c == NULL) return;
+ if (c == nullptr) return;
/* We need to get performance from last year because the image is shown
* at the start of the new year when these things have already been copied */
@@ -210,14 +210,14 @@ static const NWidgetPart _nested_highscore_widgets[] = {
};
static WindowDesc _highscore_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_HIGHSCORE, WC_NONE,
0,
_nested_highscore_widgets, lengthof(_nested_highscore_widgets)
);
static WindowDesc _endgame_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_ENDSCREEN, WC_NONE,
0,
_nested_highscore_widgets, lengthof(_nested_highscore_widgets)
diff --git a/src/hotkeys.cpp b/src/hotkeys.cpp
index 3093a8229..38ac4325d 100644
--- a/src/hotkeys.cpp
+++ b/src/hotkeys.cpp
@@ -24,7 +24,7 @@ char *_hotkeys_file;
* List of all HotkeyLists.
* This is a pointer to ensure initialisation order with the various static HotkeyList instances.
*/
-static std::vector<HotkeyList*> *_hotkey_lists = NULL;
+static std::vector<HotkeyList*> *_hotkey_lists = nullptr;
/** String representation of a keycode */
struct KeycodeNames {
@@ -254,7 +254,7 @@ void Hotkey::AddKeycode(uint16 keycode)
HotkeyList::HotkeyList(const char *ini_group, Hotkey *items, GlobalHotkeyHandlerFunc global_hotkey_handler) :
global_hotkey_handler(global_hotkey_handler), ini_group(ini_group), items(items)
{
- if (_hotkey_lists == NULL) _hotkey_lists = new std::vector<HotkeyList*>();
+ if (_hotkey_lists == nullptr) _hotkey_lists = new std::vector<HotkeyList*>();
_hotkey_lists->push_back(this);
}
@@ -270,11 +270,11 @@ HotkeyList::~HotkeyList()
void HotkeyList::Load(IniFile *ini)
{
IniGroup *group = ini->GetGroup(this->ini_group);
- for (Hotkey *hotkey = this->items; hotkey->name != NULL; ++hotkey) {
+ for (Hotkey *hotkey = this->items; hotkey->name != nullptr; ++hotkey) {
IniItem *item = group->GetItem(hotkey->name, false);
- if (item != NULL) {
+ if (item != nullptr) {
hotkey->keycodes.clear();
- if (item->value != NULL) ParseHotkeys(hotkey, item->value);
+ if (item->value != nullptr) ParseHotkeys(hotkey, item->value);
}
}
}
@@ -286,7 +286,7 @@ void HotkeyList::Load(IniFile *ini)
void HotkeyList::Save(IniFile *ini) const
{
IniGroup *group = ini->GetGroup(this->ini_group);
- for (const Hotkey *hotkey = this->items; hotkey->name != NULL; ++hotkey) {
+ for (const Hotkey *hotkey = this->items; hotkey->name != nullptr; ++hotkey) {
IniItem *item = group->GetItem(hotkey->name, true);
item->SetValue(SaveKeycodes(hotkey));
}
@@ -300,7 +300,7 @@ void HotkeyList::Save(IniFile *ini) const
*/
int HotkeyList::CheckMatch(uint16 keycode, bool global_only) const
{
- for (const Hotkey *list = this->items; list->name != NULL; ++list) {
+ for (const Hotkey *list = this->items; list->name != nullptr; ++list) {
auto begin = list->keycodes.begin();
auto end = list->keycodes.end();
if (std::find(begin, end, keycode | WKC_GLOBAL_HOTKEY) != end || (!global_only && std::find(begin, end, keycode) != end)) {
@@ -344,7 +344,7 @@ void SaveHotkeysToConfig()
void HandleGlobalHotkeys(WChar key, uint16 keycode)
{
for (HotkeyList *list : *_hotkey_lists) {
- if (list->global_hotkey_handler == NULL) continue;
+ if (list->global_hotkey_handler == nullptr) continue;
int hotkey = list->CheckMatch(keycode, true);
if (hotkey >= 0 && (list->global_hotkey_handler(hotkey) == ES_HANDLED)) return;
diff --git a/src/hotkeys.h b/src/hotkeys.h
index fd729a47a..00e8c0c3f 100644
--- a/src/hotkeys.h
+++ b/src/hotkeys.h
@@ -32,7 +32,7 @@ struct Hotkey {
std::vector<uint16> keycodes;
};
-#define HOTKEY_LIST_END Hotkey((uint16)0, NULL, -1)
+#define HOTKEY_LIST_END Hotkey((uint16)0, nullptr, -1)
struct IniFile;
@@ -42,7 +42,7 @@ struct IniFile;
struct HotkeyList {
typedef EventState (*GlobalHotkeyHandlerFunc)(int hotkey);
- HotkeyList(const char *ini_group, Hotkey *items, GlobalHotkeyHandlerFunc global_hotkey_handler = NULL);
+ HotkeyList(const char *ini_group, Hotkey *items, GlobalHotkeyHandlerFunc global_hotkey_handler = nullptr);
~HotkeyList();
void Load(IniFile *ini);
diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp
index c20b0a05b..df9286308 100644
--- a/src/industry_cmd.cpp
+++ b/src/industry_cmd.cpp
@@ -101,7 +101,7 @@ IndustryType GetIndustryType(TileIndex tile)
assert(IsTileType(tile, MP_INDUSTRY));
const Industry *ind = Industry::GetByTile(tile);
- assert(ind != NULL);
+ assert(ind != nullptr);
return ind->type;
}
@@ -200,11 +200,11 @@ void Industry::PostDestructor(size_t index)
/**
* Return a random valid industry.
- * @return random industry, NULL if there are no industries
+ * @return random industry, nullptr if there are no industries
*/
/* static */ Industry *Industry::GetRandom()
{
- if (Industry::GetNumItems() == 0) return NULL;
+ if (Industry::GetNumItems() == 0) return nullptr;
int num = RandomRange((uint16)Industry::GetNumItems());
size_t index = MAX_UVALUE(size_t);
@@ -316,7 +316,7 @@ static void DrawTile_Industry(TileInfo *ti)
* DrawNewIndustry will return false if ever the resolver could not
* find any sprite to display. So in this case, we will jump on the
* substitute gfx instead. */
- if (indts->grf_prop.spritegroup[0] != NULL && DrawNewIndustryTile(ti, ind, gfx, indts)) {
+ if (indts->grf_prop.spritegroup[0] != nullptr && DrawNewIndustryTile(ti, ind, gfx, indts)) {
return;
} else {
/* No sprite group (or no valid one) found, meaning no graphics associated.
@@ -385,7 +385,7 @@ static Foundation GetFoundation_Industry(TileIndex tile, Slope tileh)
*/
if (gfx >= NEW_INDUSTRYTILEOFFSET) {
const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
- if (indts->grf_prop.spritegroup[0] != NULL && HasBit(indts->callback_mask, CBM_INDT_DRAW_FOUNDATIONS)) {
+ if (indts->grf_prop.spritegroup[0] != nullptr && HasBit(indts->callback_mask, CBM_INDT_DRAW_FOUNDATIONS)) {
uint32 callback_res = GetIndustryTileCallback(CBID_INDTILE_DRAW_FOUNDATIONS, 0, 0, gfx, Industry::GetByTile(tile), tile);
if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(indts->grf_prop.grffile, CBID_INDTILE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
}
@@ -475,7 +475,7 @@ static void GetTileDesc_Industry(TileIndex tile, TileDesc *td)
td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
}
- if (is->grf_prop.grffile != NULL) {
+ if (is->grf_prop.grffile != nullptr) {
td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
}
}
@@ -799,7 +799,7 @@ static void TileLoopIndustry_BubbleGenerator(TileIndex tile)
EV_BUBBLE
);
- if (v != NULL) v->animation_substate = dir;
+ if (v != nullptr) v->animation_substate = dir;
}
static void TileLoop_Industry(TileIndex tile)
@@ -1106,7 +1106,7 @@ static void ChopLumberMillTrees(Industry *i)
}
TileIndex tile = i->location.tile;
- if (CircularTileSearch(&tile, 40, SearchLumberMillTrees, NULL)) { // 40x40 tiles to search.
+ if (CircularTileSearch(&tile, 40, SearchLumberMillTrees, nullptr)) { // 40x40 tiles to search.
i->produced_cargo_waiting[0] = min(0xffff, i->produced_cargo_waiting[0] + 45); // Found a tree, add according value to waiting cargo.
}
}
@@ -1339,11 +1339,11 @@ static CheckNewIndustryProc * const _check_new_industry_procs[CHECK_END] = {
* Find a town for the industry, while checking for multiple industries in the same town.
* @param tile Position of the industry to build.
* @param type Industry type.
- * @param[out] t Pointer to return town for the new industry, \c NULL is written if no good town can be found.
+ * @param[out] t Pointer to return town for the new industry, \c nullptr is written if no good town can be found.
* @return Succeeded or failed command.
*
- * @pre \c *t != NULL
- * @post \c *t points to a town on success, and \c NULL on failure.
+ * @pre \c *t != nullptr
+ * @post \c *t points to a town on success, and \c nullptr on failure.
*/
static CommandCost FindTownForIndustry(TileIndex tile, int type, Town **t)
{
@@ -1354,7 +1354,7 @@ static CommandCost FindTownForIndustry(TileIndex tile, int type, Town **t)
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
if (i->type == (byte)type && i->town == *t) {
- *t = NULL;
+ *t = nullptr;
return_cmd_error(STR_ERROR_ONLY_ONE_ALLOWED_PER_TOWN);
}
}
@@ -1391,7 +1391,7 @@ bool IsSlopeRefused(Slope current, Slope refused)
* @param[out] custom_shape_check Perform custom check for the site.
* @return Failed or succeeded command.
*/
-static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable *it, uint itspec_index, int type, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type, bool *custom_shape_check = NULL)
+static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable *it, uint itspec_index, int type, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type, bool *custom_shape_check = nullptr)
{
bool refused_slope = false;
bool custom_shape = false;
@@ -1451,7 +1451,7 @@ static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTil
}
} while ((++it)->ti.x != -0x80);
- if (custom_shape_check != NULL) *custom_shape_check = custom_shape;
+ if (custom_shape_check != nullptr) *custom_shape_check = custom_shape;
/* It is almost impossible to have a fully flat land in TG, so what we
* do is that we check if we can make the land flat later on. See
@@ -1588,7 +1588,7 @@ static bool CheckIfCanLevelIndustryPlatform(TileIndex tile, DoCommandFlag flags,
static CommandCost CheckIfFarEnoughFromConflictingIndustry(TileIndex tile, int type)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
- const Industry *i = NULL;
+ const Industry *i = nullptr;
/* On a large map with many industries, it may be faster to check an area. */
static const int dmax = 14;
@@ -1652,7 +1652,7 @@ static void AdvertiseIndustryOpening(const Industry *ind)
*/
static void PopulateStationsNearby(Industry *ind)
{
- if (ind->neutral_station != NULL && !_settings_game.station.serve_neutral_industries) {
+ if (ind->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) {
/* Industry has a neutral station. Use it and ignore any other nearby stations. */
ind->stations_near.insert(ind->neutral_station);
ind->neutral_station->industries_near.clear();
@@ -1874,7 +1874,7 @@ static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type,
* @param[out] ip Pointer to store newly created industry.
* @return Succeeded or failed command.
*
- * @post \c *ip contains the newly created industry if all checks are successful and the \a flags request actual creation, else it contains \c NULL afterwards.
+ * @post \c *ip contains the newly created industry if all checks are successful and the \a flags request actual creation, else it contains \c nullptr afterwards.
*/
static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, DoCommandFlag flags, const IndustrySpec *indspec, uint itspec_index, uint32 random_var8f, uint16 random_initial_bits, Owner founder, IndustryAvailabilityCallType creation_type, Industry **ip)
{
@@ -1882,7 +1882,7 @@ static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, Do
const IndustryTileTable *it = indspec->table[itspec_index];
bool custom_shape_check = false;
- *ip = NULL;
+ *ip = nullptr;
std::vector<ClearedObjectArea> object_areas(_cleared_object_areas);
CommandCost ret = CheckIfIndustryTilesAreFree(tile, it, itspec_index, type, random_initial_bits, founder, creation_type, &custom_shape_check);
@@ -1904,10 +1904,10 @@ static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, Do
ret = CheckIfFarEnoughFromConflictingIndustry(tile, type);
if (ret.Failed()) return ret;
- Town *t = NULL;
+ Town *t = nullptr;
ret = FindTownForIndustry(tile, type, &t);
if (ret.Failed()) return ret;
- assert(t != NULL);
+ assert(t != nullptr);
ret = CheckIfIndustryIsAllowed(tile, type, t);
if (ret.Failed()) return ret;
@@ -1963,7 +1963,7 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
CommandCost ret = CommandCost(STR_ERROR_SITE_UNSUITABLE);
const bool deity_prospect = _current_company == OWNER_DEITY && !HasBit(p1, 16);
- Industry *ind = NULL;
+ Industry *ind = nullptr;
if (deity_prospect || (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry())) {
if (flags & DC_EXEC) {
/* Prospected industries are build as OWNER_TOWN to not e.g. be build on owned land of the founder */
@@ -2005,7 +2005,7 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (ret.Failed()) return ret;
}
- if ((flags & DC_EXEC) && ind != NULL && _game_mode != GM_EDITOR) {
+ if ((flags & DC_EXEC) && ind != nullptr && _game_mode != GM_EDITOR) {
AdvertiseIndustryOpening(ind);
}
@@ -2018,7 +2018,7 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
* @param tile The location to build the industry.
* @param type The industry type to build.
* @param creation_type The circumstances the industry is created under.
- * @return the created industry or NULL if it failed.
+ * @return the created industry or nullptr if it failed.
*/
static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAvailabilityCallType creation_type)
{
@@ -2026,9 +2026,9 @@ static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAv
uint32 seed = Random();
uint32 seed2 = Random();
- Industry *i = NULL;
+ Industry *i = nullptr;
CommandCost ret = CreateNewIndustryHelper(tile, type, DC_EXEC, indspec, RandomRange(indspec->num_table), seed, GB(seed2, 0, 16), OWNER_NONE, creation_type, &i);
- assert(i != NULL || ret.Failed());
+ assert(i != nullptr || ret.Failed());
return i;
}
@@ -2110,16 +2110,16 @@ static uint GetNumberOfIndustries()
* than to try a few times before concluding it does not work.
* @param type Industry type of the desired industry.
* @param try_hard Try very hard to find a place. (Used to place at least one industry per type.)
- * @return Pointer to created industry, or \c NULL if creation failed.
+ * @return Pointer to created industry, or \c nullptr if creation failed.
*/
static Industry *PlaceIndustry(IndustryType type, IndustryAvailabilityCallType creation_type, bool try_hard)
{
uint tries = try_hard ? 10000u : 2000u;
for (; tries > 0; tries--) {
Industry *ind = CreateNewIndustry(RandomTile(), type, creation_type);
- if (ind != NULL) return ind;
+ if (ind != nullptr) return ind;
}
- return NULL;
+ return nullptr;
}
/**
@@ -2385,7 +2385,7 @@ void IndustryBuildData::TryBuildNewIndustry()
/* Try to create the industry. */
const Industry *ind = PlaceIndustry(it, IACT_RANDOMCREATION, false);
- if (ind == NULL) {
+ if (ind == nullptr) {
this->builddata[it].wait_count = this->builddata[it].max_wait + 1; // Compensate for decrementing below.
this->builddata[it].max_wait = min(1000, this->builddata[it].max_wait + 2);
} else {
@@ -2474,7 +2474,7 @@ static int WhoCanServiceIndustry(Industry *ind)
bool c_accepts = false;
bool c_produces = false;
if (v->type == VEH_TRAIN && v->IsFrontEngine()) {
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
CanCargoServiceIndustry(u->cargo_type, ind, &c_accepts, &c_produces);
}
} else if (v->type == VEH_ROAD || v->type == VEH_SHIP || v->type == VEH_AIRCRAFT) {
@@ -2493,7 +2493,7 @@ static int WhoCanServiceIndustry(Industry *ind)
if (o->IsType(OT_GOTO_STATION) && !(o->GetUnloadType() & OUFB_TRANSFER)) {
/* Vehicle visits a station to load or unload */
Station *st = Station::Get(o->GetDestination());
- assert(st != NULL);
+ assert(st != nullptr);
/* Same cargo produced by industry is dropped here => not serviced by vehicle v */
if ((o->GetUnloadType() & OUFB_UNLOAD) && !c_accepts) break;
@@ -2774,7 +2774,7 @@ void IndustryDailyLoop()
_industry_builder.TryBuildNewIndustry();
} else {
Industry *i = Industry::GetRandom();
- if (i != NULL) {
+ if (i != nullptr) {
ChangeIndustryProduction(i, false);
SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
}
@@ -2932,8 +2932,8 @@ extern const TileTypeProcs _tile_type_industry_procs = {
AnimateTile_Industry, // animate_tile_proc
TileLoop_Industry, // tile_loop_proc
ChangeTileOwner_Industry, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
- NULL, // vehicle_enter_tile_proc
+ nullptr, // add_produced_cargo_proc
+ nullptr, // vehicle_enter_tile_proc
GetFoundation_Industry, // get_foundation_proc
TerraformTile_Industry, // terraform_tile_proc
};
diff --git a/src/industry_gui.cpp b/src/industry_gui.cpp
index 2796cd979..17212926d 100644
--- a/src/industry_gui.cpp
+++ b/src/industry_gui.cpp
@@ -76,7 +76,7 @@ static void ShowIndustryCargoesWindow(IndustryType id);
* Gets the string to display after the cargo name (using callback 37)
* @param cargo the cargo for which the suffix is requested, meaning depends on presence of flag 18 in prop 1A
* @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
- * @param ind the industry (NULL if in fund window)
+ * @param ind the industry (nullptr if in fund window)
* @param ind_type the industry type
* @param indspec the industry spec
* @param suffix is filled with the string to display
@@ -138,7 +138,7 @@ enum CargoSuffixInOut {
* Gets all strings to display after the cargoes of industries (using callback 37)
* @param use_input get suffixes for output cargoes or input cargoes?
* @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
- * @param ind the industry (NULL if in fund window)
+ * @param ind the industry (nullptr if in fund window)
* @param ind_type the industry type
* @param indspec the industry spec
* @param cargoes array with cargotypes. for CT_INVALID no suffix will be determined
@@ -438,7 +438,7 @@ public:
CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
/* Measure the accepted cargoes, if any. */
- GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
+ GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
Dimension strdim = GetStringBoundingBox(cargostring.c_str());
if (strdim.width > max_minwidth) {
@@ -448,7 +448,7 @@ public:
d = maxdim(d, strdim);
/* Measure the produced cargoes, if any. */
- GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
+ GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
strdim = GetStringBoundingBox(cargostring.c_str());
if (strdim.width > max_minwidth) {
@@ -551,18 +551,18 @@ public:
CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
/* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
- GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
+ GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
y = DrawStringMultiLine(left, right, y, bottom, cargostring.c_str());
/* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
- GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
+ GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
y = DrawStringMultiLine(left, right, y, bottom, cargostring.c_str());
/* Get the additional purchase info text, if it has not already been queried. */
if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
- uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
+ uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, nullptr, this->selected_type, INVALID_TILE);
if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
if (callback_res > 0x400) {
ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
@@ -589,12 +589,12 @@ public:
if (y < this->count) { // Is it within the boundaries of available data?
this->selected_index = y;
this->selected_type = this->index[y];
- const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
+ const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
this->SetDirty();
if (_thd.GetCallbackWnd() == this &&
- ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
+ ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != nullptr && indsp->IsRawIndustry()) ||
this->selected_type == INVALID_INDUSTRYTYPE ||
!this->enabled[this->selected_index])) {
/* Reset the button state if going to prospecting or "build many industries" */
@@ -717,8 +717,8 @@ public:
if (!gui_scope) return;
this->SetupArrays();
- const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
- if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
+ const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
+ if (indsp == nullptr) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
this->SetButtons();
}
};
@@ -1048,7 +1048,7 @@ public:
void OnResize() override
{
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
nvp->UpdateViewportCoordinates(this);
@@ -1215,7 +1215,7 @@ protected:
}
if (!this->industries.Sort()) return;
- IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
+ IndustryDirectoryWindow::last_industry = nullptr; // Reset name sorter sort cache
this->SetWidgetDirty(WID_ID_INDUSTRY_LIST); // Set the modified widget dirty
}
@@ -1493,7 +1493,7 @@ public:
};
Listing IndustryDirectoryWindow::last_sorting = {false, 0};
-const Industry *IndustryDirectoryWindow::last_industry = NULL;
+const Industry *IndustryDirectoryWindow::last_industry = nullptr;
/* Available station sorting functions. */
GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
@@ -1898,8 +1898,8 @@ struct CargoesField {
/**
* Decide which cargo was clicked at in a #CFT_CARGO field.
- * @param left Left industry neighbour if available (else \c NULL should be supplied).
- * @param right Right industry neighbour if available (else \c NULL should be supplied).
+ * @param left Left industry neighbour if available (else \c nullptr should be supplied).
+ * @param right Right industry neighbour if available (else \c nullptr should be supplied).
* @param pt Click position in the cargo field.
* @return Cargo clicked at, or #INVALID_CARGO if none.
*/
@@ -1929,7 +1929,7 @@ struct CargoesField {
/* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
if (col == 0) {
if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
- if (left != NULL) {
+ if (left != nullptr) {
if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
}
@@ -1937,7 +1937,7 @@ struct CargoesField {
}
if (col == this->u.cargo.num_cargoes) {
if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
- if (right != NULL) {
+ if (right != nullptr) {
if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
}
@@ -2678,8 +2678,8 @@ struct IndustryCargoesWindow : public Window {
break;
case CFT_CARGO: {
- CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
- CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
+ CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
+ CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
break;
@@ -2703,7 +2703,7 @@ struct IndustryCargoesWindow : public Window {
if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
- if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
+ if (FindWindowByClass(WC_SMALLMAP) == nullptr) ShowSmallMap();
this->NotifySmallmap();
}
break;
@@ -2764,8 +2764,8 @@ struct IndustryCargoesWindow : public Window {
CargoID cid = INVALID_CARGO;
switch (fld->type) {
case CFT_CARGO: {
- CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
- CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
+ CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
+ CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
cid = fld->CargoClickedAt(lft, rgt, xy);
break;
}
@@ -2777,7 +2777,7 @@ struct IndustryCargoesWindow : public Window {
case CFT_INDUSTRY:
if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
- GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, NULL, close_cond);
+ GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, nullptr, close_cond);
}
return true;
@@ -2822,7 +2822,7 @@ static void ShowIndustryCargoesWindow(IndustryType id)
}
Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
- if (w != NULL) {
+ if (w != nullptr) {
w->InvalidateData(id);
return;
}
diff --git a/src/ini.cpp b/src/ini.cpp
index 6767d8525..05ddc0386 100644
--- a/src/ini.cpp
+++ b/src/ini.cpp
@@ -29,7 +29,7 @@
/**
* Create a new ini file with given group names.
- * @param list_group_names A \c NULL terminated list with group names that should be loaded as lists instead of variables. @see IGT_LIST
+ * @param list_group_names A \c nullptr terminated list with group names that should be loaded as lists instead of variables. @see IGT_LIST
*/
IniFile::IniFile(const char * const *list_group_names) : IniLoadFile(list_group_names)
{
@@ -52,23 +52,23 @@ bool IniFile::SaveToDisk(const char *filename)
strecpy(file_new, filename, lastof(file_new));
strecat(file_new, ".new", lastof(file_new));
FILE *f = fopen(file_new, "w");
- if (f == NULL) return false;
+ if (f == nullptr) return false;
- for (const IniGroup *group = this->group; group != NULL; group = group->next) {
+ for (const IniGroup *group = this->group; group != nullptr; group = group->next) {
if (group->comment) fputs(group->comment, f);
fprintf(f, "[%s]\n", group->name);
- for (const IniItem *item = group->item; item != NULL; item = item->next) {
- if (item->comment != NULL) fputs(item->comment, f);
+ for (const IniItem *item = group->item; item != nullptr; item = item->next) {
+ if (item->comment != nullptr) fputs(item->comment, f);
/* protect item->name with quotes if needed */
- if (strchr(item->name, ' ') != NULL ||
+ if (strchr(item->name, ' ') != nullptr ||
item->name[0] == '[') {
fprintf(f, "\"%s\"", item->name);
} else {
fprintf(f, "%s", item->name);
}
- fprintf(f, " = %s\n", item->value == NULL ? "" : item->value);
+ fprintf(f, " = %s\n", item->value == nullptr ? "" : item->value);
}
}
if (this->comment) fputs(this->comment, f);
diff --git a/src/ini_load.cpp b/src/ini_load.cpp
index 389dcab03..5980b459d 100644
--- a/src/ini_load.cpp
+++ b/src/ini_load.cpp
@@ -23,7 +23,7 @@
* @param name the name of the item
* @param last the last element of the name of the item
*/
-IniItem::IniItem(IniGroup *parent, const char *name, const char *last) : next(NULL), value(NULL), comment(NULL)
+IniItem::IniItem(IniGroup *parent, const char *name, const char *last) : next(nullptr), value(nullptr), comment(nullptr)
{
this->name = stredup(name, last);
str_validate(this->name, this->name + strlen(this->name));
@@ -58,7 +58,7 @@ void IniItem::SetValue(const char *value)
* @param name the name of the group
* @param last the last element of the name of the group
*/
-IniGroup::IniGroup(IniLoadFile *parent, const char *name, const char *last) : next(NULL), type(IGT_VARIABLES), item(NULL), comment(NULL)
+IniGroup::IniGroup(IniLoadFile *parent, const char *name, const char *last) : next(nullptr), type(IGT_VARIABLES), item(nullptr), comment(nullptr)
{
this->name = stredup(name, last);
str_validate(this->name, this->name + strlen(this->name));
@@ -67,16 +67,16 @@ IniGroup::IniGroup(IniLoadFile *parent, const char *name, const char *last) : ne
*parent->last_group = this;
parent->last_group = &this->next;
- if (parent->list_group_names != NULL) {
- for (uint i = 0; parent->list_group_names[i] != NULL; i++) {
+ if (parent->list_group_names != nullptr) {
+ for (uint i = 0; parent->list_group_names[i] != nullptr; i++) {
if (strcmp(this->name, parent->list_group_names[i]) == 0) {
this->type = IGT_LIST;
return;
}
}
}
- if (parent->seq_group_names != NULL) {
- for (uint i = 0; parent->seq_group_names[i] != NULL; i++) {
+ if (parent->seq_group_names != nullptr) {
+ for (uint i = 0; parent->seq_group_names[i] != nullptr; i++) {
if (strcmp(this->name, parent->seq_group_names[i]) == 0) {
this->type = IGT_SEQUENCE;
return;
@@ -100,18 +100,18 @@ IniGroup::~IniGroup()
* and create is true it creates a new item.
* @param name name of the item to find.
* @param create whether to create an item when not found or not.
- * @return the requested item or NULL if not found.
+ * @return the requested item or nullptr if not found.
*/
IniItem *IniGroup::GetItem(const char *name, bool create)
{
- for (IniItem *item = this->item; item != NULL; item = item->next) {
+ for (IniItem *item = this->item; item != nullptr; item = item->next) {
if (strcmp(item->name, name) == 0) return item;
}
- if (!create) return NULL;
+ if (!create) return nullptr;
/* otherwise make a new one */
- return new IniItem(this, name, NULL);
+ return new IniItem(this, name, nullptr);
}
/**
@@ -120,18 +120,18 @@ IniItem *IniGroup::GetItem(const char *name, bool create)
void IniGroup::Clear()
{
delete this->item;
- this->item = NULL;
+ this->item = nullptr;
this->last_item = &this->item;
}
/**
* Construct a new in-memory Ini file representation.
- * @param list_group_names A \c NULL terminated list with group names that should be loaded as lists instead of variables. @see IGT_LIST
- * @param seq_group_names A \c NULL terminated list with group names that should be loaded as lists of names. @see IGT_SEQUENCE
+ * @param list_group_names A \c nullptr terminated list with group names that should be loaded as lists instead of variables. @see IGT_LIST
+ * @param seq_group_names A \c nullptr terminated list with group names that should be loaded as lists of names. @see IGT_SEQUENCE
*/
IniLoadFile::IniLoadFile(const char * const *list_group_names, const char * const *seq_group_names) :
- group(NULL),
- comment(NULL),
+ group(nullptr),
+ comment(nullptr),
list_group_names(list_group_names),
seq_group_names(seq_group_names)
{
@@ -151,20 +151,20 @@ IniLoadFile::~IniLoadFile()
* @param name name of the group to find.
* @param len the maximum length of said name (\c 0 means length of the string).
* @param create_new Allow creation of group if it does not exist.
- * @return The requested group if it exists or was created, else \c NULL.
+ * @return The requested group if it exists or was created, else \c nullptr.
*/
IniGroup *IniLoadFile::GetGroup(const char *name, size_t len, bool create_new)
{
if (len == 0) len = strlen(name);
/* does it exist already? */
- for (IniGroup *group = this->group; group != NULL; group = group->next) {
+ for (IniGroup *group = this->group; group != nullptr; group = group->next) {
if (!strncmp(group->name, name, len) && group->name[len] == 0) {
return group;
}
}
- if (!create_new) return NULL;
+ if (!create_new) return nullptr;
/* otherwise make a new one */
IniGroup *group = new IniGroup(this, name, name + len - 1);
@@ -179,19 +179,19 @@ IniGroup *IniLoadFile::GetGroup(const char *name, size_t len, bool create_new)
void IniLoadFile::RemoveGroup(const char *name)
{
size_t len = strlen(name);
- IniGroup *prev = NULL;
+ IniGroup *prev = nullptr;
IniGroup *group;
/* does it exist already? */
- for (group = this->group; group != NULL; prev = group, group = group->next) {
+ for (group = this->group; group != nullptr; prev = group, group = group->next) {
if (strncmp(group->name, name, len) == 0) {
break;
}
}
- if (group == NULL) return;
+ if (group == nullptr) return;
- if (prev != NULL) {
+ if (prev != nullptr) {
prev->next = prev->next->next;
if (this->last_group == &group->next) this->last_group = &prev->next;
} else {
@@ -199,7 +199,7 @@ void IniLoadFile::RemoveGroup(const char *name)
if (this->last_group == &group->next) this->last_group = &this->group;
}
- group->next = NULL;
+ group->next = nullptr;
delete group;
}
@@ -214,15 +214,15 @@ void IniLoadFile::LoadFromDisk(const char *filename, Subdirectory subdir)
assert(this->last_group == &this->group);
char buffer[1024];
- IniGroup *group = NULL;
+ IniGroup *group = nullptr;
- char *comment = NULL;
+ char *comment = nullptr;
uint comment_size = 0;
uint comment_alloc = 0;
size_t end;
FILE *in = this->OpenFile(filename, subdir, &end);
- if (in == NULL) return;
+ if (in == nullptr) return;
end += ftell(in);
@@ -238,7 +238,7 @@ void IniLoadFile::LoadFromDisk(const char *filename, Subdirectory subdir)
*e = '\0';
/* Skip comments and empty lines outside IGT_SEQUENCE groups. */
- if ((group == NULL || group->type != IGT_SEQUENCE) && (*s == '#' || *s == ';' || *s == '\0')) {
+ if ((group == nullptr || group->type != IGT_SEQUENCE) && (*s == '#' || *s == ';' || *s == '\0')) {
uint ns = comment_size + (e - s + 1);
uint a = comment_alloc;
/* add to comment */
@@ -267,7 +267,7 @@ void IniLoadFile::LoadFromDisk(const char *filename, Subdirectory subdir)
group->comment = stredup(comment, comment + comment_size - 1);
comment_size = 0;
}
- } else if (group != NULL) {
+ } else if (group != nullptr) {
if (group->type == IGT_SEQUENCE) {
/* A sequence group, use the line as item name without further interpretation. */
IniItem *item = new IniItem(group, buffer, e - 1);
@@ -305,9 +305,9 @@ void IniLoadFile::LoadFromDisk(const char *filename, Subdirectory subdir)
if (e > t && e[-1] == '\"') e--;
*e = '\0';
- /* If the value was not quoted and empty, it must be NULL */
- item->value = (!quoted && e == t) ? NULL : stredup(t);
- if (item->value != NULL) str_validate(item->value, item->value + strlen(item->value));
+ /* If the value was not quoted and empty, it must be nullptr */
+ item->value = (!quoted && e == t) ? nullptr : stredup(t);
+ if (item->value != nullptr) str_validate(item->value, item->value + strlen(item->value));
} else {
/* it's an orphan item */
this->ReportFileError("ini: '", buffer, "' outside of group");
diff --git a/src/ini_type.h b/src/ini_type.h
index 9bd47fd4e..a2ff76502 100644
--- a/src/ini_type.h
+++ b/src/ini_type.h
@@ -28,7 +28,7 @@ struct IniItem {
char *value; ///< The value of this item
char *comment; ///< The comment associated with this item
- IniItem(struct IniGroup *parent, const char *name, const char *last = NULL);
+ IniItem(struct IniGroup *parent, const char *name, const char *last = nullptr);
~IniItem();
void SetValue(const char *value);
@@ -43,7 +43,7 @@ struct IniGroup {
char *name; ///< name of group
char *comment; ///< comment for group
- IniGroup(struct IniLoadFile *parent, const char *name, const char *last = NULL);
+ IniGroup(struct IniLoadFile *parent, const char *name, const char *last = nullptr);
~IniGroup();
IniItem *GetItem(const char *name, bool create);
@@ -55,10 +55,10 @@ struct IniLoadFile {
IniGroup *group; ///< the first group in the ini
IniGroup **last_group; ///< the last group in the ini
char *comment; ///< last comment in file
- const char * const *list_group_names; ///< NULL terminated list with group names that are lists
- const char * const *seq_group_names; ///< NULL terminated list with group names that are sequences.
+ const char * const *list_group_names; ///< nullptr terminated list with group names that are lists
+ const char * const *seq_group_names; ///< nullptr terminated list with group names that are sequences.
- IniLoadFile(const char * const *list_group_names = NULL, const char * const *seq_group_names = NULL);
+ IniLoadFile(const char * const *list_group_names = nullptr, const char * const *seq_group_names = nullptr);
virtual ~IniLoadFile();
IniGroup *GetGroup(const char *name, size_t len = 0, bool create_new = true);
@@ -71,7 +71,7 @@ struct IniLoadFile {
* @param filename Name of the INI file.
* @param subdir The subdir to load the file from.
* @param[out] size Size of the opened file.
- * @return File handle of the opened file, or \c NULL.
+ * @return File handle of the opened file, or \c nullptr.
*/
virtual FILE *OpenFile(const char *filename, Subdirectory subdir, size_t *size) = 0;
@@ -86,7 +86,7 @@ struct IniLoadFile {
/** Ini file that supports both loading and saving. */
struct IniFile : IniLoadFile {
- IniFile(const char * const *list_group_names = NULL);
+ IniFile(const char * const *list_group_names = nullptr);
bool SaveToDisk(const char *filename);
diff --git a/src/intro_gui.cpp b/src/intro_gui.cpp
index 307be4405..804ada8d7 100644
--- a/src/intro_gui.cpp
+++ b/src/intro_gui.cpp
@@ -269,7 +269,7 @@ static const NWidgetPart _nested_select_game_widgets[] = {
};
static WindowDesc _select_game_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_SELECT_GAME, WC_NONE,
0,
_nested_select_game_widgets, lengthof(_nested_select_game_widgets)
@@ -303,7 +303,7 @@ void AskExitGame()
ShowQuery(
STR_QUIT_CAPTION,
STR_QUIT_ARE_YOU_SURE_YOU_WANT_TO_EXIT_OPENTTD,
- NULL,
+ nullptr,
AskExitGameCallback
);
}
@@ -322,7 +322,7 @@ void AskExitToGameMenu()
ShowQuery(
STR_ABANDON_GAME_CAPTION,
(_game_mode != GM_EDITOR) ? STR_ABANDON_GAME_QUERY : STR_ABANDON_SCENARIO_QUERY,
- NULL,
+ nullptr,
AskExitToGameMenuCallback
);
}
diff --git a/src/landscape.cpp b/src/landscape.cpp
index b36f5c884..66be73bd6 100644
--- a/src/landscape.cpp
+++ b/src/landscape.cpp
@@ -82,12 +82,12 @@ extern const byte _slope_to_sprite_offset[32] = {
/**
* Description of the snow line throughout the year.
*
- * If it is \c NULL, a static snowline height is used, as set by \c _settings_game.game_creation.snow_line_height.
+ * If it is \c nullptr, a static snowline height is used, as set by \c _settings_game.game_creation.snow_line_height.
* Otherwise it points to a table loaded from a newGRF file that describes the variable snowline.
* @ingroup SnowLineGroup
* @see GetSnowLine() GameCreationSettings
*/
-static SnowLine *_snow_line = NULL;
+static SnowLine *_snow_line = nullptr;
/**
* Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
@@ -104,7 +104,7 @@ static SnowLine *_snow_line = NULL;
*/
Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
{
- if (clamped != NULL) *clamped = false; // Not clamping yet.
+ if (clamped != nullptr) *clamped = false; // Not clamping yet.
/* Initial x/y world coordinate is like if the landscape
* was completely flat on height 0. */
@@ -122,7 +122,7 @@ Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
Point old_pt = pt;
pt.x = Clamp(pt.x, -extra_tiles * TILE_SIZE, max_x);
pt.y = Clamp(pt.y, -extra_tiles * TILE_SIZE, max_y);
- if (clamped != NULL) *clamped = (pt.x != old_pt.x) || (pt.y != old_pt.y);
+ if (clamped != nullptr) *clamped = (pt.x != old_pt.x) || (pt.y != old_pt.y);
}
/* Now find the Z-world coordinate by fix point iteration.
@@ -147,7 +147,7 @@ Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
Point old_pt = pt;
pt.x = Clamp(pt.x, min_coord, max_x);
pt.y = Clamp(pt.y, min_coord, max_y);
- if (clamped != NULL) *clamped = *clamped || (pt.x != old_pt.x) || (pt.y != old_pt.y);
+ if (clamped != nullptr) *clamped = *clamped || (pt.x != old_pt.x) || (pt.y != old_pt.y);
}
return pt;
@@ -418,7 +418,7 @@ void GetSlopePixelZOnEdge(Slope tileh, DiagDirection edge, int *z1, int *z2)
* If a tile does not have a foundation, the function returns the same as GetTileSlope.
*
* @param tile The tile of interest.
- * @param z returns the z of the foundation slope. (Can be NULL, if not needed)
+ * @param z returns the z of the foundation slope. (Can be nullptr, if not needed)
* @return The slope on top of the foundation.
*/
Slope GetFoundationSlope(TileIndex tile, int *z)
@@ -426,7 +426,7 @@ Slope GetFoundationSlope(TileIndex tile, int *z)
Slope tileh = GetTileSlope(tile, z);
Foundation f = _tile_type_procs[GetTileType(tile)]->get_foundation_proc(tile, tileh);
uint z_inc = ApplyFoundationToSlope(f, &tileh);
- if (z != NULL) *z += z_inc;
+ if (z != nullptr) *z += z_inc;
return tileh;
}
@@ -572,7 +572,7 @@ void DrawFoundation(TileInfo *ti, Foundation f)
void DoClearSquare(TileIndex tile)
{
/* If the tile can have animation and we clear it, delete it from the animated tile list. */
- if (_tile_type_procs[GetTileType(tile)]->animate_tile_proc != NULL) DeleteAnimatedTile(tile);
+ if (_tile_type_procs[GetTileType(tile)]->animate_tile_proc != nullptr) DeleteAnimatedTile(tile);
MakeClear(tile, CLEAR_GRASS, _generating_world ? 3 : 0);
MarkTileDirtyByTile(tile);
@@ -616,7 +616,7 @@ void GetTileDesc(TileIndex tile, TileDesc *td)
*/
bool IsSnowLineSet()
{
- return _snow_line != NULL;
+ return _snow_line != nullptr;
}
/**
@@ -645,7 +645,7 @@ void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
*/
byte GetSnowLine()
{
- if (_snow_line == NULL) return _settings_game.game_creation.snow_line_height;
+ if (_snow_line == nullptr) return _settings_game.game_creation.snow_line_height;
YearMonthDay ymd;
ConvertDateToYMD(_date, &ymd);
@@ -659,7 +659,7 @@ byte GetSnowLine()
*/
byte HighestSnowLine()
{
- return _snow_line == NULL ? _settings_game.game_creation.snow_line_height : _snow_line->highest_value;
+ return _snow_line == nullptr ? _settings_game.game_creation.snow_line_height : _snow_line->highest_value;
}
/**
@@ -669,7 +669,7 @@ byte HighestSnowLine()
*/
byte LowestSnowLine()
{
- return _snow_line == NULL ? _settings_game.game_creation.snow_line_height : _snow_line->lowest_value;
+ return _snow_line == nullptr ? _settings_game.game_creation.snow_line_height : _snow_line->lowest_value;
}
/**
@@ -679,7 +679,7 @@ byte LowestSnowLine()
void ClearSnowLine()
{
free(_snow_line);
- _snow_line = NULL;
+ _snow_line = nullptr;
}
/**
@@ -702,8 +702,8 @@ CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
cost.AddCost(GetWaterClass(tile) == WATER_CLASS_CANAL ? _price[PR_CLEAR_CANAL] : _price[PR_CLEAR_WATER]);
}
- Company *c = (flags & (DC_AUTO | DC_BANKRUPT)) ? NULL : Company::GetIfValid(_current_company);
- if (c != NULL && (int)GB(c->clear_limit, 16, 16) < 1) {
+ Company *c = (flags & (DC_AUTO | DC_BANKRUPT)) ? nullptr : Company::GetIfValid(_current_company);
+ if (c != nullptr && (int)GB(c->clear_limit, 16, 16) < 1) {
return_cmd_error(STR_ERROR_CLEARING_LIMIT_REACHED);
}
@@ -711,7 +711,7 @@ CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
/* If this tile was the first tile which caused object destruction, always
* pass it on to the tile_type_proc. That way multiple test runs and the exec run stay consistent. */
- if (coa != NULL && coa->first_tile != tile) {
+ if (coa != nullptr && coa->first_tile != tile) {
/* If this tile belongs to an object which was already cleared via another tile, pretend it has been
* already removed.
* However, we need to check stuff, which is not the same for all object tiles. (e.g. being on water or not) */
@@ -725,7 +725,7 @@ CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
}
if (flags & DC_EXEC) {
- if (c != NULL) c->clear_limit -= 1 << 16;
+ if (c != nullptr) c->clear_limit -= 1 << 16;
if (do_clear) DoClearSquare(tile);
}
return cost;
@@ -750,8 +750,8 @@ CommandCost CmdClearArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
CommandCost last_error = CMD_ERROR;
bool had_success = false;
- const Company *c = (flags & (DC_AUTO | DC_BANKRUPT)) ? NULL : Company::GetIfValid(_current_company);
- int limit = (c == NULL ? INT32_MAX : GB(c->clear_limit, 16, 16));
+ const Company *c = (flags & (DC_AUTO | DC_BANKRUPT)) ? nullptr : Company::GetIfValid(_current_company);
+ int limit = (c == nullptr ? INT32_MAX : GB(c->clear_limit, 16, 16));
TileIterator *iter = HasBit(p2, 0) ? (TileIterator *)new DiagonalTileIterator(tile, p1) : new OrthogonalTileIterator(tile, p1);
for (; *iter != INVALID_TILE; ++(*iter)) {
@@ -761,7 +761,7 @@ CommandCost CmdClearArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
last_error = ret;
/* We may not clear more tiles. */
- if (c != NULL && GB(c->clear_limit, 16, 16) < 1) break;
+ if (c != nullptr && GB(c->clear_limit, 16, 16) < 1) break;
continue;
}
@@ -862,7 +862,7 @@ static void GenerateTerrain(int type, uint flag)
uint32 r = Random();
const Sprite *templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + 4845, ST_MAPGEN);
- if (templ == NULL) usererror("Map generator sprites could not be loaded");
+ if (templ == nullptr) usererror("Map generator sprites could not be loaded");
uint x = r & MapMaxX();
uint y = (r >> MapLogX()) & MapMaxY();
@@ -1065,7 +1065,7 @@ static bool MakeLake(TileIndex tile, void *user_data)
MakeRiver(tile, Random());
/* Remove desert directly around the river tile. */
TileIndex t = tile;
- CircularTileSearch(&t, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, NULL);
+ CircularTileSearch(&t, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, nullptr);
return false;
}
}
@@ -1132,12 +1132,12 @@ static void River_GetNeighbours(AyStar *aystar, OpenListNode *current)
/* AyStar callback when an route has been found. */
static void River_FoundEndNode(AyStar *aystar, OpenListNode *current)
{
- for (PathNode *path = &current->path; path != NULL; path = path->parent) {
+ for (PathNode *path = &current->path; path != nullptr; path = path->parent) {
TileIndex tile = path->node.tile;
if (!IsWaterTile(tile)) {
MakeRiver(tile, Random());
/* Remove desert directly around the river tile. */
- CircularTileSearch(&tile, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, NULL);
+ CircularTileSearch(&tile, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, nullptr);
}
}
}
@@ -1249,7 +1249,7 @@ static bool FlowRiver(TileIndex spring, TileIndex begin)
end = lakeCenter;
MakeRiver(lakeCenter, Random());
/* Remove desert directly around the river tile. */
- CircularTileSearch(&lakeCenter, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, NULL);
+ CircularTileSearch(&lakeCenter, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, nullptr);
lakeCenter = end;
uint range = RandomRange(8) + 3;
CircularTileSearch(&lakeCenter, range, MakeLake, &height);
@@ -1280,7 +1280,7 @@ static void CreateRivers()
IncreaseGeneratingWorldProgress(GWP_RIVER);
for (int tries = 0; tries < 128; tries++) {
TileIndex t = RandomTile();
- if (!CircularTileSearch(&t, 8, FindSpring, NULL)) continue;
+ if (!CircularTileSearch(&t, 8, FindSpring, nullptr)) continue;
if (FlowRiver(t, t)) break;
}
}
diff --git a/src/landscape.h b/src/landscape.h
index 43d9e5f2e..1209c5c1a 100644
--- a/src/landscape.h
+++ b/src/landscape.h
@@ -36,7 +36,7 @@ byte LowestSnowLine();
void ClearSnowLine();
int GetSlopeZInCorner(Slope tileh, Corner corner);
-Slope GetFoundationSlope(TileIndex tile, int *z = NULL);
+Slope GetFoundationSlope(TileIndex tile, int *z = nullptr);
uint GetPartialPixelZ(int x, int y, Slope corners);
int GetSlopePixelZ(int x, int y);
@@ -62,12 +62,12 @@ static inline int GetSlopePixelZInCorner(Slope tileh, Corner corner)
* If a tile does not have a foundation, the function returns the same as GetTilePixelSlope.
*
* @param tile The tile of interest.
- * @param z returns the z of the foundation slope. (Can be NULL, if not needed)
+ * @param z returns the z of the foundation slope. (Can be nullptr, if not needed)
* @return The slope on top of the foundation.
*/
static inline Slope GetFoundationPixelSlope(TileIndex tile, int *z)
{
- assert(z != NULL);
+ assert(z != nullptr);
Slope s = GetFoundationSlope(tile, z);
*z *= TILE_HEIGHT;
return s;
@@ -117,7 +117,7 @@ static inline Point InverseRemapCoords(int x, int y)
return pt;
}
-Point InverseRemapCoords2(int x, int y, bool clamp_to_map = false, bool *clamped = NULL);
+Point InverseRemapCoords2(int x, int y, bool clamp_to_map = false, bool *clamped = nullptr);
uint ApplyFoundationToSlope(Foundation f, Slope *s);
/**
diff --git a/src/linkgraph/linkgraph_gui.cpp b/src/linkgraph/linkgraph_gui.cpp
index 6844092c2..ebba160bf 100644
--- a/src/linkgraph/linkgraph_gui.cpp
+++ b/src/linkgraph/linkgraph_gui.cpp
@@ -301,7 +301,7 @@ void LinkGraphOverlay::DrawStationDots(const DrawPixelInfo *dpi) const
{
for (StationSupplyList::const_iterator i(this->cached_stations.begin()); i != this->cached_stations.end(); ++i) {
const Station *st = Station::GetIfValid(i->first);
- if (st == NULL) continue;
+ if (st == nullptr) continue;
Point pt = this->GetStationMiddle(st);
if (!this->IsPointVisible(pt, dpi, 3 * this->scale)) continue;
@@ -345,7 +345,7 @@ void LinkGraphOverlay::DrawStationDots(const DrawPixelInfo *dpi) const
*/
Point LinkGraphOverlay::GetStationMiddle(const Station *st) const
{
- if (this->window->viewport != NULL) {
+ if (this->window->viewport != nullptr) {
return GetViewportStationMiddle(this->window->viewport, st);
} else {
/* assume this is a smallmap */
@@ -399,7 +399,7 @@ NWidgetBase *MakeCargoesLegendLinkGraphGUI(int *biggest_index)
{
static const uint ENTRIES_PER_ROW = CeilDiv(NUM_CARGO, 5);
NWidgetVertical *panel = new NWidgetVertical(NC_EQUALSIZE);
- NWidgetHorizontal *row = NULL;
+ NWidgetHorizontal *row = nullptr;
for (uint i = 0; i < NUM_CARGO; ++i) {
if (i % ENTRIES_PER_ROW == 0) {
if (row) panel->Add(row);
@@ -563,7 +563,7 @@ bool LinkGraphLegendWindow::OnTooltip(Point pt, int widget, TooltipCloseConditio
{
if (IsInsideMM(widget, WID_LGL_COMPANY_FIRST, WID_LGL_COMPANY_LAST + 1)) {
if (this->IsWidgetDisabled(widget)) {
- GuiShowTooltips(this, STR_LINKGRAPH_LEGEND_SELECT_COMPANIES, 0, NULL, close_cond);
+ GuiShowTooltips(this, STR_LINKGRAPH_LEGEND_SELECT_COMPANIES, 0, nullptr, close_cond);
} else {
uint64 params[2];
CompanyID cid = (CompanyID)(widget - WID_LGL_COMPANY_FIRST);
diff --git a/src/linkgraph/linkgraphjob.cpp b/src/linkgraph/linkgraphjob.cpp
index 5b8683820..cf180a3ae 100644
--- a/src/linkgraph/linkgraphjob.cpp
+++ b/src/linkgraph/linkgraphjob.cpp
@@ -102,7 +102,7 @@ LinkGraphJob::~LinkGraphJob()
/* The station can have been deleted. Remove all flows originating from it then. */
Station *st = Station::GetIfValid(from.Station());
- if (st == NULL) {
+ if (st == nullptr) {
this->EraseFlows(node_id);
continue;
}
@@ -122,7 +122,7 @@ LinkGraphJob::~LinkGraphJob()
if (from[it->first].Flow() == 0) continue;
StationID to = (*this)[it->first].Station();
Station *st2 = Station::GetIfValid(to);
- if (st2 == NULL || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
+ if (st2 == nullptr || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
st2->goods[this->Cargo()].node != it->first ||
(*lg)[node_id][it->first].LastUpdate() == INVALID_DATE) {
/* Edge has been removed. Delete flows. */
@@ -240,7 +240,7 @@ void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
*/
uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
{
- if (this->parent != NULL) {
+ if (this->parent != nullptr) {
LinkGraphJob::Edge edge = job[this->parent->node][this->node];
if (max_saturation != UINT_MAX) {
uint usable_cap = edge.Capacity() * max_saturation / 100;
@@ -270,6 +270,6 @@ Path::Path(NodeID n, bool source) :
capacity(source ? UINT_MAX : 0),
free_capacity(source ? INT_MAX : INT_MIN),
flow(0), node(n), origin(source ? n : INVALID_NODE),
- num_children(0), parent(NULL)
+ num_children(0), parent(nullptr)
{}
diff --git a/src/linkgraph/linkgraphjob.h b/src/linkgraph/linkgraphjob.h
index e52d2412d..a20a2025c 100644
--- a/src/linkgraph/linkgraphjob.h
+++ b/src/linkgraph/linkgraphjob.h
@@ -403,9 +403,9 @@ public:
*/
inline void Detach()
{
- if (this->parent != NULL) {
+ if (this->parent != nullptr) {
this->parent->num_children--;
- this->parent = NULL;
+ this->parent = nullptr;
}
}
diff --git a/src/linkgraph/mcf.cpp b/src/linkgraph/mcf.cpp
index 544584ef6..c64674237 100644
--- a/src/linkgraph/mcf.cpp
+++ b/src/linkgraph/mcf.cpp
@@ -104,7 +104,7 @@ public:
* @param job Job to iterate on.
*/
GraphEdgeIterator(LinkGraphJob &job) : job(job),
- i(NULL, NULL, INVALID_NODE), end(NULL, NULL, INVALID_NODE)
+ i(nullptr, nullptr, INVALID_NODE), end(nullptr, nullptr, INVALID_NODE)
{}
/**
@@ -262,7 +262,7 @@ void MultiCommodityFlow::Dijkstra(NodeID source_node, PathVector &paths)
Tedge_iterator iter(this->job);
uint size = this->job.Size();
AnnoSet annos;
- paths.resize(size, NULL);
+ paths.resize(size, nullptr);
for (NodeID node = 0; node < size; ++node) {
Tannotation *anno = new Tannotation(node, node == source_node);
anno->UpdateAnnotation();
@@ -305,16 +305,16 @@ void MultiCommodityFlow::Dijkstra(NodeID source_node, PathVector &paths)
void MultiCommodityFlow::CleanupPaths(NodeID source_id, PathVector &paths)
{
Path *source = paths[source_id];
- paths[source_id] = NULL;
+ paths[source_id] = nullptr;
for (PathVector::iterator i = paths.begin(); i != paths.end(); ++i) {
Path *path = *i;
- if (path == NULL) continue;
+ if (path == nullptr) continue;
if (path->GetParent() == source) path->Detach();
- while (path != source && path != NULL && path->GetFlow() == 0) {
+ while (path != source && path != nullptr && path->GetFlow() == 0) {
Path *parent = path->GetParent();
path->Detach();
if (path->GetNumChildren() == 0) {
- paths[path->GetNode()] = NULL;
+ paths[path->GetNode()] = nullptr;
delete path;
}
path = parent;
@@ -404,7 +404,7 @@ bool MCF1stPass::EliminateCycles(PathVector &path, NodeID origin_id, NodeID next
/* this node has already been searched */
if (at_next_pos == Path::invalid_path) return false;
- if (at_next_pos == NULL) {
+ if (at_next_pos == nullptr) {
/* Summarize paths; add up the paths with the same source and next hop
* in one path each. */
PathList &paths = this->job[next_id].Paths();
@@ -450,7 +450,7 @@ bool MCF1stPass::EliminateCycles(PathVector &path, NodeID origin_id, NodeID next
* could be found in this branch, thus it has to be searched again next
* time we spot it.
*/
- path[next_id] = found ? NULL : Path::invalid_path;
+ path[next_id] = found ? nullptr : Path::invalid_path;
return found;
}
@@ -474,11 +474,11 @@ bool MCF1stPass::EliminateCycles()
{
bool cycles_found = false;
uint size = this->job.Size();
- PathVector path(size, NULL);
+ PathVector path(size, nullptr);
for (NodeID node = 0; node < size; ++node) {
/* Starting at each node in the graph find all cycles involving this
* node. */
- std::fill(path.begin(), path.end(), (Path *)NULL);
+ std::fill(path.begin(), path.end(), (Path *)nullptr);
cycles_found |= this->EliminateCycles(path, node, node);
}
return cycles_found;
@@ -505,7 +505,7 @@ MCF1stPass::MCF1stPass(LinkGraphJob &job) : MultiCommodityFlow(job)
Edge edge = job[source][dest];
if (edge.UnsatisfiedDemand() > 0) {
Path *path = paths[dest];
- assert(path != NULL);
+ assert(path != nullptr);
/* Generally only allow paths that don't exceed the
* available capacity. But if no demand has been assigned
* yet, make an exception and allow any valid path *once*. */
diff --git a/src/linkgraph/refresh.cpp b/src/linkgraph/refresh.cpp
index 501f06352..b749d2718 100644
--- a/src/linkgraph/refresh.cpp
+++ b/src/linkgraph/refresh.cpp
@@ -28,11 +28,11 @@
/* static */ void LinkRefresher::Run(Vehicle *v, bool allow_merge, bool is_full_loading)
{
/* If there are no orders we can't predict anything.*/
- if (v->orders.list == NULL) return;
+ if (v->orders.list == nullptr) return;
/* Make sure the first order is a useful order. */
const Order *first = v->orders.list->GetNextDecisionNode(v->GetOrder(v->cur_implicit_order_index), 0);
- if (first == NULL) return;
+ if (first == nullptr) return;
HopSet seen_hops;
LinkRefresher refresher(v, &seen_hops, allow_merge, is_full_loading);
@@ -75,7 +75,7 @@ LinkRefresher::LinkRefresher(Vehicle *vehicle, HopSet *seen_hops, bool allow_mer
memset(this->capacities, 0, sizeof(this->capacities));
/* Assemble list of capacities and set last loading stations to 0. */
- for (Vehicle *v = this->vehicle; v != NULL; v = v->Next()) {
+ for (Vehicle *v = this->vehicle; v != nullptr; v = v->Next()) {
this->refit_capacities.push_back(RefitDesc(v->cargo_type, v->cargo_cap, v->refit_cap));
if (v->refit_cap > 0) {
assert(v->cargo_type < NUM_CARGO);
@@ -94,7 +94,7 @@ bool LinkRefresher::HandleRefit(CargoID refit_cargo)
this->cargo = refit_cargo;
RefitList::iterator refit_it = this->refit_capacities.begin();
bool any_refit = false;
- for (Vehicle *v = this->vehicle; v != NULL; v = v->Next()) {
+ for (Vehicle *v = this->vehicle; v != nullptr; v = v->Next()) {
const Engine *e = Engine::Get(v->engine_type);
if (!HasBit(e->info.refit_mask, this->cargo)) {
++refit_it;
@@ -164,10 +164,10 @@ void LinkRefresher::ResetRefit()
*/
const Order *LinkRefresher::PredictNextOrder(const Order *cur, const Order *next, uint8 flags, uint num_hops)
{
- /* next is good if it's either NULL (then the caller will stop the
+ /* next is good if it's either nullptr (then the caller will stop the
* evaluation) or if it's not conditional and the caller allows it to be
* chosen (by setting USE_NEXT). */
- while (next != NULL && (!HasBit(flags, USE_NEXT) || next->IsType(OT_CONDITIONAL))) {
+ while (next != nullptr && (!HasBit(flags, USE_NEXT) || next->IsType(OT_CONDITIONAL))) {
/* After the first step any further non-conditional order is good,
* regardless of previous USE_NEXT settings. The case of cur and next or
@@ -177,7 +177,7 @@ const Order *LinkRefresher::PredictNextOrder(const Order *cur, const Order *next
if (next->IsType(OT_CONDITIONAL)) {
const Order *skip_to = this->vehicle->orders.list->GetNextDecisionNode(
this->vehicle->orders.list->GetOrderAt(next->GetConditionSkipToOrder()), num_hops);
- if (skip_to != NULL && num_hops < this->vehicle->orders.list->GetNumOrders()) {
+ if (skip_to != nullptr && num_hops < this->vehicle->orders.list->GetNumOrders()) {
/* Make copies of capacity tracking lists. There is potential
* for optimization here: If the vehicle never refits we don't
* need to copy anything. Also, if we've seen the branched link
@@ -204,7 +204,7 @@ void LinkRefresher::RefreshStats(const Order *cur, const Order *next)
{
StationID next_station = next->GetDestination();
Station *st = Station::GetIfValid(cur->GetDestination());
- if (st != NULL && next_station != INVALID_STATION && next_station != st->index) {
+ if (st != nullptr && next_station != INVALID_STATION && next_station != st->index) {
for (CargoID c = 0; c < NUM_CARGO; c++) {
/* Refresh the link and give it a minimum capacity. */
@@ -226,7 +226,7 @@ void LinkRefresher::RefreshStats(const Order *cur, const Order *next)
* loading. Don't do that if the vehicle has been waiting for longer than the entire
* order list is supposed to take, though. If that is the case the total duration is
* probably far off and we'd greatly overestimate the capacity by increasing.*/
- if (this->is_full_loading && this->vehicle->orders.list != NULL &&
+ if (this->is_full_loading && this->vehicle->orders.list != nullptr &&
st->index == vehicle->last_station_visited &&
this->vehicle->orders.list->GetTotalDuration() >
(Ticks)this->vehicle->current_order_time) {
@@ -260,7 +260,7 @@ void LinkRefresher::RefreshStats(const Order *cur, const Order *next)
*/
void LinkRefresher::RefreshLinks(const Order *cur, const Order *next, uint8 flags, uint num_hops)
{
- while (next != NULL) {
+ while (next != nullptr) {
if ((next->IsType(OT_GOTO_DEPOT) || next->IsType(OT_GOTO_STATION)) && next->IsRefit()) {
SetBit(flags, WAS_REFIT);
@@ -288,7 +288,7 @@ void LinkRefresher::RefreshLinks(const Order *cur, const Order *next, uint8 flag
}
next = this->PredictNextOrder(cur, next, flags, num_hops);
- if (next == NULL) break;
+ if (next == nullptr) break;
Hop hop(cur->index, next->index, this->cargo);
if (this->seen_hops->find(hop) != this->seen_hops->end()) {
break;
diff --git a/src/main_gui.cpp b/src/main_gui.cpp
index 808484b0e..d4559c216 100644
--- a/src/main_gui.cpp
+++ b/src/main_gui.cpp
@@ -72,7 +72,7 @@ void HandleOnEditText(const char *str)
switch (_rename_what) {
case 3: { // Give money, you can only give money in excess of loan
const Company *c = Company::GetIfValid(_local_company);
- if (c == NULL) break;
+ if (c == nullptr) break;
Money money = min(c->money - c->current_loan, (Money)(atoi(str) / _currency->rate));
uint32 money_c = Clamp(ClampToI32(money), 0, 20000000); // Clamp between 20 million and 0
@@ -124,7 +124,7 @@ void ShowNetworkGiveMoneyWindow(CompanyID company)
{
_rename_id = company;
_rename_what = 3;
- ShowQueryString(STR_EMPTY, STR_NETWORK_GIVE_MONEY_CAPTION, 30, NULL, CS_NUMERAL, QSF_NONE);
+ ShowQueryString(STR_EMPTY, STR_NETWORK_GIVE_MONEY_CAPTION, 30, nullptr, CS_NUMERAL, QSF_NONE);
}
@@ -139,7 +139,7 @@ bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
{
ViewPort *vp;
- assert(w != NULL);
+ assert(w != nullptr);
vp = w->viewport;
switch (how) {
@@ -173,7 +173,7 @@ bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
w->viewport->follow_vehicle = INVALID_VEHICLE;
break;
}
- if (vp != NULL) { // the vp can be null when how == ZOOM_NONE
+ if (vp != nullptr) { // the vp can be null when how == ZOOM_NONE
vp->virtual_left = w->viewport->scrollpos_x;
vp->virtual_top = w->viewport->scrollpos_y;
}
@@ -184,7 +184,7 @@ bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
void ZoomInOrOutToCursorWindow(bool in, Window *w)
{
- assert(w != NULL);
+ assert(w != nullptr);
if (_game_mode != GM_MENU) {
ViewPort *vp = w->viewport;
@@ -394,7 +394,7 @@ struct MainWindow : Window
case GHK_CHAT: // smart chat; send to team if any, otherwise to all
if (_networking) {
const NetworkClientInfo *cio = NetworkClientInfo::GetByClientID(_network_own_client_id);
- if (cio == NULL) break;
+ if (cio == nullptr) break;
ShowNetworkChatQueryWindow(NetworkClientPreferTeamChat(cio) ? DESTTYPE_TEAM : DESTTYPE_BROADCAST, cio->client_playas);
}
@@ -407,7 +407,7 @@ struct MainWindow : Window
case GHK_CHAT_COMPANY: // send text to all team mates
if (_networking) {
const NetworkClientInfo *cio = NetworkClientInfo::GetByClientID(_network_own_client_id);
- if (cio == NULL) break;
+ if (cio == nullptr) break;
ShowNetworkChatQueryWindow(DESTTYPE_TEAM, cio->client_playas);
}
@@ -442,7 +442,7 @@ struct MainWindow : Window
void OnResize() override
{
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_M_VIEWPORT);
nvp->UpdateViewportCoordinates(this);
this->refresh.SetInterval(LINKGRAPH_DELAY);
@@ -517,7 +517,7 @@ static Hotkey global_hotkeys[] = {
HotkeyList MainWindow::hotkeys("global", global_hotkeys);
static WindowDesc _main_window_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_MAIN_WINDOW, WC_NONE,
0,
_nested_main_window_widgets, lengthof(_nested_main_window_widgets),
diff --git a/src/map.cpp b/src/map.cpp
index 85590c3e8..53e26ed73 100644
--- a/src/map.cpp
+++ b/src/map.cpp
@@ -29,8 +29,8 @@ uint _map_size_y; ///< Size of the map along the Y
uint _map_size; ///< The number of tiles on the map
uint _map_tile_mask; ///< _map_size - 1 (to mask the mapsize)
-Tile *_m = NULL; ///< Tiles of the map
-TileExtended *_me = NULL; ///< Extended Tiles of the map
+Tile *_m = nullptr; ///< Tiles of the map
+TileExtended *_me = nullptr; ///< Extended Tiles of the map
/**
@@ -254,12 +254,12 @@ uint DistanceFromEdgeDir(TileIndex tile, DiagDirection dir)
* @param proc: callback testing function pointer.
* @param user_data to be passed to the callback function. Depends on the implementation
* @return result of the search
- * @pre proc != NULL
+ * @pre proc != nullptr
* @pre size > 0
*/
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
{
- assert(proc != NULL);
+ assert(proc != nullptr);
assert(size > 0);
if (size % 2 == 1) {
@@ -292,12 +292,12 @@ bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, v
* @param proc callback testing function pointer.
* @param user_data to be passed to the callback function. Depends on the implementation
* @return result of the search
- * @pre proc != NULL
+ * @pre proc != nullptr
* @pre radius > 0
*/
bool CircularTileSearch(TileIndex *tile, uint radius, uint w, uint h, TestTileOnSearchProc proc, void *user_data)
{
- assert(proc != NULL);
+ assert(proc != nullptr);
assert(radius > 0);
uint x = TileX(*tile) + w + 1;
diff --git a/src/misc/binaryheap.hpp b/src/misc/binaryheap.hpp
index 5bd2b794a..11e419711 100644
--- a/src/misc/binaryheap.hpp
+++ b/src/misc/binaryheap.hpp
@@ -72,7 +72,7 @@ public:
{
this->Clear();
free(this->data);
- this->data = NULL;
+ this->data = nullptr;
}
protected:
diff --git a/src/misc/blob.hpp b/src/misc/blob.hpp
index b1a5b667d..e725ccd27 100644
--- a/src/misc/blob.hpp
+++ b/src/misc/blob.hpp
@@ -86,9 +86,9 @@ public:
/** move constructor - take ownership of blob data */
inline ByteBlob(BlobHeader * const & src)
{
- assert(src != NULL);
+ assert(src != nullptr);
header = src;
- *const_cast<BlobHeader**>(&src) = NULL;
+ *const_cast<BlobHeader**>(&src) = nullptr;
}
/** destructor */
@@ -221,7 +221,7 @@ public:
/** append new bytes at the end of existing data bytes - reallocates if necessary */
inline void AppendRaw(const void *p, size_t num_bytes)
{
- assert(p != NULL);
+ assert(p != nullptr);
if (num_bytes > 0) {
memcpy(Append(num_bytes), p, num_bytes);
}
@@ -317,8 +317,8 @@ public:
OnTransfer(const OnTransfer& src) : header(src.header)
{
- assert(src.header != NULL);
- *const_cast<typename base::BlobHeader**>(&src.header) = NULL;
+ assert(src.header != nullptr);
+ *const_cast<typename base::BlobHeader**>(&src.header) = nullptr;
}
OnTransfer(CBlobT& src) : header(src.header)
@@ -328,7 +328,7 @@ public:
~OnTransfer()
{
- assert(header == NULL);
+ assert(header == nullptr);
}
};
diff --git a/src/misc/countedptr.hpp b/src/misc/countedptr.hpp
index e7b28a626..83d0e036d 100644
--- a/src/misc/countedptr.hpp
+++ b/src/misc/countedptr.hpp
@@ -34,8 +34,8 @@ protected:
Tcls *m_pT;
public:
- /** default (NULL) construct or construct from a raw pointer */
- inline CCountedPtr(Tcls *pObj = NULL) : m_pT(pObj)
+ /** default (nullptr) construct or construct from a raw pointer */
+ inline CCountedPtr(Tcls *pObj = nullptr) : m_pT(pObj)
{
AddRef();
}
@@ -56,16 +56,16 @@ protected:
/** add one ref to the underlaying object */
inline void AddRef()
{
- if (m_pT != NULL) m_pT->AddRef();
+ if (m_pT != nullptr) m_pT->AddRef();
}
public:
/** release smart pointer (and decrement ref count) if not null */
inline void Release()
{
- if (m_pT != NULL) {
+ if (m_pT != nullptr) {
Tcls *pT = m_pT;
- m_pT = NULL;
+ m_pT = nullptr;
pT->Release();
}
}
@@ -73,21 +73,21 @@ public:
/** dereference of smart pointer - const way */
inline const Tcls *operator->() const
{
- assert(m_pT != NULL);
+ assert(m_pT != nullptr);
return m_pT;
}
/** dereference of smart pointer - non const way */
inline Tcls *operator->()
{
- assert(m_pT != NULL);
+ assert(m_pT != nullptr);
return m_pT;
}
/** raw pointer casting operator - const way */
inline operator const Tcls*() const
{
- assert(m_pT == NULL);
+ assert(m_pT == nullptr);
return m_pT;
}
@@ -100,7 +100,7 @@ public:
/** operator & to support output arguments */
inline Tcls** operator&()
{
- assert(m_pT == NULL);
+ assert(m_pT == nullptr);
return &m_pT;
}
@@ -121,16 +121,16 @@ public:
/** assignment operator helper */
inline void Assign(Tcls *pT);
- /** one way how to test for NULL value */
+ /** one way how to test for nullptr value */
inline bool IsNull() const
{
- return m_pT == NULL;
+ return m_pT == nullptr;
}
- /** another way how to test for NULL value */
+ /** another way how to test for nullptr value */
//inline bool operator == (const CCountedPtr &sp) const {return m_pT == sp.m_pT;}
- /** yet another way how to test for NULL value */
+ /** yet another way how to test for nullptr value */
//inline bool operator != (const CCountedPtr &sp) const {return m_pT != sp.m_pT;}
/** assign pointer w/o incrementing ref count */
@@ -144,7 +144,7 @@ public:
inline Tcls *Detach()
{
Tcls *pT = m_pT;
- m_pT = NULL;
+ m_pT = nullptr;
return pT;
}
};
@@ -154,10 +154,10 @@ inline void CCountedPtr<Tcls_>::Assign(Tcls *pT)
{
/* if they are the same, we do nothing */
if (pT != m_pT) {
- if (pT != NULL) pT->AddRef(); // AddRef new pointer if any
+ if (pT != nullptr) pT->AddRef(); // AddRef new pointer if any
Tcls *pTold = m_pT; // save original ptr
m_pT = pT; // update m_pT to new value
- if (pTold != NULL) pTold->Release(); // release old ptr if any
+ if (pTold != nullptr) pTold->Release(); // release old ptr if any
}
}
diff --git a/src/misc/dbg_helpers.h b/src/misc/dbg_helpers.h
index acc1437d0..2e2a1a7e9 100644
--- a/src/misc/dbg_helpers.h
+++ b/src/misc/dbg_helpers.h
@@ -155,8 +155,8 @@ struct DumpTarget {
{
static size_t type_id = ++LastTypeId();
- if (s == NULL) {
- /* No need to dump NULL struct. */
+ if (s == nullptr) {
+ /* No need to dump nullptr struct. */
WriteLine("%s = <null>", name);
return;
}
diff --git a/src/misc/fixedsizearray.hpp b/src/misc/fixedsizearray.hpp
index c694ff7a1..ec1d58bf3 100644
--- a/src/misc/fixedsizearray.hpp
+++ b/src/misc/fixedsizearray.hpp
@@ -94,7 +94,7 @@ public:
Clear();
/* free the memory block occupied by items */
free(((byte*)data) - HeaderSize);
- data = NULL;
+ data = nullptr;
}
/** Clear (destroy) all items */
diff --git a/src/misc/getoptdata.cpp b/src/misc/getoptdata.cpp
index 7859594dd..d80898f08 100644
--- a/src/misc/getoptdata.cpp
+++ b/src/misc/getoptdata.cpp
@@ -26,7 +26,7 @@ int GetOptData::GetOpt()
const OptionData *odata;
char *s = this->cont;
- if (s == NULL) {
+ if (s == nullptr) {
if (this->numleft == 0) return -1; // No arguments left -> finished.
s = this->argv[0];
@@ -37,8 +37,8 @@ int GetOptData::GetOpt()
/* Is it a long option? */
for (odata = this->options; odata->flags != ODF_END; odata++) {
- if (odata->longname != NULL && !strcmp(odata->longname, s)) { // Long options always use the entire argument.
- this->cont = NULL;
+ if (odata->longname != nullptr && !strcmp(odata->longname, s)) { // Long options always use the entire argument.
+ this->cont = nullptr;
goto set_optval;
}
}
@@ -49,19 +49,19 @@ int GetOptData::GetOpt()
/* Is it a short option? */
for (odata = this->options; odata->flags != ODF_END; odata++) {
if (odata->shortname != '\0' && *s == odata->shortname) {
- this->cont = (s[1] != '\0') ? s + 1 : NULL;
+ this->cont = (s[1] != '\0') ? s + 1 : nullptr;
set_optval: // Handle option value of *odata .
- this->opt = NULL;
+ this->opt = nullptr;
switch (odata->flags) {
case ODF_NO_VALUE:
return odata->id;
case ODF_HAS_VALUE:
case ODF_OPTIONAL_VALUE:
- if (this->cont != NULL) { // Remainder of the argument is the option value.
+ if (this->cont != nullptr) { // Remainder of the argument is the option value.
this->opt = this->cont;
- this->cont = NULL;
+ this->cont = nullptr;
return odata->id;
}
/* No more arguments, either return an error or a value-less option. */
diff --git a/src/misc/getoptdata.h b/src/misc/getoptdata.h
index 4ce916aa1..4777c85b5 100644
--- a/src/misc/getoptdata.h
+++ b/src/misc/getoptdata.h
@@ -25,12 +25,12 @@ struct OptionData {
byte id; ///< Unique identification of this option data, often the same as #shortname.
char shortname; ///< Short option letter if available, else use \c '\0'.
uint16 flags; ///< Option data flags. @see OptionDataFlags
- const char *longname; ///< Long option name including '-'/'--' prefix, use \c NULL if not available.
+ const char *longname; ///< Long option name including '-'/'--' prefix, use \c nullptr if not available.
};
/** Data storage for parsing command line options. */
struct GetOptData {
- char *opt; ///< Option value, if available (else \c NULL).
+ char *opt; ///< Option value, if available (else \c nullptr).
int numleft; ///< Number of arguments left in #argv.
char **argv; ///< Remaining command line arguments.
const OptionData *options; ///< Command line option descriptions.
@@ -43,11 +43,11 @@ struct GetOptData {
* @param options Command line option descriptions.
*/
GetOptData(int argc, char **argv, const OptionData *options) :
- opt(NULL),
+ opt(nullptr),
numleft(argc),
argv(argv),
options(options),
- cont(NULL)
+ cont(nullptr)
{
}
@@ -58,7 +58,7 @@ struct GetOptData {
* General macro for creating an option.
* @param id Identification of the option.
* @param shortname Short option name. Use \c '\0' if not used.
- * @param longname Long option name including leading '-' or '--'. Use \c NULL if not used.
+ * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
* @param flags Flags of the option.
*/
#define GETOPT_GENERAL(id, shortname, longname, flags) { id, shortname, flags, longname }
@@ -66,21 +66,21 @@ struct GetOptData {
/**
* Short option without value.
* @param shortname Short option name. Use \c '\0' if not used.
- * @param longname Long option name including leading '-' or '--'. Use \c NULL if not used.
+ * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
*/
#define GETOPT_NOVAL(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_NO_VALUE)
/**
* Short option with value.
* @param shortname Short option name. Use \c '\0' if not used.
- * @param longname Long option name including leading '-' or '--'. Use \c NULL if not used.
+ * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
*/
#define GETOPT_VALUE(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_HAS_VALUE)
/**
* Short option with optional value.
* @param shortname Short option name. Use \c '\0' if not used.
- * @param longname Long option name including leading '-' or '--'. Use \c NULL if not used.
+ * @param longname Long option name including leading '-' or '--'. Use \c nullptr if not used.
* @note Options with optional values are hopelessly ambiguous, eg "-opt -value", avoid them.
*/
#define GETOPT_OPTVAL(shortname, longname) GETOPT_GENERAL(shortname, shortname, longname, ODF_OPTIONAL_VALUE)
@@ -90,23 +90,23 @@ struct GetOptData {
* Short option without value.
* @param shortname Short option name. Use \c '\0' if not used.
*/
-#define GETOPT_SHORT_NOVAL(shortname) GETOPT_NOVAL(shortname, NULL)
+#define GETOPT_SHORT_NOVAL(shortname) GETOPT_NOVAL(shortname, nullptr)
/**
* Short option with value.
* @param shortname Short option name. Use \c '\0' if not used.
*/
-#define GETOPT_SHORT_VALUE(shortname) GETOPT_VALUE(shortname, NULL)
+#define GETOPT_SHORT_VALUE(shortname) GETOPT_VALUE(shortname, nullptr)
/**
* Short option with optional value.
* @param shortname Short option name. Use \c '\0' if not used.
* @note Options with optional values are hopelessly ambiguous, eg "-opt -value", avoid them.
*/
-#define GETOPT_SHORT_OPTVAL(shortname) GETOPT_OPTVAL(shortname, NULL)
+#define GETOPT_SHORT_OPTVAL(shortname) GETOPT_OPTVAL(shortname, nullptr)
/** Option terminator. */
-#define GETOPT_END() { '\0', '\0', ODF_END, NULL}
+#define GETOPT_END() { '\0', '\0', ODF_END, nullptr}
#endif /* GETOPTDATA_H */
diff --git a/src/misc/hashtable.hpp b/src/misc/hashtable.hpp
index 1078f1861..49f321bff 100644
--- a/src/misc/hashtable.hpp
+++ b/src/misc/hashtable.hpp
@@ -21,42 +21,42 @@ struct CHashTableSlotT
Titem_ *m_pFirst;
- inline CHashTableSlotT() : m_pFirst(NULL) {}
+ inline CHashTableSlotT() : m_pFirst(nullptr) {}
/** hash table slot helper - clears the slot by simple forgetting its items */
inline void Clear()
{
- m_pFirst = NULL;
+ m_pFirst = nullptr;
}
/** hash table slot helper - linear search for item with given key through the given blob - const version */
inline const Titem_ *Find(const Key &key) const
{
- for (const Titem_ *pItem = m_pFirst; pItem != NULL; pItem = pItem->GetHashNext()) {
+ for (const Titem_ *pItem = m_pFirst; pItem != nullptr; pItem = pItem->GetHashNext()) {
if (pItem->GetKey() == key) {
/* we have found the item, return it */
return pItem;
}
}
- return NULL;
+ return nullptr;
}
/** hash table slot helper - linear search for item with given key through the given blob - non-const version */
inline Titem_ *Find(const Key &key)
{
- for (Titem_ *pItem = m_pFirst; pItem != NULL; pItem = pItem->GetHashNext()) {
+ for (Titem_ *pItem = m_pFirst; pItem != nullptr; pItem = pItem->GetHashNext()) {
if (pItem->GetKey() == key) {
/* we have found the item, return it */
return pItem;
}
}
- return NULL;
+ return nullptr;
}
/** hash table slot helper - add new item to the slot */
inline void Attach(Titem_ &new_item)
{
- assert(new_item.GetHashNext() == NULL);
+ assert(new_item.GetHashNext() == nullptr);
new_item.SetHashNext(m_pFirst);
m_pFirst = &new_item;
}
@@ -66,12 +66,12 @@ struct CHashTableSlotT
{
if (m_pFirst == &item_to_remove) {
m_pFirst = item_to_remove.GetHashNext();
- item_to_remove.SetHashNext(NULL);
+ item_to_remove.SetHashNext(nullptr);
return true;
}
Titem_ *pItem = m_pFirst;
for (;;) {
- if (pItem == NULL) {
+ if (pItem == nullptr) {
return false;
}
Titem_ *pNextItem = pItem->GetHashNext();
@@ -79,7 +79,7 @@ struct CHashTableSlotT
pItem = pNextItem;
}
pItem->SetHashNext(item_to_remove.GetHashNext());
- item_to_remove.SetHashNext(NULL);
+ item_to_remove.SetHashNext(nullptr);
return true;
}
@@ -87,27 +87,27 @@ struct CHashTableSlotT
inline Titem_ *Detach(const Key &key)
{
/* do we have any items? */
- if (m_pFirst == NULL) {
- return NULL;
+ if (m_pFirst == nullptr) {
+ return nullptr;
}
/* is it our first item? */
if (m_pFirst->GetKey() == key) {
Titem_ &ret_item = *m_pFirst;
m_pFirst = m_pFirst->GetHashNext();
- ret_item.SetHashNext(NULL);
+ ret_item.SetHashNext(nullptr);
return &ret_item;
}
/* find it in the following items */
Titem_ *pPrev = m_pFirst;
- for (Titem_ *pItem = m_pFirst->GetHashNext(); pItem != NULL; pPrev = pItem, pItem = pItem->GetHashNext()) {
+ for (Titem_ *pItem = m_pFirst->GetHashNext(); pItem != nullptr; pPrev = pItem, pItem = pItem->GetHashNext()) {
if (pItem->GetKey() == key) {
/* we have found the item, unlink and return it */
pPrev->SetHashNext(pItem->GetHashNext());
- pItem->SetHashNext(NULL);
+ pItem->SetHashNext(nullptr);
return pItem;
}
}
- return NULL;
+ return nullptr;
}
};
@@ -211,7 +211,7 @@ public:
int hash = CalcHash(key);
Slot &slot = m_slots[hash];
Titem_ *item = slot.Detach(key);
- if (item != NULL) {
+ if (item != nullptr) {
m_num_items--;
}
return item;
@@ -221,7 +221,7 @@ public:
Titem_& Pop(const Tkey &key)
{
Titem_ *item = TryPop(key);
- assert(item != NULL);
+ assert(item != nullptr);
return *item;
}
@@ -250,7 +250,7 @@ public:
{
int hash = CalcHash(new_item);
Slot &slot = m_slots[hash];
- assert(slot.Find(new_item.GetKey()) == NULL);
+ assert(slot.Find(new_item.GetKey()) == nullptr);
slot.Attach(new_item);
m_num_items++;
}
diff --git a/src/misc_cmd.cpp b/src/misc_cmd.cpp
index 09fbc78c6..b78ec948b 100644
--- a/src/misc_cmd.cpp
+++ b/src/misc_cmd.cpp
@@ -166,7 +166,7 @@ CommandCost CmdPause(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2,
ShowQuery(
STR_NEWGRF_UNPAUSE_WARNING_TITLE,
STR_NEWGRF_UNPAUSE_WARNING,
- NULL,
+ nullptr,
AskUnsafeUnpauseCallback
);
} else {
diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp
index 4aeb81736..4c7557c36 100644
--- a/src/misc_gui.cpp
+++ b/src/misc_gui.cpp
@@ -168,10 +168,10 @@ public:
td.rail_speed = 0;
td.road_speed = 0;
- td.grf = NULL;
+ td.grf = nullptr;
CargoArray acceptance;
- AddAcceptedCargo(tile, acceptance, NULL);
+ AddAcceptedCargo(tile, acceptance, nullptr);
GetTileDesc(tile, &td);
uint line_nr = 0;
@@ -194,7 +194,7 @@ public:
/* Cost to clear/revenue when cleared */
StringID str = STR_LAND_AREA_INFORMATION_COST_TO_CLEAR_N_A;
Company *c = Company::GetIfValid(_local_company);
- if (c != NULL) {
+ if (c != nullptr) {
assert(_current_company == _local_company);
CommandCost costclear = DoCommand(tile, 0, 0, DC_QUERY_COST, CMD_LANDSCAPE_CLEAR);
if (costclear.Succeeded()) {
@@ -223,7 +223,7 @@ public:
/* Local authority */
SetDParam(0, STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE);
- if (t != NULL) {
+ if (t != nullptr) {
SetDParam(0, STR_TOWN_NAME);
SetDParam(1, t->index);
}
@@ -294,7 +294,7 @@ public:
}
/* NewGRF name */
- if (td.grf != NULL) {
+ if (td.grf != nullptr) {
SetDParamStr(0, td.grf);
GetString(this->landinfo_data[line_nr], STR_LAND_AREA_INFORMATION_NEWGRF_NAME, lastof(this->landinfo_data[line_nr]));
line_nr++;
@@ -382,7 +382,7 @@ static const NWidgetPart _nested_about_widgets[] = {
};
static WindowDesc _about_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_GAME_OPTIONS, WC_NONE,
0,
_nested_about_widgets, lengthof(_nested_about_widgets)
@@ -638,7 +638,7 @@ static const NWidgetPart _nested_tooltips_widgets[] = {
};
static WindowDesc _tool_tips_desc(
- WDP_MANUAL, NULL, 0, 0, // Coordinates and sizes are not used,
+ WDP_MANUAL, nullptr, 0, 0, // Coordinates and sizes are not used,
WC_TOOLTIPS, WC_NONE,
WDF_NO_FOCUS,
_nested_tooltips_widgets, lengthof(_nested_tooltips_widgets)
@@ -880,7 +880,7 @@ Rect QueryString::GetBoundingRect(const Window *w, int wid, const char *from, co
* @param w Window the edit box is in.
* @param wid Widget index.
* @param pt Position to test.
- * @return Pointer to the character at the position or NULL if no character is at the position.
+ * @return Pointer to the character at the position or nullptr if no character is at the position.
*/
const char *QueryString::GetCharAtPosition(const Window *w, int wid, const Point &pt) const
{
@@ -898,7 +898,7 @@ const char *QueryString::GetCharAtPosition(const Window *w, int wid, const Point
int top = wi->pos_y + WD_FRAMERECT_TOP;
int bottom = wi->pos_y + wi->current_y - 1 - WD_FRAMERECT_BOTTOM;
- if (!IsInsideMM(pt.y, top, bottom)) return NULL;
+ if (!IsInsideMM(pt.y, top, bottom)) return nullptr;
/* Clamp caret position to be inside our current width. */
const Textbuf *tb = &this->text;
@@ -990,10 +990,10 @@ struct QueryStringWindow : public Window
void OnOk()
{
- if (this->editbox.orig == NULL || strcmp(this->editbox.text.buf, this->editbox.orig) != 0) {
- /* If the parent is NULL, the editbox is handled by general function
+ if (this->editbox.orig == nullptr || strcmp(this->editbox.text.buf, this->editbox.orig) != 0) {
+ /* If the parent is nullptr, the editbox is handled by general function
* HandleOnEditText */
- if (this->parent != NULL) {
+ if (this->parent != nullptr) {
this->parent->OnQueryTextFinished(this->editbox.text.buf);
} else {
HandleOnEditText(this->editbox.text.buf);
@@ -1021,10 +1021,10 @@ struct QueryStringWindow : public Window
~QueryStringWindow()
{
- if (!this->editbox.handled && this->parent != NULL) {
+ if (!this->editbox.handled && this->parent != nullptr) {
Window *parent = this->parent;
- this->parent = NULL; // so parent doesn't try to delete us again
- parent->OnQueryTextFinished(NULL);
+ this->parent = nullptr; // so parent doesn't try to delete us again
+ parent->OnQueryTextFinished(nullptr);
}
}
};
@@ -1057,7 +1057,7 @@ static WindowDesc _query_string_desc(
* @param caption StringID of text shown in caption of querywindow
* @param maxsize maximum size in bytes or characters (including terminating '\0') depending on flags
* @param parent pointer to a Window that will handle the events (ok/cancel) of this
- * window. If NULL, results are handled by global function HandleOnEditText
+ * window. If nullptr, results are handled by global function HandleOnEditText
* @param afilter filters out unwanted character input
* @param flags various flags, @see QueryStringFlags
*/
@@ -1094,7 +1094,7 @@ struct QueryWindow : public Window {
~QueryWindow()
{
- if (this->proc != NULL) this->proc(this->parent, false);
+ if (this->proc != nullptr) this->proc(this->parent, false);
}
void SetStringParameters(int widget) const override
@@ -1138,11 +1138,11 @@ struct QueryWindow : public Window {
QueryCallbackProc *proc = this->proc;
Window *parent = this->parent;
/* Prevent the destructor calling the callback function */
- this->proc = NULL;
+ this->proc = nullptr;
delete this;
- if (proc != NULL) {
+ if (proc != nullptr) {
proc(parent, true);
- proc = NULL;
+ proc = nullptr;
}
break;
}
@@ -1158,9 +1158,9 @@ struct QueryWindow : public Window {
switch (keycode) {
case WKC_RETURN:
case WKC_NUM_ENTER:
- if (this->proc != NULL) {
+ if (this->proc != nullptr) {
this->proc(this->parent, true);
- this->proc = NULL;
+ this->proc = nullptr;
}
FALLTHROUGH;
@@ -1187,7 +1187,7 @@ static const NWidgetPart _nested_query_widgets[] = {
};
static WindowDesc _query_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_CONFIRM_POPUP_QUERY, WC_NONE,
WDF_MODAL,
_nested_query_widgets, lengthof(_nested_query_widgets)
@@ -1198,13 +1198,13 @@ static WindowDesc _query_desc(
* The window is aligned to the centre of its parent.
* @param caption string shown as window caption
* @param message string that will be shown for the window
- * @param parent pointer to parent window, if this pointer is NULL the parent becomes
+ * @param parent pointer to parent window, if this pointer is nullptr the parent becomes
* the main window WC_MAIN_WINDOW
* @param callback callback function pointer to set in the window descriptor
*/
void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallbackProc *callback)
{
- if (parent == NULL) parent = FindWindowById(WC_MAIN_WINDOW, 0);
+ if (parent == nullptr) parent = FindWindowById(WC_MAIN_WINDOW, 0);
const Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
diff --git a/src/mixer.cpp b/src/mixer.cpp
index 6014f6082..5f3eeb42a 100644
--- a/src/mixer.cpp
+++ b/src/mixer.cpp
@@ -39,7 +39,7 @@ struct MixerChannel {
static MixerChannel _channels[8];
static uint32 _play_rate = 11025;
static uint32 _max_size = UINT_MAX;
-static MxStreamCallback _music_stream = NULL;
+static MxStreamCallback _music_stream = nullptr;
/**
* The theoretical maximum volume for a single sound sample. Multiple sound
@@ -175,11 +175,11 @@ MixerChannel *MxAllocateChannel()
for (mc = _channels; mc != endof(_channels); mc++) {
if (!mc->active) {
free(mc->memory);
- mc->memory = NULL;
+ mc->memory = nullptr;
return mc;
}
}
- return NULL;
+ return nullptr;
}
void MxSetChannelRawSrc(MixerChannel *mc, int8 *mem, size_t size, uint rate, bool is16bit)
@@ -238,6 +238,6 @@ bool MxInitialize(uint rate)
{
_play_rate = rate;
_max_size = UINT_MAX / _play_rate;
- _music_stream = NULL; /* rate may have changed, any music source is now invalid */
+ _music_stream = nullptr; /* rate may have changed, any music source is now invalid */
return true;
}
diff --git a/src/music.cpp b/src/music.cpp
index 3d0e40bf9..43a9508fa 100644
--- a/src/music.cpp
+++ b/src/music.cpp
@@ -25,11 +25,11 @@
* @param filename Name of CAT file to read from
* @param entrynum Index of entry whose name to read
* @return Pointer to string, caller is responsible for freeing memory,
- * NULL if entrynum does not exist.
+ * nullptr if entrynum does not exist.
*/
char *GetMusicCatEntryName(const char *filename, size_t entrynum)
{
- if (!FioCheckFileExists(filename, BASESET_DIR)) return NULL;
+ if (!FioCheckFileExists(filename, BASESET_DIR)) return nullptr;
FioOpenFile(CONFIG_SLOT, filename, BASESET_DIR);
uint32 ofs = FioReadDword();
@@ -43,7 +43,7 @@ char *GetMusicCatEntryName(const char *filename, size_t entrynum)
name[namelen] = '\0';
return name;
}
- return NULL;
+ return nullptr;
}
/**
@@ -52,12 +52,12 @@ char *GetMusicCatEntryName(const char *filename, size_t entrynum)
* @param entrynum Index of entry to read
* @param[out] entrylen Receives length of data read
* @return Pointer to buffer with data read, caller is responsible for freeind memory,
- * NULL if entrynum does not exist.
+ * nullptr if entrynum does not exist.
*/
byte *GetMusicCatEntryData(const char *filename, size_t entrynum, size_t &entrylen)
{
entrylen = 0;
- if (!FioCheckFileExists(filename, BASESET_DIR)) return NULL;
+ if (!FioCheckFileExists(filename, BASESET_DIR)) return nullptr;
FioOpenFile(CONFIG_SLOT, filename, BASESET_DIR);
uint32 ofs = FioReadDword();
@@ -72,7 +72,7 @@ byte *GetMusicCatEntryData(const char *filename, size_t entrynum, size_t &entryl
FioReadBlock(data, entrylen);
return data;
}
- return NULL;
+ return nullptr;
}
INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<MusicSet>, MusicSet)
@@ -99,13 +99,13 @@ template <class Tbase_set>
template <class Tbase_set>
/* static */ bool BaseMedia<Tbase_set>::DetermineBestSet()
{
- if (BaseMedia<Tbase_set>::used_set != NULL) return true;
+ if (BaseMedia<Tbase_set>::used_set != nullptr) return true;
- const Tbase_set *best = NULL;
- for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) {
+ const Tbase_set *best = nullptr;
+ for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != nullptr; c = c->next) {
if (c->GetNumMissing() != 0) continue;
- if (best == NULL ||
+ if (best == nullptr ||
(best->fallback && !c->fallback) ||
best->valid_files < c->valid_files ||
(best->valid_files == c->valid_files &&
@@ -115,7 +115,7 @@ template <class Tbase_set>
}
BaseMedia<Tbase_set>::used_set = best;
- return BaseMedia<Tbase_set>::used_set != NULL;
+ return BaseMedia<Tbase_set>::used_set != nullptr;
}
bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename)
@@ -129,7 +129,7 @@ bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_f
uint tracknr = 1;
for (uint i = 0; i < lengthof(this->songinfo); i++) {
const char *filename = this->files[i].filename;
- if (names == NULL || StrEmpty(filename) || this->files[i].check_result == MD5File::CR_NO_FILE) {
+ if (names == nullptr || StrEmpty(filename) || this->files[i].check_result == MD5File::CR_NO_FILE) {
this->songinfo[i].songname[0] = '\0';
continue;
}
@@ -137,12 +137,12 @@ bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_f
this->songinfo[i].filename = filename; // non-owned pointer
IniItem *item = catindex->GetItem(_music_file_names[i], false);
- if (item != NULL && !StrEmpty(item->value)) {
+ if (item != nullptr && !StrEmpty(item->value)) {
/* Song has a CAT file index, assume it's MPS MIDI format */
this->songinfo[i].filetype = MTT_MPSMIDI;
this->songinfo[i].cat_index = atoi(item->value);
char *songname = GetMusicCatEntryName(filename, this->songinfo[i].cat_index);
- if (songname == NULL) {
+ if (songname == nullptr) {
DEBUG(grf, 0, "Base music set song missing from CAT file: %s/%d", filename, this->songinfo[i].cat_index);
this->songinfo[i].songname[0] = '\0';
continue;
@@ -157,17 +157,17 @@ bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_f
/* As we possibly add a path to the filename and we compare
* on the filename with the path as in the .obm, we need to
* keep stripping path elements until we find a match. */
- for (; trimmed_filename != NULL; trimmed_filename = strchr(trimmed_filename, PATHSEPCHAR)) {
+ for (; trimmed_filename != nullptr; trimmed_filename = strchr(trimmed_filename, PATHSEPCHAR)) {
/* Remove possible double path separator characters from
* the beginning, so we don't start reading e.g. root. */
while (*trimmed_filename == PATHSEPCHAR) trimmed_filename++;
item = names->GetItem(trimmed_filename, false);
- if (item != NULL && !StrEmpty(item->value)) break;
+ if (item != nullptr && !StrEmpty(item->value)) break;
}
if (this->songinfo[i].filetype == MTT_STANDARDMIDI) {
- if (item != NULL && !StrEmpty(item->value)) {
+ if (item != nullptr && !StrEmpty(item->value)) {
strecpy(this->songinfo[i].songname, item->value, lastof(this->songinfo[i].songname));
} else {
DEBUG(grf, 0, "Base music set song name missing: %s", filename);
@@ -184,9 +184,9 @@ bool MusicSet::FillSetDetails(IniFile *ini, const char *path, const char *full_f
}
item = timingtrim->GetItem(trimmed_filename, false);
- if (item != NULL && !StrEmpty(item->value)) {
+ if (item != nullptr && !StrEmpty(item->value)) {
const char *endpos = strchr(item->value, ':');
- if (endpos != NULL) {
+ if (endpos != nullptr) {
this->songinfo[i].override_start = atoi(item->value);
this->songinfo[i].override_end = atoi(endpos + 1);
}
diff --git a/src/music/allegro_m.cpp b/src/music/allegro_m.cpp
index 906aec84f..959f15611 100644
--- a/src/music/allegro_m.cpp
+++ b/src/music/allegro_m.cpp
@@ -20,7 +20,7 @@
#include "../safeguards.h"
static FMusicDriver_Allegro iFMusicDriver_Allegro;
-static MIDI *_midi = NULL;
+static MIDI *_midi = nullptr;
/**
* There are multiple modules that might be using Allegro and
@@ -30,14 +30,14 @@ extern int _allegro_instance_count;
const char *MusicDriver_Allegro::Start(const char * const *param)
{
- if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) {
+ if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) {
DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
return "Failed to set up Allegro";
}
_allegro_instance_count++;
/* Initialise the sound */
- if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) {
+ if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, nullptr) != 0) {
DEBUG(driver, 0, "allegro: install_sound failed '%s'", allegro_error);
return "Failed to set up Allegro sound";
}
@@ -48,13 +48,13 @@ const char *MusicDriver_Allegro::Start(const char * const *param)
return "No sound card found";
}
- return NULL;
+ return nullptr;
}
void MusicDriver_Allegro::Stop()
{
- if (_midi != NULL) destroy_midi(_midi);
- _midi = NULL;
+ if (_midi != nullptr) destroy_midi(_midi);
+ _midi = nullptr;
if (--_allegro_instance_count == 0) allegro_exit();
}
@@ -63,12 +63,12 @@ void MusicDriver_Allegro::PlaySong(const MusicSongInfo &song)
{
std::string filename = MidiFile::GetSMFFile(song);
- if (_midi != NULL) destroy_midi(_midi);
+ if (_midi != nullptr) destroy_midi(_midi);
if (!filename.empty()) {
_midi = load_midi(filename.c_str());
play_midi(_midi, false);
} else {
- _midi = NULL;
+ _midi = nullptr;
}
}
diff --git a/src/music/bemidi.cpp b/src/music/bemidi.cpp
index ff56d787f..090ac0f90 100644
--- a/src/music/bemidi.cpp
+++ b/src/music/bemidi.cpp
@@ -28,7 +28,7 @@ static FMusicDriver_BeMidi iFMusicDriver_BeMidi;
const char *MusicDriver_BeMidi::Start(const char * const *parm)
{
- return NULL;
+ return nullptr;
}
void MusicDriver_BeMidi::Stop()
diff --git a/src/music/cocoa_m.cpp b/src/music/cocoa_m.cpp
index 2416cade0..c27a0a092 100644
--- a/src/music/cocoa_m.cpp
+++ b/src/music/cocoa_m.cpp
@@ -35,8 +35,8 @@
static FMusicDriver_Cocoa iFMusicDriver_Cocoa;
-static MusicPlayer _player = NULL;
-static MusicSequence _sequence = NULL;
+static MusicPlayer _player = nullptr;
+static MusicSequence _sequence = nullptr;
static MusicTimeStamp _seq_length = 0;
static bool _playing = false;
static byte _volume = 127;
@@ -45,12 +45,12 @@ static byte _volume = 127;
/** Set the volume of the current sequence. */
static void DoSetVolume()
{
- if (_sequence == NULL) return;
+ if (_sequence == nullptr) return;
AUGraph graph;
MusicSequenceGetAUGraph(_sequence, &graph);
- AudioUnit output_unit = NULL;
+ AudioUnit output_unit = nullptr;
/* Get output audio unit */
UInt32 node_count = 0;
@@ -82,7 +82,7 @@ static void DoSetVolume()
{
#if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
ComponentDescription desc;
- AUGraphGetNodeInfo(graph, node, &desc, NULL, NULL, &unit);
+ AUGraphGetNodeInfo(graph, node, &desc, nullptr, nullptr, &unit);
comp_type = desc.componentType;
#endif
}
@@ -92,7 +92,7 @@ static void DoSetVolume()
break;
}
}
- if (output_unit == NULL) {
+ if (output_unit == nullptr) {
DEBUG(driver, 1, "cocoa_m: Failed to get output node to set volume");
return;
}
@@ -109,7 +109,7 @@ const char *MusicDriver_Cocoa::Start(const char * const *parm)
{
if (NewMusicPlayer(&_player) != noErr) return "failed to create music player";
- return NULL;
+ return nullptr;
}
@@ -131,8 +131,8 @@ bool MusicDriver_Cocoa::IsSongPlaying()
*/
void MusicDriver_Cocoa::Stop()
{
- if (_player != NULL) DisposeMusicPlayer(_player);
- if (_sequence != NULL) DisposeMusicSequence(_sequence);
+ if (_player != nullptr) DisposeMusicPlayer(_player);
+ if (_sequence != nullptr) DisposeMusicSequence(_sequence);
}
@@ -148,9 +148,9 @@ void MusicDriver_Cocoa::PlaySong(const MusicSongInfo &song)
DEBUG(driver, 2, "cocoa_m: trying to play '%s'", filename.c_str());
this->StopSong();
- if (_sequence != NULL) {
+ if (_sequence != nullptr) {
DisposeMusicSequence(_sequence);
- _sequence = NULL;
+ _sequence = nullptr;
}
if (filename.empty()) return;
@@ -190,7 +190,7 @@ void MusicDriver_Cocoa::PlaySong(const MusicSongInfo &song)
CFRelease(url);
/* Construct audio graph */
- AUGraph graph = NULL;
+ AUGraph graph = nullptr;
MusicSequenceGetAUGraph(_sequence, &graph);
AUGraphOpen(graph);
@@ -204,7 +204,7 @@ void MusicDriver_Cocoa::PlaySong(const MusicSongInfo &song)
MusicSequenceGetTrackCount(_sequence, &num_tracks);
_seq_length = 0;
for (UInt32 i = 0; i < num_tracks; i++) {
- MusicTrack track = NULL;
+ MusicTrack track = nullptr;
MusicTimeStamp track_length = 0;
UInt32 prop_size = sizeof(MusicTimeStamp);
MusicSequenceGetIndTrack(_sequence, i, &track);
@@ -230,7 +230,7 @@ void MusicDriver_Cocoa::PlaySong(const MusicSongInfo &song)
void MusicDriver_Cocoa::StopSong()
{
MusicPlayerStop(_player);
- MusicPlayerSetSequence(_player, NULL);
+ MusicPlayerSetSequence(_player, nullptr);
_playing = false;
}
diff --git a/src/music/dmusic.cpp b/src/music/dmusic.cpp
index bf8657ef4..41ccd6102 100644
--- a/src/music/dmusic.cpp
+++ b/src/music/dmusic.cpp
@@ -141,16 +141,16 @@ static struct {
/** Handle to our worker thread. */
static std::thread _dmusic_thread;
/** Event to signal the thread that it should look at a state change. */
-static HANDLE _thread_event = NULL;
+static HANDLE _thread_event = nullptr;
/** Lock access to playback data that is not thread-safe. */
static std::mutex _thread_mutex;
/** The direct music object manages buffers and ports. */
-static IDirectMusic *_music = NULL;
+static IDirectMusic *_music = nullptr;
/** The port object lets us send MIDI data to the synthesizer. */
-static IDirectMusicPort *_port = NULL;
+static IDirectMusicPort *_port = nullptr;
/** The buffer object collects the data to sent. */
-static IDirectMusicBuffer *_buffer = NULL;
+static IDirectMusicBuffer *_buffer = nullptr;
/** List of downloaded DLS instruments. */
static std::vector<IDirectMusicDownload *> _dls_downloads;
@@ -438,7 +438,7 @@ bool DLSFile::LoadFile(const TCHAR *file)
DEBUG(driver, 2, "DMusic: Try to load DLS file %s", FS2OTTD(file));
FILE *f = _tfopen(file, _T("rb"));
- if (f == NULL) return false;
+ if (f == nullptr) return false;
FileCloser f_scope(f);
@@ -879,13 +879,13 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
if ((caps.dwFlags & (DMUS_PC_DLS | DMUS_PC_DLS2)) != 0 && (caps.dwFlags & DMUS_PC_GMINHARDWARE) == 0) {
DLSFile dls_file;
- if (user_dls == NULL) {
+ if (user_dls == nullptr) {
/* Try loading the default GM DLS file stored in the registry. */
HKEY hkDM;
if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\DirectMusic"), 0, KEY_READ, &hkDM))) {
TCHAR dls_path[MAX_PATH];
DWORD buf_size = sizeof(dls_path); // Buffer size as to be given in bytes!
- if (SUCCEEDED(RegQueryValueEx(hkDM, _T("GMFilePath"), NULL, NULL, (LPBYTE)dls_path, &buf_size))) {
+ if (SUCCEEDED(RegQueryValueEx(hkDM, _T("GMFilePath"), nullptr, nullptr, (LPBYTE)dls_path, &buf_size))) {
TCHAR expand_path[MAX_PATH * 2];
ExpandEnvironmentStrings(dls_path, expand_path, lengthof(expand_path));
if (!dls_file.LoadFile(expand_path)) DEBUG(driver, 1, "Failed to load default GM DLS file from registry");
@@ -906,7 +906,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
}
/* Get download port and allocate download IDs. */
- IDirectMusicPortDownload *download_port = NULL;
+ IDirectMusicPortDownload *download_port = nullptr;
if (FAILED(_port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port))) return "Can't get download port";
DWORD dlid_wave = 0, dlid_inst = 0;
@@ -920,7 +920,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
/* Download wave data. */
for (DWORD i = 0; i < dls_file.waves.size(); i++) {
- IDirectMusicDownload *dl_wave = NULL;
+ IDirectMusicDownload *dl_wave = nullptr;
if (FAILED(download_port->AllocateBuffer((DWORD)(sizeof(WAVE_DOWNLOAD) + dwAppend * dls_file.waves[i].fmt.wf.nBlockAlign + dls_file.waves[i].data.size()), &dl_wave))) {
download_port->Release();
return "Can't allocate wave download buffer";
@@ -984,7 +984,7 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
i_size += offsets * sizeof(ULONG);
/* Allocate download buffer. */
- IDirectMusicDownload *dl_inst = NULL;
+ IDirectMusicDownload *dl_inst = nullptr;
if (FAILED(download_port->AllocateBuffer((DWORD)i_size, &dl_inst))) {
download_port->Release();
return "Can't allocate instrument download buffer";
@@ -1085,19 +1085,19 @@ static const char *LoadDefaultDLSFile(const char *user_dls)
download_port->Release();
}
- return NULL;
+ return nullptr;
}
const char *MusicDriver_DMusic::Start(const char * const *parm)
{
/* Initialize COM */
- if (FAILED(CoInitializeEx(NULL, COINITBASE_MULTITHREADED))) return "COM initialization failed";
+ if (FAILED(CoInitializeEx(nullptr, COINITBASE_MULTITHREADED))) return "COM initialization failed";
/* Create the DirectMusic object */
if (FAILED(CoCreateInstance(
CLSID_DirectMusic,
- NULL,
+ nullptr,
CLSCTX_INPROC,
IID_IDirectMusic,
(LPVOID*)&_music
@@ -1106,7 +1106,7 @@ const char *MusicDriver_DMusic::Start(const char * const *parm)
}
/* Assign sound output device. */
- if (FAILED(_music->SetDirectSound(NULL, NULL))) return "Can't set DirectSound interface";
+ if (FAILED(_music->SetDirectSound(nullptr, nullptr))) return "Can't set DirectSound interface";
/* MIDI events need to be send to the synth in time before their playback time
* has come. By default, we try send any events at least 50 ms before playback. */
@@ -1149,7 +1149,7 @@ const char *MusicDriver_DMusic::Start(const char * const *parm)
params.dwSize = sizeof(DMUS_PORTPARAMS);
params.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
params.dwChannelGroups = 1;
- if (FAILED(_music->CreatePort(guidPort, &params, &_port, NULL))) return "Failed to create port";
+ if (FAILED(_music->CreatePort(guidPort, &params, &_port, nullptr))) return "Failed to create port";
/* Activate port. */
if (FAILED(_port->Activate(TRUE))) return "Failed to activate port";
@@ -1159,19 +1159,19 @@ const char *MusicDriver_DMusic::Start(const char * const *parm)
desc.dwSize = sizeof(DMUS_BUFFERDESC);
desc.guidBufferFormat = KSDATAFORMAT_SUBTYPE_DIRECTMUSIC;
desc.cbBuffer = 1024;
- if (FAILED(_music->CreateMusicBuffer(&desc, &_buffer, NULL))) return "Failed to create music buffer";
+ if (FAILED(_music->CreateMusicBuffer(&desc, &_buffer, nullptr))) return "Failed to create music buffer";
/* On soft-synths (e.g. the default DirectMusic one), we might need to load a wavetable set to get music. */
const char *dls = LoadDefaultDLSFile(GetDriverParam(parm, "dls"));
- if (dls != NULL) return dls;
+ if (dls != nullptr) return dls;
/* Create playback thread and synchronization primitives. */
- _thread_event = CreateEvent(NULL, FALSE, FALSE, NULL);
- if (_thread_event == NULL) return "Can't create thread shutdown event";
+ _thread_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
+ if (_thread_event == nullptr) return "Can't create thread shutdown event";
if (!StartNewThread(&_dmusic_thread, "ottd:dmusic", &MidiThreadProc)) return "Can't create MIDI output thread";
- return NULL;
+ return nullptr;
}
@@ -1191,34 +1191,34 @@ void MusicDriver_DMusic::Stop()
/* Unloaded any instruments we loaded. */
if (_dls_downloads.size() > 0) {
- IDirectMusicPortDownload *download_port = NULL;
+ IDirectMusicPortDownload *download_port = nullptr;
_port->QueryInterface(IID_IDirectMusicPortDownload, (LPVOID *)&download_port);
/* Instruments refer to waves. As the waves are at the beginning of the download list,
* do the unload from the back so that references are cleared properly. */
- for (std::vector<IDirectMusicDownload *>::reverse_iterator i = _dls_downloads.rbegin(); download_port != NULL && i != _dls_downloads.rend(); i++) {
+ for (std::vector<IDirectMusicDownload *>::reverse_iterator i = _dls_downloads.rbegin(); download_port != nullptr && i != _dls_downloads.rend(); i++) {
download_port->Unload(*i);
(*i)->Release();
}
_dls_downloads.clear();
- if (download_port != NULL) download_port->Release();
+ if (download_port != nullptr) download_port->Release();
}
- if (_buffer != NULL) {
+ if (_buffer != nullptr) {
_buffer->Release();
- _buffer = NULL;
+ _buffer = nullptr;
}
- if (_port != NULL) {
+ if (_port != nullptr) {
_port->Activate(FALSE);
_port->Release();
- _port = NULL;
+ _port = nullptr;
}
- if (_music != NULL) {
+ if (_music != nullptr) {
_music->Release();
- _music = NULL;
+ _music = nullptr;
}
CloseHandle(_thread_event);
diff --git a/src/music/extmidi.cpp b/src/music/extmidi.cpp
index f7fc454df..b390c42f5 100644
--- a/src/music/extmidi.cpp
+++ b/src/music/extmidi.cpp
@@ -52,7 +52,7 @@ const char *MusicDriver_ExtMidi::Start(const char * const * parm)
if (StrEmpty(command)) command = EXTERNAL_PLAYER " " MIDI_ARG;
#endif
- /* Count number of arguments, but include 3 extra slots: 1st for command, 2nd for song title, and 3rd for terminating NULL. */
+ /* Count number of arguments, but include 3 extra slots: 1st for command, 2nd for song title, and 3rd for terminating nullptr. */
uint num_args = 3;
for (const char *t = command; *t != '\0'; t++) if (*t == ' ') num_args++;
@@ -63,7 +63,7 @@ const char *MusicDriver_ExtMidi::Start(const char * const * parm)
uint p = 1;
while (true) {
this->params[p] = strchr(this->params[p - 1], ' ');
- if (this->params[p] == NULL) break;
+ if (this->params[p] == nullptr) break;
this->params[p][0] = '\0';
this->params[p]++;
@@ -75,7 +75,7 @@ const char *MusicDriver_ExtMidi::Start(const char * const * parm)
this->song[0] = '\0';
this->pid = -1;
- return NULL;
+ return nullptr;
}
void MusicDriver_ExtMidi::Stop()
@@ -103,7 +103,7 @@ void MusicDriver_ExtMidi::StopSong()
bool MusicDriver_ExtMidi::IsSongPlaying()
{
- if (this->pid != -1 && waitpid(this->pid, NULL, WNOHANG) == this->pid) {
+ if (this->pid != -1 && waitpid(this->pid, nullptr, WNOHANG) == this->pid) {
this->pid = -1;
}
if (this->pid == -1 && this->song[0] != '\0') this->DoPlay();
@@ -146,7 +146,7 @@ void MusicDriver_ExtMidi::DoStop()
* 5 seconds = 5000 milliseconds, 10 ms per cycle => 500 cycles. */
for (int i = 0; i < 500; i++) {
kill(this->pid, SIGTERM);
- if (waitpid(this->pid, NULL, WNOHANG) == this->pid) {
+ if (waitpid(this->pid, nullptr, WNOHANG) == this->pid) {
/* It has shut down, so we are done */
this->pid = -1;
return;
@@ -159,6 +159,6 @@ void MusicDriver_ExtMidi::DoStop()
/* Gracefully stopping failed. Do it the hard way
* and wait till the process finally died. */
kill(this->pid, SIGKILL);
- waitpid(this->pid, NULL, 0);
+ waitpid(this->pid, nullptr, 0);
this->pid = -1;
}
diff --git a/src/music/fluidsynth.cpp b/src/music/fluidsynth.cpp
index 49e50eb9e..4623716a4 100644
--- a/src/music/fluidsynth.cpp
+++ b/src/music/fluidsynth.cpp
@@ -39,7 +39,7 @@ static const char *default_sf[] = {
"/usr/share/sounds/sf2/TimGM6mb.sf2",
"/usr/share/sounds/sf2/FluidR3_GS.sf2",
- NULL
+ nullptr
};
static void RenderMusicStream(int16 *buffer, size_t samples)
@@ -81,18 +81,18 @@ const char *MusicDriver_FluidSynth::Start(const char * const *param)
if (sfont_id == FLUID_FAILED) return "Could not open sound font";
}
- _midi.player = NULL;
+ _midi.player = nullptr;
uint32 samplerate = MxSetMusicSource(RenderMusicStream);
fluid_synth_set_sample_rate(_midi.synth, samplerate);
DEBUG(driver, 1, "Fluidsynth: samplerate %.0f", (float)samplerate);
- return NULL;
+ return nullptr;
}
void MusicDriver_FluidSynth::Stop()
{
- MxSetMusicSource(NULL);
+ MxSetMusicSource(nullptr);
this->StopSong();
delete_fluid_synth(_midi.synth);
delete_fluid_settings(_midi.settings);
@@ -117,13 +117,13 @@ void MusicDriver_FluidSynth::PlaySong(const MusicSongInfo &song)
if (fluid_player_add(_midi.player, filename.c_str()) != FLUID_OK) {
DEBUG(driver, 0, "Could not open music file");
delete_fluid_player(_midi.player);
- _midi.player = NULL;
+ _midi.player = nullptr;
return;
}
if (fluid_player_play(_midi.player) != FLUID_OK) {
DEBUG(driver, 0, "Could not start midi player");
delete_fluid_player(_midi.player);
- _midi.player = NULL;
+ _midi.player = nullptr;
return;
}
}
@@ -138,7 +138,7 @@ void MusicDriver_FluidSynth::StopSong()
}
delete_fluid_player(_midi.player);
fluid_synth_system_reset(_midi.synth);
- _midi.player = NULL;
+ _midi.player = nullptr;
}
bool MusicDriver_FluidSynth::IsSongPlaying()
diff --git a/src/music/midifile.cpp b/src/music/midifile.cpp
index 97fb2edf8..3717ad5d3 100644
--- a/src/music/midifile.cpp
+++ b/src/music/midifile.cpp
@@ -24,7 +24,7 @@
/* SMF reader based on description at: http://www.somascape.org/midi/tech/mfile.html */
-static MidiFile *_midifile_instance = NULL;
+static MidiFile *_midifile_instance = nullptr;
/**
* Owning byte buffer readable as a stream.
@@ -426,7 +426,7 @@ bool MidiFile::LoadFile(const char *filename)
bool success = false;
FILE *file = FioFOpenFile(filename, "rb", Subdirectory::BASESET_DIR);
- if (file == NULL) return false;
+ if (file == nullptr) return false;
SMFHeader header;
if (!ReadSMFHeader(file, header)) goto cleanup;
@@ -815,7 +815,7 @@ bool MidiFile::LoadSong(const MusicSongInfo &song)
{
size_t songdatalen = 0;
byte *songdata = GetMusicCatEntryData(song.filename, song.cat_index, songdatalen);
- if (songdata != NULL) {
+ if (songdata != nullptr) {
bool result = this->LoadMpsData(songdata, songdatalen);
free(songdata);
return result;
@@ -1024,7 +1024,7 @@ std::string MidiFile::GetSMFFile(const MusicSongInfo &song)
char basename[MAX_PATH];
{
const char *fnstart = strrchr(song.filename, PATHSEPCHAR);
- if (fnstart == NULL) {
+ if (fnstart == nullptr) {
fnstart = song.filename;
} else {
fnstart++;
@@ -1054,7 +1054,7 @@ std::string MidiFile::GetSMFFile(const MusicSongInfo &song)
byte *data;
size_t datalen;
data = GetMusicCatEntryData(song.filename, song.cat_index, datalen);
- if (data == NULL) return std::string();
+ if (data == nullptr) return std::string();
MidiFile midifile;
if (!midifile.LoadMpsData(data, datalen)) {
@@ -1082,7 +1082,7 @@ static bool CmdDumpSMF(byte argc, char *argv[])
return false;
}
- if (_midifile_instance == NULL) {
+ if (_midifile_instance == nullptr) {
IConsolePrint(CC_ERROR, "There is no MIDI file loaded currently, make sure music is playing, and you're using a driver that works with raw MIDI.");
return false;
}
@@ -1120,7 +1120,7 @@ MidiFile::MidiFile()
MidiFile::~MidiFile()
{
if (_midifile_instance == this) {
- _midifile_instance = NULL;
+ _midifile_instance = nullptr;
}
}
diff --git a/src/music/null_m.h b/src/music/null_m.h
index 837eeb092..8eb7d6792 100644
--- a/src/music/null_m.h
+++ b/src/music/null_m.h
@@ -17,7 +17,7 @@
/** The music player that does nothing. */
class MusicDriver_Null : public MusicDriver {
public:
- const char *Start(const char * const *param) override { return NULL; }
+ const char *Start(const char * const *param) override { return nullptr; }
void Stop() override { }
diff --git a/src/music/os2_m.cpp b/src/music/os2_m.cpp
index 1689f00a6..92e177f84 100644
--- a/src/music/os2_m.cpp
+++ b/src/music/os2_m.cpp
@@ -45,7 +45,7 @@ static long CDECL MidiSendCommand(const char *cmd, ...)
va_start(va, cmd);
vseprintf(buf, lastof(buf), cmd, va);
va_end(va);
- return mciSendString(buf, NULL, 0, NULL, 0);
+ return mciSendString(buf, nullptr, 0, nullptr, 0);
}
/** OS/2's music player's factory. */
@@ -78,7 +78,7 @@ void MusicDriver_OS2::SetVolume(byte vol)
bool MusicDriver_OS2::IsSongPlaying()
{
char buf[16];
- mciSendString("status song mode", buf, sizeof(buf), NULL, 0);
+ mciSendString("status song mode", buf, sizeof(buf), nullptr, 0);
return strcmp(buf, "playing") == 0 || strcmp(buf, "seeking") == 0;
}
diff --git a/src/music/qtmidi.cpp b/src/music/qtmidi.cpp
index f8ab150e7..f8412a2dc 100644
--- a/src/music/qtmidi.cpp
+++ b/src/music/qtmidi.cpp
@@ -60,7 +60,7 @@ static void SetMIDITypeIfNeeded(const FSRef *ref)
assert(ref);
- if (noErr != FSGetCatalogInfo(ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &catalogInfo, NULL, NULL, NULL)) return;
+ if (noErr != FSGetCatalogInfo(ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &catalogInfo, nullptr, nullptr, nullptr)) return;
if (!(catalogInfo.nodeFlags & kFSNodeIsDirectoryMask)) {
FileInfo * const info = (FileInfo *) catalogInfo.finderInfo;
if (info->fileType != MIDI_TYPE && !(info->finderFlags & kIsAlias)) {
@@ -94,8 +94,8 @@ static bool LoadMovieForMIDIFile(const char *path, Movie *moov)
short refnum = 0;
short resid = 0;
- assert(path != NULL);
- assert(moov != NULL);
+ assert(path != nullptr);
+ assert(moov != nullptr);
DEBUG(driver, 2, "qtmidi: start loading '%s'...", path);
@@ -116,15 +116,15 @@ static bool LoadMovieForMIDIFile(const char *path, Movie *moov)
return false;
}
- if (noErr != FSPathMakeRef((const UInt8 *) path, &fsref, NULL)) return false;
+ if (noErr != FSPathMakeRef((const UInt8 *) path, &fsref, nullptr)) return false;
SetMIDITypeIfNeeded(&fsref);
- if (noErr != FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &fsspec, NULL)) return false;
+ if (noErr != FSGetCatalogInfo(&fsref, kFSCatInfoNone, nullptr, nullptr, &fsspec, nullptr)) return false;
if (OpenMovieFile(&fsspec, &refnum, fsRdPerm) != noErr) return false;
DEBUG(driver, 3, "qtmidi: '%s' successfully opened", path);
- if (noErr != NewMovieFromFile(moov, refnum, &resid, NULL,
- newMovieActive | newMovieDontAskUnresolvedDataRefs, NULL)) {
+ if (noErr != NewMovieFromFile(moov, refnum, &resid, nullptr,
+ newMovieActive | newMovieDontAskUnresolvedDataRefs, nullptr)) {
CloseMovieFile(refnum);
return false;
}
@@ -191,7 +191,7 @@ static int _quicktime_state = QT_STATE_IDLE; ///< Current player state.
const char *MusicDriver_QtMidi::Start(const char * const *parm)
{
InitQuickTimeIfNeeded();
- return (_quicktime_started) ? NULL : "can't initialize QuickTime";
+ return (_quicktime_started) ? nullptr : "can't initialize QuickTime";
}
@@ -215,7 +215,7 @@ bool MusicDriver_QtMidi::IsSongPlaying()
MoviesTask(_quicktime_movie, 0);
/* Check wether movie ended. */
if (IsMovieDone(_quicktime_movie) ||
- (GetMovieTime(_quicktime_movie, NULL) >=
+ (GetMovieTime(_quicktime_movie, nullptr) >=
GetMovieDuration(_quicktime_movie))) {
_quicktime_state = QT_STATE_STOP;
}
diff --git a/src/music/win32_m.cpp b/src/music/win32_m.cpp
index bdba202f2..de5facd48 100644
--- a/src/music/win32_m.cpp
+++ b/src/music/win32_m.cpp
@@ -396,7 +396,7 @@ const char *MusicDriver_Win32::Start(const char * const *parm)
if (timeBeginPeriod(_midi.time_period) == MMSYSERR_NOERROR) {
/* success */
DEBUG(driver, 2, "Win32-MIDI: Start: timer resolution is %d", (int)_midi.time_period);
- return NULL;
+ return nullptr;
}
}
midiOutClose(_midi.midi_out);
diff --git a/src/network/core/address.cpp b/src/network/core/address.cpp
index 11b5d753f..3d5bd5d64 100644
--- a/src/network/core/address.cpp
+++ b/src/network/core/address.cpp
@@ -25,7 +25,7 @@ const char *NetworkAddress::GetHostname()
{
if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
assert(this->address_length != 0);
- getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), NULL, 0, NI_NUMERICHOST);
+ getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST);
}
return this->hostname;
}
@@ -131,7 +131,7 @@ const sockaddr_storage *NetworkAddress::GetAddress()
* bothered to implement the specifications and allow '0' as value
* that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
*/
- this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
+ this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
this->resolved = true;
}
return &this->address;
@@ -145,7 +145,7 @@ const sockaddr_storage *NetworkAddress::GetAddress()
bool NetworkAddress::IsFamily(int family)
{
if (!this->IsResolved()) {
- this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
+ this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
}
return this->address.ss_family == family;
}
@@ -167,7 +167,7 @@ bool NetworkAddress::IsInNetmask(const char *netmask)
/* Check for CIDR separator */
const char *chr_cidr = strchr(netmask, '/');
- if (chr_cidr != NULL) {
+ if (chr_cidr != nullptr) {
int tmp_cidr = atoi(chr_cidr + 1);
/* Invalid CIDR, treat as single host */
@@ -232,7 +232,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
seprintf(port_name, lastof(port_name), "%u", this->GetPort());
bool reset_hostname = false;
- /* Setting both hostname to NULL and port to 0 is not allowed.
+ /* Setting both hostname to nullptr and port to 0 is not allowed.
* As port 0 means bind to any port, the other must mean that
* we want to bind to 'all' IPs. */
if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
@@ -242,7 +242,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
}
- int e = getaddrinfo(StrEmpty(this->hostname) ? NULL : this->hostname, port_name, &hints, &ai);
+ int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
@@ -255,18 +255,18 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
}
SOCKET sock = INVALID_SOCKET;
- for (struct addrinfo *runp = ai; runp != NULL; runp = runp->ai_next) {
+ for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
/* When we are binding to multiple sockets, make sure we do not
* connect to one with exactly the same address twice. That's
* of course totally unneeded ;) */
- if (sockets != NULL) {
+ if (sockets != nullptr) {
NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
if (sockets->Contains(address)) continue;
}
sock = func(runp);
if (sock == INVALID_SOCKET) continue;
- if (sockets == NULL) {
+ if (sockets == nullptr) {
this->address_length = (int)runp->ai_addrlen;
assert(sizeof(this->address) >= runp->ai_addrlen);
memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
@@ -323,7 +323,7 @@ SOCKET NetworkAddress::Connect()
{
DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
- return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, NULL, ConnectLoopProc);
+ return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
}
/**
@@ -386,9 +386,9 @@ static SOCKET ListenLoopProc(addrinfo *runp)
*/
void NetworkAddress::Listen(int socktype, SocketList *sockets)
{
- assert(sockets != NULL);
+ assert(sockets != nullptr);
- /* Setting both hostname to NULL and port to 0 is not allowed.
+ /* Setting both hostname to nullptr and port to 0 is not allowed.
* As port 0 means bind to any port, the other must mean that
* we want to bind to 'all' IPs. */
if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
diff --git a/src/network/core/address.h b/src/network/core/address.h
index bd1bab676..4dd0edbc0 100644
--- a/src/network/core/address.h
+++ b/src/network/core/address.h
@@ -84,7 +84,7 @@ public:
if (*hostname == '[') hostname++;
strecpy(this->hostname, StrEmpty(hostname) ? "" : hostname, lastof(this->hostname));
char *tmp = strrchr(this->hostname, ']');
- if (tmp != NULL) *tmp = '\0';
+ if (tmp != nullptr) *tmp = '\0';
memset(&this->address, 0, sizeof(this->address));
this->address.ss_family = family;
diff --git a/src/network/core/host.cpp b/src/network/core/host.cpp
index 2bf862a4f..98a706e2f 100644
--- a/src/network/core/host.cpp
+++ b/src/network/core/host.cpp
@@ -45,7 +45,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // BE
return;
}
- char *output_pointer = NULL;
+ char *output_pointer = nullptr;
int output_length = _netstat(sock, &output_pointer, 1);
if (output_length < 0) {
DEBUG(net, 0, "[core] error running _netstat");
@@ -94,9 +94,9 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // GE
if (getifaddrs(&ifap) != 0) return;
- for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
+ for (ifa = ifap; ifa != nullptr; ifa = ifa->ifa_next) {
if (!(ifa->ifa_flags & IFF_BROADCAST)) continue;
- if (ifa->ifa_broadaddr == NULL) continue;
+ if (ifa->ifa_broadaddr == nullptr) continue;
if (ifa->ifa_broadaddr->sa_family != AF_INET) continue;
NetworkAddress addr(ifa->ifa_broadaddr, sizeof(sockaddr));
@@ -116,7 +116,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // Wi
INTERFACE_INFO *ifo = CallocT<INTERFACE_INFO>(num);
for (;;) {
- if (WSAIoctl(sock, SIO_GET_INTERFACE_LIST, NULL, 0, ifo, num * sizeof(*ifo), &len, NULL, NULL) == 0) break;
+ if (WSAIoctl(sock, SIO_GET_INTERFACE_LIST, nullptr, 0, ifo, num * sizeof(*ifo), &len, nullptr, nullptr) == 0) break;
free(ifo);
if (WSAGetLastError() != WSAEFAULT) {
closesocket(sock);
diff --git a/src/network/core/packet.cpp b/src/network/core/packet.cpp
index 8cecd9bd2..fda8fdfeb 100644
--- a/src/network/core/packet.cpp
+++ b/src/network/core/packet.cpp
@@ -24,10 +24,10 @@
*/
Packet::Packet(NetworkSocketHandler *cs)
{
- assert(cs != NULL);
+ assert(cs != nullptr);
this->cs = cs;
- this->next = NULL;
+ this->next = nullptr;
this->pos = 0; // We start reading from here
this->size = 0;
this->buffer = MallocT<byte>(SEND_MTU);
@@ -39,8 +39,8 @@ Packet::Packet(NetworkSocketHandler *cs)
*/
Packet::Packet(PacketType type)
{
- this->cs = NULL;
- this->next = NULL;
+ this->cs = nullptr;
+ this->next = nullptr;
/* Skip the size so we can write that in before sending the packet */
this->pos = 0;
@@ -62,7 +62,7 @@ Packet::~Packet()
*/
void Packet::PrepareToSend()
{
- assert(this->cs == NULL && this->next == NULL);
+ assert(this->cs == nullptr && this->next == nullptr);
this->buffer[0] = GB(this->size, 0, 8);
this->buffer[1] = GB(this->size, 8, 8);
@@ -149,7 +149,7 @@ void Packet::Send_uint64(uint64 data)
*/
void Packet::Send_string(const char *data)
{
- assert(data != NULL);
+ assert(data != nullptr);
/* The <= *is* valid due to the fact that we are comparing sizes and not the index. */
assert(this->size + strlen(data) + 1 <= SEND_MTU);
while ((this->buffer[this->size++] = *data++) != '\0') {}
@@ -187,7 +187,7 @@ bool Packet::CanReadFromPacket(uint bytes_to_read)
*/
void Packet::ReadRawPacketSize()
{
- assert(this->cs != NULL && this->next == NULL);
+ assert(this->cs != nullptr && this->next == nullptr);
this->size = (PacketSize)this->buffer[0];
this->size += (PacketSize)this->buffer[1] << 8;
}
diff --git a/src/network/core/tcp.cpp b/src/network/core/tcp.cpp
index 33b61688d..63d004a8f 100644
--- a/src/network/core/tcp.cpp
+++ b/src/network/core/tcp.cpp
@@ -24,7 +24,7 @@
*/
NetworkTCPSocketHandler::NetworkTCPSocketHandler(SOCKET s) :
NetworkSocketHandler(),
- packet_queue(NULL), packet_recv(NULL),
+ packet_queue(nullptr), packet_recv(nullptr),
sock(s), writable(false)
{
}
@@ -43,13 +43,13 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
NetworkSocketHandler::CloseConnection(error);
/* Free all pending and partially received packets */
- while (this->packet_queue != NULL) {
+ while (this->packet_queue != nullptr) {
Packet *p = this->packet_queue->next;
delete this->packet_queue;
this->packet_queue = p;
}
delete this->packet_recv;
- this->packet_recv = NULL;
+ this->packet_recv = nullptr;
return NETWORK_RECV_STATUS_OKAY;
}
@@ -63,7 +63,7 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
void NetworkTCPSocketHandler::SendPacket(Packet *packet)
{
Packet *p;
- assert(packet != NULL);
+ assert(packet != nullptr);
packet->PrepareToSend();
@@ -74,12 +74,12 @@ void NetworkTCPSocketHandler::SendPacket(Packet *packet)
/* Locate last packet buffered for the client */
p = this->packet_queue;
- if (p == NULL) {
+ if (p == nullptr) {
/* No packets yet */
this->packet_queue = packet;
} else {
/* Skip to the last packet */
- while (p->next != NULL) p = p->next;
+ while (p->next != nullptr) p = p->next;
p->next = packet;
}
}
@@ -104,7 +104,7 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
if (!this->IsConnected()) return SPS_CLOSED;
p = this->packet_queue;
- while (p != NULL) {
+ while (p != nullptr) {
res = send(this->sock, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
if (res == -1) {
int err = GET_LAST_ERROR();
@@ -142,15 +142,15 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
/**
* Receives a packet for the given client
- * @return The received packet (or NULL when it didn't receive one)
+ * @return The received packet (or nullptr when it didn't receive one)
*/
Packet *NetworkTCPSocketHandler::ReceivePacket()
{
ssize_t res;
- if (!this->IsConnected()) return NULL;
+ if (!this->IsConnected()) return nullptr;
- if (this->packet_recv == NULL) {
+ if (this->packet_recv == nullptr) {
this->packet_recv = new Packet(this);
}
@@ -167,15 +167,15 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
/* Something went wrong... (104 is connection reset by peer) */
if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
this->CloseConnection();
- return NULL;
+ return nullptr;
}
/* Connection would block, so stop for now */
- return NULL;
+ return nullptr;
}
if (res == 0) {
/* Client/server has left */
this->CloseConnection();
- return NULL;
+ return nullptr;
}
p->pos += res;
}
@@ -185,7 +185,7 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
if (p->size > SEND_MTU) {
this->CloseConnection();
- return NULL;
+ return nullptr;
}
}
@@ -198,22 +198,22 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
/* Something went wrong... (104 is connection reset by peer) */
if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
this->CloseConnection();
- return NULL;
+ return nullptr;
}
/* Connection would block */
- return NULL;
+ return nullptr;
}
if (res == 0) {
/* Client/server has left */
this->CloseConnection();
- return NULL;
+ return nullptr;
}
p->pos += res;
}
/* Prepare for receiving a new packet */
- this->packet_recv = NULL;
+ this->packet_recv = nullptr;
p->PrepareToRead();
return p;
@@ -236,7 +236,7 @@ bool NetworkTCPSocketHandler::CanSendReceive()
FD_SET(this->sock, &write_fd);
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
- if (select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv) < 0) return false;
+ if (select(FD_SETSIZE, &read_fd, &write_fd, nullptr, &tv) < 0) return false;
this->writable = !!FD_ISSET(this->sock, &write_fd);
return FD_ISSET(this->sock, &read_fd) != 0;
diff --git a/src/network/core/tcp.h b/src/network/core/tcp.h
index f9e1e00cb..451b93071 100644
--- a/src/network/core/tcp.h
+++ b/src/network/core/tcp.h
@@ -52,7 +52,7 @@ public:
* Whether there is something pending in the send queue.
* @return true when something is pending in the send queue.
*/
- bool HasSendQueue() { return this->packet_queue != NULL; }
+ bool HasSendQueue() { return this->packet_queue != nullptr; }
NetworkTCPSocketHandler(SOCKET s = INVALID_SOCKET);
~NetworkTCPSocketHandler();
diff --git a/src/network/core/tcp_admin.cpp b/src/network/core/tcp_admin.cpp
index 226bae024..98ef0f0a0 100644
--- a/src/network/core/tcp_admin.cpp
+++ b/src/network/core/tcp_admin.cpp
@@ -115,7 +115,7 @@ NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet *p)
NetworkRecvStatus NetworkAdminSocketHandler::ReceivePackets()
{
Packet *p;
- while ((p = this->ReceivePacket()) != NULL) {
+ while ((p = this->ReceivePacket()) != nullptr) {
NetworkRecvStatus res = this->HandlePacket(p);
if (res != NETWORK_RECV_STATUS_OKAY) return res;
}
diff --git a/src/network/core/tcp_connect.cpp b/src/network/core/tcp_connect.cpp
index d923688b1..13330108a 100644
--- a/src/network/core/tcp_connect.cpp
+++ b/src/network/core/tcp_connect.cpp
@@ -33,7 +33,7 @@ TCPConnecter::TCPConnecter(const NetworkAddress &address) :
address(address)
{
_tcp_connecters.push_back(this);
- if (!StartNewThread(NULL, "ottd:tcp", &TCPConnecter::ThreadEntry, this)) {
+ if (!StartNewThread(nullptr, "ottd:tcp", &TCPConnecter::ThreadEntry, this)) {
this->Connect();
}
}
diff --git a/src/network/core/tcp_content.cpp b/src/network/core/tcp_content.cpp
index 8257a7252..ee8baf48e 100644
--- a/src/network/core/tcp_content.cpp
+++ b/src/network/core/tcp_content.cpp
@@ -47,8 +47,8 @@ void ContentInfo::TransferFrom(ContentInfo *other)
free(this->dependencies);
free(this->tags);
memcpy(this, other, sizeof(ContentInfo));
- other->dependencies = NULL;
- other->tags = NULL;
+ other->dependencies = nullptr;
+ other->tags = nullptr;
}
}
@@ -98,11 +98,11 @@ bool ContentInfo::IsValid() const
/**
* Search a textfile file next to this file in the content list.
* @param type The type of the textfile to search for.
- * @return The filename for the textfile, \c NULL otherwise.
+ * @return The filename for the textfile, \c nullptr otherwise.
*/
const char *ContentInfo::GetTextfile(TextfileType type) const
{
- if (this->state == INVALID) return NULL;
+ if (this->state == INVALID) return nullptr;
const char *tmp;
switch (this->type) {
default: NOT_REACHED();
@@ -120,7 +120,7 @@ const char *ContentInfo::GetTextfile(TextfileType type) const
break;
case CONTENT_TYPE_NEWGRF: {
const GRFConfig *gc = FindGRFConfig(BSWAP32(this->unique_id), FGCM_EXACT, this->md5sum);
- tmp = gc != NULL ? gc->filename : NULL;
+ tmp = gc != nullptr ? gc->filename : nullptr;
break;
}
case CONTENT_TYPE_BASE_GRAPHICS:
@@ -138,7 +138,7 @@ const char *ContentInfo::GetTextfile(TextfileType type) const
tmp = FindScenario(this, true);
break;
}
- if (tmp == NULL) return NULL;
+ if (tmp == nullptr) return nullptr;
return ::GetTextfile(type, GetContentInfoSubDir(this->type), tmp);
}
#endif /* OPENTTD_MSU */
@@ -209,7 +209,7 @@ bool NetworkContentSocketHandler::ReceivePackets()
Packet *p;
static const int MAX_PACKETS_TO_RECEIVE = 42;
int i = MAX_PACKETS_TO_RECEIVE;
- while (--i != 0 && (p = this->ReceivePacket()) != NULL) {
+ while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
bool cont = this->HandlePacket(p);
delete p;
if (!cont) return true;
diff --git a/src/network/core/tcp_game.cpp b/src/network/core/tcp_game.cpp
index 2d8a74a11..6d69d10d2 100644
--- a/src/network/core/tcp_game.cpp
+++ b/src/network/core/tcp_game.cpp
@@ -26,7 +26,7 @@
* Create a new socket for the game connection.
* @param s The socket to connect with.
*/
-NetworkGameSocketHandler::NetworkGameSocketHandler(SOCKET s) : info(NULL), client_id(INVALID_CLIENT_ID),
+NetworkGameSocketHandler::NetworkGameSocketHandler(SOCKET s) : info(nullptr), client_id(INVALID_CLIENT_ID),
last_frame(_frame_counter), last_frame_server(_frame_counter), last_packet(_realtime_tick)
{
this->sock = s;
@@ -134,7 +134,7 @@ NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet *p)
NetworkRecvStatus NetworkGameSocketHandler::ReceivePackets()
{
Packet *p;
- while ((p = this->ReceivePacket()) != NULL) {
+ while ((p = this->ReceivePacket()) != nullptr) {
NetworkRecvStatus res = HandlePacket(p);
delete p;
if (res != NETWORK_RECV_STATUS_OKAY) return res;
diff --git a/src/network/core/tcp_game.h b/src/network/core/tcp_game.h
index b392cf717..eb8881adc 100644
--- a/src/network/core/tcp_game.h
+++ b/src/network/core/tcp_game.h
@@ -130,12 +130,12 @@ struct CommandPacket;
/** A queue of CommandPackets. */
class CommandQueue {
CommandPacket *first; ///< The first packet in the queue.
- CommandPacket *last; ///< The last packet in the queue; only valid when first != NULL.
+ CommandPacket *last; ///< The last packet in the queue; only valid when first != nullptr.
uint count; ///< The number of items in the queue.
public:
/** Initialise the command queue. */
- CommandQueue() : first(NULL), last(NULL), count(0) {}
+ CommandQueue() : first(nullptr), last(nullptr), count(0) {}
/** Clear the command queue. */
~CommandQueue() { this->Free(); }
void Append(CommandPacket *p);
@@ -537,7 +537,7 @@ public:
*/
inline void SetInfo(NetworkClientInfo *info)
{
- assert(info != NULL && this->info == NULL);
+ assert(info != nullptr && this->info == nullptr);
this->info = info;
}
diff --git a/src/network/core/tcp_http.cpp b/src/network/core/tcp_http.cpp
index 3e9cc8141..116232402 100644
--- a/src/network/core/tcp_http.cpp
+++ b/src/network/core/tcp_http.cpp
@@ -43,11 +43,11 @@ NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
redirect_depth(depth),
sock(s)
{
- size_t bufferSize = strlen(url) + strlen(host) + strlen(GetNetworkRevisionString()) + (data == NULL ? 0 : strlen(data)) + 128;
+ size_t bufferSize = strlen(url) + strlen(host) + strlen(GetNetworkRevisionString()) + (data == nullptr ? 0 : strlen(data)) + 128;
char *buffer = AllocaM(char, bufferSize);
DEBUG(net, 7, "[tcp/http] requesting %s%s", host, url);
- if (data != NULL) {
+ if (data != nullptr) {
seprintf(buffer, buffer + bufferSize - 1, "POST %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s\r\n", url, host, GetNetworkRevisionString(), (int)strlen(data), data);
} else {
seprintf(buffer, buffer + bufferSize - 1, "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\n\r\n", url, host, GetNetworkRevisionString());
@@ -108,7 +108,7 @@ static const char * const LOCATION = "Location: "; ///< Header for l
int NetworkHTTPSocketHandler::HandleHeader()
{
assert(strlen(HTTP_1_0) == strlen(HTTP_1_1));
- assert(strstr(this->recv_buffer, END_OF_HEADER) != NULL);
+ assert(strstr(this->recv_buffer, END_OF_HEADER) != nullptr);
/* We expect a HTTP/1.[01] reply */
if (strncmp(this->recv_buffer, HTTP_1_0, strlen(HTTP_1_0)) != 0 &&
@@ -122,7 +122,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
/* Get the length of the document to receive */
char *length = strcasestr(this->recv_buffer, CONTENT_LENGTH);
- if (length == NULL) return_error("[tcp/http] missing 'content-length' header");
+ if (length == nullptr) return_error("[tcp/http] missing 'content-length' header");
/* Skip the header */
length += strlen(CONTENT_LENGTH);
@@ -163,7 +163,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
/* Redirect to other URL */
char *uri = strcasestr(this->recv_buffer, LOCATION);
- if (uri == NULL) return_error("[tcp/http] missing 'location' header for redirect");
+ if (uri == nullptr) return_error("[tcp/http] missing 'location' header for redirect");
uri += strlen(LOCATION);
@@ -178,7 +178,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
if (ret != 0) return ret;
/* We've relinquished control of data now. */
- this->data = NULL;
+ this->data = nullptr;
/* Restore the header. */
*end_of_line = '\r';
@@ -195,22 +195,22 @@ int NetworkHTTPSocketHandler::HandleHeader()
/* static */ int NetworkHTTPSocketHandler::Connect(char *uri, HTTPCallback *callback, const char *data, int depth)
{
char *hname = strstr(uri, "://");
- if (hname == NULL) return_error("[tcp/http] invalid location");
+ if (hname == nullptr) return_error("[tcp/http] invalid location");
hname += 3;
char *url = strchr(hname, '/');
- if (url == NULL) return_error("[tcp/http] invalid location");
+ if (url == nullptr) return_error("[tcp/http] invalid location");
*url = '\0';
/* Fetch the hostname, and possible port number. */
- const char *company = NULL;
- const char *port = NULL;
+ const char *company = nullptr;
+ const char *port = nullptr;
ParseConnectionString(&company, &port, hname);
- if (company != NULL) return_error("[tcp/http] invalid hostname");
+ if (company != nullptr) return_error("[tcp/http] invalid hostname");
- NetworkAddress address(hname, port == NULL ? 80 : atoi(port));
+ NetworkAddress address(hname, port == nullptr ? 80 : atoi(port));
/* Restore the URL. */
*url = '/';
@@ -246,7 +246,7 @@ int NetworkHTTPSocketHandler::Receive()
if (res == 0) {
if (this->recv_length != 0) return -1;
- this->callback->OnReceiveData(NULL, 0);
+ this->callback->OnReceiveData(nullptr, 0);
return 0;
}
@@ -261,7 +261,7 @@ int NetworkHTTPSocketHandler::Receive()
char *end_of_header = strstr(this->recv_buffer, END_OF_HEADER);
this->recv_buffer[end] = prev;
- if (end_of_header == NULL) {
+ if (end_of_header == nullptr) {
if (read == lengthof(this->recv_buffer)) {
DEBUG(net, 0, "[tcp/http] header too big");
return -1;
@@ -308,7 +308,7 @@ int NetworkHTTPSocketHandler::Receive()
}
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
- int n = select(FD_SETSIZE, &read_fd, NULL, NULL, &tv);
+ int n = select(FD_SETSIZE, &read_fd, nullptr, nullptr, &tv);
if (n == -1) return;
for (auto iter = _http_connections.begin(); iter < _http_connections.end(); /* nothing */) {
diff --git a/src/network/core/tcp_http.h b/src/network/core/tcp_http.h
index 5a5cdd9f2..001942ffb 100644
--- a/src/network/core/tcp_http.h
+++ b/src/network/core/tcp_http.h
@@ -26,9 +26,9 @@ struct HTTPCallback {
/**
* We're receiving data.
- * @param data the received data, NULL when all data has been received.
+ * @param data the received data, nullptr when all data has been received.
* @param length the amount of received data, 0 when all data has been received.
- * @note When NULL is sent the HTTP socket handler is closed/freed.
+ * @note When nullptr is sent the HTTP socket handler is closed/freed.
*/
virtual void OnReceiveData(const char *data, size_t length) = 0;
@@ -68,7 +68,7 @@ public:
~NetworkHTTPSocketHandler();
static int Connect(char *uri, HTTPCallback *callback,
- const char *data = NULL, int depth = 0);
+ const char *data = nullptr, int depth = 0);
static void HTTPReceive();
};
@@ -91,7 +91,7 @@ public:
*/
NetworkHTTPContentConnecter(const NetworkAddress &address,
HTTPCallback *callback, const char *url,
- const char *data = NULL, int depth = 0) :
+ const char *data = nullptr, int depth = 0) :
TCPConnecter(address),
callback(callback),
url(stredup(url)),
@@ -116,7 +116,7 @@ public:
{
new NetworkHTTPSocketHandler(s, this->callback, this->address.GetHostname(), this->url, this->data, this->depth);
/* We've relinquished control of data now. */
- this->data = NULL;
+ this->data = nullptr;
}
};
diff --git a/src/network/core/tcp_listen.h b/src/network/core/tcp_listen.h
index 5668e48b2..28b6de8ac 100644
--- a/src/network/core/tcp_listen.h
+++ b/src/network/core/tcp_listen.h
@@ -116,7 +116,7 @@ public:
}
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
- if (select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv) < 0) return false;
+ if (select(FD_SETSIZE, &read_fd, &write_fd, nullptr, &tv) < 0) return false;
/* accept clients.. */
for (auto &s : sockets) {
diff --git a/src/network/core/udp.cpp b/src/network/core/udp.cpp
index 70bb0b9f0..853b19e1a 100644
--- a/src/network/core/udp.cpp
+++ b/src/network/core/udp.cpp
@@ -24,12 +24,12 @@
*/
NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind)
{
- if (bind != NULL) {
+ if (bind != nullptr) {
for (NetworkAddress &addr : *bind) {
this->bind.push_back(addr);
}
} else {
- /* As hostname NULL and port 0/NULL don't go well when
+ /* As hostname nullptr and port 0/nullptr don't go well when
* resolving it we need to add an address for each of
* the address families we support. */
this->bind.emplace_back(nullptr, 0, AF_INET);
@@ -176,13 +176,13 @@ void NetworkUDPSocketHandler::SendNetworkGameInfo(Packet *p, const NetworkGameIn
uint count = 0;
/* Count number of GRFs to send information about */
- for (c = info->grfconfig; c != NULL; c = c->next) {
+ for (c = info->grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) count++;
}
p->Send_uint8 (count); // Send number of GRFs
/* Send actual GRF Identifications */
- for (c = info->grfconfig; c != NULL; c = c->next) {
+ for (c = info->grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
}
}
diff --git a/src/network/core/udp.h b/src/network/core/udp.h
index fab232492..9ed2705ef 100644
--- a/src/network/core/udp.h
+++ b/src/network/core/udp.h
@@ -229,7 +229,7 @@ protected:
*/
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) { NOT_REACHED(); }
public:
- NetworkUDPSocketHandler(NetworkAddressList *bind = NULL);
+ NetworkUDPSocketHandler(NetworkAddressList *bind = nullptr);
/** On destructing of this class, the socket needs to be closed */
virtual ~NetworkUDPSocketHandler() { this->Close(); }
diff --git a/src/network/network.cpp b/src/network/network.cpp
index ab3884c56..0cc415192 100644
--- a/src/network/network.cpp
+++ b/src/network/network.cpp
@@ -57,7 +57,7 @@ bool _network_available; ///< is network mode available?
bool _network_dedicated; ///< are we a dedicated server?
bool _is_network_server; ///< Does this client wants to be a network-server?
NetworkServerGameInfo _network_game_info; ///< Information about our game.
-NetworkCompanyState *_network_company_states = NULL; ///< Statistics about some companies.
+NetworkCompanyState *_network_company_states = nullptr; ///< Statistics about some companies.
ClientID _network_own_client_id; ///< Our client identifier.
ClientID _redirect_console_to_client; ///< If not invalid, redirect the console output to a client.
bool _network_need_advertise; ///< Whether we need to advertise.
@@ -119,7 +119,7 @@ NetworkClientInfo::~NetworkClientInfo()
/**
* Return the CI given it's client-identifier
* @param client_id the ClientID to search for
- * @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
+ * @return return a pointer to the corresponding NetworkClientInfo struct or nullptr when not found
*/
/* static */ NetworkClientInfo *NetworkClientInfo::GetByClientID(ClientID client_id)
{
@@ -129,13 +129,13 @@ NetworkClientInfo::~NetworkClientInfo()
if (ci->client_id == client_id) return ci;
}
- return NULL;
+ return nullptr;
}
/**
* Return the client state given it's client-identifier
* @param client_id the ClientID to search for
- * @return return a pointer to the corresponding NetworkClientSocket struct or NULL when not found
+ * @return return a pointer to the corresponding NetworkClientSocket struct or nullptr when not found
*/
/* static */ ServerNetworkGameSocketHandler *ServerNetworkGameSocketHandler::GetByClientID(ClientID client_id)
{
@@ -145,7 +145,7 @@ NetworkClientInfo::~NetworkClientInfo()
if (cs->client_id == client_id) return cs;
}
- return NULL;
+ return nullptr;
}
byte NetworkSpectatorCount()
@@ -378,7 +378,7 @@ void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
char buffer[DRAW_STRING_BUFFER];
GetString(buffer, str, lastof(buffer));
- NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, NULL, buffer);
+ NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, nullptr, buffer);
break;
}
@@ -541,7 +541,7 @@ void NetworkClose(bool close_admins)
}
ServerNetworkGameSocketHandler::CloseListeners();
ServerNetworkAdminSocketHandler::CloseListeners();
- } else if (MyClient::my_client != NULL) {
+ } else if (MyClient::my_client != nullptr) {
MyClient::SendQuit();
MyClient::my_client->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
}
@@ -554,7 +554,7 @@ void NetworkClose(bool close_admins)
NetworkFreeLocalCommandQueue();
free(_network_company_states);
- _network_company_states = NULL;
+ _network_company_states = nullptr;
InitializeNetworkPools(close_admins);
}
@@ -608,8 +608,8 @@ void NetworkTCPQueryServer(NetworkAddress address)
void NetworkAddServer(const char *b)
{
if (*b != '\0') {
- const char *port = NULL;
- const char *company = NULL;
+ const char *port = nullptr;
+ const char *company = nullptr;
char host[NETWORK_HOSTNAME_LENGTH];
uint16 rport;
@@ -619,7 +619,7 @@ void NetworkAddServer(const char *b)
rport = NETWORK_DEFAULT_PORT;
ParseConnectionString(&company, &port, host);
- if (port != NULL) rport = atoi(port);
+ if (port != nullptr) rport = atoi(port);
NetworkUDPQueryServer(NetworkAddress(host, rport), true);
}
@@ -649,7 +649,7 @@ void NetworkRebuildHostList()
{
_network_host_list.clear();
- for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
+ for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
if (item->manually) _network_host_list.emplace_back(item->address.GetAddressAsString(false));
}
}
@@ -884,21 +884,21 @@ void NetworkGameLoop()
static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
static Date next_date = 0;
static uint32 next_date_fract;
- static CommandPacket *cp = NULL;
+ static CommandPacket *cp = nullptr;
static bool check_sync_state = false;
static uint32 sync_state[2];
- if (f == NULL && next_date == 0) {
+ if (f == nullptr && next_date == 0) {
DEBUG(net, 0, "Cannot open commands.log");
next_date = 1;
}
- while (f != NULL && !feof(f)) {
+ while (f != nullptr && !feof(f)) {
if (_date == next_date && _date_fract == next_date_fract) {
- if (cp != NULL) {
- NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, NULL, cp->text, cp->company);
+ if (cp != nullptr) {
+ NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, nullptr, cp->text, cp->company);
DEBUG(net, 0, "injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd));
free(cp);
- cp = NULL;
+ cp = nullptr;
}
if (check_sync_state) {
if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
@@ -912,16 +912,16 @@ void NetworkGameLoop()
}
}
- if (cp != NULL || check_sync_state) break;
+ if (cp != nullptr || check_sync_state) break;
char buff[4096];
- if (fgets(buff, lengthof(buff), f) == NULL) break;
+ if (fgets(buff, lengthof(buff), f) == nullptr) break;
char *p = buff;
/* Ignore the "[date time] " part of the message */
if (*p == '[') {
p = strchr(p, ']');
- if (p == NULL) break;
+ if (p == nullptr) break;
p += 2;
}
@@ -968,10 +968,10 @@ void NetworkGameLoop()
NOT_REACHED();
}
}
- if (f != NULL && feof(f)) {
+ if (f != nullptr && feof(f)) {
DEBUG(net, 0, "End of commands.log");
fclose(f);
- f = NULL;
+ f = nullptr;
}
#endif /* DEBUG_DUMP_COMMANDS */
if (_frame_counter >= _frame_counter_max) {
diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp
index 73ad0e192..9c5c43ab5 100644
--- a/src/network/network_admin.cpp
+++ b/src/network/network_admin.cpp
@@ -234,12 +234,12 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientJoin(ClientID clien
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientInfo(const NetworkClientSocket *cs, const NetworkClientInfo *ci)
{
/* Only send data when we're a proper client, not just someone trying to query the server. */
- if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
+ if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_INFO);
p->Send_uint32(ci->client_id);
- p->Send_string(cs == NULL ? "" : const_cast<NetworkAddress &>(cs->client_address).GetHostname());
+ p->Send_string(cs == nullptr ? "" : const_cast<NetworkAddress &>(cs->client_address).GetHostname());
p->Send_string(ci->client_name);
p->Send_uint8 (ci->client_lang);
p->Send_uint32(ci->join_date);
@@ -734,16 +734,16 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p)
/* The admin is requesting client info. */
const NetworkClientSocket *cs;
if (d1 == UINT32_MAX) {
- this->SendClientInfo(NULL, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
+ this->SendClientInfo(nullptr, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
FOR_ALL_CLIENT_SOCKETS(cs) {
this->SendClientInfo(cs, cs->GetInfo());
}
} else {
if (d1 == CLIENT_ID_SERVER) {
- this->SendClientInfo(NULL, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
+ this->SendClientInfo(nullptr, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
} else {
cs = NetworkClientSocket::GetByClientID((ClientID)d1);
- if (cs != NULL) this->SendClientInfo(cs, cs->GetInfo());
+ if (cs != nullptr) this->SendClientInfo(cs, cs->GetInfo());
}
}
break;
@@ -757,7 +757,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p)
}
} else {
company = Company::GetIfValid(d1);
- if (company != NULL) this->SendCompanyInfo(company);
+ if (company != nullptr) this->SendCompanyInfo(company);
}
break;
@@ -884,7 +884,7 @@ void NetworkAdminClientError(ClientID client_id, NetworkErrorCode error_code)
*/
void NetworkAdminCompanyInfo(const Company *company, bool new_company)
{
- if (company == NULL) {
+ if (company == nullptr) {
DEBUG(net, 1, "[admin] Empty company given for update");
return;
}
@@ -906,7 +906,7 @@ void NetworkAdminCompanyInfo(const Company *company, bool new_company)
*/
void NetworkAdminCompanyUpdate(const Company *company)
{
- if (company == NULL) return;
+ if (company == nullptr) return;
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
@@ -992,7 +992,7 @@ void NetworkAdminGameScript(const char *json)
*/
void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp)
{
- ClientID client_id = owner == NULL ? _network_own_client_id : owner->client_id;
+ ClientID client_id = owner == nullptr ? _network_own_client_id : owner->client_id;
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
diff --git a/src/network/network_chat_gui.cpp b/src/network/network_chat_gui.cpp
index 21607e9e8..e7e22db99 100644
--- a/src/network/network_chat_gui.cpp
+++ b/src/network/network_chat_gui.cpp
@@ -46,7 +46,7 @@ struct ChatMessage {
};
/* used for chat window */
-static ChatMessage *_chatmsg_list = NULL; ///< The actual chat message list.
+static ChatMessage *_chatmsg_list = nullptr; ///< The actual chat message list.
static bool _chatmessage_dirty = false; ///< Does the chat message need repainting?
static bool _chatmessage_visible = false; ///< Is a chat message visible.
static bool _chat_tab_completion_active; ///< Whether tab completion is active.
@@ -57,7 +57,7 @@ static uint MAX_CHAT_MESSAGES = 0; ///< The limit of chat messages to sho
* the left and pixels from the bottom. The height is the maximum height.
*/
static PointDimension _chatmsg_box;
-static uint8 *_chatmessage_backup = NULL; ///< Backup in case text is moved.
+static uint8 *_chatmessage_backup = nullptr; ///< Backup in case text is moved.
/**
* Count the chat messages.
@@ -360,7 +360,7 @@ struct NetworkChatWindow : public Window {
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -371,7 +371,7 @@ struct NetworkChatWindow : public Window {
static char *ChatTabCompletionFindText(char *buf)
{
char *p = strrchr(buf, ' ');
- if (p == NULL) return buf;
+ if (p == nullptr) return buf;
*p = '\0';
return p + 1;
@@ -400,7 +400,7 @@ struct NetworkChatWindow : public Window {
tb_buf = ChatTabCompletionFindText(pre_buf);
tb_len = strlen(tb_buf);
- while ((cur_name = ChatTabCompletionNextItem(&item)) != NULL) {
+ while ((cur_name = ChatTabCompletionNextItem(&item)) != nullptr) {
item++;
if (_chat_tab_completion_active) {
@@ -543,7 +543,7 @@ static const NWidgetPart _nested_chat_window_widgets[] = {
/** The description of the chat window. */
static WindowDesc _chat_window_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_SEND_NETWORK_MSG, WC_NONE,
0,
_nested_chat_window_widgets, lengthof(_nested_chat_window_widgets)
diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp
index 4dc5a8041..7ebbdef51 100644
--- a/src/network/network_client.cpp
+++ b/src/network/network_client.cpp
@@ -50,7 +50,7 @@ struct PacketReader : LoadFilter {
size_t read_bytes; ///< The total number of read bytes.
/** Initialise everything. */
- PacketReader() : LoadFilter(NULL), buf(NULL), bufe(NULL), block(NULL), written_bytes(0), read_bytes(0)
+ PacketReader() : LoadFilter(nullptr), buf(nullptr), bufe(nullptr), block(nullptr), written_bytes(0), read_bytes(0)
{
}
@@ -143,9 +143,9 @@ void ClientNetworkEmergencySave()
* Create a new socket for the client side of the game connection.
* @param s The socket to connect with.
*/
-ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(NULL), status(STATUS_INACTIVE)
+ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(nullptr), status(STATUS_INACTIVE)
{
- assert(ClientNetworkGameSocketHandler::my_client == NULL);
+ assert(ClientNetworkGameSocketHandler::my_client == nullptr);
ClientNetworkGameSocketHandler::my_client = this;
}
@@ -153,7 +153,7 @@ ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : Netwo
ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler()
{
assert(ClientNetworkGameSocketHandler::my_client == this);
- ClientNetworkGameSocketHandler::my_client = NULL;
+ ClientNetworkGameSocketHandler::my_client = nullptr;
delete this->savegame;
}
@@ -301,7 +301,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
/** Our client's connection. */
-ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = NULL;
+ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = nullptr;
/** Last frame we performed an ack. */
static uint32 last_ack_frame;
@@ -320,9 +320,9 @@ static uint8 _network_server_max_spectators;
CompanyID _network_join_as;
/** Login password from -p argument */
-const char *_network_join_server_password = NULL;
+const char *_network_join_server_password = nullptr;
/** Company password from -P argument */
-const char *_network_join_company_password = NULL;
+const char *_network_join_company_password = nullptr;
/** Make sure the server ID length is the same as a md5 hash. */
assert_compile(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
@@ -533,7 +533,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, co
*/
bool ClientNetworkGameSocketHandler::IsConnected()
{
- return my_client != NULL && my_client->status == STATUS_ACTIVE;
+ return my_client != nullptr && my_client->status == STATUS_ACTIVE;
}
@@ -542,7 +542,7 @@ bool ClientNetworkGameSocketHandler::IsConnected()
* DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
************/
-extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
+extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
{
@@ -576,7 +576,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Pa
if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
- if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
+ if (company_info == nullptr) return NETWORK_RECV_STATUS_CLOSE_QUERY;
p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
company_info->inaugurated_year = p->Recv_uint32();
@@ -619,7 +619,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci != NULL) {
+ if (ci != nullptr) {
if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
/* Client name changed, display the change */
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
@@ -714,7 +714,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(P
/* Check whether we know this GRF */
const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
- if (f == NULL) {
+ if (f == nullptr) {
/* We do not know this GRF, bail out of initialization */
char buf[sizeof(c.md5sum) * 2 + 1];
md5sumToString(buf, lastof(buf), c.md5sum);
@@ -800,7 +800,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packe
if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_MAP;
- if (this->savegame != NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
+ if (this->savegame != nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->savegame = new PacketReader();
@@ -818,7 +818,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packe
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p)
{
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
- if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
+ if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_join_bytes_total = p->Recv_uint32();
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
@@ -829,7 +829,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p)
{
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
- if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
+ if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
/* We are still receiving data, put it to the file */
this->savegame->AddPacket(p);
@@ -843,7 +843,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *p)
{
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
- if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
+ if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
@@ -856,12 +856,12 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
* game, which would cause us to free this->savegame twice.
*/
LoadFilter *lf = this->savegame;
- this->savegame = NULL;
+ this->savegame = nullptr;
lf->Reset();
/* The map is done downloading, load it */
ClearErrorMessages();
- bool load_success = SafeLoad(NULL, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
+ bool load_success = SafeLoad(nullptr, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
/* Long savegame loads shouldn't affect the lag calculation! */
this->last_packet = _realtime_tick;
@@ -887,7 +887,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
* the server will give us a client-id and let us in */
_network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
ShowJoinStatusWindow();
- NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
+ NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company);
}
} else {
/* take control over an existing company */
@@ -952,7 +952,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet
cp.frame = p->Recv_uint32();
cp.my_cmd = p->Recv_bool();
- if (err != NULL) {
+ if (err != nullptr) {
IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
@@ -967,7 +967,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
- const NetworkClientInfo *ci = NULL, *ci_to;
+ const NetworkClientInfo *ci = nullptr, *ci_to;
NetworkAction action = (NetworkAction)p->Recv_uint8();
ClientID client_id = (ClientID)p->Recv_uint32();
@@ -976,7 +976,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
int64 data = p->Recv_uint64();
ci_to = NetworkClientInfo::GetByClientID(client_id);
- if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
+ if (ci_to == nullptr) return NETWORK_RECV_STATUS_OKAY;
/* Did we initiate the action locally? */
if (self_send) {
@@ -1009,7 +1009,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
ci = ci_to;
}
- if (ci != NULL) {
+ if (ci != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
}
return NETWORK_RECV_STATUS_OKAY;
@@ -1022,8 +1022,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Pack
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci != NULL) {
- NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
+ if (ci != nullptr) {
+ NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
delete ci;
}
@@ -1039,8 +1039,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci != NULL) {
- NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
+ if (ci != nullptr) {
+ NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
delete ci;
} else {
DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
@@ -1059,7 +1059,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci != NULL) {
+ if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
}
@@ -1129,7 +1129,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
/* Just make sure we do not try to use a client_index that does not exist */
- if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
+ if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
/* if not valid player, force spectator, else check player exists */
if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
@@ -1253,7 +1253,7 @@ void NetworkUpdateClientName()
{
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
- if (ci == NULL) return;
+ if (ci == nullptr) return;
/* Don't change the name if it is the same as the old name */
if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
diff --git a/src/network/network_command.cpp b/src/network/network_command.cpp
index 51317288e..472215a63 100644
--- a/src/network/network_command.cpp
+++ b/src/network/network_command.cpp
@@ -21,7 +21,7 @@
/** Table with all the callbacks we'll use for conversion*/
static CommandCallback * const _callback_table[] = {
- /* 0x00 */ NULL,
+ /* 0x00 */ nullptr,
/* 0x01 */ CcBuildPrimaryVehicle,
/* 0x02 */ CcBuildAirport,
/* 0x03 */ CcBuildBridge,
@@ -60,8 +60,8 @@ void CommandQueue::Append(CommandPacket *p)
{
CommandPacket *add = MallocT<CommandPacket>(1);
*add = *p;
- add->next = NULL;
- if (this->first == NULL) {
+ add->next = nullptr;
+ if (this->first == nullptr) {
this->first = add;
} else {
this->last->next = add;
@@ -79,15 +79,15 @@ CommandPacket *CommandQueue::Pop(bool ignore_paused)
{
CommandPacket **prev = &this->first;
CommandPacket *ret = this->first;
- CommandPacket *prev_item = NULL;
+ CommandPacket *prev_item = nullptr;
if (ignore_paused && _pause_mode != PM_UNPAUSED) {
- while (ret != NULL && !IsCommandAllowedWhilePaused(ret->cmd)) {
+ while (ret != nullptr && !IsCommandAllowedWhilePaused(ret->cmd)) {
prev_item = ret;
prev = &ret->next;
ret = ret->next;
}
}
- if (ret != NULL) {
+ if (ret != nullptr) {
if (ret == this->last) this->last = prev_item;
*prev = ret->next;
this->count--;
@@ -104,17 +104,17 @@ CommandPacket *CommandQueue::Peek(bool ignore_paused)
{
if (!ignore_paused || _pause_mode == PM_UNPAUSED) return this->first;
- for (CommandPacket *p = this->first; p != NULL; p = p->next) {
+ for (CommandPacket *p = this->first; p != nullptr; p = p->next) {
if (IsCommandAllowedWhilePaused(p->cmd)) return p;
}
- return NULL;
+ return nullptr;
}
/** Free everything that is in the queue. */
void CommandQueue::Free()
{
CommandPacket *cp;
- while ((cp = this->Pop()) != NULL) {
+ while ((cp = this->Pop()) != nullptr) {
free(cp);
}
assert(this->count == 0);
@@ -147,7 +147,7 @@ void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, Comman
c.cmd = cmd;
c.callback = callback;
- strecpy(c.text, (text != NULL) ? text : "", lastof(c.text));
+ strecpy(c.text, (text != nullptr) ? text : "", lastof(c.text));
if (_network_server) {
/* If we are the server, we queue the command in our 'special' queue.
@@ -180,7 +180,7 @@ void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, Comman
*/
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
{
- for (CommandPacket *p = _local_execution_queue.Peek(); p != NULL; p = p->next) {
+ for (CommandPacket *p = _local_execution_queue.Peek(); p != nullptr; p = p->next) {
CommandPacket c = *p;
c.callback = 0;
cs->outgoing_queue.Append(&c);
@@ -197,7 +197,7 @@ void NetworkExecuteLocalCommandQueue()
CommandQueue &queue = (_network_server ? _local_execution_queue : ClientNetworkGameSocketHandler::my_client->incoming_queue);
CommandPacket *cp;
- while ((cp = queue.Peek()) != NULL) {
+ while ((cp = queue.Peek()) != nullptr) {
/* The queue is always in order, which means
* that the first element will be executed first. */
if (_frame_counter < cp->frame) break;
@@ -245,13 +245,13 @@ static void DistributeCommandPacket(CommandPacket &cp, const NetworkClientSocket
if (cs->status >= NetworkClientSocket::STATUS_MAP) {
/* Callbacks are only send back to the client who sent them in the
* first place. This filters that out. */
- cp.callback = (cs != owner) ? NULL : callback;
+ cp.callback = (cs != owner) ? nullptr : callback;
cp.my_cmd = (cs == owner);
cs->outgoing_queue.Append(&cp);
}
}
- cp.callback = (cs != owner) ? NULL : callback;
+ cp.callback = (cs != owner) ? nullptr : callback;
cp.my_cmd = (cs == owner);
_local_execution_queue.Append(&cp);
}
@@ -271,7 +271,7 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne
#endif
CommandPacket *cp;
- while (--to_go >= 0 && (cp = queue->Pop(true)) != NULL) {
+ while (--to_go >= 0 && (cp = queue->Pop(true)) != nullptr) {
DistributeCommandPacket(*cp, owner);
NetworkAdminCmdLogging(owner, cp);
free(cp);
@@ -282,7 +282,7 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne
void NetworkDistributeCommands()
{
/* First send the server's commands. */
- DistributeQueue(&_local_wait_queue, NULL);
+ DistributeQueue(&_local_wait_queue, nullptr);
/* Then send the queues of the others. */
NetworkClientSocket *cs;
@@ -295,7 +295,7 @@ void NetworkDistributeCommands()
* Receives a command from the network.
* @param p the packet to read from.
* @param cp the struct to write the data to.
- * @return an error message. When NULL there has been no error.
+ * @return an error message. When nullptr there has been no error.
*/
const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *cp)
{
@@ -314,7 +314,7 @@ const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *c
if (callback >= lengthof(_callback_table)) return "invalid callback";
cp->callback = _callback_table[callback];
- return NULL;
+ return nullptr;
}
/**
@@ -338,7 +338,7 @@ void NetworkGameSocketHandler::SendCommand(Packet *p, const CommandPacket *cp)
if (callback == lengthof(_callback_table)) {
DEBUG(net, 0, "Unknown callback. (Pointer: %p) No callback sent", cp->callback);
- callback = 0; // _callback_table[0] == NULL
+ callback = 0; // _callback_table[0] == nullptr
}
p->Send_uint8 (callback);
}
diff --git a/src/network/network_content.cpp b/src/network/network_content.cpp
index 168ecd429..8768d314e 100644
--- a/src/network/network_content.cpp
+++ b/src/network/network_content.cpp
@@ -35,7 +35,7 @@ ClientNetworkContentSocketHandler _network_content_client;
/** Wrapper function for the HasProc */
static bool HasGRFConfig(const ContentInfo *ci, bool md5sum)
{
- return FindGRFConfig(BSWAP32(ci->unique_id), md5sum ? FGCM_EXACT : FGCM_ANY, md5sum ? ci->md5sum : NULL) != NULL;
+ return FindGRFConfig(BSWAP32(ci->unique_id), md5sum ? FGCM_EXACT : FGCM_ANY, md5sum ? ci->md5sum : nullptr) != nullptr;
}
/**
@@ -79,7 +79,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
}
/* Find the appropriate check function */
- HasProc proc = NULL;
+ HasProc proc = nullptr;
switch (ci->type) {
case CONTENT_TYPE_NEWGRF:
proc = HasGRFConfig;
@@ -122,7 +122,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
break;
}
- if (proc != NULL) {
+ if (proc != nullptr) {
if (proc(ci, true)) {
ci->state = ContentInfo::ALREADY_HERE;
} else {
@@ -241,7 +241,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(uint count, const Con
*/
void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bool send_md5sum)
{
- if (cv == NULL) return;
+ if (cv == nullptr) return;
this->Connect();
@@ -374,12 +374,12 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const Co
* @param ci the information to get the filename from
* @param compressed should the filename end with .gz?
* @return a statically allocated buffer with the filename or
- * NULL when no filename could be made.
+ * nullptr when no filename could be made.
*/
static char *GetFullFilename(const ContentInfo *ci, bool compressed)
{
Subdirectory dir = GetContentInfoSubDir(ci->type);
- if (dir == NO_DIRECTORY) return NULL;
+ if (dir == NO_DIRECTORY) return nullptr;
static char buf[MAX_PATH];
FioGetFullPath(buf, lastof(buf), SP_AUTODOWNLOAD_DIR, dir, ci->filename);
@@ -400,14 +400,14 @@ static bool GunzipFile(const ContentInfo *ci)
/* Need to open the file with fopen() to support non-ASCII on Windows. */
FILE *ftmp = fopen(GetFullFilename(ci, true), "rb");
- if (ftmp == NULL) return false;
+ if (ftmp == nullptr) return false;
/* Duplicate the handle, and close the FILE*, to avoid double-closing the handle later. */
gzFile fin = gzdopen(dup(fileno(ftmp)), "rb");
fclose(ftmp);
FILE *fout = fopen(GetFullFilename(ci, false), "wb");
- if (fin == NULL || fout == NULL) {
+ if (fin == nullptr || fout == nullptr) {
ret = false;
} else {
byte buff[8192];
@@ -441,8 +441,8 @@ static bool GunzipFile(const ContentInfo *ci)
}
}
- if (fin != NULL) gzclose(fin);
- if (fout != NULL) fclose(fout);
+ if (fin != nullptr) gzclose(fin);
+ if (fout != nullptr) fclose(fout);
return ret;
#else
@@ -452,7 +452,7 @@ static bool GunzipFile(const ContentInfo *ci)
bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p)
{
- if (this->curFile == NULL) {
+ if (this->curFile == nullptr) {
delete this->curInfo;
/* When we haven't opened a file this must be our first packet with metadata. */
this->curInfo = new ContentInfo;
@@ -473,7 +473,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p)
ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
this->Close();
fclose(this->curFile);
- this->curFile = NULL;
+ this->curFile = nullptr;
return false;
}
@@ -494,14 +494,14 @@ bool ClientNetworkContentSocketHandler::BeforeDownload()
{
if (!this->curInfo->IsValid()) {
delete this->curInfo;
- this->curInfo = NULL;
+ this->curInfo = nullptr;
return false;
}
if (this->curInfo->filesize != 0) {
/* The filesize is > 0, so we are going to download it */
const char *filename = GetFullFilename(this->curInfo, true);
- if (filename == NULL || (this->curFile = fopen(filename, "wb")) == NULL) {
+ if (filename == nullptr || (this->curFile = fopen(filename, "wb")) == nullptr) {
/* Unless that fails of course... */
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
@@ -520,7 +520,7 @@ void ClientNetworkContentSocketHandler::AfterDownload()
/* We read nothing; that's our marker for end-of-stream.
* Now gunzip the tar and make it known. */
fclose(this->curFile);
- this->curFile = NULL;
+ this->curFile = nullptr;
if (GunzipFile(this->curInfo)) {
unlink(GetFullFilename(this->curInfo, true));
@@ -554,25 +554,25 @@ void ClientNetworkContentSocketHandler::OnFailure()
this->http_response.shrink_to_fit();
this->http_response_index = -2;
- if (this->curFile != NULL) {
+ if (this->curFile != nullptr) {
/* Revert the download progress when we are going for the old system. */
long size = ftell(this->curFile);
if (size > 0) this->OnDownloadProgress(this->curInfo, (int)-size);
fclose(this->curFile);
- this->curFile = NULL;
+ this->curFile = nullptr;
}
}
void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t length)
{
- assert(data == NULL || length != 0);
+ assert(data == nullptr || length != 0);
/* Ignore any latent data coming from a connection we closed. */
if (this->http_response_index == -2) return;
if (this->http_response_index == -1) {
- if (data != NULL) {
+ if (data != nullptr) {
/* Append the rest of the response. */
memcpy(grow(this->http_response, (uint)length), data, length);
return;
@@ -585,7 +585,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
}
}
- if (data != NULL) {
+ if (data != nullptr) {
/* We have data, so write it to the file. */
if (fwrite(data, 1, length, this->curFile) != length) {
/* Writing failed somehow, let try via the old method. */
@@ -598,7 +598,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
return;
}
- if (this->curFile != NULL) {
+ if (this->curFile != nullptr) {
/* We've finished downloading a file. */
this->AfterDownload();
}
@@ -616,7 +616,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
this->curInfo = new ContentInfo;
/** Check p for not being null and return calling OnFailure if that's not the case. */
-#define check_not_null(p) { if ((p) == NULL) { this->OnFailure(); return; } }
+#define check_not_null(p) { if ((p) == nullptr) { this->OnFailure(); return; } }
/** Check p for not being null and then terminate, or return calling OnFailure. */
#define check_and_terminate(p) { check_not_null(p); *(p) = '\0'; }
@@ -695,8 +695,8 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
ClientNetworkContentSocketHandler::ClientNetworkContentSocketHandler() :
NetworkContentSocketHandler(),
http_response_index(-2),
- curFile(NULL),
- curInfo(NULL),
+ curFile(nullptr),
+ curInfo(nullptr),
isConnecting(false),
lastActivity(_realtime_tick)
{
@@ -706,7 +706,7 @@ ClientNetworkContentSocketHandler::ClientNetworkContentSocketHandler() :
ClientNetworkContentSocketHandler::~ClientNetworkContentSocketHandler()
{
delete this->curInfo;
- if (this->curFile != NULL) fclose(this->curFile);
+ if (this->curFile != nullptr) fclose(this->curFile);
for (ContentInfo *ci : this->infos) delete ci;
}
@@ -798,14 +798,14 @@ void ClientNetworkContentSocketHandler::DownloadContentInfo(ContentID cid)
/**
* Get the content info based on a ContentID
* @param cid the ContentID to search for
- * @return the ContentInfo or NULL if not found
+ * @return the ContentInfo or nullptr if not found
*/
ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid)
{
for (ContentInfo *ci : this->infos) {
if (ci->id == cid) return ci;
}
- return NULL;
+ return nullptr;
}
@@ -816,7 +816,7 @@ ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid)
void ClientNetworkContentSocketHandler::Select(ContentID cid)
{
ContentInfo *ci = this->GetContent(cid);
- if (ci == NULL || ci->state != ContentInfo::UNSELECTED) return;
+ if (ci == nullptr || ci->state != ContentInfo::UNSELECTED) return;
ci->state = ContentInfo::SELECTED;
this->CheckDependencyState(ci);
@@ -829,7 +829,7 @@ void ClientNetworkContentSocketHandler::Select(ContentID cid)
void ClientNetworkContentSocketHandler::Unselect(ContentID cid)
{
ContentInfo *ci = this->GetContent(cid);
- if (ci == NULL || !ci->IsSelected()) return;
+ if (ci == nullptr || !ci->IsSelected()) return;
ci->state = ContentInfo::UNSELECTED;
this->CheckDependencyState(ci);
@@ -937,7 +937,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
* selected and thus can unselect when a dependency is removed. */
for (uint i = 0; i < ci->dependency_count; i++) {
ContentInfo *c = this->GetContent(ci->dependencies[i]);
- if (c == NULL) {
+ if (c == nullptr) {
this->DownloadContentInfo(ci->dependencies[i]);
} else if (c->state == ContentInfo::UNSELECTED) {
c->state = ContentInfo::AUTOSELECTED;
@@ -963,7 +963,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
for (uint i = 0; i < ci->dependency_count; i++) {
const ContentInfo *c = this->GetContent(ci->dependencies[i]);
- if (c == NULL) {
+ if (c == nullptr) {
DownloadContentInfo(ci->dependencies[i]);
continue;
}
@@ -1068,7 +1068,7 @@ void ClientNetworkContentSocketHandler::OnDownloadProgress(const ContentInfo *ci
void ClientNetworkContentSocketHandler::OnDownloadComplete(ContentID cid)
{
ContentInfo *ci = this->GetContent(cid);
- if (ci != NULL) {
+ if (ci != nullptr) {
ci->state = ContentInfo::ALREADY_HERE;
}
diff --git a/src/network/network_content.h b/src/network/network_content.h
index fb81925d2..b65321e0f 100644
--- a/src/network/network_content.h
+++ b/src/network/network_content.h
@@ -147,7 +147,7 @@ public:
extern ClientNetworkContentSocketHandler _network_content_client;
-void ShowNetworkContentListWindow(ContentVector *cv = NULL, ContentType type1 = CONTENT_TYPE_END, ContentType type2 = CONTENT_TYPE_END);
+void ShowNetworkContentListWindow(ContentVector *cv = nullptr, ContentType type1 = CONTENT_TYPE_END, ContentType type2 = CONTENT_TYPE_END);
void ShowMissingContentWindow(const struct GRFConfig *list);
diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp
index b2e0dd795..f3eb597a6 100644
--- a/src/network/network_content_gui.cpp
+++ b/src/network/network_content_gui.cpp
@@ -95,7 +95,7 @@ static const NWidgetPart _nested_network_content_download_status_window_widgets[
/** Window description for the download window */
static WindowDesc _network_content_download_status_window_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_MODAL,
_nested_network_content_download_status_window_widgets, lengthof(_nested_network_content_download_status_window_widgets)
@@ -238,7 +238,7 @@ public:
break;
case CONTENT_TYPE_NEWGRF:
- ScanNewGRFFiles(NULL);
+ ScanNewGRFFiles(nullptr);
break;
case CONTENT_TYPE_SCENARIO:
@@ -480,7 +480,7 @@ class NetworkContentListWindow : public Window, ContentCallback {
}
/* previously selected item not in list anymore */
- this->selected = NULL;
+ this->selected = nullptr;
this->list_pos = 0;
}
@@ -501,7 +501,7 @@ class NetworkContentListWindow : public Window, ContentCallback {
/** Make sure that the currently selected content info is within the visible part of the matrix */
void ScrollToSelected()
{
- if (this->selected == NULL) return;
+ if (this->selected == nullptr) return;
this->vscroll->ScrollTowards(this->list_pos);
}
@@ -521,7 +521,7 @@ public:
Window(desc),
auto_select(select_all),
filter_editbox(EDITBOX_MAX_SIZE),
- selected(NULL),
+ selected(nullptr),
list_pos(0)
{
this->checkbox_size = maxdim(maxdim(GetSpriteSize(SPR_BOX_EMPTY), GetSpriteSize(SPR_BOX_CHECKED)), GetSpriteSize(SPR_BLOT));
@@ -685,7 +685,7 @@ public:
SetDParam(0, this->filesize_sum);
DrawString(r.left + DETAIL_LEFT, r.right - DETAIL_RIGHT, r.bottom - FONT_HEIGHT_NORMAL - WD_PAR_VSEP_NORMAL, STR_CONTENT_TOTAL_DOWNLOAD_SIZE);
- if (this->selected == NULL) return;
+ if (this->selected == nullptr) return;
/* And fill the rest of the details when there's information to place there */
DrawStringMultiLine(r.left + WD_INSET_LEFT, r.right - WD_INSET_RIGHT, r.top + DETAIL_TITLE_HEIGHT / 2, r.top + DETAIL_TITLE_HEIGHT, STR_CONTENT_DETAIL_SUBTITLE_UNSELECTED + this->selected->state, TC_FROMSTRING, SA_CENTER);
@@ -779,7 +779,7 @@ public:
void OnClick(Point pt, int widget, int click_count) override
{
if (widget >= WID_NCL_TEXTFILE && widget < WID_NCL_TEXTFILE + TFT_END) {
- if (this->selected == NULL || this->selected->state != ContentInfo::ALREADY_HERE) return;
+ if (this->selected == nullptr || this->selected->state != ContentInfo::ALREADY_HERE) return;
ShowContentTextfileWindow((TextfileType)(widget - WID_NCL_TEXTFILE), this->selected);
return;
@@ -842,14 +842,14 @@ public:
break;
case WID_NCL_OPEN_URL:
- if (this->selected != NULL) {
+ if (this->selected != nullptr) {
extern void OpenBrowser(const char *url);
OpenBrowser(this->selected->url);
}
break;
case WID_NCL_DOWNLOAD:
- if (BringWindowToFrontById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) == NULL) new NetworkContentDownloadStatusWindow();
+ if (BringWindowToFrontById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) == nullptr) new NetworkContentDownloadStatusWindow();
break;
case WID_NCL_SEARCH_EXTERNAL:
@@ -893,7 +893,7 @@ public:
case WKC_SPACE:
case WKC_RETURN:
if (keycode == WKC_RETURN || !IsWidgetFocused(WID_NCL_FILTER)) {
- if (this->selected != NULL) {
+ if (this->selected != nullptr) {
_network_content_client.ToggleSelectedState(this->selected);
this->content.ForceResort();
this->InvalidateData();
@@ -1005,13 +1005,13 @@ public:
}
/* If data == 2 then the status window caused this OnInvalidate */
- this->SetWidgetDisabledState(WID_NCL_DOWNLOAD, this->filesize_sum == 0 || (FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) != NULL && data != 2));
+ this->SetWidgetDisabledState(WID_NCL_DOWNLOAD, this->filesize_sum == 0 || (FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) != nullptr && data != 2));
this->SetWidgetDisabledState(WID_NCL_UNSELECT, this->filesize_sum == 0);
this->SetWidgetDisabledState(WID_NCL_SELECT_ALL, !show_select_all);
this->SetWidgetDisabledState(WID_NCL_SELECT_UPDATE, !show_select_upgrade);
- this->SetWidgetDisabledState(WID_NCL_OPEN_URL, this->selected == NULL || StrEmpty(this->selected->url));
+ this->SetWidgetDisabledState(WID_NCL_OPEN_URL, this->selected == nullptr || StrEmpty(this->selected->url));
for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
- this->SetWidgetDisabledState(WID_NCL_TEXTFILE + tft, this->selected == NULL || this->selected->state != ContentInfo::ALREADY_HERE || this->selected->GetTextfile(tft) == NULL);
+ this->SetWidgetDisabledState(WID_NCL_TEXTFILE + tft, this->selected == nullptr || this->selected->state != ContentInfo::ALREADY_HERE || this->selected->GetTextfile(tft) == nullptr);
}
this->GetWidget<NWidgetCore>(WID_NCL_CANCEL)->widget_data = this->filesize_sum == 0 ? STR_AI_SETTINGS_CLOSE : STR_AI_LIST_CANCEL;
@@ -1131,7 +1131,7 @@ static WindowDesc _network_content_list_desc(
/**
* Show the content list window with a given set of content
- * @param cv the content to show, or NULL when it has to search for itself
+ * @param cv the content to show, or nullptr when it has to search for itself
* @param type1 the first type to (only) show or #CONTENT_TYPE_END to show all.
* @param type2 the second type to (only) show in addition to type1. If type2 is != #CONTENT_TYPE_END, then also type1 should be != #CONTENT_TYPE_END.
* If type2 != #CONTENT_TYPE_END, then type1 != type2 must be true.
@@ -1141,7 +1141,7 @@ void ShowNetworkContentListWindow(ContentVector *cv, ContentType type1, ContentT
#if defined(WITH_ZLIB)
std::bitset<CONTENT_TYPE_END> types;
_network_content_client.Clear();
- if (cv == NULL) {
+ if (cv == nullptr) {
assert(type1 != CONTENT_TYPE_END || type2 == CONTENT_TYPE_END);
assert(type1 == CONTENT_TYPE_END || type1 != type2);
_network_content_client.RequestContentList(type1);
@@ -1154,11 +1154,11 @@ void ShowNetworkContentListWindow(ContentVector *cv, ContentType type1, ContentT
}
DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST);
- new NetworkContentListWindow(&_network_content_list_desc, cv != NULL, types);
+ new NetworkContentListWindow(&_network_content_list_desc, cv != nullptr, types);
#else
ShowErrorMessage(STR_CONTENT_NO_ZLIB, STR_CONTENT_NO_ZLIB_SUB, WL_ERROR);
/* Connection failed... clean up the mess */
- if (cv != NULL) {
+ if (cv != nullptr) {
for (ContentInfo *ci : *cv) delete ci;
}
#endif /* WITH_ZLIB */
diff --git a/src/network/network_func.h b/src/network/network_func.h
index 9adbb6e60..5cf01d32c 100644
--- a/src/network/network_func.h
+++ b/src/network/network_func.h
@@ -51,7 +51,7 @@ void NetworkPopulateCompanyStats(NetworkCompanyStats *stats);
void NetworkUpdateClientInfo(ClientID client_id);
void NetworkClientsToSpectators(CompanyID cid);
-void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password = NULL, const char *join_company_password = NULL);
+void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password = nullptr, const char *join_company_password = nullptr);
void NetworkClientRequestMove(CompanyID company, const char *pass = "");
void NetworkClientSendRcon(const char *password, const char *command);
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data = 0);
diff --git a/src/network/network_gamelist.cpp b/src/network/network_gamelist.cpp
index e9fc5f943..3b3afcb80 100644
--- a/src/network/network_gamelist.cpp
+++ b/src/network/network_gamelist.cpp
@@ -22,10 +22,10 @@
#include "../safeguards.h"
-NetworkGameList *_network_game_list = NULL;
+NetworkGameList *_network_game_list = nullptr;
/** The games to insert when the GUI thread has time for us. */
-static std::atomic<NetworkGameList *> _network_game_delayed_insertion_list(NULL);
+static std::atomic<NetworkGameList *> _network_game_delayed_insertion_list(nullptr);
/**
* Add a new item to the linked gamelist, but do it delayed in the next tick
@@ -43,12 +43,12 @@ static void NetworkGameListHandleDelayedInsert()
{
while (true) {
NetworkGameList *ins_item = _network_game_delayed_insertion_list.load(std::memory_order_relaxed);
- while (ins_item != NULL && !_network_game_delayed_insertion_list.compare_exchange_weak(ins_item, ins_item->next, std::memory_order_acq_rel)) {}
- if (ins_item == NULL) break; // No item left.
+ while (ins_item != nullptr && !_network_game_delayed_insertion_list.compare_exchange_weak(ins_item, ins_item->next, std::memory_order_acq_rel)) {}
+ if (ins_item == nullptr) break; // No item left.
NetworkGameList *item = NetworkGameListAddItem(ins_item->address);
- if (item != NULL) {
+ if (item != nullptr) {
if (StrEmpty(item->info.server_name)) {
ClearGRFConfigList(&item->info.grfconfig);
memset(&item->info, 0, sizeof(item->info));
@@ -78,22 +78,22 @@ NetworkGameList *NetworkGameListAddItem(NetworkAddress address)
if (StrEmpty(hostname) ||
strcmp(hostname, "0.0.0.0") == 0 ||
strcmp(hostname, "::") == 0) {
- return NULL;
+ return nullptr;
}
NetworkGameList *item, *prev_item;
- prev_item = NULL;
- for (item = _network_game_list; item != NULL; item = item->next) {
+ prev_item = nullptr;
+ for (item = _network_game_list; item != nullptr; item = item->next) {
if (item->address == address) return item;
prev_item = item;
}
item = CallocT<NetworkGameList>(1);
- item->next = NULL;
+ item->next = nullptr;
item->address = address;
- if (prev_item == NULL) {
+ if (prev_item == nullptr) {
_network_game_list = item;
} else {
prev_item->next = item;
@@ -111,10 +111,10 @@ NetworkGameList *NetworkGameListAddItem(NetworkAddress address)
*/
void NetworkGameListRemoveItem(NetworkGameList *remove)
{
- NetworkGameList *prev_item = NULL;
- for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
+ NetworkGameList *prev_item = nullptr;
+ for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
if (remove == item) {
- if (prev_item == NULL) {
+ if (prev_item == nullptr) {
_network_game_list = remove->next;
} else {
prev_item->next = remove->next;
@@ -123,7 +123,7 @@ void NetworkGameListRemoveItem(NetworkGameList *remove)
/* Remove GRFConfig information */
ClearGRFConfigList(&remove->info.grfconfig);
free(remove);
- remove = NULL;
+ remove = nullptr;
DEBUG(net, 4, "[gamelist] removed server from list");
NetworkRebuildHostList();
@@ -148,7 +148,7 @@ void NetworkGameListRequery()
if (++requery_cnt < REQUERY_EVERY_X_GAMELOOPS) return;
requery_cnt = 0;
- for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
+ for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
item->retries++;
if (item->retries < REFRESH_GAMEINFO_X_REQUERIES && (item->online || item->retries >= MAX_GAME_LIST_REQUERY_COUNT)) continue;
@@ -165,15 +165,15 @@ void NetworkGameListRequery()
*/
void NetworkAfterNewGRFScan()
{
- for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
+ for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
/* Reset compatibility state */
item->info.compatible = item->info.version_compatible;
- for (GRFConfig *c = item->info.grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = item->info.grfconfig; c != nullptr; c = c->next) {
assert(HasBit(c->flags, GCF_COPY));
const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
- if (f == NULL) {
+ if (f == nullptr) {
/* Don't know the GRF, so mark game incompatible and the (possibly)
* already resolved name for this GRF (another server has sent the
* name of the GRF already. */
diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp
index fc5822641..2e85f7966 100644
--- a/src/network/network_gui.cpp
+++ b/src/network/network_gui.cpp
@@ -129,13 +129,13 @@ public:
this->resize_y = 0; // We never resize in this direction
/* First initialise some variables... */
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->SetupSmallestSize(w, init_array);
this->smallest_y = max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
}
/* ... then in a second pass make sure the 'current' sizes are set. Won't change for most widgets. */
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->current_x = child_wid->smallest_x;
child_wid->current_y = this->smallest_y;
}
@@ -172,7 +172,7 @@ public:
uint position = 0; // Place to put next child relative to origin of the container.
uint i = rtl ? lengthof(this->visible) - 1 : 0;
child_wid = rtl ? this->tail : this->head;
- while (child_wid != NULL) {
+ while (child_wid != nullptr) {
if (this->visible[i]) {
child_wid->AssignSizePosition(sizing, x + position, y, child_wid->current_x, this->current_y, rtl);
position += child_wid->current_x;
@@ -186,7 +186,7 @@ public:
void Draw(const Window *w) override
{
int i = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (!this->visible[i++]) continue;
child_wid->Draw(w);
@@ -195,15 +195,15 @@ public:
NWidgetCore *GetWidgetFromPos(int x, int y) override
{
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
int i = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (!this->visible[i++]) continue;
NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
- if (nwid != NULL) return nwid;
+ if (nwid != nullptr) return nwid;
}
- return NULL;
+ return nullptr;
}
/**
@@ -252,7 +252,7 @@ protected:
/* Create temporary array of games to use for listing */
this->servers.clear();
- for (NetworkGameList *ngl = _network_game_list; ngl != NULL; ngl = ngl->next) {
+ for (NetworkGameList *ngl = _network_game_list; ngl != nullptr; ngl = ngl->next) {
this->servers.push_back(ngl);
}
@@ -364,8 +364,8 @@ protected:
static bool CDECL NGameSearchFilter(NetworkGameList * const *item, StringFilter &sf)
{
- assert(item != NULL);
- assert((*item) != NULL);
+ assert(item != nullptr);
+ assert((*item) != nullptr);
sf.ResetState();
sf.AddLine((*item)->info.server_name);
@@ -460,7 +460,7 @@ public:
NetworkGameWindow(WindowDesc *desc) : Window(desc), name_editbox(NETWORK_CLIENT_NAME_LENGTH), filter_editbox(120)
{
this->list_pos = SLP_INVALID;
- this->server = NULL;
+ this->server = nullptr;
this->lock_offset = 5;
this->blot_offset = this->lock_offset + 3 + GetSpriteSize(SPR_LOCK).width;
@@ -479,7 +479,7 @@ public:
this->last_joined = NetworkGameListAddItem(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
this->server = this->last_joined;
- if (this->last_joined != NULL) NetworkUDPQueryServer(this->last_joined->address);
+ if (this->last_joined != nullptr) NetworkUDPQueryServer(this->last_joined->address);
this->requery_timer.SetInterval(MILLISECONDS_PER_TICK);
@@ -576,7 +576,7 @@ public:
case WID_NG_LASTJOINED:
/* Draw the last joined server, if any */
- if (this->last_joined != NULL) this->DrawServerLine(this->last_joined, r.top, this->last_joined == this->server);
+ if (this->last_joined != nullptr) this->DrawServerLine(this->last_joined, r.top, this->last_joined == this->server);
break;
case WID_NG_DETAILS:
@@ -606,16 +606,16 @@ public:
NetworkGameList *sel = this->server;
/* 'Refresh' button invisible if no server selected */
- this->SetWidgetDisabledState(WID_NG_REFRESH, sel == NULL);
+ this->SetWidgetDisabledState(WID_NG_REFRESH, sel == nullptr);
/* 'Join' button disabling conditions */
- this->SetWidgetDisabledState(WID_NG_JOIN, sel == NULL || // no Selected Server
+ this->SetWidgetDisabledState(WID_NG_JOIN, sel == nullptr || // no Selected Server
!sel->online || // Server offline
sel->info.clients_on >= sel->info.clients_max || // Server full
!sel->info.compatible); // Revision mismatch
/* 'NewGRF Settings' button invisible if no NewGRF is used */
- this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_SEL)->SetDisplayedPlane(sel == NULL || !sel->online || sel->info.grfconfig == NULL);
- this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_MISSING_SEL)->SetDisplayedPlane(sel == NULL || !sel->online || sel->info.grfconfig == NULL || !sel->info.version_compatible || sel->info.compatible);
+ this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_SEL)->SetDisplayedPlane(sel == nullptr || !sel->online || sel->info.grfconfig == nullptr);
+ this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_MISSING_SEL)->SetDisplayedPlane(sel == nullptr || !sel->online || sel->info.grfconfig == nullptr || !sel->info.version_compatible || sel->info.compatible);
this->DrawWidgets();
}
@@ -628,7 +628,7 @@ public:
/* Draw the right menu */
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.top + detail_height - 1, PC_DARK_BLUE);
- if (sel == NULL) {
+ if (sel == nullptr) {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, STR_NETWORK_SERVER_LIST_GAME_INFO, TC_FROMSTRING, SA_HOR_CENTER);
} else if (!sel->online) {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, sel->info.server_name, TC_ORANGE, SA_HOR_CENTER); // game name
@@ -722,8 +722,8 @@ public:
case WID_NG_MATRIX: { // Show available network games
uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NG_MATRIX);
- this->server = (id_v < this->servers.size()) ? this->servers[id_v] : NULL;
- this->list_pos = (server == NULL) ? SLP_INVALID : id_v;
+ this->server = (id_v < this->servers.size()) ? this->servers[id_v] : nullptr;
+ this->list_pos = (server == nullptr) ? SLP_INVALID : id_v;
this->SetDirty();
/* FIXME the disabling should go into some InvalidateData, which is called instead of the SetDirty */
@@ -732,7 +732,7 @@ public:
}
case WID_NG_LASTJOINED: {
- if (this->last_joined != NULL) {
+ if (this->last_joined != nullptr) {
this->server = this->last_joined;
/* search the position of the newly selected server */
@@ -767,7 +767,7 @@ public:
break;
case WID_NG_JOIN: // Join Game
- if (this->server != NULL) {
+ if (this->server != nullptr) {
seprintf(_settings_client.network.last_host, lastof(_settings_client.network.last_host), "%s", this->server->address.GetHostname());
_settings_client.network.last_port = this->server->address.GetPort();
ShowNetworkLobbyWindow(this->server);
@@ -775,15 +775,15 @@ public:
break;
case WID_NG_REFRESH: // Refresh
- if (this->server != NULL) NetworkUDPQueryServer(this->server->address);
+ if (this->server != nullptr) NetworkUDPQueryServer(this->server->address);
break;
case WID_NG_NEWGRF: // NewGRF Settings
- if (this->server != NULL) ShowNewGRFSettings(false, false, false, &this->server->info.grfconfig);
+ if (this->server != nullptr) ShowNewGRFSettings(false, false, false, &this->server->info.grfconfig);
break;
case WID_NG_NEWGRF_MISSING: // Find missing content online
- if (this->server != NULL) ShowMissingContentWindow(this->server->info.grfconfig);
+ if (this->server != nullptr) ShowMissingContentWindow(this->server->info.grfconfig);
break;
}
}
@@ -862,11 +862,11 @@ public:
return ES_HANDLED;
}
- if (this->server != NULL) {
+ if (this->server != nullptr) {
if (keycode == WKC_DELETE) { // Press 'delete' to remove servers
NetworkGameListRemoveItem(this->server);
- if (this->server == this->last_joined) this->last_joined = NULL;
- this->server = NULL;
+ if (this->server == this->last_joined) this->last_joined = nullptr;
+ this->server = nullptr;
this->list_pos = SLP_INVALID;
}
}
@@ -1244,7 +1244,7 @@ struct NetworkStartServerWindow : public Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
if (this->widget_id == WID_NSS_SETPWD) {
strecpy(_settings_client.network.server_password, str, lastof(_settings_client.network.server_password));
@@ -1344,7 +1344,7 @@ static const NWidgetPart _nested_network_start_server_window_widgets[] = {
};
static WindowDesc _network_start_server_window_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_WINDOW, WC_NONE,
0,
_nested_network_start_server_window_widgets, lengthof(_nested_network_start_server_window_widgets)
@@ -1631,7 +1631,7 @@ static const NWidgetPart _nested_network_lobby_window_widgets[] = {
};
static WindowDesc _network_lobby_window_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_WINDOW, WC_NONE,
0,
_nested_network_lobby_window_widgets, lengthof(_nested_network_lobby_window_widgets)
@@ -1660,7 +1660,7 @@ static void ShowNetworkLobbyWindow(NetworkGameList *ngl)
NetworkCompanyInfo *GetLobbyCompanyInfo(CompanyID company)
{
NetworkLobbyWindow *lobby = dynamic_cast<NetworkLobbyWindow*>(FindWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY));
- return (lobby != NULL && company < MAX_COMPANIES) ? &lobby->company_info[company] : NULL;
+ return (lobby != nullptr && company < MAX_COMPANIES) ? &lobby->company_info[company] : nullptr;
}
/* The window below gives information about the connected clients
@@ -1680,7 +1680,7 @@ static const NWidgetPart _nested_client_list_popup_widgets[] = {
};
static WindowDesc _client_list_popup_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_CLIENT_LIST_POPUP, WC_CLIENT_LIST,
0,
_nested_client_list_popup_widgets, lengthof(_nested_client_list_popup_widgets)
@@ -1825,7 +1825,7 @@ struct NetworkClientListPopupWindow : Window {
} else {
if (index < this->actions.size() && _cursor.pos.y >= this->top) {
const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(this->client_id);
- if (ci != NULL) this->actions[index].proc(ci);
+ if (ci != nullptr) this->actions[index].proc(ci);
}
DeleteWindowByClass(WC_CLIENT_LIST_POPUP);
@@ -1840,7 +1840,7 @@ static void PopupClientList(ClientID client_id, int x, int y)
{
DeleteWindowByClass(WC_CLIENT_LIST_POPUP);
- if (NetworkClientInfo::GetByClientID(client_id) == NULL) return;
+ if (NetworkClientInfo::GetByClientID(client_id) == nullptr) return;
new NetworkClientListPopupWindow(&_client_list_popup_desc, x, y, client_id);
}
@@ -1986,7 +1986,7 @@ struct NetworkClientListWindow : Window {
client_no--;
}
- if (ci != NULL) PopupClientList(ci->client_id, pt.x + this->left, pt.y + this->top);
+ if (ci != nullptr) PopupClientList(ci->client_id, pt.x + this->left, pt.y + this->top);
}
}
@@ -2133,7 +2133,7 @@ static const NWidgetPart _nested_network_join_status_window_widgets[] = {
};
static WindowDesc _network_join_status_window_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_MODAL,
_nested_network_join_status_window_widgets, lengthof(_nested_network_join_status_window_widgets)
@@ -2148,7 +2148,7 @@ void ShowJoinStatusWindow()
void ShowNetworkNeedPassword(NetworkPasswordType npt)
{
NetworkJoinStatusWindow *w = (NetworkJoinStatusWindow *)FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
- if (w == NULL) return;
+ if (w == nullptr) return;
w->password_type = npt;
StringID caption;
@@ -2227,7 +2227,7 @@ static const NWidgetPart _nested_network_company_password_window_widgets[] = {
};
static WindowDesc _network_company_password_window_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_COMPANY_PASSWORD_WINDOW, WC_NONE,
0,
_nested_network_company_password_window_widgets, lengthof(_nested_network_company_password_window_widgets)
diff --git a/src/network/network_internal.h b/src/network/network_internal.h
index 2498d50d4..06dca992f 100644
--- a/src/network/network_internal.h
+++ b/src/network/network_internal.h
@@ -149,8 +149,8 @@ bool IsNetworkCompatibleVersion(const char *version);
* Everything we need to know about a command to be able to execute it.
*/
struct CommandPacket : CommandContainer {
- /** Make sure the pointer is NULL. */
- CommandPacket() : next(NULL), company(INVALID_COMPANY), frame(0), my_cmd(false) {}
+ /** Make sure the pointer is nullptr. */
+ CommandPacket() : next(nullptr), company(INVALID_COMPANY), frame(0), my_cmd(false) {}
CommandPacket *next; ///< the next command packet (if in queue)
CompanyID company; ///< company that is executing the command
uint32 frame; ///< the frame in which this packet is executed
diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp
index 8022f5ede..24b91e89b 100644
--- a/src/network/network_server.cpp
+++ b/src/network/network_server.cpp
@@ -67,7 +67,7 @@ struct PacketWriter : SaveFilter {
* Create the packet writer.
* @param cs The socket handler we're making the packets for.
*/
- PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(NULL), cs(cs), current(NULL), total_size(0), packets(NULL)
+ PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), current(nullptr), total_size(0), packets(nullptr)
{
}
@@ -76,11 +76,11 @@ struct PacketWriter : SaveFilter {
{
std::unique_lock<std::mutex> lock(this->mutex);
- if (this->cs != NULL) this->exit_sig.wait(lock);
+ if (this->cs != nullptr) this->exit_sig.wait(lock);
/* This must all wait until the Destroy function is called. */
- while (this->packets != NULL) {
+ while (this->packets != nullptr) {
Packet *p = this->packets->next;
delete this->packets;
this->packets = p;
@@ -93,7 +93,7 @@ struct PacketWriter : SaveFilter {
* Begin the destruction of this packet writer. It can happen in two ways:
* in the first case the client disconnected while saving the map. In this
* case the saving has not finished and killed this PacketWriter. In that
- * case we simply set cs to NULL, triggering the appending to fail due to
+ * case we simply set cs to nullptr, triggering the appending to fail due to
* the connection problem and eventually triggering the destructor. In the
* second case the destructor is already called, and it is waiting for our
* signal which we will send. Only then the packets will be removed by the
@@ -103,7 +103,7 @@ struct PacketWriter : SaveFilter {
{
std::unique_lock<std::mutex> lock(this->mutex);
- this->cs = NULL;
+ this->cs = nullptr;
this->exit_sig.notify_all();
lock.unlock();
@@ -124,7 +124,7 @@ struct PacketWriter : SaveFilter {
*/
bool HasPackets()
{
- return this->packets != NULL;
+ return this->packets != nullptr;
}
/**
@@ -136,7 +136,7 @@ struct PacketWriter : SaveFilter {
Packet *p = this->packets;
this->packets = p->next;
- p->next = NULL;
+ p->next = nullptr;
return p;
}
@@ -144,23 +144,23 @@ struct PacketWriter : SaveFilter {
/** Append the current packet to the queue. */
void AppendQueue()
{
- if (this->current == NULL) return;
+ if (this->current == nullptr) return;
Packet **p = &this->packets;
- while (*p != NULL) {
+ while (*p != nullptr) {
p = &(*p)->next;
}
*p = this->current;
- this->current = NULL;
+ this->current = nullptr;
}
void Write(byte *buf, size_t size) override
{
/* We want to abort the saving when the socket is closed. */
- if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
+ if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
- if (this->current == NULL) this->current = new Packet(PACKET_SERVER_MAP_DATA);
+ if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA);
std::lock_guard<std::mutex> lock(this->mutex);
@@ -183,7 +183,7 @@ struct PacketWriter : SaveFilter {
void Finish() override
{
/* We want to abort the saving when the socket is closed. */
- if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
+ if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
std::lock_guard<std::mutex> lock(this->mutex);
@@ -226,9 +226,9 @@ ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
OrderBackup::ResetUser(this->client_id);
- if (this->savegame != NULL) {
+ if (this->savegame != nullptr) {
this->savegame->Destroy();
- this->savegame = NULL;
+ this->savegame = nullptr;
}
}
@@ -236,12 +236,12 @@ Packet *ServerNetworkGameSocketHandler::ReceivePacket()
{
/* Only allow receiving when we have some buffer free; this value
* can go negative, but eventually it will become positive again. */
- if (this->receive_limit <= 0) return NULL;
+ if (this->receive_limit <= 0) return nullptr;
/* We can receive a packet, so try that and if needed account for
* the amount of received data. */
Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
- if (p != NULL) this->receive_limit -= p->size;
+ if (p != nullptr) this->receive_limit -= p->size;
return p;
}
@@ -264,7 +264,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvSta
this->GetClientName(client_name, lastof(client_name));
- NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
+ NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
/* Inform other clients of this... strange leaving ;) */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
@@ -361,7 +361,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
/* Add the local player (if not dedicated) */
const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
- if (ci != NULL && Company::IsValidID(ci->client_playas)) {
+ if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
}
@@ -371,7 +371,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
((ServerNetworkGameSocketHandler*)csi)->GetClientName(client_name, lastof(client_name));
ci = csi->GetInfo();
- if (ci != NULL && Company::IsValidID(ci->client_playas)) {
+ if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
if (!StrEmpty(clients[ci->client_playas])) {
strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
}
@@ -434,7 +434,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode err
DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
- NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
+ NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
@@ -463,12 +463,12 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
const GRFConfig *c;
uint grf_count = 0;
- for (c = _grfconfig; c != NULL; c = c->next) {
+ for (c = _grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
}
p->Send_uint8 (grf_count);
- for (c = _grfconfig; c != NULL; c = c->next) {
+ for (c = _grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
}
@@ -607,7 +607,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
if (last_packet) {
/* Done reading, make sure saving is done as well */
this->savegame->Destroy();
- this->savegame = NULL;
+ this->savegame = nullptr;
/* Set the status to DONE_MAP, no we will wait for the client
* to send it is ready (maybe that happens like never ;)) */
@@ -615,17 +615,17 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
/* Find the best candidate for joining, i.e. the first joiner. */
NetworkClientSocket *new_cs;
- NetworkClientSocket *best = NULL;
+ NetworkClientSocket *best = nullptr;
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status == STATUS_MAP_WAIT) {
- if (best == NULL || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
+ if (best == nullptr || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
best = new_cs;
}
}
}
/* Is there someone else to join? */
- if (best != NULL) {
+ if (best != nullptr) {
/* Let the first start joining. */
best->status = STATUS_AUTHORIZED;
best->SendMap();
@@ -946,9 +946,9 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
this->status = STATUS_NEWGRFS_CHECK;
- if (_grfconfig == NULL) {
+ if (_grfconfig == nullptr) {
/* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
- return this->Receive_CLIENT_NEWGRFS_CHECKED(NULL);
+ return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
}
return this->SendNewGRFCheck();
@@ -1032,7 +1032,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *
this->GetClientName(client_name, lastof(client_name));
- NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, NULL, this->client_id);
+ NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, nullptr, this->client_id);
/* Mark the client as pre-active, and wait for an ACK
* so we know he is done loading and in sync with us */
@@ -1089,7 +1089,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet
NetworkClientInfo *ci = this->GetInfo();
- if (err != NULL) {
+ if (err != nullptr) {
IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, this->GetClientIP());
return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
}
@@ -1155,7 +1155,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p
DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
- NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
+ NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTHORIZED) {
@@ -1182,7 +1182,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
this->GetClientName(client_name, lastof(client_name));
- NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
+ NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
@@ -1262,7 +1262,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
if ((ClientID)dest == CLIENT_ID_SERVER) {
ci = NetworkClientInfo::GetByClientID(from_id);
/* Display the text locally, and that is it */
- if (ci != NULL) {
+ if (ci != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
if (_settings_client.network.server_admin_chat) {
@@ -1284,7 +1284,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
if (from_id == CLIENT_ID_SERVER) {
ci = NetworkClientInfo::GetByClientID(from_id);
ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
- if (ci != NULL && ci_to != NULL) {
+ if (ci != nullptr && ci_to != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
}
} else {
@@ -1301,10 +1301,10 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
/* If this is false, the message is already displayed on the client who sent it. */
bool show_local = true;
/* Find all clients that belong to this company */
- ci_to = NULL;
+ ci_to = nullptr;
FOR_ALL_CLIENT_SOCKETS(cs) {
ci = cs->GetInfo();
- if (ci != NULL && ci->client_playas == (CompanyID)dest) {
+ if (ci != nullptr && ci->client_playas == (CompanyID)dest) {
cs->SendChat(action, from_id, false, msg, data);
if (cs->client_id == from_id) show_local = false;
ci_to = ci; // Remember a client that is in the company for company-name
@@ -1318,17 +1318,17 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
ci = NetworkClientInfo::GetByClientID(from_id);
ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
- if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
+ if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
if (from_id == CLIENT_ID_SERVER) show_local = false;
ci_to = ci_own;
}
/* There is no such client */
- if (ci_to == NULL) break;
+ if (ci_to == nullptr) break;
/* Display the message locally (so you know you have sent it) */
- if (ci != NULL && show_local) {
+ if (ci != nullptr && show_local) {
if (from_id == CLIENT_ID_SERVER) {
char name[NETWORK_NAME_LENGTH];
StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
@@ -1357,7 +1357,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
ci = NetworkClientInfo::GetByClientID(from_id);
- if (ci != NULL) {
+ if (ci != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
}
break;
@@ -1428,7 +1428,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
- if (ci != NULL) {
+ if (ci != nullptr) {
/* Display change */
if (NetworkFindName(client_name, lastof(client_name))) {
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
@@ -1591,7 +1591,7 @@ void NetworkUpdateClientInfo(ClientID client_id)
NetworkClientSocket *cs;
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci == NULL) return;
+ if (ci == nullptr) return;
DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
@@ -1712,7 +1712,7 @@ bool NetworkFindName(char *new_name, const char *last)
}
/* Check if it is the same as the server-name */
ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
- if (ci != NULL) {
+ if (ci != nullptr) {
if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
}
@@ -1743,7 +1743,7 @@ bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
}
ci = NetworkClientInfo::GetByClientID(client_id);
- if (ci == NULL) return false;
+ if (ci == nullptr) return false;
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
@@ -1778,7 +1778,7 @@ void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password,
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
{
CommandPacket *cp;
- while ((cp = cs->outgoing_queue.Pop()) != NULL) {
+ while ((cp = cs->outgoing_queue.Pop()) != nullptr) {
cs->SendCommand(cp);
free(cp);
}
@@ -1964,7 +1964,7 @@ void NetworkServerShowStatusToConsole()
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
NetworkClientInfo *ci = cs->GetInfo();
- if (ci == NULL) continue;
+ if (ci == nullptr) continue;
uint lag = NetworkCalculateLag(cs);
const char *status;
@@ -2131,7 +2131,7 @@ void ServerNetworkGameSocketHandler::GetClientName(char *client_name, const char
{
const NetworkClientInfo *ci = this->GetInfo();
- if (ci == NULL || StrEmpty(ci->client_name)) {
+ if (ci == nullptr || StrEmpty(ci->client_name)) {
seprintf(client_name, last, "Client #%4d", this->client_id);
} else {
strecpy(client_name, ci->client_name, last);
@@ -2162,12 +2162,12 @@ void NetworkPrintClients()
/**
* Perform all the server specific administration of a new company.
- * @param c The newly created company; can't be NULL.
- * @param ci The client information of the client that made the company; can be NULL.
+ * @param c The newly created company; can't be nullptr.
+ * @param ci The client information of the client that made the company; can be nullptr.
*/
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
{
- assert(c != NULL);
+ assert(c != nullptr);
if (!_network_server) return;
@@ -2175,18 +2175,18 @@ void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
_network_company_states[c->index].password[0] = '\0';
NetworkServerUpdateCompanyPassworded(c->index, false);
- if (ci != NULL) {
- /* ci is NULL when replaying, or for AIs. In neither case there is a client. */
+ if (ci != nullptr) {
+ /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
ci->client_playas = c->index;
NetworkUpdateClientInfo(ci->client_id);
- NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, c->index);
+ NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index);
}
/* Announce new company on network. */
NetworkAdminCompanyInfo(c, true);
- if (ci != NULL) {
- /* ci is NULL when replaying, or for AIs. In neither case there is a client.
+ if (ci != nullptr) {
+ /* ci is nullptr when replaying, or for AIs. In neither case there is a client.
We need to send Admin port update here so that they first know about the new company
and then learn about a possibly joining client (see FS#6025) */
NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
diff --git a/src/network/network_udp.cpp b/src/network/network_udp.cpp
index 7674036e7..d9f625719 100644
--- a/src/network/network_udp.cpp
+++ b/src/network/network_udp.cpp
@@ -45,9 +45,9 @@ static const uint32 ADVERTISE_NORMAL_INTERVAL = 15 * 60 * 1000; ///< interval be
static const uint32 ADVERTISE_RETRY_INTERVAL = 10 * 1000; ///< re-advertise when no response after this many ms (10 seconds)
static const uint32 ADVERTISE_RETRY_TIMES = 3; ///< give up re-advertising after this much failed retries
-NetworkUDPSocketHandler *_udp_client_socket = NULL; ///< udp client socket
-NetworkUDPSocketHandler *_udp_server_socket = NULL; ///< udp server socket
-NetworkUDPSocketHandler *_udp_master_socket = NULL; ///< udp master socket
+NetworkUDPSocketHandler *_udp_client_socket = nullptr; ///< udp client socket
+NetworkUDPSocketHandler *_udp_server_socket = nullptr; ///< udp server socket
+NetworkUDPSocketHandler *_udp_master_socket = nullptr; ///< udp master socket
/**
* Helper function doing the actual work for querying the server.
@@ -69,7 +69,7 @@ static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, b
if (needs_mutex) lock.lock();
/* Init the packet */
Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
- if (_udp_client_socket != NULL) _udp_client_socket->SendPacket(&p, &address);
+ if (_udp_client_socket != nullptr) _udp_client_socket->SendPacket(&p, &address);
}
/**
@@ -79,7 +79,7 @@ static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, b
*/
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
{
- if (address.IsResolved() || !StartNewThread(NULL, "ottd:udp-query", &DoNetworkUDPQueryServer, std::move(address), true, std::move(manually))) {
+ if (address.IsResolved() || !StartNewThread(nullptr, "ottd:udp-query", &DoNetworkUDPQueryServer, std::move(address), true, std::move(manually))) {
DoNetworkUDPQueryServer(address, true, manually);
}
}
@@ -261,7 +261,7 @@ void ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet *p, Networ
/* Find the matching GRF file */
f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
- if (f == NULL) continue; // The GRF is unknown to this server
+ if (f == nullptr) continue; // The GRF is unknown to this server
/* If the reply might exceed the size of the packet, only reply
* the current list and do not send the other data.
@@ -332,7 +332,7 @@ void ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *p, NetworkAd
const GRFConfig *c;
uint in_request_count = 0;
- for (c = item->info.grfconfig; c != NULL; c = c->next) {
+ for (c = item->info.grfconfig; c != nullptr; c = c->next) {
if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
if (c->status != GCS_NOT_FOUND || strcmp(c->GetName(), UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
in_request[in_request_count] = c;
@@ -431,7 +431,7 @@ void ClientNetworkUDPSocketHandler::Receive_SERVER_NEWGRFS(Packet *p, NetworkAdd
* If it exists and not resolved yet, then name of the fake GRF is
* overwritten with the name from the reply. */
GRFTextWrapper *unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
- if (unknown_name != NULL && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
+ if (unknown_name != nullptr && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
AddGRFTextToList(&unknown_name->text, name);
}
}
@@ -441,7 +441,7 @@ void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFCo
{
/* Find the matching GRF file */
const GRFConfig *f = FindGRFConfig(config->ident.grfid, FGCM_EXACT, config->ident.md5sum);
- if (f == NULL) {
+ if (f == nullptr) {
/* Don't know the GRF, so mark game incompatible and the (possibly)
* already resolved name for this GRF (another server has sent the
* name of the GRF already */
@@ -521,7 +521,7 @@ static void NetworkUDPRemoveAdvertiseThread()
p.Send_uint16(_settings_client.network.server_port);
std::lock_guard<std::mutex> lock(_network_udp_mutex);
- if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
+ if (_udp_master_socket != nullptr) _udp_master_socket->SendPacket(&p, &out_addr, true);
}
/**
@@ -533,7 +533,7 @@ void NetworkUDPRemoveAdvertise(bool blocking)
/* Check if we are advertising */
if (!_networking || !_network_server || !_network_udp_server) return;
- if (blocking || !StartNewThread(NULL, "ottd:udp-advert", &NetworkUDPRemoveAdvertiseThread)) {
+ if (blocking || !StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPRemoveAdvertiseThread)) {
NetworkUDPRemoveAdvertiseThread();
}
}
@@ -573,7 +573,7 @@ static void NetworkUDPAdvertiseThread()
p.Send_uint64(_session_key);
std::lock_guard<std::mutex> lock(_network_udp_mutex);
- if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
+ if (_udp_master_socket != nullptr) _udp_master_socket->SendPacket(&p, &out_addr, true);
}
/**
@@ -614,7 +614,7 @@ void NetworkUDPAdvertise()
if (_next_advertisement < _last_advertisement) _next_advertisement = UINT32_MAX;
if (_next_retry < _last_advertisement) _next_retry = UINT32_MAX;
- if (!StartNewThread(NULL, "ottd:udp-advert", &NetworkUDPAdvertiseThread)) {
+ if (!StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPAdvertiseThread)) {
NetworkUDPAdvertiseThread();
}
}
@@ -623,10 +623,10 @@ void NetworkUDPAdvertise()
void NetworkUDPInitialize()
{
/* If not closed, then do it. */
- if (_udp_server_socket != NULL) NetworkUDPClose();
+ if (_udp_server_socket != nullptr) NetworkUDPClose();
DEBUG(net, 1, "[udp] initializing listeners");
- assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
+ assert(_udp_client_socket == nullptr && _udp_server_socket == nullptr && _udp_master_socket == nullptr);
std::lock_guard<std::mutex> lock(_network_udp_mutex);
@@ -654,9 +654,9 @@ void NetworkUDPClose()
delete _udp_client_socket;
delete _udp_server_socket;
delete _udp_master_socket;
- _udp_client_socket = NULL;
- _udp_server_socket = NULL;
- _udp_master_socket = NULL;
+ _udp_client_socket = nullptr;
+ _udp_server_socket = nullptr;
+ _udp_master_socket = nullptr;
_network_udp_server = false;
_network_udp_broadcast = 0;
diff --git a/src/newgrf.cpp b/src/newgrf.cpp
index 0b3a2cc3d..4dbc6273e 100644
--- a/src/newgrf.cpp
+++ b/src/newgrf.cpp
@@ -394,7 +394,7 @@ static GRFFile *GetFileByGRFID(uint32 grfid)
for (GRFFile * const file : _grf_files) {
if (file->grfid == grfid) return file;
}
- return NULL;
+ return nullptr;
}
/**
@@ -407,31 +407,31 @@ static GRFFile *GetFileByFilename(const char *filename)
for (GRFFile * const file : _grf_files) {
if (strcmp(file->filename, filename) == 0) return file;
}
- return NULL;
+ return nullptr;
}
/** Reset all NewGRFData that was used only while processing data */
static void ClearTemporaryNewGRFData(GRFFile *gf)
{
/* Clear the GOTO labels used for GRF processing */
- for (GRFLabel *l = gf->label; l != NULL;) {
+ for (GRFLabel *l = gf->label; l != nullptr;) {
GRFLabel *l2 = l->next;
free(l);
l = l2;
}
- gf->label = NULL;
+ gf->label = nullptr;
}
/**
* Disable a GRF
* @param message Error message or STR_NULL.
- * @param config GRFConfig to disable, NULL for current.
+ * @param config GRFConfig to disable, nullptr for current.
* @return Error message of the GRF for further customisation.
*/
-static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = NULL)
+static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
{
GRFFile *file;
- if (config != NULL) {
+ if (config != nullptr) {
file = GetFileByGRFID(config->ident.grfid);
} else {
config = _cur.grfconfig;
@@ -439,7 +439,7 @@ static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = NUL
}
config->status = GCS_DISABLED;
- if (file != NULL) ClearTemporaryNewGRFData(file);
+ if (file != nullptr) ClearTemporaryNewGRFData(file);
if (config == _cur.grfconfig) _cur.skip_sprites = -1;
if (message != STR_NULL) {
@@ -589,7 +589,7 @@ static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
* @param file NewGRF that wants to change the engine.
* @param type Vehicle type.
* @param internal_id Engine ID inside the NewGRF.
- * @param static_access If the engine is not present, return NULL instead of allocating a new engine. (Used for static Action 0x04).
+ * @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04).
* @return The requested engine.
*/
static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access = false)
@@ -604,7 +604,7 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 intern
if (override != 0) {
scope_grfid = override;
const GRFFile *grf_match = GetFileByGRFID(override);
- if (grf_match == NULL) {
+ if (grf_match == nullptr) {
grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
} else {
grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
@@ -615,7 +615,7 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 intern
EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
if (engine != INVALID_ENGINE) {
Engine *e = Engine::Get(engine);
- if (e->grf_prop.grffile == NULL) e->grf_prop.grffile = file;
+ if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
return e;
}
}
@@ -625,7 +625,7 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 intern
if (engine != INVALID_ENGINE) {
Engine *e = Engine::Get(engine);
- if (e->grf_prop.grffile == NULL) {
+ if (e->grf_prop.grffile == nullptr) {
e->grf_prop.grffile = file;
grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
}
@@ -639,11 +639,11 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 intern
return e;
}
- if (static_access) return NULL;
+ if (static_access) return nullptr;
if (!Engine::CanAllocateItem()) {
grfmsg(0, "Can't allocate any more engines");
- return NULL;
+ return nullptr;
}
size_t engine_pool_size = Engine::GetPoolSize();
@@ -735,7 +735,7 @@ static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
* @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset)
* @return Read TileLayoutFlags.
*/
-static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset = NULL, uint16 *max_palette_offset = NULL)
+static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset = nullptr, uint16 *max_palette_offset = nullptr)
{
grf_sprite->sprite = buf->ReadWord();
grf_sprite->pal = buf->ReadWord();
@@ -754,7 +754,7 @@ static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags,
grf_sprite->pal = PAL_NONE;
} else {
SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
- if (max_sprite_offset != NULL) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
+ if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
}
@@ -772,7 +772,7 @@ static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags,
grf_sprite->pal = PAL_NONE;
} else {
SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
- if (max_palette_offset != NULL) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
+ if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
}
@@ -797,7 +797,7 @@ static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bo
{
if (!(flags & TLF_DRAWING_FLAGS)) return;
- if (dts->registers == NULL) dts->AllocateRegisters();
+ if (dts->registers == nullptr) dts->AllocateRegisters();
TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
regs.flags = flags & TLF_DRAWING_FLAGS;
@@ -924,9 +924,9 @@ static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool us
/* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
- if (!is_consistent || dts->registers != NULL) {
+ if (!is_consistent || dts->registers != nullptr) {
dts->consistent_max_offset = 0;
- if (dts->registers == NULL) dts->AllocateRegisters();
+ if (dts->registers == nullptr) dts->AllocateRegisters();
for (uint i = 0; i < num_building_sprites + 1; i++) {
TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
@@ -1045,7 +1045,7 @@ static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
- if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
+ if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
RailVehicleInfo *rvi = &e->u.rail;
@@ -1339,7 +1339,7 @@ static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
- if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
+ if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
RoadVehicleInfo *rvi = &e->u.road;
@@ -1527,7 +1527,7 @@ static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
- if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
+ if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
ShipVehicleInfo *svi = &e->u.ship;
@@ -1699,7 +1699,7 @@ static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
- if (e == NULL) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
+ if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
AircraftVehicleInfo *avi = &e->u.air;
@@ -1857,13 +1857,13 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte
}
/* Allocate station specs if necessary */
- if (_cur.grffile->stations == NULL) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
+ if (_cur.grffile->stations == nullptr) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
for (int i = 0; i < numinfo; i++) {
StationSpec *statspec = _cur.grffile->stations[stid + i];
/* Check that the station we are modifying is defined. */
- if (statspec == NULL && prop != 0x08) {
+ if (statspec == nullptr && prop != 0x08) {
grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
return CIR_INVALID_ID;
}
@@ -1873,7 +1873,7 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte
StationSpec **spec = &_cur.grffile->stations[stid + i];
/* Property 0x08 is special; it is where the station is allocated */
- if (*spec == NULL) *spec = CallocT<StationSpec>(1);
+ if (*spec == nullptr) *spec = CallocT<StationSpec>(1);
/* Swap classid because we read it in BE meaning WAYP or DFLT */
uint32 classid = buf->ReadDWord();
@@ -1929,7 +1929,7 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte
byte srcid = buf->ReadByte();
const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
- if (srcstatspec == NULL) {
+ if (srcstatspec == nullptr) {
grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
continue;
}
@@ -1981,7 +1981,7 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte
if (number > statspec->platforms[l]) {
statspec->layouts[l] = ReallocT(statspec->layouts[l], number);
- /* We expect NULL being 0 here, but C99 guarantees that. */
+ /* We expect nullptr being 0 here, but C99 guarantees that. */
memset(statspec->layouts[l] + statspec->platforms[l], 0,
(number - statspec->platforms[l]) * sizeof(**statspec->layouts));
@@ -2012,7 +2012,7 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte
byte srcid = buf->ReadByte();
const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
- if (srcstatspec == NULL) {
+ if (srcstatspec == nullptr) {
grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
continue;
}
@@ -2174,7 +2174,7 @@ static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteR
byte tableid = buf->ReadByte();
byte numtables = buf->ReadByte();
- if (bridge->sprite_table == NULL) {
+ if (bridge->sprite_table == nullptr) {
/* Allocate memory for sprite table pointers and zero out */
bridge->sprite_table = CallocT<PalSpriteID*>(7);
}
@@ -2186,7 +2186,7 @@ static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteR
continue;
}
- if (bridge->sprite_table[tableid] == NULL) {
+ if (bridge->sprite_table[tableid] == nullptr) {
bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
}
@@ -2320,14 +2320,14 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, Byt
}
/* Allocate house specs if they haven't been allocated already. */
- if (_cur.grffile->housespec == NULL) {
+ if (_cur.grffile->housespec == nullptr) {
_cur.grffile->housespec = CallocT<HouseSpec*>(NUM_HOUSES_PER_GRF);
}
for (int i = 0; i < numinfo; i++) {
HouseSpec *housespec = _cur.grffile->housespec[hid + i];
- if (prop != 0x08 && housespec == NULL) {
+ if (prop != 0x08 && housespec == nullptr) {
/* If the house property 08 is not yet set, ignore this property */
ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
if (cir > ret) ret = cir;
@@ -2351,7 +2351,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, Byt
}
/* Allocate space for this house. */
- if (*house == NULL) *house = CallocT<HouseSpec>(1);
+ if (*house == nullptr) *house = CallocT<HouseSpec>(1);
housespec = *house;
@@ -2562,13 +2562,13 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, Byt
* Get the language map associated with a given NewGRF and language.
* @param grfid The NewGRF to get the map for.
* @param language_id The (NewGRF) language ID to get the map for.
- * @return The LanguageMap, or NULL if it couldn't be found.
+ * @return The LanguageMap, or nullptr if it couldn't be found.
*/
/* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32 grfid, uint8 language_id)
{
/* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
const GRFFile *grffile = GetFileByGRFID(grfid);
- return (grffile != NULL && grffile->language_map != NULL && language_id < MAX_LANG) ? &grffile->language_map[language_id] : NULL;
+ return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
}
/**
@@ -2751,8 +2751,8 @@ static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, By
case 0x14: // Case translation table
case 0x15: { // Plural form translation
uint curidx = gvid + i; // The current index, i.e. language.
- const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : NULL;
- if (lang == NULL) {
+ const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
+ if (lang == nullptr) {
grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
/* Skip over the data. */
if (prop == 0x15) {
@@ -2765,7 +2765,7 @@ static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, By
break;
}
- if (_cur.grffile->language_map == NULL) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
+ if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
if (prop == 0x15) {
uint plural_form = buf->ReadByte();
@@ -3135,14 +3135,14 @@ static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int pr
}
/* Allocate industry tile specs if they haven't been allocated already. */
- if (_cur.grffile->indtspec == NULL) {
+ if (_cur.grffile->indtspec == nullptr) {
_cur.grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES_PER_GRF);
}
for (int i = 0; i < numinfo; i++) {
IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i];
- if (prop != 0x08 && tsp == NULL) {
+ if (prop != 0x08 && tsp == nullptr) {
ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
@@ -3160,7 +3160,7 @@ static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int pr
}
/* Allocate space for this industry. */
- if (*tilespec == NULL) {
+ if (*tilespec == nullptr) {
*tilespec = CallocT<IndustryTileSpec>(1);
tsp = *tilespec;
@@ -3370,14 +3370,14 @@ static bool ValidateIndustryLayout(const IndustryTileTable *layout, int size)
/** Clean the tile table of the IndustrySpec if it's needed. */
static void CleanIndustryTileTable(IndustrySpec *ind)
{
- if (HasBit(ind->cleanup_flag, CLEAN_TILELAYOUT) && ind->table != NULL) {
+ if (HasBit(ind->cleanup_flag, CLEAN_TILELAYOUT) && ind->table != nullptr) {
for (int j = 0; j < ind->num_table; j++) {
/* remove the individual layouts */
free(ind->table[j]);
}
/* remove the layouts pointers */
free(ind->table);
- ind->table = NULL;
+ ind->table = nullptr;
}
}
@@ -3399,14 +3399,14 @@ static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop,
}
/* Allocate industry specs if they haven't been allocated already. */
- if (_cur.grffile->industryspec == NULL) {
+ if (_cur.grffile->industryspec == nullptr) {
_cur.grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES_PER_GRF);
}
for (int i = 0; i < numinfo; i++) {
IndustrySpec *indsp = _cur.grffile->industryspec[indid + i];
- if (prop != 0x08 && indsp == NULL) {
+ if (prop != 0x08 && indsp == nullptr) {
ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
@@ -3431,7 +3431,7 @@ static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop,
/* Allocate space for this industry.
* Only need to do it once. If ever it is called again, it should not
* do anything */
- if (*indspec == NULL) {
+ if (*indspec == nullptr) {
*indspec = CallocT<IndustrySpec>(1);
indsp = *indspec;
@@ -3819,14 +3819,14 @@ static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, B
}
/* Allocate industry specs if they haven't been allocated already. */
- if (_cur.grffile->airportspec == NULL) {
+ if (_cur.grffile->airportspec == nullptr) {
_cur.grffile->airportspec = CallocT<AirportSpec*>(NUM_AIRPORTS_PER_GRF);
}
for (int i = 0; i < numinfo; i++) {
AirportSpec *as = _cur.grffile->airportspec[airport + i];
- if (as == NULL && prop != 0x08 && prop != 0x09) {
+ if (as == nullptr && prop != 0x08 && prop != 0x09) {
grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
return CIR_INVALID_ID;
}
@@ -3850,7 +3850,7 @@ static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, B
/* Allocate space for this airport.
* Only need to do it once. If ever it is called again, it should not
* do anything */
- if (*spec == NULL) {
+ if (*spec == nullptr) {
*spec = MallocT<AirportSpec>(1);
as = *spec;
@@ -4037,14 +4037,14 @@ static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteRea
}
/* Allocate object specs if they haven't been allocated already. */
- if (_cur.grffile->objectspec == NULL) {
+ if (_cur.grffile->objectspec == nullptr) {
_cur.grffile->objectspec = CallocT<ObjectSpec*>(NUM_OBJECTS_PER_GRF);
}
for (int i = 0; i < numinfo; i++) {
ObjectSpec *spec = _cur.grffile->objectspec[id + i];
- if (prop != 0x08 && spec == NULL) {
+ if (prop != 0x08 && spec == nullptr) {
/* If the object property 08 is not yet set, ignore this property */
ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
if (cir > ret) ret = cir;
@@ -4056,7 +4056,7 @@ static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteRea
ObjectSpec **ospec = &_cur.grffile->objectspec[id + i];
/* Allocate space for this object. */
- if (*ospec == NULL) {
+ if (*ospec == nullptr) {
*ospec = CallocT<ObjectSpec>(1);
(*ospec)->views = 1; // Default for NewGRFs that don't set it.
}
@@ -4378,14 +4378,14 @@ static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int pro
}
/* Allocate airport tile specs if they haven't been allocated already. */
- if (_cur.grffile->airtspec == NULL) {
+ if (_cur.grffile->airtspec == nullptr) {
_cur.grffile->airtspec = CallocT<AirportTileSpec*>(NUM_AIRPORTTILES_PER_GRF);
}
for (int i = 0; i < numinfo; i++) {
AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i];
- if (prop != 0x08 && tsp == NULL) {
+ if (prop != 0x08 && tsp == nullptr) {
grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
return CIR_INVALID_ID;
}
@@ -4402,7 +4402,7 @@ static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int pro
}
/* Allocate space for this airport tile. */
- if (*tilespec == NULL) {
+ if (*tilespec == nullptr) {
*tilespec = CallocT<AirportTileSpec>(1);
tsp = *tilespec;
@@ -4513,10 +4513,10 @@ static void FeatureChangeInfo(ByteReader *buf)
/* GSF_GLOBALVAR */ GlobalVarChangeInfo,
/* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
/* GSF_INDUSTRIES */ IndustriesChangeInfo,
- /* GSF_CARGOES */ NULL, // Cargo is handled during reservation
+ /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
/* GSF_SOUNDFX */ SoundEffectChangeInfo,
/* GSF_AIRPORTS */ AirportChangeInfo,
- /* GSF_SIGNALS */ NULL,
+ /* GSF_SIGNALS */ nullptr,
/* GSF_OBJECTS */ ObjectChangeInfo,
/* GSF_RAILTYPES */ RailTypeChangeInfo,
/* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
@@ -4535,7 +4535,7 @@ static void FeatureChangeInfo(ByteReader *buf)
grfmsg(6, "FeatureChangeInfo: Feature 0x%02X, %d properties, to apply to %d+%d",
feature, numprops, engine, numinfo);
- if (feature >= lengthof(handler) || handler[feature] == NULL) {
+ if (feature >= lengthof(handler) || handler[feature] == nullptr) {
if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
return;
}
@@ -4573,7 +4573,7 @@ static void SafeChangeInfo(ByteReader *buf)
uint32 s = buf->ReadDWord();
buf->ReadDWord(); // dest
const GRFConfig *grfconfig = GetGRFConfig(s);
- if (grfconfig != NULL && !HasBit(grfconfig->flags, GCF_STATIC)) {
+ if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
is_safe = false;
break;
}
@@ -4697,9 +4697,9 @@ static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 grou
return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
}
- if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == NULL) {
+ if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
- return NULL;
+ return nullptr;
}
return _cur.spritegroups[groupid];
@@ -4722,7 +4722,7 @@ static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte
if (!_cur.IsValidSpriteSet(feature, spriteid)) {
grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
- return NULL;
+ return nullptr;
}
SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
@@ -4748,7 +4748,7 @@ static void NewSpriteGroup(ByteReader *buf)
* otherwise it specifies a number of entries, the exact
* meaning depends on the feature
* V feature-specific-data (huge mess, don't even look it up --pasky) */
- SpriteGroup *act_group = NULL;
+ SpriteGroup *act_group = nullptr;
uint8 feature = buf->ReadByte();
if (feature >= GSF_END) {
@@ -5128,7 +5128,7 @@ static CargoID TranslateCargo(uint8 feature, uint8 ctype)
static bool IsValidGroupID(uint16 groupid, const char *function)
{
- if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == NULL) {
+ if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
return false;
}
@@ -5165,7 +5165,7 @@ static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
EngineID *engines = AllocaM(EngineID, idcount);
for (uint i = 0; i < idcount; i++) {
Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
- if (e == NULL) {
+ if (e == nullptr) {
/* No engine could be allocated?!? Deal with it. Okay,
* this might look bad. Also make sure this NewGRF
* gets disabled, as a half loaded one is bad. */
@@ -5263,9 +5263,9 @@ static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
if (ctype == CT_INVALID) continue;
for (uint i = 0; i < idcount; i++) {
- StationSpec *statspec = _cur.grffile->stations == NULL ? NULL : _cur.grffile->stations[stations[i]];
+ StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
- if (statspec == NULL) {
+ if (statspec == nullptr) {
grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
continue;
}
@@ -5278,14 +5278,14 @@ static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
- StationSpec *statspec = _cur.grffile->stations == NULL ? NULL : _cur.grffile->stations[stations[i]];
+ StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
- if (statspec == NULL) {
+ if (statspec == nullptr) {
grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
continue;
}
- if (statspec->grf_prop.grffile != NULL) {
+ if (statspec->grf_prop.grffile != nullptr) {
grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
continue;
}
@@ -5312,7 +5312,7 @@ static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
uint16 groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
- if (_cur.grffile->housespec == NULL) {
+ if (_cur.grffile->housespec == nullptr) {
grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
return;
}
@@ -5320,7 +5320,7 @@ static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
HouseSpec *hs = _cur.grffile->housespec[houses[i]];
- if (hs == NULL) {
+ if (hs == nullptr) {
grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
continue;
}
@@ -5343,7 +5343,7 @@ static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
uint16 groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
- if (_cur.grffile->industryspec == NULL) {
+ if (_cur.grffile->industryspec == nullptr) {
grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
return;
}
@@ -5351,7 +5351,7 @@ static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
IndustrySpec *indsp = _cur.grffile->industryspec[industries[i]];
- if (indsp == NULL) {
+ if (indsp == nullptr) {
grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
continue;
}
@@ -5374,7 +5374,7 @@ static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
uint16 groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
- if (_cur.grffile->indtspec == NULL) {
+ if (_cur.grffile->indtspec == nullptr) {
grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
return;
}
@@ -5382,7 +5382,7 @@ static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
IndustryTileSpec *indtsp = _cur.grffile->indtspec[indtiles[i]];
- if (indtsp == NULL) {
+ if (indtsp == nullptr) {
grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
continue;
}
@@ -5421,7 +5421,7 @@ static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
{
- if (_cur.grffile->objectspec == NULL) {
+ if (_cur.grffile->objectspec == nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
return;
}
@@ -5443,7 +5443,7 @@ static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
- if (spec == NULL) {
+ if (spec == nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
continue;
}
@@ -5458,12 +5458,12 @@ static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
- if (spec == NULL) {
+ if (spec == nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
continue;
}
- if (spec->grf_prop.grffile != NULL) {
+ if (spec->grf_prop.grffile != nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
continue;
}
@@ -5518,7 +5518,7 @@ static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
uint16 groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
- if (_cur.grffile->airportspec == NULL) {
+ if (_cur.grffile->airportspec == nullptr) {
grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
return;
}
@@ -5526,7 +5526,7 @@ static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
AirportSpec *as = _cur.grffile->airportspec[airports[i]];
- if (as == NULL) {
+ if (as == nullptr) {
grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
continue;
}
@@ -5549,7 +5549,7 @@ static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
uint16 groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
- if (_cur.grffile->airtspec == NULL) {
+ if (_cur.grffile->airtspec == nullptr) {
grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
return;
}
@@ -5557,7 +5557,7 @@ static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
for (uint i = 0; i < idcount; i++) {
AirportTileSpec *airtsp = _cur.grffile->airtspec[airptiles[i]];
- if (airtsp == NULL) {
+ if (airtsp == nullptr) {
grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
continue;
}
@@ -5721,7 +5721,7 @@ static void FeatureNewName(ByteReader *buf)
case GSF_AIRCRAFT:
if (!generic) {
Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
- if (e == NULL) break;
+ if (e == nullptr) break;
StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
e->info.string_id = string;
} else {
@@ -5737,7 +5737,7 @@ static void FeatureNewName(ByteReader *buf)
switch (GB(id, 8, 8)) {
case 0xC4: // Station class name
- if (_cur.grffile->stations == NULL || _cur.grffile->stations[GB(id, 0, 8)] == NULL) {
+ if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
} else {
StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
@@ -5746,7 +5746,7 @@ static void FeatureNewName(ByteReader *buf)
break;
case 0xC5: // Station name
- if (_cur.grffile->stations == NULL || _cur.grffile->stations[GB(id, 0, 8)] == NULL) {
+ if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
} else {
_cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
@@ -5754,7 +5754,7 @@ static void FeatureNewName(ByteReader *buf)
break;
case 0xC7: // Airporttile name
- if (_cur.grffile->airtspec == NULL || _cur.grffile->airtspec[GB(id, 0, 8)] == NULL) {
+ if (_cur.grffile->airtspec == nullptr || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
} else {
_cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
@@ -5762,7 +5762,7 @@ static void FeatureNewName(ByteReader *buf)
break;
case 0xC9: // House name
- if (_cur.grffile->housespec == NULL || _cur.grffile->housespec[GB(id, 0, 8)] == NULL) {
+ if (_cur.grffile->housespec == nullptr || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
} else {
_cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
@@ -6099,7 +6099,7 @@ static uint32 GetParamVal(byte param, uint32 *cond_val)
}
case 0x85: // TTDPatch flags, only for bit tests
- if (cond_val == NULL) {
+ if (cond_val == nullptr) {
/* Supported in Action 0x07 and 0x09, not 0x0D */
return 0;
} else {
@@ -6142,7 +6142,7 @@ static void CfgApply(ByteReader *buf)
size_t pos = FioGetPos();
uint32 num = _cur.grf_container_ver >= 2 ? FioReadDword() : FioReadWord();
uint8 type = FioReadByte();
- byte *preload_sprite = NULL;
+ byte *preload_sprite = nullptr;
/* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
if (type == 0xFF) {
@@ -6204,7 +6204,7 @@ static void CfgApply(ByteReader *buf)
bool carry = false;
for (i = 0; i < param_size && offset + i < num; i++) {
- uint32 value = GetParamVal(param_num + i / 4, NULL);
+ uint32 value = GetParamVal(param_num + i / 4, nullptr);
/* Reset carry flag for each iteration of the variable (only really
* matters if param_size is greater than 4) */
if (i % 4 == 0) carry = false;
@@ -6290,12 +6290,12 @@ static void SkipIf(ByteReader *buf)
GRFConfig *c = GetGRFConfig(cond_val, mask);
- if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
+ if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
- c = NULL;
+ c = nullptr;
}
- if (condtype != 10 && c == NULL) {
+ if (condtype != 10 && c == nullptr) {
grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
return;
}
@@ -6320,7 +6320,7 @@ static void SkipIf(ByteReader *buf)
case 0x0A: // GRFID is not nor will be active
/* This is the only condtype that doesn't get ignored if the GRFID is not found */
- result = c == NULL || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
+ result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
break;
default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
@@ -6364,12 +6364,12 @@ static void SkipIf(ByteReader *buf)
* file. The jump will always be the first matching label that follows
* the current nfo_line. If no matching label is found, the first matching
* label in the file is used. */
- GRFLabel *choice = NULL;
- for (GRFLabel *label = _cur.grffile->label; label != NULL; label = label->next) {
+ GRFLabel *choice = nullptr;
+ for (GRFLabel *label = _cur.grffile->label; label != nullptr; label = label->next) {
if (label->label != numsprites) continue;
/* Remember a goto before the current line */
- if (choice == NULL) choice = label;
+ if (choice == nullptr) choice = label;
/* If we find a label here, this is definitely good */
if (label->nfo_line > _cur.nfo_line) {
choice = label;
@@ -6377,7 +6377,7 @@ static void SkipIf(ByteReader *buf)
}
}
- if (choice != NULL) {
+ if (choice != nullptr) {
grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
FioSeekTo(choice->pos, SEEK_SET);
_cur.nfo_line = choice->nfo_line;
@@ -6569,7 +6569,7 @@ static void GRFLoadError(ByteReader *buf)
/* Make sure we show fatal errors, instead of silly infos from before */
delete _cur.grfconfig->error;
- _cur.grfconfig->error = NULL;
+ _cur.grfconfig->error = nullptr;
}
if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
@@ -6583,7 +6583,7 @@ static void GRFLoadError(ByteReader *buf)
}
/* For now we can only show one message per newgrf file. */
- if (_cur.grfconfig->error != NULL) return;
+ if (_cur.grfconfig->error != nullptr) return;
GRFError *error = new GRFError(sevstr[severity]);
@@ -6592,7 +6592,7 @@ static void GRFLoadError(ByteReader *buf)
if (buf->HasData()) {
const char *message = buf->ReadString();
- error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, NULL, SCC_RAW_STRING_POINTER);
+ error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, nullptr, SCC_RAW_STRING_POINTER);
} else {
grfmsg(7, "GRFLoadError: No custom message supplied.");
error->custom_message = stredup("");
@@ -6910,11 +6910,11 @@ static void ParamSet(ByteReader *buf)
/* Read another GRF File's parameter */
const GRFFile *file = GetFileByGRFID(data);
GRFConfig *c = GetGRFConfig(data);
- if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
+ if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
/* Disable the read GRF if it is a static NewGRF. */
DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
src1 = 0;
- } else if (file == NULL || c == NULL || c->status == GCS_DISABLED) {
+ } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
src1 = 0;
} else if (src1 == 0xFE) {
src1 = c->version;
@@ -6928,8 +6928,8 @@ static void ParamSet(ByteReader *buf)
* variables available in action 7, or they can be FF to use the value
* of <data>. If referring to parameters that are undefined, a value
* of 0 is used instead. */
- src1 = (src1 == 0xFF) ? data : GetParamVal(src1, NULL);
- src2 = (src2 == 0xFF) ? data : GetParamVal(src2, NULL);
+ src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
+ src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
}
uint32 res;
@@ -7115,7 +7115,7 @@ static void GRFInhibit(ByteReader *buf)
GRFConfig *file = GetGRFConfig(grfid);
/* Unset activation flag */
- if (file != NULL && file != _cur.grfconfig) {
+ if (file != nullptr && file != _cur.grfconfig) {
grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
error->data = stredup(_cur.grfconfig->GetName());
@@ -7221,15 +7221,15 @@ static void DefineGotoLabel(ByteReader *buf)
label->label = nfo_label;
label->nfo_line = _cur.nfo_line;
label->pos = FioGetPos();
- label->next = NULL;
+ label->next = nullptr;
/* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
- if (_cur.grffile->label == NULL) {
+ if (_cur.grffile->label == nullptr) {
_cur.grffile->label = label;
} else {
/* Attach the label to the end of the list */
GRFLabel *l;
- for (l = _cur.grffile->label; l->next != NULL; l = l->next) {}
+ for (l = _cur.grffile->label; l->next != nullptr; l = l->next) {}
l->next = label;
}
@@ -7247,7 +7247,7 @@ static void ImportGRFSound(SoundEntry *sound)
SoundID sound_id = FioReadWord();
file = GetFileByGRFID(grfid);
- if (file == NULL || file->sound_offset == 0) {
+ if (file == nullptr || file->sound_offset == 0) {
grfmsg(1, "ImportGRFSound: Source file not available");
return;
}
@@ -7457,7 +7457,7 @@ static void TranslateGRFStrings(ByteReader *buf)
uint32 grfid = buf->ReadDWord();
const GRFConfig *c = GetGRFConfig(grfid);
- if (c == NULL || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
+ if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
return;
}
@@ -7808,7 +7808,7 @@ static bool ChangeGRFParamValueNames(ByteReader *buf)
if (val_name != _cur_parameter->value_names.End()) {
AddGRFTextToList(&val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
} else {
- GRFText *list = NULL;
+ GRFText *list = nullptr;
AddGRFTextToList(&list, langid, _cur.grfconfig->ident.grfid, false, name_string);
_cur_parameter->value_names.Insert(id, list);
}
@@ -7851,7 +7851,7 @@ static bool HandleParameterInfo(ByteReader *buf)
if (id >= _cur.grfconfig->param_info.size()) {
_cur.grfconfig->param_info.resize(id + 1);
}
- if (_cur.grfconfig->param_info[id] == NULL) {
+ if (_cur.grfconfig->param_info[id] == nullptr) {
_cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
}
_cur_parameter = _cur.grfconfig->param_info[id];
@@ -8094,9 +8094,9 @@ static void ResetCustomStations()
{
for (GRFFile * const file : _grf_files) {
StationSpec **&stations = file->stations;
- if (stations == NULL) continue;
+ if (stations == nullptr) continue;
for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
- if (stations[i] == NULL) continue;
+ if (stations[i] == nullptr) continue;
StationSpec *statspec = stations[i];
delete[] statspec->renderdata;
@@ -8119,7 +8119,7 @@ static void ResetCustomStations()
/* Free and reset the station data */
free(stations);
- stations = NULL;
+ stations = nullptr;
}
}
@@ -8128,13 +8128,13 @@ static void ResetCustomHouses()
{
for (GRFFile * const file : _grf_files) {
HouseSpec **&housespec = file->housespec;
- if (housespec == NULL) continue;
+ if (housespec == nullptr) continue;
for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
free(housespec[i]);
}
free(housespec);
- housespec = NULL;
+ housespec = nullptr;
}
}
@@ -8143,11 +8143,11 @@ static void ResetCustomAirports()
{
for (GRFFile * const file : _grf_files) {
AirportSpec **aslist = file->airportspec;
- if (aslist != NULL) {
+ if (aslist != nullptr) {
for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
AirportSpec *as = aslist[i];
- if (as != NULL) {
+ if (as != nullptr) {
/* We need to remove the tiles layouts */
for (int j = 0; j < as->num_table; j++) {
/* remove the individual layouts */
@@ -8161,16 +8161,16 @@ static void ResetCustomAirports()
}
}
free(aslist);
- file->airportspec = NULL;
+ file->airportspec = nullptr;
}
AirportTileSpec **&airporttilespec = file->airtspec;
- if (airporttilespec != NULL) {
+ if (airporttilespec != nullptr) {
for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
free(airporttilespec[i]);
}
free(airporttilespec);
- airporttilespec = NULL;
+ airporttilespec = nullptr;
}
}
}
@@ -8184,10 +8184,10 @@ static void ResetCustomIndustries()
/* We are verifiying both tiles and industries specs loaded from the grf file
* First, let's deal with industryspec */
- if (industryspec != NULL) {
+ if (industryspec != nullptr) {
for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
IndustrySpec *ind = industryspec[i];
- if (ind == NULL) continue;
+ if (ind == nullptr) continue;
/* We need to remove the sounds array */
if (HasBit(ind->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
@@ -8201,16 +8201,16 @@ static void ResetCustomIndustries()
}
free(industryspec);
- industryspec = NULL;
+ industryspec = nullptr;
}
- if (indtspec == NULL) continue;
+ if (indtspec == nullptr) continue;
for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
free(indtspec[i]);
}
free(indtspec);
- indtspec = NULL;
+ indtspec = nullptr;
}
}
@@ -8219,13 +8219,13 @@ static void ResetCustomObjects()
{
for (GRFFile * const file : _grf_files) {
ObjectSpec **&objectspec = file->objectspec;
- if (objectspec == NULL) continue;
+ if (objectspec == nullptr) continue;
for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
free(objectspec[i]);
}
free(objectspec);
- objectspec = NULL;
+ objectspec = nullptr;
}
}
@@ -8237,16 +8237,16 @@ static void ResetNewGRF()
}
_grf_files.clear();
- _cur.grffile = NULL;
+ _cur.grffile = nullptr;
}
/** Clear all NewGRF errors */
static void ResetNewGRFErrors()
{
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
- if (!HasBit(c->flags, GCF_COPY) && c->error != NULL) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
+ if (!HasBit(c->flags, GCF_COPY) && c->error != nullptr) {
delete c->error;
- c->error = NULL;
+ c->error = nullptr;
}
}
}
@@ -8388,7 +8388,7 @@ static void BuildCargoTranslationMap()
static void InitNewGRFFile(const GRFConfig *config)
{
GRFFile *newfile = GetFileByFilename(config->filename);
- if (newfile != NULL) {
+ if (newfile != nullptr) {
/* We already loaded it once. */
_cur.grffile = newfile;
return;
@@ -8546,16 +8546,16 @@ static void CalculateRefitMasks()
* cargo type. Finally disable the vehicle, if there is still no cargo. */
if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
/* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
- const uint8 *cargo_map_for_first_refittable = NULL;
+ const uint8 *cargo_map_for_first_refittable = nullptr;
{
const GRFFile *file = _gted[engine].defaultcargo_grf;
- if (file == NULL) file = e->GetGRF();
- if (file != NULL && file->grf_version >= 8 && file->cargo_list.size() != 0) {
+ if (file == nullptr) file = e->GetGRF();
+ if (file != nullptr && file->grf_version >= 8 && file->cargo_list.size() != 0) {
cargo_map_for_first_refittable = file->cargo_map;
}
}
- if (cargo_map_for_first_refittable != NULL) {
+ if (cargo_map_for_first_refittable != nullptr) {
/* Use first refittable cargo from cargo translation table */
byte best_local_slot = 0xFF;
CargoID cargo_type;
@@ -8586,7 +8586,7 @@ static void CalculateRefitMasks()
static void FinaliseCanals()
{
for (uint i = 0; i < CF_END; i++) {
- if (_water_feature[i].grffile != NULL) {
+ if (_water_feature[i].grffile != nullptr) {
_water_feature[i].callback_mask = _water_feature[i].grffile->canal_local_properties[i].callback_mask;
_water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags;
}
@@ -8599,7 +8599,7 @@ static void FinaliseEngineArray()
Engine *e;
FOR_ALL_ENGINES(e) {
- if (e->GetGRF() == NULL) {
+ if (e->GetGRF() == nullptr) {
const EngineIDMapping &eid = _engine_mngr[e->index];
if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
@@ -8611,13 +8611,13 @@ static void FinaliseEngineArray()
/* When the train does not set property 27 (misc flags), but it
* is overridden by a NewGRF graphically we want to disable the
* flipping possibility. */
- if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
+ if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
ClrBit(e->info.misc_flags, EF_RAIL_FLIPS);
}
/* Skip wagons, there livery is defined via the engine */
if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
- LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, NULL);
+ LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr);
SetBit(_loaded_newgrf_features.used_liveries, ls);
/* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
@@ -8671,12 +8671,12 @@ static void FinaliseCargoArray()
static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
{
if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
- (next1 == NULL || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
+ (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
- (next2 == NULL || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
- next3 == NULL || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
+ (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
+ next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
hs->enabled = false;
- if (filename != NULL) DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
+ if (filename != nullptr) DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
return false;
}
@@ -8686,13 +8686,13 @@ static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseS
if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
hs->enabled = false;
- if (filename != NULL) DEBUG(grf, 1, "FinaliseHouseArray: %s defines multitile house %d with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
+ if (filename != nullptr) DEBUG(grf, 1, "FinaliseHouseArray: %s defines multitile house %d with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
return false;
}
/* Substitute type is also used for override, and having an override with a different size causes crashes.
* This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
- if (filename != NULL && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
+ if (filename != nullptr && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
hs->enabled = false;
DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
return false;
@@ -8701,7 +8701,7 @@ static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseS
/* Make sure that additional parts of multitile houses are not available. */
if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
hs->enabled = false;
- if (filename != NULL) DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
+ if (filename != nullptr) DEBUG(grf, 1, "FinaliseHouseArray: %s defines house %d without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
return false;
}
@@ -8720,7 +8720,7 @@ static void EnsureEarlyHouse(HouseZones bitmask)
for (int i = 0; i < NUM_HOUSES; i++) {
HouseSpec *hs = HouseSpec::Get(i);
- if (hs == NULL || !hs->enabled) continue;
+ if (hs == nullptr || !hs->enabled) continue;
if ((hs->building_availability & bitmask) != bitmask) continue;
if (hs->min_year < min_year) min_year = hs->min_year;
}
@@ -8729,7 +8729,7 @@ static void EnsureEarlyHouse(HouseZones bitmask)
for (int i = 0; i < NUM_HOUSES; i++) {
HouseSpec *hs = HouseSpec::Get(i);
- if (hs == NULL || !hs->enabled) continue;
+ if (hs == nullptr || !hs->enabled) continue;
if ((hs->building_availability & bitmask) != bitmask) continue;
if (hs->min_year == min_year) hs->min_year = 0;
}
@@ -8754,16 +8754,16 @@ static void FinaliseHouseArray()
*/
for (GRFFile * const file : _grf_files) {
HouseSpec **&housespec = file->housespec;
- if (housespec == NULL) continue;
+ if (housespec == nullptr) continue;
for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
HouseSpec *hs = housespec[i];
- if (hs == NULL) continue;
+ if (hs == nullptr) continue;
- const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : NULL);
- const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : NULL);
- const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : NULL);
+ const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : nullptr);
+ const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : nullptr);
+ const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : nullptr);
if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
@@ -8773,13 +8773,13 @@ static void FinaliseHouseArray()
for (int i = 0; i < NUM_HOUSES; i++) {
HouseSpec *hs = HouseSpec::Get(i);
- const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : NULL);
- const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : NULL);
- const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : NULL);
+ const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
+ const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
+ const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
/* We need to check all houses again to we are sure that multitile houses
* did get consecutive IDs and none of the parts are missing. */
- if (!IsHouseSpecValid(hs, next1, next2, next3, NULL)) {
+ if (!IsHouseSpecValid(hs, next1, next2, next3, nullptr)) {
/* GetHouseNorthPart checks 3 houses that are directly before
* it in the house pool. If any of those houses have multi-tile
* flags set it assumes it's part of a multitile house. Since
@@ -8817,11 +8817,11 @@ static void FinaliseIndustriesArray()
for (GRFFile * const file : _grf_files) {
IndustrySpec **&industryspec = file->industryspec;
IndustryTileSpec **&indtspec = file->indtspec;
- if (industryspec != NULL) {
+ if (industryspec != nullptr) {
for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
IndustrySpec *indsp = industryspec[i];
- if (indsp != NULL && indsp->enabled) {
+ if (indsp != nullptr && indsp->enabled) {
StringID strid;
/* process the conversion of text at the end, so to be sure everything will be fine
* and available. Check if it does not return undefind marker, which is a very good sign of a
@@ -8854,10 +8854,10 @@ static void FinaliseIndustriesArray()
}
}
- if (indtspec != NULL) {
+ if (indtspec != nullptr) {
for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
IndustryTileSpec *indtsp = indtspec[i];
- if (indtsp != NULL) {
+ if (indtsp != nullptr) {
_industile_mngr.SetEntitySpec(indtsp);
}
}
@@ -8866,7 +8866,7 @@ static void FinaliseIndustriesArray()
for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
IndustrySpec *indsp = &_industry_specs[j];
- if (indsp->enabled && indsp->grf_prop.grffile != NULL) {
+ if (indsp->enabled && indsp->grf_prop.grffile != nullptr) {
for (uint i = 0; i < 3; i++) {
indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
}
@@ -8886,9 +8886,9 @@ static void FinaliseObjectsArray()
{
for (GRFFile * const file : _grf_files) {
ObjectSpec **&objectspec = file->objectspec;
- if (objectspec != NULL) {
+ if (objectspec != nullptr) {
for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
- if (objectspec[i] != NULL && objectspec[i]->grf_prop.grffile != NULL && objectspec[i]->enabled) {
+ if (objectspec[i] != nullptr && objectspec[i]->grf_prop.grffile != nullptr && objectspec[i]->enabled) {
_object_mngr.SetEntitySpec(objectspec[i]);
}
}
@@ -8905,18 +8905,18 @@ static void FinaliseAirportsArray()
{
for (GRFFile * const file : _grf_files) {
AirportSpec **&airportspec = file->airportspec;
- if (airportspec != NULL) {
+ if (airportspec != nullptr) {
for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
- if (airportspec[i] != NULL && airportspec[i]->enabled) {
+ if (airportspec[i] != nullptr && airportspec[i]->enabled) {
_airport_mngr.SetEntitySpec(airportspec[i]);
}
}
}
AirportTileSpec **&airporttilespec = file->airtspec;
- if (airporttilespec != NULL) {
+ if (airporttilespec != nullptr) {
for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
- if (airporttilespec[i] != NULL && airporttilespec[i]->enabled) {
+ if (airporttilespec[i] != nullptr && airporttilespec[i]->enabled) {
_airporttile_mngr.SetEntitySpec(airporttilespec[i]);
}
}
@@ -8945,27 +8945,27 @@ static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
* is not in memory and scanning the file every time would be too expensive.
* In other stages we skip action 0x10 since it's already dealt with. */
static const SpecialSpriteHandler handlers[][GLS_END] = {
- /* 0x00 */ { NULL, SafeChangeInfo, NULL, NULL, ReserveChangeInfo, FeatureChangeInfo, },
+ /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
/* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
- /* 0x02 */ { NULL, NULL, NULL, NULL, NULL, NewSpriteGroup, },
- /* 0x03 */ { NULL, GRFUnsafe, NULL, NULL, NULL, FeatureMapSpriteGroup, },
- /* 0x04 */ { NULL, NULL, NULL, NULL, NULL, FeatureNewName, },
+ /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
+ /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
+ /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
/* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
- /* 0x06 */ { NULL, NULL, NULL, CfgApply, CfgApply, CfgApply, },
- /* 0x07 */ { NULL, NULL, NULL, NULL, SkipIf, SkipIf, },
- /* 0x08 */ { ScanInfo, NULL, NULL, GRFInfo, GRFInfo, GRFInfo, },
- /* 0x09 */ { NULL, NULL, NULL, SkipIf, SkipIf, SkipIf, },
+ /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
+ /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
+ /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
+ /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
/* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
- /* 0x0B */ { NULL, NULL, NULL, GRFLoadError, GRFLoadError, GRFLoadError, },
- /* 0x0C */ { NULL, NULL, NULL, GRFComment, NULL, GRFComment, },
- /* 0x0D */ { NULL, SafeParamSet, NULL, ParamSet, ParamSet, ParamSet, },
- /* 0x0E */ { NULL, SafeGRFInhibit, NULL, GRFInhibit, GRFInhibit, GRFInhibit, },
- /* 0x0F */ { NULL, GRFUnsafe, NULL, FeatureTownName, NULL, NULL, },
- /* 0x10 */ { NULL, NULL, DefineGotoLabel, NULL, NULL, NULL, },
+ /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
+ /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
+ /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
+ /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
+ /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
+ /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
/* 0x11 */ { SkipAct11,GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
/* 0x12 */ { SkipAct12, SkipAct12, SkipAct12, SkipAct12, SkipAct12, LoadFontGlyph, },
- /* 0x13 */ { NULL, NULL, NULL, NULL, NULL, TranslateGRFStrings, },
- /* 0x14 */ { StaticGRFInfo, NULL, NULL, NULL, NULL, NULL, },
+ /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
+ /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
};
GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
@@ -8996,7 +8996,7 @@ static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
} else if (action >= lengthof(handlers)) {
grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
- } else if (handlers[action][stage] == NULL) {
+ } else if (handlers[action][stage] == nullptr) {
grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
} else {
grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
@@ -9057,7 +9057,7 @@ void LoadNewGRFFile(GRFConfig *config, uint file_index, GrfLoadingStage stage, S
* processed once at initialization. */
if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
_cur.grffile = GetFileByFilename(filename);
- if (_cur.grffile == NULL) usererror("File '%s' lost in cache.\n", filename);
+ if (_cur.grffile == nullptr) usererror("File '%s' lost in cache.\n", filename);
if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
}
@@ -9212,7 +9212,7 @@ static void FinalisePriceBaseMultipliers()
if (override == 0) continue;
GRFFile *dest = GetFileByGRFID(override);
- if (dest == NULL) continue;
+ if (dest == nullptr) continue;
grf_overrides[i] = find_index(_grf_files, dest);
assert(grf_overrides[i] >= 0);
@@ -9437,7 +9437,7 @@ void LoadNewGRF(uint load_index, uint file_index, uint num_baseset)
* be reset, the NewGRF would remain disabled even though it should
* have been enabled.
*/
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
}
@@ -9449,7 +9449,7 @@ void LoadNewGRF(uint load_index, uint file_index, uint num_baseset)
for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
/* Set activated grfs back to will-be-activated between reservation- and activation-stage.
* This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
}
@@ -9468,7 +9468,7 @@ void LoadNewGRF(uint load_index, uint file_index, uint num_baseset)
uint num_non_static = 0;
_cur.stage = stage;
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
diff --git a/src/newgrf_airport.cpp b/src/newgrf_airport.cpp
index 615292aef..8ec390a4f 100644
--- a/src/newgrf_airport.cpp
+++ b/src/newgrf_airport.cpp
@@ -21,7 +21,7 @@
/** Resolver for the airport scope. */
struct AirportScopeResolver : public ScopeResolver {
- struct Station *st; ///< Station of the airport for which the callback is run, or \c NULL for build gui.
+ struct Station *st; ///< Station of the airport for which the callback is run, or \c nullptr for build gui.
byte airport_id; ///< Type of airport for which the callback is run.
byte layout; ///< Layout of the airport to build.
TileIndex tile; ///< Tile for the callback, only valid for airporttile callbacks.
@@ -30,7 +30,7 @@ struct AirportScopeResolver : public ScopeResolver {
* Constructor of the scope resolver for an airport.
* @param ro Surrounding resolver.
* @param tile %Tile for the callback, only valid for airporttile callbacks.
- * @param st %Station of the airport for which the callback is run, or \c NULL for build gui.
+ * @param st %Station of the airport for which the callback is run, or \c nullptr for build gui.
* @param airport_id Type of airport for which the callback is run.
* @param layout Layout of the airport to build.
*/
@@ -202,14 +202,14 @@ void AirportOverrideManager::SetEntitySpec(AirportSpec *as)
case 0x40: return this->layout;
}
- if (this->st == NULL) {
+ if (this->st == nullptr) {
*available = false;
return UINT_MAX;
}
switch (variable) {
/* Get a variable from the persistent storage */
- case 0x7C: return (this->st->airport.psa != NULL) ? this->st->airport.psa->GetValue(parameter) : 0;
+ case 0x7C: return (this->st->airport.psa != nullptr) ? this->st->airport.psa->GetValue(parameter) : 0;
case 0xF0: return this->st->facilities;
case 0xFA: return Clamp(this->st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
@@ -225,12 +225,12 @@ void AirportOverrideManager::SetEntitySpec(AirportSpec *as)
if (group->num_loaded > 0) return group->loaded[0];
if (group->num_loading > 0) return group->loading[0];
- return NULL;
+ return nullptr;
}
/* virtual */ uint32 AirportScopeResolver::GetRandomBits() const
{
- return this->st == NULL ? 0 : this->st->random_bits;
+ return this->st == nullptr ? 0 : this->st->random_bits;
}
/**
@@ -240,14 +240,14 @@ void AirportOverrideManager::SetEntitySpec(AirportSpec *as)
*/
/* virtual */ void AirportScopeResolver::StorePSA(uint pos, int32 value)
{
- if (this->st == NULL) return;
+ if (this->st == nullptr) return;
- if (this->st->airport.psa == NULL) {
+ if (this->st->airport.psa == nullptr) {
/* There is no need to create a storage if the value is zero. */
if (value == 0) return;
/* Create storage on first modification. */
- uint32 grfid = (this->ro.grffile != NULL) ? this->ro.grffile->grfid : 0;
+ uint32 grfid = (this->ro.grffile != nullptr) ? this->ro.grffile->grfid : 0;
assert(PersistentStorage::CanAllocateItem());
this->st->airport.psa = new PersistentStorage(grfid, GSF_AIRPORTS, this->st->airport.tile);
}
@@ -257,7 +257,7 @@ void AirportOverrideManager::SetEntitySpec(AirportSpec *as)
/**
* Constructor of the airport resolver.
* @param tile %Tile for the callback, only valid for airporttile callbacks.
- * @param st %Station of the airport for which the callback is run, or \c NULL for build gui.
+ * @param st %Station of the airport for which the callback is run, or \c nullptr for build gui.
* @param airport_id Type of airport for which the callback is run.
* @param layout Layout of the airport to build.
* @param callback Callback ID.
@@ -273,9 +273,9 @@ AirportResolverObject::AirportResolverObject(TileIndex tile, Station *st, byte a
SpriteID GetCustomAirportSprite(const AirportSpec *as, byte layout)
{
- AirportResolverObject object(INVALID_TILE, NULL, as->GetIndex(), layout);
+ AirportResolverObject object(INVALID_TILE, nullptr, as->GetIndex(), layout);
const SpriteGroup *group = object.Resolve();
- if (group == NULL) return as->preview_sprite;
+ if (group == nullptr) return as->preview_sprite;
return group->GetResult();
}
@@ -295,7 +295,7 @@ uint16 GetAirportCallback(CallbackID callback, uint32 param1, uint32 param2, Sta
*/
StringID GetAirportTextCallback(const AirportSpec *as, byte layout, uint16 callback)
{
- AirportResolverObject object(INVALID_TILE, NULL, as->GetIndex(), layout, (CallbackID)callback);
+ AirportResolverObject object(INVALID_TILE, nullptr, as->GetIndex(), layout, (CallbackID)callback);
uint16 cb_res = object.ResolveCallback();
if (cb_res == CALLBACK_FAILED || cb_res == 0x400) return STR_UNDEFINED;
if (cb_res > 0x400) {
diff --git a/src/newgrf_airporttiles.cpp b/src/newgrf_airporttiles.cpp
index 2d3a5129c..42f4f1d36 100644
--- a/src/newgrf_airporttiles.cpp
+++ b/src/newgrf_airporttiles.cpp
@@ -149,7 +149,7 @@ static uint32 GetAirportTileIDAtOffset(TileIndex tile, const Station *st, uint32
}
}
/* Not an 'old type' tile */
- if (ats->grf_prop.spritegroup[0] != NULL) { // tile has a spritegroup ?
+ if (ats->grf_prop.spritegroup[0] != nullptr) { // tile has a spritegroup ?
if (ats->grf_prop.grffile->grfid == cur_grfid) { // same airport, same grf ?
return ats->grf_prop.local_id;
} else {
@@ -162,7 +162,7 @@ static uint32 GetAirportTileIDAtOffset(TileIndex tile, const Station *st, uint32
/* virtual */ uint32 AirportTileScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
{
- assert(this->st != NULL);
+ assert(this->st != nullptr);
extern uint32 GetRelativePosition(TileIndex tile, TileIndex ind_tile);
@@ -203,14 +203,14 @@ static uint32 GetAirportTileIDAtOffset(TileIndex tile, const Station *st, uint32
/* virtual */ uint32 AirportTileScopeResolver::GetRandomBits() const
{
- return (this->st == NULL ? 0 : this->st->random_bits) | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits(this->tile) << 16);
+ return (this->st == nullptr ? 0 : this->st->random_bits) | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits(this->tile) << 16);
}
/**
* Constructor of the resolver for airport tiles.
* @param ats Specification of the airport tiles.
* @param tile %Tile for the callback, only valid for airporttile callbacks.
- * @param st Station of the airport for which the callback is run, or \c NULL for build gui.
+ * @param st Station of the airport for which the callback is run, or \c nullptr for build gui.
* @param callback Callback ID.
* @param callback_param1 First parameter (var 10) of the callback.
* @param callback_param2 Second parameter (var 18) of the callback.
@@ -230,7 +230,7 @@ uint16 GetAirportTileCallback(CallbackID callback, uint32 param1, uint32 param2,
static void AirportDrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGroup *group, byte colour, StationGfx gfx)
{
- const DrawTileSprites *dts = group->ProcessRegisters(NULL);
+ const DrawTileSprites *dts = group->ProcessRegisters(nullptr);
SpriteID image = dts->ground.sprite;
SpriteID pal = dts->ground.pal;
@@ -261,7 +261,7 @@ bool DrawNewAirportTile(TileInfo *ti, Station *st, StationGfx gfx, const Airport
AirportTileResolverObject object(airts, ti->tile, st);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->type != SGT_TILELAYOUT) {
+ if (group == nullptr || group->type != SGT_TILELAYOUT) {
return false;
}
@@ -282,7 +282,7 @@ struct AirportTileAnimationBase : public AnimationBase<AirportTileAnimationBase,
void AnimateAirportTile(TileIndex tile)
{
const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
- if (ats == NULL) return;
+ if (ats == nullptr) return;
AirportTileAnimationBase::AnimateTile(ats, Station::GetByTile(tile), tile, HasBit(ats->animation_special_flags, 0));
}
diff --git a/src/newgrf_airporttiles.h b/src/newgrf_airporttiles.h
index e55409c1b..313614eaf 100644
--- a/src/newgrf_airporttiles.h
+++ b/src/newgrf_airporttiles.h
@@ -21,7 +21,7 @@
/** Scope resolver for handling the tiles of an airport. */
struct AirportTileScopeResolver : public ScopeResolver {
- struct Station *st; ///< %Station of the airport for which the callback is run, or \c NULL for build gui.
+ struct Station *st; ///< %Station of the airport for which the callback is run, or \c nullptr for build gui.
byte airport_id; ///< Type of airport for which the callback is run.
TileIndex tile; ///< Tile for the callback, only valid for airporttile callbacks.
@@ -29,12 +29,12 @@ struct AirportTileScopeResolver : public ScopeResolver {
* Constructor of the scope resolver specific for airport tiles.
* @param ats Specification of the airport tiles.
* @param tile %Tile for the callback, only valid for airporttile callbacks.
- * @param st Station of the airport for which the callback is run, or \c NULL for build gui.
+ * @param st Station of the airport for which the callback is run, or \c nullptr for build gui.
*/
AirportTileScopeResolver(ResolverObject &ro, const AirportTileSpec *ats, TileIndex tile, Station *st)
: ScopeResolver(ro), st(st), tile(tile)
{
- assert(st != NULL);
+ assert(st != nullptr);
this->airport_id = st->airport.type;
}
diff --git a/src/newgrf_animation_base.h b/src/newgrf_animation_base.h
index 791f3d691..8f1135a6b 100644
--- a/src/newgrf_animation_base.h
+++ b/src/newgrf_animation_base.h
@@ -39,7 +39,7 @@ struct AnimationBase {
*/
static void AnimateTile(const Tspec *spec, Tobj *obj, TileIndex tile, bool random_animation, Textra extra_data = 0)
{
- assert(spec != NULL);
+ assert(spec != nullptr);
/* Acquire the animation speed from the NewGRF. */
uint8 animation_speed = spec->animation.speed;
diff --git a/src/newgrf_canal.cpp b/src/newgrf_canal.cpp
index 32180ee1a..61ba601d5 100644
--- a/src/newgrf_canal.cpp
+++ b/src/newgrf_canal.cpp
@@ -108,7 +108,7 @@ struct CanalResolverObject : public ResolverObject {
/* virtual */ const SpriteGroup *CanalResolverObject::ResolveReal(const RealSpriteGroup *group) const
{
- if (group->num_loaded == 0) return NULL;
+ if (group->num_loaded == 0) return nullptr;
return group->loaded[0];
}
@@ -138,7 +138,7 @@ SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
{
CanalResolverObject object(feature, tile);
const SpriteGroup *group = object.Resolve();
- if (group == NULL) return 0;
+ if (group == nullptr) return 0;
return group->GetResult();
}
diff --git a/src/newgrf_cargo.cpp b/src/newgrf_cargo.cpp
index 58d4102d3..0793d7120 100644
--- a/src/newgrf_cargo.cpp
+++ b/src/newgrf_cargo.cpp
@@ -29,7 +29,7 @@ struct CargoResolverObject : public ResolverObject {
if (group->num_loaded > 0) return group->loaded[0];
if (group->num_loading > 0) return group->loading[0];
- return NULL;
+ return nullptr;
}
/**
@@ -54,7 +54,7 @@ SpriteID GetCustomCargoSprite(const CargoSpec *cs)
{
CargoResolverObject object(cs);
const SpriteGroup *group = object.Resolve();
- if (group == NULL) return 0;
+ if (group == nullptr) return 0;
return group->GetResult();
}
diff --git a/src/newgrf_class_func.h b/src/newgrf_class_func.h
index c2a30992a..0a90bf80e 100644
--- a/src/newgrf_class_func.h
+++ b/src/newgrf_class_func.h
@@ -34,7 +34,7 @@ DEFINE_NEWGRF_CLASS_METHOD(void)::ResetClass()
this->ui_count = 0;
free(this->spec);
- this->spec = NULL;
+ this->spec = nullptr;
}
/** Reset the classes, i.e. clear everything. */
@@ -154,7 +154,7 @@ DEFINE_NEWGRF_CLASS_METHOD(Tid)::GetUIClass(uint index)
DEFINE_NEWGRF_CLASS_METHOD(const Tspec *)::GetSpec(uint index) const
{
/* If the custom spec isn't defined any more, then the GRF file probably was not loaded. */
- return index < this->GetSpecCount() ? this->spec[index] : NULL;
+ return index < this->GetSpecCount() ? this->spec[index] : nullptr;
}
/**
@@ -191,7 +191,7 @@ DEFINE_NEWGRF_CLASS_METHOD(int)::GetUIFromIndex(int index) const
* Retrieve a spec by GRF location.
* @param grfid GRF ID of spec.
* @param local_id Index within GRF file of spec.
- * @param index Pointer to return the index of the spec in its class. If NULL then not used.
+ * @param index Pointer to return the index of the spec in its class. If nullptr then not used.
* @return The spec.
*/
DEFINE_NEWGRF_CLASS_METHOD(const Tspec *)::GetByGrf(uint32 grfid, byte local_id, int *index)
@@ -201,15 +201,15 @@ DEFINE_NEWGRF_CLASS_METHOD(const Tspec *)::GetByGrf(uint32 grfid, byte local_id,
for (Tid i = (Tid)0; i < Tmax; i++) {
for (j = 0; j < classes[i].count; j++) {
const Tspec *spec = classes[i].spec[j];
- if (spec == NULL) continue;
+ if (spec == nullptr) continue;
if (spec->grf_prop.grffile->grfid == grfid && spec->grf_prop.local_id == local_id) {
- if (index != NULL) *index = j;
+ if (index != nullptr) *index = j;
return spec;
}
}
}
- return NULL;
+ return nullptr;
}
#undef DEFINE_NEWGRF_CLASS_METHOD
diff --git a/src/newgrf_commons.cpp b/src/newgrf_commons.cpp
index e05217fee..c80f0e350 100644
--- a/src/newgrf_commons.cpp
+++ b/src/newgrf_commons.cpp
@@ -235,9 +235,9 @@ uint16 IndustryOverrideManager::AddEntityID(byte grf_local_id, uint32 grfid, byt
const IndustrySpec *inds = GetIndustrySpec(id);
/* This industry must be one that is not available(enabled), mostly because of climate.
- * And it must not already be used by a grf (grffile == NULL).
+ * And it must not already be used by a grf (grffile == nullptr).
* So reserve this slot here, as it is the chosen one */
- if (!inds->enabled && inds->grf_prop.grffile == NULL) {
+ if (!inds->enabled && inds->grf_prop.grffile == nullptr) {
EntityIDMapping *map = &mapping_ID[id];
if (map->entity_id == 0 && map->grfid == 0) {
@@ -463,13 +463,13 @@ uint32 GetNearbyTileInformation(TileIndex tile, bool grf_version8)
/**
* Returns company information like in vehicle var 43 or station var 43.
* @param owner Owner of the object.
- * @param l Livery of the object; NULL to use default.
+ * @param l Livery of the object; nullptr to use default.
* @return NewGRF company information.
*/
uint32 GetCompanyInfo(CompanyID owner, const Livery *l)
{
- if (l == NULL && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT];
- return owner | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != NULL ? (l->colour1 << 24) | (l->colour2 << 28) : 0);
+ if (l == nullptr && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT];
+ return owner | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != nullptr ? (l->colour1 << 24) | (l->colour2 << 28) : 0);
}
/**
@@ -587,8 +587,8 @@ bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_r
*/
void NewGRFSpriteLayout::Clone(const DrawTileSeqStruct *source)
{
- assert(this->seq == NULL);
- assert(source != NULL);
+ assert(this->seq == nullptr);
+ assert(source != nullptr);
size_t count = 1; // 1 for the terminator
const DrawTileSeqStruct *element;
@@ -607,7 +607,7 @@ void NewGRFSpriteLayout::Clone(const NewGRFSpriteLayout *source)
{
this->Clone((const DrawTileSprites*)source);
- if (source->registers != NULL) {
+ if (source->registers != nullptr) {
size_t count = 1; // 1 for the ground sprite
const DrawTileSeqStruct *element;
foreach_draw_tile_seq(element, source->seq) count++;
@@ -625,7 +625,7 @@ void NewGRFSpriteLayout::Clone(const NewGRFSpriteLayout *source)
*/
void NewGRFSpriteLayout::Allocate(uint num_sprites)
{
- assert(this->seq == NULL);
+ assert(this->seq == nullptr);
DrawTileSeqStruct *sprites = CallocT<DrawTileSeqStruct>(num_sprites + 1);
sprites[num_sprites].MakeTerminator();
@@ -637,8 +637,8 @@ void NewGRFSpriteLayout::Allocate(uint num_sprites)
*/
void NewGRFSpriteLayout::AllocateRegisters()
{
- assert(this->seq != NULL);
- assert(this->registers == NULL);
+ assert(this->seq != nullptr);
+ assert(this->registers == nullptr);
size_t count = 1; // 1 for the ground sprite
const DrawTileSeqStruct *element;
@@ -685,7 +685,7 @@ uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_groun
bool ground = true;
foreach_draw_tile_seq(result, result_seq.data()) {
TileLayoutFlags flags = TLF_NOTHING;
- if (regs != NULL) flags = regs->flags;
+ if (regs != nullptr) flags = regs->flags;
/* Record var10 value for the sprite */
if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
@@ -697,7 +697,7 @@ uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_groun
if (!(flags & TLF_SPRITE)) {
if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
- if (constr_stage > 0 && regs != NULL) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_sprite_offset);
+ if (constr_stage > 0 && regs != nullptr) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_sprite_offset);
} else {
result->image.sprite += orig_offset;
}
@@ -713,12 +713,12 @@ uint32 NewGRFSpriteLayout::PrepareLayout(uint32 orig_offset, uint32 newgrf_groun
if (!(flags & TLF_PALETTE)) {
if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
- if (constr_stage > 0 && regs != NULL) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_palette_offset);
+ if (constr_stage > 0 && regs != nullptr) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_palette_offset);
}
}
ground = false;
- if (regs != NULL) regs++;
+ if (regs != nullptr) regs++;
}
return var10_values;
@@ -739,7 +739,7 @@ void NewGRFSpriteLayout::ProcessRegisters(uint8 resolved_var10, uint32 resolved_
bool ground = true;
foreach_draw_tile_seq(result, result_seq.data()) {
TileLayoutFlags flags = TLF_NOTHING;
- if (regs != NULL) flags = regs->flags;
+ if (regs != nullptr) flags = regs->flags;
/* Is the sprite or bounding box affected by an action-1-2-3 chain? */
if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
@@ -794,6 +794,6 @@ void NewGRFSpriteLayout::ProcessRegisters(uint8 resolved_var10, uint32 resolved_
}
ground = false;
- if (regs != NULL) regs++;
+ if (regs != nullptr) regs++;
}
}
diff --git a/src/newgrf_commons.h b/src/newgrf_commons.h
index 819e84451..ec6c454a0 100644
--- a/src/newgrf_commons.h
+++ b/src/newgrf_commons.h
@@ -132,7 +132,7 @@ struct NewGRFSpriteLayout : ZeroedMemoryAllocator, DrawTileSprites {
*/
void Clone(const DrawTileSprites *source)
{
- assert(source != NULL && this != source);
+ assert(source != nullptr && this != source);
this->ground = source->ground;
this->Clone(source->seq);
}
@@ -151,7 +151,7 @@ struct NewGRFSpriteLayout : ZeroedMemoryAllocator, DrawTileSprites {
*/
bool NeedsPreprocessing() const
{
- return this->registers != NULL;
+ return this->registers != nullptr;
}
uint32 PrepareLayout(uint32 orig_offset, uint32 newgrf_ground_offset, uint32 newgrf_offset, uint constr_stage, bool separate_ground) const;
@@ -298,7 +298,7 @@ extern ObjectOverrideManager _object_mngr;
uint32 GetTerrainType(TileIndex tile, TileContext context = TCX_NORMAL);
TileIndex GetNearbyTile(byte parameter, TileIndex tile, bool signed_offsets = true, Axis axis = INVALID_AXIS);
uint32 GetNearbyTileInformation(TileIndex tile, bool grf_version8);
-uint32 GetCompanyInfo(CompanyID owner, const struct Livery *l = NULL);
+uint32 GetCompanyInfo(CompanyID owner, const struct Livery *l = nullptr);
CommandCost GetErrorMessageFromLocationCallbackResult(uint16 cb_res, const GRFFile *grffile, StringID default_error);
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res);
diff --git a/src/newgrf_config.cpp b/src/newgrf_config.cpp
index acde37063..2eef5d183 100644
--- a/src/newgrf_config.cpp
+++ b/src/newgrf_config.cpp
@@ -31,7 +31,7 @@
/** Create a new GRFTextWrapper. */
GRFTextWrapper::GRFTextWrapper() :
- text(NULL)
+ text(nullptr)
{
}
@@ -52,7 +52,7 @@ GRFConfig::GRFConfig(const char *filename) :
url(new GRFTextWrapper()),
num_valid_params(lengthof(param))
{
- if (filename != NULL) this->filename = stredup(filename);
+ if (filename != nullptr) this->filename = stredup(filename);
this->name->AddRef();
this->info->AddRef();
this->url->AddRef();
@@ -80,14 +80,14 @@ GRFConfig::GRFConfig(const GRFConfig &config) :
{
MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
- if (config.filename != NULL) this->filename = stredup(config.filename);
+ if (config.filename != nullptr) this->filename = stredup(config.filename);
this->name->AddRef();
this->info->AddRef();
this->url->AddRef();
- if (config.error != NULL) this->error = new GRFError(*config.error);
+ if (config.error != nullptr) this->error = new GRFError(*config.error);
for (uint i = 0; i < config.param_info.size(); i++) {
- if (config.param_info[i] == NULL) {
- this->param_info.push_back(NULL);
+ if (config.param_info[i] == nullptr) {
+ this->param_info.push_back(nullptr);
} else {
this->param_info.push_back(new GRFParameterInfo(*config.param_info[i]));
}
@@ -158,7 +158,7 @@ void GRFConfig::SetParameterDefaults()
if (!this->has_param_defaults) return;
for (uint i = 0; i < this->param_info.size(); i++) {
- if (this->param_info[i] == NULL) continue;
+ if (this->param_info[i] == nullptr) continue;
this->param_info[i]->SetValue(this, this->param_info[i]->def_value);
}
}
@@ -185,7 +185,7 @@ void GRFConfig::SetSuitablePalette()
void GRFConfig::FinalizeParameterInfo()
{
for (GRFParameterInfo *info : this->param_info) {
- if (info == NULL) continue;
+ if (info == nullptr) continue;
info->Finalize();
}
}
@@ -218,8 +218,8 @@ GRFError::GRFError(const GRFError &error) :
message(error.message),
severity(error.severity)
{
- if (error.custom_message != NULL) this->custom_message = stredup(error.custom_message);
- if (error.data != NULL) this->data = stredup(error.data);
+ if (error.custom_message != nullptr) this->custom_message = stredup(error.custom_message);
+ if (error.data != nullptr) this->data = stredup(error.data);
memcpy(this->param_value, error.param_value, sizeof(this->param_value));
}
@@ -234,8 +234,8 @@ GRFError::~GRFError()
* @param nr The newgrf parameter that is changed.
*/
GRFParameterInfo::GRFParameterInfo(uint nr) :
- name(NULL),
- desc(NULL),
+ name(nullptr),
+ desc(nullptr),
type(PTYPE_UINT_ENUM),
min_value(0),
max_value(UINT32_MAX),
@@ -331,9 +331,9 @@ void GRFParameterInfo::Finalize()
*/
bool UpdateNewGRFConfigPalette(int32 p1)
{
- for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->SetSuitablePalette();
- for (GRFConfig *c = _grfconfig_static; c != NULL; c = c->next) c->SetSuitablePalette();
- for (GRFConfig *c = _all_grfs; c != NULL; c = c->next) c->SetSuitablePalette();
+ for (GRFConfig *c = _grfconfig_newgame; c != nullptr; c = c->next) c->SetSuitablePalette();
+ for (GRFConfig *c = _grfconfig_static; c != nullptr; c = c->next) c->SetSuitablePalette();
+ for (GRFConfig *c = _all_grfs; c != nullptr; c = c->next) c->SetSuitablePalette();
return true;
}
@@ -381,7 +381,7 @@ static bool CalcGRFMD5Sum(GRFConfig *config, Subdirectory subdir)
/* open the file */
f = FioFOpenFile(config->filename, "rb", subdir, &size);
- if (f == NULL) return false;
+ if (f == nullptr) return false;
long start = ftell(f);
size = min(size, GRFGetSizeOfDataSection(f));
@@ -441,16 +441,16 @@ bool FillGRFDetails(GRFConfig *config, bool is_static, Subdirectory subdir)
/**
* Clear a GRF Config list, freeing all nodes.
* @param config Start of the list.
- * @post \a config is set to \c NULL.
+ * @post \a config is set to \c nullptr.
*/
void ClearGRFConfigList(GRFConfig **config)
{
GRFConfig *c, *next;
- for (c = *config; c != NULL; c = next) {
+ for (c = *config; c != nullptr; c = next) {
next = c->next;
delete c;
}
- *config = NULL;
+ *config = nullptr;
}
@@ -465,7 +465,7 @@ GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_o
{
/* Clear destination as it will be overwritten */
ClearGRFConfigList(dst);
- for (; src != NULL; src = src->next) {
+ for (; src != nullptr; src = src->next) {
GRFConfig *c = new GRFConfig(*src);
ClrBit(c->flags, GCF_INIT_ONLY);
@@ -496,9 +496,9 @@ static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
GRFConfig *prev;
GRFConfig *cur;
- if (list == NULL) return;
+ if (list == nullptr) return;
- for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
+ for (prev = list, cur = list->next; cur != nullptr; prev = cur, cur = cur->next) {
if (cur->ident.grfid != list->ident.grfid) continue;
prev->next = cur->next;
@@ -516,7 +516,7 @@ static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
void AppendStaticGRFConfigs(GRFConfig **dst)
{
GRFConfig **tail = dst;
- while (*tail != NULL) tail = &(*tail)->next;
+ while (*tail != nullptr) tail = &(*tail)->next;
CopyGRFConfigList(tail, _grfconfig_static, false);
RemoveDuplicatesFromGRFConfigList(*dst);
@@ -530,7 +530,7 @@ void AppendStaticGRFConfigs(GRFConfig **dst)
void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
{
GRFConfig **tail = dst;
- while (*tail != NULL) tail = &(*tail)->next;
+ while (*tail != nullptr) tail = &(*tail)->next;
*tail = el;
RemoveDuplicatesFromGRFConfigList(*dst);
@@ -560,15 +560,15 @@ GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
{
GRFListCompatibility res = GLC_ALL_GOOD;
- for (GRFConfig *c = grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = grfconfig; c != nullptr; c = c->next) {
const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
- if (f == NULL || HasBit(f->flags, GCF_INVALID)) {
+ if (f == nullptr || HasBit(f->flags, GCF_INVALID)) {
char buf[256];
/* If we have not found the exactly matching GRF try to find one with the
* same grfid, as it most likely is compatible */
- f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version);
- if (f != NULL) {
+ f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, nullptr, c->version);
+ if (f != nullptr) {
md5sumToString(buf, lastof(buf), c->ident.md5sum);
DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf);
if (!HasBit(c->flags, GCF_COMPATIBLE)) {
@@ -606,14 +606,14 @@ compatible_grf:
c->info->Release();
c->info = f->name;
c->info->AddRef();
- c->error = NULL;
+ c->error = nullptr;
c->version = f->version;
c->min_loadable_version = f->min_loadable_version;
c->num_valid_params = f->num_valid_params;
c->has_param_defaults = f->has_param_defaults;
for (uint i = 0; i < f->param_info.size(); i++) {
- if (f->param_info[i] == NULL) {
- c->param_info.push_back(NULL);
+ if (f->param_info[i] == nullptr) {
+ c->param_info.push_back(nullptr);
} else {
c->param_info.push_back(new GRFParameterInfo(*f->param_info[i]));
}
@@ -655,14 +655,14 @@ bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length, const
bool added = true;
if (FillGRFDetails(c, false)) {
- if (_all_grfs == NULL) {
+ if (_all_grfs == nullptr) {
_all_grfs = c;
} else {
/* Insert file into list at a position determined by its
* name, so the list is sorted as we go along */
GRFConfig **pd, *d;
bool stop = false;
- for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
+ for (pd = &_all_grfs; (d = *pd) != nullptr; pd = &d->next) {
if (c->ident.grfid == d->ident.grfid && memcmp(c->ident.md5sum, d->ident.md5sum, sizeof(c->ident.md5sum)) == 0) added = false;
/* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
* before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
@@ -687,9 +687,9 @@ bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length, const
_modal_progress_work_mutex.unlock();
_modal_progress_paint_mutex.lock();
- const char *name = NULL;
- if (c->name != NULL) name = GetGRFStringFromGRFText(c->name->text);
- if (name == NULL) name = c->filename;
+ const char *name = nullptr;
+ if (c->name != nullptr) name = GetGRFStringFromGRFText(c->name->text);
+ if (name == nullptr) name = c->filename;
UpdateNewGRFScanStatus(this->num_scanned, name);
_modal_progress_work_mutex.lock();
@@ -736,14 +736,14 @@ void DoScanNewGRFFiles(NewGRFScanCallback *callback)
uint num = GRFFileScanner::DoScan();
DEBUG(grf, 1, "Scan complete, found %d files", num);
- if (num != 0 && _all_grfs != NULL) {
+ if (num != 0 && _all_grfs != nullptr) {
/* Sort the linked list using quicksort.
* For that we first have to make an array, then sort and
* then remake the linked list. */
GRFConfig **to_sort = MallocT<GRFConfig*>(num);
uint i = 0;
- for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
+ for (GRFConfig *p = _all_grfs; p != nullptr; p = p->next, i++) {
to_sort[i] = p;
}
/* Number of files is not necessarily right */
@@ -754,7 +754,7 @@ void DoScanNewGRFFiles(NewGRFScanCallback *callback)
for (i = 1; i < num; i++) {
to_sort[i - 1]->next = to_sort[i];
}
- to_sort[num - 1]->next = NULL;
+ to_sort[num - 1]->next = nullptr;
_all_grfs = to_sort[0];
free(to_sort);
@@ -768,7 +768,7 @@ void DoScanNewGRFFiles(NewGRFScanCallback *callback)
/* Yes... these are the NewGRF windows */
InvalidateWindowClassesData(WC_SAVELOAD, 0, true);
InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE, GOID_NEWGRF_RESCANNED, true);
- if (callback != NULL) callback->OnNewGRFsScanned();
+ if (callback != nullptr) callback->OnNewGRFsScanned();
DeleteWindowByClass(WC_MODAL_PROGRESS);
SetModalProgress(false);
@@ -786,14 +786,14 @@ void ScanNewGRFFiles(NewGRFScanCallback *callback)
/* Only then can we really start, especially by marking the whole screen dirty. Get those other windows hidden!. */
MarkWholeScreenDirty();
- if (!UseThreadedModelProgress() || !VideoDriver::GetInstance()->HasGUI() || !StartNewThread(NULL, "ottd:newgrf-scan", &DoScanNewGRFFiles, (NewGRFScanCallback *)callback)) { // Without the seemingly superfluous cast, strange compiler errors ensue.
+ if (!UseThreadedModelProgress() || !VideoDriver::GetInstance()->HasGUI() || !StartNewThread(nullptr, "ottd:newgrf-scan", &DoScanNewGRFFiles, (NewGRFScanCallback *)callback)) { // Without the seemingly superfluous cast, strange compiler errors ensue.
_modal_progress_work_mutex.unlock();
_modal_progress_paint_mutex.unlock();
DoScanNewGRFFiles(callback);
_modal_progress_paint_mutex.lock();
_modal_progress_work_mutex.lock();
} else {
- UpdateNewGRFScanStatus(0, NULL);
+ UpdateNewGRFScanStatus(0, nullptr);
}
}
@@ -803,23 +803,23 @@ void ScanNewGRFFiles(NewGRFScanCallback *callback)
* @param mode Restrictions for matching grfs
* @param md5sum Expected MD5 sum
* @param desired_version Requested version
- * @return The matching grf, if it exists in #_all_grfs, else \c NULL.
+ * @return The matching grf, if it exists in #_all_grfs, else \c nullptr.
*/
const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
{
- assert((mode == FGCM_EXACT) != (md5sum == NULL));
- const GRFConfig *best = NULL;
- for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
+ assert((mode == FGCM_EXACT) != (md5sum == nullptr));
+ const GRFConfig *best = nullptr;
+ for (const GRFConfig *c = _all_grfs; c != nullptr; c = c->next) {
/* if md5sum is set, we look for an exact match and continue if not found */
if (!c->ident.HasGrfIdentifier(grfid, md5sum)) continue;
/* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
- if (md5sum != NULL || mode == FGCM_ANY) return c;
+ if (md5sum != nullptr || mode == FGCM_ANY) return c;
/* Skip incompatible stuff, unless explicitly allowed */
if (mode != FGCM_NEWEST && HasBit(c->flags, GCF_INVALID)) continue;
/* check version compatibility */
if (mode == FGCM_COMPATIBLE && (c->version < desired_version || c->min_loadable_version > desired_version)) continue;
/* remember the newest one as "the best" */
- if (best == NULL || c->version > best->version) best = c;
+ if (best == nullptr || c->version > best->version) best = c;
}
return best;
@@ -845,21 +845,21 @@ struct UnknownGRF : public GRFIdentifier {
* @param create whether to create a new GRFConfig if the GRFConfig did not
* exist in the fake list of GRFConfigs.
* @return The GRFTextWrapper of the name of the GRFConfig with the given GRF ID
- * and MD5 checksum or NULL when it does not exist and create is false.
+ * and MD5 checksum or nullptr when it does not exist and create is false.
* This value must NEVER be freed by the caller.
*/
GRFTextWrapper *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
{
UnknownGRF *grf;
- static UnknownGRF *unknown_grfs = NULL;
+ static UnknownGRF *unknown_grfs = nullptr;
- for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
+ for (grf = unknown_grfs; grf != nullptr; grf = grf->next) {
if (grf->grfid == grfid) {
if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
}
}
- if (!create) return NULL;
+ if (!create) return nullptr;
grf = CallocT<UnknownGRF>(1);
grf->grfid = grfid;
@@ -878,17 +878,17 @@ GRFTextWrapper *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
* Retrieve a NewGRF from the current config by its grfid.
* @param grfid grf to look for.
* @param mask GRFID mask to allow for partial matching.
- * @return The grf config, if it exists, else \c NULL.
+ * @return The grf config, if it exists, else \c nullptr.
*/
GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
{
GRFConfig *c;
- for (c = _grfconfig; c != NULL; c = c->next) {
+ for (c = _grfconfig; c != nullptr; c = c->next) {
if ((c->ident.grfid & mask) == (grfid & mask)) return c;
}
- return NULL;
+ return nullptr;
}
@@ -913,7 +913,7 @@ static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
/**
* Search a textfile file next to this NewGRF.
* @param type The type of the textfile to search for.
- * @return The filename for the textfile, \c NULL otherwise.
+ * @return The filename for the textfile, \c nullptr otherwise.
*/
const char *GRFConfig::GetTextfile(TextfileType type) const
{
diff --git a/src/newgrf_config.h b/src/newgrf_config.h
index 88110f0ed..feee2dbad 100644
--- a/src/newgrf_config.h
+++ b/src/newgrf_config.h
@@ -88,13 +88,13 @@ struct GRFIdentifier {
/**
* Does the identification match the provided values?
* @param grfid Expected grfid.
- * @param md5sum Expected md5sum, may be \c NULL (in which case, do not check it).
+ * @param md5sum Expected md5sum, may be \c nullptr (in which case, do not check it).
* @return the object has the provided grfid and md5sum.
*/
inline bool HasGrfIdentifier(uint32 grfid, const uint8 *md5sum) const
{
if (this->grfid != grfid) return false;
- if (md5sum == NULL) return true;
+ if (md5sum == nullptr) return true;
return memcmp(md5sum, this->md5sum, sizeof(this->md5sum)) == 0;
}
};
@@ -151,7 +151,7 @@ struct GRFTextWrapper : public SimpleCountedObject {
/** Information about GRF, used in the game and (part of it) in savegames */
struct GRFConfig : ZeroedMemoryAllocator {
- GRFConfig(const char *filename = NULL);
+ GRFConfig(const char *filename = nullptr);
GRFConfig(const GRFConfig &config);
~GRFConfig();
@@ -215,7 +215,7 @@ struct NewGRFScanCallback {
size_t GRFGetSizeOfDataSection(FILE *f);
void ScanNewGRFFiles(NewGRFScanCallback *callback);
-const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum = NULL, uint32 desired_version = 0);
+const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum = nullptr, uint32 desired_version = 0);
GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask = 0xFFFFFFFF);
GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only);
void AppendStaticGRFConfigs(GRFConfig **dst);
diff --git a/src/newgrf_debug_gui.cpp b/src/newgrf_debug_gui.cpp
index 69eaa4afa..47bd60e37 100644
--- a/src/newgrf_debug_gui.cpp
+++ b/src/newgrf_debug_gui.cpp
@@ -47,7 +47,7 @@
#include "safeguards.h"
/** The sprite picker. */
-NewGrfDebugSpritePicker _newgrf_debug_sprite_picker = { SPM_NONE, NULL, 0, std::vector<SpriteID>() };
+NewGrfDebugSpritePicker _newgrf_debug_sprite_picker = { SPM_NONE, nullptr, 0, std::vector<SpriteID>() };
/**
* Get the feature index related to the window number.
@@ -192,11 +192,11 @@ public:
* Gets the first position of the array containing the persistent storage.
* @param index Index of the item.
* @param grfid Parameter for the PSA. Only required for items with parameters.
- * @return Pointer to the first position of the storage array or NULL if not present.
+ * @return Pointer to the first position of the storage array or nullptr if not present.
*/
virtual const int32 *GetPSAFirstPosition(uint index, uint32 grfid) const
{
- return NULL;
+ return nullptr;
}
protected:
@@ -252,18 +252,18 @@ static inline GrfSpecFeature GetFeatureNum(uint window_number)
/**
* Get the NIFeature related to the window number.
* @param window_number The window to get the NIFeature for.
- * @return the NIFeature, or NULL is there isn't one.
+ * @return the NIFeature, or nullptr is there isn't one.
*/
static inline const NIFeature *GetFeature(uint window_number)
{
GrfSpecFeature idx = GetFeatureNum(window_number);
- return idx < GSF_FAKE_END ? _nifeatures[idx] : NULL;
+ return idx < GSF_FAKE_END ? _nifeatures[idx] : nullptr;
}
/**
* Get the NIHelper related to the window number.
* @param window_number The window to get the NIHelper for.
- * @pre GetFeature(window_number) != NULL
+ * @pre GetFeature(window_number) != nullptr
* @return the NIHelper
*/
static inline const NIHelper *GetFeatureHelper(uint window_number)
@@ -332,7 +332,7 @@ struct NewGRFInspectWindow : Window {
assert(this->HasChainIndex());
const Vehicle *v = Vehicle::Get(index);
v = v->Move(this->chain_index);
- if (v != NULL) index = v->index;
+ if (v != nullptr) index = v->index;
}
return index;
}
@@ -348,7 +348,7 @@ struct NewGRFInspectWindow : Window {
const Vehicle *v = Vehicle::Get(::GetFeatureIndex(this->window_number));
v = v->Move(this->chain_index);
- if (v == NULL) this->chain_index = 0;
+ if (v == nullptr) this->chain_index = 0;
}
NewGRFInspectWindow(WindowDesc *desc, WindowNumber wno) : Window(desc)
@@ -418,7 +418,7 @@ struct NewGRFInspectWindow : Window {
int total_width = 0;
int sel_start = 0;
int sel_end = 0;
- for (const Vehicle *u = v->First(); u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v->First(); u != nullptr; u = u->Next()) {
if (u == v) sel_start = total_width;
switch (u->type) {
case VEH_TRAIN: total_width += Train ::From(u)->GetDisplayImageWidth(); break;
@@ -459,9 +459,9 @@ struct NewGRFInspectWindow : Window {
const void *base_spec = nih->GetSpec(index);
uint i = 0;
- if (nif->variables != NULL) {
+ if (nif->variables != nullptr) {
this->DrawString(r, i++, "Variables:");
- for (const NIVariable *niv = nif->variables; niv->name != NULL; niv++) {
+ for (const NIVariable *niv = nif->variables; niv->name != nullptr; niv++) {
bool avail = true;
uint param = HasVariableParameter(niv->var) ? NewGRFInspectWindow::var60params[GetFeatureNum(this->window_number)][niv->var - 0x60] : 0;
uint value = nih->Resolve(index, niv->var, param, &avail);
@@ -478,7 +478,7 @@ struct NewGRFInspectWindow : Window {
uint psa_size = nih->GetPSASize(index, this->caller_grfid);
const int32 *psa = nih->GetPSAFirstPosition(index, this->caller_grfid);
- if (psa_size != 0 && psa != NULL) {
+ if (psa_size != 0 && psa != nullptr) {
if (nih->PSAWithParameter()) {
this->DrawString(r, i++, "Persistent storage [%08X]:", BSWAP32(this->caller_grfid));
} else {
@@ -490,9 +490,9 @@ struct NewGRFInspectWindow : Window {
}
}
- if (nif->properties != NULL) {
+ if (nif->properties != nullptr) {
this->DrawString(r, i++, "Properties:");
- for (const NIProperty *nip = nif->properties; nip->name != NULL; nip++) {
+ for (const NIProperty *nip = nif->properties; nip->name != nullptr; nip++) {
const void *ptr = (const byte *)base + nip->offset;
uint value;
switch (nip->read_size) {
@@ -523,9 +523,9 @@ struct NewGRFInspectWindow : Window {
}
}
- if (nif->callbacks != NULL) {
+ if (nif->callbacks != nullptr) {
this->DrawString(r, i++, "Callbacks:");
- for (const NICallback *nic = nif->callbacks; nic->name != NULL; nic++) {
+ for (const NICallback *nic = nif->callbacks; nic->name != nullptr; nic++) {
if (nic->cb_bit != CBM_NO_BIT) {
const void *ptr = (const byte *)base_spec + nic->offset;
uint value;
@@ -571,7 +571,7 @@ struct NewGRFInspectWindow : Window {
if (this->HasChainIndex()) {
uint index = this->GetFeatureIndex();
Vehicle *v = Vehicle::Get(index);
- if (v != NULL && v->Next() != NULL) {
+ if (v != nullptr && v->Next() != nullptr) {
this->chain_index++;
this->InvalidateData();
}
@@ -581,14 +581,14 @@ struct NewGRFInspectWindow : Window {
case WID_NGRFI_MAINPANEL: {
/* Does this feature have variables? */
const NIFeature *nif = GetFeature(this->window_number);
- if (nif->variables == NULL) return;
+ if (nif->variables == nullptr) return;
/* Get the line, make sure it's within the boundaries. */
int line = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NGRFI_MAINPANEL, TOP_OFFSET);
if (line == INT_MAX) return;
/* Find the variable related to the line */
- for (const NIVariable *niv = nif->variables; niv->name != NULL; niv++, line--) {
+ for (const NIVariable *niv = nif->variables; niv->name != nullptr; niv++, line--) {
if (line != 1) continue; // 1 because of the "Variables:" line
if (!HasVariableParameter(niv->var)) break;
@@ -604,7 +604,7 @@ struct NewGRFInspectWindow : Window {
{
if (StrEmpty(str)) return;
- NewGRFInspectWindow::var60params[GetFeatureNum(this->window_number)][this->current_edit_param - 0x60] = strtol(str, NULL, 16);
+ NewGRFInspectWindow::var60params[GetFeatureNum(this->window_number)][this->current_edit_param - 0x60] = strtol(str, nullptr, 16);
this->SetDirty();
}
@@ -625,7 +625,7 @@ struct NewGRFInspectWindow : Window {
this->ValidateChainIndex();
this->SetWidgetDisabledState(WID_NGRFI_VEH_PREV, this->chain_index == 0);
Vehicle *v = Vehicle::Get(this->GetFeatureIndex());
- this->SetWidgetDisabledState(WID_NGRFI_VEH_NEXT, v == NULL || v->Next() == NULL);
+ this->SetWidgetDisabledState(WID_NGRFI_VEH_NEXT, v == nullptr || v->Next() == nullptr);
}
}
};
@@ -756,7 +756,7 @@ void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
bool IsNewGRFInspectable(GrfSpecFeature feature, uint index)
{
const NIFeature *nif = GetFeature(GetInspectWindowNumber(feature, index));
- if (nif == NULL) return false;
+ if (nif == nullptr) return false;
return nif->helper->IsInspectable(index);
}
@@ -883,7 +883,7 @@ struct SpriteAlignerWindow : Window {
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &new_dpi;
- DrawSprite(this->current_sprite, PAL_NONE, x, y, NULL, ZOOM_LVL_GUI);
+ DrawSprite(this->current_sprite, PAL_NONE, x, y, nullptr, ZOOM_LVL_GUI);
_cur_dpi = old_dpi;
diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp
index a9929540a..d6f4b0997 100644
--- a/src/newgrf_engine.cpp
+++ b/src/newgrf_engine.cpp
@@ -65,7 +65,7 @@ const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, Eng
if (wo->train_id[j] == overriding_engine) return wo->group;
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -79,7 +79,7 @@ void UnloadWagonOverrides(Engine *e)
}
free(e->overrides);
e->overrides_count = 0;
- e->overrides = NULL;
+ e->overrides = nullptr;
}
@@ -88,7 +88,7 @@ void SetCustomEngineSprites(EngineID engine, byte cargo, const SpriteGroup *grou
Engine *e = Engine::Get(engine);
assert(cargo < lengthof(e->grf_prop.spritegroup));
- if (e->grf_prop.spritegroup[cargo] != NULL) {
+ if (e->grf_prop.spritegroup[cargo] != nullptr) {
grfmsg(6, "SetCustomEngineSprites: engine %d cargo %d already has group -- replacing", engine, cargo);
}
e->grf_prop.spritegroup[cargo] = group;
@@ -166,7 +166,7 @@ enum TTDPAircraftMovementStates {
static byte MapAircraftMovementState(const Aircraft *v)
{
const Station *st = GetTargetAirportIfValid(v);
- if (st == NULL) return AMS_TTDP_FLIGHT_TO_TOWER;
+ if (st == nullptr) return AMS_TTDP_FLIGHT_TO_TOWER;
const AirportFTAClass *afc = st->airport.GetFTA();
uint16 amdflag = afc->MovingData(v->pos)->flag;
@@ -339,12 +339,12 @@ static byte MapAircraftMovementAction(const Aircraft *v)
/* virtual */ uint32 VehicleScopeResolver::GetRandomBits() const
{
- return this->v == NULL ? 0 : this->v->random_bits;
+ return this->v == nullptr ? 0 : this->v->random_bits;
}
/* virtual */ uint32 VehicleScopeResolver::GetTriggers() const
{
- return this->v == NULL ? 0 : this->v->waiting_triggers;
+ return this->v == nullptr ? 0 : this->v->waiting_triggers;
}
@@ -355,12 +355,12 @@ static byte MapAircraftMovementAction(const Aircraft *v)
case VSG_SCOPE_PARENT: return &this->parent_scope;
case VSG_SCOPE_RELATIVE: {
int32 count = GB(relative, 0, 4);
- if (this->self_scope.v != NULL && (relative != this->cached_relative_count || count == 0)) {
+ if (this->self_scope.v != nullptr && (relative != this->cached_relative_count || count == 0)) {
/* Note: This caching only works as long as the VSG_SCOPE_RELATIVE cannot be used in
* VarAct2 with procedure calls. */
if (count == 0) count = GetRegister(0x100);
- const Vehicle *v = NULL;
+ const Vehicle *v = nullptr;
switch (GB(relative, 6, 2)) {
default: NOT_REACHED();
case 0x00: // count back (away from the engine), starting at this vehicle
@@ -377,12 +377,12 @@ static byte MapAircraftMovementAction(const Aircraft *v)
const Vehicle *self = this->self_scope.v;
for (const Vehicle *u = self->First(); u != self; u = u->Next()) {
if (u->engine_type != self->engine_type) {
- v = NULL;
+ v = nullptr;
} else {
- if (v == NULL) v = u;
+ if (v == nullptr) v = u;
}
}
- if (v == NULL) v = self;
+ if (v == nullptr) v = self;
break;
}
}
@@ -400,16 +400,16 @@ static byte MapAircraftMovementAction(const Aircraft *v)
* This always uses dual company colours independent of GUI settings. So it is desync-safe.
*
* @param engine Engine type
- * @param v Vehicle, NULL in purchase list.
+ * @param v Vehicle, nullptr in purchase list.
* @return Livery to use
*/
static const Livery *LiveryHelper(EngineID engine, const Vehicle *v)
{
const Livery *l;
- if (v == NULL) {
- if (!Company::IsValidID(_current_company)) return NULL;
- l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL, LIT_ALL);
+ if (v == nullptr) {
+ if (!Company::IsValidID(_current_company)) return nullptr;
+ l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, nullptr, LIT_ALL);
} else if (v->IsGroundVehicle()) {
l = GetEngineLivery(v->engine_type, v->owner, v->GetGroundVehicleCache()->first_engine, v, LIT_ALL);
} else {
@@ -437,7 +437,7 @@ static uint32 PositionHelper(const Vehicle *v, bool consecutive)
if (consecutive && u->engine_type != v->engine_type) chain_before = 0;
}
- while (u->Next() != NULL && (!consecutive || u->Next()->engine_type == v->engine_type)) {
+ while (u->Next() != nullptr && (!consecutive || u->Next()->engine_type == v->engine_type)) {
chain_after++;
u = u->Next();
}
@@ -480,7 +480,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
memset(common_cargoes, 0, sizeof(common_cargoes));
memset(common_subtypes, 0, sizeof(common_subtypes));
- for (u = v; u != NULL; u = u->Next()) {
+ for (u = v; u != nullptr; u = u->Next()) {
if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
/* Skip empty engines */
@@ -500,7 +500,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
}
/* Count subcargo types of common_cargo_type */
- for (u = v; u != NULL; u = u->Next()) {
+ for (u = v; u != nullptr; u = u->Next()) {
/* Skip empty engines and engines not carrying common_cargo_type */
if (u->cargo_type != common_cargo_type || !u->GetEngine()->CanCarryCargo()) continue;
@@ -530,12 +530,12 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
* - For translating the cargo type we need to use the GRF which is resolving the variable, which
* is object->ro.grffile.
* In case of CBID_TRAIN_ALLOW_WAGON_ATTACH this is not the same as v->GetGRF().
- * - The grffile == NULL case only happens if this function is called for default vehicles.
+ * - The grffile == nullptr case only happens if this function is called for default vehicles.
* And this is only done by CheckCaches().
*/
const GRFFile *grffile = object->ro.grffile;
uint8 common_bitnum = (common_cargo_type == CT_INVALID) ? 0xFF :
- (grffile == NULL || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
+ (grffile == nullptr || grffile->grf_version < 8) ? CargoSpec::Get(common_cargo_type)->bitnum : grffile->cargo_map[common_cargo_type];
return (v->grf_cache.consist_cargo_information & 0xFFFF00FF) | common_bitnum << 8;
}
@@ -557,7 +557,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
- if (st != NULL && st->airport.tile != INVALID_TILE) {
+ if (st != nullptr && st->airport.tile != INVALID_TILE) {
airporttype = st->airport.GetSpec()->ttd_airport_type;
}
@@ -574,8 +574,8 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
const Vehicle *u_p = v->Previous();
const Vehicle *u_n = v->Next();
- DirDiff f = (u_p == NULL) ? DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
- DirDiff b = (u_n == NULL) ? DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
+ DirDiff f = (u_p == nullptr) ? DIRDIFF_SAME : DirDifference(u_p->direction, v->direction);
+ DirDiff b = (u_n == nullptr) ? DIRDIFF_SAME : DirDifference(v->direction, u_n->direction);
DirDiff t = ChangeDirDiff(f, b);
return ((t > DIRDIFF_REVERSE ? t | 8 : t) << 16) |
@@ -636,7 +636,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
{
uint count = 0;
- for (; v != NULL; v = v->Next()) {
+ for (; v != nullptr; v = v->Next()) {
if (v->GetEngine()->grf_prop.local_id == parameter) count++;
}
return count;
@@ -653,7 +653,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
object->ro.callback == CBID_VEHICLE_START_STOP_CHECK || object->ro.callback == CBID_VEHICLE_32DAY_CALLBACK || object->ro.callback == CBID_VEHICLE_COLOUR_MAPPING ||
object->ro.callback == CBID_VEHICLE_SPAWN_VISUAL_EFFECT) {
Vehicle *u = v->Move((int32)GetRegister(0x10F));
- if (u == NULL) return 0; // available, but zero
+ if (u == nullptr) return 0; // available, but zero
if (parameter == 0x5F) {
/* This seems to be the only variable that makes sense to access via var 61, but is not handled by VehicleGetVariable */
@@ -676,7 +676,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
if (!v->IsGroundVehicle()) return 0;
const Vehicle *u = v->Move((int8)parameter);
- if (u == NULL) return 0;
+ if (u == nullptr) return 0;
/* Get direction difference. */
bool prev = (int8)parameter < 0;
@@ -810,7 +810,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
case 0x57: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 8, 24);
case 0x58: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 16, 16);
case 0x59: return GB(ClampToI32(v->GetDisplayProfitLastYear()), 24, 8);
- case 0x5A: return v->Next() == NULL ? INVALID_VEHICLE : v->Next()->index;
+ case 0x5A: return v->Next() == nullptr ? INVALID_VEHICLE : v->Next()->index;
case 0x5C: return ClampToI32(v->value);
case 0x5D: return GB(ClampToI32(v->value), 8, 24);
case 0x5E: return GB(ClampToI32(v->value), 16, 16);
@@ -882,10 +882,10 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
/* virtual */ uint32 VehicleScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
{
- if (this->v == NULL) {
+ if (this->v == nullptr) {
/* Vehicle does not exist, so we're in a purchase list */
switch (variable) {
- case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(this->self_type, NULL)); // Owner information
+ case 0x43: return GetCompanyInfo(_current_company, LiveryHelper(this->self_type, nullptr)); // Owner information
case 0x46: return 0; // Motion counter
case 0x47: { // Vehicle cargo info
const Engine *e = Engine::Get(this->self_type);
@@ -919,17 +919,17 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
{
const Vehicle *v = this->self_scope.v;
- if (v == NULL) {
+ if (v == nullptr) {
if (group->num_loading > 0) return group->loading[0];
if (group->num_loaded > 0) return group->loaded[0];
- return NULL;
+ return nullptr;
}
bool in_motion = !v->First()->current_order.IsType(OT_LOADING);
uint totalsets = in_motion ? group->num_loaded : group->num_loading;
- if (totalsets == 0) return NULL;
+ if (totalsets == 0) return nullptr;
uint set = (v->cargo.StoredCount() * totalsets) / max((uint16)1, v->cargo_cap);
set = min(set, totalsets - 1);
@@ -945,7 +945,7 @@ static uint32 VehicleGetVariable(Vehicle *v, const VehicleScopeResolver *object,
static const GRFFile *GetEngineGrfFile(EngineID engine_type)
{
const Engine *e = Engine::Get(engine_type);
- return (e != NULL) ? e->GetGRF() : NULL;
+ return (e != nullptr) ? e->GetGRF() : nullptr;
}
/**
@@ -962,14 +962,14 @@ VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle
CallbackID callback, uint32 callback_param1, uint32 callback_param2)
: ResolverObject(GetEngineGrfFile(engine_type), callback, callback_param1, callback_param2),
self_scope(*this, engine_type, v, info_view),
- parent_scope(*this, engine_type, ((v != NULL) ? v->First() : v), info_view),
+ parent_scope(*this, engine_type, ((v != nullptr) ? v->First() : v), info_view),
relative_scope(*this, engine_type, v, info_view),
cached_relative_count(0)
{
if (wagon_override == WO_SELF) {
this->root_spritegroup = GetWagonOverrideSpriteSet(engine_type, CT_DEFAULT, engine_type);
} else {
- if (wagon_override != WO_NONE && v != NULL && v->IsGroundVehicle()) {
+ if (wagon_override != WO_NONE && v != nullptr && v->IsGroundVehicle()) {
assert(v->engine_type == engine_type); // overrides make little sense with fake scopes
/* For trains we always use cached value, except for callbacks because the override spriteset
@@ -982,11 +982,11 @@ VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle
}
}
- if (this->root_spritegroup == NULL) {
+ if (this->root_spritegroup == nullptr) {
const Engine *e = Engine::Get(engine_type);
- CargoID cargo = v != NULL ? v->cargo_type : CT_PURCHASE;
+ CargoID cargo = v != nullptr ? v->cargo_type : CT_PURCHASE;
assert(cargo < lengthof(e->grf_prop.spritegroup));
- this->root_spritegroup = e->grf_prop.spritegroup[cargo] != NULL ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[CT_DEFAULT];
+ this->root_spritegroup = e->grf_prop.spritegroup[cargo] != nullptr ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[CT_DEFAULT];
}
}
}
@@ -1005,7 +1005,7 @@ void GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction directio
object.callback_param1 = image_type | (stack << 8);
const SpriteGroup *group = object.Resolve();
uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
- if (group != NULL && group->GetNumResults() != 0) {
+ if (group != nullptr && group->GetNumResults() != 0) {
result->seq[result->count].sprite = group->GetResult() + (direction % group->GetNumResults());
result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
result->count++;
@@ -1025,7 +1025,7 @@ void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info
VehicleResolverObject object(engine, v, VehicleResolverObject::WO_SELF, info_view, CBID_NO_CALLBACK);
result->Clear();
- uint rotor_pos = v == NULL || info_view ? 0 : v->Next()->Next()->state;
+ uint rotor_pos = v == nullptr || info_view ? 0 : v->Next()->Next()->state;
bool sprite_stack = HasBit(e->info.misc_flags, EF_SPRITE_STACK);
uint max_stack = sprite_stack ? lengthof(result->seq) : 1;
@@ -1034,7 +1034,7 @@ void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info
object.callback_param1 = image_type | (stack << 8);
const SpriteGroup *group = object.Resolve();
uint32 reg100 = sprite_stack ? GetRegister(0x100) : 0;
- if (group != NULL && group->GetNumResults() != 0) {
+ if (group != nullptr && group->GetNumResults() != 0) {
result->seq[result->count].sprite = group->GetResult() + (rotor_pos % group->GetNumResults());
result->seq[result->count].pal = GB(reg100, 0, 16); // zero means default recolouring
result->count++;
@@ -1052,7 +1052,7 @@ void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info
bool UsesWagonOverride(const Vehicle *v)
{
assert(v->type == VEH_TRAIN);
- return Train::From(v)->tcache.cached_override != NULL;
+ return Train::From(v)->tcache.cached_override != nullptr;
}
/**
@@ -1061,7 +1061,7 @@ bool UsesWagonOverride(const Vehicle *v)
* @param param1 First parameter of the callback
* @param param2 Second parameter of the callback
* @param engine Engine type of the vehicle to evaluate the callback for
- * @param v The vehicle to evaluate the callback for, or NULL if it doesnt exist yet
+ * @param v The vehicle to evaluate the callback for, or nullptr if it doesnt exist yet
* @return The value the callback returned, or CALLBACK_FAILED if it failed
*/
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
@@ -1076,7 +1076,7 @@ uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, Eng
* @param param1 First parameter of the callback
* @param param2 Second parameter of the callback
* @param engine Engine type of the vehicle to evaluate the callback for
- * @param v The vehicle to evaluate the callback for, or NULL if it doesn't exist yet
+ * @param v The vehicle to evaluate the callback for, or nullptr if it doesn't exist yet
* @param parent The vehicle to use for parent scope
* @return The value the callback returned, or CALLBACK_FAILED if it failed
*/
@@ -1107,14 +1107,14 @@ uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, co
static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_random_bits, bool first)
{
/* We can't trigger a non-existent vehicle... */
- assert(v != NULL);
+ assert(v != nullptr);
VehicleResolverObject object(v->engine_type, v, VehicleResolverObject::WO_CACHED, false, CBID_RANDOM_TRIGGER);
object.waiting_triggers = v->waiting_triggers | trigger;
v->waiting_triggers = object.waiting_triggers; // store now for var 5F
const SpriteGroup *group = object.Resolve();
- if (group == NULL) return;
+ if (group == nullptr) return;
/* Store remaining triggers. */
v->waiting_triggers = object.GetRemainingTriggers();
@@ -1142,7 +1142,7 @@ static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_rando
/* We now trigger the next vehicle in chain recursively.
* The random bits portions may be different for each
* vehicle in chain. */
- if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, 0, true);
+ if (v->Next() != nullptr) DoTriggerVehicle(v->Next(), trigger, 0, true);
break;
case VEHICLE_TRIGGER_EMPTY:
@@ -1150,14 +1150,14 @@ static void DoTriggerVehicle(Vehicle *v, VehicleTrigger trigger, byte base_rando
* recursively. The random bits portions must be same
* for each vehicle in chain, so we give them all
* first chained vehicle's portion of random bits. */
- if (v->Next() != NULL) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
+ if (v->Next() != nullptr) DoTriggerVehicle(v->Next(), trigger, first ? new_random_bits : base_random_bits, false);
break;
case VEHICLE_TRIGGER_ANY_NEW_CARGO:
/* Now pass the trigger recursively to the next vehicle
* in chain. */
assert(!first);
- if (v->Next() != NULL) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
+ if (v->Next() != nullptr) DoTriggerVehicle(v->Next(), VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
break;
case VEHICLE_TRIGGER_CALLBACK_32:
diff --git a/src/newgrf_engine.h b/src/newgrf_engine.h
index 644ff5f01..a3ead85ca 100644
--- a/src/newgrf_engine.h
+++ b/src/newgrf_engine.h
@@ -81,11 +81,11 @@ void SetCustomEngineSprites(EngineID engine, byte cargo, const struct SpriteGrou
void GetCustomEngineSprite(EngineID engine, const Vehicle *v, Direction direction, EngineImageType image_type, VehicleSpriteSeq *result);
#define GetCustomVehicleSprite(v, direction, image_type, result) GetCustomEngineSprite(v->engine_type, v, direction, image_type, result)
-#define GetCustomVehicleIcon(et, direction, image_type, result) GetCustomEngineSprite(et, NULL, direction, image_type, result)
+#define GetCustomVehicleIcon(et, direction, image_type, result) GetCustomEngineSprite(et, nullptr, direction, image_type, result)
void GetRotorOverrideSprite(EngineID engine, const struct Aircraft *v, bool info_view, EngineImageType image_type, VehicleSpriteSeq *result);
#define GetCustomRotorSprite(v, i, image_type, result) GetRotorOverrideSprite(v->engine_type, v, i, image_type, result)
-#define GetCustomRotorIcon(et, image_type, result) GetRotorOverrideSprite(et, NULL, true, image_type, result)
+#define GetCustomRotorIcon(et, image_type, result) GetRotorOverrideSprite(et, nullptr, true, image_type, result)
/* Forward declaration of GRFFile, to avoid unnecessary inclusion of newgrf.h
* elsewhere... */
@@ -100,7 +100,7 @@ bool UsesWagonOverride(const Vehicle *v);
/* Handler to Evaluate callback 36. If the callback fails (i.e. most of the
* time) orig_value is returned */
uint GetVehicleProperty(const Vehicle *v, PropertyID property, uint orig_value);
-uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v = NULL);
+uint GetEngineProperty(EngineID engine, PropertyID property, uint orig_value, const Vehicle *v = nullptr);
enum VehicleTrigger {
VEHICLE_TRIGGER_NEW_CARGO = 0x01,
diff --git a/src/newgrf_generic.cpp b/src/newgrf_generic.cpp
index d29a03929..bb108f470 100644
--- a/src/newgrf_generic.cpp
+++ b/src/newgrf_generic.cpp
@@ -140,7 +140,7 @@ void AddGenericCallback(uint8 feature, const GRFFile *file, const SpriteGroup *g
/* virtual */ const SpriteGroup *GenericResolverObject::ResolveReal(const RealSpriteGroup *group) const
{
- if (group->num_loaded == 0) return NULL;
+ if (group->num_loaded == 0) return nullptr;
return group->loaded[0];
}
@@ -150,7 +150,7 @@ void AddGenericCallback(uint8 feature, const GRFFile *file, const SpriteGroup *g
* @param ai_callback Callback comes from the AI.
* @param callback Callback ID.
*/
-GenericResolverObject::GenericResolverObject(bool ai_callback, CallbackID callback) : ResolverObject(NULL, callback), generic_scope(*this, ai_callback)
+GenericResolverObject::GenericResolverObject(bool ai_callback, CallbackID callback) : ResolverObject(nullptr, callback), generic_scope(*this, ai_callback)
{
}
@@ -162,7 +162,7 @@ GenericResolverObject::GenericResolverObject(bool ai_callback, CallbackID callba
* @param object pre-populated resolver object
* @param param1_grfv7 callback_param1 for GRFs up to version 7.
* @param param1_grfv8 callback_param1 for GRFs from version 8 on.
- * @param[out] file Optionally returns the GRFFile which made the final decision for the callback result. May be NULL if not required.
+ * @param[out] file Optionally returns the GRFFile which made the final decision for the callback result. May be nullptr if not required.
* @return callback value if successful or CALLBACK_FAILED
*/
static uint16 GetGenericCallbackResult(uint8 feature, ResolverObject &object, uint32 param1_grfv7, uint32 param1_grfv8, const GRFFile **file)
@@ -179,7 +179,7 @@ static uint16 GetGenericCallbackResult(uint8 feature, ResolverObject &object, ui
if (result == CALLBACK_FAILED) continue;
/* Return NewGRF file if necessary */
- if (file != NULL) *file = it->file;
+ if (file != nullptr) *file = it->file;
return result;
}
@@ -201,7 +201,7 @@ static uint16 GetGenericCallbackResult(uint8 feature, ResolverObject &object, ui
* @param event 'AI construction event' to pass to callback. (Variable 86)
* @param count 'Construction number' to pass to callback. (Variable 87)
* @param station_size 'Station size' to pass to callback. (Variable 88)
- * @param[out] file Optionally returns the GRFFile which made the final decision for the callback result. May be NULL if not required.
+ * @param[out] file Optionally returns the GRFFile which made the final decision for the callback result. May be nullptr if not required.
* @return callback value if successful or CALLBACK_FAILED
*/
uint16 GetAiPurchaseCallbackResult(uint8 feature, CargoID cargo_type, uint8 default_selection, IndustryType src_industry, IndustryType dst_industry, uint8 distance, AIConstructionEvent event, uint8 count, uint8 station_size, const GRFFile **file)
diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp
index e2a76319c..aa8764f3c 100644
--- a/src/newgrf_gui.cpp
+++ b/src/newgrf_gui.cpp
@@ -48,11 +48,11 @@ void ShowNewGRFError()
/* Do not show errors when entering the main screen */
if (_game_mode == GM_MENU) return;
- for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
/* We only want to show fatal errors */
- if (c->error == NULL || c->error->severity != STR_NEWGRF_ERROR_MSG_FATAL) continue;
+ if (c->error == nullptr || c->error->severity != STR_NEWGRF_ERROR_MSG_FATAL) continue;
- SetDParam (0, c->error->custom_message == NULL ? c->error->message : STR_JUST_RAW_STRING);
+ SetDParam (0, c->error->custom_message == nullptr ? c->error->message : STR_JUST_RAW_STRING);
SetDParamStr(1, c->error->custom_message);
SetDParamStr(2, c->filename);
SetDParamStr(3, c->error->data);
@@ -66,7 +66,7 @@ void ShowNewGRFError()
static void ShowNewGRFInfo(const GRFConfig *c, uint x, uint y, uint right, uint bottom, bool show_params)
{
- if (c->error != NULL) {
+ if (c->error != nullptr) {
char message[512];
SetDParamStr(0, c->error->custom_message); // is skipped by built-in messages
SetDParamStr(1, c->filename);
@@ -74,14 +74,14 @@ static void ShowNewGRFInfo(const GRFConfig *c, uint x, uint y, uint right, uint
for (uint i = 0; i < lengthof(c->error->param_value); i++) {
SetDParam(3 + i, c->error->param_value[i]);
}
- GetString(message, c->error->custom_message == NULL ? c->error->message : STR_JUST_RAW_STRING, lastof(message));
+ GetString(message, c->error->custom_message == nullptr ? c->error->message : STR_JUST_RAW_STRING, lastof(message));
SetDParamStr(0, message);
y = DrawStringMultiLine(x, right, y, bottom, c->error->severity);
}
/* Draw filename or not if it is not known (GRF sent over internet) */
- if (c->filename != NULL) {
+ if (c->filename != nullptr) {
SetDParamStr(0, c->filename);
y = DrawStringMultiLine(x, right, y, bottom, STR_NEWGRF_SETTINGS_FILENAME);
}
@@ -222,9 +222,9 @@ struct NewGRFParametersWindow : public Window {
Dimension suggestion = {500 - WD_FRAMERECT_LEFT - WD_FRAMERECT_RIGHT, (uint)FONT_HEIGHT_NORMAL * 4 + WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM};
for (uint i = 0; i < this->grf_config->param_info.size(); i++) {
const GRFParameterInfo *par_info = this->grf_config->param_info[i];
- if (par_info == NULL) continue;
+ if (par_info == nullptr) continue;
const char *desc = GetGRFStringFromGRFText(par_info->desc);
- if (desc == NULL) continue;
+ if (desc == nullptr) continue;
Dimension d = GetStringMultiLineBoundingBox(desc, suggestion);
d.height += WD_TEXTPANEL_TOP + WD_TEXTPANEL_BOTTOM;
suggestion = maxdim(d, suggestion);
@@ -246,10 +246,10 @@ struct NewGRFParametersWindow : public Window {
void DrawWidget(const Rect &r, int widget) const override
{
if (widget == WID_NP_DESCRIPTION) {
- const GRFParameterInfo *par_info = (this->clicked_row < this->grf_config->param_info.size()) ? this->grf_config->param_info[this->clicked_row] : NULL;
- if (par_info == NULL) return;
+ const GRFParameterInfo *par_info = (this->clicked_row < this->grf_config->param_info.size()) ? this->grf_config->param_info[this->clicked_row] : nullptr;
+ if (par_info == nullptr) return;
const char *desc = GetGRFStringFromGRFText(par_info->desc);
- if (desc == NULL) return;
+ if (desc == nullptr) return;
DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_TEXTPANEL_TOP, r.bottom - WD_TEXTPANEL_BOTTOM, desc, TC_BLACK);
return;
} else if (widget != WID_NP_BACKGROUND) {
@@ -265,8 +265,8 @@ struct NewGRFParametersWindow : public Window {
int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
int text_y_offset = (this->line_height - FONT_HEIGHT_NORMAL) / 2;
for (uint i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < this->vscroll->GetCount(); i++) {
- GRFParameterInfo *par_info = (i < this->grf_config->param_info.size()) ? this->grf_config->param_info[i] : NULL;
- if (par_info == NULL) par_info = GetDummyParameterInfo(i);
+ GRFParameterInfo *par_info = (i < this->grf_config->param_info.size()) ? this->grf_config->param_info[i] : nullptr;
+ if (par_info == nullptr) par_info = GetDummyParameterInfo(i);
uint32 current_value = par_info->GetValue(this->grf_config);
bool selected = (i == this->clicked_row);
@@ -283,7 +283,7 @@ struct NewGRFParametersWindow : public Window {
SetDParam(3, current_value);
if (par_info->value_names.Contains(current_value)) {
const char *label = GetGRFStringFromGRFText(par_info->value_names.Find(current_value)->second);
- if (label != NULL) {
+ if (label != nullptr) {
SetDParam(2, STR_JUST_RAW_STRING);
SetDParamStr(3, label);
}
@@ -291,7 +291,7 @@ struct NewGRFParametersWindow : public Window {
}
const char *name = GetGRFStringFromGRFText(par_info->name);
- if (name != NULL) {
+ if (name != nullptr) {
SetDParam(0, STR_JUST_RAW_STRING);
SetDParamStr(1, name);
} else {
@@ -350,8 +350,8 @@ struct NewGRFParametersWindow : public Window {
if (_current_text_dir == TD_RTL) x = wid->current_x - 1 - x;
x -= 4;
- GRFParameterInfo *par_info = (num < this->grf_config->param_info.size()) ? this->grf_config->param_info[num] : NULL;
- if (par_info == NULL) par_info = GetDummyParameterInfo(num);
+ GRFParameterInfo *par_info = (num < this->grf_config->param_info.size()) ? this->grf_config->param_info[num] : nullptr;
+ if (par_info == nullptr) par_info = GetDummyParameterInfo(num);
/* One of the arrows is clicked */
uint32 old_val = par_info->GetValue(this->grf_config);
@@ -431,8 +431,8 @@ struct NewGRFParametersWindow : public Window {
{
if (StrEmpty(str)) return;
int32 value = atoi(str);
- GRFParameterInfo *par_info = ((uint)this->clicked_row < this->grf_config->param_info.size()) ? this->grf_config->param_info[this->clicked_row] : NULL;
- if (par_info == NULL) par_info = GetDummyParameterInfo(this->clicked_row);
+ GRFParameterInfo *par_info = ((uint)this->clicked_row < this->grf_config->param_info.size()) ? this->grf_config->param_info[this->clicked_row] : nullptr;
+ if (par_info == nullptr) par_info = GetDummyParameterInfo(this->clicked_row);
uint32 val = Clamp<uint32>(value, par_info->min_value, par_info->max_value);
par_info->SetValue(this->grf_config, val);
this->SetDirty();
@@ -441,8 +441,8 @@ struct NewGRFParametersWindow : public Window {
void OnDropdownSelect(int widget, int index) override
{
assert(this->clicked_dropdown);
- GRFParameterInfo *par_info = ((uint)this->clicked_row < this->grf_config->param_info.size()) ? this->grf_config->param_info[this->clicked_row] : NULL;
- if (par_info == NULL) par_info = GetDummyParameterInfo(this->clicked_row);
+ GRFParameterInfo *par_info = ((uint)this->clicked_row < this->grf_config->param_info.size()) ? this->grf_config->param_info[this->clicked_row] : nullptr;
+ if (par_info == nullptr) par_info = GetDummyParameterInfo(this->clicked_row);
par_info->SetValue(this->grf_config, index);
this->SetDirty();
}
@@ -574,7 +574,7 @@ typedef std::map<uint32, const GRFConfig *> GrfIdMap; ///< Map of grfid to the g
*/
static void FillGrfidMap(const GRFConfig *c, GrfIdMap *grfid_map)
{
- while (c != NULL) {
+ while (c != nullptr) {
std::pair<uint32, const GRFConfig *> p(c->ident.grfid, c);
grfid_map->insert(p);
c = c->next;
@@ -598,7 +598,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
static GUIGRFConfigList::FilterFunction * const filter_funcs[]; ///< Filter functions of the #GUIGRFConfigList.
GUIGRFConfigList avails; ///< Available (non-active) grfs.
- const GRFConfig *avail_sel; ///< Currently selected available grf. \c NULL is none is selected.
+ const GRFConfig *avail_sel; ///< Currently selected available grf. \c nullptr is none is selected.
int avail_pos; ///< Index of #avail_sel if existing, else \c -1.
StringFilter string_filter; ///< Filter for available grf.
QueryString filter_editbox; ///< Filter editbox;
@@ -620,10 +620,10 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
NewGRFWindow(WindowDesc *desc, bool editable, bool show_params, bool execute, GRFConfig **orig_list) : Window(desc), filter_editbox(EDITBOX_MAX_SIZE)
{
- this->avail_sel = NULL;
+ this->avail_sel = nullptr;
this->avail_pos = -1;
- this->active_sel = NULL;
- this->actives = NULL;
+ this->active_sel = nullptr;
+ this->actives = nullptr;
this->orig_list = orig_list;
this->editable = editable;
this->execute = execute;
@@ -684,7 +684,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
GrfIdMap grfid_map;
FillGrfidMap(this->actives, &grfid_map);
- for (const GRFConfig *a = _all_grfs; a != NULL; a = a->next) {
+ for (const GRFConfig *a = _all_grfs; a != nullptr; a = a->next) {
GrfIdMap::const_iterator iter = grfid_map.find(a->ident.grfid);
if (iter != grfid_map.end() && a->version > iter->second->version) return true;
}
@@ -697,7 +697,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
GrfIdMap grfid_map;
FillGrfidMap(this->actives, &grfid_map);
- for (const GRFConfig *a = _all_grfs; a != NULL; a = a->next) {
+ for (const GRFConfig *a = _all_grfs; a != nullptr; a = a->next) {
GrfIdMap::iterator iter = grfid_map.find(a->ident.grfid);
if (iter == grfid_map.end() || iter->second->version >= a->version) continue;
@@ -709,7 +709,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
if (this->active_sel == *c) {
DeleteWindowByClass(WC_GRF_PARAMETERS);
DeleteWindowByClass(WC_TEXTFILE);
- this->active_sel = NULL;
+ this->active_sel = nullptr;
}
delete *c;
*c = d;
@@ -842,7 +842,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
uint warning_left = rtl ? r.right - square.width - warning.width - 10 : r.left + square.width + 10;
int i = 0;
- for (const GRFConfig *c = this->actives; c != NULL; c = c->next, i++) {
+ for (const GRFConfig *c = this->actives; c != nullptr; c = c->next, i++) {
if (this->vscroll->IsVisible(i)) {
const char *text = c->GetName();
bool h = (this->active_sel == c);
@@ -853,15 +853,15 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
} else if (i == this->active_over) {
/* Get index of current selection. */
int active_sel_pos = 0;
- for (GRFConfig *c = this->actives; c != NULL && c != this->active_sel; c = c->next, active_sel_pos++) {}
+ for (GRFConfig *c = this->actives; c != nullptr && c != this->active_sel; c = c->next, active_sel_pos++) {}
if (active_sel_pos != this->active_over) {
uint top = this->active_over < active_sel_pos ? y + 1 : y + step_height - 2;
GfxFillRect(r.left + WD_FRAMERECT_LEFT, top - 1, r.right - WD_FRAMERECT_RIGHT, top + 1, PC_GREY);
}
}
DrawSprite(SPR_SQUARE, pal, square_left, y + square_offset_y);
- if (c->error != NULL) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, y + warning_offset_y);
- uint txtoffset = c->error == NULL ? 0 : warning.width;
+ if (c->error != nullptr) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, y + warning_offset_y);
+ uint txtoffset = c->error == nullptr ? 0 : warning.width;
DrawString(text_left + (rtl ? 0 : txtoffset), text_right - (rtl ? txtoffset : 0), y + offset_y, text, h ? TC_WHITE : TC_ORANGE);
y += step_height;
}
@@ -901,8 +901,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
case WID_NS_NEWGRF_INFO: {
const GRFConfig *selected = this->active_sel;
- if (selected == NULL) selected = this->avail_sel;
- if (selected != NULL) {
+ if (selected == nullptr) selected = this->avail_sel;
+ if (selected != nullptr) {
ShowNewGRFInfo(selected, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, r.right - WD_FRAMERECT_RIGHT, r.bottom - WD_FRAMERECT_BOTTOM, this->show_params);
}
break;
@@ -913,9 +913,9 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
void OnClick(Point pt, int widget, int click_count) override
{
if (widget >= WID_NS_NEWGRF_TEXTFILE && widget < WID_NS_NEWGRF_TEXTFILE + TFT_END) {
- if (this->active_sel == NULL && this->avail_sel == NULL) return;
+ if (this->active_sel == nullptr && this->avail_sel == nullptr) return;
- ShowNewGRFTextfileWindow((TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != NULL ? this->active_sel : this->avail_sel);
+ ShowNewGRFTextfileWindow((TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel);
return;
}
@@ -936,7 +936,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
}
case WID_NS_OPEN_URL: {
- const GRFConfig *c = (this->avail_sel == NULL) ? this->active_sel : this->avail_sel;
+ const GRFConfig *c = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
extern void OpenBrowser(const char *url);
OpenBrowser(c->GetURL());
@@ -944,7 +944,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
}
case WID_NS_PRESET_SAVE:
- ShowSavePresetWindow((this->preset == -1) ? NULL : this->grf_presets[this->preset].c_str());
+ ShowSavePresetWindow((this->preset == -1) ? nullptr : this->grf_presets[this->preset].c_str());
break;
case WID_NS_PRESET_DELETE:
@@ -958,10 +958,10 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
break;
case WID_NS_MOVE_UP: { // Move GRF up
- if (this->active_sel == NULL || !this->editable) break;
+ if (this->active_sel == nullptr || !this->editable) break;
int pos = 0;
- for (GRFConfig **pc = &this->actives; *pc != NULL; pc = &(*pc)->next, pos++) {
+ for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next, pos++) {
GRFConfig *c = *pc;
if (c->next == this->active_sel) {
c->next = this->active_sel->next;
@@ -977,10 +977,10 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
}
case WID_NS_MOVE_DOWN: { // Move GRF down
- if (this->active_sel == NULL || !this->editable) break;
+ if (this->active_sel == nullptr || !this->editable) break;
int pos = 1; // Start at 1 as we swap the selected newgrf with the next one
- for (GRFConfig **pc = &this->actives; *pc != NULL; pc = &(*pc)->next, pos++) {
+ for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next, pos++) {
GRFConfig *c = *pc;
if (c == this->active_sel) {
*pc = c->next;
@@ -1001,19 +1001,19 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST);
GRFConfig *c;
- for (c = this->actives; c != NULL && i > 0; c = c->next, i--) {}
+ for (c = this->actives; c != nullptr && i > 0; c = c->next, i--) {}
if (this->active_sel != c) {
DeleteWindowByClass(WC_GRF_PARAMETERS);
DeleteWindowByClass(WC_TEXTFILE);
}
this->active_sel = c;
- this->avail_sel = NULL;
+ this->avail_sel = nullptr;
this->avail_pos = -1;
this->InvalidateData();
if (click_count == 1) {
- if (this->editable && this->active_sel != NULL) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
+ if (this->editable && this->active_sel != nullptr) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
break;
}
/* With double click, continue */
@@ -1021,20 +1021,20 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
}
case WID_NS_REMOVE: { // Remove GRF
- if (this->active_sel == NULL || !this->editable) break;
+ if (this->active_sel == nullptr || !this->editable) break;
DeleteWindowByClass(WC_GRF_PARAMETERS);
DeleteWindowByClass(WC_TEXTFILE);
/* Choose the next GRF file to be the selected file. */
GRFConfig *newsel = this->active_sel->next;
- for (GRFConfig **pc = &this->actives; *pc != NULL; pc = &(*pc)->next) {
+ for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next) {
GRFConfig *c = *pc;
/* If the new selection is empty (i.e. we're deleting the last item
* in the list, pick the file just before the selected file */
- if (newsel == NULL && c->next == this->active_sel) newsel = c;
+ if (newsel == nullptr && c->next == this->active_sel) newsel = c;
if (c == this->active_sel) {
- if (newsel == c) newsel = NULL;
+ if (newsel == c) newsel = nullptr;
*pc = c->next;
delete c;
@@ -1045,14 +1045,14 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
this->active_sel = newsel;
this->preset = -1;
this->avail_pos = -1;
- this->avail_sel = NULL;
+ this->avail_sel = nullptr;
this->avails.ForceRebuild();
this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
break;
}
case WID_NS_UPGRADE: { // Upgrade GRF.
- if (!this->editable || this->actives == NULL) break;
+ if (!this->editable || this->actives == nullptr) break;
UpgradeCurrent();
this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
break;
@@ -1062,7 +1062,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
ResetObjectToPlace();
uint i = this->vscroll2->GetScrolledRowFromWidget(pt.y, this, WID_NS_AVAIL_LIST);
- this->active_sel = NULL;
+ this->active_sel = nullptr;
DeleteWindowByClass(WC_GRF_PARAMETERS);
if (i < this->avails.size()) {
if (this->avail_sel != this->avails[i]) DeleteWindowByClass(WC_TEXTFILE);
@@ -1071,7 +1071,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
}
this->InvalidateData();
if (click_count == 1) {
- if (this->editable && this->avail_sel != NULL && !HasBit(this->avail_sel->flags, GCF_INVALID)) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
+ if (this->editable && this->avail_sel != nullptr && !HasBit(this->avail_sel->flags, GCF_INVALID)) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
break;
}
/* With double click, continue */
@@ -1079,7 +1079,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
}
case WID_NS_ADD:
- if (this->avail_sel == NULL || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) break;
+ if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) break;
this->AddGRFToActive();
break;
@@ -1103,14 +1103,14 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
case WID_NS_VIEW_PARAMETERS:
case WID_NS_SET_PARAMETERS: { // Edit parameters
- if (this->active_sel == NULL || !this->show_params || this->active_sel->num_valid_params == 0) break;
+ if (this->active_sel == nullptr || !this->show_params || this->active_sel->num_valid_params == 0) break;
OpenGRFParameterWindow(this->active_sel, this->editable);
break;
}
case WID_NS_TOGGLE_PALETTE:
- if (this->active_sel != NULL && this->editable) {
+ if (this->active_sel != nullptr && this->editable) {
this->active_sel->palette ^= GRFP_USE_MASK;
this->SetDirty();
}
@@ -1136,8 +1136,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
void OnNewGRFsScanned() override
{
- if (this->active_sel == NULL) DeleteWindowByClass(WC_TEXTFILE);
- this->avail_sel = NULL;
+ if (this->active_sel == nullptr) DeleteWindowByClass(WC_TEXTFILE);
+ this->avail_sel = nullptr;
this->avail_pos = -1;
this->avails.ForceRebuild();
this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window
@@ -1158,13 +1158,13 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
ResetObjectToPlace();
DeleteWindowByClass(WC_GRF_PARAMETERS);
DeleteWindowByClass(WC_TEXTFILE);
- this->active_sel = NULL;
+ this->active_sel = nullptr;
this->InvalidateData(GOID_NEWGRF_PRESET_LOADED);
}
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
SaveGRFPresetToConfig(str, this->actives);
this->grf_presets = GetGRFPresetList();
@@ -1195,13 +1195,13 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
case GOID_NEWGRF_RESCANNED:
/* Search the list for items that are now found and mark them as such. */
- for (GRFConfig **l = &this->actives; *l != NULL; l = &(*l)->next) {
+ for (GRFConfig **l = &this->actives; *l != nullptr; l = &(*l)->next) {
GRFConfig *c = *l;
bool compatible = HasBit(c->flags, GCF_COMPATIBLE);
if (c->status != GCS_NOT_FOUND && !compatible) continue;
const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, compatible ? c->original_md5sum : c->ident.md5sum);
- if (f == NULL || HasBit(f->flags, GCF_INVALID)) continue;
+ if (f == nullptr || HasBit(f->flags, GCF_INVALID)) continue;
*l = new GRFConfig(*f);
(*l)->next = c->next;
@@ -1221,7 +1221,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
case GOID_NEWGRF_PRESET_LOADED: {
/* Update scrollbars */
int i = 0;
- for (const GRFConfig *c = this->actives; c != NULL; c = c->next, i++) {}
+ for (const GRFConfig *c = this->actives; c != nullptr; c = c->next, i++) {}
this->vscroll->SetCount(i + 1); // Reserve empty space for drag and drop handling.
@@ -1238,10 +1238,10 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
WID_NS_TOGGLE_PALETTE,
WIDGET_LIST_END
);
- this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == NULL || HasBit(this->avail_sel->flags, GCF_INVALID));
- this->SetWidgetDisabledState(WID_NS_UPGRADE, !this->editable || this->actives == NULL || !this->CanUpgradeCurrent());
+ this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == nullptr || HasBit(this->avail_sel->flags, GCF_INVALID));
+ this->SetWidgetDisabledState(WID_NS_UPGRADE, !this->editable || this->actives == nullptr || !this->CanUpgradeCurrent());
- bool disable_all = this->active_sel == NULL || !this->editable;
+ bool disable_all = this->active_sel == nullptr || !this->editable;
this->SetWidgetsDisabledState(disable_all,
WID_NS_REMOVE,
WID_NS_MOVE_UP,
@@ -1249,28 +1249,28 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
WIDGET_LIST_END
);
- const GRFConfig *c = (this->avail_sel == NULL) ? this->active_sel : this->avail_sel;
+ const GRFConfig *c = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
- this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, c == NULL || c->GetTextfile(tft) == NULL);
+ this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, c == nullptr || c->GetTextfile(tft) == nullptr);
}
- this->SetWidgetDisabledState(WID_NS_OPEN_URL, c == NULL || StrEmpty(c->GetURL()));
+ this->SetWidgetDisabledState(WID_NS_OPEN_URL, c == nullptr || StrEmpty(c->GetURL()));
- this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || this->active_sel == NULL || this->active_sel->num_valid_params == 0);
- this->SetWidgetDisabledState(WID_NS_VIEW_PARAMETERS, !this->show_params || this->active_sel == NULL || this->active_sel->num_valid_params == 0);
+ this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
+ this->SetWidgetDisabledState(WID_NS_VIEW_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
this->SetWidgetDisabledState(WID_NS_TOGGLE_PALETTE, disable_all ||
(!(_settings_client.gui.newgrf_developer_tools || _settings_client.gui.scenario_developer) && ((c->palette & GRFP_GRF_MASK) != GRFP_GRF_UNSET)));
if (!disable_all) {
/* All widgets are now enabled, so disable widgets we can't use */
if (this->active_sel == this->actives) this->DisableWidget(WID_NS_MOVE_UP);
- if (this->active_sel->next == NULL) this->DisableWidget(WID_NS_MOVE_DOWN);
+ if (this->active_sel->next == nullptr) this->DisableWidget(WID_NS_MOVE_DOWN);
}
this->SetWidgetDisabledState(WID_NS_PRESET_DELETE, this->preset == -1);
bool has_missing = false;
bool has_compatible = false;
- for (const GRFConfig *c = this->actives; !has_missing && c != NULL; c = c->next) {
+ for (const GRFConfig *c = this->actives; !has_missing && c != nullptr; c = c->next) {
has_missing |= c->status == GCS_NOT_FOUND;
has_compatible |= HasBit(c->flags, GCF_COMPATIBLE);
}
@@ -1332,7 +1332,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
if (this->avails.size() == 0) this->avail_pos = -1;
if (this->avail_pos >= 0) {
- this->active_sel = NULL;
+ this->active_sel = nullptr;
DeleteWindowByClass(WC_GRF_PARAMETERS);
if (this->avail_sel != this->avails[this->avail_pos]) DeleteWindowByClass(WC_TEXTFILE);
this->avail_sel = this->avails[this->avail_pos];
@@ -1358,7 +1358,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
if (!this->editable) return;
if (widget == WID_NS_FILE_LIST) {
- if (this->active_sel != NULL) {
+ if (this->active_sel != nullptr) {
/* Get pointer to the selected file in the active list. */
int from_pos = 0;
GRFConfig **from_prev;
@@ -1369,7 +1369,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
if (to_pos != from_pos) { // Don't move NewGRF file over itself.
/* Get pointer to destination position. */
GRFConfig **to_prev = &this->actives;
- for (int i = from_pos < to_pos ? -1 : 0; *to_prev != NULL && i < to_pos; to_prev = &(*to_prev)->next, i++) {}
+ for (int i = from_pos < to_pos ? -1 : 0; *to_prev != nullptr && i < to_pos; to_prev = &(*to_prev)->next, i++) {}
/* Detach NewGRF file from its original position. */
*from_prev = this->active_sel->next;
@@ -1382,11 +1382,11 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
this->preset = -1;
this->InvalidateData();
}
- } else if (this->avail_sel != NULL) {
+ } else if (this->avail_sel != nullptr) {
int to_pos = min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 1);
this->AddGRFToActive(to_pos);
}
- } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != NULL) {
+ } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
/* Remove active NewGRF file by dragging it over available list. */
Point dummy = {-1, -1};
this->OnClick(dummy, WID_NS_REMOVE, 1);
@@ -1405,17 +1405,17 @@ struct NewGRFWindow : public Window, NewGRFScanCallback {
{
if (!this->editable) return;
- if (widget == WID_NS_FILE_LIST && (this->active_sel != NULL || this->avail_sel != NULL)) {
+ if (widget == WID_NS_FILE_LIST && (this->active_sel != nullptr || this->avail_sel != nullptr)) {
/* An NewGRF file is dragged over the active list. */
int to_pos = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST);
/* Skip the last dummy line if the source is from the active list. */
- to_pos = min(to_pos, this->vscroll->GetCount() - (this->active_sel != NULL ? 2 : 1));
+ to_pos = min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
if (to_pos != this->active_over) {
this->active_over = to_pos;
this->SetWidgetDirty(WID_NS_FILE_LIST);
}
- } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != NULL) {
+ } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
this->active_over = -2;
this->SetWidgetDirty(WID_NS_AVAIL_LIST);
} else if (this->active_over != -1) {
@@ -1453,9 +1453,9 @@ private:
this->avails.clear();
- for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
+ for (const GRFConfig *c = _all_grfs; c != nullptr; c = c->next) {
bool found = false;
- for (const GRFConfig *grf = this->actives; grf != NULL && !found; grf = grf->next) found = grf->ident.HasGrfIdentifier(c->ident.grfid, c->ident.md5sum);
+ for (const GRFConfig *grf = this->actives; grf != nullptr && !found; grf = grf->next) found = grf->ident.HasGrfIdentifier(c->ident.grfid, c->ident.md5sum);
if (found) continue;
if (_settings_client.gui.newgrf_show_old_versions) {
@@ -1480,10 +1480,10 @@ private:
this->avails.RebuildDone();
this->avails.Sort();
- if (this->avail_sel != NULL) {
+ if (this->avail_sel != nullptr) {
this->avail_pos = find_index(this->avails, this->avail_sel);
if (this->avail_pos == -1) {
- this->avail_sel = NULL;
+ this->avail_sel = nullptr;
}
}
@@ -1497,15 +1497,15 @@ private:
*/
bool AddGRFToActive(int ins_pos = -1)
{
- if (this->avail_sel == NULL || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) return false;
+ if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) return false;
DeleteWindowByClass(WC_TEXTFILE);
uint count = 0;
- GRFConfig **entry = NULL;
+ GRFConfig **entry = nullptr;
GRFConfig **list;
/* Find last entry in the list, checking for duplicate grfid on the way */
- for (list = &this->actives; *list != NULL; list = &(*list)->next, ins_pos--) {
+ for (list = &this->actives; *list != nullptr; list = &(*list)->next, ins_pos--) {
if (ins_pos == 0) entry = list; // Insert position? Save.
if ((*list)->ident.grfid == this->avail_sel->ident.grfid) {
ShowErrorMessage(STR_NEWGRF_DUPLICATE_GRFID, INVALID_STRING_ID, WL_INFO);
@@ -1513,7 +1513,7 @@ private:
}
if (!HasBit((*list)->flags, GCF_STATIC)) count++;
}
- if (entry == NULL) entry = list;
+ if (entry == nullptr) entry = list;
if (count >= NETWORK_MAX_GRF_COUNT) {
ShowErrorMessage(STR_NEWGRF_TOO_MANY_NEWGRFS, INVALID_STRING_ID, WL_INFO);
return false;
@@ -1546,7 +1546,7 @@ void ShowMissingContentWindow(const GRFConfig *list)
{
/* Only show the things in the current list, or everything when nothing's selected */
ContentVector cv;
- for (const GRFConfig *c = list; c != NULL; c = c->next) {
+ for (const GRFConfig *c = list; c != nullptr; c = c->next) {
if (c->status != GCS_NOT_FOUND && !HasBit(c->flags, GCF_COMPATIBLE)) continue;
ContentInfo *ci = new ContentInfo();
@@ -1557,7 +1557,7 @@ void ShowMissingContentWindow(const GRFConfig *list)
memcpy(ci->md5sum, HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum, sizeof(ci->md5sum));
cv.push_back(ci);
}
- ShowNetworkContentListWindow(cv.size() == 0 ? NULL : &cv, CONTENT_TYPE_NEWGRF);
+ ShowNetworkContentListWindow(cv.size() == 0 ? nullptr : &cv, CONTENT_TYPE_NEWGRF);
}
Listing NewGRFWindow::last_sorting = {false, 0};
@@ -1605,7 +1605,7 @@ public:
void SetupSmallestSize(Window *w, bool init_array) override
{
/* Copy state flag from the window. */
- assert(dynamic_cast<NewGRFWindow *>(w) != NULL);
+ assert(dynamic_cast<NewGRFWindow *>(w) != nullptr);
NewGRFWindow *ngw = (NewGRFWindow *)w;
this->editable = ngw->editable;
@@ -1766,11 +1766,11 @@ public:
NWidgetCore *GetWidgetFromPos(int x, int y) override
{
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
- NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : NULL;
- if (nw == NULL) nw = this->acs->GetWidgetFromPos(x, y);
- if (nw == NULL) nw = this->inf->GetWidgetFromPos(x, y);
+ NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : nullptr;
+ if (nw == nullptr) nw = this->acs->GetWidgetFromPos(x, y);
+ if (nw == nullptr) nw = this->inf->GetWidgetFromPos(x, y);
return nw;
}
@@ -1912,13 +1912,13 @@ static const NWidgetPart _nested_newgrf_infopanel_widgets[] = {
/** Construct nested container widget for managing the lists and the info panel of the NewGRF GUI. */
NWidgetBase* NewGRFDisplay(int *biggest_index)
{
- NWidgetBase *avs = MakeNWidgets(_nested_newgrf_availables_widgets, lengthof(_nested_newgrf_availables_widgets), biggest_index, NULL);
+ NWidgetBase *avs = MakeNWidgets(_nested_newgrf_availables_widgets, lengthof(_nested_newgrf_availables_widgets), biggest_index, nullptr);
int biggest2;
- NWidgetBase *acs = MakeNWidgets(_nested_newgrf_actives_widgets, lengthof(_nested_newgrf_actives_widgets), &biggest2, NULL);
+ NWidgetBase *acs = MakeNWidgets(_nested_newgrf_actives_widgets, lengthof(_nested_newgrf_actives_widgets), &biggest2, nullptr);
*biggest_index = max(*biggest_index, biggest2);
- NWidgetBase *inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, lengthof(_nested_newgrf_infopanel_widgets), &biggest2, NULL);
+ NWidgetBase *inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, lengthof(_nested_newgrf_infopanel_widgets), &biggest2, nullptr);
*biggest_index = max(*biggest_index, biggest2);
return new NWidgetNewGRFDisplay(avs, acs, inf);
@@ -1970,9 +1970,9 @@ static void NewGRFConfirmationCallback(Window *w, bool confirmed)
/* Show new, updated list */
GRFConfig *c;
int i = 0;
- for (c = nw->actives; c != NULL && c != nw->active_sel; c = c->next, i++) {}
+ for (c = nw->actives; c != nullptr && c != nw->active_sel; c = c->next, i++) {}
CopyGRFConfigList(&nw->actives, *nw->orig_list, false);
- for (c = nw->actives; c != NULL && i > 0; c = c->next, i--) {}
+ for (c = nw->actives; c != nullptr && i > 0; c = c->next, i--) {}
nw->active_sel = c;
nw->avails.ForceRebuild();
@@ -2039,13 +2039,13 @@ struct SavePresetWindow : public Window {
/**
* Constructor of the save preset window.
- * @param initial_text Initial text to display in the edit box, or \c NULL.
+ * @param initial_text Initial text to display in the edit box, or \c nullptr.
*/
SavePresetWindow(const char *initial_text) : Window(&_save_preset_desc), presetname_editbox(32)
{
this->presets = GetGRFPresetList();
this->selected = -1;
- if (initial_text != NULL) {
+ if (initial_text != nullptr) {
for (uint i = 0; i < this->presets.size(); i++) {
if (this->presets[i] == initial_text) {
this->selected = i;
@@ -2064,7 +2064,7 @@ struct SavePresetWindow : public Window {
this->vscroll->SetCount((uint)this->presets.size());
this->SetFocusedWidget(WID_SVP_EDITBOX);
- if (initial_text != NULL) this->presetname_editbox.text.Assign(initial_text);
+ if (initial_text != nullptr) this->presetname_editbox.text.Assign(initial_text);
}
~SavePresetWindow()
@@ -2132,7 +2132,7 @@ struct SavePresetWindow : public Window {
case WID_SVP_SAVE: {
Window *w = FindWindowById(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
- if (w != NULL && !StrEmpty(this->presetname_editbox.text.buf)) w->OnQueryTextFinished(this->presetname_editbox.text.buf);
+ if (w != nullptr && !StrEmpty(this->presetname_editbox.text.buf)) w->OnQueryTextFinished(this->presetname_editbox.text.buf);
delete this;
break;
}
@@ -2147,7 +2147,7 @@ struct SavePresetWindow : public Window {
/**
* Open the window for saving a preset.
- * @param initial_text Initial text to display in the edit box, or \c NULL.
+ * @param initial_text Initial text to display in the edit box, or \c nullptr.
*/
static void ShowSavePresetWindow(const char *initial_text)
{
@@ -2171,7 +2171,7 @@ static const NWidgetPart _nested_scan_progress_widgets[] = {
/** Description of the widgets and other settings of the window. */
static WindowDesc _scan_progress_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_MODAL_PROGRESS, WC_NONE,
0,
_nested_scan_progress_widgets, lengthof(_nested_scan_progress_widgets)
@@ -2183,7 +2183,7 @@ struct ScanProgressWindow : public Window {
int scanned; ///< The number of NewGRFs that we have seen.
/** Create the window. */
- ScanProgressWindow() : Window(&_scan_progress_desc), last_name(NULL), scanned(0)
+ ScanProgressWindow() : Window(&_scan_progress_desc), last_name(nullptr), scanned(0)
{
this->InitNested(1);
}
@@ -2235,7 +2235,7 @@ struct ScanProgressWindow : public Window {
SetDParam(1, _settings_client.gui.last_newgrf_count);
DrawString(r.left, r.right, r.top, STR_NEWGRF_SCAN_STATUS, TC_FROMSTRING, SA_HOR_CENTER);
- DrawString(r.left, r.right, r.top + FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL, this->last_name == NULL ? "" : this->last_name, TC_BLACK, SA_HOR_CENTER);
+ DrawString(r.left, r.right, r.top + FONT_HEIGHT_NORMAL + WD_PAR_VSEP_NORMAL, this->last_name == nullptr ? "" : this->last_name, TC_BLACK, SA_HOR_CENTER);
break;
}
}
@@ -2248,7 +2248,7 @@ struct ScanProgressWindow : public Window {
void UpdateNewGRFScanStatus(uint num, const char *name)
{
free(this->last_name);
- if (name == NULL) {
+ if (name == nullptr) {
char buf[256];
GetString(buf, STR_NEWGRF_SCAN_ARCHIVES, lastof(buf));
this->last_name = stredup(buf);
@@ -2270,6 +2270,6 @@ struct ScanProgressWindow : public Window {
void UpdateNewGRFScanStatus(uint num, const char *name)
{
ScanProgressWindow *w = dynamic_cast<ScanProgressWindow *>(FindWindowByClass(WC_MODAL_PROGRESS));
- if (w == NULL) w = new ScanProgressWindow();
+ if (w == nullptr) w = new ScanProgressWindow();
w->UpdateNewGRFScanStatus(num, name);
}
diff --git a/src/newgrf_house.cpp b/src/newgrf_house.cpp
index e6abf0962..7df48304b 100644
--- a/src/newgrf_house.cpp
+++ b/src/newgrf_house.cpp
@@ -34,12 +34,12 @@ HouseOverrideManager _house_mngr(NEW_HOUSE_OFFSET, NUM_HOUSES, INVALID_HOUSE_ID)
/**
* Retrieve the grf file associated with a house.
* @param house_id House to query.
- * @return The associated GRF file (may be \c NULL).
+ * @return The associated GRF file (may be \c nullptr).
*/
static const GRFFile *GetHouseSpecGrf(HouseID house_id)
{
const HouseSpec *hs = HouseSpec::Get(house_id);
- return (hs != NULL) ? hs->grf_prop.grffile : NULL;
+ return (hs != nullptr) ? hs->grf_prop.grffile : nullptr;
}
/**
@@ -190,7 +190,7 @@ static bool SearchNearbyHouseID(TileIndex tile, void *user_data)
if (IsTileType(tile, MP_HOUSE)) {
HouseID house = GetHouseType(tile); // tile been examined
const HouseSpec *hs = HouseSpec::Get(house);
- if (hs->grf_prop.grffile != NULL) { // must be one from a grf file
+ if (hs->grf_prop.grffile != nullptr) { // must be one from a grf file
SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data;
TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
@@ -214,7 +214,7 @@ static bool SearchNearbyHouseClass(TileIndex tile, void *user_data)
if (IsTileType(tile, MP_HOUSE)) {
HouseID house = GetHouseType(tile); // tile been examined
const HouseSpec *hs = HouseSpec::Get(house);
- if (hs->grf_prop.grffile != NULL) { // must be one from a grf file
+ if (hs->grf_prop.grffile != nullptr) { // must be one from a grf file
SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data;
TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
@@ -238,7 +238,7 @@ static bool SearchNearbyHouseGRFID(TileIndex tile, void *user_data)
if (IsTileType(tile, MP_HOUSE)) {
HouseID house = GetHouseType(tile); // tile been examined
const HouseSpec *hs = HouseSpec::Get(house);
- if (hs->grf_prop.grffile != NULL) { // must be one from a grf file
+ if (hs->grf_prop.grffile != nullptr) { // must be one from a grf file
SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data;
TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
@@ -320,7 +320,7 @@ static uint32 GetDistanceFromNearbyHouse(uint8 parameter, TileIndex tile, HouseI
/* Building counts for new houses with id = parameter. */
case 0x61: {
const HouseSpec *hs = HouseSpec::Get(this->house_id);
- if (hs->grf_prop.grffile == NULL) return 0;
+ if (hs->grf_prop.grffile == nullptr) return 0;
HouseID new_house = _house_mngr.GetID(parameter, hs->grf_prop.grffile->grfid);
return new_house == INVALID_HOUSE_ID ? 0 : GetNumHouses(new_house, this->town);
@@ -462,7 +462,7 @@ void DrawNewHouseTile(TileInfo *ti, HouseID house_id)
HouseResolverObject object(house_id, ti->tile, Town::GetByTile(ti->tile));
const SpriteGroup *group = object.Resolve();
- if (group != NULL && group->type == SGT_TILELAYOUT) {
+ if (group != nullptr && group->type == SGT_TILELAYOUT) {
/* Limit the building stage to the number of stages supplied. */
const TileLayoutSpriteGroup *tlgroup = (const TileLayoutSpriteGroup *)group;
byte stage = GetHouseBuildingStage(ti->tile);
@@ -488,7 +488,7 @@ struct HouseAnimationBase : public AnimationBase<HouseAnimationBase, HouseSpec,
void AnimateNewHouseTile(TileIndex tile)
{
const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
- if (hs == NULL) return;
+ if (hs == nullptr) return;
HouseAnimationBase::AnimateTile(hs, Town::GetByTile(tile), tile, HasBit(hs->extra_flags, CALLBACK_1A_RANDOM_BITS));
}
@@ -581,14 +581,14 @@ static void DoTriggerHouse(TileIndex tile, HouseTrigger trigger, byte base_rando
HouseID hid = GetHouseType(tile);
HouseSpec *hs = HouseSpec::Get(hid);
- if (hs->grf_prop.spritegroup[0] == NULL) return;
+ if (hs->grf_prop.spritegroup[0] == nullptr) return;
HouseResolverObject object(hid, tile, Town::GetByTile(tile), CBID_RANDOM_TRIGGER);
object.waiting_triggers = GetHouseTriggers(tile) | trigger;
SetHouseTriggers(tile, object.waiting_triggers); // store now for var 5F
const SpriteGroup *group = object.Resolve();
- if (group == NULL) return;
+ if (group == nullptr) return;
/* Store remaining triggers. */
SetHouseTriggers(tile, object.GetRemainingTriggers());
diff --git a/src/newgrf_industries.cpp b/src/newgrf_industries.cpp
index 457b06f67..9f9416ff3 100644
--- a/src/newgrf_industries.cpp
+++ b/src/newgrf_industries.cpp
@@ -79,7 +79,7 @@ uint32 GetIndustryIDAtOffset(TileIndex tile, const Industry *i, uint32 cur_grfid
}
}
/* Not an 'old type' tile */
- if (indtsp->grf_prop.spritegroup[0] != NULL) { // tile has a spritegroup ?
+ if (indtsp->grf_prop.spritegroup[0] != nullptr) { // tile has a spritegroup ?
if (indtsp->grf_prop.grffile->grfid == cur_grfid) { // same industry, same grf ?
return indtsp->grf_prop.local_id;
} else {
@@ -202,7 +202,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
const IndustrySpec *indspec = GetIndustrySpec(this->type);
- if (this->industry == NULL) {
+ if (this->industry == nullptr) {
DEBUG(grf, 1, "Unhandled variable 0x%X (no available industry) in callback 0x%x", variable, this->ro.callback);
*available = false;
@@ -240,7 +240,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
bool is_ai = false;
const Company *c = Company::GetIfValid(this->industry->founder);
- if (c != NULL) {
+ if (c != nullptr) {
const Livery *l = &c->livery[LS_DEFAULT];
is_ai = c->is_ai;
@@ -338,7 +338,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
}
/* Get a variable from the persistent storage */
- case 0x7C: return (this->industry->psa != NULL) ? this->industry->psa->GetValue(parameter) : 0;
+ case 0x7C: return (this->industry->psa != nullptr) ? this->industry->psa->GetValue(parameter) : 0;
/* Industry structure access*/
case 0x80: return this->industry->location.tile;
@@ -411,7 +411,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
/* virtual */ uint32 IndustriesScopeResolver::GetRandomBits() const
{
- return this->industry != NULL ? this->industry->random : 0;
+ return this->industry != nullptr ? this->industry->random : 0;
}
/* virtual */ uint32 IndustriesScopeResolver::GetTriggers() const
@@ -423,13 +423,13 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
{
if (this->industry->index == INVALID_INDUSTRY) return;
- if (this->industry->psa == NULL) {
+ if (this->industry->psa == nullptr) {
/* There is no need to create a storage if the value is zero. */
if (value == 0) return;
/* Create storage on first modification. */
const IndustrySpec *indsp = GetIndustrySpec(this->industry->type);
- uint32 grfid = (indsp->grf_prop.grffile != NULL) ? indsp->grf_prop.grffile->grfid : 0;
+ uint32 grfid = (indsp->grf_prop.grffile != nullptr) ? indsp->grf_prop.grffile->grfid : 0;
assert(PersistentStorage::CanAllocateItem());
this->industry->psa = new PersistentStorage(grfid, GSF_INDUSTRIES, this->industry->location.tile);
}
@@ -445,7 +445,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
static const GRFFile *GetGrffile(IndustryType type)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
- return (indspec != NULL) ? indspec->grf_prop.grffile : NULL;
+ return (indspec != nullptr) ? indspec->grf_prop.grffile : nullptr;
}
/**
@@ -462,7 +462,7 @@ IndustriesResolverObject::IndustriesResolverObject(TileIndex tile, Industry *ind
CallbackID callback, uint32 callback_param1, uint32 callback_param2)
: ResolverObject(GetGrffile(type), callback, callback_param1, callback_param2),
industries_scope(*this, tile, indus, type, random_bits),
- town_scope(NULL)
+ town_scope(nullptr)
{
this->root_spritegroup = GetIndustrySpec(type)->grf_prop.spritegroup[0];
}
@@ -478,16 +478,16 @@ IndustriesResolverObject::~IndustriesResolverObject()
*/
TownScopeResolver *IndustriesResolverObject::GetTown()
{
- if (this->town_scope == NULL) {
- Town *t = NULL;
+ if (this->town_scope == nullptr) {
+ Town *t = nullptr;
bool readonly = true;
- if (this->industries_scope.industry != NULL) {
+ if (this->industries_scope.industry != nullptr) {
t = this->industries_scope.industry->town;
readonly = this->industries_scope.industry->index == INVALID_INDUSTRY;
} else if (this->industries_scope.tile != INVALID_TILE) {
t = ClosestTownFromTile(this->industries_scope.tile, UINT_MAX);
}
- if (t == NULL) return NULL;
+ if (t == nullptr) return nullptr;
this->town_scope = new TownScopeResolver(*this, t, readonly);
}
return this->town_scope;
@@ -533,7 +533,7 @@ CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, uin
ind.town = ClosestTownFromTile(tile, UINT_MAX);
ind.random = initial_random_bits;
ind.founder = founder;
- ind.psa = NULL;
+ ind.psa = nullptr;
IndustriesResolverObject object(tile, &ind, type, seed, CBID_INDUSTRY_LOCATION, 0, creation_type);
uint16 result = object.ResolveCallback();
@@ -556,7 +556,7 @@ uint32 GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityCal
const IndustrySpec *indspec = GetIndustrySpec(type);
if (HasBit(indspec->callback_mask, CBM_IND_PROBABILITY)) {
- uint16 res = GetIndustryCallback(CBID_INDUSTRY_PROBABILITY, 0, creation_type, NULL, type, INVALID_TILE);
+ uint16 res = GetIndustryCallback(CBID_INDUSTRY_PROBABILITY, 0, creation_type, nullptr, type, INVALID_TILE);
if (res != CALLBACK_FAILED) {
if (indspec->grf_prop.grffile->grf_version < 8) {
/* Disallow if result != 0 */
@@ -608,7 +608,7 @@ void IndustryProductionCallback(Industry *ind, int reason)
SB(object.callback_param2, 8, 16, loop);
const SpriteGroup *tgroup = object.Resolve();
- if (tgroup == NULL || tgroup->type != SGT_INDUSTRY_PRODUCTION) break;
+ if (tgroup == nullptr || tgroup->type != SGT_INDUSTRY_PRODUCTION) break;
const IndustryProductionSpriteGroup *group = (const IndustryProductionSpriteGroup *)tgroup;
if (group->version == 0xFF) {
diff --git a/src/newgrf_industries.h b/src/newgrf_industries.h
index 2fa8f7d36..b0c1e3bdd 100644
--- a/src/newgrf_industries.h
+++ b/src/newgrf_industries.h
@@ -43,7 +43,7 @@ struct IndustriesScopeResolver : public ScopeResolver {
/** Resolver for industries. */
struct IndustriesResolverObject : public ResolverObject {
IndustriesScopeResolver industries_scope; ///< Scope resolver for the industry.
- TownScopeResolver *town_scope; ///< Scope resolver for the associated town (if needed and available, else \c NULL).
+ TownScopeResolver *town_scope; ///< Scope resolver for the associated town (if needed and available, else \c nullptr).
IndustriesResolverObject(TileIndex tile, Industry *indus, IndustryType type, uint32 random_bits = 0,
CallbackID callback = CBID_NO_CALLBACK, uint32 callback_param1 = 0, uint32 callback_param2 = 0);
@@ -57,7 +57,7 @@ struct IndustriesResolverObject : public ResolverObject {
case VSG_SCOPE_SELF: return &industries_scope;
case VSG_SCOPE_PARENT: {
TownScopeResolver *tsr = this->GetTown();
- if (tsr != NULL) return tsr;
+ if (tsr != nullptr) return tsr;
}
FALLTHROUGH;
diff --git a/src/newgrf_industrytiles.cpp b/src/newgrf_industrytiles.cpp
index 0b2a55000..5a8794564 100644
--- a/src/newgrf_industrytiles.cpp
+++ b/src/newgrf_industrytiles.cpp
@@ -80,7 +80,7 @@ uint32 GetRelativePosition(TileIndex tile, TileIndex ind_tile)
/* Land info of nearby tiles */
case 0x60: return GetNearbyIndustryTileInformation(parameter, this->tile,
- this->industry == NULL ? (IndustryID)INVALID_INDUSTRY : this->industry->index, true, this->ro.grffile->grf_version >= 8);
+ this->industry == nullptr ? (IndustryID)INVALID_INDUSTRY : this->industry->index, true, this->ro.grffile->grf_version >= 8);
/* Animation stage of nearby tiles */
case 0x61: {
@@ -103,7 +103,7 @@ uint32 GetRelativePosition(TileIndex tile, TileIndex ind_tile)
/* virtual */ uint32 IndustryTileScopeResolver::GetRandomBits() const
{
- assert(this->industry != NULL && IsValidTile(this->tile));
+ assert(this->industry != nullptr && IsValidTile(this->tile));
assert(this->industry->index == INVALID_INDUSTRY || IsTileType(this->tile, MP_INDUSTRY));
return (this->industry->index != INVALID_INDUSTRY) ? GetIndustryRandomBits(this->tile) : 0;
@@ -111,7 +111,7 @@ uint32 GetRelativePosition(TileIndex tile, TileIndex ind_tile)
/* virtual */ uint32 IndustryTileScopeResolver::GetTriggers() const
{
- assert(this->industry != NULL && IsValidTile(this->tile));
+ assert(this->industry != nullptr && IsValidTile(this->tile));
assert(this->industry->index == INVALID_INDUSTRY || IsTileType(this->tile, MP_INDUSTRY));
if (this->industry->index == INVALID_INDUSTRY) return 0;
return GetIndustryTriggers(this->tile);
@@ -125,7 +125,7 @@ uint32 GetRelativePosition(TileIndex tile, TileIndex ind_tile)
static const GRFFile *GetIndTileGrffile(IndustryGfx gfx)
{
const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
- return (its != NULL) ? its->grf_prop.grffile : NULL;
+ return (its != nullptr) ? its->grf_prop.grffile : nullptr;
}
/**
@@ -171,7 +171,7 @@ static void IndustryDrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGro
uint16 GetIndustryTileCallback(CallbackID callback, uint32 param1, uint32 param2, IndustryGfx gfx_id, Industry *industry, TileIndex tile)
{
- assert(industry != NULL && IsValidTile(tile));
+ assert(industry != nullptr && IsValidTile(tile));
assert(industry->index == INVALID_INDUSTRY || IsTileType(tile, MP_INDUSTRY));
IndustryTileResolverObject object(gfx_id, tile, industry, callback, param1, param2);
@@ -194,7 +194,7 @@ bool DrawNewIndustryTile(TileInfo *ti, Industry *i, IndustryGfx gfx, const Indus
IndustryTileResolverObject object(gfx, ti->tile, i);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->type != SGT_TILELAYOUT) return false;
+ if (group == nullptr || group->type != SGT_TILELAYOUT) return false;
/* Limit the building stage to the number of stages supplied. */
const TileLayoutSpriteGroup *tlgroup = (const TileLayoutSpriteGroup *)group;
@@ -259,7 +259,7 @@ struct IndustryAnimationBase : public AnimationBase<IndustryAnimationBase, Indus
void AnimateNewIndustryTile(TileIndex tile)
{
const IndustryTileSpec *itspec = GetIndustryTileSpec(GetIndustryGfx(tile));
- if (itspec == NULL) return;
+ if (itspec == nullptr) return;
IndustryAnimationBase::AnimateTile(itspec, Industry::GetByTile(tile), tile, (itspec->special_flags & INDTILE_SPECIAL_NEXTFRAME_RANDOMBITS) != 0);
}
@@ -305,14 +305,14 @@ static void DoTriggerIndustryTile(TileIndex tile, IndustryTileTrigger trigger, I
IndustryGfx gfx = GetIndustryGfx(tile);
const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
- if (itspec->grf_prop.spritegroup[0] == NULL) return;
+ if (itspec->grf_prop.spritegroup[0] == nullptr) return;
IndustryTileResolverObject object(gfx, tile, ind, CBID_RANDOM_TRIGGER);
object.waiting_triggers = GetIndustryTriggers(tile) | trigger;
SetIndustryTriggers(tile, object.waiting_triggers); // store now for var 5F
const SpriteGroup *group = object.Resolve();
- if (group == NULL) return;
+ if (group == nullptr) return;
/* Store remaining triggers. */
SetIndustryTriggers(tile, object.GetRemainingTriggers());
@@ -335,7 +335,7 @@ static void DoTriggerIndustryTile(TileIndex tile, IndustryTileTrigger trigger, I
*/
static void DoReseedIndustry(Industry *ind, uint32 reseed)
{
- if (reseed == 0 || ind == NULL) return;
+ if (reseed == 0 || ind == nullptr) return;
uint16 random_bits = Random();
ind->random &= reseed;
diff --git a/src/newgrf_object.cpp b/src/newgrf_object.cpp
index 1501cb9b8..6038f092f 100644
--- a/src/newgrf_object.cpp
+++ b/src/newgrf_object.cpp
@@ -151,7 +151,7 @@ static uint32 GetObjectIDAtOffset(TileIndex tile, uint32 cur_grfid)
const ObjectSpec *spec = ObjectSpec::Get(o->type);
/* Default objects have no associated NewGRF file */
- if (spec->grf_prop.grffile == NULL) {
+ if (spec->grf_prop.grffile == nullptr) {
return 0xFFFE; // Defined in another grf file
}
@@ -237,9 +237,9 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte local_id, uint32 grfid,
{
/* We get the town from the object, or we calculate the closest
* town if we need to when there's no object. */
- const Town *t = NULL;
+ const Town *t = nullptr;
- if (this->obj == NULL) {
+ if (this->obj == nullptr) {
switch (variable) {
/* Allow these when there's no object. */
case 0x41:
@@ -325,7 +325,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte local_id, uint32 grfid,
}
/* Land info of nearby tiles */
- case 0x62: return GetNearbyObjectTileInformation(parameter, this->tile, this->obj == NULL ? INVALID_OBJECT : this->obj->index, this->ro.grffile->grf_version >= 8);
+ case 0x62: return GetNearbyObjectTileInformation(parameter, this->tile, this->obj == nullptr ? INVALID_OBJECT : this->obj->index, this->ro.grffile->grf_version >= 8);
/* Animation counter of nearby tile */
case 0x63: {
@@ -357,8 +357,8 @@ ObjectResolverObject::ObjectResolverObject(const ObjectSpec *spec, Object *obj,
CallbackID callback, uint32 param1, uint32 param2)
: ResolverObject(spec->grf_prop.grffile, callback, param1, param2), object_scope(*this, obj, tile, view)
{
- this->town_scope = NULL;
- this->root_spritegroup = (obj == NULL && spec->grf_prop.spritegroup[CT_PURCHASE_OBJECT] != NULL) ?
+ this->town_scope = nullptr;
+ this->root_spritegroup = (obj == nullptr && spec->grf_prop.spritegroup[CT_PURCHASE_OBJECT] != nullptr) ?
spec->grf_prop.spritegroup[CT_PURCHASE_OBJECT] : spec->grf_prop.spritegroup[0];
}
@@ -374,15 +374,15 @@ ObjectResolverObject::~ObjectResolverObject()
*/
TownScopeResolver *ObjectResolverObject::GetTown()
{
- if (this->town_scope == NULL) {
+ if (this->town_scope == nullptr) {
Town *t;
- if (this->object_scope.obj != NULL) {
+ if (this->object_scope.obj != nullptr) {
t = this->object_scope.obj->town;
} else {
t = ClosestTownFromTile(this->object_scope.tile, UINT_MAX);
}
- if (t == NULL) return NULL;
- this->town_scope = new TownScopeResolver(*this, t, this->object_scope.obj == NULL);
+ if (t == nullptr) return nullptr;
+ this->town_scope = new TownScopeResolver(*this, t, this->object_scope.obj == nullptr);
}
return this->town_scope;
}
@@ -395,7 +395,7 @@ TownScopeResolver *ObjectResolverObject::GetTown()
* @param spec The specification of the object / the entry point.
* @param o The object to call the callback for.
* @param tile The tile the callback is called for.
- * @param view The view of the object (only used when o == NULL).
+ * @param view The view of the object (only used when o == nullptr).
* @return The result of the callback.
*/
uint16 GetObjectCallback(CallbackID callback, uint32 param1, uint32 param2, const ObjectSpec *spec, Object *o, TileIndex tile, uint8 view)
@@ -412,7 +412,7 @@ uint16 GetObjectCallback(CallbackID callback, uint32 param1, uint32 param2, cons
*/
static void DrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGroup *group, const ObjectSpec *spec)
{
- const DrawTileSprites *dts = group->ProcessRegisters(NULL);
+ const DrawTileSprites *dts = group->ProcessRegisters(nullptr);
PaletteID palette = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? SPR_2CCMAP_BASE : PALETTE_RECOLOUR_START) + Object::GetByTile(ti->tile)->colour;
SpriteID image = dts->ground.sprite;
@@ -442,7 +442,7 @@ void DrawNewObjectTile(TileInfo *ti, const ObjectSpec *spec)
ObjectResolverObject object(spec, o, ti->tile);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->type != SGT_TILELAYOUT) return;
+ if (group == nullptr || group->type != SGT_TILELAYOUT) return;
DrawTileLayout(ti, (const TileLayoutSpriteGroup *)group, spec);
}
@@ -456,11 +456,11 @@ void DrawNewObjectTile(TileInfo *ti, const ObjectSpec *spec)
*/
void DrawNewObjectTileInGUI(int x, int y, const ObjectSpec *spec, uint8 view)
{
- ObjectResolverObject object(spec, NULL, INVALID_TILE, view);
+ ObjectResolverObject object(spec, nullptr, INVALID_TILE, view);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->type != SGT_TILELAYOUT) return;
+ if (group == nullptr || group->type != SGT_TILELAYOUT) return;
- const DrawTileSprites *dts = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(NULL);
+ const DrawTileSprites *dts = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
PaletteID palette;
if (Company::IsValidID(_local_company)) {
@@ -518,7 +518,7 @@ struct ObjectAnimationBase : public AnimationBase<ObjectAnimationBase, ObjectSpe
void AnimateNewObjectTile(TileIndex tile)
{
const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
- if (spec == NULL || !(spec->flags & OBJECT_FLAG_ANIMATION)) return;
+ if (spec == nullptr || !(spec->flags & OBJECT_FLAG_ANIMATION)) return;
ObjectAnimationBase::AnimateTile(spec, Object::GetByTile(tile), tile, (spec->flags & OBJECT_FLAG_ANIM_RANDOM_BITS) != 0);
}
diff --git a/src/newgrf_object.h b/src/newgrf_object.h
index 1ab351be9..dcc5caa8b 100644
--- a/src/newgrf_object.h
+++ b/src/newgrf_object.h
@@ -137,7 +137,7 @@ struct ObjectResolverObject : public ResolverObject {
case VSG_SCOPE_PARENT: {
TownScopeResolver *tsr = this->GetTown();
- if (tsr != NULL) return tsr;
+ if (tsr != nullptr) return tsr;
FALLTHROUGH;
}
diff --git a/src/newgrf_railtype.cpp b/src/newgrf_railtype.cpp
index c57be5b6c..63121c1e8 100644
--- a/src/newgrf_railtype.cpp
+++ b/src/newgrf_railtype.cpp
@@ -44,13 +44,13 @@
if (IsRailDepotTile(this->tile)) return Depot::GetByTile(this->tile)->build_date;
return _date;
case 0x44: {
- const Town *t = NULL;
+ const Town *t = nullptr;
if (IsRailDepotTile(this->tile)) {
t = Depot::GetByTile(this->tile)->town;
} else if (IsLevelCrossingTile(this->tile)) {
t = ClosestTownFromTile(this->tile, UINT_MAX);
}
- return t != NULL ? GetTownRadiusGroup(t, this->tile) : HZB_TOWN_EDGE;
+ return t != nullptr ? GetTownRadiusGroup(t, this->tile) : HZB_TOWN_EDGE;
}
}
@@ -64,12 +64,12 @@
{
if (group->num_loading > 0) return group->loading[0];
if (group->num_loaded > 0) return group->loaded[0];
- return NULL;
+ return nullptr;
}
/**
* Resolver object for rail types.
- * @param rti Railtype. NULL in NewGRF Inspect window.
+ * @param rti Railtype. nullptr in NewGRF Inspect window.
* @param tile %Tile containing the track. For track on a bridge this is the southern bridgehead.
* @param context Are we resolving sprites for the upper halftile, or on a bridge?
* @param rtsg Railpart of interest
@@ -77,9 +77,9 @@
* @param param2 Extra parameter (second parameter of the callback, except railtypes do not have callbacks).
*/
RailTypeResolverObject::RailTypeResolverObject(const RailtypeInfo *rti, TileIndex tile, TileContext context, RailTypeSpriteGroup rtsg, uint32 param1, uint32 param2)
- : ResolverObject(rti != NULL ? rti->grffile[rtsg] : NULL, CBID_NO_CALLBACK, param1, param2), railtype_scope(*this, tile, context)
+ : ResolverObject(rti != nullptr ? rti->grffile[rtsg] : nullptr, CBID_NO_CALLBACK, param1, param2), railtype_scope(*this, tile, context)
{
- this->root_spritegroup = rti != NULL ? rti->group[rtsg] : NULL;
+ this->root_spritegroup = rti != nullptr ? rti->group[rtsg] : nullptr;
}
/**
@@ -88,18 +88,18 @@ RailTypeResolverObject::RailTypeResolverObject(const RailtypeInfo *rti, TileInde
* @param tile The tile to get the sprite for.
* @param rtsg The type of sprite to draw.
* @param context Where are we drawing the tile?
- * @param[out] num_results If not NULL, return the number of sprites in the spriteset.
+ * @param[out] num_results If not nullptr, return the number of sprites in the spriteset.
* @return The sprite to draw.
*/
SpriteID GetCustomRailSprite(const RailtypeInfo *rti, TileIndex tile, RailTypeSpriteGroup rtsg, TileContext context, uint *num_results)
{
assert(rtsg < RTSG_END);
- if (rti->group[rtsg] == NULL) return 0;
+ if (rti->group[rtsg] == nullptr) return 0;
RailTypeResolverObject object(rti, tile, context, rtsg);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->GetNumResults() == 0) return 0;
+ if (group == nullptr || group->GetNumResults() == 0) return 0;
if (num_results) *num_results = group->GetNumResults();
@@ -118,14 +118,14 @@ SpriteID GetCustomRailSprite(const RailtypeInfo *rti, TileIndex tile, RailTypeSp
*/
SpriteID GetCustomSignalSprite(const RailtypeInfo *rti, TileIndex tile, SignalType type, SignalVariant var, SignalState state, bool gui)
{
- if (rti->group[RTSG_SIGNALS] == NULL) return 0;
+ if (rti->group[RTSG_SIGNALS] == nullptr) return 0;
uint32 param1 = gui ? 0x10 : 0x00;
uint32 param2 = (type << 16) | (var << 8) | state;
RailTypeResolverObject object(rti, tile, TCX_NORMAL, RTSG_SIGNALS, param1, param2);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->GetNumResults() == 0) return 0;
+ if (group == nullptr || group->GetNumResults() == 0) return 0;
return group->GetResult();
}
@@ -139,7 +139,7 @@ SpriteID GetCustomSignalSprite(const RailtypeInfo *rti, TileIndex tile, SignalTy
uint8 GetReverseRailTypeTranslation(RailType railtype, const GRFFile *grffile)
{
/* No rail type table present, return rail type as-is */
- if (grffile == NULL || grffile->railtype_list.size() == 0) return railtype;
+ if (grffile == nullptr || grffile->railtype_list.size() == 0) return railtype;
/* Look for a matching rail type label in the table */
RailTypeLabel label = GetRailTypeInfo(railtype)->label;
diff --git a/src/newgrf_railtype.h b/src/newgrf_railtype.h
index 829c166cb..ddcbd71ae 100644
--- a/src/newgrf_railtype.h
+++ b/src/newgrf_railtype.h
@@ -53,7 +53,7 @@ struct RailTypeResolverObject : public ResolverObject {
const SpriteGroup *ResolveReal(const RealSpriteGroup *group) const override;
};
-SpriteID GetCustomRailSprite(const RailtypeInfo *rti, TileIndex tile, RailTypeSpriteGroup rtsg, TileContext context = TCX_NORMAL, uint *num_results = NULL);
+SpriteID GetCustomRailSprite(const RailtypeInfo *rti, TileIndex tile, RailTypeSpriteGroup rtsg, TileContext context = TCX_NORMAL, uint *num_results = nullptr);
SpriteID GetCustomSignalSprite(const RailtypeInfo *rti, TileIndex tile, SignalType type, SignalVariant var, SignalState state, bool gui = false);
uint8 GetReverseRailTypeTranslation(RailType railtype, const GRFFile *grffile);
diff --git a/src/newgrf_sound.cpp b/src/newgrf_sound.cpp
index 0a04f4400..a25c3abcc 100644
--- a/src/newgrf_sound.cpp
+++ b/src/newgrf_sound.cpp
@@ -49,7 +49,7 @@ void InitializeSoundPool()
SoundEntry *GetSound(SoundID index)
{
- if (index >= _sounds.size()) return NULL;
+ if (index >= _sounds.size()) return nullptr;
return &_sounds[index];
}
@@ -173,7 +173,7 @@ SoundID GetNewGRFSoundID(const GRFFile *file, SoundID sound_id)
if (sound_id < ORIGINAL_SAMPLE_COUNT) return sound_id;
sound_id -= ORIGINAL_SAMPLE_COUNT;
- if (file == NULL || sound_id >= file->num_sounds) return INVALID_SOUND;
+ if (file == nullptr || sound_id >= file->num_sounds) return INVALID_SOUND;
return file->sound_offset + sound_id;
}
@@ -192,7 +192,7 @@ bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
uint16 callback;
/* If the engine has no GRF ID associated it can't ever play any new sounds */
- if (file == NULL) return false;
+ if (file == nullptr) return false;
/* Check that the vehicle type uses the sound effect callback */
if (!HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_SOUND_EFFECT)) return false;
diff --git a/src/newgrf_spritegroup.cpp b/src/newgrf_spritegroup.cpp
index 1bcb4a035..2bff33a03 100644
--- a/src/newgrf_spritegroup.cpp
+++ b/src/newgrf_spritegroup.cpp
@@ -26,7 +26,7 @@ TemporaryStorageArray<int32, 0x110> _temp_store;
/**
* ResolverObject (re)entry point.
* This cannot be made a call to a virtual function because virtual functions
- * do not like NULL and checking for NULL *everywhere* is more cumbersome than
+ * do not like nullptr and checking for nullptr *everywhere* is more cumbersome than
* this little helper function.
* @param group the group to resolve for
* @param object information needed to resolve the group
@@ -35,7 +35,7 @@ TemporaryStorageArray<int32, 0x110> _temp_store;
*/
/* static */ const SpriteGroup *SpriteGroup::Resolve(const SpriteGroup *group, ResolverObject &object, bool top_level)
{
- if (group == NULL) return NULL;
+ if (group == nullptr) return nullptr;
if (top_level) {
_temp_store.ClearChanges();
}
@@ -73,7 +73,7 @@ static inline uint32 GetVariable(const ResolverObject &object, ScopeResolver *sc
case 0x7D: return _temp_store.GetValue(parameter);
case 0x7F:
- if (object.grffile == NULL) return 0;
+ if (object.grffile == nullptr) return 0;
return object.grffile->GetParam(parameter);
default:
@@ -130,7 +130,7 @@ static inline uint32 GetVariable(const ResolverObject &object, ScopeResolver *sc
*/
/* virtual */ const SpriteGroup *ResolverObject::ResolveReal(const RealSpriteGroup *group) const
{
- return NULL;
+ return nullptr;
}
/**
@@ -207,7 +207,7 @@ const SpriteGroup *DeterministicSpriteGroup::Resolve(ResolverObject &object) con
bool available = true;
if (adjust->variable == 0x7E) {
const SpriteGroup *subgroup = SpriteGroup::Resolve(adjust->subroutine, object, false);
- if (subgroup == NULL) {
+ if (subgroup == nullptr) {
value = CALLBACK_FAILED;
} else {
value = subgroup->GetCallbackResult();
@@ -293,24 +293,24 @@ const SpriteGroup *RealSpriteGroup::Resolve(ResolverObject &object) const
* Process registers and the construction stage into the sprite layout.
* The passed construction stage might get reset to zero, if it gets incorporated into the layout
* during the preprocessing.
- * @param[in,out] stage Construction stage (0-3), or NULL if not applicable.
+ * @param[in,out] stage Construction stage (0-3), or nullptr if not applicable.
* @return sprite layout to draw.
*/
const DrawTileSprites *TileLayoutSpriteGroup::ProcessRegisters(uint8 *stage) const
{
if (!this->dts.NeedsPreprocessing()) {
- if (stage != NULL && this->dts.consistent_max_offset > 0) *stage = GetConstructionStageOffset(*stage, this->dts.consistent_max_offset);
+ if (stage != nullptr && this->dts.consistent_max_offset > 0) *stage = GetConstructionStageOffset(*stage, this->dts.consistent_max_offset);
return &this->dts;
}
static DrawTileSprites result;
- uint8 actual_stage = stage != NULL ? *stage : 0;
+ uint8 actual_stage = stage != nullptr ? *stage : 0;
this->dts.PrepareLayout(0, 0, 0, actual_stage, false);
this->dts.ProcessRegisters(0, 0, false);
result.seq = this->dts.GetLayout(&result.ground);
/* Stage has been processed by PrepareLayout(), set it to zero. */
- if (stage != NULL) *stage = 0;
+ if (stage != nullptr) *stage = 0;
return &result;
}
diff --git a/src/newgrf_spritegroup.h b/src/newgrf_spritegroup.h
index 2db78f6ba..55fb0b58f 100644
--- a/src/newgrf_spritegroup.h
+++ b/src/newgrf_spritegroup.h
@@ -316,13 +316,13 @@ struct ScopeResolver {
struct ResolverObject {
/**
* Resolver constructor.
- * @param grffile NewGRF file associated with the object (or \c NULL if none).
+ * @param grffile NewGRF file associated with the object (or \c nullptr if none).
* @param callback Callback code being resolved (default value is #CBID_NO_CALLBACK).
* @param callback_param1 First parameter (var 10) of the callback (only used when \a callback is also set).
* @param callback_param2 Second parameter (var 18) of the callback (only used when \a callback is also set).
*/
ResolverObject(const GRFFile *grffile, CallbackID callback = CBID_NO_CALLBACK, uint32 callback_param1 = 0, uint32 callback_param2 = 0)
- : default_scope(*this), callback(callback), callback_param1(callback_param1), callback_param2(callback_param2), grffile(grffile), root_spritegroup(NULL)
+ : default_scope(*this), callback(callback), callback_param1(callback_param1), callback_param2(callback_param2), grffile(grffile), root_spritegroup(nullptr)
{
this->ResetState();
}
@@ -360,7 +360,7 @@ struct ResolverObject {
uint16 ResolveCallback()
{
const SpriteGroup *result = Resolve();
- return result != NULL ? result->GetCallbackResult() : CALLBACK_FAILED;
+ return result != nullptr ? result->GetCallbackResult() : CALLBACK_FAILED;
}
virtual const SpriteGroup *ResolveReal(const RealSpriteGroup *group) const;
diff --git a/src/newgrf_station.cpp b/src/newgrf_station.cpp
index d9b79c55a..8b6e87bca 100644
--- a/src/newgrf_station.cpp
+++ b/src/newgrf_station.cpp
@@ -35,11 +35,11 @@ template <typename Tspec, typename Tid, Tid Tmax>
/* Set up initial data */
classes[0].global_id = 'DFLT';
classes[0].name = STR_STATION_CLASS_DFLT;
- classes[0].Insert(NULL);
+ classes[0].Insert(nullptr);
classes[1].global_id = 'WAYP';
classes[1].name = STR_STATION_CLASS_WAYP;
- classes[1].Insert(NULL);
+ classes[1].Insert(nullptr);
}
template <typename Tspec, typename Tid, Tid Tmax>
@@ -225,13 +225,13 @@ static uint32 GetRailContinuationInfo(TileIndex tile)
/* Station Resolver Functions */
/* virtual */ uint32 StationScopeResolver::GetRandomBits() const
{
- return (this->st == NULL ? 0 : this->st->random_bits) | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits(this->tile) << 16);
+ return (this->st == nullptr ? 0 : this->st->random_bits) | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits(this->tile) << 16);
}
/* virtual */ uint32 StationScopeResolver::GetTriggers() const
{
- return this->st == NULL ? 0 : this->st->waiting_triggers;
+ return this->st == nullptr ? 0 : this->st->waiting_triggers;
}
@@ -257,22 +257,22 @@ static struct {
*/
TownScopeResolver *StationResolverObject::GetTown()
{
- if (this->town_scope == NULL) {
- Town *t = NULL;
- if (this->station_scope.st != NULL) {
+ if (this->town_scope == nullptr) {
+ Town *t = nullptr;
+ if (this->station_scope.st != nullptr) {
t = this->station_scope.st->town;
} else if (this->station_scope.tile != INVALID_TILE) {
t = ClosestTownFromTile(this->station_scope.tile, UINT_MAX);
}
- if (t == NULL) return NULL;
- this->town_scope = new TownScopeResolver(*this, t, this->station_scope.st == NULL);
+ if (t == nullptr) return nullptr;
+ this->town_scope = new TownScopeResolver(*this, t, this->station_scope.st == nullptr);
}
return this->town_scope;
}
/* virtual */ uint32 StationScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
{
- if (this->st == NULL) {
+ if (this->st == nullptr) {
/* Station does not exist, so we're in a purchase list or the land slope check callback. */
switch (variable) {
case 0x40:
@@ -396,8 +396,8 @@ uint32 Station::GetNewGRFVariable(const ResolverObject &object, byte variable, b
case 0x8A: return this->had_vehicle_of_type;
case 0xF1: return (this->airport.tile != INVALID_TILE) ? this->airport.GetSpec()->ttd_airport_type : ATP_TTDP_LARGE;
- case 0xF2: return (this->truck_stops != NULL) ? this->truck_stops->status : 0;
- case 0xF3: return (this->bus_stops != NULL) ? this->bus_stops->status : 0;
+ case 0xF2: return (this->truck_stops != nullptr) ? this->truck_stops->status : 0;
+ case 0xF3: return (this->bus_stops != nullptr) ? this->bus_stops->status : 0;
case 0xF6: return this->airport.flags;
case 0xF7: return GB(this->airport.flags, 8, 8);
}
@@ -486,7 +486,7 @@ uint32 Waypoint::GetNewGRFVariable(const ResolverObject &object, byte variable,
/* virtual */ const SpriteGroup *StationResolverObject::ResolveReal(const RealSpriteGroup *group) const
{
- if (this->station_scope.st == NULL || this->station_scope.statspec->cls_id == STAT_CLASS_WAYP) {
+ if (this->station_scope.st == nullptr || this->station_scope.statspec->cls_id == STAT_CLASS_WAYP) {
return group->loading[0];
}
@@ -541,14 +541,14 @@ uint32 Waypoint::GetNewGRFVariable(const ResolverObject &object, byte variable,
StationResolverObject::StationResolverObject(const StationSpec *statspec, BaseStation *st, TileIndex tile,
CallbackID callback, uint32 callback_param1, uint32 callback_param2)
: ResolverObject(statspec->grf_prop.grffile, callback, callback_param1, callback_param2),
- station_scope(*this, statspec, st, tile), town_scope(NULL)
+ station_scope(*this, statspec, st, tile), town_scope(nullptr)
{
/* Invalidate all cached vars */
_svc.valid = 0;
CargoID ctype = CT_DEFAULT_NA;
- if (this->station_scope.st == NULL) {
+ if (this->station_scope.st == nullptr) {
/* No station, so we are in a purchase list */
ctype = CT_PURCHASE;
} else if (Station::IsExpected(this->station_scope.st)) {
@@ -556,7 +556,7 @@ StationResolverObject::StationResolverObject(const StationSpec *statspec, BaseSt
/* Pick the first cargo that we have waiting */
const CargoSpec *cs;
FOR_ALL_CARGOSPECS(cs) {
- if (this->station_scope.statspec->grf_prop.spritegroup[cs->Index()] != NULL &&
+ if (this->station_scope.statspec->grf_prop.spritegroup[cs->Index()] != nullptr &&
st->goods[cs->Index()].cargo.TotalCount() > 0) {
ctype = cs->Index();
break;
@@ -564,7 +564,7 @@ StationResolverObject::StationResolverObject(const StationSpec *statspec, BaseSt
}
}
- if (this->station_scope.statspec->grf_prop.spritegroup[ctype] == NULL) {
+ if (this->station_scope.statspec->grf_prop.spritegroup[ctype] == nullptr) {
ctype = CT_DEFAULT;
}
@@ -581,7 +581,7 @@ StationResolverObject::~StationResolverObject()
/**
* Resolve sprites for drawing a station tile.
* @param statspec Station spec
- * @param st Station (NULL in GUI)
+ * @param st Station (nullptr in GUI)
* @param tile Station tile being drawn (INVALID_TILE in GUI)
* @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
* @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
@@ -590,7 +590,7 @@ SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st
{
StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, var10);
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->type != SGT_RESULT) return 0;
+ if (group == nullptr || group->type != SGT_RESULT) return 0;
return group->GetResult() - 0x42D;
}
@@ -609,7 +609,7 @@ SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseS
StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, 2, layout | (edge_info << 16));
const SpriteGroup *group = object.Resolve();
- if (group == NULL || group->type != SGT_RESULT) return 0;
+ if (group == nullptr || group->type != SGT_RESULT) return 0;
/* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
return group->GetResult() + GetRegister(0x100);
@@ -637,7 +637,7 @@ CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_til
TileIndexDiff diff = cur_tile - north_tile;
Slope slope = GetTileSlope(cur_tile);
- StationResolverObject object(statspec, NULL, cur_tile, CBID_STATION_LAND_SLOPE_CHECK,
+ StationResolverObject object(statspec, nullptr, cur_tile, CBID_STATION_LAND_SLOPE_CHECK,
(slope << 4) | (slope ^ (axis == AXIS_Y && HasBit(slope, CORNER_W) != HasBit(slope, CORNER_E) ? SLOPE_EW : 0)),
(numtracks << 24) | (plat_len << 16) | (axis == AXIS_Y ? TileX(diff) << 8 | TileY(diff) : TileY(diff) << 8 | TileX(diff)));
object.station_scope.axis = axis;
@@ -664,10 +664,10 @@ int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exe
{
uint i;
- if (statspec == NULL || st == NULL) return 0;
+ if (statspec == nullptr || st == nullptr) return 0;
for (i = 1; i < st->num_specs && i < NUM_STATIONSSPECS_PER_STATION; i++) {
- if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
+ if (st->speclist[i].spec == nullptr && st->speclist[i].grfid == 0) break;
}
if (i == NUM_STATIONSSPECS_PER_STATION) {
@@ -690,7 +690,7 @@ int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exe
if (st->num_specs == 2) {
/* Initial allocation */
- st->speclist[0].spec = NULL;
+ st->speclist[0].spec = nullptr;
st->speclist[0].grfid = 0;
st->speclist[0].localidx = 0;
}
@@ -727,7 +727,7 @@ void DeallocateSpecFromStation(BaseStation *st, byte specindex)
}
/* This specindex is no longer in use, so deallocate it */
- st->speclist[specindex].spec = NULL;
+ st->speclist[specindex].spec = nullptr;
st->speclist[specindex].grfid = 0;
st->speclist[specindex].localidx = 0;
@@ -740,7 +740,7 @@ void DeallocateSpecFromStation(BaseStation *st, byte specindex)
} else {
free(st->speclist);
st->num_specs = 0;
- st->speclist = NULL;
+ st->speclist = nullptr;
st->cached_anim_triggers = 0;
st->cached_cargo_triggers = 0;
return;
@@ -762,42 +762,42 @@ void DeallocateSpecFromStation(BaseStation *st, byte specindex)
*/
bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
{
- const DrawTileSprites *sprites = NULL;
+ const DrawTileSprites *sprites = nullptr;
const RailtypeInfo *rti = GetRailTypeInfo(railtype);
PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
uint tile = 2;
const StationSpec *statspec = StationClass::Get(sclass)->GetSpec(station);
- if (statspec == NULL) return false;
+ if (statspec == nullptr) return false;
if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
- uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, NULL, INVALID_TILE);
+ uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, nullptr, INVALID_TILE);
if (callback != CALLBACK_FAILED) tile = callback;
}
uint32 total_offset = rti->GetRailtypeSpriteOffset();
uint32 relocation = 0;
uint32 ground_relocation = 0;
- const NewGRFSpriteLayout *layout = NULL;
+ const NewGRFSpriteLayout *layout = nullptr;
DrawTileSprites tmp_rail_layout;
- if (statspec->renderdata == NULL) {
+ if (statspec->renderdata == nullptr) {
sprites = GetStationTileLayout(STATION_RAIL, tile + axis);
} else {
layout = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
if (!layout->NeedsPreprocessing()) {
sprites = layout;
- layout = NULL;
+ layout = nullptr;
}
}
- if (layout != NULL) {
+ if (layout != nullptr) {
/* Sprite layout which needs preprocessing */
bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
uint8 var10;
FOR_EACH_SET_BIT(var10, var10_values) {
- uint32 var10_relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE, var10);
+ uint32 var10_relocation = GetCustomStationRelocation(statspec, nullptr, INVALID_TILE, var10);
layout->ProcessRegisters(var10, var10_relocation, separate_ground);
}
@@ -806,9 +806,9 @@ bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID
total_offset = 0;
} else {
/* Simple sprite layout */
- ground_relocation = relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE, 0);
+ ground_relocation = relocation = GetCustomStationRelocation(statspec, nullptr, INVALID_TILE, 0);
if (HasBit(sprites->ground.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
- ground_relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE, 1);
+ ground_relocation = GetCustomStationRelocation(statspec, nullptr, INVALID_TILE, 1);
}
ground_relocation += rti->fallback_railtype;
}
@@ -816,7 +816,7 @@ bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID
SpriteID image = sprites->ground.sprite;
PaletteID pal = sprites->ground.pal;
RailTrackOffset overlay_offset;
- if (rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &image, &overlay_offset)) {
+ if (rti->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &image, &overlay_offset)) {
SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
DrawSprite(image, PAL_NONE, x, y);
DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
@@ -834,11 +834,11 @@ bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID
const StationSpec *GetStationSpec(TileIndex t)
{
- if (!IsCustomStationSpecIndex(t)) return NULL;
+ if (!IsCustomStationSpecIndex(t)) return nullptr;
const BaseStation *st = BaseStation::GetByTile(t);
uint specindex = GetCustomStationSpecIndex(t);
- return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
+ return specindex < st->num_specs ? st->speclist[specindex].spec : nullptr;
}
@@ -852,7 +852,7 @@ bool IsStationTileBlocked(TileIndex tile)
{
const StationSpec *statspec = GetStationSpec(tile);
- return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
+ return statspec != nullptr && HasBit(statspec->blocked, GetStationGfx(tile));
}
/**
@@ -866,7 +866,7 @@ bool CanStationTileHavePylons(TileIndex tile)
const StationSpec *statspec = GetStationSpec(tile);
uint gfx = GetStationGfx(tile);
/* Default stations do not draw pylons under roofs (gfx >= 4) */
- return statspec != NULL ? HasBit(statspec->pylons, gfx) : gfx < 4;
+ return statspec != nullptr ? HasBit(statspec->pylons, gfx) : gfx < 4;
}
/**
@@ -878,7 +878,7 @@ bool CanStationTileHavePylons(TileIndex tile)
bool CanStationTileHaveWires(TileIndex tile)
{
const StationSpec *statspec = GetStationSpec(tile);
- return statspec == NULL || !HasBit(statspec->wires, GetStationGfx(tile));
+ return statspec == nullptr || !HasBit(statspec->wires, GetStationGfx(tile));
}
/** Wrapper for animation control, see GetStationCallback. */
@@ -899,7 +899,7 @@ struct StationAnimationBase : public AnimationBase<StationAnimationBase, Station
void AnimateStationTile(TileIndex tile)
{
const StationSpec *ss = GetStationSpec(tile);
- if (ss == NULL) return;
+ if (ss == nullptr) return;
StationAnimationBase::AnimateTile(ss, BaseStation::GetByTile(tile), tile, HasBit(ss->flags, SSF_CB141_RANDOM_BITS));
}
@@ -912,7 +912,7 @@ void TriggerStationAnimation(BaseStation *st, TileIndex tile, StationAnimationTr
};
/* Get Station if it wasn't supplied */
- if (st == NULL) st = BaseStation::GetByTile(tile);
+ if (st == nullptr) st = BaseStation::GetByTile(tile);
/* Check the cached animation trigger bitmask to see if we need
* to bother with any further processing. */
@@ -925,7 +925,7 @@ void TriggerStationAnimation(BaseStation *st, TileIndex tile, StationAnimationTr
TILE_AREA_LOOP(tile, area) {
if (st->TileBelongsToRailStation(tile)) {
const StationSpec *ss = GetStationSpec(tile);
- if (ss != NULL && HasBit(ss->animation.triggers, trigger)) {
+ if (ss != nullptr && HasBit(ss->animation.triggers, trigger)) {
CargoID cargo;
if (cargo_type == CT_INVALID) {
cargo = CT_INVALID;
@@ -953,7 +953,7 @@ void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigg
};
/* Get Station if it wasn't supplied */
- if (st == NULL) st = Station::GetByTile(tile);
+ if (st == nullptr) st = Station::GetByTile(tile);
/* Check the cached cargo trigger bitmask to see if we need
* to bother with any further processing. */
@@ -981,7 +981,7 @@ void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigg
TILE_AREA_LOOP(tile, area) {
if (st->TileBelongsToRailStation(tile)) {
const StationSpec *ss = GetStationSpec(tile);
- if (ss == NULL) continue;
+ if (ss == nullptr) continue;
/* Cargo taken "will only be triggered if all of those
* cargo types have no more cargo waiting." */
@@ -994,7 +994,7 @@ void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigg
object.waiting_triggers = st->waiting_triggers;
const SpriteGroup *group = object.Resolve();
- if (group == NULL) continue;
+ if (group == nullptr) continue;
used_triggers |= object.used_triggers;
@@ -1036,7 +1036,7 @@ void StationUpdateCachedTriggers(BaseStation *st)
* of this station. */
for (uint i = 0; i < st->num_specs; i++) {
const StationSpec *ss = st->speclist[i].spec;
- if (ss != NULL) {
+ if (ss != nullptr) {
st->cached_anim_triggers |= ss->animation.triggers;
st->cached_cargo_triggers |= ss->cargo_triggers;
}
diff --git a/src/newgrf_station.h b/src/newgrf_station.h
index 2a19b5811..8f3bb6dce 100644
--- a/src/newgrf_station.h
+++ b/src/newgrf_station.h
@@ -67,7 +67,7 @@ struct StationResolverObject : public ResolverObject {
case VSG_SCOPE_PARENT: {
TownScopeResolver *tsr = this->GetTown();
- if (tsr != NULL) return tsr;
+ if (tsr != nullptr) return tsr;
FALLTHROUGH;
}
diff --git a/src/newgrf_storage.h b/src/newgrf_storage.h
index a0c1558f8..e9155dc5c 100644
--- a/src/newgrf_storage.h
+++ b/src/newgrf_storage.h
@@ -70,7 +70,7 @@ struct PersistentStorageArray : BasePersistentStorageArray {
TYPE *prev_storage; ///< Memory to store "old" states so we can revert them on the performance of test cases for commands etc.
/** Simply construct the array */
- PersistentStorageArray() : prev_storage(NULL)
+ PersistentStorageArray() : prev_storage(nullptr)
{
memset(this->storage, 0, sizeof(this->storage));
}
@@ -105,8 +105,8 @@ struct PersistentStorageArray : BasePersistentStorageArray {
/* We do not have made a backup; lets do so */
if (AreChangesPersistent()) {
- assert(this->prev_storage == NULL);
- } else if (this->prev_storage == NULL) {
+ assert(this->prev_storage == nullptr);
+ } else if (this->prev_storage == nullptr) {
this->prev_storage = MallocT<TYPE>(SIZE);
memcpy(this->prev_storage, this->storage, sizeof(this->storage));
@@ -133,10 +133,10 @@ struct PersistentStorageArray : BasePersistentStorageArray {
void ClearChanges()
{
- if (this->prev_storage != NULL) {
+ if (this->prev_storage != nullptr) {
memcpy(this->storage, this->prev_storage, sizeof(this->storage));
free(this->prev_storage);
- this->prev_storage = NULL;
+ this->prev_storage = nullptr;
}
}
};
diff --git a/src/newgrf_text.cpp b/src/newgrf_text.cpp
index e1f73a5c3..4cba3c368 100644
--- a/src/newgrf_text.cpp
+++ b/src/newgrf_text.cpp
@@ -115,7 +115,7 @@ private:
* @param text_ The text to store in this GRFText.
* @param len_ The length of the text to store.
*/
- GRFText(byte langid_, const char *text_, size_t len_) : next(NULL), len(len_), langid(langid_)
+ GRFText(byte langid_, const char *text_, size_t len_) : next(nullptr), len(len_), langid(langid_)
{
/* We need to use memcpy instead of strcpy due to
* the possibility of "choice lists" and therefore
@@ -232,7 +232,7 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
}
char *d = old_d;
- if (lm == NULL) {
+ if (lm == nullptr) {
/* In case there is no mapping, just ignore everything but the default.
* A probable cause for this happening is when the language file has
* been removed by the user and as such no mapping could be made. */
@@ -342,7 +342,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
size_t len = Utf8Decode(&c, str);
/* Helper variable for a possible (string) mapping. */
- UnmappedChoiceList *mapping = NULL;
+ UnmappedChoiceList *mapping = nullptr;
if (c == NFO_UTF8_IDENTIFIER) {
unicode = true;
@@ -461,7 +461,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
if (str[0] == '\0') goto string_end;
const LanguageMap *lm = LanguageMap::GetLanguageMap(grfid, language_id);
int index = *str++;
- int mapped = lm != NULL ? lm->GetMapping(index, code == 0x0E) : -1;
+ int mapped = lm != nullptr ? lm->GetMapping(index, code == 0x0E) : -1;
if (mapped >= 0) {
d += Utf8Encode(d, code == 0x0E ? SCC_GENDER_INDEX : SCC_SET_CASE);
d += Utf8Encode(d, code == 0x0E ? mapped : mapped + 1);
@@ -472,7 +472,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
case 0x10:
case 0x11:
if (str[0] == '\0') goto string_end;
- if (mapping == NULL) {
+ if (mapping == nullptr) {
if (code == 0x10) str++; // Skip the index
grfmsg(1, "choice list %s marker found when not expected", code == 0x10 ? "next" : "default");
break;
@@ -490,7 +490,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
break;
case 0x12:
- if (mapping == NULL) {
+ if (mapping == nullptr) {
grfmsg(1, "choice list end marker found when not expected");
} else {
/* Terminate the previous string. */
@@ -499,7 +499,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
/* Now we can start flushing everything and clean everything up. */
d = mapping->Flush(LanguageMap::GetLanguageMap(grfid, language_id));
delete mapping;
- mapping = NULL;
+ mapping = nullptr;
}
break;
@@ -507,7 +507,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
case 0x14:
case 0x15:
if (str[0] == '\0') goto string_end;
- if (mapping != NULL) {
+ if (mapping != nullptr) {
grfmsg(1, "choice lists can't be stacked, it's going to get messy now...");
if (code != 0x14) str++;
} else {
@@ -559,13 +559,13 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
}
string_end:
- if (mapping != NULL) {
+ if (mapping != nullptr) {
grfmsg(1, "choice list was incomplete, the whole list is ignored");
delete mapping;
}
*d = '\0';
- if (olen != NULL) *olen = d - tmp + 1;
+ if (olen != nullptr) *olen = d - tmp + 1;
tmp = ReallocT(tmp, d - tmp + 1);
return tmp;
}
@@ -580,7 +580,7 @@ void AddGRFTextToList(GRFText **list, GRFText *text_to_add)
GRFText **ptext, *text;
/* Loop through all languages and see if we can replace a string */
- for (ptext = list; (text = *ptext) != NULL; ptext = &text->next) {
+ for (ptext = list; (text = *ptext) != nullptr; ptext = &text->next) {
if (text->langid == text_to_add->langid) {
text_to_add->next = text->next;
*ptext = text_to_add;
@@ -630,9 +630,9 @@ void AddGRFTextToList(struct GRFText **list, const char *text_to_add)
*/
GRFText *DuplicateGRFText(GRFText *orig)
{
- GRFText *newtext = NULL;
+ GRFText *newtext = nullptr;
GRFText **ptext = &newtext;
- for (; orig != NULL; orig = orig->next) {
+ for (; orig != nullptr; orig = orig->next) {
*ptext = GRFText::Copy(orig);
ptext = &(*ptext)->next;
}
@@ -684,7 +684,7 @@ StringID AddGRFString(uint32 grfid, uint16 stringid, byte langid_to_add, bool ne
/* If we didn't find our stringid and grfid in the list, allocate a new id */
if (id == _num_grf_texts) _num_grf_texts++;
- if (_grf_text[id].textholder == NULL) {
+ if (_grf_text[id].textholder == nullptr) {
_grf_text[id].grfid = grfid;
_grf_text[id].stringid = stringid;
_grf_text[id].def_string = def_string;
@@ -715,20 +715,20 @@ StringID GetGRFStringID(uint32 grfid, StringID stringid)
* Get a C-string from a GRFText-list. If there is a translation for the
* current language it is returned, otherwise the default translation
* is returned. If there is neither a default nor a translation for the
- * current language NULL is returned.
+ * current language nullptr is returned.
* @param text The GRFText to get the string from.
*/
const char *GetGRFStringFromGRFText(const GRFText *text)
{
- const char *default_text = NULL;
+ const char *default_text = nullptr;
/* Search the list of lang-strings of this stringid for current lang */
- for (; text != NULL; text = text->next) {
+ for (; text != nullptr; text = text->next) {
if (text->langid == _currentLangID) return text->text;
/* If the current string is English or American, set it as the
* fallback language if the specific language isn't available. */
- if (text->langid == GRFLX_UNSPECIFIED || (default_text == NULL && (text->langid == GRFLX_ENGLISH || text->langid == GRFLX_AMERICAN))) {
+ if (text->langid == GRFLX_UNSPECIFIED || (default_text == nullptr && (text->langid == GRFLX_ENGLISH || text->langid == GRFLX_AMERICAN))) {
default_text = text->text;
}
}
@@ -744,7 +744,7 @@ const char *GetGRFStringPtr(uint16 stringid)
assert(_grf_text[stringid].grfid != 0);
const char *str = GetGRFStringFromGRFText(_grf_text[stringid].textholder);
- if (str != NULL) return str;
+ if (str != nullptr) return str;
/* Use the default string ID if the fallback string isn't available */
return GetStringPtr(_grf_text[stringid].def_string);
@@ -783,7 +783,7 @@ bool CheckGrfLangID(byte lang_id, byte grf_version)
*/
void CleanUpGRFText(GRFText *grftext)
{
- while (grftext != NULL) {
+ while (grftext != nullptr) {
GRFText *grftext2 = grftext->next;
delete grftext;
grftext = grftext2;
@@ -802,7 +802,7 @@ void CleanUpStrings()
CleanUpGRFText(_grf_text[id].textholder);
_grf_text[id].grfid = 0;
_grf_text[id].stringid = 0;
- _grf_text[id].textholder = NULL;
+ _grf_text[id].textholder = nullptr;
}
_num_grf_texts = 0;
@@ -814,7 +814,7 @@ struct TextRefStack {
const GRFFile *grffile;
bool used;
- TextRefStack() : position(0), grffile(NULL), used(false) {}
+ TextRefStack() : position(0), grffile(nullptr), used(false) {}
TextRefStack(const TextRefStack &stack) :
position(stack.position),
@@ -872,7 +872,7 @@ struct TextRefStack {
void ResetStack(const GRFFile *grffile)
{
- assert(grffile != NULL);
+ assert(grffile != nullptr);
this->position = 0;
this->grffile = grffile;
this->used = true;
@@ -928,7 +928,7 @@ void RestoreTextRefStackBackup(struct TextRefStack *backup)
*
* @param grffile the NewGRF providing the stack data
* @param numEntries number of entries to copy from the registers
- * @param values values to copy onto the stack; if NULL the temporary NewGRF registers will be used instead
+ * @param values values to copy onto the stack; if nullptr the temporary NewGRF registers will be used instead
*/
void StartTextRefStackUsage(const GRFFile *grffile, byte numEntries, const uint32 *values)
{
@@ -938,7 +938,7 @@ void StartTextRefStackUsage(const GRFFile *grffile, byte numEntries, const uint3
byte *p = _newgrf_textrefstack.stack;
for (uint i = 0; i < numEntries; i++) {
- uint32 value = values != NULL ? values[i] : _temp_store.GetValue(0x100 + i);
+ uint32 value = values != nullptr ? values[i] : _temp_store.GetValue(0x100 + i);
for (uint j = 0; j < 32; j += 8) {
*p = GB(value, j, 8);
p++;
diff --git a/src/newgrf_text.h b/src/newgrf_text.h
index 141e1536f..69ea6bd40 100644
--- a/src/newgrf_text.h
+++ b/src/newgrf_text.h
@@ -26,7 +26,7 @@ const char *GetGRFStringFromGRFText(const struct GRFText *text);
const char *GetGRFStringPtr(uint16 stringid);
void CleanUpStrings();
void SetCurrentGrfLangID(byte language_id);
-char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newlines, const char *str, int *olen = NULL, StringControlCode byte80 = SCC_NEWGRF_PRINT_WORD_STRING_ID);
+char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newlines, const char *str, int *olen = nullptr, StringControlCode byte80 = SCC_NEWGRF_PRINT_WORD_STRING_ID);
struct GRFText *DuplicateGRFText(struct GRFText *orig);
void AddGRFTextToList(struct GRFText **list, struct GRFText *text_to_add);
void AddGRFTextToList(struct GRFText **list, byte langid, uint32 grfid, bool allow_newlines, const char *text_to_add);
@@ -35,7 +35,7 @@ void CleanUpGRFText(struct GRFText *grftext);
bool CheckGrfLangID(byte lang_id, byte grf_version);
-void StartTextRefStackUsage(const GRFFile *grffile, byte numEntries, const uint32 *values = NULL);
+void StartTextRefStackUsage(const GRFFile *grffile, byte numEntries, const uint32 *values = nullptr);
void StopTextRefStackUsage();
void RewindTextRefStack();
bool UsingNewGRFTextStack();
diff --git a/src/newgrf_town.cpp b/src/newgrf_town.cpp
index 00fcf76b6..d124eaab5 100644
--- a/src/newgrf_town.cpp
+++ b/src/newgrf_town.cpp
@@ -33,7 +33,7 @@
/* Check the persistent storage for the GrfID stored in register 100h. */
uint32 grfid = GetRegister(0x100);
if (grfid == 0xFFFFFFFF) {
- if (this->ro.grffile == NULL) return 0;
+ if (this->ro.grffile == nullptr) return 0;
grfid = this->ro.grffile->grfid;
}
@@ -123,9 +123,9 @@
{
if (this->readonly) return;
- assert(this->t != NULL);
+ assert(this->t != nullptr);
/* We can't store anything if the caller has no #GRFFile. */
- if (this->ro.grffile == NULL) return;
+ if (this->ro.grffile == nullptr) return;
/* Check the persistent storage for the GrfID stored in register 100h. */
uint32 grfid = GetRegister(0x100);
diff --git a/src/newgrf_townname.cpp b/src/newgrf_townname.cpp
index 42aae3f14..df99dd738 100644
--- a/src/newgrf_townname.cpp
+++ b/src/newgrf_townname.cpp
@@ -21,21 +21,21 @@
#include "safeguards.h"
-static GRFTownName *_grf_townnames = NULL;
+static GRFTownName *_grf_townnames = nullptr;
GRFTownName *GetGRFTownName(uint32 grfid)
{
GRFTownName *t = _grf_townnames;
- for (; t != NULL; t = t->next) {
+ for (; t != nullptr; t = t->next) {
if (t->grfid == grfid) return t;
}
- return NULL;
+ return nullptr;
}
GRFTownName *AddGRFTownName(uint32 grfid)
{
GRFTownName *t = GetGRFTownName(grfid);
- if (t == NULL) {
+ if (t == nullptr) {
t = CallocT<GRFTownName>(1);
t->grfid = grfid;
t->next = _grf_townnames;
@@ -47,9 +47,9 @@ GRFTownName *AddGRFTownName(uint32 grfid)
void DelGRFTownName(uint32 grfid)
{
GRFTownName *t = _grf_townnames;
- GRFTownName *p = NULL;
- for (;t != NULL; p = t, t = t->next) if (t->grfid == grfid) break;
- if (t != NULL) {
+ GRFTownName *p = nullptr;
+ for (;t != nullptr; p = t, t = t->next) if (t->grfid == grfid) break;
+ if (t != nullptr) {
for (int i = 0; i < 128; i++) {
for (int j = 0; j < t->nbparts[i]; j++) {
for (int k = 0; k < t->partlist[i][j].partcount; k++) {
@@ -59,7 +59,7 @@ void DelGRFTownName(uint32 grfid)
}
free(t->partlist[i]);
}
- if (p != NULL) {
+ if (p != nullptr) {
p->next = t->next;
} else {
_grf_townnames = t->next;
@@ -70,7 +70,7 @@ void DelGRFTownName(uint32 grfid)
static char *RandomPart(char *buf, GRFTownName *t, uint32 seed, byte id, const char *last)
{
- assert(t != NULL);
+ assert(t != nullptr);
for (int i = 0; i < t->nbparts[id]; i++) {
byte count = t->partlist[id][i].bitcount;
uint16 maxprob = t->partlist[id][i].maxprob;
@@ -93,7 +93,7 @@ static char *RandomPart(char *buf, GRFTownName *t, uint32 seed, byte id, const c
char *GRFTownNameGenerate(char *buf, uint32 grfid, uint16 gen, uint32 seed, const char *last)
{
strecpy(buf, "", last);
- for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
+ for (GRFTownName *t = _grf_townnames; t != nullptr; t = t->next) {
if (t->grfid == grfid) {
assert(gen < t->nb_gen);
buf = RandomPart(buf, t, seed, t->id[gen], last);
@@ -106,9 +106,9 @@ char *GRFTownNameGenerate(char *buf, uint32 grfid, uint16 gen, uint32 seed, cons
StringID *GetGRFTownNameList()
{
int nb_names = 0, n = 0;
- for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) nb_names += t->nb_gen;
+ for (GRFTownName *t = _grf_townnames; t != nullptr; t = t->next) nb_names += t->nb_gen;
StringID *list = MallocT<StringID>(nb_names + 1);
- for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
+ for (GRFTownName *t = _grf_townnames; t != nullptr; t = t->next) {
for (int j = 0; j < t->nb_gen; j++) list[n++] = t->name[j];
}
list[n] = INVALID_STRING_ID;
@@ -117,12 +117,12 @@ StringID *GetGRFTownNameList()
void CleanUpGRFTownNames()
{
- while (_grf_townnames != NULL) DelGRFTownName(_grf_townnames->grfid);
+ while (_grf_townnames != nullptr) DelGRFTownName(_grf_townnames->grfid);
}
uint32 GetGRFTownNameId(int gen)
{
- for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
+ for (GRFTownName *t = _grf_townnames; t != nullptr; t = t->next) {
if (gen < t->nb_gen) return t->grfid;
gen -= t->nb_gen;
}
@@ -132,7 +132,7 @@ uint32 GetGRFTownNameId(int gen)
uint16 GetGRFTownNameType(int gen)
{
- for (GRFTownName *t = _grf_townnames; t != NULL; t = t->next) {
+ for (GRFTownName *t = _grf_townnames; t != nullptr; t = t->next) {
if (gen < t->nb_gen) return gen;
gen -= t->nb_gen;
}
diff --git a/src/news_func.h b/src/news_func.h
index cd0862f34..bfd38a724 100644
--- a/src/news_func.h
+++ b/src/news_func.h
@@ -17,7 +17,7 @@
#include "station_type.h"
#include "industry_type.h"
-void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1 = NR_NONE, uint32 ref1 = UINT32_MAX, NewsReferenceType reftype2 = NR_NONE, uint32 ref2 = UINT32_MAX, void *free_data = NULL);
+void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1 = NR_NONE, uint32 ref1 = UINT32_MAX, NewsReferenceType reftype2 = NR_NONE, uint32 ref2 = UINT32_MAX, void *free_data = nullptr);
static inline void AddCompanyNewsItem(StringID string, CompanyNewsInformation *cni)
{
@@ -44,7 +44,7 @@ static inline void AddVehicleAdviceNewsItem(StringID string, VehicleID vehicle)
AddNewsItem(string, NT_ADVICE, NF_INCOLOUR | NF_SMALL | NF_VEHICLE_PARAM0, NR_VEHICLE, vehicle);
}
-static inline void AddTileNewsItem(StringID string, NewsType type, TileIndex tile, void *free_data = NULL)
+static inline void AddTileNewsItem(StringID string, NewsType type, TileIndex tile, void *free_data = nullptr)
{
AddNewsItem(string, type, NF_NO_TRANSPARENT | NF_SHADE | NF_THIN, NR_TILE, tile, NR_NONE, UINT32_MAX, free_data);
}
diff --git a/src/news_gui.cpp b/src/news_gui.cpp
index 59c75eb51..7aee32cac 100644
--- a/src/news_gui.cpp
+++ b/src/news_gui.cpp
@@ -41,23 +41,23 @@
#include "safeguards.h"
-const NewsItem *_statusbar_news_item = NULL;
+const NewsItem *_statusbar_news_item = nullptr;
static uint MIN_NEWS_AMOUNT = 30; ///< preferred minimum amount of news messages
static uint _total_news = 0; ///< current number of news items
-NewsItem *_oldest_news = NULL; ///< head of news items queue
-static NewsItem *_latest_news = NULL; ///< tail of news items queue
+NewsItem *_oldest_news = nullptr; ///< head of news items queue
+static NewsItem *_latest_news = nullptr; ///< tail of news items queue
/**
* Forced news item.
* Users can force an item by accessing the history or "last message".
* If the message being shown was forced by the user, a pointer is stored
- * in _forced_news. Otherwise, \a _forced_news variable is NULL.
+ * in _forced_news. Otherwise, \a _forced_news variable is nullptr.
*/
-static const NewsItem *_forced_news = NULL; ///< item the user has asked for
+static const NewsItem *_forced_news = nullptr; ///< item the user has asked for
/** Current news item (last item shown regularly). */
-static const NewsItem *_current_news = NULL;
+static const NewsItem *_current_news = nullptr;
/**
@@ -93,7 +93,7 @@ static const NWidgetPart _nested_normal_news_widgets[] = {
};
static WindowDesc _normal_news_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_NEWS_WINDOW, WC_NONE,
0,
_nested_normal_news_widgets, lengthof(_nested_normal_news_widgets)
@@ -120,7 +120,7 @@ static const NWidgetPart _nested_vehicle_news_widgets[] = {
};
static WindowDesc _vehicle_news_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_NEWS_WINDOW, WC_NONE,
0,
_nested_vehicle_news_widgets, lengthof(_nested_vehicle_news_widgets)
@@ -148,7 +148,7 @@ static const NWidgetPart _nested_company_news_widgets[] = {
};
static WindowDesc _company_news_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_NEWS_WINDOW, WC_NONE,
0,
_nested_company_news_widgets, lengthof(_nested_company_news_widgets)
@@ -171,7 +171,7 @@ static const NWidgetPart _nested_thin_news_widgets[] = {
};
static WindowDesc _thin_news_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_NEWS_WINDOW, WC_NONE,
0,
_nested_thin_news_widgets, lengthof(_nested_thin_news_widgets)
@@ -195,7 +195,7 @@ static const NWidgetPart _nested_small_news_widgets[] = {
};
static WindowDesc _small_news_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_NEWS_WINDOW, WC_NONE,
0,
_nested_small_news_widgets, lengthof(_nested_small_news_widgets)
@@ -251,8 +251,8 @@ NewsDisplay NewsTypeData::GetDisplay() const
{
uint index;
const SettingDesc *sd = GetSettingFromName(this->name, &index);
- assert(sd != NULL);
- void *ptr = GetVariableAddress(NULL, &sd->save);
+ assert(sd != nullptr);
+ void *ptr = GetVariableAddress(nullptr, &sd->save);
return (NewsDisplay)ReadValue(ptr, sd->save.conv);
}
@@ -269,7 +269,7 @@ struct NewsWindow : Window {
{
NewsWindow::duration = 16650;
const Window *w = FindWindowByClass(WC_SEND_NETWORK_MSG);
- this->chat_height = (w != NULL) ? w->height : 0;
+ this->chat_height = (w != nullptr) ? w->height : 0;
this->status_height = FindWindowById(WC_STATUS_BAR, 0)->height;
this->flags |= WF_DISABLE_VP_SCROLL;
@@ -285,7 +285,7 @@ struct NewsWindow : Window {
/* Initialize viewport if it exists. */
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_N_VIEWPORT);
- if (nvp != NULL) {
+ if (nvp != nullptr) {
nvp->InitializeViewport(this, ni->reftype1 == NR_VEHICLE ? 0x80000000 | ni->ref1 : GetReferenceTile(ni->reftype1, ni->ref1), ZOOM_LVL_NEWS);
if (this->ni->flags & NF_NO_TRANSPARENT) nvp->disp_flags |= ND_NO_TRANSPARENCY;
if ((this->ni->flags & NF_INCOLOUR) == 0) {
@@ -433,7 +433,7 @@ struct NewsWindow : Window {
case WID_N_CLOSEBOX:
NewsWindow::duration = 0;
delete this;
- _forced_news = NULL;
+ _forced_news = nullptr;
break;
case WID_N_CAPTION:
@@ -515,7 +515,7 @@ private:
int mintop = min(newtop, this->top);
int maxtop = max(newtop, this->top);
- if (this->viewport != NULL) this->viewport->top += newtop - this->top;
+ if (this->viewport != nullptr) this->viewport->top += newtop - this->top;
this->top = newtop;
SetDirtyBlocks(this->left, mintop, this->left + this->width, maxtop + this->height);
@@ -572,18 +572,18 @@ static void ShowTicker(const NewsItem *ni)
/** Initialize the news-items data structures */
void InitNewsItemStructs()
{
- for (NewsItem *ni = _oldest_news; ni != NULL; ) {
+ for (NewsItem *ni = _oldest_news; ni != nullptr; ) {
NewsItem *next = ni->next;
delete ni;
ni = next;
}
_total_news = 0;
- _oldest_news = NULL;
- _latest_news = NULL;
- _forced_news = NULL;
- _current_news = NULL;
- _statusbar_news_item = NULL;
+ _oldest_news = nullptr;
+ _latest_news = nullptr;
+ _forced_news = nullptr;
+ _current_news = nullptr;
+ _statusbar_news_item = nullptr;
NewsWindow::duration = 0;
}
@@ -593,15 +593,15 @@ void InitNewsItemStructs()
*/
static bool ReadyForNextItem()
{
- const NewsItem *ni = _forced_news == NULL ? _current_news : _forced_news;
- if (ni == NULL) return true;
+ const NewsItem *ni = _forced_news == nullptr ? _current_news : _forced_news;
+ if (ni == nullptr) return true;
/* Ticker message
* Check if the status bar message is still being displayed? */
if (IsNewsTickerShown()) return false;
/* neither newsticker nor newspaper are running */
- return (NewsWindow::duration <= 0 || FindWindowById(WC_NEWS_WINDOW, 0) == NULL);
+ return (NewsWindow::duration <= 0 || FindWindowById(WC_NEWS_WINDOW, 0) == nullptr);
}
/** Move to the next news item */
@@ -609,12 +609,12 @@ static void MoveToNextItem()
{
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED); // invalidate the statusbar
DeleteWindowById(WC_NEWS_WINDOW, 0); // close the newspapers window if shown
- _forced_news = NULL;
- _statusbar_news_item = NULL;
+ _forced_news = nullptr;
+ _statusbar_news_item = nullptr;
/* if we're not at the last item, then move on */
if (_current_news != _latest_news) {
- _current_news = (_current_news == NULL) ? _oldest_news : _current_news->next;
+ _current_news = (_current_news == nullptr) ? _oldest_news : _current_news->next;
const NewsItem *ni = _current_news;
const NewsType type = ni->type;
@@ -674,16 +674,16 @@ void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceTy
CopyOutDParam(ni->params, 0, lengthof(ni->params));
if (_total_news++ == 0) {
- assert(_oldest_news == NULL);
+ assert(_oldest_news == nullptr);
_oldest_news = ni;
- ni->prev = NULL;
+ ni->prev = nullptr;
} else {
- assert(_latest_news->next == NULL);
+ assert(_latest_news->next == nullptr);
_latest_news->next = ni;
ni->prev = _latest_news;
}
- ni->next = NULL;
+ ni->next = nullptr;
_latest_news = ni;
SetWindowDirty(WC_MESSAGE_HISTORY, 0);
@@ -757,14 +757,14 @@ CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
static void DeleteNewsItem(NewsItem *ni)
{
/* Delete the news from the news queue. */
- if (ni->prev != NULL) {
+ if (ni->prev != nullptr) {
ni->prev->next = ni->next;
} else {
assert(_oldest_news == ni);
_oldest_news = ni->next;
}
- if (ni->next != NULL) {
+ if (ni->next != nullptr) {
ni->next->prev = ni->prev;
} else {
assert(_latest_news == ni);
@@ -798,7 +798,7 @@ void DeleteVehicleNews(VehicleID vid, StringID news)
{
NewsItem *ni = _oldest_news;
- while (ni != NULL) {
+ while (ni != nullptr) {
NewsItem *next = ni->next;
if (((ni->reftype1 == NR_VEHICLE && ni->ref1 == vid) || (ni->reftype2 == NR_VEHICLE && ni->ref2 == vid)) &&
(news == INVALID_STRING_ID || ni->string_id == news)) {
@@ -817,7 +817,7 @@ void DeleteStationNews(StationID sid)
{
NewsItem *ni = _oldest_news;
- while (ni != NULL) {
+ while (ni != nullptr) {
NewsItem *next = ni->next;
if ((ni->reftype1 == NR_STATION && ni->ref1 == sid) || (ni->reftype2 == NR_STATION && ni->ref2 == sid)) {
DeleteNewsItem(ni);
@@ -834,7 +834,7 @@ void DeleteIndustryNews(IndustryID iid)
{
NewsItem *ni = _oldest_news;
- while (ni != NULL) {
+ while (ni != nullptr) {
NewsItem *next = ni->next;
if ((ni->reftype1 == NR_INDUSTRY && ni->ref1 == iid) || (ni->reftype2 == NR_INDUSTRY && ni->ref2 == iid)) {
DeleteNewsItem(ni);
@@ -850,7 +850,7 @@ void DeleteInvalidEngineNews()
{
NewsItem *ni = _oldest_news;
- while (ni != NULL) {
+ while (ni != nullptr) {
NewsItem *next = ni->next;
if ((ni->reftype1 == NR_ENGINE && (!Engine::IsValidID(ni->ref1) || !Engine::Get(ni->ref1)->IsEnabled())) ||
(ni->reftype2 == NR_ENGINE && (!Engine::IsValidID(ni->ref2) || !Engine::Get(ni->ref2)->IsEnabled()))) {
@@ -863,7 +863,7 @@ void DeleteInvalidEngineNews()
static void RemoveOldNewsItems()
{
NewsItem *next;
- for (NewsItem *cur = _oldest_news; _total_news > MIN_NEWS_AMOUNT && cur != NULL; cur = next) {
+ for (NewsItem *cur = _oldest_news; _total_news > MIN_NEWS_AMOUNT && cur != nullptr; cur = next) {
next = cur->next;
if (_date - _news_type_data[cur->type].age * _settings_client.gui.news_message_timeout > cur->date) DeleteNewsItem(cur);
}
@@ -877,7 +877,7 @@ static void RemoveOldNewsItems()
*/
void ChangeVehicleNews(VehicleID from_index, VehicleID to_index)
{
- for (NewsItem *ni = _oldest_news; ni != NULL; ni = ni->next) {
+ for (NewsItem *ni = _oldest_news; ni != nullptr; ni = ni->next) {
if (ni->reftype1 == NR_VEHICLE && ni->ref1 == from_index) ni->ref1 = to_index;
if (ni->reftype2 == NR_VEHICLE && ni->ref2 == from_index) ni->ref2 = to_index;
if (ni->flags & NF_VEHICLE_PARAM0 && ni->params[0] == from_index) ni->params[0] = to_index;
@@ -892,7 +892,7 @@ void NewsLoop()
/* There is no status bar, so no reason to show news;
* especially important with the end game screen when
* there is no status bar but possible news. */
- if (FindWindowById(WC_STATUS_BAR, 0) == NULL) return;
+ if (FindWindowById(WC_STATUS_BAR, 0) == nullptr) return;
static byte _last_clean_month = 0;
@@ -915,7 +915,7 @@ static void ShowNewsMessage(const NewsItem *ni)
/* setup forced news item */
_forced_news = ni;
- if (_forced_news != NULL) {
+ if (_forced_news != nullptr) {
DeleteWindowById(WC_NEWS_WINDOW, 0);
ShowNewspaper(ni);
}
@@ -924,19 +924,19 @@ static void ShowNewsMessage(const NewsItem *ni)
/** Show previous news item */
void ShowLastNewsMessage()
{
- const NewsItem *ni = NULL;
+ const NewsItem *ni = nullptr;
if (_total_news == 0) {
return;
- } else if (_forced_news == NULL) {
+ } else if (_forced_news == nullptr) {
/* Not forced any news yet, show the current one, unless a news window is
* open (which can only be the current one), then show the previous item */
- if (_current_news == NULL) {
+ if (_current_news == nullptr) {
/* No news were shown yet resp. the last shown one was already deleted.
* Threat this as if _forced_news reached _oldest_news; so, wrap around and start anew with the latest. */
ni = _latest_news;
} else {
const Window *w = FindWindowById(WC_NEWS_WINDOW, 0);
- ni = (w == NULL || (_current_news == _oldest_news)) ? _current_news : _current_news->prev;
+ ni = (w == nullptr || (_current_news == _oldest_news)) ? _current_news : _current_news->prev;
}
} else if (_forced_news == _oldest_news) {
/* We have reached the oldest news, start anew with the latest */
@@ -953,7 +953,7 @@ void ShowLastNewsMessage()
}
ni = ni->prev;
- if (ni == NULL) {
+ if (ni == nullptr) {
if (wrap) break;
/* We have reached the oldest news, start anew with the latest */
ni = _latest_news;
@@ -1054,7 +1054,7 @@ struct MessageHistoryWindow : Window {
NewsItem *ni = _latest_news;
for (int n = this->vscroll->GetPosition(); n > 0; n--) {
ni = ni->prev;
- if (ni == NULL) return;
+ if (ni == nullptr) return;
}
/* Fill the widget with news items. */
@@ -1072,7 +1072,7 @@ struct MessageHistoryWindow : Window {
y += this->line_height;
ni = ni->prev;
- if (ni == NULL) return;
+ if (ni == nullptr) return;
}
}
@@ -1091,11 +1091,11 @@ struct MessageHistoryWindow : Window {
{
if (widget == WID_MH_BACKGROUND) {
NewsItem *ni = _latest_news;
- if (ni == NULL) return;
+ if (ni == nullptr) return;
for (int n = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_MH_BACKGROUND, WD_FRAMERECT_TOP, this->line_height); n > 0; n--) {
ni = ni->prev;
- if (ni == NULL) return;
+ if (ni == nullptr) return;
}
ShowNewsMessage(ni);
diff --git a/src/news_type.h b/src/news_type.h
index cad15ecbe..e91b4be3a 100644
--- a/src/news_type.h
+++ b/src/news_type.h
@@ -155,7 +155,7 @@ struct CompanyNewsInformation {
uint32 face; ///< The face of the president
byte colour; ///< The colour related to the company
- void FillData(const struct Company *c, const struct Company *other = NULL);
+ void FillData(const struct Company *c, const struct Company *other = nullptr);
};
#endif /* NEWS_TYPE_H */
diff --git a/src/object.h b/src/object.h
index 0ab92d376..7375aad15 100644
--- a/src/object.h
+++ b/src/object.h
@@ -18,7 +18,7 @@
void UpdateCompanyHQ(TileIndex tile, uint score);
-void BuildObject(ObjectType type, TileIndex tile, CompanyID owner = OWNER_NONE, struct Town *town = NULL, uint8 view = 0);
+void BuildObject(ObjectType type, TileIndex tile, CompanyID owner = OWNER_NONE, struct Town *town = nullptr, uint8 view = 0);
void ShowBuildObjectPicker();
diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp
index a57aa57f0..c6cee00a5 100644
--- a/src/object_cmd.cpp
+++ b/src/object_cmd.cpp
@@ -90,7 +90,7 @@ void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, u
Object *o = new Object();
o->type = type;
o->location = ta;
- o->town = town == NULL ? CalcClosestTownFromTile(tile) : town;
+ o->town = town == nullptr ? CalcClosestTownFromTile(tile) : town;
o->build_date = _date;
o->view = view;
@@ -114,7 +114,7 @@ void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, u
}
}
- assert(o->town != NULL);
+ assert(o->town != nullptr);
TILE_AREA_LOOP(t, ta) {
WaterClass wc = (IsWaterTile(t) ? GetWaterClass(t) : WATER_CLASS_INVALID);
@@ -263,7 +263,7 @@ CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
uint16 callback = CALLBACK_FAILED;
if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
TileIndex diff = t - tile;
- callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, NULL, t, view);
+ callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t), TileY(diff) << 4 | TileX(diff), spec, nullptr, t, view);
}
if (callback == CALLBACK_FAILED) {
@@ -342,7 +342,7 @@ CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
}
if (flags & DC_EXEC) {
- BuildObject(type, tile, _current_company, NULL, view);
+ BuildObject(type, tile, _current_company, nullptr, view);
/* Make sure the HQ starts at the right size. */
if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
@@ -366,7 +366,7 @@ static void DrawTile_Object(TileInfo *ti)
if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
if (type < NEW_OBJECT_OFFSET) {
- const DrawTileSprites *dts = NULL;
+ const DrawTileSprites *dts = nullptr;
Owner to = GetTileOwner(ti->tile);
PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
@@ -447,7 +447,7 @@ std::vector<ClearedObjectArea> _cleared_object_areas;
/**
* Find the entry in _cleared_object_areas which occupies a certain tile.
* @param tile Tile of interest
- * @return Occupying entry, or NULL if none
+ * @return Occupying entry, or nullptr if none
*/
ClearedObjectArea *FindClearedObject(TileIndex tile)
{
@@ -457,7 +457,7 @@ ClearedObjectArea *FindClearedObject(TileIndex tile)
if (coa.area.Intersects(ta)) return &coa;
}
- return NULL;
+ return nullptr;
}
static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
@@ -567,7 +567,7 @@ static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
td->owner[0] = GetTileOwner(tile);
td->build_date = Object::GetByTile(tile)->build_date;
- if (spec->grf_prop.grffile != NULL) {
+ if (spec->grf_prop.grffile != nullptr) {
td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
}
}
@@ -694,7 +694,7 @@ static bool TryBuildTransmitter()
int h;
if (IsTileType(tile, MP_CLEAR) && IsTileFlat(tile, &h) && h >= 4 && !IsBridgeAbove(tile)) {
TileIndex t = tile;
- if (CircularTileSearch(&t, 9, HasTransmitter, NULL)) return false;
+ if (CircularTileSearch(&t, 9, HasTransmitter, nullptr)) return false;
BuildObject(OBJECT_TRANSMITTER, tile);
return true;
@@ -754,7 +754,7 @@ void GenerateObjects()
default:
uint8 view = RandomRange(spec->views);
- if (CmdBuildObject(RandomTile(), DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, i, view, NULL).Succeeded()) amount--;
+ if (CmdBuildObject(RandomTile(), DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, i, view, nullptr).Succeeded()) amount--;
break;
}
}
@@ -840,8 +840,8 @@ extern const TileTypeProcs _tile_type_object_procs = {
AnimateTile_Object, // animate_tile_proc
TileLoop_Object, // tile_loop_proc
ChangeTileOwner_Object, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
- NULL, // vehicle_enter_tile_proc
+ nullptr, // add_produced_cargo_proc
+ nullptr, // vehicle_enter_tile_proc
GetFoundation_Object, // get_foundation_proc
TerraformTile_Object, // terraform_tile_proc
};
diff --git a/src/object_gui.cpp b/src/object_gui.cpp
index 6684566f1..a84be26e6 100644
--- a/src/object_gui.cpp
+++ b/src/object_gui.cpp
@@ -104,13 +104,13 @@ public:
switch (widget) {
case WID_BO_OBJECT_NAME: {
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- SetDParam(0, spec != NULL ? spec->name : STR_EMPTY);
+ SetDParam(0, spec != nullptr ? spec->name : STR_EMPTY);
break;
}
case WID_BO_OBJECT_SIZE: {
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- int size = spec == NULL ? 0 : spec->size;
+ int size = spec == nullptr ? 0 : spec->size;
SetDParam(0, GB(size, HasBit(_selected_object_view, 0) ? 4 : 0, 4));
SetDParam(1, GB(size, HasBit(_selected_object_view, 0) ? 0 : 4, 4));
break;
@@ -145,7 +145,7 @@ public:
case WID_BO_OBJECT_MATRIX: {
/* Get the right amount of buttons based on the current spec. */
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- if (spec != NULL) {
+ if (spec != nullptr) {
if (spec->views >= 2) size->width += resize->width;
if (spec->views >= 4) size->height += resize->height;
}
@@ -185,7 +185,7 @@ public:
/* Get the right size for the single widget based on the current spec. */
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- if (spec != NULL) {
+ if (spec != nullptr) {
if (spec->views >= 2) size->width = size->width / 2 - 1;
if (spec->views >= 4) size->height = size->height / 2 - 1;
}
@@ -229,7 +229,7 @@ public:
case WID_BO_OBJECT_SPRITE: {
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- if (spec == NULL) break;
+ if (spec == nullptr) break;
/* Height of the selection matrix.
* Depending on the number of views, the matrix has a 1x1, 1x2, 2x1 or 2x2 layout. To make the previews
@@ -243,7 +243,7 @@ public:
if (FillDrawPixelInfo(&tmp_dpi, r.left, r.top, r.right - r.left + 1, r.bottom - r.top + 1)) {
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
- if (spec->grf_prop.grffile == NULL) {
+ if (spec->grf_prop.grffile == nullptr) {
extern const DrawTileSprites _objects[];
const DrawTileSprites *dts = &_objects[spec->grf_prop.local_id];
DrawOrigTileSeqInGUI((r.right - r.left) / 2 - 1, (r.bottom - r.top + matrix_height / 2) / 2 - OBJECT_MARGIN - ScaleGUITrad(TILE_PIXELS), dts, PAL_NONE);
@@ -260,7 +260,7 @@ public:
int obj_index = objclass->GetIndexFromUI(GB(widget, 16, 16));
if (obj_index < 0) break;
const ObjectSpec *spec = objclass->GetSpec(obj_index);
- if (spec == NULL) break;
+ if (spec == nullptr) break;
if (!spec->IsAvailable()) {
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, PC_BLACK, FILLRECT_CHECKER);
@@ -270,7 +270,7 @@ public:
if (FillDrawPixelInfo(&tmp_dpi, r.left + 1, r.top, (r.right - 1) - (r.left + 1) + 1, r.bottom - r.top + 1)) {
DrawPixelInfo *old_dpi = _cur_dpi;
_cur_dpi = &tmp_dpi;
- if (spec->grf_prop.grffile == NULL) {
+ if (spec->grf_prop.grffile == nullptr) {
extern const DrawTileSprites _objects[];
const DrawTileSprites *dts = &_objects[spec->grf_prop.local_id];
DrawOrigTileSeqInGUI((r.right - r.left) / 2 - 1, r.bottom - r.top - OBJECT_MARGIN - ScaleGUITrad(TILE_PIXELS), dts, PAL_NONE);
@@ -285,11 +285,11 @@ public:
case WID_BO_INFO: {
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- if (spec == NULL) break;
+ if (spec == nullptr) break;
/* Get the extra message for the GUI */
if (HasBit(spec->callback_mask, CBM_OBJ_FUND_MORE_TEXT)) {
- uint16 callback_res = GetObjectCallback(CBID_OBJECT_FUND_MORE_TEXT, 0, 0, spec, NULL, INVALID_TILE, _selected_object_view);
+ uint16 callback_res = GetObjectCallback(CBID_OBJECT_FUND_MORE_TEXT, 0, 0, spec, nullptr, INVALID_TILE, _selected_object_view);
if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
if (callback_res > 0x400) {
ErrorUnknownCallbackResult(spec->grf_prop.grffile->grfid, CBID_OBJECT_FUND_MORE_TEXT, callback_res);
diff --git a/src/openttd.cpp b/src/openttd.cpp
index d4ce37b06..4f629c118 100644
--- a/src/openttd.cpp
+++ b/src/openttd.cpp
@@ -99,7 +99,7 @@ void CDECL usererror(const char *s, ...)
va_end(va);
ShowOSErrorBox(buf, false);
- if (VideoDriver::GetInstance() != NULL) VideoDriver::GetInstance()->Stop();
+ if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
exit(1);
}
@@ -118,7 +118,7 @@ void CDECL error(const char *s, ...)
vseprintf(buf, lastof(buf), s, va);
va_end(va);
- if (VideoDriver::GetInstance() == NULL || VideoDriver::GetInstance()->HasGUI()) {
+ if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
ShowOSErrorBox(buf, true);
}
@@ -242,7 +242,7 @@ static void WriteSavegameInfo(const char *name)
p = strecpy(p, "NewGRFs:\n", lastof(buf));
if (_load_check_data.HasNewGrfs()) {
- for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
char md5sum[33];
md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
@@ -268,13 +268,13 @@ static void WriteSavegameInfo(const char *name)
static void ParseResolution(Dimension *res, const char *s)
{
const char *t = strchr(s, 'x');
- if (t == NULL) {
+ if (t == nullptr) {
ShowInfoF("Invalid resolution '%s'", s);
return;
}
- res->width = max(strtoul(s, NULL, 0), 64UL);
- res->height = max(strtoul(t + 1, NULL, 0), 64UL);
+ res->width = max(strtoul(s, nullptr, 0), 64UL);
+ res->height = max(strtoul(t + 1, nullptr, 0), 64UL);
}
@@ -347,11 +347,11 @@ static void LoadIntroGame(bool load_newgrfs = true)
void MakeNewgameSettingsLive()
{
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
- if (_settings_game.ai_config[c] != NULL) {
+ if (_settings_game.ai_config[c] != nullptr) {
delete _settings_game.ai_config[c];
}
}
- if (_settings_game.game_config != NULL) {
+ if (_settings_game.game_config != nullptr) {
delete _settings_game.game_config;
}
@@ -361,16 +361,16 @@ void MakeNewgameSettingsLive()
_old_vds = _settings_client.company.vehicle;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
- _settings_game.ai_config[c] = NULL;
- if (_settings_newgame.ai_config[c] != NULL) {
+ _settings_game.ai_config[c] = nullptr;
+ if (_settings_newgame.ai_config[c] != nullptr) {
_settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
if (!AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->HasScript()) {
- AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(NULL);
+ AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(nullptr);
}
}
}
- _settings_game.game_config = NULL;
- if (_settings_newgame.game_config != NULL) {
+ _settings_game.game_config = nullptr;
+ if (_settings_newgame.game_config != nullptr) {
_settings_game.game_config = new GameConfig(_settings_newgame.game_config);
}
}
@@ -390,7 +390,7 @@ struct AfterNewGRFScan : NewGRFScanCallback {
uint32 generation_seed; ///< Seed for the new game.
char *dedicated_host; ///< Hostname for the dedicated server.
uint16 dedicated_port; ///< Port for the dedicated server.
- char *network_conn; ///< Information about the server to connect to, or NULL.
+ char *network_conn; ///< Information about the server to connect to, or nullptr.
const char *join_server_password; ///< The password to join the server with.
const char *join_company_password; ///< The password to join the company with.
bool *save_config_ptr; ///< The pointer to the save config setting.
@@ -403,8 +403,8 @@ struct AfterNewGRFScan : NewGRFScanCallback {
*/
AfterNewGRFScan(bool *save_config_ptr) :
startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
- dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
- join_server_password(NULL), join_company_password(NULL),
+ dedicated_host(nullptr), dedicated_port(0), network_conn(nullptr),
+ join_server_password(nullptr), join_company_password(nullptr),
save_config_ptr(save_config_ptr), save_config(true)
{
/* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
@@ -444,7 +444,7 @@ struct AfterNewGRFScan : NewGRFScanCallback {
if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
- if (dedicated_host != NULL) {
+ if (dedicated_host != nullptr) {
_network_bind_list.clear();
_network_bind_list.emplace_back(dedicated_host);
}
@@ -458,15 +458,15 @@ struct AfterNewGRFScan : NewGRFScanCallback {
/* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
- if (_network_available && network_conn != NULL) {
- const char *port = NULL;
- const char *company = NULL;
+ if (_network_available && network_conn != nullptr) {
+ const char *port = nullptr;
+ const char *company = nullptr;
uint16 rport = NETWORK_DEFAULT_PORT;
CompanyID join_as = COMPANY_NEW_COMPANY;
ParseConnectionString(&company, &port, network_conn);
- if (company != NULL) {
+ if (company != nullptr) {
join_as = (CompanyID)atoi(company);
if (join_as != COMPANY_SPECTATOR) {
@@ -477,7 +477,7 @@ struct AfterNewGRFScan : NewGRFScanCallback {
}
}
}
- if (port != NULL) rport = atoi(port);
+ if (port != nullptr) rport = atoi(port);
LoadIntroGame();
_switch_mode = SM_NONE;
@@ -531,19 +531,19 @@ static const OptionData _options[] = {
*/
int openttd_main(int argc, char *argv[])
{
- char *musicdriver = NULL;
- char *sounddriver = NULL;
- char *videodriver = NULL;
- char *blitter = NULL;
- char *graphics_set = NULL;
- char *sounds_set = NULL;
- char *music_set = NULL;
+ char *musicdriver = nullptr;
+ char *sounddriver = nullptr;
+ char *videodriver = nullptr;
+ char *blitter = nullptr;
+ char *graphics_set = nullptr;
+ char *sounds_set = nullptr;
+ char *music_set = nullptr;
Dimension resolution = {0, 0};
/* AfterNewGRFScan sets save_config to true after scanning completed. */
bool save_config = false;
AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
bool dedicated = false;
- char *debuglog_conn = NULL;
+ char *debuglog_conn = nullptr;
extern bool _dedicated_forks;
_dedicated_forks = false;
@@ -553,7 +553,7 @@ int openttd_main(int argc, char *argv[])
_game_mode = GM_MENU;
_switch_mode = SM_MENU;
- _config_file = NULL;
+ _config_file = nullptr;
GetOptData mgo(argc - 1, argv + 1, _options);
int ret = 0;
@@ -579,19 +579,19 @@ int openttd_main(int argc, char *argv[])
blitter = stredup("null");
dedicated = true;
SetDebugString("net=6");
- if (mgo.opt != NULL) {
+ if (mgo.opt != nullptr) {
/* Use the existing method for parsing (openttd -n).
* However, we do ignore the #company part. */
- const char *temp = NULL;
- const char *port = NULL;
+ const char *temp = nullptr;
+ const char *port = nullptr;
ParseConnectionString(&temp, &port, mgo.opt);
if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
- if (port != NULL) scanner->dedicated_port = atoi(port);
+ if (port != nullptr) scanner->dedicated_port = atoi(port);
}
break;
case 'f': _dedicated_forks = true; break;
case 'n':
- scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
+ scanner->network_conn = mgo.opt; // optional IP parameter, nullptr if unset
break;
case 'l':
debuglog_conn = mgo.opt;
@@ -608,12 +608,12 @@ int openttd_main(int argc, char *argv[])
#if defined(_WIN32)
CreateConsole();
#endif
- if (mgo.opt != NULL) SetDebugString(mgo.opt);
+ if (mgo.opt != nullptr) SetDebugString(mgo.opt);
break;
}
case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
case 'g':
- if (mgo.opt != NULL) {
+ if (mgo.opt != nullptr) {
_file_to_saveload.SetName(mgo.opt);
bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
_switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
@@ -621,8 +621,8 @@ int openttd_main(int argc, char *argv[])
/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
const char *t = strrchr(_file_to_saveload.name, '.');
- if (t != NULL) {
- FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, NULL, NULL);
+ if (t != nullptr) {
+ FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, nullptr, nullptr);
if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
}
@@ -663,7 +663,7 @@ int openttd_main(int argc, char *argv[])
goto exit_noshutdown;
}
- case 'G': scanner->generation_seed = strtoul(mgo.opt, NULL, 10); break;
+ case 'G': scanner->generation_seed = strtoul(mgo.opt, nullptr, 10); break;
case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
case 'x': scanner->save_config = false; break;
case 'h':
@@ -729,10 +729,10 @@ int openttd_main(int argc, char *argv[])
InitWindowSystem();
BaseGraphics::FindSets();
- if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = stredup(BaseGraphics::ini_set);
+ if (graphics_set == nullptr && BaseGraphics::ini_set != nullptr) graphics_set = stredup(BaseGraphics::ini_set);
if (!BaseGraphics::SetSet(graphics_set)) {
if (!StrEmpty(graphics_set)) {
- BaseGraphics::SetSet(NULL);
+ BaseGraphics::SetSet(nullptr);
ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
msg.SetDParamStr(0, graphics_set);
@@ -745,7 +745,7 @@ int openttd_main(int argc, char *argv[])
GfxInitPalettes();
DEBUG(misc, 1, "Loading blitter...");
- if (blitter == NULL && _ini_blitter != NULL) blitter = stredup(_ini_blitter);
+ if (blitter == nullptr && _ini_blitter != nullptr) blitter = stredup(_ini_blitter);
_blitter_autodetected = StrEmpty(blitter);
/* Activate the initial blitter.
* This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
@@ -754,9 +754,9 @@ int openttd_main(int argc, char *argv[])
* - Use 8bpp blitter otherwise.
*/
if (!_blitter_autodetected ||
- (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
- BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
- if (BlitterFactory::SelectBlitter(blitter) == NULL) {
+ (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
+ BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
+ if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
StrEmpty(blitter) ?
usererror("Failed to autoprobe blitter") :
usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
@@ -764,7 +764,7 @@ int openttd_main(int argc, char *argv[])
}
free(blitter);
- if (videodriver == NULL && _ini_videodriver != NULL) videodriver = stredup(_ini_videodriver);
+ if (videodriver == nullptr && _ini_videodriver != nullptr) videodriver = stredup(_ini_videodriver);
DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
free(videodriver);
@@ -775,15 +775,15 @@ int openttd_main(int argc, char *argv[])
NetworkStartUp(); // initialize network-core
- if (debuglog_conn != NULL && _network_available) {
- const char *not_used = NULL;
- const char *port = NULL;
+ if (debuglog_conn != nullptr && _network_available) {
+ const char *not_used = nullptr;
+ const char *port = nullptr;
uint16 rport;
rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
ParseConnectionString(&not_used, &port, debuglog_conn);
- if (port != NULL) rport = atoi(port);
+ if (port != nullptr) rport = atoi(port);
NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
}
@@ -800,9 +800,9 @@ int openttd_main(int argc, char *argv[])
InitializeScreenshotFormats();
BaseSounds::FindSets();
- if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = stredup(BaseSounds::ini_set);
+ if (sounds_set == nullptr && BaseSounds::ini_set != nullptr) sounds_set = stredup(BaseSounds::ini_set);
if (!BaseSounds::SetSet(sounds_set)) {
- if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
+ if (StrEmpty(sounds_set) || !BaseSounds::SetSet(nullptr)) {
usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of README.md.");
} else {
ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
@@ -813,9 +813,9 @@ int openttd_main(int argc, char *argv[])
free(sounds_set);
BaseMusic::FindSets();
- if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = stredup(BaseMusic::ini_set);
+ if (music_set == nullptr && BaseMusic::ini_set != nullptr) music_set = stredup(BaseMusic::ini_set);
if (!BaseMusic::SetSet(music_set)) {
- if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
+ if (StrEmpty(music_set) || !BaseMusic::SetSet(nullptr)) {
usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of README.md.");
} else {
ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
@@ -825,11 +825,11 @@ int openttd_main(int argc, char *argv[])
}
free(music_set);
- if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = stredup(_ini_sounddriver);
+ if (sounddriver == nullptr && _ini_sounddriver != nullptr) sounddriver = stredup(_ini_sounddriver);
DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
free(sounddriver);
- if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = stredup(_ini_musicdriver);
+ if (musicdriver == nullptr && _ini_musicdriver != nullptr) musicdriver = stredup(_ini_musicdriver);
DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
free(musicdriver);
@@ -852,7 +852,7 @@ int openttd_main(int argc, char *argv[])
/* ScanNewGRFFiles now has control over the scanner. */
ScanNewGRFFiles(scanner);
- scanner = NULL;
+ scanner = nullptr;
VideoDriver::GetInstance()->MainLoop();
@@ -897,7 +897,7 @@ exit_normal:
delete scanner;
extern FILE *_log_fd;
- if (_log_fd != NULL) {
+ if (_log_fd != nullptr) {
fclose(_log_fd);
}
@@ -994,17 +994,17 @@ static void MakeNewEditorWorld()
* @param fop mode of loading, always SLO_LOAD
* @param newgm switch to this mode of loading fails due to some unknown error
* @param subdir default directory to look for filename, set to 0 if not needed
- * @param lf Load filter to use, if NULL: use filename + subdir.
+ * @param lf Load filter to use, if nullptr: use filename + subdir.
*/
-bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
+bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
{
assert(fop == SLO_LOAD);
- assert(dft == DFT_GAME_FILE || (lf == NULL && dft == DFT_OLD_GAME_FILE));
+ assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
GameMode ogm = _game_mode;
_game_mode = newgm;
- switch (lf == NULL ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
+ switch (lf == nullptr ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
case SL_OK: return true;
case SL_REINIT:
@@ -1139,7 +1139,7 @@ void SwitchToMode(SwitchMode new_mode)
case SM_MENU: // Switch to game intro menu
LoadIntroGame();
- if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
+ if (BaseSounds::ini_set == nullptr && BaseSounds::GetUsedSet()->fallback) {
ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
BaseSounds::ini_set = stredup(BaseSounds::GetUsedSet()->name);
}
@@ -1235,7 +1235,7 @@ static void CheckCaches()
if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
uint length = 0;
- for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) length++;
NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
VehicleCache *veh_cache = CallocT<VehicleCache>(length);
@@ -1243,7 +1243,7 @@ static void CheckCaches()
TrainCache *tra_cache = CallocT<TrainCache>(length);
length = 0;
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
FillNewGRFVehicleCache(u);
grf_cache[length] = u->grf_cache;
veh_cache[length] = u->vcache;
@@ -1270,7 +1270,7 @@ static void CheckCaches()
}
length = 0;
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
FillNewGRFVehicleCache(u);
if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
DEBUG(desync, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
diff --git a/src/order_backup.cpp b/src/order_backup.cpp
index 38c4c8e67..4f8b13fa0 100644
--- a/src/order_backup.cpp
+++ b/src/order_backup.cpp
@@ -30,7 +30,7 @@ OrderBackup::~OrderBackup()
if (CleaningPool()) return;
Order *o = this->orders;
- while (o != NULL) {
+ while (o != nullptr) {
Order *next = o->next;
delete o;
o = next;
@@ -75,11 +75,11 @@ OrderBackup::OrderBackup(const Vehicle *v, uint32 user)
void OrderBackup::DoRestore(Vehicle *v)
{
/* If we had shared orders, recover that */
- if (this->clone != NULL) {
+ if (this->clone != nullptr) {
DoCommand(0, v->index | CO_SHARE << 30, this->clone->index, DC_EXEC, CMD_CLONE_ORDER);
- } else if (this->orders != NULL && OrderList::CanAllocateItem()) {
+ } else if (this->orders != nullptr && OrderList::CanAllocateItem()) {
v->orders.list = new OrderList(this->orders, v);
- this->orders = NULL;
+ this->orders = nullptr;
/* Make sure buoys/oil rigs are updated in the station list. */
InvalidateWindowClassesData(WC_STATION_LIST, 0);
}
@@ -206,7 +206,7 @@ CommandCost CmdClearOrderBackup(TileIndex tile, DoCommandFlag flags, uint32 p1,
/* We need to circumvent the "prevention" from this command being executed
* while the game is paused, so use the internal method. Nor do we want
* this command to get its cost estimated when shift is pressed. */
- DoCommandPInternal(ob->tile, 0, user, CMD_CLEAR_ORDER_BACKUP, NULL, NULL, true, false);
+ DoCommandPInternal(ob->tile, 0, user, CMD_CLEAR_ORDER_BACKUP, nullptr, nullptr, true, false);
} else {
/* The command came from the game logic, i.e. the clearing of a tile.
* In that case we have no need to actually sync this, just do it. */
@@ -230,20 +230,20 @@ CommandCost CmdClearOrderBackup(TileIndex tile, DoCommandFlag flags, uint32 p1,
/**
* Clear/update the (clone) vehicle from an order backup.
* @param v The vehicle to clear.
- * @pre v != NULL
+ * @pre v != nullptr
* @note If it is not possible to set another vehicle as clone
* "example", then this backed up order will be removed.
*/
/* static */ void OrderBackup::ClearVehicle(const Vehicle *v)
{
- assert(v != NULL);
+ assert(v != nullptr);
OrderBackup *ob;
FOR_ALL_ORDER_BACKUPS(ob) {
if (ob->clone == v) {
/* Get another item in the shared list. */
ob->clone = (v->FirstShared() == v) ? v->NextShared() : v->FirstShared();
/* But if that isn't there, remove it. */
- if (ob->clone == NULL) delete ob;
+ if (ob->clone == nullptr) delete ob;
}
}
}
@@ -260,7 +260,7 @@ CommandCost CmdClearOrderBackup(TileIndex tile, DoCommandFlag flags, uint32 p1,
{
OrderBackup *ob;
FOR_ALL_ORDER_BACKUPS(ob) {
- for (Order *order = ob->orders; order != NULL; order = order->next) {
+ for (Order *order = ob->orders; order != nullptr; order = order->next) {
OrderType ot = order->GetType();
if (ot == OT_GOTO_DEPOT && (order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) != 0) continue;
if (ot == OT_GOTO_DEPOT && hangar && !IsHangarTile(ob->tile)) continue; // Not an aircraft? Can't have a hangar order.
diff --git a/src/order_base.h b/src/order_base.h
index b11c20d8e..5164a4d6e 100644
--- a/src/order_base.h
+++ b/src/order_base.h
@@ -48,7 +48,7 @@ private:
uint16 max_speed; ///< How fast the vehicle may go on the way to the destination.
public:
- Order *next; ///< Pointer to next order. If NULL, end of list
+ Order *next; ///< Pointer to next order. If nullptr, end of list
Order() : flags(0), refit_cargo(CT_NO_REFIT), max_speed(UINT16_MAX) {}
~Order();
@@ -268,7 +268,7 @@ private:
public:
/** Default constructor producing an invalid order list. */
OrderList(VehicleOrderID num_orders = INVALID_VEH_ORDER_ID)
- : first(NULL), num_orders(num_orders), num_manual_orders(0), num_vehicles(0), first_shared(NULL),
+ : first(nullptr), num_orders(num_orders), num_manual_orders(0), num_vehicles(0), first_shared(nullptr),
timetable_duration(0), total_duration(0) { }
/**
@@ -303,7 +303,7 @@ public:
* @param curr Order to find the next one for.
* @return Next order.
*/
- inline const Order *GetNext(const Order *curr) const { return (curr->next == NULL) ? this->GetFirstOrder() : curr->next; }
+ inline const Order *GetNext(const Order *curr) const { return (curr->next == nullptr) ? this->GetFirstOrder() : curr->next; }
/**
* Get number of orders in the order list.
@@ -317,7 +317,7 @@ public:
*/
inline VehicleOrderID GetNumManualOrders() const { return this->num_manual_orders; }
- StationIDStack GetNextStoppingStation(const Vehicle *v, const Order *first = NULL, uint hops = 0) const;
+ StationIDStack GetNextStoppingStation(const Vehicle *v, const Order *first = nullptr, uint hops = 0) const;
const Order *GetNextDecisionNode(const Order *next, uint hops) const;
void InsertOrderAt(Order *new_order, int index);
@@ -396,7 +396,7 @@ public:
#define FOR_ALL_ORDERS(var) FOR_ALL_ORDERS_FROM(var, 0)
-#define FOR_VEHICLE_ORDERS(v, order) for (order = (v->orders.list == NULL) ? NULL : v->orders.list->GetFirstOrder(); order != NULL; order = order->next)
+#define FOR_VEHICLE_ORDERS(v, order) for (order = (v->orders.list == nullptr) ? nullptr : v->orders.list->GetFirstOrder(); order != nullptr; order = order->next)
#define FOR_ALL_ORDER_LISTS_FROM(var, start) FOR_ALL_ITEMS_FROM(OrderList, orderlist_index, var, start)
diff --git a/src/order_cmd.cpp b/src/order_cmd.cpp
index 2bfe5d29b..1a9d648c6 100644
--- a/src/order_cmd.cpp
+++ b/src/order_cmd.cpp
@@ -53,7 +53,7 @@ Order::~Order()
* the list of stations. So, we need to invalidate that window if needed. */
if (this->IsType(OT_GOTO_STATION) || this->IsType(OT_GOTO_WAYPOINT)) {
BaseStation *bs = BaseStation::GetIfValid(this->GetDestination());
- if (bs != NULL && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
+ if (bs != nullptr && bs->owner == OWNER_NONE) InvalidateWindowClassesData(WC_STATION_LIST, 0);
}
}
@@ -66,7 +66,7 @@ void Order::Free()
this->type = OT_NOTHING;
this->flags = 0;
this->dest = 0;
- this->next = NULL;
+ this->next = nullptr;
}
/**
@@ -237,7 +237,7 @@ Order::Order(uint32 packed)
this->type = (OrderType)GB(packed, 0, 8);
this->flags = GB(packed, 8, 8);
this->dest = GB(packed, 16, 16);
- this->next = NULL;
+ this->next = nullptr;
this->refit_cargo = CT_NO_REFIT;
this->wait_time = 0;
this->travel_time = 0;
@@ -300,19 +300,19 @@ void OrderList::Initialize(Order *chain, Vehicle *v)
this->timetable_duration = 0;
this->total_duration = 0;
- for (Order *o = this->first; o != NULL; o = o->next) {
+ for (Order *o = this->first; o != nullptr; o = o->next) {
++this->num_orders;
if (!o->IsType(OT_IMPLICIT)) ++this->num_manual_orders;
this->timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
this->total_duration += o->GetWaitTime() + o->GetTravelTime();
}
- for (Vehicle *u = this->first_shared->PreviousShared(); u != NULL; u = u->PreviousShared()) {
+ for (Vehicle *u = this->first_shared->PreviousShared(); u != nullptr; u = u->PreviousShared()) {
++this->num_vehicles;
this->first_shared = u;
}
- for (const Vehicle *u = v->NextShared(); u != NULL; u = u->NextShared()) ++this->num_vehicles;
+ for (const Vehicle *u = v->NextShared(); u != nullptr; u = u->NextShared()) ++this->num_vehicles;
}
/**
@@ -323,13 +323,13 @@ void OrderList::Initialize(Order *chain, Vehicle *v)
void OrderList::FreeChain(bool keep_orderlist)
{
Order *next;
- for (Order *o = this->first; o != NULL; o = next) {
+ for (Order *o = this->first; o != nullptr; o = next) {
next = o->next;
delete o;
}
if (keep_orderlist) {
- this->first = NULL;
+ this->first = nullptr;
this->num_orders = 0;
this->num_manual_orders = 0;
this->timetable_duration = 0;
@@ -345,11 +345,11 @@ void OrderList::FreeChain(bool keep_orderlist)
*/
Order *OrderList::GetOrderAt(int index) const
{
- if (index < 0) return NULL;
+ if (index < 0) return nullptr;
Order *order = this->first;
- while (order != NULL && index-- > 0) {
+ while (order != nullptr && index-- > 0) {
order = order->next;
}
return order;
@@ -364,11 +364,11 @@ Order *OrderList::GetOrderAt(int index) const
* \li a station order
* \li a refitting depot order
* \li a non-trivial conditional order
- * \li NULL if the vehicle won't stop anymore.
+ * \li nullptr if the vehicle won't stop anymore.
*/
const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
{
- if (hops > this->GetNumOrders() || next == NULL) return NULL;
+ if (hops > this->GetNumOrders() || next == nullptr) return nullptr;
if (next->IsType(OT_CONDITIONAL)) {
if (next->GetConditionVariable() != OCV_UNCONDITIONALLY) return next;
@@ -381,7 +381,7 @@ const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
}
if (next->IsType(OT_GOTO_DEPOT)) {
- if (next->GetDepotActionType() == ODATFB_HALT) return NULL;
+ if (next->GetDepotActionType() == ODATFB_HALT) return nullptr;
if (next->IsRefit()) return next;
}
@@ -395,7 +395,7 @@ const Order *OrderList::GetNextDecisionNode(const Order *next, uint hops) const
/**
* Recursively determine the next deterministic station to stop at.
* @param v The vehicle we're looking at.
- * @param first Order to start searching at or NULL to start at cur_implicit_order_index + 1.
+ * @param first Order to start searching at or nullptr to start at cur_implicit_order_index + 1.
* @param hops Number of orders we have already looked at.
* @return Next stoppping station or INVALID_STATION.
* @pre The vehicle is currently loading and v->last_station_visited is meaningful.
@@ -405,17 +405,17 @@ StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *
{
const Order *next = first;
- if (first == NULL) {
+ if (first == nullptr) {
next = this->GetOrderAt(v->cur_implicit_order_index);
- if (next == NULL) {
+ if (next == nullptr) {
next = this->GetFirstOrder();
- if (next == NULL) return INVALID_STATION;
+ if (next == nullptr) return INVALID_STATION;
} else {
- /* GetNext never returns NULL if there is a valid station in the list.
+ /* GetNext never returns nullptr if there is a valid station in the list.
* As the given "next" is already valid and a station in the list, we
- * don't have to check for NULL here. */
+ * don't have to check for nullptr here. */
next = this->GetNext(next);
- assert(next != NULL);
+ assert(next != nullptr);
}
}
@@ -423,16 +423,16 @@ StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *
next = this->GetNextDecisionNode(next, ++hops);
/* Resolve possibly nested conditionals by estimation. */
- while (next != NULL && next->IsType(OT_CONDITIONAL)) {
+ while (next != nullptr && next->IsType(OT_CONDITIONAL)) {
/* We return both options of conditional orders. */
const Order *skip_to = this->GetNextDecisionNode(
this->GetOrderAt(next->GetConditionSkipToOrder()), hops);
const Order *advance = this->GetNextDecisionNode(
this->GetNext(next), hops);
- if (advance == NULL || advance == first || skip_to == advance) {
- next = (skip_to == first) ? NULL : skip_to;
- } else if (skip_to == NULL || skip_to == first) {
- next = (advance == first) ? NULL : advance;
+ if (advance == nullptr || advance == first || skip_to == advance) {
+ next = (skip_to == first) ? nullptr : skip_to;
+ } else if (skip_to == nullptr || skip_to == first) {
+ next = (advance == first) ? nullptr : advance;
} else {
StationIDStack st1 = this->GetNextStoppingStation(v, skip_to, hops);
StationIDStack st2 = this->GetNextStoppingStation(v, advance, hops);
@@ -443,7 +443,7 @@ StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *
}
/* Don't return a next stop if the vehicle has to unload everything. */
- if (next == NULL || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
+ if (next == nullptr || ((next->IsType(OT_GOTO_STATION) || next->IsType(OT_IMPLICIT)) &&
next->GetDestination() == v->last_station_visited &&
(next->GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) != 0)) {
return INVALID_STATION;
@@ -460,7 +460,7 @@ StationIDStack OrderList::GetNextStoppingStation(const Vehicle *v, const Order *
*/
void OrderList::InsertOrderAt(Order *new_order, int index)
{
- if (this->first == NULL) {
+ if (this->first == nullptr) {
this->first = new_order;
} else {
if (index == 0) {
@@ -566,7 +566,7 @@ void OrderList::RemoveVehicle(Vehicle *v)
*/
bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
{
- for (const Vehicle *v_shared = this->first_shared; v_shared != NULL; v_shared = v_shared->NextShared()) {
+ for (const Vehicle *v_shared = this->first_shared; v_shared != nullptr; v_shared = v_shared->NextShared()) {
if (v_shared == v) return true;
}
@@ -581,7 +581,7 @@ bool OrderList::IsVehicleInSharedOrdersList(const Vehicle *v) const
int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
{
int count = 0;
- for (const Vehicle *v_shared = v->PreviousShared(); v_shared != NULL; v_shared = v_shared->PreviousShared()) count++;
+ for (const Vehicle *v_shared = v->PreviousShared(); v_shared != nullptr; v_shared = v_shared->PreviousShared()) count++;
return count;
}
@@ -591,7 +591,7 @@ int OrderList::GetPositionInSharedOrderList(const Vehicle *v) const
*/
bool OrderList::IsCompleteTimetable() const
{
- for (Order *o = this->first; o != NULL; o = o->next) {
+ for (Order *o = this->first; o != nullptr; o = o->next) {
/* Implicit orders are, by definition, not timetabled. */
if (o->IsType(OT_IMPLICIT)) continue;
if (!o->IsCompletelyTimetabled()) return false;
@@ -612,7 +612,7 @@ void OrderList::DebugCheckSanity() const
DEBUG(misc, 6, "Checking OrderList %hu for sanity...", this->index);
- for (const Order *o = this->first; o != NULL; o = o->next) {
+ for (const Order *o = this->first; o != nullptr; o = o->next) {
++check_num_orders;
if (!o->IsType(OT_IMPLICIT)) ++check_num_manual_orders;
check_timetable_duration += o->GetTimetabledWait() + o->GetTimetabledTravel();
@@ -623,7 +623,7 @@ void OrderList::DebugCheckSanity() const
assert(this->timetable_duration == check_timetable_duration);
assert(this->total_duration == check_total_duration);
- for (const Vehicle *v = this->first_shared; v != NULL; v = v->NextShared()) {
+ for (const Vehicle *v = this->first_shared; v != nullptr; v = v->NextShared()) {
++check_num_vehicles;
assert(v->orders.list == this);
}
@@ -702,7 +702,7 @@ uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int
conditional_depth++;
int dist1 = GetOrderDistance(prev, v->GetOrder(cur->GetConditionSkipToOrder()), v, conditional_depth);
- int dist2 = GetOrderDistance(prev, cur->next == NULL ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
+ int dist2 = GetOrderDistance(prev, cur->next == nullptr ? v->orders.list->GetFirstOrder() : cur->next, v, conditional_depth);
return max(dist1, dist2);
}
@@ -732,7 +732,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
Order new_order(p2);
Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -742,7 +742,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
switch (new_order.GetType()) {
case OT_GOTO_STATION: {
const Station *st = Station::GetIfValid(new_order.GetDestination());
- if (st == NULL) return CMD_ERROR;
+ if (st == nullptr) return CMD_ERROR;
if (st->owner != OWNER_NONE) {
CommandCost ret = CheckOwnership(st->owner);
@@ -750,7 +750,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
}
if (!CanVehicleUseStation(v, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER);
- for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
+ for (Vehicle *u = v->FirstShared(); u != nullptr; u = u->NextShared()) {
if (!CanVehicleUseStation(u, st)) return_cmd_error(STR_ERROR_CAN_T_ADD_ORDER_SHARED);
}
@@ -789,7 +789,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (v->type == VEH_AIRCRAFT) {
const Station *st = Station::GetIfValid(new_order.GetDestination());
- if (st == NULL) return CMD_ERROR;
+ if (st == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(st->owner);
if (ret.Failed()) return ret;
@@ -800,7 +800,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
} else {
const Depot *dp = Depot::GetIfValid(new_order.GetDestination());
- if (dp == NULL) return CMD_ERROR;
+ if (dp == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(GetTileOwner(dp->xy));
if (ret.Failed()) return ret;
@@ -832,7 +832,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
case OT_GOTO_WAYPOINT: {
const Waypoint *wp = Waypoint::GetIfValid(new_order.GetDestination());
- if (wp == NULL) return CMD_ERROR;
+ if (wp == nullptr) return CMD_ERROR;
switch (v->type) {
default: return CMD_ERROR;
@@ -897,7 +897,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (v->GetNumOrders() >= MAX_VEH_ORDER_ID) return_cmd_error(STR_ERROR_TOO_MANY_ORDERS);
if (!Order::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
- if (v->orders.list == NULL && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
+ if (v->orders.list == nullptr && !OrderList::CanAllocateItem()) return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
if (flags & DC_EXEC) {
Order *new_o = new Order();
@@ -917,7 +917,7 @@ CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
{
/* Create new order and link in list */
- if (v->orders.list == NULL) {
+ if (v->orders.list == nullptr) {
v->orders.list = new OrderList(new_o, v);
} else {
v->orders.list->InsertOrderAt(new_o, sel_ord);
@@ -925,7 +925,7 @@ void InsertOrder(Vehicle *v, Order *new_o, VehicleOrderID sel_ord)
Vehicle *u = v->FirstShared();
DeleteOrderWarnings(u);
- for (; u != NULL; u = u->NextShared()) {
+ for (; u != nullptr; u = u->NextShared()) {
assert(v->orders.list == u->orders.list);
/* If there is added an order before the current one, we need
@@ -1008,7 +1008,7 @@ CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
Vehicle *v = Vehicle::GetIfValid(veh_id);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -1016,7 +1016,7 @@ CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
/* If we did not select an order, we maybe want to de-clone the orders */
if (sel_ord >= v->GetNumOrders()) return DecloneOrder(v, flags);
- if (v->GetOrder(sel_ord) == NULL) return CMD_ERROR;
+ if (v->GetOrder(sel_ord) == nullptr) return CMD_ERROR;
if (flags & DC_EXEC) DeleteOrder(v, sel_ord);
return CommandCost();
@@ -1048,7 +1048,7 @@ void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Vehicle *u = v->FirstShared();
DeleteOrderWarnings(u);
- for (; u != NULL; u = u->NextShared()) {
+ for (; u != nullptr; u = u->NextShared()) {
assert(v->orders.list == u->orders.list);
if (sel_ord == u->cur_real_order_index && u->current_order.IsType(OT_LOADING)) {
@@ -1080,7 +1080,7 @@ void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
/* As we delete an order, the order to skip to will be 'wrong'. */
VehicleOrderID cur_order_id = 0;
- Order *order = NULL;
+ Order *order = nullptr;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_CONDITIONAL)) {
VehicleOrderID order_id = order->GetConditionSkipToOrder();
@@ -1114,7 +1114,7 @@ CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
Vehicle *v = Vehicle::GetIfValid(veh_id);
- if (v == NULL || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle() || sel_ord == v->cur_implicit_order_index || sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -1155,7 +1155,7 @@ CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
VehicleOrderID target_order = GB(p2, 16, 16);
Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -1166,7 +1166,7 @@ CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
Order *moving_one = v->GetOrder(moving_order);
/* Don't move an empty order */
- if (moving_one == NULL) return CMD_ERROR;
+ if (moving_one == nullptr) return CMD_ERROR;
if (flags & DC_EXEC) {
v->orders.list->MoveOrder(moving_order, target_order);
@@ -1176,7 +1176,7 @@ CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
DeleteOrderWarnings(u);
- for (; u != NULL; u = u->NextShared()) {
+ for (; u != nullptr; u = u->NextShared()) {
/* Update the current order.
* There are multiple ways to move orders, which result in cur_implicit_order_index
* and cur_real_order_index to not longer make any sense. E.g. moving another
@@ -1262,7 +1262,7 @@ CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
if (mof >= MOF_END) return CMD_ERROR;
Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -1459,7 +1459,7 @@ CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
/* Update the windows and full load flags, also for vehicles that share the same order list */
Vehicle *u = v->FirstShared();
DeleteOrderWarnings(u);
- for (; u != NULL; u = u->NextShared()) {
+ for (; u != nullptr; u = u->NextShared()) {
/* Toggle u->current_order "Full load" flag if it changed.
* However, as the same flag is used for depot orders, check
* whether we are not going to a depot as there are three
@@ -1490,17 +1490,17 @@ CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
*/
static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_order, const Order *first)
{
- if (first == NULL || v_new->acache.cached_max_range == 0) return true;
+ if (first == nullptr || v_new->acache.cached_max_range == 0) return true;
/* Iterate over all orders to check the distance between all
* 'goto' orders and their respective next order (of any type). */
- for (const Order *o = first; o != NULL; o = o->next) {
+ for (const Order *o = first; o != nullptr; o = o->next) {
switch (o->GetType()) {
case OT_GOTO_STATION:
case OT_GOTO_DEPOT:
case OT_GOTO_WAYPOINT:
/* If we don't have a next order, we've reached the end and must check the first order instead. */
- if (GetOrderDistance(o, o->next != NULL ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
+ if (GetOrderDistance(o, o->next != nullptr ? o->next : first, v_order) > v_new->acache.cached_max_range_sqr) return false;
break;
default: break;
@@ -1527,7 +1527,7 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
VehicleID veh_dst = GB(p1, 0, 20);
Vehicle *dst = Vehicle::GetIfValid(veh_dst);
- if (dst == NULL || !dst->IsPrimaryVehicle()) return CMD_ERROR;
+ if (dst == nullptr || !dst->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(dst->owner);
if (ret.Failed()) return ret;
@@ -1537,7 +1537,7 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
Vehicle *src = Vehicle::GetIfValid(veh_src);
/* Sanity checks */
- if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
+ if (src == nullptr || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
CommandCost ret = CheckOwnership(src->owner);
if (ret.Failed()) return ret;
@@ -1569,7 +1569,7 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
return_cmd_error(STR_ERROR_AIRCRAFT_NOT_ENOUGH_RANGE);
}
- if (src->orders.list == NULL && !OrderList::CanAllocateItem()) {
+ if (src->orders.list == nullptr && !OrderList::CanAllocateItem()) {
return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
}
@@ -1596,7 +1596,7 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
Vehicle *src = Vehicle::GetIfValid(veh_src);
/* Sanity checks */
- if (src == NULL || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
+ if (src == nullptr || !src->IsPrimaryVehicle() || dst->type != src->type || dst == src) return CMD_ERROR;
CommandCost ret = CheckOwnership(src->owner);
if (ret.Failed()) return ret;
@@ -1623,7 +1623,7 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (flags & DC_EXEC) {
const Order *order;
- Order *first = NULL;
+ Order *first = nullptr;
Order **order_dst;
/* If the destination vehicle had an order list, destroy the chain but keep the OrderList.
@@ -1637,10 +1637,10 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
(*order_dst)->AssignOrder(*order);
order_dst = &(*order_dst)->next;
}
- if (dst->orders.list == NULL) {
+ if (dst->orders.list == nullptr) {
dst->orders.list = new OrderList(first, dst);
} else {
- assert(dst->orders.list->GetFirstOrder() == NULL);
+ assert(dst->orders.list->GetFirstOrder() == nullptr);
assert(!dst->orders.list->IsShared());
delete dst->orders.list;
assert(OrderList::CanAllocateItem());
@@ -1681,13 +1681,13 @@ CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (cargo >= NUM_CARGO && cargo != CT_NO_REFIT && cargo != CT_AUTO_REFIT) return CMD_ERROR;
const Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
Order *order = v->GetOrder(order_number);
- if (order == NULL) return CMD_ERROR;
+ if (order == nullptr) return CMD_ERROR;
/* Automatic refit cargo is only supported for goto station orders. */
if (cargo == CT_AUTO_REFIT && !order->IsType(OT_GOTO_STATION)) return CMD_ERROR;
@@ -1703,7 +1703,7 @@ CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() & ~ODATFB_HALT));
}
- for (Vehicle *u = v->FirstShared(); u != NULL; u = u->NextShared()) {
+ for (Vehicle *u = v->FirstShared(); u != nullptr; u = u->NextShared()) {
/* Update any possible open window of the vehicle */
InvalidateVehicleOrder(u, VIWD_MODIFY_ORDERS);
@@ -1781,7 +1781,7 @@ void CheckOrders(const Vehicle *v)
if (n_st < 2 && message == INVALID_STRING_ID) message = STR_NEWS_VEHICLE_HAS_TOO_FEW_ORDERS;
#ifndef NDEBUG
- if (v->orders.list != NULL) v->orders.list->DebugCheckSanity();
+ if (v->orders.list != nullptr) v->orders.list->DebugCheckSanity();
#endif
/* We don't have a problem */
@@ -1836,7 +1836,7 @@ restart:
if (order->IsType(OT_IMPLICIT)) {
order = order->next; // DeleteOrder() invalidates current order
DeleteOrder(v, id);
- if (order != NULL) goto restart;
+ if (order != nullptr) goto restart;
break;
}
@@ -1853,7 +1853,7 @@ restart:
order->MakeDummy();
order->SetTravelTimetabled(travel_timetabled);
- for (const Vehicle *w = v->FirstShared(); w != NULL; w = w->NextShared()) {
+ for (const Vehicle *w = v->FirstShared(); w != nullptr; w = w->NextShared()) {
/* In GUI, simulate by removing the order and adding it back */
InvalidateVehicleOrder(w, id | (INVALID_VEH_ORDER_ID << 8));
InvalidateVehicleOrder(w, (INVALID_VEH_ORDER_ID << 8) | id);
@@ -1896,11 +1896,11 @@ void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indic
if (v->IsOrderListShared()) {
/* Remove ourself from the shared order list. */
v->RemoveFromShared();
- v->orders.list = NULL;
- } else if (v->orders.list != NULL) {
+ v->orders.list = nullptr;
+ } else if (v->orders.list != nullptr) {
/* Remove the orders */
v->orders.list->FreeChain(keep_orderlist);
- if (!keep_orderlist) v->orders.list = NULL;
+ if (!keep_orderlist) v->orders.list = nullptr;
}
if (reset_order_indices) {
@@ -1982,7 +1982,7 @@ VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
uint16 value = order->GetConditionValue();
switch (order->GetConditionVariable()) {
- case OCV_LOAD_PERCENTAGE: skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, NULL), value); break;
+ case OCV_LOAD_PERCENTAGE: skip_order = OrderConditionCompare(occ, CalcPercentVehicleFilled(v, nullptr), value); break;
case OCV_RELIABILITY: skip_order = OrderConditionCompare(occ, ToPercent16(v->reliability), value); break;
case OCV_MAX_RELIABILITY: skip_order = OrderConditionCompare(occ, ToPercent16(v->GetEngine()->reliability), value); break;
case OCV_MAX_SPEED: skip_order = OrderConditionCompare(occ, v->GetDisplayMaxSpeed() * 10 / 16, value); break;
@@ -2109,12 +2109,12 @@ bool UpdateOrderDest(Vehicle *v, const Order *order, int conditional_depth, bool
/* Get the current order */
order = v->GetOrder(v->cur_real_order_index);
- if (order != NULL && order->IsType(OT_IMPLICIT)) {
+ if (order != nullptr && order->IsType(OT_IMPLICIT)) {
assert(v->GetNumManualOrders() == 0);
- order = NULL;
+ order = nullptr;
}
- if (order == NULL) {
+ if (order == nullptr) {
v->current_order.Free();
v->SetDestTile(0);
return false;
@@ -2177,13 +2177,13 @@ bool ProcessOrders(Vehicle *v)
v->UpdateRealOrderIndex();
const Order *order = v->GetOrder(v->cur_real_order_index);
- if (order != NULL && order->IsType(OT_IMPLICIT)) {
+ if (order != nullptr && order->IsType(OT_IMPLICIT)) {
assert(v->GetNumManualOrders() == 0);
- order = NULL;
+ order = nullptr;
}
/* If no order, do nothing. */
- if (order == NULL || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
+ if (order == nullptr || (v->type == VEH_AIRCRAFT && !CheckForValidOrders(v))) {
if (v->type == VEH_AIRCRAFT) {
/* Aircraft do something vastly different here, so handle separately */
extern void HandleMissingAircraftOrders(Aircraft *v);
diff --git a/src/order_gui.cpp b/src/order_gui.cpp
index a48638a85..bd7ea39cc 100644
--- a/src/order_gui.cpp
+++ b/src/order_gui.cpp
@@ -239,7 +239,7 @@ void DrawOrderString(const Vehicle *v, const Order *order, int order_index, int
/* Check range for aircraft. */
if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0 && order->IsGotoOrder()) {
- const Order *next = order->next != NULL ? order->next : v->GetFirstOrder();
+ const Order *next = order->next != nullptr ? order->next : v->GetFirstOrder();
if (GetOrderDistance(order, next, v) > Aircraft::From(v)->acache.cached_max_range_sqr) SetDParam(8, STR_ORDER_OUT_OF_RANGE);
}
@@ -576,7 +576,7 @@ private:
VehicleOrderID sel_ord = this->OrderGetSel();
const Order *order = this->vehicle->GetOrder(sel_ord);
- if (order == NULL || order->GetLoadType() == load_type) return;
+ if (order == nullptr || order->GetLoadType() == load_type) return;
if (load_type < 0) {
load_type = order->GetLoadType() == OLF_LOAD_IF_POSSIBLE ? OLF_FULL_LOAD_ANY : OLF_LOAD_IF_POSSIBLE;
@@ -601,7 +601,7 @@ private:
if (i < 0) {
const Order *order = this->vehicle->GetOrder(sel_ord);
- if (order == NULL) return;
+ if (order == nullptr) return;
i = (order->GetDepotOrderType() & ODTFB_SERVICE) ? DA_ALWAYS_GO : DA_SERVICE;
}
DoCommandP(this->vehicle->tile, this->vehicle->index + (sel_ord << 20), MOF_DEPOT_ACTION | (i << 4), CMD_MODIFY_ORDER | CMD_MSG(STR_ERROR_CAN_T_MODIFY_THIS_ORDER));
@@ -613,7 +613,7 @@ private:
void OrderClick_NearestDepot()
{
Order order;
- order.next = NULL;
+ order.next = nullptr;
order.index = 0;
order.MakeGoToDepot(0, ODTFB_PART_OF_ORDERS,
_settings_client.gui.new_nonstop && this->vehicle->IsGroundVehicle() ? ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS : ONSF_STOP_EVERYWHERE);
@@ -630,7 +630,7 @@ private:
VehicleOrderID sel_ord = this->OrderGetSel();
const Order *order = this->vehicle->GetOrder(sel_ord);
- if (order == NULL || order->GetUnloadType() == unload_type) return;
+ if (order == nullptr || order->GetUnloadType() == unload_type) return;
if (unload_type < 0) {
unload_type = order->GetUnloadType() == OUF_UNLOAD_IF_POSSIBLE ? OUFB_UNLOAD : OUF_UNLOAD_IF_POSSIBLE;
@@ -672,7 +672,7 @@ private:
VehicleOrderID sel_ord = this->OrderGetSel();
const Order *order = this->vehicle->GetOrder(sel_ord);
- if (order == NULL || order->GetNonStopType() == non_stop) return;
+ if (order == nullptr || order->GetNonStopType() == non_stop) return;
/* Keypress if negative, so 'toggle' to the next */
if (non_stop < 0) {
@@ -760,7 +760,7 @@ private:
{
this->can_do_refit = false;
this->can_do_autorefit = false;
- for (const Vehicle *w = this->vehicle; w != NULL; w = w->IsGroundVehicle() ? w->Next() : NULL) {
+ for (const Vehicle *w = this->vehicle; w != nullptr; w = w->IsGroundVehicle() ? w->Next() : nullptr) {
if (IsEngineRefittable(w->engine_type)) this->can_do_refit = true;
if (HasBit(Engine::Get(w->engine_type)->info.misc_flags, EF_AUTO_REFIT)) this->can_do_autorefit = true;
}
@@ -953,11 +953,11 @@ public:
NWidgetStacked *right_sel = this->GetWidget<NWidgetStacked>(WID_O_SEL_TOP_RIGHT);
/* Ship or airplane. */
NWidgetStacked *row_sel = this->GetWidget<NWidgetStacked>(WID_O_SEL_TOP_ROW);
- assert(row_sel != NULL || (train_row_sel != NULL && left_sel != NULL && middle_sel != NULL && right_sel != NULL));
+ assert(row_sel != nullptr || (train_row_sel != nullptr && left_sel != nullptr && middle_sel != nullptr && right_sel != nullptr));
- if (order == NULL) {
- if (row_sel != NULL) {
+ if (order == nullptr) {
+ if (row_sel != nullptr) {
row_sel->SetDisplayedPlane(DP_ROW_LOAD);
} else {
train_row_sel->SetDisplayedPlane(DP_GROUNDVEHICLE_ROW_NORMAL);
@@ -976,7 +976,7 @@ public:
switch (order->GetType()) {
case OT_GOTO_STATION:
- if (row_sel != NULL) {
+ if (row_sel != nullptr) {
row_sel->SetDisplayedPlane(DP_ROW_LOAD);
} else {
train_row_sel->SetDisplayedPlane(DP_GROUNDVEHICLE_ROW_NORMAL);
@@ -998,7 +998,7 @@ public:
break;
case OT_GOTO_WAYPOINT:
- if (row_sel != NULL) {
+ if (row_sel != nullptr) {
row_sel->SetDisplayedPlane(DP_ROW_LOAD);
} else {
train_row_sel->SetDisplayedPlane(DP_GROUNDVEHICLE_ROW_NORMAL);
@@ -1014,7 +1014,7 @@ public:
break;
case OT_GOTO_DEPOT:
- if (row_sel != NULL) {
+ if (row_sel != nullptr) {
row_sel->SetDisplayedPlane(DP_ROW_DEPOT);
} else {
train_row_sel->SetDisplayedPlane(DP_GROUNDVEHICLE_ROW_NORMAL);
@@ -1033,7 +1033,7 @@ public:
break;
case OT_CONDITIONAL: {
- if (row_sel != NULL) {
+ if (row_sel != nullptr) {
row_sel->SetDisplayedPlane(DP_ROW_CONDITIONAL);
} else {
train_row_sel->SetDisplayedPlane(DP_GROUNDVEHICLE_ROW_CONDITIONAL);
@@ -1048,7 +1048,7 @@ public:
}
default: // every other order
- if (row_sel != NULL) {
+ if (row_sel != nullptr) {
row_sel->SetDisplayedPlane(DP_ROW_LOAD);
} else {
train_row_sel->SetDisplayedPlane(DP_GROUNDVEHICLE_ROW_NORMAL);
@@ -1096,7 +1096,7 @@ public:
const Order *order = this->vehicle->GetOrder(i);
/* First draw the highlighting underground if it exists. */
if (this->order_over != INVALID_VEH_ORDER_ID) {
- while (order != NULL) {
+ while (order != nullptr) {
/* Don't draw anything if it extends past the end of the window. */
if (!this->vscroll->IsVisible(i)) break;
@@ -1121,7 +1121,7 @@ public:
}
/* Draw the orders. */
- while (order != NULL) {
+ while (order != nullptr) {
/* Don't draw anything if it extends past the end of the window. */
if (!this->vscroll->IsVisible(i)) break;
@@ -1145,7 +1145,7 @@ public:
VehicleOrderID sel = this->OrderGetSel();
const Order *order = this->vehicle->GetOrder(sel);
- if (order != NULL && order->IsType(OT_CONDITIONAL)) {
+ if (order != nullptr && order->IsType(OT_CONDITIONAL)) {
uint value = order->GetConditionValue();
if (order->GetConditionVariable() == OCV_MAX_SPEED) value = ConvertSpeedToDisplaySpeed(value);
SetDParam(0, value);
@@ -1167,7 +1167,7 @@ public:
VehicleOrderID order_id = this->GetOrderFromPt(_cursor.pos.y - this->top);
if (order_id != INVALID_VEH_ORDER_ID) {
Order order;
- order.next = NULL;
+ order.next = nullptr;
order.index = 0;
order.MakeConditional(order_id);
@@ -1714,7 +1714,7 @@ void ShowOrdersWindow(const Vehicle *v)
{
DeleteWindowById(WC_VEHICLE_DETAILS, v->index, false);
DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
- if (BringWindowToFrontById(WC_VEHICLE_ORDERS, v->index) != NULL) return;
+ if (BringWindowToFrontById(WC_VEHICLE_ORDERS, v->index) != nullptr) return;
/* Using a different WindowDescs for _local_company causes problems.
* Due to this we have to close order windows in ChangeWindowOwner/DeleteCompanyWindows,
diff --git a/src/os/macosx/crashlog_osx.cpp b/src/os/macosx/crashlog_osx.cpp
index c1b321340..16c029639 100644
--- a/src/os/macosx/crashlog_osx.cpp
+++ b/src/os/macosx/crashlog_osx.cpp
@@ -66,7 +66,7 @@ class CrashLogOSX : public CrashLog {
" Machine: %s\n"
" Min Ver: %d\n",
ver_maj, ver_min, ver_bug,
- arch != NULL ? arch->description : "unknown",
+ arch != nullptr ? arch->description : "unknown",
MAC_OS_X_VERSION_MIN_REQUIRED
);
}
@@ -79,7 +79,7 @@ class CrashLogOSX : public CrashLog {
" Message: %s\n\n",
strsignal(this->signum),
this->signum,
- message == NULL ? "<none>" : message
+ message == nullptr ? "<none>" : message
);
}
@@ -99,14 +99,14 @@ class CrashLogOSX : public CrashLog {
frame = (void **)__builtin_frame_address(0);
#endif
- for (int i = 0; frame != NULL && i < MAX_STACK_FRAMES; i++) {
+ for (int i = 0; frame != nullptr && i < MAX_STACK_FRAMES; i++) {
/* Get IP for current stack frame. */
#if defined(__ppc__) || defined(__ppc64__)
void *ip = frame[2];
#else
void *ip = frame[1];
#endif
- if (ip == NULL) break;
+ if (ip == nullptr) break;
/* Print running index. */
buffer += seprintf(buffer, last, " [%02d]", i);
@@ -118,7 +118,7 @@ class CrashLogOSX : public CrashLog {
if (dl_valid && dli.dli_fname) {
/* Valid image name? Extract filename from the complete path. */
const char *s = strrchr(dli.dli_fname, '/');
- if (s != NULL) {
+ if (s != nullptr) {
fname = s + 1;
} else {
fname = dli.dli_fname;
@@ -128,13 +128,13 @@ class CrashLogOSX : public CrashLog {
buffer += seprintf(buffer, last, " %-20s " PRINTF_PTR, fname, (uintptr_t)ip);
/* Print function offset if information is available. */
- if (dl_valid && dli.dli_sname != NULL && dli.dli_saddr != NULL) {
+ if (dl_valid && dli.dli_sname != nullptr && dli.dli_saddr != nullptr) {
/* Try to demangle a possible C++ symbol. */
int status = -1;
- char *func_name = abi::__cxa_demangle(dli.dli_sname, NULL, 0, &status);
+ char *func_name = abi::__cxa_demangle(dli.dli_sname, nullptr, 0, &status);
long int offset = (intptr_t)ip - (intptr_t)dli.dli_saddr;
- buffer += seprintf(buffer, last, " (%s + %ld)", func_name != NULL ? func_name : dli.dli_sname, offset);
+ buffer += seprintf(buffer, last, " (%s + %ld)", func_name != nullptr ? func_name : dli.dli_sname, offset);
free(func_name);
}
diff --git a/src/os/macosx/splash.cpp b/src/os/macosx/splash.cpp
index eadb78510..1ddb165b3 100644
--- a/src/os/macosx/splash.cpp
+++ b/src/os/macosx/splash.cpp
@@ -54,7 +54,7 @@ static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
void DisplaySplashImage()
{
FILE *f = FioFOpenFile(SPLASH_IMAGE_FILE, "r", BASESET_DIR);
- if (f == NULL) return;
+ if (f == nullptr) return;
png_byte header[8];
fread(header, sizeof(png_byte), 8, f);
@@ -63,23 +63,23 @@ void DisplaySplashImage()
return;
}
- png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp) NULL, png_my_error, png_my_warning);
+ png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp) nullptr, png_my_error, png_my_warning);
- if (png_ptr == NULL) {
+ if (png_ptr == nullptr) {
fclose(f);
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
- if (info_ptr == NULL) {
- png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
+ if (info_ptr == nullptr) {
+ png_destroy_read_struct(&png_ptr, (png_infopp)nullptr, (png_infopp)nullptr);
fclose(f);
return;
}
png_infop end_info = png_create_info_struct(png_ptr);
- if (end_info == NULL) {
- png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+ if (end_info == nullptr) {
+ png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)nullptr);
fclose(f);
return;
}
@@ -93,7 +93,7 @@ void DisplaySplashImage()
png_init_io(png_ptr, f);
png_set_sig_bytes(png_ptr, 8);
- png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
+ png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, nullptr);
uint width = png_get_image_width(png_ptr, info_ptr);
uint height = png_get_image_height(png_ptr, info_ptr);
diff --git a/src/os/macosx/string_osx.cpp b/src/os/macosx/string_osx.cpp
index 580be3520..6d90b91a8 100644
--- a/src/os/macosx/string_osx.cpp
+++ b/src/os/macosx/string_osx.cpp
@@ -22,7 +22,7 @@
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
/** Cached current locale. */
-static CFLocaleRef _osx_locale = NULL;
+static CFLocaleRef _osx_locale = nullptr;
/** CoreText cache for font information, cleared when OTTD changes fonts. */
static CTFontRef _font_cache[FS_END];
@@ -125,21 +125,21 @@ static CGFloat SpriteFontGetWidth(void *ref_con)
}
static CTRunDelegateCallbacks _sprite_font_callback = {
- kCTRunDelegateCurrentVersion, NULL, NULL, NULL,
+ kCTRunDelegateCurrentVersion, nullptr, nullptr, nullptr,
&SpriteFontGetWidth
};
/* static */ ParagraphLayouter *CoreTextParagraphLayoutFactory::GetParagraphLayout(CharType *buff, CharType *buff_end, FontMap &fontMapping)
{
- if (!MacOSVersionIsAtLeast(10, 5, 0)) return NULL;
+ if (!MacOSVersionIsAtLeast(10, 5, 0)) return nullptr;
/* Can't layout an empty string. */
ptrdiff_t length = buff_end - buff;
- if (length == 0) return NULL;
+ if (length == 0) return nullptr;
/* Can't layout our in-built sprite fonts. */
for (const auto &i : fontMapping) {
- if (i.second->fc->IsBuiltInFont()) return NULL;
+ if (i.second->fc->IsBuiltInFont()) return nullptr;
}
/* Make attributed string with embedded font information. */
@@ -156,10 +156,10 @@ static CTRunDelegateCallbacks _sprite_font_callback = {
for (const auto &i : fontMapping) {
if (i.first - last == 0) continue;
- if (_font_cache[i.second->fc->GetSize()] == NULL) {
+ if (_font_cache[i.second->fc->GetSize()] == nullptr) {
/* Cache font information. */
CFStringRef font_name = CFStringCreateWithCString(kCFAllocatorDefault, i.second->fc->GetFontName(), kCFStringEncodingUTF8);
- _font_cache[i.second->fc->GetSize()] = CTFontCreateWithName(font_name, i.second->fc->GetFontSize(), NULL);
+ _font_cache[i.second->fc->GetSize()] = CTFontCreateWithName(font_name, i.second->fc->GetFontSize(), nullptr);
CFRelease(font_name);
}
CFAttributedStringSetAttribute(str, CFRangeMake(last, i.first - last), kCTFontAttributeName, _font_cache[i.second->fc->GetSize()]);
@@ -185,12 +185,12 @@ static CTRunDelegateCallbacks _sprite_font_callback = {
CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString(str);
CFRelease(str);
- return typesetter != NULL ? new CoreTextParagraphLayout(typesetter, buff, length, fontMapping) : NULL;
+ return typesetter != nullptr ? new CoreTextParagraphLayout(typesetter, buff, length, fontMapping) : nullptr;
}
/* virtual */ std::unique_ptr<const ParagraphLayouter::Line> CoreTextParagraphLayout::NextLine(int max_width)
{
- if (this->cur_offset >= this->length) return NULL;
+ if (this->cur_offset >= this->length) return nullptr;
/* Get line break position, trying word breaking first and breaking somewhere if that doesn't work. */
CFIndex len = CTTypesetterSuggestLineBreak(this->typesetter, this->cur_offset, max_width);
@@ -200,7 +200,7 @@ static CTRunDelegateCallbacks _sprite_font_callback = {
CTLineRef line = CTTypesetterCreateLine(this->typesetter, CFRangeMake(this->cur_offset, len));
this->cur_offset += len;
- return std::unique_ptr<const Line>(line != NULL ? new CoreTextLine(line, this->font_map, this->text_buffer) : NULL);
+ return std::unique_ptr<const Line>(line != nullptr ? new CoreTextLine(line, this->font_map, this->text_buffer) : nullptr);
}
CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font *font, const CoreTextParagraphLayoutFactory::CharType *buff) : font(font)
@@ -233,7 +233,7 @@ CoreTextParagraphLayout::CoreTextVisualRun::CoreTextVisualRun(CTRunRef run, Font
this->positions[i * 2 + 1] = pts[i].y;
}
}
- this->total_advance = (int)CTRunGetTypographicBounds(run, CFRangeMake(0, 0), NULL, NULL, NULL);
+ this->total_advance = (int)CTRunGetTypographicBounds(run, CFRangeMake(0, 0), nullptr, nullptr, nullptr);
this->positions[this->glyphs.size() * 2] = this->positions[0] + this->total_advance;
}
@@ -271,9 +271,9 @@ int CoreTextParagraphLayout::CoreTextLine::GetWidth() const
/** Delete CoreText font reference for a specific font size. */
void MacOSResetScriptCache(FontSize size)
{
- if (_font_cache[size] != NULL) {
+ if (_font_cache[size] != nullptr) {
CFRelease(_font_cache[size]);
- _font_cache[size] = NULL;
+ _font_cache[size] = nullptr;
}
}
@@ -282,7 +282,7 @@ void MacOSSetCurrentLocaleName(const char *iso_code)
{
if (!MacOSVersionIsAtLeast(10, 5, 0)) return;
- if (_osx_locale != NULL) CFRelease(_osx_locale);
+ if (_osx_locale != nullptr) CFRelease(_osx_locale);
CFStringRef iso = CFStringCreateWithCString(kCFAllocatorNull, iso_code, kCFStringEncodingUTF8);
_osx_locale = CFLocaleCreate(kCFAllocatorDefault, iso);
@@ -425,7 +425,7 @@ int MacOSStringCompare(const char *s1, const char *s2)
/* static */ StringIterator *OSXStringIterator::Create()
{
- if (!MacOSVersionIsAtLeast(10, 5, 0)) return NULL;
+ if (!MacOSVersionIsAtLeast(10, 5, 0)) return nullptr;
return new OSXStringIterator();
}
@@ -441,11 +441,11 @@ int MacOSStringCompare(const char *s1, const char *s2)
/* static */ StringIterator *OSXStringIterator::Create()
{
- return NULL;
+ return nullptr;
}
/* static */ ParagraphLayouter *CoreTextParagraphLayoutFactory::GetParagraphLayout(CharType *buff, CharType *buff_end, FontMap &fontMapping)
{
- return NULL;
+ return nullptr;
}
#endif /* (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) */
diff --git a/src/os/os2/os2.cpp b/src/os/os2/os2.cpp
index 70c75a410..9ba6f8ef9 100644
--- a/src/os/os2/os2.cpp
+++ b/src/os/os2/os2.cpp
@@ -102,7 +102,7 @@ bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
struct diskfree_t free;
char drive = path[0] - 'A' + 1;
- if (tot != NULL && _getdiskfree(drive, &free) == 0) {
+ if (tot != nullptr && _getdiskfree(drive, &free) == 0) {
*tot = free.avail_clusters * free.sectors_per_cluster * free.bytes_per_sector;
return true;
}
@@ -119,7 +119,7 @@ bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
free = (uint64)s.f_frsize * s.f_bavail;
}
#endif
- if (tot != NULL) *tot = free;
+ if (tot != nullptr) *tot = free;
return true;
#endif
}
@@ -173,7 +173,7 @@ void ShowOSErrorBox(const char *buf, bool system)
int CDECL main(int argc, char *argv[])
{
- SetRandomSeed(time(NULL));
+ SetRandomSeed(time(nullptr));
/* Make sure our arguments contain only valid UTF-8 characters. */
for (int i = 0; i < argc; i++) ValidateString(argv[i]);
@@ -191,7 +191,7 @@ bool GetClipboardContents(char *buffer, const char *last)
{
const char *text = (const char*)WinQueryClipbrdData(hab, CF_TEXT);
- if (text != NULL)
+ if (text != nullptr)
{
strecpy(buffer, text, last);
WinCloseClipbrd(hab);
diff --git a/src/os/unix/crashlog_unix.cpp b/src/os/unix/crashlog_unix.cpp
index 2e9f4215f..005babebd 100644
--- a/src/os/unix/crashlog_unix.cpp
+++ b/src/os/unix/crashlog_unix.cpp
@@ -68,7 +68,7 @@ class CrashLogUnix : public CrashLog {
" Message: %s\n\n",
strsignal(this->signum),
this->signum,
- message == NULL ? "<none>" : message
+ message == nullptr ? "<none>" : message
);
}
diff --git a/src/os/unix/unix.cpp b/src/os/unix/unix.cpp
index aa63019f6..430e3770f 100644
--- a/src/os/unix/unix.cpp
+++ b/src/os/unix/unix.cpp
@@ -84,7 +84,7 @@ bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
if (statvfs(path, &s) != 0) return false;
free = (uint64)s.f_frsize * s.f_bavail;
#endif
- if (tot != NULL) *tot = free;
+ if (tot != nullptr) *tot = free;
return true;
}
@@ -130,9 +130,9 @@ static const char *GetLocalCode()
#else
/* Strip locale (eg en_US.UTF-8) to only have UTF-8 */
const char *locale = GetCurrentLocale("LC_CTYPE");
- if (locale != NULL) locale = strchr(locale, '.');
+ if (locale != nullptr) locale = strchr(locale, '.');
- return (locale == NULL) ? "" : locale + 1;
+ return (locale == nullptr) ? "" : locale + 1;
#endif
}
@@ -158,7 +158,7 @@ static const char *convert_tofrom_fs(iconv_t convd, const char *name)
strecpy(outbuf, name, outbuf + outlen);
- iconv(convd, NULL, NULL, NULL, NULL);
+ iconv(convd, nullptr, nullptr, nullptr, nullptr);
if (iconv(convd, &inbuf, &inlen, &outbuf, &outlen) == (size_t)(-1)) {
DEBUG(misc, 0, "[iconv] error converting '%s'. Errno %d", name, errno);
}
@@ -246,13 +246,13 @@ int CDECL main(int argc, char *argv[])
cocoaSetupAutoreleasePool();
/* This is passed if we are launched by double-clicking */
if (argc >= 2 && strncmp(argv[1], "-psn", 4) == 0) {
- argv[1] = NULL;
+ argv[1] = nullptr;
argc = 1;
}
#endif
CrashLog::InitialiseCrashLog();
- SetRandomSeed(time(NULL));
+ SetRandomSeed(time(nullptr));
signal(SIGPIPE, SIG_IGN);
@@ -282,7 +282,7 @@ void OSOpenBrowser(const char *url)
const char *args[3];
args[0] = "xdg-open";
args[1] = url;
- args[2] = NULL;
+ args[2] = nullptr;
execvp(args[0], const_cast<char * const *>(args));
DEBUG(misc, 0, "Failed to open url: %s", url);
exit(0);
diff --git a/src/os/windows/crashlog_win.cpp b/src/os/windows/crashlog_win.cpp
index 458a76163..a19789976 100644
--- a/src/os/windows/crashlog_win.cpp
+++ b/src/os/windows/crashlog_win.cpp
@@ -66,7 +66,7 @@ public:
* A crash log is always generated when it's generated.
* @param ep the data related to the exception.
*/
- CrashLogWindows(EXCEPTION_POINTERS *ep = NULL) :
+ CrashLogWindows(EXCEPTION_POINTERS *ep = nullptr) :
ep(ep)
{
this->crashlog[0] = '\0';
@@ -81,7 +81,7 @@ public:
static CrashLogWindows *current;
};
-/* static */ CrashLogWindows *CrashLogWindows::current = NULL;
+/* static */ CrashLogWindows *CrashLogWindows::current = nullptr;
/* virtual */ char *CrashLogWindows::LogOSVersion(char *buffer, const char *last) const
{
@@ -114,7 +114,7 @@ public:
" Message: %s\n\n",
(int)ep->ExceptionRecord->ExceptionCode,
(size_t)ep->ExceptionRecord->ExceptionAddress,
- message == NULL ? "<none>" : message
+ message == nullptr ? "<none>" : message
);
}
@@ -156,7 +156,7 @@ static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename)
HANDLE file;
memset(dfi, 0, sizeof(*dfi));
- file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
+ file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, 0);
if (file != INVALID_HANDLE_VALUE) {
byte buffer[1024];
DWORD numread;
@@ -165,7 +165,7 @@ static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename)
uint32 crc = (uint32)-1;
for (;;) {
- if (ReadFile(file, buffer, sizeof(buffer), &numread, NULL) == 0 || numread == 0) {
+ if (ReadFile(file, buffer, sizeof(buffer), &numread, nullptr) == 0 || numread == 0) {
break;
}
filesize += numread;
@@ -174,7 +174,7 @@ static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename)
dfi->size = filesize;
dfi->crc32 = crc ^ (uint32)-1;
- if (GetFileTime(file, NULL, NULL, &write_time)) {
+ if (GetFileTime(file, nullptr, nullptr, &write_time)) {
FileTimeToSystemTime(&write_time, &dfi->file_time);
}
CloseHandle(file);
@@ -217,7 +217,7 @@ static char *PrintModuleInfo(char *output, const char *last, HMODULE mod)
BOOL res;
HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
- if (proc != NULL) {
+ if (proc != nullptr) {
res = EnumProcessModules(proc, modules, sizeof(modules), &needed);
CloseHandle(proc);
if (res) {
@@ -228,7 +228,7 @@ static char *PrintModuleInfo(char *output, const char *last, HMODULE mod)
}
}
}
- output = PrintModuleInfo(output, last, NULL);
+ output = PrintModuleInfo(output, last, nullptr);
return output + seprintf(output, last, "\n");
}
@@ -362,7 +362,7 @@ char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) c
if (LoadLibraryList((Function*)&proc, dbg_import)) {
/* Initialize symbol handler. */
HANDLE hCur = GetCurrentProcess();
- proc.pSymInitialize(hCur, NULL, TRUE);
+ proc.pSymInitialize(hCur, nullptr, TRUE);
/* Load symbols only when needed, fail silently on errors, demangle symbol names. */
proc.pSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_UNDNAME);
@@ -399,7 +399,7 @@ char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) c
#else
IMAGE_FILE_MACHINE_I386,
#endif
- hCur, GetCurrentThread(), &frame, &ctx, NULL, proc.pSymFunctionTableAccess64, proc.pSymGetModuleBase64, NULL)) break;
+ hCur, GetCurrentThread(), &frame, &ctx, nullptr, proc.pSymFunctionTableAccess64, proc.pSymGetModuleBase64, nullptr)) break;
if (frame.AddrPC.Offset == frame.AddrReturn.Offset) {
buffer += seprintf(buffer, last, " <infinite loop>\n");
@@ -443,16 +443,16 @@ char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) c
{
int ret = 0;
HMODULE dbghelp = LoadLibrary(_T("dbghelp.dll"));
- if (dbghelp != NULL) {
+ if (dbghelp != nullptr) {
typedef BOOL (WINAPI *MiniDumpWriteDump_t)(HANDLE, DWORD, HANDLE,
MINIDUMP_TYPE,
CONST PMINIDUMP_EXCEPTION_INFORMATION,
CONST PMINIDUMP_USER_STREAM_INFORMATION,
CONST PMINIDUMP_CALLBACK_INFORMATION);
MiniDumpWriteDump_t funcMiniDumpWriteDump = (MiniDumpWriteDump_t)GetProcAddress(dbghelp, "MiniDumpWriteDump");
- if (funcMiniDumpWriteDump != NULL) {
+ if (funcMiniDumpWriteDump != nullptr) {
seprintf(filename, filename_last, "%scrash.dmp", _personal_dir);
- HANDLE file = CreateFile(OTTD2FS(filename), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
+ HANDLE file = CreateFile(OTTD2FS(filename), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, 0);
HANDLE proc = GetCurrentProcess();
DWORD procid = GetCurrentProcessId();
MINIDUMP_EXCEPTION_INFORMATION mdei;
@@ -470,7 +470,7 @@ char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) c
mdei.ExceptionPointers = ep;
mdei.ClientPointers = false;
- funcMiniDumpWriteDump(proc, procid, file, MiniDumpWithDataSegs, &mdei, &musi, NULL);
+ funcMiniDumpWriteDump(proc, procid, file, MiniDumpWithDataSegs, &mdei, &musi, nullptr);
ret = 1;
} else {
ret = -1;
@@ -488,11 +488,11 @@ static void ShowCrashlogWindow();
* Stack pointer for use when 'starting' the crash handler.
* Not static as gcc's inline assembly needs it that way.
*/
-void *_safe_esp = NULL;
+void *_safe_esp = nullptr;
static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
{
- if (CrashLogWindows::current != NULL) {
+ if (CrashLogWindows::current != nullptr) {
CrashLog::AfterCrashLogCleanup();
ExitProcess(2);
}
@@ -501,7 +501,7 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
static const TCHAR _emergency_crash[] =
_T("A serious fault condition occurred in the game. The game will shut down.\n")
_T("As you loaded an emergency savegame no crash information will be generated.\n");
- MessageBox(NULL, _emergency_crash, _T("Fatal Application Failure"), MB_ICONERROR);
+ MessageBox(nullptr, _emergency_crash, _T("Fatal Application Failure"), MB_ICONERROR);
ExitProcess(3);
}
@@ -510,7 +510,7 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
_T("A serious fault condition occurred in the game. The game will shut down.\n")
_T("As you loaded an savegame for which you do not have the required NewGRFs\n")
_T("no crash information will be generated.\n");
- MessageBox(NULL, _saveload_crash, _T("Fatal Application Failure"), MB_ICONERROR);
+ MessageBox(nullptr, _saveload_crash, _T("Fatal Application Failure"), MB_ICONERROR);
ExitProcess(3);
}
@@ -525,7 +525,7 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
/* Close any possible log files */
CloseConsoleLogIfActive();
- if ((VideoDriver::GetInstance() == NULL || VideoDriver::GetInstance()->HasGUI()) && _safe_esp != NULL) {
+ if ((VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) && _safe_esp != nullptr) {
#ifdef _M_AMD64
ep->ContextRecord->Rip = (DWORD64)ShowCrashlogWindow;
ep->ContextRecord->Rsp = (DWORD64)_safe_esp;
@@ -542,7 +542,7 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
static void CDECL CustomAbort(int signal)
{
- RaiseException(0xE1212012, 0, 0, NULL);
+ RaiseException(0xE1212012, 0, 0, nullptr);
}
/* static */ void CrashLog::InitialiseCrashLog()
@@ -693,5 +693,5 @@ static void ShowCrashlogWindow()
{
ShowCursor(TRUE);
ShowWindow(GetActiveWindow(), FALSE);
- DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc);
+ DialogBox(GetModuleHandle(nullptr), MAKEINTRESOURCE(100), nullptr, CrashDialogFunc);
}
diff --git a/src/os/windows/string_uniscribe.cpp b/src/os/windows/string_uniscribe.cpp
index 5abe848bd..8c4e11d3f 100644
--- a/src/os/windows/string_uniscribe.cpp
+++ b/src/os/windows/string_uniscribe.cpp
@@ -86,7 +86,7 @@ public:
int num_glyphs;
Font *font;
- mutable int *glyph_to_char = NULL;
+ mutable int *glyph_to_char = nullptr;
public:
UniscribeVisualRun(const UniscribeRun &range, int x);
@@ -139,9 +139,9 @@ public:
void UniscribeResetScriptCache(FontSize size)
{
- if (_script_cache[size] != NULL) {
+ if (_script_cache[size] != nullptr) {
ScriptFreeCache(&_script_cache[size]);
- _script_cache[size] = NULL;
+ _script_cache[size] = nullptr;
}
}
@@ -168,9 +168,9 @@ static bool UniscribeShapeRun(const UniscribeParagraphLayoutFactory::CharType *b
/* The char-to-glyph array is the same size as the input. */
range.char_to_glyph.resize(range.len);
- HDC temp_dc = NULL;
- HFONT old_font = NULL;
- HFONT cur_font = NULL;
+ HDC temp_dc = nullptr;
+ HFONT old_font = nullptr;
+ HFONT cur_font = nullptr;
while (true) {
/* Shape the text run by determining the glyphs needed for display. */
@@ -217,9 +217,9 @@ static bool UniscribeShapeRun(const UniscribeParagraphLayoutFactory::CharType *b
} else if (hr == E_PENDING) {
/* Glyph data is not in cache, load native font. */
cur_font = HFontFromFont(range.font);
- if (cur_font == NULL) return false; // Sorry, no dice.
+ if (cur_font == nullptr) return false; // Sorry, no dice.
- temp_dc = CreateCompatibleDC(NULL);
+ temp_dc = CreateCompatibleDC(nullptr);
SetMapMode(temp_dc, MM_TEXT);
old_font = (HFONT)SelectObject(temp_dc, cur_font);
} else if (hr == USP_E_SCRIPT_NOT_IN_FONT && range.sa.eScript != SCRIPT_UNDEFINED) {
@@ -227,19 +227,19 @@ static bool UniscribeShapeRun(const UniscribeParagraphLayoutFactory::CharType *b
range.sa.eScript = SCRIPT_UNDEFINED;
} else {
/* Some unknown other error. */
- if (temp_dc != NULL) {
+ if (temp_dc != nullptr) {
SelectObject(temp_dc, old_font);
DeleteObject(cur_font);
- ReleaseDC(NULL, temp_dc);
+ ReleaseDC(nullptr, temp_dc);
}
return false;
}
}
- if (temp_dc != NULL) {
+ if (temp_dc != nullptr) {
SelectObject(temp_dc, old_font);
DeleteObject(cur_font);
- ReleaseDC(NULL, temp_dc);
+ ReleaseDC(nullptr, temp_dc);
}
return true;
@@ -280,16 +280,16 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
{
int32 length = buff_end - buff;
/* Can't layout an empty string. */
- if (length == 0) return NULL;
+ if (length == 0) return nullptr;
/* Can't layout our in-built sprite fonts. */
for (auto const &pair : fontMapping) {
- if (pair.second->fc->IsBuiltInFont()) return NULL;
+ if (pair.second->fc->IsBuiltInFont()) return nullptr;
}
/* Itemize text. */
std::vector<SCRIPT_ITEM> items = UniscribeItemizeString(buff, length);
- if (items.size() == 0) return NULL;
+ if (items.size() == 0) return nullptr;
/* Build ranges from the items and the font map. A range is a run of text
* that is part of a single item and formatted using a single font style. */
@@ -306,7 +306,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
/* Shape the range. */
if (!UniscribeShapeRun(buff, ranges.back())) {
- return NULL;
+ return nullptr;
}
/* If we are at the end of the current item, advance to the next item. */
@@ -323,7 +323,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
std::vector<UniscribeRun>::iterator start_run = this->cur_range;
std::vector<UniscribeRun>::iterator last_run = this->cur_range;
- if (start_run == this->ranges.end()) return NULL;
+ if (start_run == this->ranges.end()) return nullptr;
/* Add remaining width of the first run if it is a broken run. */
int cur_width = 0;
@@ -355,7 +355,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
int last_cluster = this->cur_range_offset + 1;
for (std::vector<UniscribeRun>::iterator r = start_run; r != last_run; r++) {
log_attribs.resize(r->pos - start_run->pos + r->len);
- if (FAILED(ScriptBreak(this->text_buffer + r->pos + start_offs, r->len - start_offs, &r->sa, &log_attribs[r->pos - start_run->pos + start_offs]))) return NULL;
+ if (FAILED(ScriptBreak(this->text_buffer + r->pos + start_offs, r->len - start_offs, &r->sa, &log_attribs[r->pos - start_run->pos + start_offs]))) return nullptr;
std::vector<int> dx(r->len);
ScriptGetLogicalWidths(&r->sa, r->len, (int)r->glyphs.size(), &r->advances[0], &r->char_to_glyph[0], &r->vis_attribs[0], &dx[0]);
@@ -401,7 +401,7 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
bidi_level.push_back(r->sa.s.uBidiLevel);
}
std::vector<INT> vis_to_log(bidi_level.size());
- if (FAILED(ScriptLayout((int)bidi_level.size(), &bidi_level[0], &vis_to_log[0], NULL))) return NULL;
+ if (FAILED(ScriptLayout((int)bidi_level.size(), &bidi_level[0], &vis_to_log[0], nullptr))) return nullptr;
/* Create line. */
std::unique_ptr<UniscribeLine> line(new UniscribeLine());
@@ -415,14 +415,14 @@ static std::vector<SCRIPT_ITEM> UniscribeItemizeString(UniscribeParagraphLayoutF
if (i_run == last_run - 1 && remaing_offset < (last_run - 1)->len) {
run.len = remaing_offset - 1;
- if (!UniscribeShapeRun(this->text_buffer, run)) return NULL;
+ if (!UniscribeShapeRun(this->text_buffer, run)) return nullptr;
}
if (i_run == start_run && this->cur_range_offset > 0) {
assert(run.len - this->cur_range_offset > 0);
run.pos += this->cur_range_offset;
run.len -= this->cur_range_offset;
- if (!UniscribeShapeRun(this->text_buffer, run)) return NULL;
+ if (!UniscribeShapeRun(this->text_buffer, run)) return nullptr;
}
line->emplace_back(run, cur_pos);
@@ -490,12 +490,12 @@ UniscribeParagraphLayout::UniscribeVisualRun::UniscribeVisualRun(UniscribeVisual
start_pos(other.start_pos), total_advance(other.total_advance), num_glyphs(other.num_glyphs), font(other.font)
{
this->glyph_to_char = other.glyph_to_char;
- other.glyph_to_char = NULL;
+ other.glyph_to_char = nullptr;
}
const int *UniscribeParagraphLayout::UniscribeVisualRun::GetGlyphToCharMap() const
{
- if (this->glyph_to_char == NULL) {
+ if (this->glyph_to_char == nullptr) {
this->glyph_to_char = CallocT<int>(this->GetGlyphCount());
/* The char to glyph array contains the first glyph index of the cluster that is associated
diff --git a/src/os/windows/win32.cpp b/src/os/windows/win32.cpp
index ae78407ac..b0495d64d 100644
--- a/src/os/windows/win32.cpp
+++ b/src/os/windows/win32.cpp
@@ -61,14 +61,14 @@ bool LoadLibraryList(Function proc[], const char *dll)
HMODULE lib;
lib = LoadLibrary(MB_TO_WIDE(dll));
- if (lib == NULL) return false;
+ if (lib == nullptr) return false;
for (;;) {
FARPROC p;
while (*dll++ != '\0') { /* Nothing */ }
if (*dll == '\0') break;
p = GetProcAddress(lib, dll);
- if (p == NULL) return false;
+ if (p == nullptr) return false;
*proc++ = (Function)p;
}
dll++;
@@ -84,7 +84,7 @@ void ShowOSErrorBox(const char *buf, bool system)
void OSOpenBrowser(const char *url)
{
- ShellExecute(GetActiveWindow(), _T("open"), OTTD2FS(url), NULL, NULL, SW_SHOWNORMAL);
+ ShellExecute(GetActiveWindow(), _T("open"), OTTD2FS(url), nullptr, nullptr, SW_SHOWNORMAL);
}
/* Code below for windows version of opendir/readdir/closedir copied and
@@ -142,7 +142,7 @@ DIR *opendir(const TCHAR *path)
if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) {
d = dir_calloc();
- if (d != NULL) {
+ if (d != nullptr) {
TCHAR search_path[MAX_PATH];
bool slash = path[_tcslen(path) - 1] == '\\';
@@ -158,14 +158,14 @@ DIR *opendir(const TCHAR *path)
d->at_first_entry = true;
} else {
dir_free(d);
- d = NULL;
+ d = nullptr;
}
} else {
errno = ENOMEM;
}
} else {
/* path not found or not a directory */
- d = NULL;
+ d = nullptr;
errno = ENOENT;
}
@@ -179,11 +179,11 @@ struct dirent *readdir(DIR *d)
if (d->at_first_entry) {
/* the directory was empty when opened */
- if (d->hFind == INVALID_HANDLE_VALUE) return NULL;
+ if (d->hFind == INVALID_HANDLE_VALUE) return nullptr;
d->at_first_entry = false;
} else if (!FindNextFile(d->hFind, &d->fd)) { // determine cause and bail
if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err);
- return NULL;
+ return nullptr;
}
/* This entry has passed all checks; return information about it.
@@ -251,7 +251,7 @@ bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
DWORD spc, bps, nfc, tnc;
_sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]);
- if (tot != NULL && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) {
+ if (tot != nullptr && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) {
*tot = ((spc * bps) * (uint64)nfc);
retval = true;
}
@@ -339,9 +339,9 @@ void CreateConsole()
*stderr = *fdopen(2, "w" );
#endif
- setvbuf(stdin, NULL, _IONBF, 0);
- setvbuf(stdout, NULL, _IONBF, 0);
- setvbuf(stderr, NULL, _IONBF, 0);
+ setvbuf(stdin, nullptr, _IONBF, 0);
+ setvbuf(stdout, nullptr, _IONBF, 0);
+ setvbuf(stderr, nullptr, _IONBF, 0);
}
/** Temporary pointer to get the help message to the window */
@@ -398,7 +398,7 @@ void ShowInfo(const char *str)
* ShowInfo are much shorter, or so long they need this way of displaying
* them anyway. */
_help_msg = str;
- DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(101), NULL, HelpDialogFunc);
+ DialogBox(GetModuleHandle(nullptr), MAKEINTRESOURCE(101), nullptr, HelpDialogFunc);
} else {
/* We need to put the text in a separate buffer because the default
* buffer in OTTD2FS might not be large enough (512 chars). */
@@ -459,28 +459,28 @@ void DetermineBasePaths(const char *exe)
char tmp[MAX_PATH];
TCHAR path[MAX_PATH];
#ifdef WITH_PERSONAL_DIR
- if (SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path))) {
+ if (SUCCEEDED(OTTDSHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, SHGFP_TYPE_CURRENT, path))) {
strecpy(tmp, FS2OTTD(path), lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
strecat(tmp, PERSONAL_DIR, lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_PERSONAL_DIR] = stredup(tmp);
} else {
- _searchpaths[SP_PERSONAL_DIR] = NULL;
+ _searchpaths[SP_PERSONAL_DIR] = nullptr;
}
- if (SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path))) {
+ if (SUCCEEDED(OTTDSHGetFolderPath(nullptr, CSIDL_COMMON_DOCUMENTS, nullptr, SHGFP_TYPE_CURRENT, path))) {
strecpy(tmp, FS2OTTD(path), lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
strecat(tmp, PERSONAL_DIR, lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_SHARED_DIR] = stredup(tmp);
} else {
- _searchpaths[SP_SHARED_DIR] = NULL;
+ _searchpaths[SP_SHARED_DIR] = nullptr;
}
#else
- _searchpaths[SP_PERSONAL_DIR] = NULL;
- _searchpaths[SP_SHARED_DIR] = NULL;
+ _searchpaths[SP_PERSONAL_DIR] = nullptr;
+ _searchpaths[SP_SHARED_DIR] = nullptr;
#endif
/* Get the path to working directory of OpenTTD */
@@ -488,15 +488,15 @@ void DetermineBasePaths(const char *exe)
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_WORKING_DIR] = stredup(tmp);
- if (!GetModuleFileName(NULL, path, lengthof(path))) {
+ if (!GetModuleFileName(nullptr, path, lengthof(path))) {
DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
- _searchpaths[SP_BINARY_DIR] = NULL;
+ _searchpaths[SP_BINARY_DIR] = nullptr;
} else {
TCHAR exec_dir[MAX_PATH];
_tcsncpy(path, convert_to_fs(exe, path, lengthof(path)), lengthof(path));
- if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, NULL)) {
+ if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, nullptr)) {
DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
- _searchpaths[SP_BINARY_DIR] = NULL;
+ _searchpaths[SP_BINARY_DIR] = nullptr;
} else {
strecpy(tmp, convert_from_fs(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
char *s = strrchr(tmp, PATHSEPCHAR);
@@ -505,8 +505,8 @@ void DetermineBasePaths(const char *exe)
}
}
- _searchpaths[SP_INSTALLATION_DIR] = NULL;
- _searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
+ _searchpaths[SP_INSTALLATION_DIR] = nullptr;
+ _searchpaths[SP_APPLICATION_BUNDLE_DIR] = nullptr;
}
@@ -516,18 +516,18 @@ bool GetClipboardContents(char *buffer, const char *last)
const char *ptr;
if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
- OpenClipboard(NULL);
+ OpenClipboard(nullptr);
cbuf = GetClipboardData(CF_UNICODETEXT);
ptr = (const char*)GlobalLock(cbuf);
- int out_len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)ptr, -1, buffer, (last - buffer) + 1, NULL, NULL);
+ int out_len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)ptr, -1, buffer, (last - buffer) + 1, nullptr, nullptr);
GlobalUnlock(cbuf);
CloseClipboard();
if (out_len == 0) return false;
#if !defined(UNICODE)
} else if (IsClipboardFormatAvailable(CF_TEXT)) {
- OpenClipboard(NULL);
+ OpenClipboard(nullptr);
cbuf = GetClipboardData(CF_TEXT);
ptr = (const char*)GlobalLock(cbuf);
@@ -596,7 +596,7 @@ char *convert_from_fs(const TCHAR *name, char *utf8_buf, size_t buflen)
const WCHAR *wide_buf = name;
#else
/* Convert string from the local codepage to UTF-16. */
- int wide_len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
+ int wide_len = MultiByteToWideChar(CP_ACP, 0, name, -1, nullptr, 0);
if (wide_len == 0) {
utf8_buf[0] = '\0';
return utf8_buf;
@@ -607,7 +607,7 @@ char *convert_from_fs(const TCHAR *name, char *utf8_buf, size_t buflen)
#endif
/* Convert UTF-16 string to UTF-8. */
- int len = WideCharToMultiByte(CP_UTF8, 0, wide_buf, -1, utf8_buf, (int)buflen, NULL, NULL);
+ int len = WideCharToMultiByte(CP_UTF8, 0, wide_buf, -1, utf8_buf, (int)buflen, nullptr, nullptr);
if (len == 0) utf8_buf[0] = '\0';
return utf8_buf;
@@ -630,7 +630,7 @@ TCHAR *convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool co
int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, system_buf, (int)buflen);
if (len == 0) system_buf[0] = '\0';
#else
- int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
+ int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, nullptr, 0);
if (len == 0) {
system_buf[0] = '\0';
return system_buf;
@@ -639,7 +639,7 @@ TCHAR *convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool co
WCHAR *wide_buf = AllocaM(WCHAR, len);
MultiByteToWideChar(CP_UTF8, 0, name, -1, wide_buf, len);
- len = WideCharToMultiByte(console_cp ? CP_OEMCP : CP_ACP, 0, wide_buf, len, system_buf, (int)buflen, NULL, NULL);
+ len = WideCharToMultiByte(console_cp ? CP_OEMCP : CP_ACP, 0, wide_buf, len, system_buf, (int)buflen, nullptr, nullptr);
if (len == 0) system_buf[0] = '\0';
#endif
@@ -654,7 +654,7 @@ TCHAR *convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool co
*/
HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
{
- static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = NULL;
+ static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = nullptr;
static bool first_time = true;
/* We only try to load the library one time; if it fails, it fails */
@@ -674,7 +674,7 @@ HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags,
first_time = false;
}
- if (SHGetFolderPath != NULL) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath);
+ if (SHGetFolderPath != nullptr) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath);
/* SHGetFolderPath doesn't exist, try a more conservative approach,
* eg environment variables. This is only included for legacy modes
@@ -698,7 +698,7 @@ HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags,
HKEY key;
if (RegOpenKeyEx(csidl == CSIDL_PERSONAL ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, REGSTR_PATH_SPECIAL_FOLDERS, 0, KEY_READ, &key) != ERROR_SUCCESS) break;
DWORD len = MAX_PATH;
- ret = RegQueryValueEx(key, csidl == CSIDL_PERSONAL ? _T("Personal") : _T("Common Documents"), NULL, NULL, (LPBYTE)pszPath, &len);
+ ret = RegQueryValueEx(key, csidl == CSIDL_PERSONAL ? _T("Personal") : _T("Common Documents"), nullptr, nullptr, (LPBYTE)pszPath, &len);
RegCloseKey(key);
if (ret == ERROR_SUCCESS) return (HRESULT)0;
break;
@@ -718,7 +718,7 @@ const char *GetCurrentLocale(const char *)
if (GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 ||
GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) {
/* Unable to retrieve the locale. */
- return NULL;
+ return nullptr;
}
/* Format it as 'en_us'. */
static char retbuf[6] = {lang[0], lang[1], '_', country[0], country[1], 0};
@@ -750,7 +750,7 @@ void Win32SetCurrentLocaleName(const char *iso_code)
int OTTDStringCompare(const char *s1, const char *s2)
{
typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
- static PFNCOMPARESTRINGEX _CompareStringEx = NULL;
+ static PFNCOMPARESTRINGEX _CompareStringEx = nullptr;
static bool first_time = true;
#ifndef SORT_DIGITSASNUMBERS
@@ -765,10 +765,10 @@ int OTTDStringCompare(const char *s1, const char *s2)
first_time = false;
}
- if (_CompareStringEx != NULL) {
+ if (_CompareStringEx != nullptr) {
/* CompareStringEx takes UTF-16 strings, even in ANSI-builds. */
- int len_s1 = MultiByteToWideChar(CP_UTF8, 0, s1, -1, NULL, 0);
- int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2, -1, NULL, 0);
+ int len_s1 = MultiByteToWideChar(CP_UTF8, 0, s1, -1, nullptr, 0);
+ int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2, -1, nullptr, 0);
if (len_s1 != 0 && len_s2 != 0) {
LPWSTR str_s1 = AllocaM(WCHAR, len_s1);
@@ -777,7 +777,7 @@ int OTTDStringCompare(const char *s1, const char *s2)
MultiByteToWideChar(CP_UTF8, 0, s1, -1, str_s1, len_s1);
MultiByteToWideChar(CP_UTF8, 0, s2, -1, str_s2, len_s2);
- int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1, -1, str_s2, -1, NULL, NULL, 0);
+ int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1, -1, str_s2, -1, nullptr, nullptr, 0);
if (result != 0) return result;
}
}
diff --git a/src/osk_gui.cpp b/src/osk_gui.cpp
index de8be373e..a706a9160 100644
--- a/src/osk_gui.cpp
+++ b/src/osk_gui.cpp
@@ -46,10 +46,10 @@ struct OskWindow : public Window {
OskWindow(WindowDesc *desc, Window *parent, int button) : Window(desc)
{
this->parent = parent;
- assert(parent != NULL);
+ assert(parent != nullptr);
NWidgetCore *par_wid = parent->GetWidget<NWidgetCore>(button);
- assert(par_wid != NULL);
+ assert(par_wid != nullptr);
assert(parent->querystrings.Contains(button));
this->qs = parent->querystrings.Find(button)->second;
@@ -166,7 +166,7 @@ struct OskWindow : public Window {
break;
case WID_OSK_OK:
- if (this->qs->orig == NULL || strcmp(this->qs->text.buf, this->qs->orig) != 0) {
+ if (this->qs->orig == nullptr || strcmp(this->qs->text.buf, this->qs->orig) != 0) {
/* pass information by simulating a button press on parent window */
if (this->qs->ok_button >= 0) {
this->parent->OnClick(pt, this->qs->ok_button, 1);
@@ -427,7 +427,7 @@ void ShowOnScreenKeyboard(Window *parent, int button)
void UpdateOSKOriginalText(const Window *parent, int button)
{
OskWindow *osk = dynamic_cast<OskWindow *>(FindWindowById(WC_OSK, 0));
- if (osk == NULL || osk->parent != parent || osk->text_btn != button) return;
+ if (osk == nullptr || osk->parent != parent || osk->text_btn != button) return;
free(osk->orig_str_buf);
osk->orig_str_buf = stredup(osk->qs->text.buf);
@@ -444,5 +444,5 @@ void UpdateOSKOriginalText(const Window *parent, int button)
bool IsOSKOpenedFor(const Window *w, int button)
{
OskWindow *osk = dynamic_cast<OskWindow *>(FindWindowById(WC_OSK, 0));
- return osk != NULL && osk->parent == w && osk->text_btn == button;
+ return osk != nullptr && osk->parent == w && osk->text_btn == button;
}
diff --git a/src/pathfinder/follow_track.hpp b/src/pathfinder/follow_track.hpp
index 2bbad8d70..999f7f94d 100644
--- a/src/pathfinder/follow_track.hpp
+++ b/src/pathfinder/follow_track.hpp
@@ -53,27 +53,27 @@ struct CFollowTrackT
CPerformanceTimer *m_pPerf;
RailTypes m_railtypes;
- inline CFollowTrackT(const VehicleType *v = NULL, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = NULL)
+ inline CFollowTrackT(const VehicleType *v = nullptr, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = nullptr)
{
Init(v, railtype_override, pPerf);
}
- inline CFollowTrackT(Owner o, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = NULL)
+ inline CFollowTrackT(Owner o, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = nullptr)
{
- m_veh = NULL;
+ m_veh = nullptr;
Init(o, railtype_override, pPerf);
}
inline void Init(const VehicleType *v, RailTypes railtype_override, CPerformanceTimer *pPerf)
{
- assert(!IsRailTT() || (v != NULL && v->type == VEH_TRAIN));
+ assert(!IsRailTT() || (v != nullptr && v->type == VEH_TRAIN));
m_veh = v;
- Init(v != NULL ? v->owner : INVALID_OWNER, IsRailTT() && railtype_override == INVALID_RAILTYPES ? Train::From(v)->compatible_railtypes : railtype_override, pPerf);
+ Init(v != nullptr ? v->owner : INVALID_OWNER, IsRailTT() && railtype_override == INVALID_RAILTYPES ? Train::From(v)->compatible_railtypes : railtype_override, pPerf);
}
inline void Init(Owner o, RailTypes railtype_override, CPerformanceTimer *pPerf)
{
- assert(!IsRoadTT() || m_veh != NULL);
+ assert(!IsRoadTT() || m_veh != nullptr);
assert(!IsRailTT() || railtype_override != INVALID_RAILTYPES);
m_veh_owner = o;
m_pPerf = pPerf;
@@ -126,7 +126,7 @@ struct CFollowTrackT
m_err = EC_NONE;
assert(
((TrackStatusToTrackdirBits(
- GetTileTrackStatus(m_old_tile, TT(), (IsRoadTT() && m_veh != NULL) ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0)
+ GetTileTrackStatus(m_old_tile, TT(), (IsRoadTT() && m_veh != nullptr) ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0)
) & TrackdirToTrackdirBits(m_old_td)) != 0) ||
(IsTram() && GetSingleTramBit(m_old_tile) != INVALID_DIAGDIR) // Disable the assertion for single tram bits
);
@@ -447,7 +447,7 @@ protected:
public:
/** Helper for pathfinders - get min/max speed on the m_old_tile/m_old_td */
- int GetSpeedLimit(int *pmin_speed = NULL) const
+ int GetSpeedLimit(int *pmin_speed = nullptr) const
{
int min_speed = 0;
int max_speed = INT_MAX; // no limit
@@ -465,7 +465,7 @@ public:
}
/* if min speed was requested, return it */
- if (pmin_speed != NULL) *pmin_speed = min_speed;
+ if (pmin_speed != nullptr) *pmin_speed = min_speed;
return max_speed;
}
};
diff --git a/src/pathfinder/npf/aystar.cpp b/src/pathfinder/npf/aystar.cpp
index beac06291..addfc4930 100644
--- a/src/pathfinder/npf/aystar.cpp
+++ b/src/pathfinder/npf/aystar.cpp
@@ -32,7 +32,7 @@
/**
* This looks in the hash whether a node exists in the closed list.
* @param node Node to search.
- * @return The #PathNode if it is available, else \c NULL
+ * @return The #PathNode if it is available, else \c nullptr
*/
PathNode *AyStar::ClosedListIsInList(const AyStarNode *node)
{
@@ -55,7 +55,7 @@ void AyStar::ClosedListAdd(const PathNode *node)
/**
* Check whether a node is in the open list.
* @param node Node to search.
- * @return If the node is available, it is returned, else \c NULL is returned.
+ * @return If the node is available, it is returned, else \c nullptr is returned.
*/
OpenListNode *AyStar::OpenListIsInList(const AyStarNode *node)
{
@@ -65,13 +65,13 @@ OpenListNode *AyStar::OpenListIsInList(const AyStarNode *node)
/**
* Gets the best node from the open list.
* It deletes the returned node from the open list.
- * @returns the best node available, or \c NULL of none is found.
+ * @returns the best node available, or \c nullptr of none is found.
*/
OpenListNode *AyStar::OpenListPop()
{
/* Return the item the Queue returns.. the best next OpenList item. */
OpenListNode *res = (OpenListNode*)this->openlist_queue.Pop();
- if (res != NULL) {
+ if (res != nullptr) {
this->openlist_hash.DeleteValue(res->path.node.tile, res->path.node.direction);
}
@@ -105,7 +105,7 @@ void AyStar::CheckTile(AyStarNode *current, OpenListNode *parent)
OpenListNode *check;
/* Check the new node against the ClosedList */
- if (this->ClosedListIsInList(current) != NULL) return;
+ if (this->ClosedListIsInList(current) != nullptr) return;
/* Calculate the G-value for this node */
new_g = this->CalculateG(this, current, parent);
@@ -131,7 +131,7 @@ void AyStar::CheckTile(AyStarNode *current, OpenListNode *parent)
/* Check if this item is already in the OpenList */
check = this->OpenListIsInList(current);
- if (check != NULL) {
+ if (check != nullptr) {
uint i;
/* Yes, check if this g value is lower.. */
if (new_g > check->g) return;
@@ -167,11 +167,11 @@ int AyStar::Loop()
/* Get the best node from OpenList */
OpenListNode *current = this->OpenListPop();
/* If empty, drop an error */
- if (current == NULL) return AYSTAR_EMPTY_OPENLIST;
+ if (current == nullptr) return AYSTAR_EMPTY_OPENLIST;
/* Check for end node and if found, return that code */
if (this->EndNodeCheck(this, current) == AYSTAR_FOUND_END_NODE && !CheckIgnoreFirstTile(&current->path)) {
- if (this->FoundEndNode != NULL) {
+ if (this->FoundEndNode != nullptr) {
this->FoundEndNode(this, current);
}
free(current);
@@ -285,7 +285,7 @@ void AyStar::AddStartNode(AyStarNode *start_node, uint g)
printf("[AyStar] Starting A* Algorithm from node (%d, %d, %d)\n",
TileX(start_node->tile), TileY(start_node->tile), start_node->direction);
#endif
- this->OpenListAdd(NULL, start_node, 0, g);
+ this->OpenListAdd(nullptr, start_node, 0, g);
}
/**
diff --git a/src/pathfinder/npf/npf.cpp b/src/pathfinder/npf/npf.cpp
index 32c6e982d..2863e7881 100644
--- a/src/pathfinder/npf/npf.cpp
+++ b/src/pathfinder/npf/npf.cpp
@@ -103,7 +103,7 @@ static inline void NPFSetFlag(AyStarNode *node, NPFNodeFlag flag, bool value)
bool CheckIgnoreFirstTile(const PathNode *node)
{
- return (node->parent == NULL && HasBit(node->node.user_data[NPF_NODE_FLAGS], NPF_FLAG_IGNORE_START_TILE));
+ return (node->parent == nullptr && HasBit(node->node.user_data[NPF_NODE_FLAGS], NPF_FLAG_IGNORE_START_TILE));
}
/**
@@ -192,7 +192,7 @@ static int32 NPFCalcStationOrTileHeuristic(AyStar *as, AyStarNode *current, Open
* choice */
static void NPFFillTrackdirChoice(AyStarNode *current, OpenListNode *parent)
{
- if (parent->path.parent == NULL) {
+ if (parent->path.parent == nullptr) {
Trackdir trackdir = current->direction;
/* This is a first order decision, so we'd better save the
* direction we chose */
@@ -584,7 +584,7 @@ static const PathNode *FindSafePosition(PathNode *path, const Train *v)
/* If there is no signal, reserve the whole path. */
PathNode *sig = path;
- for (; path->parent != NULL; path = path->parent) {
+ for (; path->parent != nullptr; path = path->parent) {
if (IsSafeWaitingPosition(v, path->node.tile, path->node.direction, true, _settings_game.pf.forbid_90_deg)) {
sig = path;
}
@@ -625,7 +625,7 @@ static void NPFSaveTargetData(AyStar *as, OpenListNode *current)
ftd->node = current->path.node;
ftd->res_okay = false;
- if (as->user_target != NULL && ((NPFFindStationOrTileData*)as->user_target)->reserve_path && user->type == TRANSPORT_RAIL) {
+ if (as->user_target != nullptr && ((NPFFindStationOrTileData*)as->user_target)->reserve_path && user->type == TRANSPORT_RAIL) {
/* Path reservation is requested. */
const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
@@ -647,7 +647,7 @@ static void NPFSaveTargetData(AyStar *as, OpenListNode *current)
if (!IsWaitingPositionFree(v, target->node.tile, target->node.direction, _settings_game.pf.forbid_90_deg)) return;
}
- for (const PathNode *cur = target; cur->parent != NULL; cur = cur->parent) {
+ for (const PathNode *cur = target; cur->parent != nullptr; cur = cur->parent) {
if (!TryReserveRailTrack(cur->node.tile, TrackdirToTrack(cur->node.direction))) {
/* Reservation failed, undo. */
ClearPathReservation(target, cur);
@@ -957,7 +957,7 @@ static void NPFFollowTrack(AyStar *aystar, OpenListNode *current)
/*
* Plan a route to the specified target (which is checked by target_proc),
- * from start1 and if not NULL, from start2 as well. The type of transport we
+ * from start1 and if not nullptr, from start2 as well. The type of transport we
* are checking is in type. reverse_penalty is applied to all routes that
* originate from the second start node.
* When we are looking for one specific target (optionally multiple tiles), we
@@ -989,7 +989,7 @@ static NPFFoundTargetData NPFRouteInternal(AyStarNode *start1, bool ignore_start
NPFSetFlag(start1, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile1);
NPFSetFlag(start1, NPF_FLAG_IGNORE_RESERVED, ignore_reserved);
_npf_aystar.AddStartNode(start1, 0);
- if (start2 != NULL) {
+ if (start2 != nullptr) {
start2->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
start2->user_data[NPF_NODE_FLAGS] = 0;
NPFSetFlag(start2, NPF_FLAG_IGNORE_START_TILE, ignore_start_tile2);
@@ -1017,10 +1017,10 @@ static NPFFoundTargetData NPFRouteInternal(AyStarNode *start1, bool ignore_start
assert(r != AYSTAR_STILL_BUSY);
if (result.best_bird_dist != 0) {
- if (target != NULL) {
+ if (target != nullptr) {
DEBUG(npf, 1, "Could not find route to tile 0x%X from 0x%X.", target->dest_coords, start1->tile);
} else {
- /* Assumption: target == NULL, so we are looking for a depot */
+ /* Assumption: target == nullptr, so we are looking for a depot */
DEBUG(npf, 1, "Could not find route to a depot from tile 0x%X.", start1->tile);
}
@@ -1041,7 +1041,7 @@ static NPFFoundTargetData NPFRouteToStationOrTileTwoWay(TileIndex tile1, Trackdi
start1.direction = trackdir1;
start2.direction = trackdir2;
- return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindStationOrTile, NPFCalcStationOrTileHeuristic, user, 0);
+ return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : nullptr), ignore_start_tile2, target, NPFFindStationOrTile, NPFCalcStationOrTileHeuristic, user, 0);
}
/* Will search from the given tile and direction, for a route to the given
@@ -1069,9 +1069,9 @@ static NPFFoundTargetData NPFRouteToDepotBreadthFirstTwoWay(TileIndex tile1, Tra
start1.direction = trackdir1;
start2.direction = trackdir2;
- /* perform a breadth first search. Target is NULL,
+ /* perform a breadth first search. Target is nullptr,
* since we are just looking for any depot...*/
- return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : NULL), ignore_start_tile2, target, NPFFindDepot, NPFCalcZero, user, reverse_penalty, false, max_penalty);
+ return NPFRouteInternal(&start1, ignore_start_tile1, (IsValidTile(tile2) ? &start2 : nullptr), ignore_start_tile2, target, NPFFindDepot, NPFCalcZero, user, reverse_penalty, false, max_penalty);
}
void InitializeNPF()
@@ -1121,7 +1121,7 @@ FindDepotData NPFRoadVehicleFindNearestDepot(const RoadVehicle *v, int max_penal
Trackdir trackdir = v->GetVehicleTrackdir();
AyStarUserData user = { v->owner, TRANSPORT_ROAD, INVALID_RAILTYPES, v->compatible_roadtypes };
- NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, INVALID_TILE, INVALID_TRACKDIR, false, NULL, &user, 0, max_penalty);
+ NPFFoundTargetData ftd = NPFRouteToDepotBreadthFirstTwoWay(v->tile, trackdir, false, INVALID_TILE, INVALID_TRACKDIR, false, nullptr, &user, 0, max_penalty);
if (ftd.best_bird_dist != 0) return FindDepotData();
@@ -1233,10 +1233,10 @@ bool NPFTrainFindNearestSafeTile(const Train *v, TileIndex tile, Trackdir trackd
RailTypes railtypes = v->compatible_railtypes;
if (override_railtype) railtypes |= GetRailTypeInfo(v->railtype)->compatible_railtypes;
- /* perform a breadth first search. Target is NULL,
+ /* perform a breadth first search. Target is nullptr,
* since we are just looking for any safe tile...*/
AyStarUserData user = { v->owner, TRANSPORT_RAIL, railtypes, ROADTYPES_NONE };
- return NPFRouteInternal(&start1, true, NULL, false, &fstd, NPFFindSafeTile, NPFCalcZero, &user, 0, true).res_okay;
+ return NPFRouteInternal(&start1, true, nullptr, false, &fstd, NPFFindSafeTile, NPFCalcZero, &user, 0, true).res_okay;
}
bool NPFTrainCheckReverse(const Train *v)
@@ -1269,7 +1269,7 @@ Track NPFTrainChooseTrack(const Train *v, bool &path_found, bool reserve_track,
AyStarUserData user = { v->owner, TRANSPORT_RAIL, v->compatible_railtypes, ROADTYPES_NONE };
NPFFoundTargetData ftd = NPFRouteToStationOrTile(origin.tile, origin.trackdir, true, &fstd, &user);
- if (target != NULL) {
+ if (target != nullptr) {
target->tile = ftd.node.tile;
target->trackdir = (Trackdir)ftd.node.direction;
target->okay = ftd.res_okay;
diff --git a/src/pathfinder/npf/queue.cpp b/src/pathfinder/npf/queue.cpp
index 2afb41391..02a195c5d 100644
--- a/src/pathfinder/npf/queue.cpp
+++ b/src/pathfinder/npf/queue.cpp
@@ -37,7 +37,7 @@ void BinaryHeap::Clear(bool free_values)
uint j;
for (i = 0; i < this->blocks; i++) {
- if (this->elements[i] == NULL) {
+ if (this->elements[i] == nullptr) {
/* No more allocated blocks */
break;
}
@@ -55,7 +55,7 @@ void BinaryHeap::Clear(bool free_values)
if (i != 0) {
/* Leave the first block of memory alone */
free(this->elements[i]);
- this->elements[i] = NULL;
+ this->elements[i] = nullptr;
}
}
this->size = 0;
@@ -73,7 +73,7 @@ void BinaryHeap::Free(bool free_values)
this->Clear(free_values);
for (i = 0; i < this->blocks; i++) {
- if (this->elements[i] == NULL) break;
+ if (this->elements[i] == nullptr) break;
free(this->elements[i]);
}
free(this->elements);
@@ -88,7 +88,7 @@ bool BinaryHeap::Push(void *item, int priority)
if (this->size == this->max_size) return false;
assert(this->size < this->max_size);
- if (this->elements[this->size >> BINARY_HEAP_BLOCKSIZE_BITS] == NULL) {
+ if (this->elements[this->size >> BINARY_HEAP_BLOCKSIZE_BITS] == nullptr) {
/* The currently allocated blocks are full, allocate a new one */
assert((this->size & BINARY_HEAP_BLOCKSIZE_MASK) == 0);
this->elements[this->size >> BINARY_HEAP_BLOCKSIZE_BITS] = MallocT<BinaryHeapNode>(BINARY_HEAP_BLOCKSIZE);
@@ -195,7 +195,7 @@ void *BinaryHeap::Pop()
{
void *result;
- if (this->size == 0) return NULL;
+ if (this->size == 0) return nullptr;
/* The best item is always on top, so give that as result */
result = this->GetElement(1).item;
@@ -264,7 +264,7 @@ void Hash::Delete(bool free_values)
/* Free the first value */
if (free_values) free(this->buckets[i].value);
node = this->buckets[i].next;
- while (node != NULL) {
+ while (node != nullptr) {
HashNode *prev = node;
node = node->next;
@@ -296,7 +296,7 @@ void Hash::PrintStatistics() const
const HashNode *node;
used_buckets++;
- for (node = &this->buckets[i]; node != NULL; node = node->next) collision++;
+ for (node = &this->buckets[i]; node != nullptr; node = node->next) collision++;
if (collision > max_collision) max_collision = collision;
}
if (collision >= lengthof(usage)) collision = lengthof(usage) - 1;
@@ -351,7 +351,7 @@ void Hash::Clear(bool free_values)
/* Free the first value */
if (free_values) free(this->buckets[i].value);
node = this->buckets[i].next;
- while (node != NULL) {
+ while (node != nullptr) {
HashNode *prev = node;
node = node->next;
@@ -365,32 +365,32 @@ void Hash::Clear(bool free_values)
/**
* Finds the node that that saves this key pair. If it is not
- * found, returns NULL. If it is found, *prev is set to the
+ * found, returns nullptr. If it is found, *prev is set to the
* node before the one found, or if the node found was the first in the bucket
- * to NULL. If it is not found, *prev is set to the last HashNode in the
- * bucket, or NULL if it is empty. prev can also be NULL, in which case it is
+ * to nullptr. If it is not found, *prev is set to the last HashNode in the
+ * bucket, or nullptr if it is empty. prev can also be nullptr, in which case it is
* not used for output.
*/
HashNode *Hash::FindNode(uint key1, uint key2, HashNode** prev_out) const
{
uint hash = this->hash(key1, key2);
- HashNode *result = NULL;
+ HashNode *result = nullptr;
/* Check if the bucket is empty */
if (!this->buckets_in_use[hash]) {
- if (prev_out != NULL) *prev_out = NULL;
- result = NULL;
+ if (prev_out != nullptr) *prev_out = nullptr;
+ result = nullptr;
/* Check the first node specially */
} else if (this->buckets[hash].key1 == key1 && this->buckets[hash].key2 == key2) {
/* Save the value */
result = this->buckets + hash;
- if (prev_out != NULL) *prev_out = NULL;
+ if (prev_out != nullptr) *prev_out = nullptr;
/* Check all other nodes */
} else {
HashNode *prev = this->buckets + hash;
HashNode *node;
- for (node = prev->next; node != NULL; node = node->next) {
+ for (node = prev->next; node != nullptr; node = node->next) {
if (node->key1 == key1 && node->key2 == key2) {
/* Found it */
result = node;
@@ -398,14 +398,14 @@ HashNode *Hash::FindNode(uint key1, uint key2, HashNode** prev_out) const
}
prev = node;
}
- if (prev_out != NULL) *prev_out = prev;
+ if (prev_out != nullptr) *prev_out = prev;
}
return result;
}
/**
* Deletes the value with the specified key pair from the hash and returns
- * that value. Returns NULL when the value was not present. The value returned
+ * that value. Returns nullptr when the value was not present. The value returned
* is _not_ free()'d!
*/
void *Hash::DeleteValue(uint key1, uint key2)
@@ -414,15 +414,15 @@ void *Hash::DeleteValue(uint key1, uint key2)
HashNode *prev; // Used as output var for below function call
HashNode *node = this->FindNode(key1, key2, &prev);
- if (node == NULL) {
+ if (node == nullptr) {
/* not found */
- result = NULL;
- } else if (prev == NULL) {
+ result = nullptr;
+ } else if (prev == nullptr) {
/* It is in the first node, we can't free that one, so we free
* the next one instead (if there is any)*/
/* Save the value */
result = node->value;
- if (node->next != NULL) {
+ if (node->next != nullptr) {
HashNode *next = node->next;
/* Copy the second to the first */
*node = *next;
@@ -443,20 +443,20 @@ void *Hash::DeleteValue(uint key1, uint key2)
/* Free the node */
free(node);
}
- if (result != NULL) this->size--;
+ if (result != nullptr) this->size--;
return result;
}
/**
* Sets the value associated with the given key pair to the given value.
- * Returns the old value if the value was replaced, NULL when it was not yet present.
+ * Returns the old value if the value was replaced, nullptr when it was not yet present.
*/
void *Hash::Set(uint key1, uint key2, void *value)
{
HashNode *prev;
HashNode *node = this->FindNode(key1, key2, &prev);
- if (node != NULL) {
+ if (node != nullptr) {
/* Found it */
void *result = node->value;
@@ -464,7 +464,7 @@ void *Hash::Set(uint key1, uint key2, void *value)
return result;
}
/* It is not yet present, let's add it */
- if (prev == NULL) {
+ if (prev == nullptr) {
/* The bucket is still empty */
uint hash = this->hash(key1, key2);
this->buckets_in_use[hash] = true;
@@ -474,21 +474,21 @@ void *Hash::Set(uint key1, uint key2, void *value)
node = MallocT<HashNode>(1);
prev->next = node;
}
- node->next = NULL;
+ node->next = nullptr;
node->key1 = key1;
node->key2 = key2;
node->value = value;
this->size++;
- return NULL;
+ return nullptr;
}
/**
- * Gets the value associated with the given key pair, or NULL when it is not
+ * Gets the value associated with the given key pair, or nullptr when it is not
* present.
*/
void *Hash::Get(uint key1, uint key2) const
{
- HashNode *node = this->FindNode(key1, key2, NULL);
+ HashNode *node = this->FindNode(key1, key2, nullptr);
- return (node != NULL) ? node->value : NULL;
+ return (node != nullptr) ? node->value : nullptr;
}
diff --git a/src/pathfinder/pf_performance_timer.hpp b/src/pathfinder/pf_performance_timer.hpp
index 808542d25..c06ef815e 100644
--- a/src/pathfinder/pf_performance_timer.hpp
+++ b/src/pathfinder/pf_performance_timer.hpp
@@ -53,7 +53,7 @@ struct CPerfStartReal
inline CPerfStartReal(CPerformanceTimer& perf) : m_pperf(&perf)
{
- if (m_pperf != NULL) m_pperf->Start();
+ if (m_pperf != nullptr) m_pperf->Start();
}
inline ~CPerfStartReal()
@@ -63,9 +63,9 @@ struct CPerfStartReal
inline void Stop()
{
- if (m_pperf != NULL) {
+ if (m_pperf != nullptr) {
m_pperf->Stop();
- m_pperf = NULL;
+ m_pperf = nullptr;
}
}
};
diff --git a/src/pathfinder/yapf/nodelist.hpp b/src/pathfinder/yapf/nodelist.hpp
index 87e65fd26..45a72efd5 100644
--- a/src/pathfinder/yapf/nodelist.hpp
+++ b/src/pathfinder/yapf/nodelist.hpp
@@ -42,7 +42,7 @@ public:
/** default constructor */
CNodeList_HashTableT() : m_open_queue(2048)
{
- m_new_node = NULL;
+ m_new_node = nullptr;
}
/** destructor */
@@ -65,7 +65,7 @@ public:
/** allocate new data item from m_arr */
inline Titem_ *CreateNewNode()
{
- if (m_new_node == NULL) m_new_node = m_arr.AppendC();
+ if (m_new_node == nullptr) m_new_node = m_arr.AppendC();
return m_new_node;
}
@@ -74,7 +74,7 @@ public:
{
/* for now it is enough to invalidate m_new_node if it is our given node */
if (&item == m_new_node) {
- m_new_node = NULL;
+ m_new_node = nullptr;
}
/* TODO: do we need to store best nodes found in some extra list/array? Probably not now. */
}
@@ -82,11 +82,11 @@ public:
/** insert given item as open node (into m_open and m_open_queue) */
inline void InsertOpenNode(Titem_ &item)
{
- assert(m_closed.Find(item.GetKey()) == NULL);
+ assert(m_closed.Find(item.GetKey()) == nullptr);
m_open.Push(item);
m_open_queue.Include(&item);
if (&item == m_new_node) {
- m_new_node = NULL;
+ m_new_node = nullptr;
}
}
@@ -96,7 +96,7 @@ public:
if (!m_open_queue.IsEmpty()) {
return m_open_queue.Begin();
}
- return NULL;
+ return nullptr;
}
/** remove and return the best open node */
@@ -107,10 +107,10 @@ public:
m_open.Pop(*item);
return item;
}
- return NULL;
+ return nullptr;
}
- /** return the open node specified by a key or NULL if not found */
+ /** return the open node specified by a key or nullptr if not found */
inline Titem_ *FindOpenNode(const Key &key)
{
Titem_ *item = m_open.Find(key);
@@ -129,11 +129,11 @@ public:
/** close node */
inline void InsertClosedNode(Titem_ &item)
{
- assert(m_open.Find(item.GetKey()) == NULL);
+ assert(m_open.Find(item.GetKey()) == nullptr);
m_closed.Push(item);
}
- /** return the closed node specified by a key or NULL if not found */
+ /** return the closed node specified by a key or nullptr if not found */
inline Titem_ *FindClosedNode(const Key &key)
{
Titem_ *item = m_closed.Find(key);
diff --git a/src/pathfinder/yapf/yapf_base.hpp b/src/pathfinder/yapf/yapf_base.hpp
index 6360567bb..5483b9874 100644
--- a/src/pathfinder/yapf/yapf_base.hpp
+++ b/src/pathfinder/yapf/yapf_base.hpp
@@ -81,11 +81,11 @@ public:
public:
/** default constructor */
inline CYapfBaseT()
- : m_pBestDestNode(NULL)
- , m_pBestIntermediateNode(NULL)
+ : m_pBestDestNode(nullptr)
+ , m_pBestIntermediateNode(nullptr)
, m_settings(&_settings_game.pf.yapf)
, m_max_search_nodes(PfGetSettings().max_search_nodes)
- , m_veh(NULL)
+ , m_veh(nullptr)
, m_stats_cost_calcs(0)
, m_stats_cache_hits(0)
, m_num_steps(0)
@@ -131,12 +131,12 @@ public:
for (;;) {
m_num_steps++;
Node *n = m_nodes.GetBestOpenNode();
- if (n == NULL) {
+ if (n == nullptr) {
break;
}
/* if the best open node was worse than the best path found, we can finish */
- if (m_pBestDestNode != NULL && m_pBestDestNode->GetCost() < n->GetCostEstimate()) {
+ if (m_pBestDestNode != nullptr && m_pBestDestNode->GetCost() < n->GetCostEstimate()) {
break;
}
@@ -150,7 +150,7 @@ public:
}
}
- bDestFound &= (m_pBestDestNode != NULL);
+ bDestFound &= (m_pBestDestNode != nullptr);
perf.Stop();
if (_debug_yapf_level >= 2) {
@@ -158,7 +158,7 @@ public:
_total_pf_time_us += t;
if (_debug_yapf_level >= 3) {
- UnitID veh_idx = (m_veh != NULL) ? m_veh->unitnumber : 0;
+ UnitID veh_idx = (m_veh != nullptr) ? m_veh->unitnumber : 0;
char ttc = Yapf().TransportTypeChar();
float cache_hit_ratio = (m_stats_cache_hits == 0) ? 0.0f : ((float)m_stats_cache_hits / (float)(m_stats_cache_hits + m_stats_cost_calcs) * 100.0f);
int cost = bDestFound ? m_pBestDestNode->m_cost : -1;
@@ -180,7 +180,7 @@ public:
*/
inline Node *GetBestNode()
{
- return (m_pBestDestNode != NULL) ? m_pBestDestNode : m_pBestIntermediateNode;
+ return (m_pBestDestNode != nullptr) ? m_pBestDestNode : m_pBestIntermediateNode;
}
/**
@@ -198,7 +198,7 @@ public:
{
Yapf().PfNodeCacheFetch(n);
/* insert the new node only if it is not there */
- if (m_nodes.FindOpenNode(n.m_key) == NULL) {
+ if (m_nodes.FindOpenNode(n.m_key) == nullptr) {
m_nodes.InsertOpenNode(n);
} else {
/* if we are here, it means that node is already there - how it is possible?
@@ -229,7 +229,7 @@ public:
*/
void PruneIntermediateNodeBranch()
{
- while (Yapf().m_pBestIntermediateNode != NULL && (Yapf().m_pBestIntermediateNode->m_segment->m_end_segment_reason & ESRB_CHOICE_FOLLOWS) == 0) {
+ while (Yapf().m_pBestIntermediateNode != nullptr && (Yapf().m_pBestIntermediateNode->m_segment->m_end_segment_reason & ESRB_CHOICE_FOLLOWS) == 0) {
Yapf().m_pBestIntermediateNode = Yapf().m_pBestIntermediateNode->m_parent;
}
}
@@ -262,20 +262,20 @@ public:
/* detect the destination */
bool bDestination = Yapf().PfDetectDestination(n);
if (bDestination) {
- if (m_pBestDestNode == NULL || n < *m_pBestDestNode) {
+ if (m_pBestDestNode == nullptr || n < *m_pBestDestNode) {
m_pBestDestNode = &n;
}
m_nodes.FoundBestNode(n);
return;
}
- if (m_max_search_nodes > 0 && (m_pBestIntermediateNode == NULL || (m_pBestIntermediateNode->GetCostEstimate() - m_pBestIntermediateNode->GetCost()) > (n.GetCostEstimate() - n.GetCost()))) {
+ if (m_max_search_nodes > 0 && (m_pBestIntermediateNode == nullptr || (m_pBestIntermediateNode->GetCostEstimate() - m_pBestIntermediateNode->GetCost()) > (n.GetCostEstimate() - n.GetCost()))) {
m_pBestIntermediateNode = &n;
}
/* check new node against open list */
Node *openNode = m_nodes.FindOpenNode(n.GetKey());
- if (openNode != NULL) {
+ if (openNode != nullptr) {
/* another node exists with the same key in the open list
* is it better than new one? */
if (n.GetCostEstimate() < openNode->GetCostEstimate()) {
@@ -290,7 +290,7 @@ public:
/* check new node against closed list */
Node *closedNode = m_nodes.FindClosedNode(n.GetKey());
- if (closedNode != NULL) {
+ if (closedNode != nullptr) {
/* another node exists with the same key in the closed list
* is it better than new one? */
int node_est = n.GetCostEstimate();
diff --git a/src/pathfinder/yapf/yapf_common.hpp b/src/pathfinder/yapf/yapf_common.hpp
index 8ff69b3f6..95adf37d7 100644
--- a/src/pathfinder/yapf/yapf_common.hpp
+++ b/src/pathfinder/yapf/yapf_common.hpp
@@ -46,7 +46,7 @@ public:
for (TrackdirBits tdb = m_orgTrackdirs; tdb != TRACKDIR_BIT_NONE; tdb = KillFirstBit(tdb)) {
Trackdir td = (Trackdir)FindFirstBit2x64(tdb);
Node &n1 = Yapf().CreateNewNode();
- n1.Set(NULL, m_orgTile, td, is_choice);
+ n1.Set(nullptr, m_orgTile, td, is_choice);
Yapf().AddStartupNode(n1);
}
}
@@ -92,12 +92,12 @@ public:
{
if (m_orgTile != INVALID_TILE && m_orgTd != INVALID_TRACKDIR) {
Node &n1 = Yapf().CreateNewNode();
- n1.Set(NULL, m_orgTile, m_orgTd, false);
+ n1.Set(nullptr, m_orgTile, m_orgTd, false);
Yapf().AddStartupNode(n1);
}
if (m_revTile != INVALID_TILE && m_revTd != INVALID_TRACKDIR) {
Node &n2 = Yapf().CreateNewNode();
- n2.Set(NULL, m_revTile, m_revTd, false);
+ n2.Set(nullptr, m_revTile, m_revTd, false);
n2.m_cost = m_reverse_penalty;
Yapf().AddStartupNode(n2);
}
diff --git a/src/pathfinder/yapf/yapf_costcache.hpp b/src/pathfinder/yapf/yapf_costcache.hpp
index f16d4054c..2cdbf06c0 100644
--- a/src/pathfinder/yapf/yapf_costcache.hpp
+++ b/src/pathfinder/yapf/yapf_costcache.hpp
@@ -143,7 +143,7 @@ struct CSegmentCostCacheT : public CSegmentCostCacheBase {
inline Tsegment& Get(Key &key, bool *found)
{
Tsegment *item = m_map.Find(key);
- if (item == NULL) {
+ if (item == nullptr) {
*found = false;
item = new (m_heap.Append()) Tsegment(key);
m_map.Push(*item);
diff --git a/src/pathfinder/yapf/yapf_costrail.hpp b/src/pathfinder/yapf/yapf_costrail.hpp
index 022b9a167..6c1c3ca7a 100644
--- a/src/pathfinder/yapf/yapf_costrail.hpp
+++ b/src/pathfinder/yapf/yapf_costrail.hpp
@@ -251,7 +251,7 @@ public:
{
int cost = 0;
const Train *v = Yapf().GetVehicle();
- assert(v != NULL);
+ assert(v != nullptr);
assert(v->type == VEH_TRAIN);
assert(v->gcache.cached_total_length != 0);
int missing_platform_length = CeilDiv(v->gcache.cached_total_length, TILE_SIZE) - platform_length;
@@ -285,7 +285,7 @@ public:
CPerfStart perf_cost(Yapf().m_perf_cost);
/* Does the node have some parent node? */
- bool has_parent = (n.m_parent != NULL);
+ bool has_parent = (n.m_parent != nullptr);
/* Do we already have a cached segment? */
CachedData &segment = *n.m_segment;
@@ -606,7 +606,7 @@ no_entry_cost: // jump here at the beginning if the node has no parent (it is th
/* Station platform-length penalty. */
if ((end_segment_reason & ESRB_STATION) != ESRB_NONE) {
const BaseStation *st = BaseStation::GetByTile(n.GetLastTile());
- assert(st != NULL);
+ assert(st != nullptr);
uint platform_length = st->GetPlatformLength(n.GetLastTile(), ReverseDiagDir(TrackdirToExitdir(n.GetLastTrackdir())));
/* Reduce the extra cost caused by passing-station penalty (each station receives it in the segment cost). */
extra_cost -= Yapf().PfGetSettings().rail_station_penalty * platform_length;
@@ -624,7 +624,7 @@ no_entry_cost: // jump here at the beginning if the node has no parent (it is th
inline bool CanUseGlobalCache(Node &n) const
{
return !m_disable_cache
- && (n.m_parent != NULL)
+ && (n.m_parent != nullptr)
&& (n.m_parent->m_num_signals_passed >= m_sig_look_ahead_costs.Size());
}
diff --git a/src/pathfinder/yapf/yapf_node.hpp b/src/pathfinder/yapf/yapf_node.hpp
index e510b2a6c..136ce53bd 100644
--- a/src/pathfinder/yapf/yapf_node.hpp
+++ b/src/pathfinder/yapf/yapf_node.hpp
@@ -72,7 +72,7 @@ struct CYapfNodeT {
inline void Set(Node *parent, TileIndex tile, Trackdir td, bool is_choice)
{
m_key.Set(tile, td);
- m_hash_next = NULL;
+ m_hash_next = nullptr;
m_parent = parent;
m_cost = 0;
m_estimate = 0;
diff --git a/src/pathfinder/yapf/yapf_node_rail.hpp b/src/pathfinder/yapf/yapf_node_rail.hpp
index 180c89439..2dfd6ae7d 100644
--- a/src/pathfinder/yapf/yapf_node_rail.hpp
+++ b/src/pathfinder/yapf/yapf_node_rail.hpp
@@ -83,7 +83,7 @@ struct CYapfRailSegment
, m_last_signal_tile(INVALID_TILE)
, m_last_signal_td(INVALID_TRACKDIR)
, m_end_segment_reason(ESRB_NONE)
- , m_hash_next(NULL)
+ , m_hash_next(nullptr)
{}
inline const Key& GetKey() const
@@ -142,8 +142,8 @@ struct CYapfRailNodeT
inline void Set(CYapfRailNodeT *parent, TileIndex tile, Trackdir td, bool is_choice)
{
base::Set(parent, tile, td, is_choice);
- m_segment = NULL;
- if (parent == NULL) {
+ m_segment = nullptr;
+ if (parent == nullptr) {
m_num_signals_passed = 0;
flags_u.m_inherited_flags = 0;
m_last_red_signal_type = SIGTYPE_NORMAL;
@@ -169,19 +169,19 @@ struct CYapfRailNodeT
inline TileIndex GetLastTile() const
{
- assert(m_segment != NULL);
+ assert(m_segment != nullptr);
return m_segment->m_last_tile;
}
inline Trackdir GetLastTrackdir() const
{
- assert(m_segment != NULL);
+ assert(m_segment != nullptr);
return m_segment->m_last_td;
}
inline void SetLastTileTrackdir(TileIndex tile, Trackdir td)
{
- assert(m_segment != NULL);
+ assert(m_segment != nullptr);
m_segment->m_last_tile = tile;
m_segment->m_last_td = td;
}
diff --git a/src/pathfinder/yapf/yapf_rail.cpp b/src/pathfinder/yapf/yapf_rail.cpp
index d3f8e8aee..8d69b8aad 100644
--- a/src/pathfinder/yapf/yapf_rail.cpp
+++ b/src/pathfinder/yapf/yapf_rail.cpp
@@ -28,8 +28,8 @@ template <typename Tpf> void DumpState(Tpf &pf1, Tpf &pf2)
pf2.DumpBase(dmp2);
FILE *f1 = fopen("yapf1.txt", "wt");
FILE *f2 = fopen("yapf2.txt", "wt");
- assert(f1 != NULL);
- assert(f2 != NULL);
+ assert(f1 != nullptr);
+ assert(f2 != nullptr);
fwrite(dmp1.m_out.Data(), 1, dmp1.m_out.Size(), f1);
fwrite(dmp2.m_out.Data(), 1, dmp2.m_out.Size(), f2);
fclose(f1);
@@ -84,7 +84,7 @@ private:
tile = TILE_ADD(tile, diff);
} while (IsCompatibleTrainStationTile(tile, start) && tile != m_origin_tile);
- TriggerStationRandomisation(NULL, start, SRT_PATH_RESERVATION);
+ TriggerStationRandomisation(nullptr, start, SRT_PATH_RESERVATION);
return true;
}
@@ -138,7 +138,7 @@ public:
/** Check the node for a possible reservation target. */
inline void FindSafePositionOnNode(Node *node)
{
- assert(node->m_parent != NULL);
+ assert(node->m_parent != nullptr);
/* We will never pass more than two signals, no need to check for a safe tile. */
if (node->m_parent->m_num_signals_passed >= 2) return;
@@ -154,7 +154,7 @@ public:
m_res_fail_tile = INVALID_TILE;
m_origin_tile = origin;
- if (target != NULL) {
+ if (target != nullptr) {
target->tile = m_res_dest;
target->trackdir = m_res_dest_td;
target->okay = false;
@@ -163,7 +163,7 @@ public:
/* Don't bother if the target is reserved. */
if (!IsWaitingPositionFree(Yapf().GetVehicle(), m_res_dest, m_res_dest_td)) return false;
- for (Node *node = m_res_node; node->m_parent != NULL; node = node->m_parent) {
+ for (Node *node = m_res_node; node->m_parent != nullptr; node = node->m_parent) {
node->IterateTiles(Yapf().GetVehicle(), Yapf(), *this, &CYapfReserveTrack<Types>::ReserveSingleTrack);
if (m_res_fail_tile != INVALID_TILE) {
/* Reservation failed, undo. */
@@ -173,13 +173,13 @@ public:
/* If this is the node that failed, stop at the failed tile. */
m_res_fail_tile = fail_node == node ? stop_tile : INVALID_TILE;
fail_node->IterateTiles(Yapf().GetVehicle(), Yapf(), *this, &CYapfReserveTrack<Types>::UnreserveSingleTrack);
- } while (fail_node != node && (fail_node = fail_node->m_parent) != NULL);
+ } while (fail_node != node && (fail_node = fail_node->m_parent) != nullptr);
return false;
}
}
- if (target != NULL) target->okay = true;
+ if (target != nullptr) target->okay = true;
if (Yapf().CanUseGlobalCache(*m_res_node)) {
YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
@@ -270,7 +270,7 @@ public:
/* walk through the path back to the origin */
Node *pNode = n;
- while (pNode->m_parent != NULL) {
+ while (pNode->m_parent != nullptr) {
pNode = pNode->m_parent;
}
@@ -351,15 +351,15 @@ public:
this->SetReservationTarget(pNode, pNode->GetLastTile(), pNode->GetLastTrackdir());
/* Walk through the path back to the origin. */
- Node *pPrev = NULL;
- while (pNode->m_parent != NULL) {
+ Node *pPrev = nullptr;
+ while (pNode->m_parent != nullptr) {
pPrev = pNode;
pNode = pNode->m_parent;
this->FindSafePositionOnNode(pPrev);
}
- return dont_reserve || this->TryReservePath(NULL, pNode->GetLastTile());
+ return dont_reserve || this->TryReservePath(nullptr, pNode->GetLastTile());
}
};
@@ -408,7 +408,7 @@ public:
if (_debug_desync_level < 2) {
result1 = pf1.ChooseRailTrack(v, tile, enterdir, tracks, path_found, reserve_track, target);
} else {
- result1 = pf1.ChooseRailTrack(v, tile, enterdir, tracks, path_found, false, NULL);
+ result1 = pf1.ChooseRailTrack(v, tile, enterdir, tracks, path_found, false, nullptr);
Tpf pf2;
pf2.DisableCache(true);
Trackdir result2 = pf2.ChooseRailTrack(v, tile, enterdir, tracks, path_found, reserve_track, target);
@@ -423,7 +423,7 @@ public:
inline Trackdir ChooseRailTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, PBSTileInfo *target)
{
- if (target != NULL) target->tile = INVALID_TILE;
+ if (target != nullptr) target->tile = INVALID_TILE;
/* set origin and destination nodes */
PBSTileInfo origin = FollowTrainReservation(v);
@@ -436,14 +436,14 @@ public:
/* if path not found - return INVALID_TRACKDIR */
Trackdir next_trackdir = INVALID_TRACKDIR;
Node *pNode = Yapf().GetBestNode();
- if (pNode != NULL) {
+ if (pNode != nullptr) {
/* reserve till end of path */
this->SetReservationTarget(pNode, pNode->GetLastTile(), pNode->GetLastTrackdir());
/* path was found or at least suggested
* walk through the path back to the origin */
- Node *pPrev = NULL;
- while (pNode->m_parent != NULL) {
+ Node *pPrev = nullptr;
+ while (pNode->m_parent != nullptr) {
pPrev = pNode;
pNode = pNode->m_parent;
@@ -494,7 +494,7 @@ public:
/* path was found
* walk through the path back to the origin */
Node *pNode = Yapf().GetBestNode();
- while (pNode->m_parent != NULL) {
+ while (pNode->m_parent != nullptr) {
pNode = pNode->m_parent;
}
diff --git a/src/pathfinder/yapf/yapf_road.cpp b/src/pathfinder/yapf/yapf_road.cpp
index 908915763..3122dd111 100644
--- a/src/pathfinder/yapf/yapf_road.cpp
+++ b/src/pathfinder/yapf/yapf_road.cpp
@@ -118,7 +118,7 @@ public:
/* start at n.m_key.m_tile / n.m_key.m_td and walk to the end of segment */
TileIndex tile = n.m_key.m_tile;
Trackdir trackdir = n.m_key.m_td;
- int parent_cost = (n.m_parent != NULL) ? n.m_parent->m_cost : 0;
+ int parent_cost = (n.m_parent != nullptr) ? n.m_parent->m_cost : 0;
for (;;) {
/* base tile cost depending on distance between edges */
@@ -381,13 +381,13 @@ public:
/* if path not found - return INVALID_TRACKDIR */
Trackdir next_trackdir = INVALID_TRACKDIR;
Node *pNode = Yapf().GetBestNode();
- if (pNode != NULL) {
+ if (pNode != nullptr) {
uint steps = 0;
- for (Node *n = pNode; n->m_parent != NULL; n = n->m_parent) steps++;
+ for (Node *n = pNode; n->m_parent != nullptr; n = n->m_parent) steps++;
/* path was found or at least suggested
* walk through the path back to its origin */
- while (pNode->m_parent != NULL) {
+ while (pNode->m_parent != nullptr) {
steps--;
if (pNode->GetIsChoice() && steps < YAPF_ROADVEH_PATH_CACHE_SEGMENTS) {
TrackdirByte td;
@@ -436,7 +436,7 @@ public:
if (!Yapf().FindPath(v)) return dist;
Node *pNode = Yapf().GetBestNode();
- if (pNode != NULL) {
+ if (pNode != nullptr) {
/* path was found
* get the path cost estimate */
dist = pNode->GetCostEstimate();
diff --git a/src/pathfinder/yapf/yapf_ship.cpp b/src/pathfinder/yapf/yapf_ship.cpp
index b880128f5..e7391d686 100644
--- a/src/pathfinder/yapf/yapf_ship.cpp
+++ b/src/pathfinder/yapf/yapf_ship.cpp
@@ -89,13 +89,13 @@ public:
Trackdir next_trackdir = INVALID_TRACKDIR; // this would mean "path not found"
Node *pNode = pf.GetBestNode();
- if (pNode != NULL) {
+ if (pNode != nullptr) {
uint steps = 0;
- for (Node *n = pNode; n->m_parent != NULL; n = n->m_parent) steps++;
+ for (Node *n = pNode; n->m_parent != nullptr; n = n->m_parent) steps++;
/* walk through the path back to the origin */
- Node *pPrevNode = NULL;
- while (pNode->m_parent != NULL) {
+ Node *pPrevNode = nullptr;
+ while (pNode->m_parent != nullptr) {
steps--;
if (steps > 0 && steps < YAPF_SHIP_PATH_CACHE_LENGTH) {
TrackdirByte td;
@@ -138,11 +138,11 @@ public:
if (!pf.FindPath(v)) return false;
Node *pNode = pf.GetBestNode();
- if (pNode == NULL) return false;
+ if (pNode == nullptr) return false;
/* path was found
* walk through the path back to the origin */
- while (pNode->m_parent != NULL) {
+ while (pNode->m_parent != nullptr) {
pNode = pNode->m_parent;
}
diff --git a/src/pbs.cpp b/src/pbs.cpp
index 44b5b069b..90ac3e70e 100644
--- a/src/pbs.cpp
+++ b/src/pbs.cpp
@@ -116,7 +116,7 @@ bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
case MP_STATION:
if (HasStationRail(tile) && !HasStationReservation(tile)) {
SetRailStationReservation(tile, true);
- if (trigger_stations && IsRailStation(tile)) TriggerStationRandomisation(NULL, tile, SRT_PATH_RESERVATION);
+ if (trigger_stations && IsRailStation(tile)) TriggerStationRandomisation(nullptr, tile, SRT_PATH_RESERVATION);
MarkTileDirtyByTile(tile); // some GRFs need redraw after reserving track
return true;
}
@@ -258,8 +258,8 @@ struct FindTrainOnTrackInfo {
PBSTileInfo res; ///< Information about the track.
Train *best; ///< The currently "best" vehicle we have found.
- /** Init the best location to NULL always! */
- FindTrainOnTrackInfo() : best(NULL) {}
+ /** Init the best location to nullptr always! */
+ FindTrainOnTrackInfo() : best(nullptr) {}
};
/** Callback for Has/FindVehicleOnPos to find a train on a specific track. */
@@ -267,18 +267,18 @@ static Vehicle *FindTrainOnTrackEnum(Vehicle *v, void *data)
{
FindTrainOnTrackInfo *info = (FindTrainOnTrackInfo *)data;
- if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
+ if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
Train *t = Train::From(v);
if (t->track == TRACK_BIT_WORMHOLE || HasBit((TrackBits)t->track, TrackdirToTrack(info->res.trackdir))) {
t = t->First();
/* ALWAYS return the lowest ID (anti-desync!) */
- if (info->best == NULL || t->index < info->best->index) info->best = t;
+ if (info->best == nullptr || t->index < info->best->index) info->best = t;
return t;
}
- return NULL;
+ return nullptr;
}
/**
@@ -300,24 +300,24 @@ PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
FindTrainOnTrackInfo ftoti;
ftoti.res = FollowReservation(v->owner, GetRailTypeInfo(v->railtype)->compatible_railtypes, tile, trackdir);
ftoti.res.okay = IsSafeWaitingPosition(v, ftoti.res.tile, ftoti.res.trackdir, true, _settings_game.pf.forbid_90_deg);
- if (train_on_res != NULL) {
+ if (train_on_res != nullptr) {
FindVehicleOnPos(ftoti.res.tile, &ftoti, FindTrainOnTrackEnum);
- if (ftoti.best != NULL) *train_on_res = ftoti.best->First();
- if (*train_on_res == NULL && IsRailStationTile(ftoti.res.tile)) {
+ if (ftoti.best != nullptr) *train_on_res = ftoti.best->First();
+ if (*train_on_res == nullptr && IsRailStationTile(ftoti.res.tile)) {
/* The target tile is a rail station. The track follower
* has stopped on the last platform tile where we haven't
* found a train. Also check all previous platform tiles
* for a possible train. */
TileIndexDiff diff = TileOffsByDiagDir(TrackdirToExitdir(ReverseTrackdir(ftoti.res.trackdir)));
- for (TileIndex st_tile = ftoti.res.tile + diff; *train_on_res == NULL && IsCompatibleTrainStationTile(st_tile, ftoti.res.tile); st_tile += diff) {
+ for (TileIndex st_tile = ftoti.res.tile + diff; *train_on_res == nullptr && IsCompatibleTrainStationTile(st_tile, ftoti.res.tile); st_tile += diff) {
FindVehicleOnPos(st_tile, &ftoti, FindTrainOnTrackEnum);
- if (ftoti.best != NULL) *train_on_res = ftoti.best->First();
+ if (ftoti.best != nullptr) *train_on_res = ftoti.best->First();
}
}
- if (*train_on_res == NULL && IsTileType(ftoti.res.tile, MP_TUNNELBRIDGE)) {
+ if (*train_on_res == nullptr && IsTileType(ftoti.res.tile, MP_TUNNELBRIDGE)) {
/* The target tile is a bridge/tunnel, also check the other end tile. */
FindVehicleOnPos(GetOtherTunnelBridgeEnd(ftoti.res.tile), &ftoti, FindTrainOnTrackEnum);
- if (ftoti.best != NULL) *train_on_res = ftoti.best->First();
+ if (ftoti.best != nullptr) *train_on_res = ftoti.best->First();
}
}
return ftoti.res;
@@ -328,7 +328,7 @@ PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
*
* @param tile A tile on the path.
* @param track A reserved track on the tile.
- * @return The vehicle holding the reservation or NULL if the path is stray.
+ * @return The vehicle holding the reservation or nullptr if the path is stray.
*/
Train *GetTrainForReservation(TileIndex tile, Track track)
{
@@ -349,25 +349,25 @@ Train *GetTrainForReservation(TileIndex tile, Track track)
ftoti.res = FollowReservation(GetTileOwner(tile), rts, tile, trackdir, true);
FindVehicleOnPos(ftoti.res.tile, &ftoti, FindTrainOnTrackEnum);
- if (ftoti.best != NULL) return ftoti.best;
+ if (ftoti.best != nullptr) return ftoti.best;
/* Special case for stations: check the whole platform for a vehicle. */
if (IsRailStationTile(ftoti.res.tile)) {
TileIndexDiff diff = TileOffsByDiagDir(TrackdirToExitdir(ReverseTrackdir(ftoti.res.trackdir)));
for (TileIndex st_tile = ftoti.res.tile + diff; IsCompatibleTrainStationTile(st_tile, ftoti.res.tile); st_tile += diff) {
FindVehicleOnPos(st_tile, &ftoti, FindTrainOnTrackEnum);
- if (ftoti.best != NULL) return ftoti.best;
+ if (ftoti.best != nullptr) return ftoti.best;
}
}
/* Special case for bridges/tunnels: check the other end as well. */
if (IsTileType(ftoti.res.tile, MP_TUNNELBRIDGE)) {
FindVehicleOnPos(GetOtherTunnelBridgeEnd(ftoti.res.tile), &ftoti, FindTrainOnTrackEnum);
- if (ftoti.best != NULL) return ftoti.best;
+ if (ftoti.best != nullptr) return ftoti.best;
}
}
- return NULL;
+ return nullptr;
}
/**
diff --git a/src/pbs.h b/src/pbs.h
index a02d4d06e..96f9184b2 100644
--- a/src/pbs.h
+++ b/src/pbs.h
@@ -44,7 +44,7 @@ struct PBSTileInfo {
PBSTileInfo(TileIndex _t, Trackdir _td, bool _okay) : tile(_t), trackdir(_td), okay(_okay) {}
};
-PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res = NULL);
+PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res = nullptr);
bool IsSafeWaitingPosition(const Train *v, TileIndex tile, Trackdir trackdir, bool include_line_end, bool forbid_90deg = false);
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg = false);
diff --git a/src/querystring_gui.h b/src/querystring_gui.h
index a1f3896dd..f67809b78 100644
--- a/src/querystring_gui.h
+++ b/src/querystring_gui.h
@@ -37,7 +37,7 @@ struct QueryString {
* @param size Maximum size in bytes.
* @param chars Maximum size in chars.
*/
- QueryString(uint16 size, uint16 chars = UINT16_MAX) : ok_button(ACTION_NOTHING), cancel_button(ACTION_DESELECT), text(size, chars), orig(NULL)
+ QueryString(uint16 size, uint16 chars = UINT16_MAX) : ok_button(ACTION_NOTHING), cancel_button(ACTION_DESELECT), text(size, chars), orig(nullptr)
{
}
@@ -79,11 +79,11 @@ public:
/**
* Get the currently marked text.
* @param[out] length Length of the marked text.
- * @return Begining of the marked area or NULL if no text is marked.
+ * @return Begining of the marked area or nullptr if no text is marked.
*/
const char *GetMarkedText(size_t *length) const
{
- if (this->text.markend == 0) return NULL;
+ if (this->text.markend == 0) return nullptr;
*length = this->text.markend - this->text.markpos;
return this->text.buf + this->text.markpos;
diff --git a/src/rail.h b/src/rail.h
index 004593ce7..8bfc3f025 100644
--- a/src/rail.h
+++ b/src/rail.h
@@ -270,7 +270,7 @@ public:
byte sorting_order;
/**
- * NewGRF providing the Action3 for the railtype. NULL if not available.
+ * NewGRF providing the Action3 for the railtype. nullptr if not available.
*/
const GRFFile *grffile[RTSG_END];
@@ -281,7 +281,7 @@ public:
inline bool UsesOverlay() const
{
- return this->group[RTSG_GROUND] != NULL;
+ return this->group[RTSG_GROUND] != nullptr;
}
/**
diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp
index 4257b5258..d8327c444 100644
--- a/src/rail_cmd.cpp
+++ b/src/rail_cmd.cpp
@@ -622,7 +622,7 @@ CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1,
* so do not call GetTileOwner(tile) in any case here */
Owner owner = INVALID_OWNER;
- Train *v = NULL;
+ Train *v = nullptr;
switch (GetTileType(tile)) {
case MP_ROAD: {
@@ -643,7 +643,7 @@ CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1,
if (flags & DC_EXEC) {
if (HasReservedTracks(tile, trackbit)) {
v = GetTrainForReservation(tile, track);
- if (v != NULL) FreeTrainTrackReservation(v);
+ if (v != nullptr) FreeTrainTrackReservation(v);
}
owner = GetTileOwner(tile);
Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
@@ -681,7 +681,7 @@ CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1,
if (flags & DC_EXEC) {
if (HasReservedTracks(tile, trackbit)) {
v = GetTrainForReservation(tile, track);
- if (v != NULL) FreeTrainTrackReservation(v);
+ if (v != nullptr) FreeTrainTrackReservation(v);
}
owner = GetTileOwner(tile);
@@ -736,7 +736,7 @@ CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1,
YapfNotifyTrackLayoutChange(tile, track);
}
- if (v != NULL) TryPathReserve(v, true);
+ if (v != nullptr) TryPathReserve(v, true);
}
return cost;
@@ -1095,13 +1095,13 @@ CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1,
}
if (flags & DC_EXEC) {
- Train *v = NULL;
+ Train *v = nullptr;
/* The new/changed signal could block our path. As this can lead to
* stale reservations, we clear the path reservation here and try
* to redo it later on. */
if (HasReservedTracks(tile, TrackToTrackBits(track))) {
v = GetTrainForReservation(tile, track);
- if (v != NULL) FreeTrainTrackReservation(v);
+ if (v != nullptr) FreeTrainTrackReservation(v);
}
if (!HasSignals(tile)) {
@@ -1177,7 +1177,7 @@ CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1,
MarkTileDirtyByTile(tile);
AddTrackToSignalBuffer(tile, track, _current_company);
YapfNotifyTrackLayoutChange(tile, track);
- if (v != NULL) {
+ if (v != nullptr) {
/* Extend the train's path if it's not stopped or loading, or not at a safe position. */
if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
!IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
@@ -1467,13 +1467,13 @@ CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1
/* Do it? */
if (flags & DC_EXEC) {
- Train *v = NULL;
+ Train *v = nullptr;
if (HasReservedTracks(tile, TrackToTrackBits(track))) {
v = GetTrainForReservation(tile, track);
} else if (IsPbsSignal(GetSignalType(tile, track))) {
/* PBS signal, might be the end of a path reservation. */
Trackdir td = TrackToTrackdir(track);
- for (int i = 0; v == NULL && i < 2; i++, td = ReverseTrackdir(td)) {
+ for (int i = 0; v == nullptr && i < 2; i++, td = ReverseTrackdir(td)) {
/* Only test the active signal side. */
if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
@@ -1497,7 +1497,7 @@ CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1
AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
YapfNotifyTrackLayoutChange(tile, track);
- if (v != NULL) TryPathReserve(v, false);
+ if (v != nullptr) TryPathReserve(v, false);
MarkTileDirtyByTile(tile);
}
@@ -1531,12 +1531,12 @@ CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1,
/** Update power of train under which is the railtype being converted */
static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
{
- if (v->type != VEH_TRAIN) return NULL;
+ if (v->type != VEH_TRAIN) return nullptr;
TrainList *affected_trains = static_cast<TrainList*>(data);
include(*affected_trains, Train::From(v)->First());
- return NULL;
+ return nullptr;
}
/**
@@ -1620,7 +1620,7 @@ CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
Track track;
while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
Train *v = GetTrainForReservation(tile, track);
- if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
+ if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
/* No power on new rail type, reroute. */
FreeTrainTrackReservation(v);
vehicles_affected.push_back(v);
@@ -1702,7 +1702,7 @@ CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
if (HasTunnelBridgeReservation(tile)) {
Train *v = GetTrainForReservation(tile, track);
- if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
+ if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
/* No power on new rail type, reroute. */
FreeTrainTrackReservation(v);
vehicles_affected.push_back(v);
@@ -1777,11 +1777,11 @@ static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
/* read variables before the depot is removed */
DiagDirection dir = GetRailDepotDirection(tile);
Owner owner = GetTileOwner(tile);
- Train *v = NULL;
+ Train *v = nullptr;
if (HasDepotReservation(tile)) {
v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
- if (v != NULL) FreeTrainTrackReservation(v);
+ if (v != nullptr) FreeTrainTrackReservation(v);
}
Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
@@ -1791,7 +1791,7 @@ static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
DoClearSquare(tile);
AddSideToSignalBuffer(tile, dir, owner);
YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
- if (v != NULL) TryPathReserve(v, true);
+ if (v != nullptr) TryPathReserve(v, true);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
@@ -2064,7 +2064,7 @@ static const SubSprite _halftile_sub_sprite[4] = {
static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
{
- DrawGroundSprite(sprite, pal, NULL, 0, (ti->tileh & s) ? -8 : 0);
+ DrawGroundSprite(sprite, pal, nullptr, 0, (ti->tileh & s) ? -8 : 0);
}
static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
@@ -2258,7 +2258,7 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track)
SpriteID image;
PaletteID pal = PAL_NONE;
- const SubSprite *sub = NULL;
+ const SubSprite *sub = nullptr;
bool junction = false;
/* Select the sprite to use. */
@@ -2355,10 +2355,10 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track)
DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
}
}
- if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
- if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
- if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
- if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
+ if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
+ if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
+ if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
+ if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
}
if (IsValidCorner(halftile_corner)) {
@@ -2378,7 +2378,7 @@ static void DrawTrackBits(TileInfo *ti, TrackBits track)
if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
- DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, -(int)TILE_HEIGHT);
+ DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, -(int)TILE_HEIGHT);
}
}
}
@@ -2958,7 +2958,7 @@ static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int
if (fract_coord_leave == fract_coord) {
/* Leave the depot. */
- if ((v = v->Next()) != NULL) {
+ if ((v = v->Next()) != nullptr) {
v->vehstatus &= ~VS_HIDDEN;
v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
}
@@ -2969,7 +2969,7 @@ static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int
v->track = TRACK_BIT_DEPOT,
v->vehstatus |= VS_HIDDEN;
v->direction = ReverseDir(v->direction);
- if (v->Next() == NULL) VehicleEnterDepot(v->First());
+ if (v->Next() == nullptr) VehicleEnterDepot(v->First());
v->tile = tile;
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
@@ -3034,7 +3034,7 @@ static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old
*/
static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
{
- return v->type == VEH_SHIP ? v : NULL;
+ return v->type == VEH_SHIP ? v : nullptr;
}
static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
@@ -3047,7 +3047,7 @@ static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int
bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
/* Allow clearing the water only if there is no ship */
- if (was_water && HasVehicleOnPos(tile, NULL, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
+ if (was_water && HasVehicleOnPos(tile, nullptr, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
/* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
@@ -3090,14 +3090,14 @@ extern const TileTypeProcs _tile_type_rail_procs = {
DrawTile_Track, // draw_tile_proc
GetSlopePixelZ_Track, // get_slope_z_proc
ClearTile_Track, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_Track, // get_tile_desc_proc
GetTileTrackStatus_Track, // get_tile_track_status_proc
ClickTile_Track, // click_tile_proc
- NULL, // animate_tile_proc
+ nullptr, // animate_tile_proc
TileLoop_Track, // tile_loop_proc
ChangeTileOwner_Track, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
+ nullptr, // add_produced_cargo_proc
VehicleEnter_Track, // vehicle_enter_tile_proc
GetFoundation_Track, // get_foundation_proc
TerraformTile_Track, // terraform_tile_proc
diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp
index e3d307dc9..54aaf61f6 100644
--- a/src/rail_gui.cpp
+++ b/src/rail_gui.cpp
@@ -78,9 +78,9 @@ static void ShowSignalBuilder(Window *parent);
*/
static bool IsStationAvailable(const StationSpec *statspec)
{
- if (statspec == NULL || !HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) return true;
+ if (statspec == nullptr || !HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) return true;
- uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
+ uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
if (cb_res == CALLBACK_FAILED) return true;
return Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res);
@@ -234,7 +234,7 @@ static void GenericPlaceSignals(TileIndex tile)
/* various bitstuffed elements for CmdBuildSingleSignal() */
uint32 p1 = track;
- if (w != NULL) {
+ if (w != nullptr) {
/* signal GUI is used */
SB(p1, 3, 1, _ctrl_pressed);
SB(p1, 4, 1, _cur_signal_variant);
@@ -250,7 +250,7 @@ static void GenericPlaceSignals(TileIndex tile)
}
DoCommandP(tile, p1, 0, CMD_BUILD_SIGNALS |
- CMD_MSG((w != NULL && _convert_signal_button) ? STR_ERROR_SIGNAL_CAN_T_CONVERT_SIGNALS_HERE : STR_ERROR_CAN_T_BUILD_SIGNALS_HERE),
+ CMD_MSG((w != nullptr && _convert_signal_button) ? STR_ERROR_SIGNAL_CAN_T_CONVERT_SIGNALS_HERE : STR_ERROR_CAN_T_BUILD_SIGNALS_HERE),
CcPlaySound_SPLAT_RAIL);
}
}
@@ -388,7 +388,7 @@ static void HandleAutoSignalPlacement()
const Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
- if (w != NULL) {
+ if (w != nullptr) {
/* signal GUI is used */
SB(p2, 3, 1, 0);
SB(p2, 4, 1, _cur_signal_variant);
@@ -683,7 +683,7 @@ struct BuildRailToolbarWindow : Window {
void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt) override
{
/* no dragging if you have pressed the convert button */
- if (FindWindowById(WC_BUILD_SIGNAL, 0) != NULL && _convert_signal_button && this->IsWidgetLowered(WID_RAT_BUILD_SIGNALS)) return;
+ if (FindWindowById(WC_BUILD_SIGNAL, 0) != nullptr && _convert_signal_button && this->IsWidgetLowered(WID_RAT_BUILD_SIGNALS)) return;
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
@@ -781,7 +781,7 @@ static EventState RailToolbarGlobalHotkeys(int hotkey)
if (_game_mode != GM_NORMAL || !CanBuildVehicleInfrastructure(VEH_TRAIN)) return ES_NOT_HANDLED;
extern RailType _last_built_railtype;
Window *w = ShowBuildRailToolbar(_last_built_railtype);
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -862,12 +862,12 @@ static WindowDesc _build_rail_desc(
* If the terraform toolbar is linked to the toolbar, that window is also opened.
*
* @param railtype Rail type to open the window for
- * @return newly opened rail toolbar, or NULL if the toolbar could not be opened.
+ * @return newly opened rail toolbar, or nullptr if the toolbar could not be opened.
*/
Window *ShowBuildRailToolbar(RailType railtype)
{
- if (!Company::IsValidID(_local_company)) return NULL;
- if (!ValParamRailtype(railtype)) return NULL;
+ if (!Company::IsValidID(_local_company)) return nullptr;
+ if (!ValParamRailtype(railtype)) return nullptr;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
_cur_railtype = railtype;
@@ -907,7 +907,7 @@ private:
*/
void CheckSelectedSize(const StationSpec *statspec)
{
- if (statspec == NULL || _settings_client.gui.station_dragdrop) return;
+ if (statspec == nullptr || _settings_client.gui.station_dragdrop) return;
/* If current number of tracks is not allowed, make it as big as possible */
if (HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
@@ -937,7 +937,7 @@ public:
BuildRailStationWindow(WindowDesc *desc, Window *parent, bool newstation) : PickerWindowBase(desc, parent)
{
this->coverage_height = 2 * FONT_HEIGHT_NORMAL + 3 * WD_PAR_VSEP_NORMAL;
- this->vscroll = NULL;
+ this->vscroll = nullptr;
_railstation.newstations = newstation;
this->CreateNestedTree();
@@ -970,7 +970,7 @@ public:
* type is 'selected'. */
_railstation.station_class = STAT_CLASS_DFLT;
_railstation.station_type = 0;
- this->vscroll2 = NULL;
+ this->vscroll2 = nullptr;
}
if (newstation) {
_railstation.station_count = StationClass::Get(_railstation.station_class)->GetSpecCount();
@@ -999,7 +999,7 @@ public:
void OnPaint() override
{
bool newstations = _railstation.newstations;
- const StationSpec *statspec = newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : NULL;
+ const StationSpec *statspec = newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
if (_settings_client.gui.station_dragdrop) {
SetTileSelectSize(1, 1);
@@ -1018,7 +1018,7 @@ public:
for (uint bits = 0; bits < 7; bits++) {
bool disable = bits >= _settings_game.station.station_spread;
- if (statspec == NULL) {
+ if (statspec == nullptr) {
this->SetWidgetDisabledState(bits + WID_BRAS_PLATFORM_NUM_1, disable);
this->SetWidgetDisabledState(bits + WID_BRAS_PLATFORM_LEN_1, disable);
} else {
@@ -1078,7 +1078,7 @@ public:
StationClass *stclass = StationClass::Get(statclass);
for (uint16 j = 0; j < stclass->GetSpecCount(); j++) {
const StationSpec *statspec = stclass->GetSpec(j);
- SetDParam(0, (statspec != NULL && statspec->name != 0) ? statspec->name : STR_STATION_CLASS_DFLT);
+ SetDParam(0, (statspec != nullptr && statspec->name != 0) ? statspec->name : STR_STATION_CLASS_DFLT);
d = maxdim(d, GetStringBoundingBox(str));
}
}
@@ -1180,7 +1180,7 @@ public:
void OnResize() override
{
- if (this->vscroll != NULL) { // New stations available.
+ if (this->vscroll != nullptr) { // New stations available.
this->vscroll->SetCapacityFromWidget(this, WID_BRAS_NEWST_LIST);
}
}
@@ -1189,7 +1189,7 @@ public:
{
if (widget == WID_BRAS_SHOW_NEWST_TYPE) {
const StationSpec *statspec = StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type);
- SetDParam(0, (statspec != NULL && statspec->name != 0) ? statspec->name : STR_STATION_CLASS_DFLT);
+ SetDParam(0, (statspec != nullptr && statspec->name != 0) ? statspec->name : STR_STATION_CLASS_DFLT);
}
}
@@ -1221,8 +1221,8 @@ public:
_settings_client.gui.station_dragdrop = false;
- const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : NULL;
- if (statspec != NULL && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
+ const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
+ if (statspec != nullptr && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
/* The previously selected number of platforms in invalid */
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_lengths, i)) {
@@ -1256,8 +1256,8 @@ public:
_settings_client.gui.station_dragdrop = false;
- const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : NULL;
- if (statspec != NULL && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
+ const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
+ if (statspec != nullptr && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
/* The previously selected number of tracks in invalid */
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_platforms, i)) {
@@ -1282,8 +1282,8 @@ public:
this->ToggleWidgetLoweredState(WID_BRAS_PLATFORM_DRAG_N_DROP);
/* get the first allowed length/number of platforms */
- const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : NULL;
- if (statspec != NULL && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
+ const StationSpec *statspec = _railstation.newstations ? StationClass::Get(_railstation.station_class)->GetSpec(_railstation.station_type) : nullptr;
+ if (statspec != nullptr && HasBit(statspec->disallowed_lengths, _settings_client.gui.station_platlength - 1)) {
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_lengths, i)) {
this->RaiseWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN);
@@ -1292,7 +1292,7 @@ public:
}
}
}
- if (statspec != NULL && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
+ if (statspec != nullptr && HasBit(statspec->disallowed_platforms, _settings_client.gui.station_numtracks - 1)) {
for (uint i = 0; i < 7; i++) {
if (!HasBit(statspec->disallowed_platforms, i)) {
this->RaiseWidget(_settings_client.gui.station_numtracks + WID_BRAS_PLATFORM_NUM_BEGIN);
@@ -1598,7 +1598,7 @@ public:
/* If 'remove' button of rail build toolbar is active, disable it. */
if (_remove_button_clicked) {
Window *w = FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL);
- if (w != NULL) ToggleRailButton_Remove(w);
+ if (w != nullptr) ToggleRailButton_Remove(w);
}
break;
@@ -1768,7 +1768,7 @@ static const NWidgetPart _nested_build_depot_widgets[] = {
};
static WindowDesc _build_depot_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_build_depot_widgets, lengthof(_nested_build_depot_widgets)
@@ -1896,7 +1896,7 @@ void ReinitGuiAfterToggleElrail(bool disable)
if (disable && _last_built_railtype == RAILTYPE_ELECTRIC) {
_last_built_railtype = _cur_railtype = RAILTYPE_RAIL;
BuildRailToolbarWindow *w = dynamic_cast<BuildRailToolbarWindow *>(FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL));
- if (w != NULL) w->ModifyRailType(_cur_railtype);
+ if (w != nullptr) w->ModifyRailType(_cur_railtype);
}
MarkWholeScreenDirty();
}
@@ -1943,7 +1943,7 @@ static void SetDefaultRailGui()
_last_built_railtype = _cur_railtype = rt;
BuildRailToolbarWindow *w = dynamic_cast<BuildRailToolbarWindow *>(FindWindowById(WC_BUILD_TOOLBAR, TRANSPORT_RAIL));
- if (w != NULL) w->ModifyRailType(_cur_railtype);
+ if (w != nullptr) w->ModifyRailType(_cur_railtype);
}
/**
@@ -1958,7 +1958,7 @@ bool ResetSignalVariant(int32 p)
if (new_variant != _cur_signal_variant) {
Window *w = FindWindowById(WC_BUILD_SIGNAL, 0);
- if (w != NULL) {
+ if (w != nullptr) {
w->SetDirty();
w->RaiseWidget((_cur_signal_variant == SIG_ELECTRIC ? WID_BS_ELECTRIC_NORM : WID_BS_SEMAPHORE_NORM) + _cur_signal_type);
}
diff --git a/src/road.cpp b/src/road.cpp
index f51597538..3700629ef 100644
--- a/src/road.cpp
+++ b/src/road.cpp
@@ -115,7 +115,7 @@ bool HasRoadTypesAvail(const CompanyID company, const RoadTypes rts)
avail_roadtypes = ROADTYPES_ROAD;
} else {
Company *c = Company::GetIfValid(company);
- if (c == NULL) return false;
+ if (c == nullptr) return false;
avail_roadtypes = (RoadTypes)c->avail_roadtypes | ROADTYPES_ROAD; // road is available for always for everybody
}
return (rts & ~avail_roadtypes) == 0;
diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp
index d9825c9bf..e9edbf254 100644
--- a/src/road_cmd.cpp
+++ b/src/road_cmd.cpp
@@ -136,7 +136,7 @@ CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, R
if (_cheats.magic_bulldozer.value) return CommandCost();
Town *t = ClosestTownFromTile(tile, UINT_MAX);
- if (t == NULL) return CommandCost();
+ if (t == nullptr) return CommandCost();
/* check if you're allowed to remove the street owned by a town
* removal allowance depends on difficulty setting */
@@ -227,7 +227,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits piec
cost.AddCost(len * 2 * _price[PR_CLEAR_ROAD]);
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
DirtyCompanyInfrastructureWindows(c->index);
@@ -258,7 +258,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits piec
cost.AddCost(_price[PR_CLEAR_ROAD] * 2);
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= 2;
DirtyCompanyInfrastructureWindows(c->index);
@@ -319,7 +319,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits piec
}
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.road[rt] -= CountBits(pieces);
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -333,7 +333,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits piec
if (rt == ROADTYPE_ROAD && IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN)) {
/* Update nearest-town index */
const Town *town = CalcClosestTownFromTile(tile);
- SetTownIndex(tile, town == NULL ? INVALID_TOWN : town->index);
+ SetTownIndex(tile, town == nullptr ? INVALID_TOWN : town->index);
}
SetRoadBits(tile, ROAD_NONE, rt);
SetRoadTypes(tile, rts);
@@ -367,7 +367,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits piec
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= 2;
DirtyCompanyInfrastructureWindows(c->index);
@@ -384,7 +384,7 @@ static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits piec
/* Update rail count for level crossings. The plain track should still be accounted
* for, so only subtract the difference to the level crossing cost. */
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -494,13 +494,13 @@ CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if ((Company::IsValidID(company) && p2 != 0) || (company == OWNER_TOWN && !Town::IsValidID(p2)) || (company == OWNER_DEITY && p2 != 0)) return CMD_ERROR;
if (company != OWNER_TOWN) {
const Town *town = CalcClosestTownFromTile(tile);
- p2 = (town != NULL) ? town->index : INVALID_TOWN;
+ p2 = (town != nullptr) ? town->index : INVALID_TOWN;
if (company == OWNER_DEITY) {
company = OWNER_TOWN;
/* If we are not within a town, we are not owned by the town */
- if (town == NULL || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
+ if (town == nullptr || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
company = OWNER_NONE;
}
}
@@ -633,7 +633,7 @@ CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
YapfNotifyTrackLayoutChange(tile, railtrack);
/* Update company infrastructure counts. A level crossing has two road bits. */
Company *c = Company::GetIfValid(company);
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.road[rt] += 2;
if (rt != ROADTYPE_ROAD) c->infrastructure.road[ROADTYPE_ROAD] += 2;
DirtyCompanyInfrastructureWindows(company);
@@ -641,7 +641,7 @@ CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Update rail count for level crossings. The plain track is already
* counted, so only add the difference to the level crossing cost. */
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -783,7 +783,7 @@ do_clear:;
/* Update company infrastructure count. */
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
c->infrastructure.road[rt] += num_pieces;
DirtyCompanyInfrastructureWindows(c->index);
@@ -1064,7 +1064,7 @@ static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
if (flags & DC_EXEC) {
Company *c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
/* A road depot has two road bits. */
c->infrastructure.road[FIND_FIRST_BIT(GetRoadTypes(tile))] -= 2;
DirtyCompanyInfrastructureWindows(c->index);
@@ -1449,7 +1449,7 @@ void UpdateNearestTownForRoadTiles(bool invalidate)
TownID tid = INVALID_TOWN;
if (!invalidate) {
const Town *town = CalcClosestTownFromTile(t);
- if (town != NULL) tid = town->index;
+ if (town != nullptr) tid = town->index;
}
SetTownIndex(t, tid);
}
@@ -1522,7 +1522,7 @@ static void TileLoop_Road(TileIndex tile)
if (!HasRoadWorks(tile)) {
HouseZonesBits grp = HZB_TOWN_EDGE;
- if (t != NULL) {
+ if (t != nullptr) {
grp = GetTownRadiusGroup(t, tile);
/* Show an animation to indicate road work */
@@ -1751,7 +1751,7 @@ static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int
rv->state = RVSB_IN_DEPOT;
rv->vehstatus |= VS_HIDDEN;
rv->direction = ReverseDir(rv->direction);
- if (rv->Next() == NULL) VehicleEnterDepot(rv->First());
+ if (rv->Next() == nullptr) VehicleEnterDepot(rv->First());
rv->tile = tile;
InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
@@ -1863,14 +1863,14 @@ extern const TileTypeProcs _tile_type_road_procs = {
DrawTile_Road, // draw_tile_proc
GetSlopePixelZ_Road, // get_slope_z_proc
ClearTile_Road, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_Road, // get_tile_desc_proc
GetTileTrackStatus_Road, // get_tile_track_status_proc
ClickTile_Road, // click_tile_proc
- NULL, // animate_tile_proc
+ nullptr, // animate_tile_proc
TileLoop_Road, // tile_loop_proc
ChangeTileOwner_Road, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
+ nullptr, // add_produced_cargo_proc
VehicleEnter_Road, // vehicle_enter_tile_proc
GetFoundation_Road, // get_foundation_proc
TerraformTile_Road, // terraform_tile_proc
diff --git a/src/road_gui.cpp b/src/road_gui.cpp
index 40212e8fb..27c8fe8e7 100644
--- a/src/road_gui.cpp
+++ b/src/road_gui.cpp
@@ -681,7 +681,7 @@ struct BuildRoadToolbarWindow : Window {
*/
static EventState RoadToolbarGlobalHotkeys(int hotkey)
{
- Window *w = NULL;
+ Window *w = nullptr;
switch (_game_mode) {
case GM_NORMAL: {
extern RoadType _last_built_roadtype;
@@ -697,7 +697,7 @@ static EventState RoadToolbarGlobalHotkeys(int hotkey)
break;
}
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -804,11 +804,11 @@ static WindowDesc _build_tramway_desc(
*
* If the terraform toolbar is linked to the toolbar, that window is also opened.
*
- * @return newly opened road toolbar, or NULL if the toolbar could not be opened.
+ * @return newly opened road toolbar, or nullptr if the toolbar could not be opened.
*/
Window *ShowBuildRoadToolbar(RoadType roadtype)
{
- if (!Company::IsValidID(_local_company)) return NULL;
+ if (!Company::IsValidID(_local_company)) return nullptr;
_cur_roadtype = roadtype;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
@@ -852,7 +852,7 @@ static WindowDesc _build_road_scen_desc(
/**
* Show the road building toolbar in the scenario editor.
- * @return The just opened toolbar, or \c NULL if the toolbar was already open.
+ * @return The just opened toolbar, or \c nullptr if the toolbar was already open.
*/
Window *ShowBuildRoadScenToolbar()
{
@@ -940,7 +940,7 @@ static const NWidgetPart _nested_build_road_depot_widgets[] = {
};
static WindowDesc _build_road_depot_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_build_road_depot_widgets, lengthof(_nested_build_road_depot_widgets)
@@ -1100,7 +1100,7 @@ static const NWidgetPart _nested_road_station_picker_widgets[] = {
};
static WindowDesc _road_station_picker_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUS_STATION, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_road_station_picker_widgets, lengthof(_nested_road_station_picker_widgets)
@@ -1138,7 +1138,7 @@ static const NWidgetPart _nested_tram_station_picker_widgets[] = {
};
static WindowDesc _tram_station_picker_desc(
- WDP_AUTO, NULL, 0, 0,
+ WDP_AUTO, nullptr, 0, 0,
WC_BUS_STATION, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION,
_nested_tram_station_picker_widgets, lengthof(_nested_tram_station_picker_widgets)
diff --git a/src/roadstop.cpp b/src/roadstop.cpp
index ca049979c..acefa8362 100644
--- a/src/roadstop.cpp
+++ b/src/roadstop.cpp
@@ -43,7 +43,7 @@ RoadStop::~RoadStop()
*/
RoadStop *RoadStop::GetNextRoadStop(const RoadVehicle *v) const
{
- for (RoadStop *rs = this->next; rs != NULL; rs = rs->next) {
+ for (RoadStop *rs = this->next; rs != nullptr; rs = rs->next) {
/* The vehicle cannot go to this roadstop (different roadtype) */
if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
/* The vehicle is articulated and can therefore not go to a standard road stop. */
@@ -53,7 +53,7 @@ RoadStop *RoadStop::GetNextRoadStop(const RoadVehicle *v) const
return rs;
}
- return NULL;
+ return nullptr;
}
/**
@@ -63,7 +63,7 @@ RoadStop *RoadStop::GetNextRoadStop(const RoadVehicle *v) const
*/
void RoadStop::MakeDriveThrough()
{
- assert(this->east == NULL && this->west == NULL);
+ assert(this->east == nullptr && this->west == nullptr);
RoadStopType rst = GetRoadStopType(this->xy);
DiagDirection dir = GetRoadStopDir(this->xy);
@@ -73,21 +73,21 @@ void RoadStop::MakeDriveThrough()
/* Information about the tile north of us */
TileIndex north_tile = this->xy - offset;
bool north = IsDriveThroughRoadStopContinuation(this->xy, north_tile);
- RoadStop *rs_north = north ? RoadStop::GetByTile(north_tile, rst) : NULL;
+ RoadStop *rs_north = north ? RoadStop::GetByTile(north_tile, rst) : nullptr;
/* Information about the tile south of us */
TileIndex south_tile = this->xy + offset;
bool south = IsDriveThroughRoadStopContinuation(this->xy, south_tile);
- RoadStop *rs_south = south ? RoadStop::GetByTile(south_tile, rst) : NULL;
+ RoadStop *rs_south = south ? RoadStop::GetByTile(south_tile, rst) : nullptr;
/* Amount of road stops that will be added to the 'northern' head */
int added = 1;
- if (north && rs_north->east != NULL) { // (east != NULL) == (west != NULL)
+ if (north && rs_north->east != nullptr) { // (east != nullptr) == (west != nullptr)
/* There is a more northern one, so this can join them */
this->east = rs_north->east;
this->west = rs_north->west;
- if (south && rs_south->east != NULL) { // (east != NULL) == (west != NULL)
+ if (south && rs_south->east != nullptr) { // (east != nullptr) == (west != nullptr)
/* There more southern tiles too, they must 'join' us too */
ClrBit(rs_south->status, RSSFB_BASE_ENTRY);
this->east->occupied += rs_south->east->occupied;
@@ -100,13 +100,13 @@ void RoadStop::MakeDriveThrough()
/* Make all 'children' of the southern tile take the new master */
for (; IsDriveThroughRoadStopContinuation(this->xy, south_tile); south_tile += offset) {
rs_south = RoadStop::GetByTile(south_tile, rst);
- if (rs_south->east == NULL) break;
+ if (rs_south->east == nullptr) break;
rs_south->east = rs_north->east;
rs_south->west = rs_north->west;
added++;
}
}
- } else if (south && rs_south->east != NULL) { // (east != NULL) == (west != NULL)
+ } else if (south && rs_south->east != nullptr) { // (east != nullptr) == (west != nullptr)
/* There is one to the south, but not to the north... so we become 'parent' */
this->east = rs_south->east;
this->west = rs_south->west;
@@ -131,7 +131,7 @@ void RoadStop::MakeDriveThrough()
*/
void RoadStop::ClearDriveThrough()
{
- assert(this->east != NULL && this->west != NULL);
+ assert(this->east != nullptr && this->west != nullptr);
RoadStopType rst = GetRoadStopType(this->xy);
DiagDirection dir = GetRoadStopDir(this->xy);
@@ -141,12 +141,12 @@ void RoadStop::ClearDriveThrough()
/* Information about the tile north of us */
TileIndex north_tile = this->xy - offset;
bool north = IsDriveThroughRoadStopContinuation(this->xy, north_tile);
- RoadStop *rs_north = north ? RoadStop::GetByTile(north_tile, rst) : NULL;
+ RoadStop *rs_north = north ? RoadStop::GetByTile(north_tile, rst) : nullptr;
/* Information about the tile south of us */
TileIndex south_tile = this->xy + offset;
bool south = IsDriveThroughRoadStopContinuation(this->xy, south_tile);
- RoadStop *rs_south = south ? RoadStop::GetByTile(south_tile, rst) : NULL;
+ RoadStop *rs_south = south ? RoadStop::GetByTile(south_tile, rst) : nullptr;
/* Must only be cleared after we determined which neighbours are
* part of our little entry 'queue' */
@@ -207,8 +207,8 @@ void RoadStop::ClearDriveThrough()
/* Make sure we don't get used for something 'incorrect' */
ClrBit(this->status, RSSFB_BASE_ENTRY);
- this->east = NULL;
- this->west = NULL;
+ this->east = nullptr;
+ this->west = nullptr;
}
/**
@@ -271,7 +271,7 @@ bool RoadStop::Enter(RoadVehicle *rv)
for (RoadStop *rs = st->GetPrimaryRoadStop(type);; rs = rs->next) {
if (rs->xy == tile) return rs;
- assert(rs->next != NULL);
+ assert(rs->next != nullptr);
}
}
@@ -325,25 +325,25 @@ struct RoadStopEntryRebuilderHelper {
* Add road vehicles to the station's list if needed.
* @param v the found vehicle
* @param data the extra data used to make our decision
- * @return always NULL
+ * @return always nullptr
*/
Vehicle *FindVehiclesInRoadStop(Vehicle *v, void *data)
{
RoadStopEntryRebuilderHelper *rserh = (RoadStopEntryRebuilderHelper*)data;
/* Not a RV or not in the right direction or crashed :( */
- if (v->type != VEH_ROAD || DirToDiagDir(v->direction) != rserh->dir || !v->IsPrimaryVehicle() || (v->vehstatus & VS_CRASHED) != 0) return NULL;
+ if (v->type != VEH_ROAD || DirToDiagDir(v->direction) != rserh->dir || !v->IsPrimaryVehicle() || (v->vehstatus & VS_CRASHED) != 0) return nullptr;
RoadVehicle *rv = RoadVehicle::From(v);
/* Don't add ones not in a road stop */
- if (rv->state < RVSB_IN_ROAD_STOP) return NULL;
+ if (rv->state < RVSB_IN_ROAD_STOP) return nullptr;
/* Do not add duplicates! */
for (RVList::iterator it = rserh->vehicles.begin(); it != rserh->vehicles.end(); it++) {
- if (rv == *it) return NULL;
+ if (rv == *it) return nullptr;
}
rserh->vehicles.push_back(rv);
- return NULL;
+ return nullptr;
}
/**
diff --git a/src/roadveh.h b/src/roadveh.h
index c2a799951..22f827b1d 100644
--- a/src/roadveh.h
+++ b/src/roadveh.h
@@ -133,7 +133,7 @@ struct RoadVehicle FINAL : public GroundVehicle<RoadVehicle, VEH_ROAD> {
int GetDisplaySpeed() const { return this->gcache.last_speed / 2; }
int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed / 2; }
Money GetRunningCost() const;
- int GetDisplayImageWidth(Point *offset = NULL) const;
+ int GetDisplayImageWidth(Point *offset = nullptr) const;
bool IsInDepot() const { return this->state == RVSB_IN_DEPOT; }
bool Tick();
void OnNewDay();
diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp
index 559b87547..7086d151d 100644
--- a/src/roadveh_cmd.cpp
+++ b/src/roadveh_cmd.cpp
@@ -86,14 +86,14 @@ bool RoadVehicle::IsBus() const
/**
* Get the width of a road vehicle image in the GUI.
- * @param offset Additional offset for positioning the sprite; set to NULL if not needed
+ * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
* @return Width in pixels
*/
int RoadVehicle::GetDisplayImageWidth(Point *offset) const
{
int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
- if (offset != NULL) {
+ if (offset != nullptr) {
offset->x = ScaleGUITrad(reference_width) / 2;
offset->y = 0;
}
@@ -192,7 +192,7 @@ static uint GetRoadVehLength(const RoadVehicle *v)
uint length = VEHICLE_LENGTH;
uint16 veh_len = CALLBACK_FAILED;
- if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
+ if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
/* Use callback 36 */
veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
@@ -223,7 +223,7 @@ void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
v->gcache.cached_total_length = 0;
- for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
+ for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
/* Check the v->first cache. */
assert(u->First() == v);
@@ -315,7 +315,7 @@ CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engin
v->InvalidateNewGRFCacheOfChain();
/* Call various callbacks after the whole consist has been constructed */
- for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
+ for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
u->refit_cap = 0;
v->InvalidateNewGRFCache();
@@ -350,8 +350,8 @@ bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destinati
FindDepotData rfdd = FindClosestRoadDepot(this, 0);
if (rfdd.best_length == UINT_MAX) return false;
- if (location != NULL) *location = rfdd.tile;
- if (destination != NULL) *destination = GetDepotIndex(rfdd.tile);
+ if (location != nullptr) *location = rfdd.tile;
+ if (destination != nullptr) *destination = GetDepotIndex(rfdd.tile);
return true;
}
@@ -368,7 +368,7 @@ bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destinati
CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
RoadVehicle *v = RoadVehicle::GetIfValid(p1);
- if (v == NULL) return CMD_ERROR;
+ if (v == nullptr) return CMD_ERROR;
if (!v->IsPrimaryVehicle()) return CMD_ERROR;
@@ -397,7 +397,7 @@ CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
void RoadVehicle::MarkDirty()
{
- for (RoadVehicle *v = this; v != NULL; v = v->Next()) {
+ for (RoadVehicle *v = this; v != nullptr; v = v->Next()) {
v->colourmap = PAL_NONE;
v->UpdateViewport(true, false);
}
@@ -440,7 +440,7 @@ inline int RoadVehicle::GetCurrentMaxSpeed() const
int max_speed = this->vcache.cached_max_speed;
/* Limit speed to 50% while reversing, 75% in curves. */
- for (const RoadVehicle *u = this; u != NULL; u = u->Next()) {
+ for (const RoadVehicle *u = this; u != nullptr; u = u->Next()) {
if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir((Trackdir)this->state)) {
max_speed = this->vcache.cached_max_speed / 2;
@@ -467,8 +467,8 @@ static void DeleteLastRoadVeh(RoadVehicle *v)
{
RoadVehicle *first = v->First();
Vehicle *u = v;
- for (; v->Next() != NULL; v = v->Next()) u = v;
- u->SetNext(NULL);
+ for (; v->Next() != nullptr; v = v->Next()) u = v;
+ u->SetNext(nullptr);
v->last_station_visited = first->last_station_visited; // for PreDestructor
/* Only leave the road stop when we're really gone. */
@@ -488,7 +488,7 @@ static void RoadVehSetRandomDirection(RoadVehicle *v)
v->direction = ChangeDir(v->direction, delta[r & 3]);
v->UpdateViewport(true, true);
- } while ((v = v->Next()) != NULL);
+ } while ((v = v->Next()) != nullptr);
}
/**
@@ -504,7 +504,7 @@ static bool RoadVehIsCrashed(RoadVehicle *v)
} else if (v->crashed_ctr <= 45) {
if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
} else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
- bool ret = v->Next() != NULL;
+ bool ret = v->Next() != nullptr;
DeleteLastRoadVeh(v);
return ret;
}
@@ -516,7 +516,7 @@ static bool RoadVehIsCrashed(RoadVehicle *v)
* Check routine whether a road and a train vehicle have collided.
* @param v %Train vehicle to test.
* @param data Road vehicle to test.
- * @return %Train vehicle if the vehicles collided, else \c NULL.
+ * @return %Train vehicle if the vehicles collided, else \c nullptr.
*/
static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
{
@@ -525,7 +525,7 @@ static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
return (v->type == VEH_TRAIN &&
abs(v->z_pos - u->z_pos) <= 6 &&
abs(v->x_pos - u->x_pos) <= 4 &&
- abs(v->y_pos - u->y_pos) <= 4) ? v : NULL;
+ abs(v->y_pos - u->y_pos) <= 4) ? v : nullptr;
}
uint RoadVehicle::Crash(bool flooded)
@@ -564,7 +564,7 @@ static void RoadVehCrash(RoadVehicle *v)
static bool RoadVehCheckTrainCrash(RoadVehicle *v)
{
- for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
+ for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
if (u->state == RVSB_WORMHOLE) continue;
TileIndex tile = u->tile;
@@ -641,7 +641,7 @@ static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
}
}
- return NULL;
+ return nullptr;
}
static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
@@ -649,7 +649,7 @@ static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction d
RoadVehFindData rvf;
RoadVehicle *front = v->First();
- if (front->reverse_ctr != 0) return NULL;
+ if (front->reverse_ctr != 0) return nullptr;
rvf.x = x;
rvf.y = y;
@@ -670,10 +670,10 @@ static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction d
* It can be disabled. */
if (rvf.best_diff == UINT_MAX) {
front->blocked_ctr = 0;
- return NULL;
+ return nullptr;
}
- if (update_blocked_ctr && ++front->blocked_ctr > 1480) return NULL;
+ if (update_blocked_ctr && ++front->blocked_ctr > 1480) return nullptr;
return RoadVehicle::From(rvf.best);
}
@@ -772,7 +772,7 @@ static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
{
const OvertakeData *od = (OvertakeData*)data;
- return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : NULL;
+ return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : nullptr;
}
/**
@@ -1006,7 +1006,7 @@ struct RoadDriveEntry {
static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
{
/* Don't leave unless v and following wagons are in the depot. */
- for (const RoadVehicle *u = v; u != NULL; u = u->Next()) {
+ for (const RoadVehicle *u = v; u != nullptr; u = u->Next()) {
if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
}
@@ -1026,7 +1026,7 @@ static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
return true;
}
- if (RoadVehFindCloseTo(v, x, y, v->direction, false) != NULL) return true;
+ if (RoadVehFindCloseTo(v, x, y, v->direction, false) != nullptr) return true;
VehicleServiceInDepot(v);
@@ -1161,7 +1161,7 @@ bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
if (v->IsFrontEngine()) {
const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
- if (u != NULL) {
+ if (u != nullptr) {
v->cur_speed = u->First()->cur_speed;
return false;
}
@@ -1225,7 +1225,7 @@ again:
case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
}
- if ((v->Previous() != NULL && v->Previous()->tile == tile) ||
+ if ((v->Previous() != nullptr && v->Previous()->tile == tile) ||
(v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
(needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE)) {
/*
@@ -1274,7 +1274,7 @@ again:
Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
if (v->IsFrontEngine()) {
Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
- if (u != NULL) {
+ if (u != nullptr) {
v->cur_speed = u->First()->cur_speed;
return false;
}
@@ -1376,7 +1376,7 @@ again:
int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
- if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != NULL) return false;
+ if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != nullptr) return false;
uint32 r = VehicleEnterTile(v, v->tile, x, y);
if (HasBit(r, VETS_CANNOT_ENTER)) {
@@ -1402,7 +1402,7 @@ again:
/* This vehicle is not in a wormhole and it hasn't entered a new tile. If
* it's on a depot tile, check if it's time to activate the next vehicle in
* the chain yet. */
- if (v->Next() != NULL && IsRoadDepotTile(v->tile)) {
+ if (v->Next() != nullptr && IsRoadDepotTile(v->tile)) {
if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
RoadVehLeaveDepot(v->Next(), false);
}
@@ -1419,7 +1419,7 @@ again:
* Check for another vehicle to overtake */
RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
- if (u != NULL) {
+ if (u != nullptr) {
u = u->First();
/* There is a vehicle in front overtake it if possible */
if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
@@ -1569,7 +1569,7 @@ static bool RoadVehController(RoadVehicle *v)
j -= adv_spd;
RoadVehicle *u = v;
- for (RoadVehicle *prev = NULL; u != NULL; prev = u, u = u->Next()) {
+ for (RoadVehicle *prev = nullptr; u != nullptr; prev = u, u = u->Next()) {
if (!IndividualRoadVehicleController(u, prev)) {
blocked = true;
break;
@@ -1586,7 +1586,7 @@ static bool RoadVehController(RoadVehicle *v)
v->SetLastSpeed();
- for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
+ for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
if ((u->vehstatus & VS_HIDDEN) != 0) continue;
u->UpdateViewport(false, false);
diff --git a/src/roadveh_gui.cpp b/src/roadveh_gui.cpp
index 63e054958..1c96c29e9 100644
--- a/src/roadveh_gui.cpp
+++ b/src/roadveh_gui.cpp
@@ -47,7 +47,7 @@ void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y)
memset(subtype_text, 0, sizeof(subtype_text));
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
max_cargo[u->cargo_type] += u->cargo_cap;
if (u->cargo_cap > 0) {
StringID text = GetCargoSubtypeText(u);
@@ -80,7 +80,7 @@ void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y)
DrawString(left, right, y + FONT_HEIGHT_NORMAL + y_offset, capacity, TC_BLUE);
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
if (u->cargo_cap == 0) continue;
str = STR_VEHICLE_DETAILS_CARGO_EMPTY;
@@ -143,7 +143,7 @@ void DrawRoadVehImage(const Vehicle *v, int left, int right, int y, VehicleID se
_cur_dpi = &tmp_dpi;
int px = rtl ? max_width + skip : -skip;
- for (; u != NULL && (rtl ? px > 0 : px < max_width); u = u->Next()) {
+ for (; u != nullptr && (rtl ? px > 0 : px < max_width); u = u->Next()) {
Point offset;
int width = u->GetDisplayImageWidth(&offset);
diff --git a/src/safeguards.h b/src/safeguards.h
index f447627e6..157730fbe 100644
--- a/src/safeguards.h
+++ b/src/safeguards.h
@@ -12,7 +12,7 @@
*
* Unsafe methods are, for example, strndup and strncpy because they may leave the
* string without a null termination, but also strdup and strndup because they can
- * return NULL and then all strdups would need to be guarded against that instead
+ * return nullptr and then all strdups would need to be guarded against that instead
* of using the current MallocT/ReallocT/CallocT technique of just giving the user
* an error that too much memory was used instead of spreading that code though
* the whole code base.
diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp
index b4e3ce986..8d9b0ffa6 100644
--- a/src/saveload/afterload.cpp
+++ b/src/saveload/afterload.cpp
@@ -263,14 +263,14 @@ static void InitializeWindowsAndCaches()
/* Identify owners of persistent storage arrays */
Industry *i;
FOR_ALL_INDUSTRIES(i) {
- if (i->psa != NULL) {
+ if (i->psa != nullptr) {
i->psa->feature = GSF_INDUSTRIES;
i->psa->tile = i->location.tile;
}
}
Station *s;
FOR_ALL_STATIONS(s) {
- if (s->airport.psa != NULL) {
+ if (s->airport.psa != nullptr) {
s->airport.psa->feature = GSF_AIRPORTS;
s->airport.psa->tile = s->airport.tile;
}
@@ -303,9 +303,9 @@ static void InitializeWindowsAndCaches()
}
typedef void (CDECL *SignalHandlerPointer)(int);
-static SignalHandlerPointer _prev_segfault = NULL;
-static SignalHandlerPointer _prev_abort = NULL;
-static SignalHandlerPointer _prev_fpe = NULL;
+static SignalHandlerPointer _prev_segfault = nullptr;
+static SignalHandlerPointer _prev_abort = nullptr;
+static SignalHandlerPointer _prev_fpe = nullptr;
static void CDECL HandleSavegameLoadCrash(int signum);
@@ -375,7 +375,7 @@ static void CDECL HandleSavegameLoadCrash(int signum)
char *p = buffer;
p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
- for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
+ for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != nullptr; c = c->next) {
_saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
}
@@ -393,7 +393,7 @@ static void CDECL HandleSavegameLoadCrash(int signum)
"Please load the savegame with the appropriate NewGRFs installed.\n"
"The missing/compatible NewGRFs are:\n");
- for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (HasBit(c->flags, GCF_COMPATIBLE)) {
const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
char buf[40];
@@ -414,14 +414,14 @@ static void CDECL HandleSavegameLoadCrash(int signum)
ShowInfo(buffer);
- SignalHandlerPointer call = NULL;
+ SignalHandlerPointer call = nullptr;
switch (signum) {
case SIGSEGV: call = _prev_segfault; break;
case SIGABRT: call = _prev_abort; break;
case SIGFPE: call = _prev_fpe; break;
default: NOT_REACHED();
}
- if (call != NULL) call(signum);
+ if (call != nullptr) call(signum);
}
/**
@@ -434,7 +434,7 @@ static void FixOwnerOfRailTrack(TileIndex t)
assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
/* remove leftover rail piece from crossing (from very old savegames) */
- Train *v = NULL, *w;
+ Train *v = nullptr, *w;
FOR_ALL_TRAINS(w) {
if (w->tile == t) {
v = w;
@@ -442,7 +442,7 @@ static void FixOwnerOfRailTrack(TileIndex t)
}
}
- if (v != NULL) {
+ if (v != nullptr) {
/* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
SetTileOwner(t, v->owner);
return;
@@ -631,22 +631,22 @@ bool AfterLoadGame()
Company *c;
FOR_ALL_COMPANIES(c) {
c->name = CopyFromOldName(c->name_1);
- if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
+ if (c->name != nullptr) c->name_1 = STR_SV_UNNAMED;
c->president_name = CopyFromOldName(c->president_name_1);
- if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
+ if (c->president_name != nullptr) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
}
Station *st;
FOR_ALL_STATIONS(st) {
st->name = CopyFromOldName(st->string_id);
/* generating new name would be too much work for little effect, use the station name fallback */
- if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
+ if (st->name != nullptr) st->string_id = STR_SV_STNAME_FALLBACK;
}
Town *t;
FOR_ALL_TOWNS(t) {
t->name = CopyFromOldName(t->townnametype);
- if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
+ if (t->name != nullptr) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
}
}
@@ -676,7 +676,7 @@ bool AfterLoadGame()
/* Check if all NewGRFs are present, we are very strict in MP mode */
GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (c->status == GCS_NOT_FOUND) {
GamelogGRFRemove(c->ident.grfid);
} else if (HasBit(c->flags, GCF_COMPATIBLE)) {
@@ -787,7 +787,7 @@ bool AfterLoadGame()
{
Company *c;
FOR_ALL_COMPANIES(c) {
- if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
+ if (c->is_ai && c->ai_instance == nullptr) AI::StartNew(c->index);
}
}
@@ -987,7 +987,7 @@ bool AfterLoadGame()
if (IsSavegameVersionBefore(SLV_16)) {
Company *c;
FOR_ALL_COMPANIES(c) {
- c->engine_renew_list = NULL;
+ c->engine_renew_list = nullptr;
c->settings.engine_renew = false;
c->settings.engine_renew_months = 6;
c->settings.engine_renew_money = 100000;
@@ -1000,7 +1000,7 @@ bool AfterLoadGame()
* companies are 'invalid'.
*/
c = Company::GetIfValid(COMPANY_FIRST);
- if (!_network_dedicated && c != NULL) {
+ if (!_network_dedicated && c != nullptr) {
c->settings = _settings_client.company;
}
}
@@ -1104,7 +1104,7 @@ bool AfterLoadGame()
}
if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
const Town *town = CalcClosestTownFromTile(t);
- if (town != NULL) SetTownIndex(t, town->index);
+ if (town != nullptr) SetTownIndex(t, town->index);
}
_m[t].m4 = 0;
break;
@@ -1711,9 +1711,9 @@ bool AfterLoadGame()
Vehicle *v;
FOR_ALL_VEHICLES(v) {
- if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
+ if (v->orders.list != nullptr && v->orders.list->GetFirstOrder() != nullptr && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
v->orders.list->FreeChain();
- v->orders.list = NULL;
+ v->orders.list = nullptr;
}
v->current_order.ConvertFromOldSavegame();
@@ -2165,7 +2165,7 @@ bool AfterLoadGame()
FOR_ALL_DISASTERVEHICLES(v) {
if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
- if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
+ if (u == nullptr || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
delete v;
}
}
@@ -2186,7 +2186,7 @@ bool AfterLoadGame()
assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
assert(CargoPayment::CanAllocateItem());
Vehicle *v = *iter;
- if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
+ if (v->cargo_payment == nullptr) v->cargo_payment = new CargoPayment(v);
}
}
}
@@ -2199,7 +2199,7 @@ bool AfterLoadGame()
for (auto tile = _animated_tiles.begin(); tile < _animated_tiles.end(); /* Nothing */) {
/* Remove if tile is not animated */
- bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == NULL;
+ bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == nullptr;
/* and remove if duplicate */
for (auto j = _animated_tiles.begin(); !remove && j < tile; j++) {
@@ -2271,7 +2271,7 @@ bool AfterLoadGame()
/* Town -> Town */
const Station *ss = Station::GetIfValid(s->src);
const Station *sd = Station::GetIfValid(s->dst);
- if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
+ if (ss != nullptr && sd != nullptr && ss->owner == sd->owner &&
Company::IsValidID(ss->owner)) {
s->src_type = s->dst_type = ST_TOWN;
s->src = ss->town->index;
@@ -2438,13 +2438,13 @@ bool AfterLoadGame()
FOR_ALL_AIRCRAFT(v) {
if (!v->IsNormalAircraft()) continue;
Station *st = GetTargetAirportIfValid(v);
- if (st == NULL && v->state != FLYING) {
+ if (st == nullptr && v->state != FLYING) {
v->state = FLYING;
UpdateAircraftCache(v);
AircraftNextAirportPos_and_Order(v);
/* get aircraft back on running altitude */
if ((v->vehstatus & VS_CRASHED) == 0) {
- GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
+ GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
}
}
@@ -2506,11 +2506,11 @@ bool AfterLoadGame()
* order they have in the pool. */
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
- if (wp->name != NULL) wp->town_cn = UINT16_MAX;
+ if (wp->name != nullptr) wp->town_cn = UINT16_MAX;
}
FOR_ALL_WAYPOINTS(wp) {
- if (wp->name != NULL) MakeDefaultName(wp);
+ if (wp->name != nullptr) MakeDefaultName(wp);
}
}
@@ -2742,7 +2742,7 @@ bool AfterLoadGame()
if (!IsSavegameVersionBefore(SLV_76)) {
Industry *ind;
FOR_ALL_INDUSTRIES(ind) {
- assert(ind->psa != NULL);
+ assert(ind->psa != nullptr);
/* Check if the old storage was empty. */
bool is_empty = true;
@@ -2757,7 +2757,7 @@ bool AfterLoadGame()
ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
} else {
delete ind->psa;
- ind->psa = NULL;
+ ind->psa = nullptr;
}
}
}
@@ -2766,7 +2766,7 @@ bool AfterLoadGame()
Station *st;
FOR_ALL_STATIONS(st) {
if (!(st->facilities & FACIL_AIRPORT)) continue;
- assert(st->airport.psa != NULL);
+ assert(st->airport.psa != nullptr);
/* Check if the old storage was empty. */
bool is_empty = true;
@@ -2781,7 +2781,7 @@ bool AfterLoadGame()
st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
} else {
delete st->airport.psa;
- st->airport.psa = NULL;
+ st->airport.psa = nullptr;
}
}
@@ -2821,12 +2821,12 @@ bool AfterLoadGame()
/* Set the default cargo requirement for town growth */
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
- if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
+ if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
break;
case LT_TROPIC:
- if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
- if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
+ if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
+ if (FindFirstCargoWithTownEffect(TE_WATER) != nullptr) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
break;
}
}
@@ -2946,7 +2946,7 @@ bool AfterLoadGame()
TileIndex prev_tile = v->tile;
uint prev_tile_skip = 0;
uint cur_skip = 0;
- for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
+ for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
if (u->tile != prev_tile) {
prev_tile_skip = cur_skip;
prev_tile = u->tile;
@@ -2980,7 +2980,7 @@ bool AfterLoadGame()
}
while (cur_skip > skip_frames[0]) {
RoadVehicle *u = v;
- RoadVehicle *prev = NULL;
+ RoadVehicle *prev = nullptr;
for (uint sf : skip_frames) {
extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
if (sf >= cur_skip) IndividualRoadVehicleController(u, prev);
@@ -3111,7 +3111,7 @@ bool AfterLoadGame()
} else {
/* Link neutral station back to industry, as this is not saved. */
Industry *ind;
- FOR_ALL_INDUSTRIES(ind) if (ind->neutral_station != NULL) ind->neutral_station->industry = ind;
+ FOR_ALL_INDUSTRIES(ind) if (ind->neutral_station != nullptr) ind->neutral_station->industry = ind;
}
if (IsSavegameVersionBefore(SLV_TREES_WATER_CLASS)) {
diff --git a/src/saveload/ai_sl.cpp b/src/saveload/ai_sl.cpp
index 2492bb666..336c773d5 100644
--- a/src/saveload/ai_sl.cpp
+++ b/src/saveload/ai_sl.cpp
@@ -53,7 +53,7 @@ static void SaveReal_AIPL(int *index_ptr)
_ai_saveload_settings[0] = '\0';
config->SettingsToString(_ai_saveload_settings, lastof(_ai_saveload_settings));
- SlObject(NULL, _ai_company);
+ SlObject(nullptr, _ai_company);
/* If the AI was active, store his data too */
if (Company::IsValidAiID(index)) AI::Save(index);
}
@@ -62,7 +62,7 @@ static void Load_AIPL()
{
/* Free all current data */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
- AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(NULL);
+ AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(nullptr);
}
CompanyID index;
@@ -71,7 +71,7 @@ static void Load_AIPL()
_ai_saveload_is_random = 0;
_ai_saveload_version = -1;
- SlObject(NULL, _ai_company);
+ SlObject(nullptr, _ai_company);
if (_networking && !_network_server) {
if (Company::IsValidAiID(index)) AIInstance::LoadEmpty();
@@ -81,7 +81,7 @@ static void Load_AIPL()
AIConfig *config = AIConfig::GetConfig(index, AIConfig::SSS_FORCE_GAME);
if (StrEmpty(_ai_saveload_name)) {
/* A random AI. */
- config->Change(NULL, -1, false, true);
+ config->Change(nullptr, -1, false, true);
} else {
config->Change(_ai_saveload_name, _ai_saveload_version, false, _ai_saveload_is_random);
if (!config->HasScript()) {
@@ -125,5 +125,5 @@ static void Save_AIPL()
}
extern const ChunkHandler _ai_chunk_handlers[] = {
- { 'AIPL', Save_AIPL, Load_AIPL, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'AIPL', Save_AIPL, Load_AIPL, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/airport_sl.cpp b/src/saveload/airport_sl.cpp
index 1172d2593..ef207bacb 100644
--- a/src/saveload/airport_sl.cpp
+++ b/src/saveload/airport_sl.cpp
@@ -37,6 +37,6 @@ static void Load_ATID()
}
extern const ChunkHandler _airport_chunk_handlers[] = {
- { 'ATID', Save_ATID, Load_ATID, NULL, NULL, CH_ARRAY },
- { 'APID', Save_APID, Load_APID, NULL, NULL, CH_ARRAY | CH_LAST },
+ { 'ATID', Save_ATID, Load_ATID, nullptr, nullptr, CH_ARRAY },
+ { 'APID', Save_APID, Load_APID, nullptr, nullptr, CH_ARRAY | CH_LAST },
};
diff --git a/src/saveload/animated_tile_sl.cpp b/src/saveload/animated_tile_sl.cpp
index f82950c50..aab06f667 100644
--- a/src/saveload/animated_tile_sl.cpp
+++ b/src/saveload/animated_tile_sl.cpp
@@ -58,5 +58,5 @@ static void Load_ANIT()
* the animated tile table.
*/
extern const ChunkHandler _animated_tile_chunk_handlers[] = {
- { 'ANIT', Save_ANIT, Load_ANIT, NULL, NULL, CH_RIFF | CH_LAST},
+ { 'ANIT', Save_ANIT, Load_ANIT, nullptr, nullptr, CH_RIFF | CH_LAST},
};
diff --git a/src/saveload/autoreplace_sl.cpp b/src/saveload/autoreplace_sl.cpp
index 1798df1ad..6493b6f45 100644
--- a/src/saveload/autoreplace_sl.cpp
+++ b/src/saveload/autoreplace_sl.cpp
@@ -63,5 +63,5 @@ static void Ptrs_ERNW()
}
extern const ChunkHandler _autoreplace_chunk_handlers[] = {
- { 'ERNW', Save_ERNW, Load_ERNW, Ptrs_ERNW, NULL, CH_ARRAY | CH_LAST},
+ { 'ERNW', Save_ERNW, Load_ERNW, Ptrs_ERNW, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/cargomonitor_sl.cpp b/src/saveload/cargomonitor_sl.cpp
index 9a313970f..97acc435e 100644
--- a/src/saveload/cargomonitor_sl.cpp
+++ b/src/saveload/cargomonitor_sl.cpp
@@ -121,6 +121,6 @@ static void LoadPickup()
/** Chunk definition of the cargomonitoring maps. */
extern const ChunkHandler _cargomonitor_chunk_handlers[] = {
- { 'CMDL', SaveDelivery, LoadDelivery, NULL, NULL, CH_ARRAY},
- { 'CMPU', SavePickup, LoadPickup, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'CMDL', SaveDelivery, LoadDelivery, nullptr, nullptr, CH_ARRAY},
+ { 'CMPU', SavePickup, LoadPickup, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/cargopacket_sl.cpp b/src/saveload/cargopacket_sl.cpp
index e3f372e9a..51cdf1cf1 100644
--- a/src/saveload/cargopacket_sl.cpp
+++ b/src/saveload/cargopacket_sl.cpp
@@ -139,5 +139,5 @@ static void Load_CAPA()
/** Chunk handlers related to cargo packets. */
extern const ChunkHandler _cargopacket_chunk_handlers[] = {
- { 'CAPA', Save_CAPA, Load_CAPA, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'CAPA', Save_CAPA, Load_CAPA, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/cheat_sl.cpp b/src/saveload/cheat_sl.cpp
index 4616b7e85..e7b4735a9 100644
--- a/src/saveload/cheat_sl.cpp
+++ b/src/saveload/cheat_sl.cpp
@@ -51,5 +51,5 @@ static void Load_CHTS()
/** Chunk handlers related to cheats. */
extern const ChunkHandler _cheat_chunk_handlers[] = {
- { 'CHTS', Save_CHTS, Load_CHTS, NULL, NULL, CH_RIFF | CH_LAST},
+ { 'CHTS', Save_CHTS, Load_CHTS, nullptr, nullptr, CH_RIFF | CH_LAST},
};
diff --git a/src/saveload/company_sl.cpp b/src/saveload/company_sl.cpp
index a51f8081b..6c88db727 100644
--- a/src/saveload/company_sl.cpp
+++ b/src/saveload/company_sl.cpp
@@ -111,7 +111,7 @@ void AfterLoadCompanyStats()
switch (GetTileType(tile)) {
case MP_RAILWAY:
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
uint pieces = 1;
if (IsPlainRail(tile)) {
TrackBits bits = GetTrackBits(tile);
@@ -127,7 +127,7 @@ void AfterLoadCompanyStats()
case MP_ROAD: {
if (IsLevelCrossing(tile)) {
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
+ if (c != nullptr) c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
}
/* Iterate all present road types as each can have a different owner. */
@@ -135,19 +135,19 @@ void AfterLoadCompanyStats()
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
c = Company::GetIfValid(IsRoadDepot(tile) ? GetTileOwner(tile) : GetRoadOwner(tile, rt));
/* A level crossings and depots have two road bits. */
- if (c != NULL) c->infrastructure.road[rt] += IsNormalRoad(tile) ? CountBits(GetRoadBits(tile, rt)) : 2;
+ if (c != nullptr) c->infrastructure.road[rt] += IsNormalRoad(tile) ? CountBits(GetRoadBits(tile, rt)) : 2;
}
break;
}
case MP_STATION:
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL && GetStationType(tile) != STATION_AIRPORT && !IsBuoy(tile)) c->infrastructure.station++;
+ if (c != nullptr && GetStationType(tile) != STATION_AIRPORT && !IsBuoy(tile)) c->infrastructure.station++;
switch (GetStationType(tile)) {
case STATION_RAIL:
case STATION_WAYPOINT:
- if (c != NULL && !IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]++;
+ if (c != nullptr && !IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]++;
break;
case STATION_BUS:
@@ -156,7 +156,7 @@ void AfterLoadCompanyStats()
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) c->infrastructure.road[rt] += 2; // A road stop has two road bits.
+ if (c != nullptr) c->infrastructure.road[rt] += 2; // A road stop has two road bits.
}
break;
}
@@ -164,7 +164,7 @@ void AfterLoadCompanyStats()
case STATION_DOCK:
case STATION_BUOY:
if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
- if (c != NULL) c->infrastructure.water++;
+ if (c != nullptr) c->infrastructure.water++;
}
break;
@@ -176,7 +176,7 @@ void AfterLoadCompanyStats()
case MP_WATER:
if (IsShipDepot(tile) || IsLock(tile)) {
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
if (IsShipDepot(tile)) c->infrastructure.water += LOCK_DEPOT_TILE_FACTOR;
if (IsLock(tile) && GetLockPart(tile) == LOCK_PART_MIDDLE) {
/* The middle tile specifies the owner of the lock. */
@@ -190,7 +190,7 @@ void AfterLoadCompanyStats()
case MP_OBJECT:
if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) c->infrastructure.water++;
+ if (c != nullptr) c->infrastructure.water++;
}
break;
@@ -205,7 +205,7 @@ void AfterLoadCompanyStats()
switch (GetTunnelBridgeTransportType(tile)) {
case TRANSPORT_RAIL:
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) c->infrastructure.rail[GetRailType(tile)] += len;
+ if (c != nullptr) c->infrastructure.rail[GetRailType(tile)] += len;
break;
case TRANSPORT_ROAD: {
@@ -213,14 +213,14 @@ void AfterLoadCompanyStats()
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) c->infrastructure.road[rt] += len * 2; // A full diagonal road has two road bits.
+ if (c != nullptr) c->infrastructure.road[rt] += len * 2; // A full diagonal road has two road bits.
}
break;
}
case TRANSPORT_WATER:
c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) c->infrastructure.water += len;
+ if (c != nullptr) c->infrastructure.water += len;
break;
default:
@@ -414,7 +414,7 @@ static void SaveLoad_PLYR_common(Company *c, CompanyProperties *cprops)
int i;
SlObject(cprops, _company_desc);
- if (c != NULL) {
+ if (c != nullptr) {
SlObject(c, _company_settings_desc);
} else {
char nothing;
@@ -444,7 +444,7 @@ static void SaveLoad_PLYR_common(Company *c, CompanyProperties *cprops)
/* Write each livery entry. */
int num_liveries = IsSavegameVersionBefore(SLV_63) ? LS_END - 4 : (IsSavegameVersionBefore(SLV_85) ? LS_END - 2: LS_END);
bool update_in_use = IsSavegameVersionBefore(SLV_GROUP_LIVERIES);
- if (c != NULL) {
+ if (c != nullptr) {
for (i = 0; i < num_liveries; i++) {
SlObject(&c->livery[i], _company_livery_desc);
if (update_in_use && i != LS_DEFAULT) {
@@ -507,7 +507,7 @@ static void Check_PLYR()
int index;
while ((index = SlIterateArray()) != -1) {
CompanyProperties *cprops = new CompanyProperties();
- SaveLoad_PLYR_common(NULL, cprops);
+ SaveLoad_PLYR_common(nullptr, cprops);
/* We do not load old custom names */
if (IsSavegameVersionBefore(SLV_84)) {
@@ -520,7 +520,7 @@ static void Check_PLYR()
}
}
- if (cprops->name == NULL && !IsInsideMM(cprops->name_1, SPECSTR_COMPANY_NAME_START, SPECSTR_COMPANY_NAME_LAST + 1) &&
+ if (cprops->name == nullptr && !IsInsideMM(cprops->name_1, SPECSTR_COMPANY_NAME_START, SPECSTR_COMPANY_NAME_LAST + 1) &&
cprops->name_1 != STR_GAME_SAVELOAD_NOT_AVAILABLE && cprops->name_1 != STR_SV_UNNAMED &&
cprops->name_1 != SPECSTR_ANDCO_NAME && cprops->name_1 != SPECSTR_PRESIDENT_NAME &&
cprops->name_1 != SPECSTR_SILLY_NAME) {
diff --git a/src/saveload/depot_sl.cpp b/src/saveload/depot_sl.cpp
index b92417693..74559f923 100644
--- a/src/saveload/depot_sl.cpp
+++ b/src/saveload/depot_sl.cpp
@@ -64,5 +64,5 @@ static void Ptrs_DEPT()
}
extern const ChunkHandler _depot_chunk_handlers[] = {
- { 'DEPT', Save_DEPT, Load_DEPT, Ptrs_DEPT, NULL, CH_ARRAY | CH_LAST},
+ { 'DEPT', Save_DEPT, Load_DEPT, Ptrs_DEPT, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/economy_sl.cpp b/src/saveload/economy_sl.cpp
index 0ddab1351..6161f668f 100644
--- a/src/saveload/economy_sl.cpp
+++ b/src/saveload/economy_sl.cpp
@@ -22,8 +22,8 @@ static void Load_PRIC()
{
/* Old games store 49 base prices, very old games store them as int32 */
int vt = IsSavegameVersionBefore(SLV_65) ? SLE_FILE_I32 : SLE_FILE_I64;
- SlArray(NULL, 49, vt | SLE_VAR_NULL);
- SlArray(NULL, 49, SLE_FILE_U16 | SLE_VAR_NULL);
+ SlArray(nullptr, 49, vt | SLE_VAR_NULL);
+ SlArray(nullptr, 49, SLE_FILE_U16 | SLE_VAR_NULL);
}
/** Cargo payment rates in pre 126 savegames */
@@ -31,8 +31,8 @@ static void Load_CAPR()
{
uint num_cargo = IsSavegameVersionBefore(SLV_55) ? 12 : IsSavegameVersionBefore(SLV_EXTEND_CARGOTYPES) ? 32 : NUM_CARGO;
int vt = IsSavegameVersionBefore(SLV_65) ? SLE_FILE_I32 : SLE_FILE_I64;
- SlArray(NULL, num_cargo, vt | SLE_VAR_NULL);
- SlArray(NULL, num_cargo, SLE_FILE_U16 | SLE_VAR_NULL);
+ SlArray(nullptr, num_cargo, vt | SLE_VAR_NULL);
+ SlArray(nullptr, num_cargo, SLE_FILE_U16 | SLE_VAR_NULL);
}
static const SaveLoad _economy_desc[] = {
@@ -101,8 +101,8 @@ static void Ptrs_CAPY()
extern const ChunkHandler _economy_chunk_handlers[] = {
- { 'CAPY', Save_CAPY, Load_CAPY, Ptrs_CAPY, NULL, CH_ARRAY},
- { 'PRIC', NULL, Load_PRIC, NULL, NULL, CH_RIFF | CH_AUTO_LENGTH},
- { 'CAPR', NULL, Load_CAPR, NULL, NULL, CH_RIFF | CH_AUTO_LENGTH},
- { 'ECMY', Save_ECMY, Load_ECMY, NULL, NULL, CH_RIFF | CH_LAST},
+ { 'CAPY', Save_CAPY, Load_CAPY, Ptrs_CAPY, nullptr, CH_ARRAY},
+ { 'PRIC', nullptr, Load_PRIC, nullptr, nullptr, CH_RIFF | CH_AUTO_LENGTH},
+ { 'CAPR', nullptr, Load_CAPR, nullptr, nullptr, CH_RIFF | CH_AUTO_LENGTH},
+ { 'ECMY', Save_ECMY, Load_ECMY, nullptr, nullptr, CH_RIFF | CH_LAST},
};
diff --git a/src/saveload/engine_sl.cpp b/src/saveload/engine_sl.cpp
index 891e30783..0fe190a0f 100644
--- a/src/saveload/engine_sl.cpp
+++ b/src/saveload/engine_sl.cpp
@@ -68,7 +68,7 @@ static Engine* CallocEngine()
*/
static void FreeEngine(Engine *e)
{
- if (e != NULL) {
+ if (e != nullptr) {
e->~Engine();
free(e);
}
@@ -141,7 +141,7 @@ void CopyTempEngineData()
e->preview_wait = se->preview_wait;
e->company_avail = se->company_avail;
e->company_hidden = se->company_hidden;
- if (se->name != NULL) e->name = stredup(se->name);
+ if (se->name != nullptr) e->name = stredup(se->name);
}
/* Get rid of temporary data */
@@ -197,7 +197,7 @@ static void Load_EIDS()
}
extern const ChunkHandler _engine_chunk_handlers[] = {
- { 'EIDS', Save_EIDS, Load_EIDS, NULL, NULL, CH_ARRAY },
- { 'ENGN', Save_ENGN, Load_ENGN, NULL, NULL, CH_ARRAY },
- { 'ENGS', NULL, Load_ENGS, NULL, NULL, CH_RIFF | CH_LAST },
+ { 'EIDS', Save_EIDS, Load_EIDS, nullptr, nullptr, CH_ARRAY },
+ { 'ENGN', Save_ENGN, Load_ENGN, nullptr, nullptr, CH_ARRAY },
+ { 'ENGS', nullptr, Load_ENGS, nullptr, nullptr, CH_RIFF | CH_LAST },
};
diff --git a/src/saveload/game_sl.cpp b/src/saveload/game_sl.cpp
index 52e8ac521..3602f0f29 100644
--- a/src/saveload/game_sl.cpp
+++ b/src/saveload/game_sl.cpp
@@ -52,19 +52,19 @@ static void SaveReal_GSDT(int *index_ptr)
_game_saveload_settings[0] = '\0';
config->SettingsToString(_game_saveload_settings, lastof(_game_saveload_settings));
- SlObject(NULL, _game_script);
+ SlObject(nullptr, _game_script);
Game::Save();
}
static void Load_GSDT()
{
/* Free all current data */
- GameConfig::GetConfig(GameConfig::SSS_FORCE_GAME)->Change(NULL);
+ GameConfig::GetConfig(GameConfig::SSS_FORCE_GAME)->Change(nullptr);
if ((CompanyID)SlIterateArray() == (CompanyID)-1) return;
_game_saveload_version = -1;
- SlObject(NULL, _game_script);
+ SlObject(nullptr, _game_script);
if (_networking && !_network_server) {
GameInstance::LoadEmpty();
@@ -110,7 +110,7 @@ static void Load_GSDT()
static void Save_GSDT()
{
SlSetArrayIndex(0);
- SlAutolength((AutolengthProc *)SaveReal_GSDT, NULL);
+ SlAutolength((AutolengthProc *)SaveReal_GSDT, nullptr);
}
extern GameStrings *_current_data;
@@ -134,10 +134,10 @@ static void SaveReal_GSTR(const LanguageStrings *ls)
_game_saveload_string = ls->language;
_game_saveload_strings = (uint)ls->lines.size();
- SlObject(NULL, _game_language_header);
+ SlObject(nullptr, _game_language_header);
for (const auto &i : ls->lines) {
_game_saveload_string = i.c_str();
- SlObject(NULL, _game_language_string);
+ SlObject(nullptr, _game_language_string);
}
}
@@ -147,22 +147,22 @@ static void Load_GSTR()
_current_data = new GameStrings();
while (SlIterateArray() != -1) {
- _game_saveload_string = NULL;
- SlObject(NULL, _game_language_header);
+ _game_saveload_string = nullptr;
+ SlObject(nullptr, _game_language_header);
- std::unique_ptr<LanguageStrings> ls(new LanguageStrings(_game_saveload_string != NULL ? _game_saveload_string : ""));
+ std::unique_ptr<LanguageStrings> ls(new LanguageStrings(_game_saveload_string != nullptr ? _game_saveload_string : ""));
for (uint i = 0; i < _game_saveload_strings; i++) {
- SlObject(NULL, _game_language_string);
- ls->lines.emplace_back(_game_saveload_string != NULL ? _game_saveload_string : "");
+ SlObject(nullptr, _game_language_string);
+ ls->lines.emplace_back(_game_saveload_string != nullptr ? _game_saveload_string : "");
}
_current_data->raw_strings.push_back(std::move(ls));
}
- /* If there were no strings in the savegame, set GameStrings to NULL */
+ /* If there were no strings in the savegame, set GameStrings to nullptr */
if (_current_data->raw_strings.size() == 0) {
delete _current_data;
- _current_data = NULL;
+ _current_data = nullptr;
return;
}
@@ -172,7 +172,7 @@ static void Load_GSTR()
static void Save_GSTR()
{
- if (_current_data == NULL) return;
+ if (_current_data == nullptr) return;
for (uint i = 0; i < _current_data->raw_strings.size(); i++) {
SlSetArrayIndex(i);
@@ -181,6 +181,6 @@ static void Save_GSTR()
}
extern const ChunkHandler _game_chunk_handlers[] = {
- { 'GSTR', Save_GSTR, Load_GSTR, NULL, NULL, CH_ARRAY },
- { 'GSDT', Save_GSDT, Load_GSDT, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'GSTR', Save_GSTR, Load_GSTR, nullptr, nullptr, CH_ARRAY },
+ { 'GSDT', Save_GSDT, Load_GSDT, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/gamelog_sl.cpp b/src/saveload/gamelog_sl.cpp
index d1c502d3b..812d716ec 100644
--- a/src/saveload/gamelog_sl.cpp
+++ b/src/saveload/gamelog_sl.cpp
@@ -106,7 +106,7 @@ assert_compile(lengthof(_glog_desc) == GLCT_END);
static void Load_GLOG_common(LoggedAction *&gamelog_action, uint &gamelog_actions)
{
- assert(gamelog_action == NULL);
+ assert(gamelog_action == nullptr);
assert(gamelog_actions == 0);
GamelogActionType at;
@@ -117,7 +117,7 @@ static void Load_GLOG_common(LoggedAction *&gamelog_action, uint &gamelog_action
la->at = at;
SlObject(la, _glog_action_desc); // has to be saved after 'DATE'!
- la->change = NULL;
+ la->change = nullptr;
la->changes = 0;
GamelogChangeType ct;
@@ -125,7 +125,7 @@ static void Load_GLOG_common(LoggedAction *&gamelog_action, uint &gamelog_action
la->change = ReallocT(la->change, la->changes + 1);
LoggedChange *lc = &la->change[la->changes++];
- /* for SLE_STR, pointer has to be valid! so make it NULL */
+ /* for SLE_STR, pointer has to be valid! so make it nullptr */
memset(lc, 0, sizeof(*lc));
lc->ct = ct;
@@ -179,5 +179,5 @@ static void Check_GLOG()
}
extern const ChunkHandler _gamelog_chunk_handlers[] = {
- { 'GLOG', Save_GLOG, Load_GLOG, NULL, Check_GLOG, CH_RIFF | CH_LAST }
+ { 'GLOG', Save_GLOG, Load_GLOG, nullptr, Check_GLOG, CH_RIFF | CH_LAST }
};
diff --git a/src/saveload/goal_sl.cpp b/src/saveload/goal_sl.cpp
index a8cdc2305..b636dcf6a 100644
--- a/src/saveload/goal_sl.cpp
+++ b/src/saveload/goal_sl.cpp
@@ -45,5 +45,5 @@ static void Load_GOAL()
}
extern const ChunkHandler _goal_chunk_handlers[] = {
- { 'GOAL', Save_GOAL, Load_GOAL, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'GOAL', Save_GOAL, Load_GOAL, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/group_sl.cpp b/src/saveload/group_sl.cpp
index 025c8ee3a..e43140132 100644
--- a/src/saveload/group_sl.cpp
+++ b/src/saveload/group_sl.cpp
@@ -61,5 +61,5 @@ static void Load_GRPS()
}
extern const ChunkHandler _group_chunk_handlers[] = {
- { 'GRPS', Save_GRPS, Load_GRPS, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'GRPS', Save_GRPS, Load_GRPS, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/industry_sl.cpp b/src/saveload/industry_sl.cpp
index e5a0b74a3..391e5fbc3 100644
--- a/src/saveload/industry_sl.cpp
+++ b/src/saveload/industry_sl.cpp
@@ -183,9 +183,9 @@ static void Load_ITBL()
}
extern const ChunkHandler _industry_chunk_handlers[] = {
- { 'INDY', Save_INDY, Load_INDY, Ptrs_INDY, NULL, CH_ARRAY},
- { 'IIDS', Save_IIDS, Load_IIDS, NULL, NULL, CH_ARRAY},
- { 'TIDS', Save_TIDS, Load_TIDS, NULL, NULL, CH_ARRAY},
- { 'IBLD', LoadSave_IBLD, LoadSave_IBLD, NULL, NULL, CH_RIFF},
- { 'ITBL', Save_ITBL, Load_ITBL, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'INDY', Save_INDY, Load_INDY, Ptrs_INDY, nullptr, CH_ARRAY},
+ { 'IIDS', Save_IIDS, Load_IIDS, nullptr, nullptr, CH_ARRAY},
+ { 'TIDS', Save_TIDS, Load_TIDS, nullptr, nullptr, CH_ARRAY},
+ { 'IBLD', LoadSave_IBLD, LoadSave_IBLD, nullptr, nullptr, CH_RIFF},
+ { 'ITBL', Save_ITBL, Load_ITBL, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/labelmaps_sl.cpp b/src/saveload/labelmaps_sl.cpp
index dd71f1c3e..6236e190e 100644
--- a/src/saveload/labelmaps_sl.cpp
+++ b/src/saveload/labelmaps_sl.cpp
@@ -119,6 +119,6 @@ static void Load_RAIL()
}
extern const ChunkHandler _labelmaps_chunk_handlers[] = {
- { 'RAIL', Save_RAIL, Load_RAIL, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'RAIL', Save_RAIL, Load_RAIL, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/linkgraph_sl.cpp b/src/saveload/linkgraph_sl.cpp
index 90c056eba..172025dce 100644
--- a/src/saveload/linkgraph_sl.cpp
+++ b/src/saveload/linkgraph_sl.cpp
@@ -64,7 +64,7 @@ const SaveLoad *GetLinkGraphJobDesc()
int setting = 0;
const SettingDesc *desc = GetSettingDescription(setting);
while (desc->save.cmd != SL_END) {
- if (desc->desc.name != NULL && strncmp(desc->desc.name, prefix, prefixlen) == 0) {
+ if (desc->desc.name != nullptr && strncmp(desc->desc.name, prefix, prefixlen) == 0) {
SaveLoad sl = desc->save;
char *&address = reinterpret_cast<char *&>(sl.address);
address -= offset_gamesettings;
@@ -290,7 +290,7 @@ static void Ptrs_LGRS()
}
extern const ChunkHandler _linkgraph_chunk_handlers[] = {
- { 'LGRP', Save_LGRP, Load_LGRP, NULL, NULL, CH_ARRAY },
- { 'LGRJ', Save_LGRJ, Load_LGRJ, NULL, NULL, CH_ARRAY },
- { 'LGRS', Save_LGRS, Load_LGRS, Ptrs_LGRS, NULL, CH_LAST }
+ { 'LGRP', Save_LGRP, Load_LGRP, nullptr, nullptr, CH_ARRAY },
+ { 'LGRJ', Save_LGRJ, Load_LGRJ, nullptr, nullptr, CH_ARRAY },
+ { 'LGRS', Save_LGRS, Load_LGRS, Ptrs_LGRS, nullptr, CH_LAST }
};
diff --git a/src/saveload/map_sl.cpp b/src/saveload/map_sl.cpp
index 5402ecc0d..18c135117 100644
--- a/src/saveload/map_sl.cpp
+++ b/src/saveload/map_sl.cpp
@@ -297,15 +297,15 @@ static void Save_MAP8()
extern const ChunkHandler _map_chunk_handlers[] = {
- { 'MAPS', Save_MAPS, Load_MAPS, NULL, Check_MAPS, CH_RIFF },
- { 'MAPT', Save_MAPT, Load_MAPT, NULL, NULL, CH_RIFF },
- { 'MAPH', Save_MAPH, Load_MAPH, NULL, NULL, CH_RIFF },
- { 'MAPO', Save_MAP1, Load_MAP1, NULL, NULL, CH_RIFF },
- { 'MAP2', Save_MAP2, Load_MAP2, NULL, NULL, CH_RIFF },
- { 'M3LO', Save_MAP3, Load_MAP3, NULL, NULL, CH_RIFF },
- { 'M3HI', Save_MAP4, Load_MAP4, NULL, NULL, CH_RIFF },
- { 'MAP5', Save_MAP5, Load_MAP5, NULL, NULL, CH_RIFF },
- { 'MAPE', Save_MAP6, Load_MAP6, NULL, NULL, CH_RIFF },
- { 'MAP7', Save_MAP7, Load_MAP7, NULL, NULL, CH_RIFF },
- { 'MAP8', Save_MAP8, Load_MAP8, NULL, NULL, CH_RIFF | CH_LAST },
+ { 'MAPS', Save_MAPS, Load_MAPS, nullptr, Check_MAPS, CH_RIFF },
+ { 'MAPT', Save_MAPT, Load_MAPT, nullptr, nullptr, CH_RIFF },
+ { 'MAPH', Save_MAPH, Load_MAPH, nullptr, nullptr, CH_RIFF },
+ { 'MAPO', Save_MAP1, Load_MAP1, nullptr, nullptr, CH_RIFF },
+ { 'MAP2', Save_MAP2, Load_MAP2, nullptr, nullptr, CH_RIFF },
+ { 'M3LO', Save_MAP3, Load_MAP3, nullptr, nullptr, CH_RIFF },
+ { 'M3HI', Save_MAP4, Load_MAP4, nullptr, nullptr, CH_RIFF },
+ { 'MAP5', Save_MAP5, Load_MAP5, nullptr, nullptr, CH_RIFF },
+ { 'MAPE', Save_MAP6, Load_MAP6, nullptr, nullptr, CH_RIFF },
+ { 'MAP7', Save_MAP7, Load_MAP7, nullptr, nullptr, CH_RIFF },
+ { 'MAP8', Save_MAP8, Load_MAP8, nullptr, nullptr, CH_RIFF | CH_LAST },
};
diff --git a/src/saveload/misc_sl.cpp b/src/saveload/misc_sl.cpp
index cca3365b5..9755f74e1 100644
--- a/src/saveload/misc_sl.cpp
+++ b/src/saveload/misc_sl.cpp
@@ -36,7 +36,7 @@ void SaveViewportBeforeSaveGame()
{
const Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
- if (w != NULL) {
+ if (w != nullptr) {
_saved_scrollpos_x = w->viewport->scrollpos_x;
_saved_scrollpos_y = w->viewport->scrollpos_y;
_saved_scrollpos_zoom = w->viewport->zoom;
@@ -151,6 +151,6 @@ static void SaveLoad_VIEW()
}
extern const ChunkHandler _misc_chunk_handlers[] = {
- { 'DATE', SaveLoad_DATE, SaveLoad_DATE, NULL, Check_DATE, CH_RIFF},
- { 'VIEW', SaveLoad_VIEW, SaveLoad_VIEW, NULL, NULL, CH_RIFF | CH_LAST},
+ { 'DATE', SaveLoad_DATE, SaveLoad_DATE, nullptr, Check_DATE, CH_RIFF},
+ { 'VIEW', SaveLoad_VIEW, SaveLoad_VIEW, nullptr, nullptr, CH_RIFF | CH_LAST},
};
diff --git a/src/saveload/newgrf_sl.cpp b/src/saveload/newgrf_sl.cpp
index e40b45926..2f7dfb356 100644
--- a/src/saveload/newgrf_sl.cpp
+++ b/src/saveload/newgrf_sl.cpp
@@ -73,7 +73,7 @@ static void Save_NGRF()
{
int index = 0;
- for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
+ for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
if (HasBit(c->flags, GCF_STATIC)) continue;
SlSetArrayIndex(index++);
SlObject(c, _grfconfig_desc);
@@ -98,7 +98,7 @@ static void Load_NGRF()
if (_game_mode == GM_MENU) {
/* Intro game must not have NewGRF. */
- if (_grfconfig != NULL) SlErrorCorrupt("The intro game must not use NewGRF");
+ if (_grfconfig != nullptr) SlErrorCorrupt("The intro game must not use NewGRF");
/* Activate intro NewGRFs (townnames) */
ResetGRFConfig(false);
@@ -114,5 +114,5 @@ static void Check_NGRF()
}
extern const ChunkHandler _newgrf_chunk_handlers[] = {
- { 'NGRF', Save_NGRF, Load_NGRF, NULL, Check_NGRF, CH_ARRAY | CH_LAST }
+ { 'NGRF', Save_NGRF, Load_NGRF, nullptr, Check_NGRF, CH_ARRAY | CH_LAST }
};
diff --git a/src/saveload/object_sl.cpp b/src/saveload/object_sl.cpp
index 6b0b99e47..2ec996664 100644
--- a/src/saveload/object_sl.cpp
+++ b/src/saveload/object_sl.cpp
@@ -74,6 +74,6 @@ static void Load_OBID()
}
extern const ChunkHandler _object_chunk_handlers[] = {
- { 'OBID', Save_OBID, Load_OBID, NULL, NULL, CH_ARRAY },
- { 'OBJS', Save_OBJS, Load_OBJS, Ptrs_OBJS, NULL, CH_ARRAY | CH_LAST},
+ { 'OBID', Save_OBID, Load_OBID, nullptr, nullptr, CH_ARRAY },
+ { 'OBJS', Save_OBJS, Load_OBJS, Ptrs_OBJS, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/oldloader.cpp b/src/saveload/oldloader.cpp
index e0ad0e732..9b24750d2 100644
--- a/src/saveload/oldloader.cpp
+++ b/src/saveload/oldloader.cpp
@@ -154,11 +154,11 @@ bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
default: NOT_REACHED();
}
- /* When both pointers are NULL, we are just skipping data */
- if (base_ptr == NULL && chunk->ptr == NULL) continue;
+ /* When both pointers are nullptr, we are just skipping data */
+ if (base_ptr == nullptr && chunk->ptr == nullptr) continue;
/* Writing to the var: bits 8 to 15 have the VAR type */
- if (chunk->ptr == NULL) ptr = base_ptr + chunk->offset;
+ if (chunk->ptr == nullptr) ptr = base_ptr + chunk->offset;
/* Write the data */
switch (GetOldChunkVarType(chunk->type)) {
@@ -174,7 +174,7 @@ bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
}
/* Increase pointer base for arrays when looping */
- if (chunk->amount > 1 && chunk->ptr != NULL) ptr += CalcOldVarLen(chunk->type);
+ if (chunk->amount > 1 && chunk->ptr != nullptr) ptr += CalcOldVarLen(chunk->type);
}
}
}
@@ -259,7 +259,7 @@ static SavegameType DetermineOldSavegameType(FILE *f, char *title, const char *l
}
}
- if (title != NULL) {
+ if (title != nullptr) {
switch (type) {
case SGT_TTO: title = strecpy(title, "(TTO) ", last); break;
case SGT_TTD: title = strecpy(title, "(TTD) ", last); break;
@@ -284,14 +284,14 @@ bool LoadOldSaveGame(const char *file)
/* Open file */
ls.file = FioFOpenFile(file, "rb", NO_DIRECTORY);
- if (ls.file == NULL) {
+ if (ls.file == nullptr) {
DEBUG(oldloader, 0, "Cannot open file '%s'", file);
return false;
}
- SavegameType type = DetermineOldSavegameType(ls.file, NULL, NULL);
+ SavegameType type = DetermineOldSavegameType(ls.file, nullptr, nullptr);
- LoadOldMainProc *proc = NULL;
+ LoadOldMainProc *proc = nullptr;
switch (type) {
case SGT_TTO: proc = &LoadTTOMain; break;
@@ -303,7 +303,7 @@ bool LoadOldSaveGame(const char *file)
bool game_loaded;
try {
- game_loaded = proc != NULL && proc(&ls);
+ game_loaded = proc != nullptr && proc(&ls);
} catch (...) {
game_loaded = false;
}
@@ -323,7 +323,7 @@ void GetOldSaveGameName(const char *file, char *title, const char *last)
{
FILE *f = FioFOpenFile(file, "rb", NO_DIRECTORY);
- if (f == NULL) {
+ if (f == nullptr) {
*title = '\0';
return;
}
diff --git a/src/saveload/oldloader.h b/src/saveload/oldloader.h
index 5483440ea..a2953196b 100644
--- a/src/saveload/oldloader.h
+++ b/src/saveload/oldloader.h
@@ -90,7 +90,7 @@ struct OldChunks {
uint32 amount; ///< Amount of fields
void *ptr; ///< Pointer where to save the data (may only be set if offset is 0)
- uint offset; ///< Offset from basepointer (may only be set if ptr is NULL)
+ uint offset; ///< Offset from basepointer (may only be set if ptr is nullptr)
OldChunkProc *proc; ///< Pointer to function that is called with OC_CHUNK
};
@@ -125,12 +125,12 @@ static inline uint32 ReadUint32(LoadgameState *ls)
* - OCL_CHUNK: load another proc to load a part of the savegame, 'amount' times
* - OCL_ASSERT: to check if we are really at the place we expect to be.. because old savegames are too binary to be sure ;)
*/
-#define OCL_SVAR(type, base, offset) { type, 1, NULL, (uint)cpp_offsetof(base, offset), NULL }
-#define OCL_VAR(type, amount, pointer) { type, amount, pointer, 0, NULL }
-#define OCL_END() { OC_END, 0, NULL, 0, NULL }
-#define OCL_CNULL(type, amount) { OC_NULL | type, amount, NULL, 0, NULL }
-#define OCL_CCHUNK(type, amount, proc) { OC_CHUNK | type, amount, NULL, 0, proc }
-#define OCL_ASSERT(type, size) { OC_ASSERT | type, 1, NULL, size, NULL }
+#define OCL_SVAR(type, base, offset) { type, 1, nullptr, (uint)cpp_offsetof(base, offset), nullptr }
+#define OCL_VAR(type, amount, pointer) { type, amount, pointer, 0, nullptr }
+#define OCL_END() { OC_END, 0, nullptr, 0, nullptr }
+#define OCL_CNULL(type, amount) { OC_NULL | type, amount, nullptr, 0, nullptr }
+#define OCL_CCHUNK(type, amount, proc) { OC_CHUNK | type, amount, nullptr, 0, proc }
+#define OCL_ASSERT(type, size) { OC_ASSERT | type, 1, nullptr, size, nullptr }
#define OCL_NULL(amount) OCL_CNULL((OldChunkType)0, amount)
#define OCL_CHUNK(amount, proc) OCL_CCHUNK((OldChunkType)0, amount, proc)
diff --git a/src/saveload/oldloader_sl.cpp b/src/saveload/oldloader_sl.cpp
index a93006f1f..663934103 100644
--- a/src/saveload/oldloader_sl.cpp
+++ b/src/saveload/oldloader_sl.cpp
@@ -178,7 +178,7 @@ void FixOldVehicles()
FOR_ALL_VEHICLES(v) {
if ((size_t)v->next == 0xFFFF) {
- v->next = NULL;
+ v->next = nullptr;
} else {
v->next = Vehicle::GetIfValid((size_t)v->next);
}
@@ -452,7 +452,7 @@ static bool FixTTOEngines()
e->preview_company = INVALID_COMPANY;
e->preview_asked = (CompanyMask)-1;
e->preview_wait = 0;
- e->name = NULL;
+ e->name = nullptr;
}
return true;
@@ -621,7 +621,7 @@ static const OldChunks order_chunk[] = {
static bool LoadOldOrder(LoadgameState *ls, int num)
{
- if (!LoadChunk(ls, NULL, order_chunk)) return false;
+ if (!LoadChunk(ls, nullptr, order_chunk)) return false;
Order *o = new (num) Order();
o->AssignOrder(UnpackOldOrder(_old_order));
@@ -632,7 +632,7 @@ static bool LoadOldOrder(LoadgameState *ls, int num)
/* Relink the orders to each other (in the orders for one vehicle are behind each other,
* with an invalid order (OT_NOTHING) as indication that it is the last order */
Order *prev = Order::GetIfValid(num - 1);
- if (prev != NULL) prev->next = o;
+ if (prev != nullptr) prev->next = o;
}
return true;
@@ -646,7 +646,7 @@ static bool LoadOldAnimTileList(LoadgameState *ls, int num)
OCL_END ()
};
- if (!LoadChunk(ls, NULL, anim_chunk)) return false;
+ if (!LoadChunk(ls, nullptr, anim_chunk)) return false;
/* The first zero in the loaded array indicates the end of the list. */
for (int i = 0; i < 256; i++) {
@@ -671,7 +671,7 @@ static bool LoadOldDepot(LoadgameState *ls, int num)
if (d->xy != 0) {
/* In some cases, there could be depots referencing invalid town. */
Town *t = Town::GetIfValid(RemapTownIndex(_old_town_index));
- if (t == NULL) t = Town::GetRandom();
+ if (t == nullptr) t = Town::GetRandom();
d->town = t;
} else {
delete d;
@@ -876,7 +876,7 @@ static bool LoadOldCompanyYearly(LoadgameState *ls, int num)
if (_savegame_type == SGT_TTO && i == 6) {
_old_yearly = 0; // property maintenance
} else {
- if (!LoadChunk(ls, NULL, _company_yearly_chunk)) return false;
+ if (!LoadChunk(ls, nullptr, _company_yearly_chunk)) return false;
}
c->yearly_expenses[num][i] = _old_yearly;
@@ -1106,8 +1106,8 @@ static bool LoadOldVehicleUnion(LoadgameState *ls, int num)
uint temp = ls->total_read;
bool res;
- if (v == NULL) {
- res = LoadChunk(ls, NULL, vehicle_empty_chunk);
+ if (v == nullptr) {
+ res = LoadChunk(ls, nullptr, vehicle_empty_chunk);
} else {
switch (v->type) {
default: SlErrorCorrupt("Invalid vehicle type");
@@ -1240,7 +1240,7 @@ bool LoadOldVehicle(LoadgameState *ls, int num)
uint type = ReadByte(ls);
switch (type) {
default: return false;
- case 0x00 /* VEH_INVALID */: v = NULL; break;
+ case 0x00 /* VEH_INVALID */: v = nullptr; break;
case 0x25 /* MONORAIL */:
case 0x20 /* VEH_TRAIN */: v = new (_current_vehicle_id) Train(); break;
case 0x21 /* VEH_ROAD */: v = new (_current_vehicle_id) RoadVehicle(); break;
@@ -1251,7 +1251,7 @@ bool LoadOldVehicle(LoadgameState *ls, int num)
}
if (!LoadChunk(ls, v, vehicle_chunk)) return false;
- if (v == NULL) continue;
+ if (v == nullptr) continue;
v->refit_cap = v->cargo_cap;
SpriteID sprite = v->sprite_seq.seq[0].sprite;
@@ -1318,7 +1318,7 @@ bool LoadOldVehicle(LoadgameState *ls, int num)
/* Read the vehicle type and allocate the right vehicle */
switch (ReadByte(ls)) {
default: SlErrorCorrupt("Invalid vehicle type");
- case 0x00 /* VEH_INVALID */: v = NULL; break;
+ case 0x00 /* VEH_INVALID */: v = nullptr; break;
case 0x10 /* VEH_TRAIN */: v = new (_current_vehicle_id) Train(); break;
case 0x11 /* VEH_ROAD */: v = new (_current_vehicle_id) RoadVehicle(); break;
case 0x12 /* VEH_SHIP */: v = new (_current_vehicle_id) Ship(); break;
@@ -1328,7 +1328,7 @@ bool LoadOldVehicle(LoadgameState *ls, int num)
}
if (!LoadChunk(ls, v, vehicle_chunk)) return false;
- if (v == NULL) continue;
+ if (v == nullptr) continue;
_old_vehicle_names[_current_vehicle_id] = RemapOldStringID(_old_string_id);
@@ -1756,9 +1756,9 @@ bool LoadTTDMain(LoadgameState *ls)
/* Load the biggest chunk */
SmallStackSafeStackAlloc<byte, OLD_MAP_SIZE * 2> map3;
_old_map3 = map3.data;
- _old_vehicle_names = NULL;
+ _old_vehicle_names = nullptr;
try {
- if (!LoadChunk(ls, NULL, main_chunk)) {
+ if (!LoadChunk(ls, nullptr, main_chunk)) {
DEBUG(oldloader, 0, "Loading failed");
free(_old_vehicle_names);
return false;
@@ -1803,7 +1803,7 @@ bool LoadTTOMain(LoadgameState *ls)
_old_vehicle_names = vehnames.data;
/* Load the biggest chunk */
- if (!LoadChunk(ls, NULL, main_chunk)) {
+ if (!LoadChunk(ls, nullptr, main_chunk)) {
DEBUG(oldloader, 0, "Loading failed");
return false;
}
diff --git a/src/saveload/order_sl.cpp b/src/saveload/order_sl.cpp
index b89514d47..c21782de5 100644
--- a/src/saveload/order_sl.cpp
+++ b/src/saveload/order_sl.cpp
@@ -178,7 +178,7 @@ static void Load_ORDR()
/* The orders were built like this:
* While the order is valid, set the previous will get its next pointer set */
Order *prev = Order::GetIfValid(order_index - 1);
- if (prev != NULL) prev->next = o;
+ if (prev != nullptr) prev->next = o;
}
} else {
int index;
@@ -306,7 +306,7 @@ static void Ptrs_BKOR()
}
extern const ChunkHandler _order_chunk_handlers[] = {
- { 'BKOR', Save_BKOR, Load_BKOR, Ptrs_BKOR, NULL, CH_ARRAY},
- { 'ORDR', Save_ORDR, Load_ORDR, Ptrs_ORDR, NULL, CH_ARRAY},
- { 'ORDL', Save_ORDL, Load_ORDL, Ptrs_ORDL, NULL, CH_ARRAY | CH_LAST},
+ { 'BKOR', Save_BKOR, Load_BKOR, Ptrs_BKOR, nullptr, CH_ARRAY},
+ { 'ORDR', Save_ORDR, Load_ORDR, Ptrs_ORDR, nullptr, CH_ARRAY},
+ { 'ORDL', Save_ORDL, Load_ORDL, Ptrs_ORDL, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/saveload.cpp b/src/saveload/saveload.cpp
index f03e3d659..bab1e894f 100644
--- a/src/saveload/saveload.cpp
+++ b/src/saveload/saveload.cpp
@@ -95,7 +95,7 @@ struct ReadBuffer {
* Initialise our variables.
* @param reader The filter to actually read data.
*/
- ReadBuffer(LoadFilter *reader) : bufp(NULL), bufe(NULL), reader(reader), read(0)
+ ReadBuffer(LoadFilter *reader) : bufp(nullptr), bufe(nullptr), reader(reader), read(0)
{
}
@@ -131,7 +131,7 @@ struct MemoryDumper {
byte *bufe; ///< End of the buffer we write to.
/** Initialise our variables. */
- MemoryDumper() : buf(NULL), bufe(NULL)
+ MemoryDumper() : buf(nullptr), bufe(nullptr)
{
}
@@ -247,7 +247,7 @@ extern const ChunkHandler _airport_chunk_handlers[];
extern const ChunkHandler _object_chunk_handlers[];
extern const ChunkHandler _persistent_storage_chunk_handlers[];
-/** Array of all chunks in a savegame, \c NULL terminated. */
+/** Array of all chunks in a savegame, \c nullptr terminated. */
static const ChunkHandler * const _chunk_handlers[] = {
_gamelog_chunk_handlers,
_map_chunk_handlers,
@@ -282,7 +282,7 @@ static const ChunkHandler * const _chunk_handlers[] = {
_airport_chunk_handlers,
_object_chunk_handlers,
_persistent_storage_chunk_handlers,
- NULL,
+ nullptr,
};
/**
@@ -290,10 +290,10 @@ static const ChunkHandler * const _chunk_handlers[] = {
* @param ch the chunk handler iterator
*/
#define FOR_ALL_CHUNK_HANDLERS(ch) \
- for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != NULL; chsc++) \
- for (const ChunkHandler *ch = *chsc; ch != NULL; ch = (ch->flags & CH_LAST) ? NULL : ch + 1)
+ for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != nullptr; chsc++) \
+ for (const ChunkHandler *ch = *chsc; ch != nullptr; ch = (ch->flags & CH_LAST) ? nullptr : ch + 1)
-/** Null all pointers (convert index -> NULL) */
+/** Null all pointers (convert index -> nullptr) */
static void SlNullPointers()
{
_sl.action = SLA_NULL;
@@ -306,7 +306,7 @@ static void SlNullPointers()
DEBUG(sl, 1, "Nulling pointers");
FOR_ALL_CHUNK_HANDLERS(ch) {
- if (ch->ptrs_proc != NULL) {
+ if (ch->ptrs_proc != nullptr) {
DEBUG(sl, 2, "Nulling pointers for %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
ch->ptrs_proc();
}
@@ -331,14 +331,14 @@ void NORETURN SlError(StringID string, const char *extra_msg)
if (_sl.action == SLA_LOAD_CHECK) {
_load_check_data.error = string;
free(_load_check_data.error_data);
- _load_check_data.error_data = (extra_msg == NULL) ? NULL : stredup(extra_msg);
+ _load_check_data.error_data = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
} else {
_sl.error_str = string;
free(_sl.extra_msg);
- _sl.extra_msg = (extra_msg == NULL) ? NULL : stredup(extra_msg);
+ _sl.extra_msg = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
}
- /* We have to NULL all pointers here; we might be in a state where
+ /* We have to nullptr all pointers here; we might be in a state where
* the pointers are actually filled with indices, which means that
* when we access them during cleaning the pool dereferences of
* those indices will be made with segmentation faults as result. */
@@ -389,7 +389,7 @@ static std::thread _save_thread; ///< The thread we'r
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
{
if (_exit_game) return;
- while (_async_save_finish.load(std::memory_order_acquire) != NULL) CSleep(10);
+ while (_async_save_finish.load(std::memory_order_acquire) != nullptr) CSleep(10);
_async_save_finish.store(proc, std::memory_order_release);
}
@@ -399,8 +399,8 @@ static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
*/
void ProcessAsyncSaveFinish()
{
- AsyncSaveFinishProc proc = _async_save_finish.exchange(NULL, std::memory_order_acq_rel);
- if (proc == NULL) return;
+ AsyncSaveFinishProc proc = _async_save_finish.exchange(nullptr, std::memory_order_acq_rel);
+ if (proc == nullptr) return;
proc();
@@ -863,7 +863,7 @@ static void SlSaveLoadConv(void *ptr, VarType conv)
*/
static inline size_t SlCalcNetStringLen(const char *ptr, size_t length)
{
- if (ptr == NULL) return 0;
+ if (ptr == nullptr) return 0;
return min(strlen(ptr), length - 1);
}
@@ -948,7 +948,7 @@ static void SlString(void *ptr, size_t length, VarType conv)
case SLE_VAR_STRQ: // Malloc'd string, free previous incarnation, and allocate
free(*(char **)ptr);
if (len == 0) {
- *(char **)ptr = NULL;
+ *(char **)ptr = nullptr;
return;
} else {
*(char **)ptr = MallocT<char>(len + 1); // terminating '\0'
@@ -1043,7 +1043,7 @@ void SlArray(void *array, size_t length, VarType conv)
* Pointers cannot be saved to a savegame, so this functions gets
* the index of the item, and if not available, it hussles with
* pointers (looks really bad :()
- * Remember that a NULL item has value 0, and all
+ * Remember that a nullptr item has value 0, and all
* indices have +1, so vehicle 0 is saved as index 1.
* @param obj The object that we want to get the index of
* @param rt SLRefType type of the object the index is being sought of
@@ -1053,7 +1053,7 @@ static size_t ReferenceToInt(const void *obj, SLRefType rt)
{
assert(_sl.action == SLA_SAVE);
- if (obj == NULL) return 0;
+ if (obj == nullptr) return 0;
switch (rt) {
case REF_VEHICLE_OLD: // Old vehicles we save as new ones
@@ -1076,7 +1076,7 @@ static size_t ReferenceToInt(const void *obj, SLRefType rt)
* Pointers cannot be loaded from a savegame, so this function
* gets the index from the savegame and returns the appropriate
* pointer from the already loaded base.
- * Remember that an index of 0 is a NULL pointer so all indices
+ * Remember that an index of 0 is a nullptr pointer so all indices
* are +1 so vehicle 0 is saved as 1.
* @param index The index that is being converted to a pointer
* @param rt SLRefType type of the object the pointer is sought of
@@ -1094,8 +1094,8 @@ static void *IntToReference(size_t index, SLRefType rt)
rt = REF_VEHICLE;
}
- /* No need to look up NULL pointers, just return immediately */
- if (index == (rt == REF_VEHICLE_OLD ? 0xFFFF : 0)) return NULL;
+ /* No need to look up nullptr pointers, just return immediately */
+ if (index == (rt == REF_VEHICLE_OLD ? 0xFFFF : 0)) return nullptr;
/* Correct index. Old vehicles were saved differently:
* invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
@@ -1109,7 +1109,7 @@ static void *IntToReference(size_t index, SLRefType rt)
case REF_ORDER:
if (Order::IsValidID(index)) return Order::Get(index);
/* in old versions, invalid order was used to mark end of order list */
- if (IsSavegameVersionBefore(SLV_5, 2)) return NULL;
+ if (IsSavegameVersionBefore(SLV_5, 2)) return nullptr;
SlErrorCorrupt("Referencing invalid Order");
case REF_VEHICLE_OLD:
@@ -1499,7 +1499,7 @@ bool SlObjectMember(void *ptr, const SaveLoad *sld)
*(void **)ptr = IntToReference(*(size_t *)ptr, (SLRefType)conv);
break;
case SLA_NULL:
- *(void **)ptr = NULL;
+ *(void **)ptr = nullptr;
break;
default: NOT_REACHED();
}
@@ -1565,7 +1565,7 @@ void SlObject(void *object, const SaveLoad *sld)
*/
void SlGlobList(const SaveLoadGlobVarList *sldg)
{
- SlObject(NULL, (const SaveLoad*)sldg);
+ SlObject(nullptr, (const SaveLoad*)sldg);
}
/**
@@ -1637,7 +1637,7 @@ static void SlLoadChunk(const ChunkHandler *ch)
/**
* Load a chunk of data for checking savegames.
- * If the chunkhandler is NULL, the chunk is skipped.
+ * If the chunkhandler is nullptr, the chunk is skipped.
* @param ch The chunkhandler that will be used for the operation
*/
static void SlLoadCheckChunk(const ChunkHandler *ch)
@@ -1708,7 +1708,7 @@ static inline void SlStubSaveProc2(void *arg)
*/
static void SlStubSaveProc()
{
- SlAutolength(SlStubSaveProc2, NULL);
+ SlAutolength(SlStubSaveProc2, nullptr);
}
/**
@@ -1721,7 +1721,7 @@ static void SlSaveChunk(const ChunkHandler *ch)
ChunkSaveLoadProc *proc = ch->save_proc;
/* Don't save any chunk information if there is no save handler. */
- if (proc == NULL) return;
+ if (proc == nullptr) return;
SlWriteUint32(ch->id);
DEBUG(sl, 2, "Saving chunk %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
@@ -1773,7 +1773,7 @@ static void SlSaveChunks()
static const ChunkHandler *SlFindChunkHandler(uint32 id)
{
FOR_ALL_CHUNK_HANDLERS(ch) if (ch->id == id) return ch;
- return NULL;
+ return nullptr;
}
/** Load all chunks */
@@ -1786,7 +1786,7 @@ static void SlLoadChunks()
DEBUG(sl, 2, "Loading chunk %c%c%c%c", id >> 24, id >> 16, id >> 8, id);
ch = SlFindChunkHandler(id);
- if (ch == NULL) SlErrorCorrupt("Unknown chunk type");
+ if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
SlLoadChunk(ch);
}
}
@@ -1801,7 +1801,7 @@ static void SlLoadCheckChunks()
DEBUG(sl, 2, "Loading chunk %c%c%c%c", id >> 24, id >> 16, id >> 8, id);
ch = SlFindChunkHandler(id);
- if (ch == NULL) SlErrorCorrupt("Unknown chunk type");
+ if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
SlLoadCheckChunk(ch);
}
}
@@ -1814,7 +1814,7 @@ static void SlFixPointers()
DEBUG(sl, 1, "Fixing pointers");
FOR_ALL_CHUNK_HANDLERS(ch) {
- if (ch->ptrs_proc != NULL) {
+ if (ch->ptrs_proc != nullptr) {
DEBUG(sl, 2, "Fixing pointers for %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
ch->ptrs_proc();
}
@@ -1835,24 +1835,24 @@ struct FileReader : LoadFilter {
* Create the file reader, so it reads from a specific file.
* @param file The file to read from.
*/
- FileReader(FILE *file) : LoadFilter(NULL), file(file), begin(ftell(file))
+ FileReader(FILE *file) : LoadFilter(nullptr), file(file), begin(ftell(file))
{
}
/** Make sure everything is cleaned up. */
~FileReader()
{
- if (this->file != NULL) fclose(this->file);
- this->file = NULL;
+ if (this->file != nullptr) fclose(this->file);
+ this->file = nullptr;
/* Make sure we don't double free. */
- _sl.sf = NULL;
+ _sl.sf = nullptr;
}
size_t Read(byte *buf, size_t size) override
{
/* We're in the process of shutting down, i.e. in "failure" mode. */
- if (this->file == NULL) return 0;
+ if (this->file == nullptr) return 0;
return fread(buf, 1, size, this->file);
}
@@ -1874,7 +1874,7 @@ struct FileWriter : SaveFilter {
* Create the file writer, so it writes to a specific file.
* @param file The file to write to.
*/
- FileWriter(FILE *file) : SaveFilter(NULL), file(file)
+ FileWriter(FILE *file) : SaveFilter(nullptr), file(file)
{
}
@@ -1884,21 +1884,21 @@ struct FileWriter : SaveFilter {
this->Finish();
/* Make sure we don't double free. */
- _sl.sf = NULL;
+ _sl.sf = nullptr;
}
void Write(byte *buf, size_t size) override
{
/* We're in the process of shutting down, i.e. in "failure" mode. */
- if (this->file == NULL) return;
+ if (this->file == nullptr) return;
if (fwrite(buf, 1, size, this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
}
void Finish() override
{
- if (this->file != NULL) fclose(this->file);
- this->file = NULL;
+ if (this->file != nullptr) fclose(this->file);
+ this->file = nullptr;
}
};
@@ -1953,7 +1953,7 @@ struct LZOLoadFilter : LoadFilter {
if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32))) SlErrorCorrupt("Bad checksum");
/* Decompress */
- int ret = lzo1x_decompress_safe(out + sizeof(uint32) * 1, size, buf, &len, NULL);
+ int ret = lzo1x_decompress_safe(out + sizeof(uint32) * 1, size, buf, &len, nullptr);
if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
return len;
}
@@ -2147,7 +2147,7 @@ struct ZlibSaveFilter : SaveFilter {
void Finish() override
{
- this->WriteLoop(NULL, 0, Z_FINISH);
+ this->WriteLoop(nullptr, 0, Z_FINISH);
this->chain->Finish();
}
};
@@ -2266,7 +2266,7 @@ struct LZMASaveFilter : SaveFilter {
void Finish() override
{
- this->WriteLoop(NULL, 0, LZMA_FINISH);
+ this->WriteLoop(nullptr, 0, LZMA_FINISH);
this->chain->Finish();
}
};
@@ -2296,7 +2296,7 @@ static const SaveLoadFormat _saveload_formats[] = {
/* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
{"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
#else
- {"lzo", TO_BE32X('OTTD'), NULL, NULL, 0, 0, 0},
+ {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
#endif
/* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
{"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
@@ -2306,7 +2306,7 @@ static const SaveLoadFormat _saveload_formats[] = {
* 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
{"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
#else
- {"zlib", TO_BE32X('OTTZ'), NULL, NULL, 0, 0, 0},
+ {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
#endif
#if defined(WITH_LIBLZMA)
/* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
@@ -2316,14 +2316,14 @@ static const SaveLoadFormat _saveload_formats[] = {
* It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
{"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
#else
- {"lzma", TO_BE32X('OTTX'), NULL, NULL, 0, 0, 0},
+ {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
#endif
};
/**
* Return the savegameformat of the game. Whether it was created with ZLIB compression
* uncompressed, or another type
- * @param s Name of the savegame format. If NULL it picks the first available one
+ * @param s Name of the savegame format. If nullptr it picks the first available one
* @param compression_level Output for telling what compression level we want.
* @return Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame
*/
@@ -2337,12 +2337,12 @@ static const SaveLoadFormat *GetSavegameFormat(char *s, byte *compression_level)
if (!StrEmpty(s)) {
/* Get the ":..." of the compression level out of the way */
char *complevel = strrchr(s, ':');
- if (complevel != NULL) *complevel = '\0';
+ if (complevel != nullptr) *complevel = '\0';
for (const SaveLoadFormat *slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
- if (slf->init_write != NULL && strcmp(s, slf->name) == 0) {
+ if (slf->init_write != nullptr && strcmp(s, slf->name) == 0) {
*compression_level = slf->default_compression;
- if (complevel != NULL) {
+ if (complevel != nullptr) {
/* There is a compression level in the string.
* First restore the : we removed to do proper name matching,
* then move the the begin of the actual version. */
@@ -2368,7 +2368,7 @@ static const SaveLoadFormat *GetSavegameFormat(char *s, byte *compression_level)
ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, WL_CRITICAL);
/* Restore the string by adding the : back */
- if (complevel != NULL) *complevel = ':';
+ if (complevel != nullptr) *complevel = ':';
}
*compression_level = def->default_compression;
return def;
@@ -2385,16 +2385,16 @@ extern bool LoadOldSaveGame(const char *file);
static inline void ClearSaveLoadState()
{
delete _sl.dumper;
- _sl.dumper = NULL;
+ _sl.dumper = nullptr;
delete _sl.sf;
- _sl.sf = NULL;
+ _sl.sf = nullptr;
delete _sl.reader;
- _sl.reader = NULL;
+ _sl.reader = nullptr;
delete _sl.lf;
- _sl.lf = NULL;
+ _sl.lf = nullptr;
}
/**
@@ -2614,7 +2614,7 @@ static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
}
/* loader for this savegame type is not implemented? */
- if (fmt->init_load == NULL) {
+ if (fmt->init_load == nullptr) {
char err_str[64];
seprintf(err_str, lastof(err_str), "Loader for '%s' is not available.", fmt->name);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, err_str);
@@ -2769,11 +2769,11 @@ SaveOrLoadResult SaveOrLoad(const char *filename, SaveLoadOperation fop, Detaile
FILE *fh = (fop == SLO_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
/* Make it a little easier to load savegames from the console */
- if (fh == NULL && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
- if (fh == NULL && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
- if (fh == NULL && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
+ if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
+ if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
+ if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
- if (fh == NULL) {
+ if (fh == nullptr) {
SlError(fop == SLO_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
}
diff --git a/src/saveload/saveload.h b/src/saveload/saveload.h
index 07d45fafd..966de0c8a 100644
--- a/src/saveload/saveload.h
+++ b/src/saveload/saveload.h
@@ -641,11 +641,11 @@ typedef SaveLoad SaveLoadGlobVarList;
/** Translate values ingame to different values in the savegame and vv. */
#define SLE_WRITEBYTE(base, variable) SLE_GENERAL(SL_WRITEBYTE, base, variable, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION)
-#define SLE_VEH_INCLUDE() {false, SL_VEH_INCLUDE, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION, NULL, 0}
-#define SLE_ST_INCLUDE() {false, SL_ST_INCLUDE, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION, NULL, 0}
+#define SLE_VEH_INCLUDE() {false, SL_VEH_INCLUDE, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION, nullptr, 0}
+#define SLE_ST_INCLUDE() {false, SL_ST_INCLUDE, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION, nullptr, 0}
/** End marker of a struct/class save or load. */
-#define SLE_END() {false, SL_END, 0, 0, SL_MIN_VERSION, SL_MIN_VERSION, NULL, 0}
+#define SLE_END() {false, SL_END, 0, 0, SL_MIN_VERSION, SL_MIN_VERSION, nullptr, 0}
/**
* Storage of global simple variables, references (pointers), and arrays.
@@ -746,10 +746,10 @@ typedef SaveLoad SaveLoadGlobVarList;
* @param from First savegame version that has the empty space.
* @param to Last savegame version that has the empty space.
*/
-#define SLEG_CONDNULL(length, from, to) {true, SL_ARR, SLE_FILE_U8 | SLE_VAR_NULL | SLF_NOT_IN_CONFIG, length, from, to, (void*)NULL}
+#define SLEG_CONDNULL(length, from, to) {true, SL_ARR, SLE_FILE_U8 | SLE_VAR_NULL | SLF_NOT_IN_CONFIG, length, from, to, (void*)nullptr}
/** End marker of global variables save or load. */
-#define SLEG_END() {true, SL_END, 0, 0, SL_MIN_VERSION, SL_MIN_VERSION, NULL, 0}
+#define SLEG_END() {true, SL_END, 0, 0, SL_MIN_VERSION, SL_MIN_VERSION, nullptr, 0}
/**
* Checks whether the savegame is below \a major.\a minor.
@@ -813,13 +813,13 @@ static inline bool IsNumericType(VarType conv)
/**
* Get the address of the variable. Which one to pick depends on the object
- * pointer. If it is NULL we are dealing with global variables so the address
+ * pointer. If it is nullptr we are dealing with global variables so the address
* is taken. If non-null only the offset is stored in the union and we need
* to add this to the address of the object
*/
static inline void *GetVariableAddress(const void *object, const SaveLoad *sld)
{
- return const_cast<byte *>((const byte*)(sld->global ? NULL : object) + (ptrdiff_t)sld->address);
+ return const_cast<byte *>((const byte*)(sld->global ? nullptr : object) + (ptrdiff_t)sld->address);
}
int64 ReadValue(const void *ptr, VarType conv);
@@ -841,7 +841,7 @@ void SlGlobList(const SaveLoadGlobVarList *sldg);
void SlArray(void *array, size_t length, VarType conv);
void SlObject(void *object, const SaveLoad *sld);
bool SlObjectMember(void *object, const SaveLoad *sld);
-void NORETURN SlError(StringID string, const char *extra_msg = NULL);
+void NORETURN SlError(StringID string, const char *extra_msg = nullptr);
void NORETURN SlErrorCorrupt(const char *msg);
void NORETURN SlErrorCorruptFmt(const char *format, ...);
diff --git a/src/saveload/saveload_filter.h b/src/saveload/saveload_filter.h
index 0cb5c8695..ace9182d3 100644
--- a/src/saveload/saveload_filter.h
+++ b/src/saveload/saveload_filter.h
@@ -89,7 +89,7 @@ struct SaveFilter {
*/
virtual void Finish()
{
- if (this->chain != NULL) this->chain->Finish();
+ if (this->chain != nullptr) this->chain->Finish();
}
};
diff --git a/src/saveload/signs_sl.cpp b/src/saveload/signs_sl.cpp
index 545c628b3..f2ec21d94 100644
--- a/src/saveload/signs_sl.cpp
+++ b/src/saveload/signs_sl.cpp
@@ -68,5 +68,5 @@ static void Load_SIGN()
/** Chunk handlers related to signs. */
extern const ChunkHandler _sign_chunk_handlers[] = {
- { 'SIGN', Save_SIGN, Load_SIGN, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'SIGN', Save_SIGN, Load_SIGN, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/station_sl.cpp b/src/saveload/station_sl.cpp
index 995483ee6..40b5fb0e9 100644
--- a/src/saveload/station_sl.cpp
+++ b/src/saveload/station_sl.cpp
@@ -47,7 +47,7 @@ void MoveBuoysToWaypoints()
VehicleType vt = ol->GetFirstSharedVehicle()->type;
if (vt != VEH_SHIP && vt != VEH_TRAIN) continue;
- for (Order *o = ol->GetFirstOrder(); o != NULL; o = o->next) UpdateWaypointOrder(o);
+ for (Order *o = ol->GetFirstOrder(); o != nullptr; o = o->next) UpdateWaypointOrder(o);
}
Vehicle *v;
@@ -68,7 +68,7 @@ void MoveBuoysToWaypoints()
Town *town = st->town;
StringID string_id = st->string_id;
char *name = st->name;
- st->name = NULL;
+ st->name = nullptr;
Date build_date = st->build_date;
/* TTDPatch could use "buoys with rail station" for rail waypoints */
bool train = st->train_station.tile != INVALID_TILE;
@@ -116,13 +116,13 @@ void AfterLoadStations()
for (uint i = 0; i < st->num_specs; i++) {
if (st->speclist[i].grfid == 0) continue;
- st->speclist[i].spec = StationClass::GetByGrf(st->speclist[i].grfid, st->speclist[i].localidx, NULL);
+ st->speclist[i].spec = StationClass::GetByGrf(st->speclist[i].grfid, st->speclist[i].localidx, nullptr);
}
if (Station::IsExpected(st)) {
Station *sta = Station::From(st);
- for (const RoadStop *rs = sta->bus_stops; rs != NULL; rs = rs->next) sta->bus_station.Add(rs->xy);
- for (const RoadStop *rs = sta->truck_stops; rs != NULL; rs = rs->next) sta->truck_station.Add(rs->xy);
+ for (const RoadStop *rs = sta->bus_stops; rs != nullptr; rs = rs->next) sta->bus_station.Add(rs->xy);
+ for (const RoadStop *rs = sta->truck_stops; rs != nullptr; rs = rs->next) sta->truck_station.Add(rs->xy);
}
StationUpdateCachedTriggers(st);
@@ -544,11 +544,11 @@ static void Load_STNN()
for (CargoID i = 0; i < num_cargo; i++) {
SlObject(&st->goods[i], GetGoodsDesc());
FlowSaveLoad flow;
- FlowStat *fs = NULL;
+ FlowStat *fs = nullptr;
StationID prev_source = INVALID_STATION;
for (uint32 j = 0; j < _num_flows; ++j) {
SlObject(&flow, _flow_desc);
- if (fs == NULL || prev_source != flow.source) {
+ if (fs == nullptr || prev_source != flow.source) {
fs = &(st->goods[i].flows.insert(std::make_pair(flow.source, FlowStat(flow.via, flow.share, flow.restricted))).first->second);
} else {
fs->AppendShare(flow.via, flow.share, flow.restricted);
@@ -638,7 +638,7 @@ static void Ptrs_ROADSTOP()
}
extern const ChunkHandler _station_chunk_handlers[] = {
- { 'STNS', NULL, Load_STNS, Ptrs_STNS, NULL, CH_ARRAY },
- { 'STNN', Save_STNN, Load_STNN, Ptrs_STNN, NULL, CH_ARRAY },
- { 'ROAD', Save_ROADSTOP, Load_ROADSTOP, Ptrs_ROADSTOP, NULL, CH_ARRAY | CH_LAST},
+ { 'STNS', nullptr, Load_STNS, Ptrs_STNS, nullptr, CH_ARRAY },
+ { 'STNN', Save_STNN, Load_STNN, Ptrs_STNN, nullptr, CH_ARRAY },
+ { 'ROAD', Save_ROADSTOP, Load_ROADSTOP, Ptrs_ROADSTOP, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/storage_sl.cpp b/src/saveload/storage_sl.cpp
index 1396d25ae..fafc35cb1 100644
--- a/src/saveload/storage_sl.cpp
+++ b/src/saveload/storage_sl.cpp
@@ -50,5 +50,5 @@ static void Save_PSAC()
/** Chunk handler for persistent storages. */
extern const ChunkHandler _persistent_storage_chunk_handlers[] = {
- { 'PSAC', Save_PSAC, Load_PSAC, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'PSAC', Save_PSAC, Load_PSAC, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/story_sl.cpp b/src/saveload/story_sl.cpp
index f9bbf34b9..8cca9aed7 100644
--- a/src/saveload/story_sl.cpp
+++ b/src/saveload/story_sl.cpp
@@ -102,6 +102,6 @@ static void Load_STORY_PAGE()
}
extern const ChunkHandler _story_page_chunk_handlers[] = {
- { 'STPE', Save_STORY_PAGE_ELEMENT, Load_STORY_PAGE_ELEMENT, NULL, NULL, CH_ARRAY},
- { 'STPA', Save_STORY_PAGE, Load_STORY_PAGE, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'STPE', Save_STORY_PAGE_ELEMENT, Load_STORY_PAGE_ELEMENT, nullptr, nullptr, CH_ARRAY},
+ { 'STPA', Save_STORY_PAGE, Load_STORY_PAGE, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/strings_sl.cpp b/src/saveload/strings_sl.cpp
index d8fe81d11..9e0351ae0 100644
--- a/src/saveload/strings_sl.cpp
+++ b/src/saveload/strings_sl.cpp
@@ -49,7 +49,7 @@ StringID RemapOldStringID(StringID s)
}
/** Location to load the old names to. */
-char *_old_name_array = NULL;
+char *_old_name_array = nullptr;
/**
* Copy and convert old custom names to UTF-8.
@@ -61,7 +61,7 @@ char *_old_name_array = NULL;
char *CopyFromOldName(StringID id)
{
/* Is this name an (old) custom name? */
- if (GetStringTab(id) != TEXT_TAB_OLD_CUSTOM) return NULL;
+ if (GetStringTab(id) != TEXT_TAB_OLD_CUSTOM) return nullptr;
if (IsSavegameVersionBefore(SLV_37)) {
/* Allow for expansion when converted to UTF-8. */
@@ -109,7 +109,7 @@ char *CopyFromOldName(StringID id)
void ResetOldNames()
{
free(_old_name_array);
- _old_name_array = NULL;
+ _old_name_array = nullptr;
}
/**
@@ -140,5 +140,5 @@ static void Load_NAME()
/** Chunk handlers related to strings. */
extern const ChunkHandler _name_chunk_handlers[] = {
- { 'NAME', NULL, Load_NAME, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'NAME', nullptr, Load_NAME, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/subsidy_sl.cpp b/src/saveload/subsidy_sl.cpp
index 6f10ec8d0..536ec2145 100644
--- a/src/saveload/subsidy_sl.cpp
+++ b/src/saveload/subsidy_sl.cpp
@@ -48,5 +48,5 @@ static void Load_SUBS()
}
extern const ChunkHandler _subsidy_chunk_handlers[] = {
- { 'SUBS', Save_SUBS, Load_SUBS, NULL, NULL, CH_ARRAY | CH_LAST},
+ { 'SUBS', Save_SUBS, Load_SUBS, nullptr, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/town_sl.cpp b/src/saveload/town_sl.cpp
index bc2ed8be6..c85bb4a82 100644
--- a/src/saveload/town_sl.cpp
+++ b/src/saveload/town_sl.cpp
@@ -321,6 +321,6 @@ static void Ptrs_TOWN()
/** Chunk handler for towns. */
extern const ChunkHandler _town_chunk_handlers[] = {
- { 'HIDS', Save_HIDS, Load_HIDS, NULL, NULL, CH_ARRAY },
- { 'CITY', Save_TOWN, Load_TOWN, Ptrs_TOWN, NULL, CH_ARRAY | CH_LAST},
+ { 'HIDS', Save_HIDS, Load_HIDS, nullptr, nullptr, CH_ARRAY },
+ { 'CITY', Save_TOWN, Load_TOWN, Ptrs_TOWN, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/saveload/vehicle_sl.cpp b/src/saveload/vehicle_sl.cpp
index 058587139..c42e3938f 100644
--- a/src/saveload/vehicle_sl.cpp
+++ b/src/saveload/vehicle_sl.cpp
@@ -36,7 +36,7 @@ void ConnectMultiheadedTrains()
Train *v;
FOR_ALL_TRAINS(v) {
- v->other_multiheaded_part = NULL;
+ v->other_multiheaded_part = nullptr;
}
FOR_ALL_TRAINS(v) {
@@ -56,8 +56,8 @@ void ConnectMultiheadedTrains()
bool sequential_matching = v->IsFrontEngine();
- for (Train *u = v; u != NULL; u = u->GetNextVehicle()) {
- if (u->other_multiheaded_part != NULL) continue; // we already linked this one
+ for (Train *u = v; u != nullptr; u = u->GetNextVehicle()) {
+ if (u->other_multiheaded_part != nullptr) continue; // we already linked this one
if (u->IsMultiheaded()) {
if (!u->IsEngine()) {
@@ -70,8 +70,8 @@ void ConnectMultiheadedTrains()
EngineID eid = u->engine_type;
Train *w;
if (sequential_matching) {
- for (w = u->GetNextVehicle(); w != NULL; w = w->GetNextVehicle()) {
- if (w->engine_type != eid || w->other_multiheaded_part != NULL || !w->IsMultiheaded()) continue;
+ for (w = u->GetNextVehicle(); w != nullptr; w = w->GetNextVehicle()) {
+ if (w->engine_type != eid || w->other_multiheaded_part != nullptr || !w->IsMultiheaded()) continue;
/* we found a car to partner with this engine. Now we will make sure it face the right way */
if (w->IsEngine()) {
@@ -82,8 +82,8 @@ void ConnectMultiheadedTrains()
}
} else {
uint stack_pos = 0;
- for (w = u->GetNextVehicle(); w != NULL; w = w->GetNextVehicle()) {
- if (w->engine_type != eid || w->other_multiheaded_part != NULL || !w->IsMultiheaded()) continue;
+ for (w = u->GetNextVehicle(); w != nullptr; w = w->GetNextVehicle()) {
+ if (w->engine_type != eid || w->other_multiheaded_part != nullptr || !w->IsMultiheaded()) continue;
if (w->IsEngine()) {
stack_pos++;
@@ -94,7 +94,7 @@ void ConnectMultiheadedTrains()
}
}
- if (w != NULL) {
+ if (w != nullptr) {
w->other_multiheaded_part = u;
u->other_multiheaded_part = w;
} else {
@@ -118,7 +118,7 @@ void ConvertOldMultiheadToNew()
FOR_ALL_TRAINS(t) {
if (HasBit(t->subtype, 7) && ((t->subtype & ~0x80) == 0 || (t->subtype & ~0x80) == 4)) {
- for (Train *u = t; u != NULL; u = u->Next()) {
+ for (Train *u = t; u != nullptr; u = u->Next()) {
const RailVehicleInfo *rvi = RailVehInfo(u->engine_type);
ClrBit(u->subtype, 7);
@@ -200,7 +200,7 @@ void UpdateOldAircraft()
if (a->subtype == AIR_HELICOPTER) a->Next()->Next()->cur_speed = 32;
/* set new position x,y,z */
- GetAircraftFlightLevelBounds(a, &a->z_pos, NULL);
+ GetAircraftFlightLevelBounds(a, &a->z_pos, nullptr);
SetAircraftPosition(a, gp.x, gp.y, GetAircraftFlightLevel(a));
}
}
@@ -252,11 +252,11 @@ void AfterLoadVehicles(bool part_of_load)
FOR_ALL_VEHICLES(v) {
/* Reinstate the previous pointer */
- if (v->Next() != NULL) v->Next()->previous = v;
- if (v->NextShared() != NULL) v->NextShared()->previous_shared = v;
+ if (v->Next() != nullptr) v->Next()->previous = v;
+ if (v->NextShared() != nullptr) v->NextShared()->previous_shared = v;
if (part_of_load) v->fill_percent_te_id = INVALID_TE_ID;
- v->first = NULL;
+ v->first = nullptr;
if (v->IsGroundVehicle()) v->GetGroundVehicleCache()->first_engine = INVALID_ENGINE;
}
@@ -272,9 +272,9 @@ void AfterLoadVehicles(bool part_of_load)
std::map<Order*, OrderList*> mapping;
FOR_ALL_VEHICLES(v) {
- if (v->orders.old != NULL) {
+ if (v->orders.old != nullptr) {
if (IsSavegameVersionBefore(SLV_105)) { // Pre-105 didn't save an OrderList
- if (mapping[v->orders.old] == NULL) {
+ if (mapping[v->orders.old] == nullptr) {
/* This adds the whole shared vehicle chain for case b */
/* Creating an OrderList here is safe because the number of vehicles
@@ -290,7 +290,7 @@ void AfterLoadVehicles(bool part_of_load)
}
}
} else { // OrderList was saved as such, only recalculate not saved values
- if (v->PreviousShared() == NULL) {
+ if (v->PreviousShared() == nullptr) {
v->orders.list->Initialize(v->orders.list->first, v);
}
}
@@ -300,8 +300,8 @@ void AfterLoadVehicles(bool part_of_load)
FOR_ALL_VEHICLES(v) {
/* Fill the first pointers */
- if (v->Previous() == NULL) {
- for (Vehicle *u = v; u != NULL; u = u->Next()) {
+ if (v->Previous() == nullptr) {
+ for (Vehicle *u = v; u != nullptr; u = u->Next()) {
u->first = v;
}
}
@@ -311,12 +311,12 @@ void AfterLoadVehicles(bool part_of_load)
if (IsSavegameVersionBefore(SLV_105)) {
/* Before 105 there was no order for shared orders, thus it messed up horribly */
FOR_ALL_VEHICLES(v) {
- if (v->First() != v || v->orders.list != NULL || v->previous_shared != NULL || v->next_shared == NULL) continue;
+ if (v->First() != v || v->orders.list != nullptr || v->previous_shared != nullptr || v->next_shared == nullptr) continue;
/* As above, allocating OrderList here is safe. */
assert(OrderList::CanAllocateItem());
- v->orders.list = new OrderList(NULL, v);
- for (Vehicle *u = v; u != NULL; u = u->next_shared) {
+ v->orders.list = new OrderList(nullptr, v);
+ for (Vehicle *u = v; u != nullptr; u = u->next_shared) {
u->orders.list = v->orders.list;
}
}
@@ -392,9 +392,9 @@ void AfterLoadVehicles(bool part_of_load)
CheckValidVehicles();
FOR_ALL_VEHICLES(v) {
- assert(v->first != NULL);
+ assert(v->first != nullptr);
- v->trip_occupancy = CalcPercentVehicleFilled(v, NULL);
+ v->trip_occupancy = CalcPercentVehicleFilled(v, nullptr);
switch (v->type) {
case VEH_TRAIN: {
@@ -502,7 +502,7 @@ void FixupTrainLengths()
/* The vehicle center is now more to the front depending on vehicle length,
* so we need to move all vehicles forward to cover the difference to the
* old center, otherwise wagon spacing in trains would be broken upon load. */
- for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
+ for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
if (u->track == TRACK_BIT_DEPOT || (u->vehstatus & VS_CRASHED)) continue;
Train *next = u->Next();
@@ -514,7 +514,7 @@ void FixupTrainLengths()
if (!TrainController(u, next, false)) break;
}
- if (next != NULL && done < diff && u->IsFrontEngine()) {
+ if (next != nullptr && done < diff && u->IsFrontEngine()) {
/* Pulling the front vehicle forwards failed, we either encountered a dead-end
* or a red signal. To fix this, we try to move the whole train the required
* space backwards and re-do the fix up of the front vehicle. */
@@ -530,14 +530,14 @@ void FixupTrainLengths()
/* We moved the first vehicle which is now the last. Move it back to the
* original position as we will fix up the last vehicle later in the loop. */
- for (int i = 0; i < done; i++) TrainController(u->Last(), NULL);
+ for (int i = 0; i < done; i++) TrainController(u->Last(), nullptr);
/* Move the train backwards to get space for the first vehicle. As the stopping
* distance from a line end is rounded up, move the train one unit more to cater
* for front vehicles with odd lengths. */
int moved;
for (moved = 0; moved < diff + 1; moved++) {
- if (!TrainController(u, NULL, false)) break;
+ if (!TrainController(u, nullptr, false)) break;
}
/* Swap start<>end, start+1<>end-1, ... again. */
@@ -556,17 +556,17 @@ void FixupTrainLengths()
/* We moved one unit more backwards than needed for even-length front vehicles,
* try to move that unit forward again. We don't care if this step fails. */
- TrainController(u, NULL, false);
+ TrainController(u, nullptr, false);
}
/* If the next wagon is still in a depot, check if it shouldn't be outside already. */
- if (next != NULL && next->track == TRACK_BIT_DEPOT) {
+ if (next != nullptr && next->track == TRACK_BIT_DEPOT) {
int d = TicksToLeaveDepot(u);
if (d <= 0) {
/* Next vehicle should have left the depot already, show it and pull forward. */
next->vehstatus &= ~VS_HIDDEN;
next->track = TrackToTrackBits(GetRailDepotTrack(next->tile));
- for (int i = 0; i >= d; i--) TrainController(next, NULL);
+ for (int i = 0; i >= d; i--) TrainController(next, nullptr);
}
}
}
@@ -960,5 +960,5 @@ static void Ptrs_VEHS()
}
extern const ChunkHandler _veh_chunk_handlers[] = {
- { 'VEHS', Save_VEHS, Load_VEHS, Ptrs_VEHS, NULL, CH_SPARSE_ARRAY | CH_LAST},
+ { 'VEHS', Save_VEHS, Load_VEHS, Ptrs_VEHS, nullptr, CH_SPARSE_ARRAY | CH_LAST},
};
diff --git a/src/saveload/waypoint_sl.cpp b/src/saveload/waypoint_sl.cpp
index 167086467..66ef145fc 100644
--- a/src/saveload/waypoint_sl.cpp
+++ b/src/saveload/waypoint_sl.cpp
@@ -88,7 +88,7 @@ void MoveWaypointsToBaseStations()
StationClass* stclass = StationClass::Get(STAT_CLASS_WAYP);
for (uint i = 0; i < stclass->GetSpecCount(); i++) {
const StationSpec *statspec = stclass->GetSpec(i);
- if (statspec != NULL && statspec->grf_prop.grffile->grfid == wp.grfid && statspec->grf_prop.local_id == wp.localidx) {
+ if (statspec != nullptr && statspec->grf_prop.grffile->grfid == wp.grfid && statspec->grf_prop.local_id == wp.localidx) {
wp.spec = statspec;
break;
}
@@ -122,7 +122,7 @@ void MoveWaypointsToBaseStations()
SetRailStationReservation(t, reserved);
- if (wp.spec != NULL) {
+ if (wp.spec != nullptr) {
SetCustomStationSpecIndex(t, AllocateSpecToStation(wp.spec, new_wp, true));
}
new_wp->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
@@ -136,7 +136,7 @@ void MoveWaypointsToBaseStations()
FOR_ALL_ORDER_LISTS(ol) {
if (ol->GetFirstSharedVehicle()->type != VEH_TRAIN) continue;
- for (Order *o = ol->GetFirstOrder(); o != NULL; o = o->next) UpdateWaypointOrder(o);
+ for (Order *o = ol->GetFirstOrder(); o != nullptr; o = o->next) UpdateWaypointOrder(o);
}
Vehicle *v;
@@ -199,10 +199,10 @@ static void Ptrs_WAYP()
/* Only for versions 12 .. 122 */
if (!Town::IsValidID(wp.town_index)) {
/* Upon a corrupted waypoint we'll likely get here. The next step will be to
- * loop over all Ptrs procs to NULL the pointers. However, we don't know
- * whether we're in the NULL or "normal" Ptrs proc. So just clear the list
+ * loop over all Ptrs procs to nullptr the pointers. However, we don't know
+ * whether we're in the nullptr or "normal" Ptrs proc. So just clear the list
* of old waypoints we constructed and then this waypoint (and the other
- * possibly corrupt ones) will not be queried in the NULL Ptrs proc run. */
+ * possibly corrupt ones) will not be queried in the nullptr Ptrs proc run. */
_old_waypoints.clear();
SlErrorCorrupt("Referencing invalid Town");
}
@@ -215,5 +215,5 @@ static void Ptrs_WAYP()
}
extern const ChunkHandler _waypoint_chunk_handlers[] = {
- { 'CHKP', NULL, Load_WAYP, Ptrs_WAYP, NULL, CH_ARRAY | CH_LAST},
+ { 'CHKP', nullptr, Load_WAYP, Ptrs_WAYP, nullptr, CH_ARRAY | CH_LAST},
};
diff --git a/src/screenshot.cpp b/src/screenshot.cpp
index 700a06566..b2d7d21bd 100644
--- a/src/screenshot.cpp
+++ b/src/screenshot.cpp
@@ -120,7 +120,7 @@ static bool MakeBMPImage(const char *name, ScreenshotCallback *callb, void *user
}
FILE *f = fopen(name, "wb");
- if (f == NULL) return false;
+ if (f == nullptr) return false;
/* Each scanline must be aligned on a 32bit boundary */
uint bytewidth = Align(w * bpp, 4); // bytes per line in file
@@ -268,18 +268,18 @@ static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *user
if (pixelformat != 8 && pixelformat != 32) return false;
f = fopen(name, "wb");
- if (f == NULL) return false;
+ if (f == nullptr) return false;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, const_cast<char *>(name), png_my_error, png_my_warning);
- if (png_ptr == NULL) {
+ if (png_ptr == nullptr) {
fclose(f);
return false;
}
info_ptr = png_create_info_struct(png_ptr);
- if (info_ptr == NULL) {
- png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
+ if (info_ptr == nullptr) {
+ png_destroy_write_struct(&png_ptr, (png_infopp)nullptr);
fclose(f);
return false;
}
@@ -311,7 +311,7 @@ static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *user
char *p = buf;
p += seprintf(p, lastof(buf), "Graphics set: %s (%u)\n", BaseGraphics::GetUsedSet()->name, BaseGraphics::GetUsedSet()->version);
p = strecpy(p, "NewGRFs:\n", lastof(buf));
- for (const GRFConfig *c = _game_mode == GM_MENU ? NULL : _grfconfig; c != NULL; c = c->next) {
+ for (const GRFConfig *c = _game_mode == GM_MENU ? nullptr : _grfconfig; c != nullptr; c = c->next) {
p += seprintf(p, lastof(buf), "%08X ", BSWAP32(c->ident.grfid));
p = md5sumToString(p, lastof(buf), c->ident.md5sum);
p += seprintf(p, lastof(buf), " %s\n", c->filename);
@@ -319,7 +319,7 @@ static bool MakePNGImage(const char *name, ScreenshotCallback *callb, void *user
p = strecpy(p, "\nCompanies:\n", lastof(buf));
const Company *c;
FOR_ALL_COMPANIES(c) {
- if (c->ai_info == NULL) {
+ if (c->ai_info == nullptr) {
p += seprintf(p, lastof(buf), "%2i: Human\n", (int)c->index);
} else {
p += seprintf(p, lastof(buf), "%2i: %s (v%d)\n", (int)c->index, c->ai_info->GetName(), c->ai_info->GetVersion());
@@ -447,7 +447,7 @@ static bool MakePCXImage(const char *name, ScreenshotCallback *callb, void *user
if (pixelformat != 8 || w == 0) return false;
f = fopen(name, "wb");
- if (f == NULL) return false;
+ if (f == nullptr) return false;
memset(&pcx, 0, sizeof(pcx));
@@ -701,7 +701,7 @@ static const char *MakeScreenshotName(const char *default_fn, const char *ext, b
static bool MakeSmallScreenshot(bool crashlog)
{
const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
- return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension, crashlog), CurrentScreenCallback, NULL, _screen.width, _screen.height,
+ return sf->proc(MakeScreenshotName(SCREENSHOT_NAME, sf->extension, crashlog), CurrentScreenCallback, nullptr, _screen.width, _screen.height,
BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette.palette);
}
@@ -743,7 +743,7 @@ void SetupScreenshotViewport(ScreenshotType t, ViewPort *vp)
vp->top = 0;
vp->width = UnScaleByZoom(vp->virtual_width, vp->zoom);
vp->height = UnScaleByZoom(vp->virtual_height, vp->zoom);
- vp->overlay = NULL;
+ vp->overlay = nullptr;
}
/**
@@ -800,7 +800,7 @@ bool MakeHeightmapScreenshot(const char *filename)
palette[i].b = i;
}
const ScreenshotFormat *sf = _screenshot_formats + _cur_screenshot_format;
- return sf->proc(filename, HeightmapCallback, NULL, MapSizeX(), MapSizeY(), 8, palette);
+ return sf->proc(filename, HeightmapCallback, nullptr, MapSizeX(), MapSizeY(), 8, palette);
}
/**
@@ -821,7 +821,7 @@ bool MakeScreenshot(ScreenshotType t, const char *name)
}
_screenshot_name[0] = '\0';
- if (name != NULL) strecpy(_screenshot_name, name, lastof(_screenshot_name));
+ if (name != nullptr) strecpy(_screenshot_name, name, lastof(_screenshot_name));
bool ret;
switch (t) {
diff --git a/src/script/api/script_basestation.cpp b/src/script/api/script_basestation.cpp
index 229abf865..c51fa867a 100644
--- a/src/script/api/script_basestation.cpp
+++ b/src/script/api/script_basestation.cpp
@@ -22,12 +22,12 @@
/* static */ bool ScriptBaseStation::IsValidBaseStation(StationID station_id)
{
const BaseStation *st = ::BaseStation::GetIfValid(station_id);
- return st != NULL && (st->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY || st->owner == OWNER_NONE);
+ return st != nullptr && (st->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY || st->owner == OWNER_NONE);
}
/* static */ char *ScriptBaseStation::GetName(StationID station_id)
{
- if (!IsValidBaseStation(station_id)) return NULL;
+ if (!IsValidBaseStation(station_id)) return nullptr;
::SetDParam(0, station_id);
return GetString(::Station::IsValidID(station_id) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
@@ -39,7 +39,7 @@
EnforcePrecondition(false, ScriptObject::GetCompany() != OWNER_DEITY);
EnforcePrecondition(false, IsValidBaseStation(station_id));
- EnforcePrecondition(false, name != NULL);
+ EnforcePrecondition(false, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_STATION_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
diff --git a/src/script/api/script_basestation.hpp b/src/script/api/script_basestation.hpp
index 9676829f6..5bfd9ac84 100644
--- a/src/script/api/script_basestation.hpp
+++ b/src/script/api/script_basestation.hpp
@@ -52,7 +52,7 @@ public:
* @param station_id The basestation to set the name of.
* @param name The new name of the station (can be either a raw string, or a ScriptText object).
* @pre IsValidBaseStation(station_id).
- * @pre name != NULL && len(name) != 0.
+ * @pre name != nullptr && len(name) != 0.
* @game @pre Valid ScriptCompanyMode active in scope.
* @exception ScriptError::ERR_NAME_IS_NOT_UNIQUE
* @return True if the name was changed.
diff --git a/src/script/api/script_bridge.cpp b/src/script/api/script_bridge.cpp
index f532f11b7..03787be2a 100644
--- a/src/script/api/script_bridge.cpp
+++ b/src/script/api/script_bridge.cpp
@@ -102,7 +102,7 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance)
ScriptObject::SetCallbackVariable(0, start);
ScriptObject::SetCallbackVariable(1, end);
- return ScriptObject::DoCommand(end, start, type | bridge_id, CMD_BUILD_BRIDGE, NULL, &::_DoCommandReturnBuildBridge1);
+ return ScriptObject::DoCommand(end, start, type | bridge_id, CMD_BUILD_BRIDGE, nullptr, &::_DoCommandReturnBuildBridge1);
}
/* static */ bool ScriptBridge::_BuildBridgeRoad1()
@@ -114,7 +114,7 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance)
DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start);
DiagDirection dir_2 = ::ReverseDiagDir(dir_1);
- return ScriptObject::DoCommand(start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2) | (ScriptObject::GetRoadType() << 4), 0, CMD_BUILD_ROAD, NULL, &::_DoCommandReturnBuildBridge2);
+ return ScriptObject::DoCommand(start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2) | (ScriptObject::GetRoadType() << 4), 0, CMD_BUILD_ROAD, nullptr, &::_DoCommandReturnBuildBridge2);
}
/* static */ bool ScriptBridge::_BuildBridgeRoad2()
@@ -138,8 +138,8 @@ static void _DoCommandReturnBuildBridge1(class ScriptInstance *instance)
/* static */ char *ScriptBridge::GetName(BridgeID bridge_id, ScriptVehicle::VehicleType vehicle_type)
{
- EnforcePrecondition(NULL, vehicle_type == ScriptVehicle::VT_ROAD || vehicle_type == ScriptVehicle::VT_RAIL || vehicle_type == ScriptVehicle::VT_WATER);
- if (!IsValidBridge(bridge_id)) return NULL;
+ EnforcePrecondition(nullptr, vehicle_type == ScriptVehicle::VT_ROAD || vehicle_type == ScriptVehicle::VT_RAIL || vehicle_type == ScriptVehicle::VT_WATER);
+ if (!IsValidBridge(bridge_id)) return nullptr;
return GetString(vehicle_type == ScriptVehicle::VT_WATER ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : ::GetBridgeSpec(bridge_id)->transport_name[vehicle_type]);
}
diff --git a/src/script/api/script_cargo.cpp b/src/script/api/script_cargo.cpp
index a2643f897..9e83daa08 100644
--- a/src/script/api/script_cargo.cpp
+++ b/src/script/api/script_cargo.cpp
@@ -29,7 +29,7 @@
/* static */ char *ScriptCargo::GetCargoLabel(CargoID cargo_type)
{
- if (!IsValidCargo(cargo_type)) return NULL;
+ if (!IsValidCargo(cargo_type)) return nullptr;
const CargoSpec *cargo = ::CargoSpec::Get(cargo_type);
/* cargo->label is a uint32 packing a 4 character non-terminated string,
diff --git a/src/script/api/script_client.cpp b/src/script/api/script_client.cpp
index 855ad86a0..247cac98c 100644
--- a/src/script/api/script_client.cpp
+++ b/src/script/api/script_client.cpp
@@ -20,37 +20,37 @@
* Finds NetworkClientInfo given client-identifier,
* is used by other methods to resolve client-identifier.
* @param client The client to get info structure for
- * @return A pointer to corresponding CI struct or NULL when not found.
+ * @return A pointer to corresponding CI struct or nullptr when not found.
*/
static NetworkClientInfo *FindClientInfo(ScriptClient::ClientID client)
{
- if (client == ScriptClient::CLIENT_INVALID) return NULL;
- if (!_networking) return NULL;
+ if (client == ScriptClient::CLIENT_INVALID) return nullptr;
+ if (!_networking) return nullptr;
return NetworkClientInfo::GetByClientID((::ClientID)client);
}
/* static */ ScriptClient::ClientID ScriptClient::ResolveClientID(ScriptClient::ClientID client)
{
- return (FindClientInfo(client) == NULL ? ScriptClient::CLIENT_INVALID : client);
+ return (FindClientInfo(client) == nullptr ? ScriptClient::CLIENT_INVALID : client);
}
/* static */ char *ScriptClient::GetName(ScriptClient::ClientID client)
{
NetworkClientInfo *ci = FindClientInfo(client);
- if (ci == NULL) return NULL;
+ if (ci == nullptr) return nullptr;
return stredup(ci->client_name);
}
/* static */ ScriptCompany::CompanyID ScriptClient::GetCompany(ScriptClient::ClientID client)
{
NetworkClientInfo *ci = FindClientInfo(client);
- if (ci == NULL) return ScriptCompany::COMPANY_INVALID;
+ if (ci == nullptr) return ScriptCompany::COMPANY_INVALID;
return (ScriptCompany::CompanyID)ci->client_playas;
}
/* static */ ScriptDate::Date ScriptClient::GetJoinDate(ScriptClient::ClientID client)
{
NetworkClientInfo *ci = FindClientInfo(client);
- if (ci == NULL) return ScriptDate::DATE_INVALID;
+ if (ci == nullptr) return ScriptDate::DATE_INVALID;
return (ScriptDate::Date)ci->join_date;
}
diff --git a/src/script/api/script_company.cpp b/src/script/api/script_company.cpp
index 54888c33c..59f4fa43e 100644
--- a/src/script/api/script_company.cpp
+++ b/src/script/api/script_company.cpp
@@ -45,7 +45,7 @@
{
CCountedPtr<Text> counter(name);
- EnforcePrecondition(false, name != NULL);
+ EnforcePrecondition(false, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_COMPANY_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
@@ -56,7 +56,7 @@
/* static */ char *ScriptCompany::GetName(ScriptCompany::CompanyID company)
{
company = ResolveCompanyID(company);
- if (company == COMPANY_INVALID) return NULL;
+ if (company == COMPANY_INVALID) return nullptr;
::SetDParam(0, company);
return GetString(STR_COMPANY_NAME);
@@ -66,7 +66,7 @@
{
CCountedPtr<Text> counter(name);
- EnforcePrecondition(false, name != NULL);
+ EnforcePrecondition(false, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_PRESIDENT_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
@@ -312,7 +312,7 @@
if ((::LiveryScheme)scheme < LS_BEGIN || (::LiveryScheme)scheme >= LS_END) return COLOUR_INVALID;
const Company *c = ::Company::GetIfValid(_current_company);
- if (c == NULL) return COLOUR_INVALID;
+ if (c == nullptr) return COLOUR_INVALID;
return (ScriptCompany::Colours)c->livery[scheme].colour1;
}
@@ -322,7 +322,7 @@
if ((::LiveryScheme)scheme < LS_BEGIN || (::LiveryScheme)scheme >= LS_END) return COLOUR_INVALID;
const Company *c = ::Company::GetIfValid(_current_company);
- if (c == NULL) return COLOUR_INVALID;
+ if (c == nullptr) return COLOUR_INVALID;
return (ScriptCompany::Colours)c->livery[scheme].colour2;
}
diff --git a/src/script/api/script_company.hpp b/src/script/api/script_company.hpp
index 55cb7a930..e3be24e55 100644
--- a/src/script/api/script_company.hpp
+++ b/src/script/api/script_company.hpp
@@ -139,7 +139,7 @@ public:
/**
* Set the name of your company.
* @param name The new name of the company (can be either a raw string, or a ScriptText object).
- * @pre name != NULL && len(name) != 0.
+ * @pre name != nullptr && len(name) != 0.
* @exception ScriptError::ERR_NAME_IS_NOT_UNIQUE
* @return True if the name was changed.
*/
@@ -156,7 +156,7 @@ public:
/**
* Set the name of your president.
* @param name The new name of the president (can be either a raw string, or a ScriptText object).
- * @pre name != NULL && len(name) != 0.
+ * @pre name != nullptr && len(name) != 0.
* @exception ScriptError::ERR_NAME_IS_NOT_UNIQUE
* @return True if the name was changed.
*/
diff --git a/src/script/api/script_controller.cpp b/src/script/api/script_controller.cpp
index a42c8ede9..beb9b155f 100644
--- a/src/script/api/script_controller.cpp
+++ b/src/script/api/script_controller.cpp
@@ -43,7 +43,7 @@
ticks = 1;
}
- throw Script_Suspend(ticks, NULL);
+ throw Script_Suspend(ticks, nullptr);
}
/* static */ void ScriptController::Break(const char* message)
@@ -119,7 +119,7 @@ ScriptController::~ScriptController()
strtolower(library_name);
ScriptInfo *lib = ScriptObject::GetActiveInstance()->FindLibrary(library, version);
- if (lib == NULL) {
+ if (lib == nullptr) {
char error[1024];
seprintf(error, lastof(error), "couldn't find library '%s' with version %d", library, version);
throw sq_throwerror(vm, error);
diff --git a/src/script/api/script_engine.cpp b/src/script/api/script_engine.cpp
index c564cee97..dfd15bee4 100644
--- a/src/script/api/script_engine.cpp
+++ b/src/script/api/script_engine.cpp
@@ -25,7 +25,7 @@
/* static */ bool ScriptEngine::IsValidEngine(EngineID engine_id)
{
const Engine *e = ::Engine::GetIfValid(engine_id);
- if (e == NULL || !e->IsEnabled()) return false;
+ if (e == nullptr || !e->IsEnabled()) return false;
/* AIs have only access to engines they can purchase or still have in use.
* Deity has access to all engined that will be or were available ever. */
@@ -36,12 +36,12 @@
/* static */ bool ScriptEngine::IsBuildable(EngineID engine_id)
{
const Engine *e = ::Engine::GetIfValid(engine_id);
- return e != NULL && ::IsEngineBuildable(engine_id, e->type, ScriptObject::GetCompany());
+ return e != nullptr && ::IsEngineBuildable(engine_id, e->type, ScriptObject::GetCompany());
}
/* static */ char *ScriptEngine::GetName(EngineID engine_id)
{
- if (!IsValidEngine(engine_id)) return NULL;
+ if (!IsValidEngine(engine_id)) return nullptr;
::SetDParam(0, engine_id);
return GetString(STR_ENGINE_NAME);
diff --git a/src/script/api/script_error.hpp b/src/script/api/script_error.hpp
index 1817cdb7d..346298d2c 100644
--- a/src/script/api/script_error.hpp
+++ b/src/script/api/script_error.hpp
@@ -44,7 +44,7 @@
* @param string The string that is checked.
*/
#define EnforcePreconditionEncodedText(returnval, string) \
- if ((string) == NULL) { \
+ if ((string) == nullptr) { \
ScriptObject::SetLastError(ScriptError::ERR_PRECONDITION_TOO_MANY_PARAMETERS); \
return returnval; \
} \
diff --git a/src/script/api/script_event.cpp b/src/script/api/script_event.cpp
index 0e711ca41..2d364e8d2 100644
--- a/src/script/api/script_event.cpp
+++ b/src/script/api/script_event.cpp
@@ -23,7 +23,7 @@ struct ScriptEventData {
/* static */ void ScriptEventController::CreateEventPointer()
{
- assert(ScriptObject::GetEventPointer() == NULL);
+ assert(ScriptObject::GetEventPointer() == nullptr);
ScriptObject::GetEventPointer() = new ScriptEventData();
}
@@ -45,7 +45,7 @@ struct ScriptEventData {
/* static */ bool ScriptEventController::IsEventWaiting()
{
- if (ScriptObject::GetEventPointer() == NULL) ScriptEventController::CreateEventPointer();
+ if (ScriptObject::GetEventPointer() == nullptr) ScriptEventController::CreateEventPointer();
ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer();
return !data->stack.empty();
@@ -53,10 +53,10 @@ struct ScriptEventData {
/* static */ ScriptEvent *ScriptEventController::GetNextEvent()
{
- if (ScriptObject::GetEventPointer() == NULL) ScriptEventController::CreateEventPointer();
+ if (ScriptObject::GetEventPointer() == nullptr) ScriptEventController::CreateEventPointer();
ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer();
- if (data->stack.empty()) return NULL;
+ if (data->stack.empty()) return nullptr;
ScriptEvent *e = data->stack.front();
data->stack.pop();
@@ -65,7 +65,7 @@ struct ScriptEventData {
/* static */ void ScriptEventController::InsertEvent(ScriptEvent *event)
{
- if (ScriptObject::GetEventPointer() == NULL) ScriptEventController::CreateEventPointer();
+ if (ScriptObject::GetEventPointer() == nullptr) ScriptEventController::CreateEventPointer();
ScriptEventData *data = (ScriptEventData *)ScriptObject::GetEventPointer();
event->AddRef();
diff --git a/src/script/api/script_event_types.cpp b/src/script/api/script_event_types.cpp
index d424e6fef..e997f2320 100644
--- a/src/script/api/script_event_types.cpp
+++ b/src/script/api/script_event_types.cpp
@@ -25,12 +25,12 @@
bool ScriptEventEnginePreview::IsEngineValid() const
{
const Engine *e = ::Engine::GetIfValid(this->engine);
- return e != NULL && e->IsEnabled();
+ return e != nullptr && e->IsEnabled();
}
char *ScriptEventEnginePreview::GetName()
{
- if (!this->IsEngineValid()) return NULL;
+ if (!this->IsEngineValid()) return nullptr;
::SetDParam(0, this->engine);
return GetString(STR_ENGINE_NAME);
@@ -132,13 +132,13 @@ ScriptEventAdminPort::~ScriptEventAdminPort()
}
#define SKIP_EMPTY(p) while (*(p) == ' ' || *(p) == '\n' || *(p) == '\r') (p)++;
-#define RETURN_ERROR(stack) { ScriptLog::Error("Received invalid JSON data from AdminPort."); if (stack != 0) sq_pop(vm, stack); return NULL; }
+#define RETURN_ERROR(stack) { ScriptLog::Error("Received invalid JSON data from AdminPort."); if (stack != 0) sq_pop(vm, stack); return nullptr; }
SQInteger ScriptEventAdminPort::GetObject(HSQUIRRELVM vm)
{
char *p = this->json;
- if (this->ReadTable(vm, p) == NULL) {
+ if (this->ReadTable(vm, p) == nullptr) {
sq_pushnull(vm);
return 1;
}
@@ -189,18 +189,18 @@ char *ScriptEventAdminPort::ReadTable(HSQUIRRELVM vm, char *p)
if (*p++ != '"') RETURN_ERROR(1);
p = ReadString(vm, p);
- if (p == NULL) {
+ if (p == nullptr) {
sq_pop(vm, 1);
- return NULL;
+ return nullptr;
}
SKIP_EMPTY(p);
if (*p++ != ':') RETURN_ERROR(2);
p = this->ReadValue(vm, p);
- if (p == NULL) {
+ if (p == nullptr) {
sq_pop(vm, 2);
- return NULL;
+ return nullptr;
}
sq_rawset(vm, -3);
@@ -241,7 +241,7 @@ char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, char *p)
case '"': {
/* String */
p = ReadString(vm, ++p);
- if (p == NULL) return NULL;
+ if (p == nullptr) return nullptr;
break;
}
@@ -249,7 +249,7 @@ char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, char *p)
case '{': {
/* Table */
p = this->ReadTable(vm, p);
- if (p == NULL) return NULL;
+ if (p == nullptr) return nullptr;
break;
}
@@ -268,9 +268,9 @@ char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, char *p)
while (*p++ != ']') {
p = this->ReadValue(vm, p);
- if (p == NULL) {
+ if (p == nullptr) {
sq_pop(vm, 1);
- return NULL;
+ return nullptr;
}
sq_arrayappend(vm, -2);
diff --git a/src/script/api/script_gamesettings.cpp b/src/script/api/script_gamesettings.cpp
index 1f8ded877..490e6eee0 100644
--- a/src/script/api/script_gamesettings.cpp
+++ b/src/script/api/script_gamesettings.cpp
@@ -21,7 +21,7 @@
{
uint i;
const SettingDesc *sd = GetSettingFromName(setting, &i);
- return sd != NULL && sd->desc.cmd != SDT_STRING;
+ return sd != nullptr && sd->desc.cmd != SDT_STRING;
}
/* static */ int32 ScriptGameSettings::GetValue(const char *setting)
diff --git a/src/script/api/script_goal.cpp b/src/script/api/script_goal.cpp
index 54312cd9d..b5f6ccef2 100644
--- a/src/script/api/script_goal.cpp
+++ b/src/script/api/script_goal.cpp
@@ -34,14 +34,14 @@
CCountedPtr<Text> counter(goal);
EnforcePrecondition(GOAL_INVALID, ScriptObject::GetCompany() == OWNER_DEITY);
- EnforcePrecondition(GOAL_INVALID, goal != NULL);
+ EnforcePrecondition(GOAL_INVALID, goal != nullptr);
const char *text = goal->GetEncodedText();
EnforcePreconditionEncodedText(GOAL_INVALID, text);
EnforcePrecondition(GOAL_INVALID, company == ScriptCompany::COMPANY_INVALID || ScriptCompany::ResolveCompanyID(company) != ScriptCompany::COMPANY_INVALID);
uint8 c = company;
if (company == ScriptCompany::COMPANY_INVALID) c = INVALID_COMPANY;
- StoryPage *story_page = NULL;
+ StoryPage *story_page = nullptr;
if (type == GT_STORY_PAGE && ScriptStoryPage::IsValidStoryPage((ScriptStoryPage::StoryPageID)destination)) story_page = ::StoryPage::Get((ScriptStoryPage::StoryPageID)destination);
EnforcePrecondition(GOAL_INVALID, (type == GT_NONE && destination == 0) ||
@@ -49,7 +49,7 @@
(type == GT_INDUSTRY && ScriptIndustry::IsValidIndustry(destination)) ||
(type == GT_TOWN && ScriptTown::IsValidTown(destination)) ||
(type == GT_COMPANY && ScriptCompany::ResolveCompanyID((ScriptCompany::CompanyID)destination) != ScriptCompany::COMPANY_INVALID) ||
- (type == GT_STORY_PAGE && story_page != NULL && (c == INVALID_COMPANY ? story_page->company == INVALID_COMPANY : story_page->company == INVALID_COMPANY || story_page->company == c)));
+ (type == GT_STORY_PAGE && story_page != nullptr && (c == INVALID_COMPANY ? story_page->company == INVALID_COMPANY : story_page->company == INVALID_COMPANY || story_page->company == c)));
if (!ScriptObject::DoCommand(0, type | (c << 8), destination, CMD_CREATE_GOAL, text, &ScriptInstance::DoCommandReturnGoalID)) return GOAL_INVALID;
@@ -71,7 +71,7 @@
EnforcePrecondition(false, IsValidGoal(goal_id));
EnforcePrecondition(false, ScriptObject::GetCompany() == OWNER_DEITY);
- EnforcePrecondition(false, goal != NULL);
+ EnforcePrecondition(false, goal != nullptr);
EnforcePrecondition(false, !StrEmpty(goal->GetEncodedText()));
return ScriptObject::DoCommand(0, goal_id, 0, CMD_SET_GOAL_TEXT, goal->GetEncodedText());
@@ -85,11 +85,11 @@
EnforcePrecondition(false, ScriptObject::GetCompany() == OWNER_DEITY);
/* Ensure null as used for emtpy string. */
- if (progress != NULL && StrEmpty(progress->GetEncodedText())) {
- progress = NULL;
+ if (progress != nullptr && StrEmpty(progress->GetEncodedText())) {
+ progress = nullptr;
}
- return ScriptObject::DoCommand(0, goal_id, 0, CMD_SET_GOAL_PROGRESS, progress != NULL ? progress->GetEncodedText() : NULL);
+ return ScriptObject::DoCommand(0, goal_id, 0, CMD_SET_GOAL_PROGRESS, progress != nullptr ? progress->GetEncodedText() : nullptr);
}
/* static */ bool ScriptGoal::SetCompleted(GoalID goal_id, bool completed)
@@ -106,7 +106,7 @@
EnforcePrecondition(false, ScriptObject::GetCompany() == OWNER_DEITY);
Goal *g = Goal::Get(goal_id);
- return g != NULL && g->completed;
+ return g != nullptr && g->completed;
}
/* static */ bool ScriptGoal::DoQuestion(uint16 uniqueid, uint8 target, bool is_client, Text *question, QuestionType type, int buttons)
@@ -114,7 +114,7 @@
CCountedPtr<Text> counter(question);
EnforcePrecondition(false, ScriptObject::GetCompany() == OWNER_DEITY);
- EnforcePrecondition(false, question != NULL);
+ EnforcePrecondition(false, question != nullptr);
const char *text = question->GetEncodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePrecondition(false, CountBits(buttons) >= 1 && CountBits(buttons) <= 3);
diff --git a/src/script/api/script_goal.hpp b/src/script/api/script_goal.hpp
index f5dfba095..b8c0873a2 100644
--- a/src/script/api/script_goal.hpp
+++ b/src/script/api/script_goal.hpp
@@ -99,7 +99,7 @@ public:
* @param destination The destination of the \a type type.
* @return The new GoalID, or GOAL_INVALID if it failed.
* @pre No ScriptCompanyMode may be in scope.
- * @pre goal != NULL && len(goal) != 0.
+ * @pre goal != nullptr && len(goal) != 0.
* @pre company == COMPANY_INVALID || ResolveCompanyID(company) != COMPANY_INVALID.
* @pre if type is GT_STORY_PAGE, the company of the goal and the company of the story page need to match:
* \li Global goals can only reference global story pages.
@@ -122,7 +122,7 @@ public:
* @param goal The new goal text (can be either a raw string, or a ScriptText object).
* @return True if the action succeeded.
* @pre No ScriptCompanyMode may be in scope.
- * @pre goal != NULL && len(goal) != 0.
+ * @pre goal != nullptr && len(goal) != 0.
* @pre IsValidGoal(goal_id).
*/
static bool SetText(GoalID goal_id, Text *goal);
@@ -133,7 +133,7 @@ public:
* the progress string short.
* @param goal_id The goal to update.
* @param progress The new progress text for the goal (can be either a raw string,
- * or a ScriptText object). To clear the progress string you can pass NULL or an
+ * or a ScriptText object). To clear the progress string you can pass nullptr or an
* empty string.
* @return True if the action succeeded.
* @pre No ScriptCompanyMode may be in scope.
@@ -169,7 +169,7 @@ public:
* @param buttons Any combinations (at least 1, up to 3) of buttons defined in QuestionButton. Like BUTTON_YES + BUTTON_NO.
* @return True if the action succeeded.
* @pre No ScriptCompanyMode may be in scope.
- * @pre question != NULL && len(question) != 0.
+ * @pre question != nullptr && len(question) != 0.
* @pre company == COMPANY_INVALID || ResolveCompanyID(company) != COMPANY_INVALID.
* @pre CountBits(buttons) >= 1 && CountBits(buttons) <= 3.
* @note Replies to the question are given by you via the event ScriptEvent_GoalQuestionAnswer.
@@ -187,7 +187,7 @@ public:
* @return True if the action succeeded.
* @pre No ScriptCompanyMode may be in scope.
* @pre ScriptGame::IsMultiplayer()
- * @pre question != NULL && len(question) != 0.
+ * @pre question != nullptr && len(question) != 0.
* @pre ResolveClientID(client) != CLIENT_INVALID.
* @pre CountBits(buttons) >= 1 && CountBits(buttons) <= 3.
* @note Replies to the question are given by you via the event ScriptEvent_GoalQuestionAnswer.
diff --git a/src/script/api/script_group.cpp b/src/script/api/script_group.cpp
index fcae6c3d2..55f5ffdeb 100644
--- a/src/script/api/script_group.cpp
+++ b/src/script/api/script_group.cpp
@@ -25,12 +25,12 @@
/* static */ bool ScriptGroup::IsValidGroup(GroupID group_id)
{
const Group *g = ::Group::GetIfValid(group_id);
- return g != NULL && g->owner == ScriptObject::GetCompany();
+ return g != nullptr && g->owner == ScriptObject::GetCompany();
}
/* static */ ScriptGroup::GroupID ScriptGroup::CreateGroup(ScriptVehicle::VehicleType vehicle_type, GroupID parent_group_id)
{
- if (!ScriptObject::DoCommand(0, (::VehicleType)vehicle_type, parent_group_id, CMD_CREATE_GROUP, NULL, &ScriptInstance::DoCommandReturnGroupID)) return GROUP_INVALID;
+ if (!ScriptObject::DoCommand(0, (::VehicleType)vehicle_type, parent_group_id, CMD_CREATE_GROUP, nullptr, &ScriptInstance::DoCommandReturnGroupID)) return GROUP_INVALID;
/* In case of test-mode, we return GroupID 0 */
return (ScriptGroup::GroupID)0;
@@ -55,7 +55,7 @@
CCountedPtr<Text> counter(name);
EnforcePrecondition(false, IsValidGroup(group_id));
- EnforcePrecondition(false, name != NULL);
+ EnforcePrecondition(false, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_GROUP_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
@@ -65,7 +65,7 @@
/* static */ char *ScriptGroup::GetName(GroupID group_id)
{
- if (!IsValidGroup(group_id)) return NULL;
+ if (!IsValidGroup(group_id)) return nullptr;
::SetDParam(0, group_id);
return GetString(STR_GROUP_NAME);
diff --git a/src/script/api/script_group.hpp b/src/script/api/script_group.hpp
index 6e7deb0b7..f44163bba 100644
--- a/src/script/api/script_group.hpp
+++ b/src/script/api/script_group.hpp
@@ -71,7 +71,7 @@ public:
* @param group_id The group to set the name for.
* @param name The name for the group (can be either a raw string, or a ScriptText object).
* @pre IsValidGroup(group_id).
- * @pre name != NULL && len(name) != 0
+ * @pre name != nullptr && len(name) != 0
* @exception ScriptError::ERR_NAME_IS_NOT_UNIQUE
* @return True if and only if the name was changed.
*/
diff --git a/src/script/api/script_industry.cpp b/src/script/api/script_industry.cpp
index 68bb9003d..e72f9955b 100644
--- a/src/script/api/script_industry.cpp
+++ b/src/script/api/script_industry.cpp
@@ -39,7 +39,7 @@
/* static */ char *ScriptIndustry::GetName(IndustryID industry_id)
{
- if (!IsValidIndustry(industry_id)) return NULL;
+ if (!IsValidIndustry(industry_id)) return nullptr;
::SetDParam(0, industry_id);
return GetString(STR_INDUSTRY_NAME);
diff --git a/src/script/api/script_industrytype.cpp b/src/script/api/script_industrytype.cpp
index 1ac59975d..e154705bb 100644
--- a/src/script/api/script_industrytype.cpp
+++ b/src/script/api/script_industrytype.cpp
@@ -59,14 +59,14 @@
/* static */ char *ScriptIndustryType::GetName(IndustryType industry_type)
{
- if (!IsValidIndustryType(industry_type)) return NULL;
+ if (!IsValidIndustryType(industry_type)) return nullptr;
return GetString(::GetIndustrySpec(industry_type)->name);
}
/* static */ ScriptList *ScriptIndustryType::GetProducedCargo(IndustryType industry_type)
{
- if (!IsValidIndustryType(industry_type)) return NULL;
+ if (!IsValidIndustryType(industry_type)) return nullptr;
const IndustrySpec *ins = ::GetIndustrySpec(industry_type);
@@ -80,7 +80,7 @@
/* static */ ScriptList *ScriptIndustryType::GetAcceptedCargo(IndustryType industry_type)
{
- if (!IsValidIndustryType(industry_type)) return NULL;
+ if (!IsValidIndustryType(industry_type)) return nullptr;
const IndustrySpec *ins = ::GetIndustrySpec(industry_type);
diff --git a/src/script/api/script_list.cpp b/src/script/api/script_list.cpp
index d0c72b5bb..13545c422 100644
--- a/src/script/api/script_list.cpp
+++ b/src/script/api/script_list.cpp
@@ -109,7 +109,7 @@ public:
void End()
{
- this->bucket_list = NULL;
+ this->bucket_list = nullptr;
this->has_no_more_items = true;
this->item_next = 0;
}
@@ -119,7 +119,7 @@ public:
*/
void FindNext()
{
- if (this->bucket_list == NULL) {
+ if (this->bucket_list == nullptr) {
this->has_no_more_items = true;
return;
}
@@ -128,7 +128,7 @@ public:
if (this->bucket_list_iter == this->bucket_list->end()) {
this->bucket_iter++;
if (this->bucket_iter == this->list->buckets.end()) {
- this->bucket_list = NULL;
+ this->bucket_list = nullptr;
return;
}
this->bucket_list = &(*this->bucket_iter).second;
@@ -203,7 +203,7 @@ public:
void End()
{
- this->bucket_list = NULL;
+ this->bucket_list = nullptr;
this->has_no_more_items = true;
this->item_next = 0;
}
@@ -213,14 +213,14 @@ public:
*/
void FindNext()
{
- if (this->bucket_list == NULL) {
+ if (this->bucket_list == nullptr) {
this->has_no_more_items = true;
return;
}
if (this->bucket_list_iter == this->bucket_list->begin()) {
if (this->bucket_iter == this->list->buckets.begin()) {
- this->bucket_list = NULL;
+ this->bucket_list = nullptr;
return;
}
this->bucket_iter--;
diff --git a/src/script/api/script_list.hpp b/src/script/api/script_list.hpp
index 1fbafe3d9..b32ebc463 100644
--- a/src/script/api/script_list.hpp
+++ b/src/script/api/script_list.hpp
@@ -198,7 +198,7 @@ public:
/**
* Remove everything that is in the given list from this list (same item index that is).
* @param list the list of items to remove.
- * @pre list != NULL
+ * @pre list != nullptr
*/
void RemoveList(ScriptList *list);
@@ -242,7 +242,7 @@ public:
/**
* Keeps everything that is in the given list from this list (same item index that is).
* @param list the list of items to keep.
- * @pre list != NULL
+ * @pre list != nullptr
*/
void KeepList(ScriptList *list);
diff --git a/src/script/api/script_log.cpp b/src/script/api/script_log.cpp
index d9fbbde98..b40ed97aa 100644
--- a/src/script/api/script_log.cpp
+++ b/src/script/api/script_log.cpp
@@ -35,7 +35,7 @@
/* static */ void ScriptLog::Log(ScriptLog::ScriptLogType level, const char *message)
{
- if (ScriptObject::GetLogPointer() == NULL) {
+ if (ScriptObject::GetLogPointer() == nullptr) {
ScriptObject::GetLogPointer() = new LogData();
LogData *log = (LogData *)ScriptObject::GetLogPointer();
@@ -59,7 +59,7 @@
/* Cut string after first \n */
char *p;
- while ((p = strchr(log->lines[log->pos], '\n')) != NULL) {
+ while ((p = strchr(log->lines[log->pos], '\n')) != nullptr) {
*p = '\0';
break;
}
diff --git a/src/script/api/script_marine.cpp b/src/script/api/script_marine.cpp
index 434ec11ac..bba361cec 100644
--- a/src/script/api/script_marine.cpp
+++ b/src/script/api/script_marine.cpp
@@ -166,9 +166,9 @@
/* static */ Money ScriptMarine::GetBuildCost(BuildType build_type)
{
switch (build_type) {
- case BT_DOCK: return ::GetPrice(PR_BUILD_STATION_DOCK, 1, NULL);
- case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_SHIP, 1, NULL);
- case BT_BUOY: return ::GetPrice(PR_BUILD_WAYPOINT_BUOY, 1, NULL);
+ case BT_DOCK: return ::GetPrice(PR_BUILD_STATION_DOCK, 1, nullptr);
+ case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_SHIP, 1, nullptr);
+ case BT_BUOY: return ::GetPrice(PR_BUILD_WAYPOINT_BUOY, 1, nullptr);
default: return -1;
}
}
diff --git a/src/script/api/script_news.cpp b/src/script/api/script_news.cpp
index 5f84f96d6..0c2ca3792 100644
--- a/src/script/api/script_news.cpp
+++ b/src/script/api/script_news.cpp
@@ -25,7 +25,7 @@
{
CCountedPtr<Text> counter(text);
- EnforcePrecondition(false, text != NULL);
+ EnforcePrecondition(false, text != nullptr);
const char *encoded = text->GetEncodedText();
EnforcePreconditionEncodedText(false, encoded);
EnforcePrecondition(false, type == NT_ECONOMY || type == NT_SUBSIDIES || type == NT_GENERAL);
diff --git a/src/script/api/script_news.hpp b/src/script/api/script_news.hpp
index ca0656608..441419338 100644
--- a/src/script/api/script_news.hpp
+++ b/src/script/api/script_news.hpp
@@ -61,7 +61,7 @@ public:
* - For #NR_TOWN this parameter should be a valid townID (ScriptTown::IsValidTown).
* @return True if the action succeeded.
* @pre type must be #NT_ECONOMY, #NT_SUBSIDIES, or #NT_GENERAL.
- * @pre text != NULL.
+ * @pre text != nullptr.
* @pre company == COMPANY_INVALID || ResolveCompanyID(company) != COMPANY_INVALID.
* @pre The \a reference condition must be fulfilled.
*/
diff --git a/src/script/api/script_object.cpp b/src/script/api/script_object.cpp
index 7a22e3ab7..67ab7e40d 100644
--- a/src/script/api/script_object.cpp
+++ b/src/script/api/script_object.cpp
@@ -36,7 +36,7 @@ static ScriptStorage *GetStorage()
}
-/* static */ ScriptInstance *ScriptObject::ActiveInstance::active = NULL;
+/* static */ ScriptInstance *ScriptObject::ActiveInstance::active = nullptr;
ScriptObject::ActiveInstance::ActiveInstance(ScriptInstance *instance)
{
@@ -51,7 +51,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
/* static */ ScriptInstance *ScriptObject::GetActiveInstance()
{
- assert(ScriptObject::ActiveInstance::active != NULL);
+ assert(ScriptObject::ActiveInstance::active != nullptr);
return ScriptObject::ActiveInstance::active;
}
@@ -296,16 +296,16 @@ ScriptObject::ActiveInstance::~ActiveInstance()
}
/* Set the default callback to return a true/false result of the DoCommand */
- if (callback == NULL) callback = &ScriptInstance::DoCommandReturn;
+ if (callback == nullptr) callback = &ScriptInstance::DoCommandReturn;
/* Are we only interested in the estimate costs? */
- bool estimate_only = GetDoCommandMode() != NULL && !GetDoCommandMode()();
+ bool estimate_only = GetDoCommandMode() != nullptr && !GetDoCommandMode()();
/* Only set p2 when the command does not come from the network. */
if (GetCommandFlags(cmd) & CMD_CLIENT_ID && p2 == 0) p2 = UINT32_MAX;
/* Try to perform the command. */
- CommandCost res = ::DoCommandPInternal(tile, p1, p2, cmd, (_networking && !_generating_world) ? ScriptObject::GetActiveInstance()->GetDoCommandCallback() : NULL, text, false, estimate_only);
+ CommandCost res = ::DoCommandPInternal(tile, p1, p2, cmd, (_networking && !_generating_world) ? ScriptObject::GetActiveInstance()->GetDoCommandCallback() : nullptr, text, false, estimate_only);
/* We failed; set the error and bail out */
if (res.Failed()) {
@@ -328,7 +328,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
if (_generating_world) {
IncreaseDoCommandCosts(res.GetCost());
- if (callback != NULL) {
+ if (callback != nullptr) {
/* Insert return value into to stack and throw a control code that
* the return value in the stack should be used. */
callback(GetActiveInstance());
diff --git a/src/script/api/script_object.hpp b/src/script/api/script_object.hpp
index 482e76f66..6725f0ed1 100644
--- a/src/script/api/script_object.hpp
+++ b/src/script/api/script_object.hpp
@@ -69,7 +69,7 @@ protected:
/**
* Executes a raw DoCommand for the script.
*/
- static bool DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint cmd, const char *text = NULL, Script_SuspendCallbackProc *callback = NULL);
+ static bool DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint cmd, const char *text = nullptr, Script_SuspendCallbackProc *callback = nullptr);
/**
* Sets the DoCommand costs counter to a value.
diff --git a/src/script/api/script_order.cpp b/src/script/api/script_order.cpp
index a1390bf8f..04f7c69f4 100644
--- a/src/script/api/script_order.cpp
+++ b/src/script/api/script_order.cpp
@@ -66,7 +66,7 @@ static const Order *ResolveOrder(VehicleID vehicle_id, ScriptOrder::OrderPositio
const Order *order = &v->current_order;
if (order->GetType() == OT_GOTO_DEPOT && !(order->GetDepotOrderType() & ODTFB_PART_OF_ORDERS)) return order;
order_position = ScriptOrder::ResolveOrderPosition(vehicle_id, order_position);
- if (order_position == ScriptOrder::ORDER_INVALID) return NULL;
+ if (order_position == ScriptOrder::ORDER_INVALID) return nullptr;
}
const Order *order = v->GetFirstOrder();
while (order->GetType() == OT_IMPLICIT) order = order->next;
@@ -108,7 +108,7 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
- return order != NULL && order->GetType() == OT_GOTO_STATION;
+ return order != nullptr && order->GetType() == OT_GOTO_STATION;
}
/* static */ bool ScriptOrder::IsGotoDepotOrder(VehicleID vehicle_id, OrderPosition order_position)
@@ -116,7 +116,7 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
- return order != NULL && order->GetType() == OT_GOTO_DEPOT;
+ return order != nullptr && order->GetType() == OT_GOTO_DEPOT;
}
/* static */ bool ScriptOrder::IsGotoWaypointOrder(VehicleID vehicle_id, OrderPosition order_position)
@@ -124,7 +124,7 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
- return order != NULL && order->GetType() == OT_GOTO_WAYPOINT;
+ return order != nullptr && order->GetType() == OT_GOTO_WAYPOINT;
}
/* static */ bool ScriptOrder::IsConditionalOrder(VehicleID vehicle_id, OrderPosition order_position)
@@ -150,7 +150,7 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
- return order != NULL && order->IsRefit();
+ return order != nullptr && order->IsRefit();
}
/* static */ bool ScriptOrder::IsCurrentOrderPartOfOrderList(VehicleID vehicle_id)
@@ -240,7 +240,7 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
if (!IsValidVehicleOrder(vehicle_id, order_position)) return INVALID_TILE;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
- if (order == NULL || order->GetType() == OT_CONDITIONAL) return INVALID_TILE;
+ if (order == nullptr || order->GetType() == OT_CONDITIONAL) return INVALID_TILE;
const Vehicle *v = ::Vehicle::Get(vehicle_id);
switch (order->GetType()) {
@@ -263,9 +263,9 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
}
} else if (st->dock_tile != INVALID_TILE) {
return st->dock_tile;
- } else if (st->bus_stops != NULL) {
+ } else if (st->bus_stops != nullptr) {
return st->bus_stops->xy;
- } else if (st->truck_stops != NULL) {
+ } else if (st->truck_stops != nullptr) {
return st->truck_stops->xy;
} else if (st->airport.tile != INVALID_TILE) {
TILE_AREA_LOOP(tile, st->airport) {
@@ -294,7 +294,7 @@ static int ScriptOrderPositionToRealOrderPosition(VehicleID vehicle_id, ScriptOr
if (!IsValidVehicleOrder(vehicle_id, order_position)) return OF_INVALID;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
- if (order == NULL || order->GetType() == OT_CONDITIONAL || order->GetType() == OT_DUMMY) return OF_INVALID;
+ if (order == nullptr || order->GetType() == OT_CONDITIONAL || order->GetType() == OT_DUMMY) return OF_INVALID;
ScriptOrderFlags order_flags = OF_NONE;
order_flags |= (ScriptOrderFlags)order->GetNonStopType();
@@ -586,7 +586,7 @@ static void _DoCommandReturnSetOrderFlags(class ScriptInstance *instance)
EnforcePrecondition(false, (order_flags & OF_GOTO_NEAREST_DEPOT) == (current & OF_GOTO_NEAREST_DEPOT));
if ((current & OF_NON_STOP_FLAGS) != (order_flags & OF_NON_STOP_FLAGS)) {
- return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (order_flags & OF_NON_STOP_FLAGS) << 4 | MOF_NON_STOP, CMD_MODIFY_ORDER, NULL, &::_DoCommandReturnSetOrderFlags);
+ return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (order_flags & OF_NON_STOP_FLAGS) << 4 | MOF_NON_STOP, CMD_MODIFY_ORDER, nullptr, &::_DoCommandReturnSetOrderFlags);
}
switch (order->GetType()) {
@@ -595,16 +595,16 @@ static void _DoCommandReturnSetOrderFlags(class ScriptInstance *instance)
uint data = DA_ALWAYS_GO;
if (order_flags & OF_SERVICE_IF_NEEDED) data = DA_SERVICE;
if (order_flags & OF_STOP_IN_DEPOT) data = DA_STOP;
- return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (data << 4) | MOF_DEPOT_ACTION, CMD_MODIFY_ORDER, NULL, &::_DoCommandReturnSetOrderFlags);
+ return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (data << 4) | MOF_DEPOT_ACTION, CMD_MODIFY_ORDER, nullptr, &::_DoCommandReturnSetOrderFlags);
}
break;
case OT_GOTO_STATION:
if ((current & OF_UNLOAD_FLAGS) != (order_flags & OF_UNLOAD_FLAGS)) {
- return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (order_flags & OF_UNLOAD_FLAGS) << 2 | MOF_UNLOAD, CMD_MODIFY_ORDER, NULL, &::_DoCommandReturnSetOrderFlags);
+ return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (order_flags & OF_UNLOAD_FLAGS) << 2 | MOF_UNLOAD, CMD_MODIFY_ORDER, nullptr, &::_DoCommandReturnSetOrderFlags);
}
if ((current & OF_LOAD_FLAGS) != (order_flags & OF_LOAD_FLAGS)) {
- return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (order_flags & OF_LOAD_FLAGS) >> 1 | MOF_LOAD, CMD_MODIFY_ORDER, NULL, &::_DoCommandReturnSetOrderFlags);
+ return ScriptObject::DoCommand(0, vehicle_id | (order_pos << 20), (order_flags & OF_LOAD_FLAGS) >> 1 | MOF_LOAD, CMD_MODIFY_ORDER, nullptr, &::_DoCommandReturnSetOrderFlags);
}
break;
diff --git a/src/script/api/script_rail.cpp b/src/script/api/script_rail.cpp
index f7682cfd8..d4580fc32 100644
--- a/src/script/api/script_rail.cpp
+++ b/src/script/api/script_rail.cpp
@@ -25,7 +25,7 @@
/* static */ char *ScriptRail::GetName(RailType rail_type)
{
- if (!IsRailTypeAvailable(rail_type)) return NULL;
+ if (!IsRailTypeAvailable(rail_type)) return nullptr;
return GetString(GetRailTypeInfo((::RailType)rail_type)->strings.menu_text);
}
@@ -185,7 +185,7 @@
if (res != CALLBACK_FAILED) {
int index = 0;
const StationSpec *spec = StationClass::GetByGrf(file->grfid, res, &index);
- if (spec == NULL) {
+ if (spec == nullptr) {
DEBUG(grf, 1, "%s returned an invalid station ID for 'AI construction/purchase selection (18)' callback", file->filename);
} else {
/* We might have gotten an usable station spec. Try to build it, but if it fails we'll fall back to the original station. */
@@ -487,10 +487,10 @@ static bool IsValidSignalType(int signal_type)
switch (build_type) {
case BT_TRACK: return ::RailBuildCost((::RailType)railtype);
- case BT_SIGNAL: return ::GetPrice(PR_BUILD_SIGNALS, 1, NULL);
- case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_TRAIN, 1, NULL);
- case BT_STATION: return ::GetPrice(PR_BUILD_STATION_RAIL, 1, NULL) + ::GetPrice(PR_BUILD_STATION_RAIL_LENGTH, 1, NULL);
- case BT_WAYPOINT: return ::GetPrice(PR_BUILD_WAYPOINT_RAIL, 1, NULL);
+ case BT_SIGNAL: return ::GetPrice(PR_BUILD_SIGNALS, 1, nullptr);
+ case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_TRAIN, 1, nullptr);
+ case BT_STATION: return ::GetPrice(PR_BUILD_STATION_RAIL, 1, nullptr) + ::GetPrice(PR_BUILD_STATION_RAIL_LENGTH, 1, nullptr);
+ case BT_WAYPOINT: return ::GetPrice(PR_BUILD_WAYPOINT_RAIL, 1, nullptr);
default: return -1;
}
}
diff --git a/src/script/api/script_road.cpp b/src/script/api/script_road.cpp
index 44972cdea..74899f8bb 100644
--- a/src/script/api/script_road.cpp
+++ b/src/script/api/script_road.cpp
@@ -588,10 +588,10 @@ static bool NeighbourHasReachableRoad(::RoadTypes rts, TileIndex start_tile, Dia
if (!ScriptRoad::IsRoadTypeAvailable(roadtype)) return -1;
switch (build_type) {
- case BT_ROAD: return ::GetPrice(PR_BUILD_ROAD, 1, NULL);
- case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_ROAD, 1, NULL);
- case BT_BUS_STOP: return ::GetPrice(PR_BUILD_STATION_BUS, 1, NULL);
- case BT_TRUCK_STOP: return ::GetPrice(PR_BUILD_STATION_TRUCK, 1, NULL);
+ case BT_ROAD: return ::GetPrice(PR_BUILD_ROAD, 1, nullptr);
+ case BT_DEPOT: return ::GetPrice(PR_BUILD_DEPOT_ROAD, 1, nullptr);
+ case BT_BUS_STOP: return ::GetPrice(PR_BUILD_STATION_BUS, 1, nullptr);
+ case BT_TRUCK_STOP: return ::GetPrice(PR_BUILD_STATION_TRUCK, 1, nullptr);
default: return -1;
}
}
diff --git a/src/script/api/script_sign.cpp b/src/script/api/script_sign.cpp
index 236e1df7e..33c8e9a28 100644
--- a/src/script/api/script_sign.cpp
+++ b/src/script/api/script_sign.cpp
@@ -23,7 +23,7 @@
/* static */ bool ScriptSign::IsValidSign(SignID sign_id)
{
const Sign *si = ::Sign::GetIfValid(sign_id);
- return si != NULL && (si->owner == ScriptObject::GetCompany() || si->owner == OWNER_DEITY);
+ return si != nullptr && (si->owner == ScriptObject::GetCompany() || si->owner == OWNER_DEITY);
}
/* static */ ScriptCompany::CompanyID ScriptSign::GetOwner(SignID sign_id)
@@ -38,7 +38,7 @@
CCountedPtr<Text> counter(name);
EnforcePrecondition(false, IsValidSign(sign_id));
- EnforcePrecondition(false, name != NULL);
+ EnforcePrecondition(false, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_SIGN_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
@@ -48,7 +48,7 @@
/* static */ char *ScriptSign::GetName(SignID sign_id)
{
- if (!IsValidSign(sign_id)) return NULL;
+ if (!IsValidSign(sign_id)) return nullptr;
::SetDParam(0, sign_id);
return GetString(STR_SIGN_NAME);
@@ -73,7 +73,7 @@
CCountedPtr<Text> counter(name);
EnforcePrecondition(INVALID_SIGN, ::IsValidTile(location));
- EnforcePrecondition(INVALID_SIGN, name != NULL);
+ EnforcePrecondition(INVALID_SIGN, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(INVALID_SIGN, text);
EnforcePreconditionCustomError(INVALID_SIGN, ::Utf8StringLength(text) < MAX_LENGTH_SIGN_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
diff --git a/src/script/api/script_sign.hpp b/src/script/api/script_sign.hpp
index e5c2164da..4b0483e98 100644
--- a/src/script/api/script_sign.hpp
+++ b/src/script/api/script_sign.hpp
@@ -45,7 +45,7 @@ public:
* @param sign_id The sign to set the name for.
* @param name The name for the sign (can be either a raw string, or a ScriptText object).
* @pre IsValidSign(sign_id).
- * @pre name != NULL && len(name) != 0.
+ * @pre name != nullptr && len(name) != 0.
* @exception ScriptError::ERR_NAME_IS_NOT_UNIQUE
* @return True if and only if the name was changed.
*/
@@ -81,7 +81,7 @@ public:
* @param location The place to build the sign.
* @param name The text to place on the sign (can be either a raw string, or a ScriptText object).
* @pre ScriptMap::IsValidTile(location).
- * @pre name != NULL && len(name) != 0.
+ * @pre name != nullptr && len(name) != 0.
* @exception ScriptSign::ERR_SIGN_TOO_MANY_SIGNS
* @return The SignID of the build sign (use IsValidSign() to check for validity).
* In test-mode it returns 0 if successful, or any other value to indicate
diff --git a/src/script/api/script_station.cpp b/src/script/api/script_station.cpp
index 5ed43e0a6..3b3bae33c 100644
--- a/src/script/api/script_station.cpp
+++ b/src/script/api/script_station.cpp
@@ -23,7 +23,7 @@
/* static */ bool ScriptStation::IsValidStation(StationID station_id)
{
const Station *st = ::Station::GetIfValid(station_id);
- return st != NULL && (st->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY || st->owner == OWNER_NONE);
+ return st != nullptr && (st->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY || st->owner == OWNER_NONE);
}
/* static */ ScriptCompany::CompanyID ScriptStation::GetOwner(StationID station_id)
@@ -213,10 +213,10 @@ template<bool Tfrom, bool Tvia>
::RoadTypes r = RoadTypeToRoadTypes((::RoadType)road_type);
- for (const RoadStop *rs = ::Station::Get(station_id)->GetPrimaryRoadStop(ROADSTOP_BUS); rs != NULL; rs = rs->next) {
+ for (const RoadStop *rs = ::Station::Get(station_id)->GetPrimaryRoadStop(ROADSTOP_BUS); rs != nullptr; rs = rs->next) {
if ((::GetRoadTypes(rs->xy) & r) != 0) return true;
}
- for (const RoadStop *rs = ::Station::Get(station_id)->GetPrimaryRoadStop(ROADSTOP_TRUCK); rs != NULL; rs = rs->next) {
+ for (const RoadStop *rs = ::Station::Get(station_id)->GetPrimaryRoadStop(ROADSTOP_TRUCK); rs != nullptr; rs = rs->next) {
if ((::GetRoadTypes(rs->xy) & r) != 0) return true;
}
diff --git a/src/script/api/script_stationlist.cpp b/src/script/api/script_stationlist.cpp
index 51a06b5a7..4bbb5fa67 100644
--- a/src/script/api/script_stationlist.cpp
+++ b/src/script/api/script_stationlist.cpp
@@ -32,7 +32,7 @@ ScriptStationList_Vehicle::ScriptStationList_Vehicle(VehicleID vehicle_id)
Vehicle *v = ::Vehicle::Get(vehicle_id);
- for (Order *o = v->GetFirstOrder(); o != NULL; o = o->next) {
+ for (Order *o = v->GetFirstOrder(); o != nullptr; o = o->next) {
if (o->IsType(OT_GOTO_STATION)) this->AddItem(o->GetDestination());
}
}
@@ -120,7 +120,7 @@ private:
CargoCollector::CargoCollector(ScriptStationList_Cargo *parent,
StationID station_id, CargoID cargo, StationID other) :
- list(parent), ge(NULL), other_station(other), last_key(INVALID_STATION), amount(0)
+ list(parent), ge(nullptr), other_station(other), last_key(INVALID_STATION), amount(0)
{
if (!ScriptStation::IsValidStation(station_id)) return;
if (!ScriptCargo::IsValidCargo(cargo)) return;
@@ -176,7 +176,7 @@ template<ScriptStationList_Cargo::CargoSelector Tselector>
void ScriptStationList_CargoWaiting::Add(StationID station_id, CargoID cargo, StationID other_station)
{
CargoCollector collector(this, station_id, cargo, other_station);
- if (collector.GE() == NULL) return;
+ if (collector.GE() == nullptr) return;
StationCargoList::ConstIterator iter = collector.GE()->cargo.Packets()->begin();
StationCargoList::ConstIterator end = collector.GE()->cargo.Packets()->end();
@@ -190,7 +190,7 @@ template<ScriptStationList_Cargo::CargoSelector Tselector>
void ScriptStationList_CargoPlanned::Add(StationID station_id, CargoID cargo, StationID other_station)
{
CargoCollector collector(this, station_id, cargo, other_station);
- if (collector.GE() == NULL) return;
+ if (collector.GE() == nullptr) return;
FlowStatMap::const_iterator iter = collector.GE()->flows.begin();
FlowStatMap::const_iterator end = collector.GE()->flows.end();
@@ -215,7 +215,7 @@ ScriptStationList_CargoWaitingViaByFrom::ScriptStationList_CargoWaitingViaByFrom
StationID station_id, CargoID cargo, StationID via)
{
CargoCollector collector(this, station_id, cargo, via);
- if (collector.GE() == NULL) return;
+ if (collector.GE() == nullptr) return;
std::pair<StationCargoList::ConstIterator, StationCargoList::ConstIterator> range =
collector.GE()->cargo.Packets()->equal_range(via);
@@ -261,7 +261,7 @@ ScriptStationList_CargoPlannedFromByVia::ScriptStationList_CargoPlannedFromByVia
StationID station_id, CargoID cargo, StationID from)
{
CargoCollector collector(this, station_id, cargo, from);
- if (collector.GE() == NULL) return;
+ if (collector.GE() == nullptr) return;
FlowStatMap::const_iterator iter = collector.GE()->flows.find(from);
if (iter == collector.GE()->flows.end()) return;
diff --git a/src/script/api/script_story_page.cpp b/src/script/api/script_story_page.cpp
index 11820ec3f..e31ad71c3 100644
--- a/src/script/api/script_story_page.cpp
+++ b/src/script/api/script_story_page.cpp
@@ -48,7 +48,7 @@
c,
0,
CMD_CREATE_STORY_PAGE,
- title != NULL? title->GetEncodedText() : NULL,
+ title != nullptr? title->GetEncodedText() : nullptr,
&ScriptInstance::DoCommandReturnStoryPageID)) return STORY_PAGE_INVALID;
/* In case of test-mode, we return StoryPageID 0 */
@@ -61,7 +61,7 @@
EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, ScriptObject::GetCompany() == OWNER_DEITY);
EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, IsValidStoryPage(story_page_id));
- EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, (type != SPET_TEXT && type != SPET_LOCATION) || (text != NULL && !StrEmpty(text->GetEncodedText())));
+ EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, (type != SPET_TEXT && type != SPET_LOCATION) || (text != nullptr && !StrEmpty(text->GetEncodedText())));
EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, type != SPET_LOCATION || ::IsValidTile(reference));
EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, type != SPET_GOAL || ScriptGoal::IsValidGoal((ScriptGoal::GoalID)reference));
EnforcePrecondition(STORY_PAGE_ELEMENT_INVALID, type != SPET_GOAL || !(StoryPage::Get(story_page_id)->company == INVALID_COMPANY && Goal::Get(reference)->company != INVALID_COMPANY));
@@ -70,7 +70,7 @@
story_page_id + (type << 16),
type == SPET_GOAL ? reference : 0,
CMD_CREATE_STORY_PAGE_ELEMENT,
- type == SPET_TEXT || type == SPET_LOCATION ? text->GetEncodedText() : NULL,
+ type == SPET_TEXT || type == SPET_LOCATION ? text->GetEncodedText() : nullptr,
&ScriptInstance::DoCommandReturnStoryPageElementID)) return STORY_PAGE_ELEMENT_INVALID;
/* In case of test-mode, we return StoryPageElementID 0 */
@@ -88,7 +88,7 @@
StoryPage *p = StoryPage::Get(pe->page);
::StoryPageElementType type = pe->type;
- EnforcePrecondition(false, (type != ::SPET_TEXT && type != ::SPET_LOCATION) || (text != NULL && !StrEmpty(text->GetEncodedText())));
+ EnforcePrecondition(false, (type != ::SPET_TEXT && type != ::SPET_LOCATION) || (text != nullptr && !StrEmpty(text->GetEncodedText())));
EnforcePrecondition(false, type != ::SPET_LOCATION || ::IsValidTile(reference));
EnforcePrecondition(false, type != ::SPET_GOAL || ScriptGoal::IsValidGoal((ScriptGoal::GoalID)reference));
EnforcePrecondition(false, type != ::SPET_GOAL || !(p->company == INVALID_COMPANY && Goal::Get(reference)->company != INVALID_COMPANY));
@@ -97,7 +97,7 @@
story_page_element_id,
type == ::SPET_GOAL ? reference : 0,
CMD_UPDATE_STORY_PAGE_ELEMENT,
- type == ::SPET_TEXT || type == ::SPET_LOCATION ? text->GetEncodedText() : NULL);
+ type == ::SPET_TEXT || type == ::SPET_LOCATION ? text->GetEncodedText() : nullptr);
}
/* static */ uint32 ScriptStoryPage::GetPageSortValue(StoryPageID story_page_id)
@@ -121,7 +121,7 @@
EnforcePrecondition(false, IsValidStoryPage(story_page_id));
EnforcePrecondition(false, ScriptObject::GetCompany() == OWNER_DEITY);
- return ScriptObject::DoCommand(0, story_page_id, 0, CMD_SET_STORY_PAGE_TITLE, title != NULL? title->GetEncodedText() : NULL);
+ return ScriptObject::DoCommand(0, story_page_id, 0, CMD_SET_STORY_PAGE_TITLE, title != nullptr? title->GetEncodedText() : nullptr);
}
/* static */ ScriptCompany::CompanyID ScriptStoryPage::GetCompany(StoryPageID story_page_id)
@@ -147,7 +147,7 @@
EnforcePrecondition(false, IsValidStoryPage(story_page_id));
EnforcePrecondition(false, ScriptObject::GetCompany() == OWNER_DEITY);
- return ScriptObject::DoCommand(0, story_page_id, date, CMD_SET_STORY_PAGE_DATE, NULL);
+ return ScriptObject::DoCommand(0, story_page_id, date, CMD_SET_STORY_PAGE_DATE, nullptr);
}
diff --git a/src/script/api/script_story_page.hpp b/src/script/api/script_story_page.hpp
index c22d4c198..772c16200 100644
--- a/src/script/api/script_story_page.hpp
+++ b/src/script/api/script_story_page.hpp
@@ -97,7 +97,7 @@ public:
* @return The new StoryPageElementID, or STORY_PAGE_ELEMENT_INVALID if it failed.
* @pre No ScriptCompanyMode may be in scope.
* @pre IsValidStoryPage(story_page).
- * @pre (type != SPET_TEXT && type != SPET_LOCATION) || (text != NULL && len(text) != 0).
+ * @pre (type != SPET_TEXT && type != SPET_LOCATION) || (text != nullptr && len(text) != 0).
* @pre type != SPET_LOCATION || ScriptMap::IsValidTile(reference).
* @pre type != SPET_GOAL || ScriptGoal::IsValidGoal(reference).
* @pre if type is SPET_GOAL and story_page is a global page, then referenced goal must be global.
@@ -112,7 +112,7 @@ public:
* @return True if the action succeeded.
* @pre No ScriptCompanyMode may be in scope.
* @pre IsValidStoryPage(story_page).
- * @pre (type != SPET_TEXT && type != SPET_LOCATION) || (text != NULL && len(text) != 0).
+ * @pre (type != SPET_TEXT && type != SPET_LOCATION) || (text != nullptr && len(text) != 0).
* @pre type != SPET_LOCATION || ScriptMap::IsValidTile(reference).
* @pre type != SPET_GOAL || ScriptGoal::IsValidGoal(reference).
* @pre if type is SPET_GOAL and story_page is a global page, then referenced goal must be global.
diff --git a/src/script/api/script_text.cpp b/src/script/api/script_text.cpp
index e692be0ae..bfc866ac4 100644
--- a/src/script/api/script_text.cpp
+++ b/src/script/api/script_text.cpp
@@ -63,7 +63,7 @@ ScriptText::~ScriptText()
{
for (int i = 0; i < SCRIPT_TEXT_MAX_PARAMETERS; i++) {
free(this->params[i]);
- if (this->paramt[i] != NULL) this->paramt[i]->Release();
+ if (this->paramt[i] != nullptr) this->paramt[i]->Release();
}
}
@@ -72,11 +72,11 @@ SQInteger ScriptText::_SetParam(int parameter, HSQUIRRELVM vm)
if (parameter >= SCRIPT_TEXT_MAX_PARAMETERS) return SQ_ERROR;
free(this->params[parameter]);
- if (this->paramt[parameter] != NULL) this->paramt[parameter]->Release();
+ if (this->paramt[parameter] != nullptr) this->paramt[parameter]->Release();
this->parami[parameter] = 0;
- this->params[parameter] = NULL;
- this->paramt[parameter] = NULL;
+ this->params[parameter] = nullptr;
+ this->paramt[parameter] = nullptr;
switch (sq_gettype(vm, -1)) {
case OT_STRING: {
@@ -97,7 +97,7 @@ SQInteger ScriptText::_SetParam(int parameter, HSQUIRRELVM vm)
}
case OT_INSTANCE: {
- SQUserPointer real_instance = NULL;
+ SQUserPointer real_instance = nullptr;
HSQOBJECT instance;
sq_getstackobj(vm, -1, &instance);
@@ -112,7 +112,7 @@ SQInteger ScriptText::_SetParam(int parameter, HSQUIRRELVM vm)
/* Get the 'real' instance of this class */
sq_getinstanceup(vm, -1, &real_instance, 0);
- if (real_instance == NULL) return SQ_ERROR;
+ if (real_instance == nullptr) return SQ_ERROR;
ScriptText *value = static_cast<ScriptText *>(real_instance);
value->AddRef();
@@ -183,7 +183,7 @@ const char *ScriptText::GetEncodedText()
static char buf[1024];
int param_count = 0;
this->_GetEncodedText(buf, lastof(buf), param_count);
- return (param_count > SCRIPT_TEXT_MAX_PARAMETERS) ? NULL : buf;
+ return (param_count > SCRIPT_TEXT_MAX_PARAMETERS) ? nullptr : buf;
}
char *ScriptText::_GetEncodedText(char *p, char *lastofp, int &param_count)
@@ -191,12 +191,12 @@ char *ScriptText::_GetEncodedText(char *p, char *lastofp, int &param_count)
p += Utf8Encode(p, SCC_ENCODED);
p += seprintf(p, lastofp, "%X", this->string);
for (int i = 0; i < this->paramc; i++) {
- if (this->params[i] != NULL) {
+ if (this->params[i] != nullptr) {
p += seprintf(p, lastofp, ":\"%s\"", this->params[i]);
param_count++;
continue;
}
- if (this->paramt[i] != NULL) {
+ if (this->paramt[i] != nullptr) {
p += seprintf(p, lastofp, ":");
p = this->paramt[i]->_GetEncodedText(p, lastofp, param_count);
continue;
@@ -211,7 +211,7 @@ char *ScriptText::_GetEncodedText(char *p, char *lastofp, int &param_count)
const char *Text::GetDecodedText()
{
const char *encoded_text = this->GetEncodedText();
- if (encoded_text == NULL) return NULL;
+ if (encoded_text == nullptr) return nullptr;
static char buf[1024];
::SetDParamStr(0, encoded_text);
diff --git a/src/script/api/script_text.hpp b/src/script/api/script_text.hpp
index 0b82ffb20..12892a7e7 100644
--- a/src/script/api/script_text.hpp
+++ b/src/script/api/script_text.hpp
@@ -23,14 +23,14 @@ class Text : public ScriptObject {
public:
/**
* Convert a ScriptText to a normal string.
- * @return A string (in a static buffer), or NULL.
+ * @return A string (in a static buffer), or nullptr.
* @api -all
*/
virtual const char *GetEncodedText() = 0;
/**
* Convert a #ScriptText into a decoded normal string.
- * @return A string (in a static buffer), or NULL.
+ * @return A string (in a static buffer), or nullptr.
* @api -all
*/
const char *GetDecodedText();
diff --git a/src/script/api/script_tile.cpp b/src/script/api/script_tile.cpp
index db9220acd..136461762 100644
--- a/src/script/api/script_tile.cpp
+++ b/src/script/api/script_tile.cpp
@@ -292,7 +292,7 @@
if (!::IsValidTile(tile)) return INVALID_TOWN;
Town *town = ::ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
- if (town == NULL) return INVALID_TOWN;
+ if (town == nullptr) return INVALID_TOWN;
return town->index;
}
@@ -302,7 +302,7 @@
if (!::IsValidTile(tile)) return INVALID_TOWN;
Town *town = ::ClosestTownFromTile(tile, UINT_MAX);
- if (town == NULL) return INVALID_TOWN;
+ if (town == nullptr) return INVALID_TOWN;
return town->index;
}
@@ -310,14 +310,14 @@
/* static */ Money ScriptTile::GetBuildCost(BuildType build_type)
{
switch (build_type) {
- case BT_FOUNDATION: return ::GetPrice(PR_BUILD_FOUNDATION, 1, NULL);
- case BT_TERRAFORM: return ::GetPrice(PR_TERRAFORM, 1, NULL);
- case BT_BUILD_TREES: return ::GetPrice(PR_BUILD_TREES, 1, NULL);
- case BT_CLEAR_GRASS: return ::GetPrice(PR_CLEAR_GRASS, 1, NULL);
- case BT_CLEAR_ROUGH: return ::GetPrice(PR_CLEAR_ROUGH, 1, NULL);
- case BT_CLEAR_ROCKY: return ::GetPrice(PR_CLEAR_ROCKS, 1, NULL);
- case BT_CLEAR_FIELDS: return ::GetPrice(PR_CLEAR_FIELDS, 1, NULL);
- case BT_CLEAR_HOUSE: return ::GetPrice(PR_CLEAR_HOUSE, 1, NULL);
+ case BT_FOUNDATION: return ::GetPrice(PR_BUILD_FOUNDATION, 1, nullptr);
+ case BT_TERRAFORM: return ::GetPrice(PR_TERRAFORM, 1, nullptr);
+ case BT_BUILD_TREES: return ::GetPrice(PR_BUILD_TREES, 1, nullptr);
+ case BT_CLEAR_GRASS: return ::GetPrice(PR_CLEAR_GRASS, 1, nullptr);
+ case BT_CLEAR_ROUGH: return ::GetPrice(PR_CLEAR_ROUGH, 1, nullptr);
+ case BT_CLEAR_ROCKY: return ::GetPrice(PR_CLEAR_ROCKS, 1, nullptr);
+ case BT_CLEAR_FIELDS: return ::GetPrice(PR_CLEAR_FIELDS, 1, nullptr);
+ case BT_CLEAR_HOUSE: return ::GetPrice(PR_CLEAR_HOUSE, 1, nullptr);
default: return -1;
}
}
diff --git a/src/script/api/script_town.cpp b/src/script/api/script_town.cpp
index 64f8e166e..9adfa5075 100644
--- a/src/script/api/script_town.cpp
+++ b/src/script/api/script_town.cpp
@@ -35,7 +35,7 @@
/* static */ char *ScriptTown::GetName(TownID town_id)
{
- if (!IsValidTown(town_id)) return NULL;
+ if (!IsValidTown(town_id)) return nullptr;
::SetDParam(0, town_id);
return GetString(STR_TOWN_NAME);
@@ -45,8 +45,8 @@
{
CCountedPtr<Text> counter(name);
- const char *text = NULL;
- if (name != NULL) {
+ const char *text = nullptr;
+ if (name != nullptr) {
text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_TOWN_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
@@ -60,7 +60,7 @@
{
CCountedPtr<Text> counter(text);
- EnforcePrecondition(false, text != NULL);
+ EnforcePrecondition(false, text != nullptr);
const char *encoded_text = text->GetEncodedText();
EnforcePreconditionEncodedText(false, encoded_text);
EnforcePrecondition(false, IsValidTown(town_id));
@@ -257,7 +257,7 @@
if (ScriptObject::GetCompany() == OWNER_DEITY) return false;
if (!IsValidTown(town_id)) return false;
- return HasBit(::GetMaskOfTownActions(NULL, ScriptObject::GetCompany(), ::Town::Get(town_id)), town_action);
+ return HasBit(::GetMaskOfTownActions(nullptr, ScriptObject::GetCompany(), ::Town::Get(town_id)), town_action);
}
/* static */ bool ScriptTown::PerformTownAction(TownID town_id, TownAction town_action)
@@ -293,8 +293,8 @@
layout = (RoadLayout) (byte)_settings_game.economy.town_layout;
}
- const char *text = NULL;
- if (name != NULL) {
+ const char *text = nullptr;
+ if (name != nullptr) {
text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_TOWN_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
diff --git a/src/script/api/script_town.hpp b/src/script/api/script_town.hpp
index 7fdf8a6b3..302c676eb 100644
--- a/src/script/api/script_town.hpp
+++ b/src/script/api/script_town.hpp
@@ -148,7 +148,7 @@ public:
/**
* Rename a town.
* @param town_id The town to rename
- * @param name The new name of the town. If NULL or an empty string is passed, the town name will be reset to the default name.
+ * @param name The new name of the town. If nullptr or an empty string is passed, the town name will be reset to the default name.
* @pre IsValidTown(town_id).
* @return True if the action succeeded.
* @api -ai
@@ -402,7 +402,7 @@ public:
* @param size The town size of the new town.
* @param city True if the new town should be a city.
* @param layout The town layout of the new town.
- * @param name The name of the new town. Pass NULL to use a random town name.
+ * @param name The name of the new town. Pass nullptr to use a random town name.
* @game @pre no company mode in scope || ScriptSettings.GetValue("economy.found_town") != 0.
* @ai @pre ScriptSettings.GetValue("economy.found_town") != 0.
* @game @pre no company mode in scope || size != TOWN_SIZE_LARGE.
diff --git a/src/script/api/script_tunnel.cpp b/src/script/api/script_tunnel.cpp
index 7b891f28d..a8bfcbfd3 100644
--- a/src/script/api/script_tunnel.cpp
+++ b/src/script/api/script_tunnel.cpp
@@ -102,7 +102,7 @@ static void _DoCommandReturnBuildTunnel1(class ScriptInstance *instance)
}
ScriptObject::SetCallbackVariable(0, start);
- return ScriptObject::DoCommand(start, type, 0, CMD_BUILD_TUNNEL, NULL, &::_DoCommandReturnBuildTunnel1);
+ return ScriptObject::DoCommand(start, type, 0, CMD_BUILD_TUNNEL, nullptr, &::_DoCommandReturnBuildTunnel1);
}
/* static */ bool ScriptTunnel::_BuildTunnelRoad1()
@@ -114,7 +114,7 @@ static void _DoCommandReturnBuildTunnel1(class ScriptInstance *instance)
DiagDirection dir_1 = ::DiagdirBetweenTiles(end, start);
DiagDirection dir_2 = ::ReverseDiagDir(dir_1);
- return ScriptObject::DoCommand(start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2) | (ScriptObject::GetRoadType() << 4), 0, CMD_BUILD_ROAD, NULL, &::_DoCommandReturnBuildTunnel2);
+ return ScriptObject::DoCommand(start + ::TileOffsByDiagDir(dir_1), ::DiagDirToRoadBits(dir_2) | (ScriptObject::GetRoadType() << 4), 0, CMD_BUILD_ROAD, nullptr, &::_DoCommandReturnBuildTunnel2);
}
/* static */ bool ScriptTunnel::_BuildTunnelRoad2()
diff --git a/src/script/api/script_vehicle.cpp b/src/script/api/script_vehicle.cpp
index f5023d12c..15bc68a97 100644
--- a/src/script/api/script_vehicle.cpp
+++ b/src/script/api/script_vehicle.cpp
@@ -29,7 +29,7 @@
/* static */ bool ScriptVehicle::IsValidVehicle(VehicleID vehicle_id)
{
const Vehicle *v = ::Vehicle::GetIfValid(vehicle_id);
- return v != NULL && (v->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY) && (v->IsPrimaryVehicle() || (v->type == VEH_TRAIN && ::Train::From(v)->IsFreeWagon()));
+ return v != nullptr && (v->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY) && (v->IsPrimaryVehicle() || (v->type == VEH_TRAIN && ::Train::From(v)->IsFreeWagon()));
}
/* static */ ScriptCompany::CompanyID ScriptVehicle::GetOwner(VehicleID vehicle_id)
@@ -46,8 +46,8 @@
int num = 1;
const Train *v = ::Train::GetIfValid(vehicle_id);
- if (v != NULL) {
- while ((v = v->GetNextUnit()) != NULL) num++;
+ if (v != nullptr) {
+ while ((v = v->GetNextUnit()) != nullptr) num++;
}
return num;
@@ -71,7 +71,7 @@
EnforcePreconditionCustomError(VEHICLE_INVALID, !ScriptGameSettings::IsDisabledVehicleType((ScriptVehicle::VehicleType)type), ScriptVehicle::ERR_VEHICLE_BUILD_DISABLED);
- if (!ScriptObject::DoCommand(depot, engine_id | (cargo << 24), 0, ::GetCmdBuildVeh(type), NULL, &ScriptInstance::DoCommandReturnVehicleID)) return VEHICLE_INVALID;
+ if (!ScriptObject::DoCommand(depot, engine_id | (cargo << 24), 0, ::GetCmdBuildVeh(type), nullptr, &ScriptInstance::DoCommandReturnVehicleID)) return VEHICLE_INVALID;
/* In case of test-mode, we return VehicleID 0 */
return 0;
@@ -104,7 +104,7 @@
EnforcePrecondition(false, ScriptObject::GetCompany() != OWNER_DEITY);
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
- if (!ScriptObject::DoCommand(depot, vehicle_id, share_orders, CMD_CLONE_VEHICLE, NULL, &ScriptInstance::DoCommandReturnVehicleID)) return VEHICLE_INVALID;
+ if (!ScriptObject::DoCommand(depot, vehicle_id, share_orders, CMD_CLONE_VEHICLE, nullptr, &ScriptInstance::DoCommandReturnVehicleID)) return VEHICLE_INVALID;
/* In case of test-mode, we return VehicleID 0 */
return 0;
@@ -120,13 +120,13 @@
const Train *v = ::Train::Get(source_vehicle_id);
while (source_wagon-- > 0) v = v->GetNextUnit();
- const Train *w = NULL;
+ const Train *w = nullptr;
if (dest_vehicle_id != -1) {
w = ::Train::Get(dest_vehicle_id);
while (dest_wagon-- > 0) w = w->GetNextUnit();
}
- return ScriptObject::DoCommand(0, v->index | (move_attached_wagons ? 1 : 0) << 20, w == NULL ? ::INVALID_VEHICLE : w->index, CMD_MOVE_RAIL_VEHICLE);
+ return ScriptObject::DoCommand(0, v->index | (move_attached_wagons ? 1 : 0) << 20, w == nullptr ? ::INVALID_VEHICLE : w->index, CMD_MOVE_RAIL_VEHICLE);
}
/* static */ bool ScriptVehicle::MoveWagon(VehicleID source_vehicle_id, int source_wagon, int dest_vehicle_id, int dest_wagon)
@@ -243,7 +243,7 @@
EnforcePrecondition(false, ScriptObject::GetCompany() != OWNER_DEITY);
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
- EnforcePrecondition(false, name != NULL);
+ EnforcePrecondition(false, name != nullptr);
const char *text = name->GetDecodedText();
EnforcePreconditionEncodedText(false, text);
EnforcePreconditionCustomError(false, ::Utf8StringLength(text) < MAX_LENGTH_VEHICLE_NAME_CHARS, ScriptError::ERR_PRECONDITION_STRING_TOO_LONG);
@@ -293,7 +293,7 @@
/* static */ char *ScriptVehicle::GetName(VehicleID vehicle_id)
{
- if (!IsValidVehicle(vehicle_id)) return NULL;
+ if (!IsValidVehicle(vehicle_id)) return nullptr;
::SetDParam(0, vehicle_id);
return GetString(STR_VEHICLE_NAME);
@@ -410,7 +410,7 @@
if (!ScriptCargo::IsValidCargo(cargo)) return -1;
uint32 amount = 0;
- for (const Vehicle *v = ::Vehicle::Get(vehicle_id); v != NULL; v = v->Next()) {
+ for (const Vehicle *v = ::Vehicle::Get(vehicle_id); v != nullptr; v = v->Next()) {
if (v->cargo_type == cargo) amount += v->cargo_cap;
}
@@ -423,7 +423,7 @@
if (!ScriptCargo::IsValidCargo(cargo)) return -1;
uint32 amount = 0;
- for (const Vehicle *v = ::Vehicle::Get(vehicle_id); v != NULL; v = v->Next()) {
+ for (const Vehicle *v = ::Vehicle::Get(vehicle_id); v != nullptr; v = v->Next()) {
if (v->cargo_type == cargo) amount += v->cargo.StoredCount();
}
@@ -455,7 +455,7 @@
if (!IsValidVehicle(vehicle_id)) return false;
Vehicle *v = ::Vehicle::Get(vehicle_id);
- return v->orders.list != NULL && v->orders.list->GetNumVehicles() > 1;
+ return v->orders.list != nullptr && v->orders.list->GetNumVehicles() > 1;
}
/* static */ int ScriptVehicle::GetReliability(VehicleID vehicle_id)
diff --git a/src/script/api/script_vehicle.hpp b/src/script/api/script_vehicle.hpp
index d027e1243..58a0319d0 100644
--- a/src/script/api/script_vehicle.hpp
+++ b/src/script/api/script_vehicle.hpp
@@ -115,7 +115,7 @@ public:
* @param vehicle_id The vehicle to set the name for.
* @param name The name for the vehicle (can be either a raw string, or a ScriptText object).
* @pre IsValidVehicle(vehicle_id).
- * @pre name != NULL && len(name) != 0.
+ * @pre name != nullptr && len(name) != 0.
* @game @pre Valid ScriptCompanyMode active in scope.
* @exception ScriptError::ERR_NAME_IS_NOT_UNIQUE
* @return True if and only if the name was changed.
diff --git a/src/script/api/script_vehiclelist.cpp b/src/script/api/script_vehiclelist.cpp
index 625f0f8c4..48b290cae 100644
--- a/src/script/api/script_vehiclelist.cpp
+++ b/src/script/api/script_vehiclelist.cpp
@@ -101,7 +101,7 @@ ScriptVehicleList_SharedOrders::ScriptVehicleList_SharedOrders(VehicleID vehicle
{
if (!ScriptVehicle::IsValidVehicle(vehicle_id)) return;
- for (const Vehicle *v = Vehicle::Get(vehicle_id)->FirstShared(); v != NULL; v = v->NextShared()) {
+ for (const Vehicle *v = Vehicle::Get(vehicle_id)->FirstShared(); v != nullptr; v = v->NextShared()) {
this->AddItem(v->index);
}
}
diff --git a/src/script/api/script_waypoint.cpp b/src/script/api/script_waypoint.cpp
index 91733a38e..3d121a2dc 100644
--- a/src/script/api/script_waypoint.cpp
+++ b/src/script/api/script_waypoint.cpp
@@ -20,7 +20,7 @@
/* static */ bool ScriptWaypoint::IsValidWaypoint(StationID waypoint_id)
{
const Waypoint *wp = ::Waypoint::GetIfValid(waypoint_id);
- return wp != NULL && (wp->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY || wp->owner == OWNER_NONE);
+ return wp != nullptr && (wp->owner == ScriptObject::GetCompany() || ScriptObject::GetCompany() == OWNER_DEITY || wp->owner == OWNER_NONE);
}
/* static */ StationID ScriptWaypoint::GetWaypointID(TileIndex tile)
diff --git a/src/script/api/script_waypointlist.cpp b/src/script/api/script_waypointlist.cpp
index dd641a684..7e0b45a5b 100644
--- a/src/script/api/script_waypointlist.cpp
+++ b/src/script/api/script_waypointlist.cpp
@@ -32,7 +32,7 @@ ScriptWaypointList_Vehicle::ScriptWaypointList_Vehicle(VehicleID vehicle_id)
const Vehicle *v = ::Vehicle::Get(vehicle_id);
- for (const Order *o = v->GetFirstOrder(); o != NULL; o = o->next) {
+ for (const Order *o = v->GetFirstOrder(); o != nullptr; o = o->next) {
if (o->IsType(OT_GOTO_WAYPOINT)) this->AddItem(o->GetDestination());
}
}
diff --git a/src/script/api/script_window.cpp b/src/script/api/script_window.cpp
index 1252f0fc7..2766a0562 100644
--- a/src/script/api/script_window.cpp
+++ b/src/script/api/script_window.cpp
@@ -34,10 +34,10 @@
if (ScriptGame::IsMultiplayer()) return false;
if (number == NUMBER_ALL) {
- return (FindWindowByClass((::WindowClass)window) != NULL);
+ return (FindWindowByClass((::WindowClass)window) != nullptr);
}
- return FindWindowById((::WindowClass)window, number) != NULL;
+ return FindWindowById((::WindowClass)window, number) != nullptr;
}
/* static */ void ScriptWindow::Highlight(WindowClass window, uint32 number, uint8 widget, TextColour colour)
@@ -56,6 +56,6 @@
}
const NWidgetBase *wid = w->GetWidget<NWidgetBase>(widget);
- if (wid == NULL) return;
+ if (wid == nullptr) return;
w->SetWidgetHighlight(widget, (::TextColour)colour);
}
diff --git a/src/script/script_config.cpp b/src/script/script_config.cpp
index 3171e67d4..e9b0f69bc 100644
--- a/src/script/script_config.cpp
+++ b/src/script/script_config.cpp
@@ -21,17 +21,17 @@
void ScriptConfig::Change(const char *name, int version, bool force_exact_match, bool is_random)
{
free(this->name);
- this->name = (name == NULL) ? NULL : stredup(name);
- this->info = (name == NULL) ? NULL : this->FindInfo(this->name, version, force_exact_match);
- this->version = (info == NULL) ? -1 : info->GetVersion();
+ this->name = (name == nullptr) ? nullptr : stredup(name);
+ this->info = (name == nullptr) ? nullptr : this->FindInfo(this->name, version, force_exact_match);
+ this->version = (info == nullptr) ? -1 : info->GetVersion();
this->is_random = is_random;
- if (this->config_list != NULL) delete this->config_list;
- this->config_list = (info == NULL) ? NULL : new ScriptConfigItemList();
- if (this->config_list != NULL) this->PushExtraConfigList();
+ if (this->config_list != nullptr) delete this->config_list;
+ this->config_list = (info == nullptr) ? nullptr : new ScriptConfigItemList();
+ if (this->config_list != nullptr) this->PushExtraConfigList();
this->ClearConfigList();
- if (_game_mode == GM_NORMAL && this->info != NULL) {
+ if (_game_mode == GM_NORMAL && this->info != nullptr) {
/* If we're in an existing game and the Script is changed, set all settings
* for the Script that have the random flag to a random value. */
for (ScriptConfigItemList::const_iterator it = this->info->GetConfigList()->begin(); it != this->info->GetConfigList()->end(); it++) {
@@ -45,10 +45,10 @@ void ScriptConfig::Change(const char *name, int version, bool force_exact_match,
ScriptConfig::ScriptConfig(const ScriptConfig *config)
{
- this->name = (config->name == NULL) ? NULL : stredup(config->name);
+ this->name = (config->name == nullptr) ? nullptr : stredup(config->name);
this->info = config->info;
this->version = config->version;
- this->config_list = NULL;
+ this->config_list = nullptr;
this->is_random = config->is_random;
for (SettingValueList::const_iterator it = config->settings.begin(); it != config->settings.end(); it++) {
@@ -61,7 +61,7 @@ ScriptConfig::~ScriptConfig()
{
free(this->name);
this->ResetSettings();
- if (this->config_list != NULL) delete this->config_list;
+ if (this->config_list != nullptr) delete this->config_list;
}
ScriptInfo *ScriptConfig::GetInfo() const
@@ -71,8 +71,8 @@ ScriptInfo *ScriptConfig::GetInfo() const
const ScriptConfigItemList *ScriptConfig::GetConfigList()
{
- if (this->info != NULL) return this->info->GetConfigList();
- if (this->config_list == NULL) {
+ if (this->info != nullptr) return this->info->GetConfigList();
+ if (this->config_list == nullptr) {
this->config_list = new ScriptConfigItemList();
this->PushExtraConfigList();
}
@@ -106,10 +106,10 @@ int ScriptConfig::GetSetting(const char *name) const
void ScriptConfig::SetSetting(const char *name, int value)
{
/* You can only set Script specific settings if an Script is selected. */
- if (this->info == NULL) return;
+ if (this->info == nullptr) return;
const ScriptConfigItem *config_item = this->info->GetConfigItem(name);
- if (config_item == NULL) return;
+ if (config_item == nullptr) return;
value = Clamp(value, config_item->min_value, config_item->max_value);
@@ -140,7 +140,7 @@ void ScriptConfig::AddRandomDeviation()
bool ScriptConfig::HasScript() const
{
- return this->info != NULL;
+ return this->info != nullptr;
}
bool ScriptConfig::IsRandom() const
@@ -163,18 +163,18 @@ void ScriptConfig::StringToSettings(const char *value)
char *value_copy = stredup(value);
char *s = value_copy;
- while (s != NULL) {
+ while (s != nullptr) {
/* Analyze the string ('name=value,name=value\0') */
char *item_name = s;
s = strchr(s, '=');
- if (s == NULL) break;
+ if (s == nullptr) break;
if (*s == '\0') break;
*s = '\0';
s++;
char *item_value = s;
s = strchr(s, ',');
- if (s != NULL) {
+ if (s != nullptr) {
*s = '\0';
s++;
}
@@ -209,7 +209,7 @@ void ScriptConfig::SettingsToString(char *string, const char *last) const
const char *ScriptConfig::GetTextfile(TextfileType type, CompanyID slot) const
{
- if (slot == INVALID_COMPANY || this->GetInfo() == NULL) return NULL;
+ if (slot == INVALID_COMPANY || this->GetInfo() == nullptr) return nullptr;
return ::GetTextfile(type, (slot == OWNER_DEITY) ? GAME_DIR : AI_DIR, this->GetInfo()->GetMainScript());
}
diff --git a/src/script/script_config.hpp b/src/script/script_config.hpp
index 3dfd6bb0b..db04397a7 100644
--- a/src/script/script_config.hpp
+++ b/src/script/script_config.hpp
@@ -61,10 +61,10 @@ protected:
public:
ScriptConfig() :
- name(NULL),
+ name(nullptr),
version(-1),
- info(NULL),
- config_list(NULL),
+ info(nullptr),
+ config_list(nullptr),
is_random(false)
{}
@@ -178,7 +178,7 @@ public:
* Search a textfile file next to this script.
* @param type The type of the textfile to search for.
* @param slot #CompanyID to check status of.
- * @return The filename for the textfile, \c NULL otherwise.
+ * @return The filename for the textfile, \c nullptr otherwise.
*/
const char *GetTextfile(TextfileType type, CompanyID slot) const;
diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp
index 47ff2ee5f..5cab36d0b 100644
--- a/src/script/script_info.cpp
+++ b/src/script/script_info.cpp
@@ -25,7 +25,7 @@ ScriptInfo::~ScriptInfo()
for (ScriptConfigItemList::iterator it = this->config_list.begin(); it != this->config_list.end(); it++) {
free((*it).name);
free((*it).description);
- if (it->labels != NULL) {
+ if (it->labels != nullptr) {
for (auto &lbl_map : *(*it).labels) {
free(lbl_map.second);
}
@@ -85,7 +85,7 @@ bool ScriptInfo::CheckMethod(const char *name) const
/* Get location information of the scanner */
info->main_script = stredup(info->scanner->GetMainScript());
const char *tar_name = info->scanner->GetTarFile();
- if (tar_name != NULL) info->tar_file = stredup(tar_name);
+ if (tar_name != nullptr) info->tar_file = stredup(tar_name);
/* Cache the data the info file gives us. */
if (!info->engine->CallStringMethodStrdup(*info->SQ_instance, "GetAuthor", &info->author, MAX_GET_OPS)) return SQ_ERROR;
@@ -111,7 +111,7 @@ bool ScriptInfo::CheckMethod(const char *name) const
bool ScriptInfo::GetSettings()
{
- return this->engine->CallMethod(*this->SQ_instance, "GetSettings", NULL, MAX_GET_SETTING_OPS);
+ return this->engine->CallMethod(*this->SQ_instance, "GetSettings", nullptr, MAX_GET_SETTING_OPS);
}
SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm)
@@ -138,8 +138,8 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm)
/* Don't allow '=' and ',' in configure setting names, as we need those
* 2 chars to nicely store the settings as a string. */
- while ((s = strchr(name, '=')) != NULL) *s = '_';
- while ((s = strchr(name, ',')) != NULL) *s = '_';
+ while ((s = strchr(name, '=')) != nullptr) *s = '_';
+ while ((s = strchr(name, ',')) != nullptr) *s = '_';
config.name = name;
items |= 0x001;
} else if (strcmp(key, "description") == 0) {
@@ -233,18 +233,18 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
if (SQ_FAILED(sq_getstring(vm, -2, &setting_name))) return SQ_ERROR;
ValidateString(setting_name);
- ScriptConfigItem *config = NULL;
+ ScriptConfigItem *config = nullptr;
for (ScriptConfigItemList::iterator it = this->config_list.begin(); it != this->config_list.end(); it++) {
if (strcmp((*it).name, setting_name) == 0) config = &(*it);
}
- if (config == NULL) {
+ if (config == nullptr) {
char error[1024];
seprintf(error, lastof(error), "Trying to add labels for non-defined setting '%s'", setting_name);
this->engine->ThrowError(error);
return SQ_ERROR;
}
- if (config->labels != NULL) return SQ_ERROR;
+ if (config->labels != nullptr) return SQ_ERROR;
config->labels = new LabelMapping;
@@ -289,7 +289,7 @@ const ScriptConfigItem *ScriptInfo::GetConfigItem(const char *name) const
for (ScriptConfigItemList::const_iterator it = this->config_list.begin(); it != this->config_list.end(); it++) {
if (strcmp((*it).name, name) == 0) return &(*it);
}
- return NULL;
+ return nullptr;
}
int ScriptInfo::GetSettingDefaultValue(const char *name) const
diff --git a/src/script/script_info.hpp b/src/script/script_info.hpp
index ae341a7d8..6bcec878a 100644
--- a/src/script/script_info.hpp
+++ b/src/script/script_info.hpp
@@ -32,19 +32,19 @@ static const int MAX_GET_SETTING_OPS = 100000;
class ScriptInfo : public SimpleCountedObject {
public:
ScriptInfo() :
- engine(NULL),
- SQ_instance(NULL),
- main_script(NULL),
- tar_file(NULL),
- author(NULL),
- name(NULL),
- short_name(NULL),
- description(NULL),
- date(NULL),
- instance_name(NULL),
+ engine(nullptr),
+ SQ_instance(nullptr),
+ main_script(nullptr),
+ tar_file(nullptr),
+ author(nullptr),
+ name(nullptr),
+ short_name(nullptr),
+ description(nullptr),
+ date(nullptr),
+ instance_name(nullptr),
version(0),
- url(NULL),
- scanner(NULL)
+ url(nullptr),
+ scanner(nullptr)
{}
~ScriptInfo();
diff --git a/src/script/script_info_dummy.cpp b/src/script/script_info_dummy.cpp
index 53860386c..34e5541e2 100644
--- a/src/script/script_info_dummy.cpp
+++ b/src/script/script_info_dummy.cpp
@@ -86,11 +86,11 @@ void Script_CreateDummy(HSQUIRRELVM vm, StringID string, const char *type)
char *p = safe_error_message;
do {
newline = strchr(p, '\n');
- if (newline != NULL) *newline = '\0';
+ if (newline != nullptr) *newline = '\0';
dp += seprintf(dp, lastof(dummy_script), " %sLog.Error(\"%s\");\n", type, p);
p = newline + 1;
- } while (newline != NULL);
+ } while (newline != nullptr);
strecpy(dp, " }\n}\n", lastof(dummy_script));
diff --git a/src/script/script_instance.cpp b/src/script/script_instance.cpp
index 5df06ad89..336d3366a 100644
--- a/src/script/script_instance.cpp
+++ b/src/script/script_instance.cpp
@@ -34,8 +34,8 @@
ScriptStorage::~ScriptStorage()
{
/* Free our pointers */
- if (event_data != NULL) ScriptEventController::FreeEventPointer();
- if (log_data != NULL) ScriptLog::FreeLogPointer();
+ if (event_data != nullptr) ScriptEventController::FreeEventPointer();
+ if (log_data != nullptr) ScriptLog::FreeLogPointer();
}
/**
@@ -50,17 +50,17 @@ static void PrintFunc(bool error_msg, const SQChar *message)
}
ScriptInstance::ScriptInstance(const char *APIName) :
- engine(NULL),
- versionAPI(NULL),
- controller(NULL),
- storage(NULL),
- instance(NULL),
+ engine(nullptr),
+ versionAPI(nullptr),
+ controller(nullptr),
+ storage(nullptr),
+ instance(nullptr),
is_started(false),
is_dead(false),
is_save_data_on_stack(false),
suspend(0),
is_paused(false),
- callback(NULL)
+ callback(nullptr)
{
this->storage = new ScriptStorage();
this->engine = new Squirrel(APIName);
@@ -135,8 +135,8 @@ ScriptInstance::~ScriptInstance()
{
ScriptObject::ActiveInstance active(this);
- if (instance != NULL) this->engine->ReleaseObject(this->instance);
- if (engine != NULL) delete this->engine;
+ if (instance != nullptr) this->engine->ReleaseObject(this->instance);
+ if (engine != nullptr) delete this->engine;
delete this->storage;
delete this->controller;
free(this->instance);
@@ -153,10 +153,10 @@ void ScriptInstance::Died()
DEBUG(script, 0, "The script died unexpectedly.");
this->is_dead = true;
- if (this->instance != NULL) this->engine->ReleaseObject(this->instance);
+ if (this->instance != nullptr) this->engine->ReleaseObject(this->instance);
delete this->engine;
- this->instance = NULL;
- this->engine = NULL;
+ this->instance = nullptr;
+ this->engine = nullptr;
}
void ScriptInstance::GameLoop()
@@ -179,7 +179,7 @@ void ScriptInstance::GameLoop()
_current_company = ScriptObject::GetCompany();
/* If there is a callback to call, call that first */
- if (this->callback != NULL) {
+ if (this->callback != nullptr) {
if (this->is_save_data_on_stack) {
sq_poptop(this->engine->GetVM());
this->is_save_data_on_stack = false;
@@ -195,7 +195,7 @@ void ScriptInstance::GameLoop()
}
this->suspend = 0;
- this->callback = NULL;
+ this->callback = nullptr;
if (!this->is_started) {
try {
@@ -351,7 +351,7 @@ static const SaveLoad _script_byte[] = {
case OT_INTEGER: {
if (!test) {
_script_sl_byte = SQSL_INT;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
SQInteger res;
sq_getinteger(vm, index, &res);
@@ -365,7 +365,7 @@ static const SaveLoad _script_byte[] = {
case OT_STRING: {
if (!test) {
_script_sl_byte = SQSL_STRING;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
const SQChar *buf;
sq_getstring(vm, index, &buf);
@@ -376,7 +376,7 @@ static const SaveLoad _script_byte[] = {
}
if (!test) {
_script_sl_byte = (byte)len;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
SlArray(const_cast<char *>(buf), len, SLE_CHAR);
}
return true;
@@ -385,7 +385,7 @@ static const SaveLoad _script_byte[] = {
case OT_ARRAY: {
if (!test) {
_script_sl_byte = SQSL_ARRAY;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
sq_pushnull(vm);
while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
@@ -400,7 +400,7 @@ static const SaveLoad _script_byte[] = {
sq_pop(vm, 1);
if (!test) {
_script_sl_byte = SQSL_ARRAY_TABLE_END;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
return true;
}
@@ -408,7 +408,7 @@ static const SaveLoad _script_byte[] = {
case OT_TABLE: {
if (!test) {
_script_sl_byte = SQSL_TABLE;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
sq_pushnull(vm);
while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
@@ -423,7 +423,7 @@ static const SaveLoad _script_byte[] = {
sq_pop(vm, 1);
if (!test) {
_script_sl_byte = SQSL_ARRAY_TABLE_END;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
return true;
}
@@ -431,13 +431,13 @@ static const SaveLoad _script_byte[] = {
case OT_BOOL: {
if (!test) {
_script_sl_byte = SQSL_BOOL;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
SQBool res;
sq_getbool(vm, index, &res);
if (!test) {
_script_sl_byte = res ? 1 : 0;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
return true;
}
@@ -445,7 +445,7 @@ static const SaveLoad _script_byte[] = {
case OT_NULL: {
if (!test) {
_script_sl_byte = SQSL_NULL;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
return true;
}
@@ -459,7 +459,7 @@ static const SaveLoad _script_byte[] = {
/* static */ void ScriptInstance::SaveEmpty()
{
_script_sl_byte = 0;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
void ScriptInstance::Save()
@@ -467,7 +467,7 @@ void ScriptInstance::Save()
ScriptObject::ActiveInstance active(this);
/* Don't save data if the script didn't start yet or if it crashed. */
- if (this->engine == NULL || this->engine->HasScriptCrashed()) {
+ if (this->engine == nullptr || this->engine->HasScriptCrashed()) {
SaveEmpty();
return;
}
@@ -475,7 +475,7 @@ void ScriptInstance::Save()
HSQUIRRELVM vm = this->engine->GetVM();
if (this->is_save_data_on_stack) {
_script_sl_byte = 1;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
/* Save the data that was just loaded. */
SaveObject(vm, -1, SQUIRREL_MAX_DEPTH, false);
} else if (!this->is_started) {
@@ -518,7 +518,7 @@ void ScriptInstance::Save()
sq_pushobject(vm, savedata);
if (SaveObject(vm, -1, SQUIRREL_MAX_DEPTH, true)) {
_script_sl_byte = 1;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
SaveObject(vm, -1, SQUIRREL_MAX_DEPTH, false);
this->is_save_data_on_stack = true;
} else {
@@ -528,7 +528,7 @@ void ScriptInstance::Save()
} else {
ScriptLog::Warning("Save function is not implemented");
_script_sl_byte = 0;
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
}
}
@@ -553,50 +553,50 @@ bool ScriptInstance::IsPaused()
/* static */ bool ScriptInstance::LoadObjects(HSQUIRRELVM vm)
{
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
switch (_script_sl_byte) {
case SQSL_INT: {
int value;
SlArray(&value, 1, SLE_INT32);
- if (vm != NULL) sq_pushinteger(vm, (SQInteger)value);
+ if (vm != nullptr) sq_pushinteger(vm, (SQInteger)value);
return true;
}
case SQSL_STRING: {
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
static char buf[256];
SlArray(buf, _script_sl_byte, SLE_CHAR);
- if (vm != NULL) sq_pushstring(vm, buf, -1);
+ if (vm != nullptr) sq_pushstring(vm, buf, -1);
return true;
}
case SQSL_ARRAY: {
- if (vm != NULL) sq_newarray(vm, 0);
+ if (vm != nullptr) sq_newarray(vm, 0);
while (LoadObjects(vm)) {
- if (vm != NULL) sq_arrayappend(vm, -2);
+ if (vm != nullptr) sq_arrayappend(vm, -2);
/* The value is popped from the stack by squirrel. */
}
return true;
}
case SQSL_TABLE: {
- if (vm != NULL) sq_newtable(vm);
+ if (vm != nullptr) sq_newtable(vm);
while (LoadObjects(vm)) {
LoadObjects(vm);
- if (vm != NULL) sq_rawset(vm, -3);
+ if (vm != nullptr) sq_rawset(vm, -3);
/* The key (-2) and value (-1) are popped from the stack by squirrel. */
}
return true;
}
case SQSL_BOOL: {
- SlObject(NULL, _script_byte);
- if (vm != NULL) sq_pushbool(vm, (SQBool)(_script_sl_byte != 0));
+ SlObject(nullptr, _script_byte);
+ if (vm != nullptr) sq_pushbool(vm, (SQBool)(_script_sl_byte != 0));
return true;
}
case SQSL_NULL: {
- if (vm != NULL) sq_pushnull(vm);
+ if (vm != nullptr) sq_pushnull(vm);
return true;
}
@@ -610,24 +610,24 @@ bool ScriptInstance::IsPaused()
/* static */ void ScriptInstance::LoadEmpty()
{
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
/* Check if there was anything saved at all. */
if (_script_sl_byte == 0) return;
- LoadObjects(NULL);
+ LoadObjects(nullptr);
}
void ScriptInstance::Load(int version)
{
ScriptObject::ActiveInstance active(this);
- if (this->engine == NULL || version == -1) {
+ if (this->engine == nullptr || version == -1) {
LoadEmpty();
return;
}
HSQUIRRELVM vm = this->engine->GetVM();
- SlObject(NULL, _script_byte);
+ SlObject(nullptr, _script_byte);
/* Check if there was anything saved at all. */
if (_script_sl_byte == 0) return;
diff --git a/src/script/script_instance.hpp b/src/script/script_instance.hpp
index e6f3c64b2..56e830367 100644
--- a/src/script/script_instance.hpp
+++ b/src/script/script_instance.hpp
@@ -52,7 +52,7 @@ public:
* Find a library.
* @param library The library name to find.
* @param version The version the library should have.
- * @return The library if found, NULL otherwise.
+ * @return The library if found, nullptr otherwise.
*/
virtual class ScriptInfo *FindLibrary(const char *library, int version) = 0;
diff --git a/src/script/script_scanner.cpp b/src/script/script_scanner.cpp
index 168a852a5..2812ef65e 100644
--- a/src/script/script_scanner.cpp
+++ b/src/script/script_scanner.cpp
@@ -28,19 +28,19 @@ bool ScriptScanner::AddFile(const char *filename, size_t basepath_length, const
{
free(this->main_script);
this->main_script = stredup(filename);
- if (this->main_script == NULL) return false;
+ if (this->main_script == nullptr) return false;
free(this->tar_file);
- if (tar_filename != NULL) {
+ if (tar_filename != nullptr) {
this->tar_file = stredup(tar_filename);
- if (this->tar_file == NULL) return false;
+ if (this->tar_file == nullptr) return false;
} else {
- this->tar_file = NULL;
+ this->tar_file = nullptr;
}
const char *end = this->main_script + strlen(this->main_script) + 1;
char *p = strrchr(this->main_script, PATHSEPCHAR);
- if (p == NULL) {
+ if (p == nullptr) {
p = this->main_script;
} else {
/* Skip over the path separator character. We don't need that. */
@@ -58,9 +58,9 @@ bool ScriptScanner::AddFile(const char *filename, size_t basepath_length, const
}
ScriptScanner::ScriptScanner() :
- engine(NULL),
- main_script(NULL),
- tar_file(NULL)
+ engine(nullptr),
+ main_script(nullptr),
+ tar_file(nullptr)
{
}
@@ -203,7 +203,7 @@ struct ScriptFileChecksumCreator : FileScanner {
/* Open the file ... */
FILE *f = FioFOpenFile(filename, "rb", this->dir, &size);
- if (f == NULL) return false;
+ if (f == nullptr) return false;
/* ... calculate md5sum... */
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
@@ -241,7 +241,7 @@ static bool IsSameScript(const ContentInfo *ci, bool md5sum, ScriptInfo *info, S
ScriptFileChecksumCreator checksum(dir);
const char *tar_filename = info->GetTarFile();
TarList::iterator iter;
- if (tar_filename != NULL && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) {
+ if (tar_filename != nullptr && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) {
/* The main script is in a tar file, so find all files that
* are in the same tar and add them to the MD5 checksumming. */
TarFileList::iterator tar;
@@ -251,7 +251,7 @@ static bool IsSameScript(const ContentInfo *ci, bool md5sum, ScriptInfo *info, S
/* Check the extension. */
const char *ext = strrchr(tar->first.c_str(), '.');
- if (ext == NULL || strcasecmp(ext, ".nut") != 0) continue;
+ if (ext == nullptr || strcasecmp(ext, ".nut") != 0) continue;
checksum.AddFile(tar->first.c_str(), 0, tar_filename);
}
@@ -281,5 +281,5 @@ const char *ScriptScanner::FindMainScript(const ContentInfo *ci, bool md5sum)
for (ScriptInfoList::iterator it = this->info_list.begin(); it != this->info_list.end(); it++) {
if (IsSameScript(ci, md5sum, (*it).second, this->GetDirectory())) return (*it).second->GetMainScript();
}
- return NULL;
+ return nullptr;
}
diff --git a/src/script/script_scanner.hpp b/src/script/script_scanner.hpp
index 7fecf6eb2..3627d251b 100644
--- a/src/script/script_scanner.hpp
+++ b/src/script/script_scanner.hpp
@@ -73,7 +73,7 @@ public:
* Find a script of a #ContentInfo
* @param ci The information to compare to.
* @param md5sum Whether to check the MD5 checksum.
- * @return A filename of a file of the content, else \c NULL.
+ * @return A filename of a file of the content, else \c nullptr.
*/
const char *FindMainScript(const ContentInfo *ci, bool md5sum);
diff --git a/src/script/script_storage.hpp b/src/script/script_storage.hpp
index 8fe1e1732..ef7d81ed7 100644
--- a/src/script/script_storage.hpp
+++ b/src/script/script_storage.hpp
@@ -63,8 +63,8 @@ private:
public:
ScriptStorage() :
- mode (NULL),
- mode_instance (NULL),
+ mode (nullptr),
+ mode_instance (nullptr),
root_company (INVALID_OWNER),
company (INVALID_OWNER),
delay (1),
@@ -82,8 +82,8 @@ public:
/* calback_value (can't be set) */
road_type (INVALID_ROADTYPE),
rail_type (INVALID_RAILTYPE),
- event_data (NULL),
- log_data (NULL)
+ event_data (nullptr),
+ log_data (nullptr)
{ }
~ScriptStorage();
diff --git a/src/script/squirrel.cpp b/src/script/squirrel.cpp
index 23163f6b3..fd0478bb5 100644
--- a/src/script/squirrel.cpp
+++ b/src/script/squirrel.cpp
@@ -31,7 +31,7 @@ void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *so
Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
engine->crashed = true;
SQPrintFunc *func = engine->print_func;
- if (func == NULL) {
+ if (func == nullptr) {
DEBUG(misc, 0, "[Squirrel] Compile error: %s", buf);
} else {
(*func)(true, buf);
@@ -49,7 +49,7 @@ void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
/* Check if we have a custom print function */
SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
- if (func == NULL) {
+ if (func == nullptr) {
fprintf(stderr, "%s", buf);
} else {
(*func)(true, buf);
@@ -67,7 +67,7 @@ void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error)
seprintf(buf, lastof(buf), "Your script made an error: %s\n", error);
Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
SQPrintFunc *func = engine->print_func;
- if (func == NULL) {
+ if (func == nullptr) {
fprintf(stderr, "%s", buf);
} else {
(*func)(true, buf);
@@ -106,7 +106,7 @@ void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
/* Check if we have a custom print function */
SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
- if (func == NULL) {
+ if (func == nullptr) {
printf("%s", buf);
} else {
(*func)(false, buf);
@@ -234,8 +234,8 @@ bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT
}
/* Call the method */
sq_pushobject(this->vm, instance);
- if (SQ_FAILED(sq_call(this->vm, 1, ret == NULL ? SQFalse : SQTrue, SQTrue, suspend))) return false;
- if (ret != NULL) sq_getstackobj(vm, -1, ret);
+ if (SQ_FAILED(sq_call(this->vm, 1, ret == nullptr ? SQFalse : SQTrue, SQTrue, suspend))) return false;
+ if (ret != nullptr) sq_getstackobj(vm, -1, ret);
/* Reset the top, but don't do so for the script main function, as we need
* a correct stack when resuming. */
if (suspend == -1 || !this->IsSuspended()) sq_settop(this->vm, top);
@@ -305,7 +305,7 @@ bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool
return false;
}
- if (instance != NULL) {
+ if (instance != nullptr) {
/* Find our instance */
sq_getstackobj(vm, -1, instance);
/* Add a reference to it, so it survives for ever */
@@ -316,16 +316,16 @@ bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool
/* Store it in the class */
sq_setinstanceup(vm, -1, real_instance);
- if (release_hook != NULL) sq_setreleasehook(vm, -1, release_hook);
+ if (release_hook != nullptr) sq_setreleasehook(vm, -1, release_hook);
- if (instance != NULL) sq_settop(vm, oldtop);
+ if (instance != nullptr) sq_settop(vm, oldtop);
return true;
}
bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
{
- return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, NULL);
+ return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, nullptr);
}
Squirrel::Squirrel(const char *APIName) :
@@ -336,8 +336,8 @@ Squirrel::Squirrel(const char *APIName) :
void Squirrel::Initialize()
{
- this->global_pointer = NULL;
- this->print_func = NULL;
+ this->global_pointer = nullptr;
+ this->print_func = nullptr;
this->crashed = false;
this->overdrawn_ops = 0;
this->vm = sq_open(1024);
@@ -436,15 +436,15 @@ SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printer
size_t size;
if (strncmp(this->GetAPIName(), "AI", 2) == 0) {
file = FioFOpenFile(filename, "rb", AI_DIR, &size);
- if (file == NULL) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
+ if (file == nullptr) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
} else if (strncmp(this->GetAPIName(), "GS", 2) == 0) {
file = FioFOpenFile(filename, "rb", GAME_DIR, &size);
- if (file == NULL) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
+ if (file == nullptr) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
} else {
NOT_REACHED();
}
- if (file == NULL) {
+ if (file == nullptr) {
return sq_throwerror(vm, "cannot open the file");
}
unsigned short bom = 0;
diff --git a/src/script/squirrel.hpp b/src/script/squirrel.hpp
index 9e1d113a8..bec41f575 100644
--- a/src/script/squirrel.hpp
+++ b/src/script/squirrel.hpp
@@ -26,7 +26,7 @@ private:
HSQUIRRELVM vm; ///< The VirtualMachine instance for squirrel
void *global_pointer; ///< Can be set by who ever initializes Squirrel
- SQPrintFunc *print_func; ///< Points to either NULL, or a custom print handler
+ SQPrintFunc *print_func; ///< Points to either nullptr, or a custom print handler
bool crashed; ///< True if the squirrel script made an error.
int overdrawn_ops; ///< The amount of operations we have overdrawn.
const char *APIName; ///< Name of the API used for this squirrel.
@@ -93,7 +93,7 @@ public:
* Adds a function to the stack. Depending on the current state this means
* either a method or a global function.
*/
- void AddMethod(const char *method_name, SQFUNCTION proc, uint nparam = 0, const char *params = NULL, void *userdata = NULL, int size = 0);
+ void AddMethod(const char *method_name, SQFUNCTION proc, uint nparam = 0, const char *params = nullptr, void *userdata = nullptr, int size = 0);
/**
* Adds a const to the stack. Depending on the current state this means
@@ -155,7 +155,7 @@ public:
* @return False if the script crashed or returned a wrong type.
*/
bool CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend);
- bool CallMethod(HSQOBJECT instance, const char *method_name, int suspend) { return this->CallMethod(instance, method_name, NULL, suspend); }
+ bool CallMethod(HSQOBJECT instance, const char *method_name, int suspend) { return this->CallMethod(instance, method_name, nullptr, suspend); }
bool CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend);
bool CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend);
bool CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend);
diff --git a/src/script/squirrel_class.hpp b/src/script/squirrel_class.hpp
index ce63e3b03..8ec3f9dc7 100644
--- a/src/script/squirrel_class.hpp
+++ b/src/script/squirrel_class.hpp
@@ -35,7 +35,7 @@ public:
void DefSQMethod(Squirrel *engine, Func function_proc, const char *function_name)
{
using namespace SQConvert;
- engine->AddMethod(function_name, DefSQNonStaticCallback<CL, Func, ST>, 0, NULL, &function_proc, sizeof(function_proc));
+ engine->AddMethod(function_name, DefSQNonStaticCallback<CL, Func, ST>, 0, nullptr, &function_proc, sizeof(function_proc));
}
/**
@@ -45,7 +45,7 @@ public:
void DefSQAdvancedMethod(Squirrel *engine, Func function_proc, const char *function_name)
{
using namespace SQConvert;
- engine->AddMethod(function_name, DefSQAdvancedNonStaticCallback<CL, Func, ST>, 0, NULL, &function_proc, sizeof(function_proc));
+ engine->AddMethod(function_name, DefSQAdvancedNonStaticCallback<CL, Func, ST>, 0, nullptr, &function_proc, sizeof(function_proc));
}
/**
@@ -68,7 +68,7 @@ public:
void DefSQStaticMethod(Squirrel *engine, Func function_proc, const char *function_name)
{
using namespace SQConvert;
- engine->AddMethod(function_name, DefSQStaticCallback<CL, Func>, 0, NULL, &function_proc, sizeof(function_proc));
+ engine->AddMethod(function_name, DefSQStaticCallback<CL, Func>, 0, nullptr, &function_proc, sizeof(function_proc));
}
/**
@@ -78,7 +78,7 @@ public:
void DefSQAdvancedStaticMethod(Squirrel *engine, Func function_proc, const char *function_name)
{
using namespace SQConvert;
- engine->AddMethod(function_name, DefSQAdvancedStaticCallback<CL, Func>, 0, NULL, &function_proc, sizeof(function_proc));
+ engine->AddMethod(function_name, DefSQAdvancedStaticCallback<CL, Func>, 0, nullptr, &function_proc, sizeof(function_proc));
}
/**
@@ -120,7 +120,7 @@ public:
void AddSQAdvancedConstructor(Squirrel *engine)
{
using namespace SQConvert;
- engine->AddMethod("constructor", DefSQAdvancedConstructorCallback<CL>, 0, NULL);
+ engine->AddMethod("constructor", DefSQAdvancedConstructorCallback<CL>, 0, nullptr);
}
void PostRegister(Squirrel *engine)
diff --git a/src/script/squirrel_helper.hpp b/src/script/squirrel_helper.hpp
index 10f04f945..e266148c5 100644
--- a/src/script/squirrel_helper.hpp
+++ b/src/script/squirrel_helper.hpp
@@ -88,8 +88,8 @@ namespace SQConvert {
template <> inline int Return<int64> (HSQUIRRELVM vm, int64 res) { sq_pushinteger(vm, res); return 1; }
template <> inline int Return<Money> (HSQUIRRELVM vm, Money res) { sq_pushinteger(vm, res); return 1; }
template <> inline int Return<bool> (HSQUIRRELVM vm, bool res) { sq_pushbool (vm, res); return 1; }
- template <> inline int Return<char *> (HSQUIRRELVM vm, char *res) { if (res == NULL) sq_pushnull(vm); else { sq_pushstring(vm, res, -1); free(res); } return 1; }
- template <> inline int Return<const char *>(HSQUIRRELVM vm, const char *res) { if (res == NULL) sq_pushnull(vm); else { sq_pushstring(vm, res, -1); } return 1; }
+ template <> inline int Return<char *> (HSQUIRRELVM vm, char *res) { if (res == nullptr) sq_pushnull(vm); else { sq_pushstring(vm, res, -1); free(res); } return 1; }
+ template <> inline int Return<const char *>(HSQUIRRELVM vm, const char *res) { if (res == nullptr) sq_pushnull(vm); else { sq_pushstring(vm, res, -1); } return 1; }
template <> inline int Return<void *> (HSQUIRRELVM vm, void *res) { sq_pushuserpointer(vm, res); return 1; }
template <> inline int Return<HSQOBJECT> (HSQUIRRELVM vm, HSQOBJECT res) { sq_pushobject(vm, res); return 1; }
@@ -739,8 +739,8 @@ namespace SQConvert {
{
/* Find the amount of params we got */
int nparam = sq_gettop(vm);
- SQUserPointer ptr = NULL;
- SQUserPointer real_instance = NULL;
+ SQUserPointer ptr = nullptr;
+ SQUserPointer real_instance = nullptr;
HSQOBJECT instance;
/* Get the 'SQ' instance of this class */
@@ -759,7 +759,7 @@ namespace SQConvert {
sq_getinstanceup(vm, 1, &real_instance, 0);
/* Get the real function pointer */
sq_getuserdata(vm, nparam, &ptr, 0);
- if (real_instance == NULL) return sq_throwerror(vm, "couldn't detect real instance of class for non-static call");
+ if (real_instance == nullptr) return sq_throwerror(vm, "couldn't detect real instance of class for non-static call");
/* Remove the userdata from the stack */
sq_pop(vm, 1);
@@ -781,8 +781,8 @@ namespace SQConvert {
{
/* Find the amount of params we got */
int nparam = sq_gettop(vm);
- SQUserPointer ptr = NULL;
- SQUserPointer real_instance = NULL;
+ SQUserPointer ptr = nullptr;
+ SQUserPointer real_instance = nullptr;
HSQOBJECT instance;
/* Get the 'SQ' instance of this class */
@@ -801,7 +801,7 @@ namespace SQConvert {
sq_getinstanceup(vm, 1, &real_instance, 0);
/* Get the real function pointer */
sq_getuserdata(vm, nparam, &ptr, 0);
- if (real_instance == NULL) return sq_throwerror(vm, "couldn't detect real instance of class for non-static call");
+ if (real_instance == nullptr) return sq_throwerror(vm, "couldn't detect real instance of class for non-static call");
/* Remove the userdata from the stack */
sq_pop(vm, 1);
@@ -819,14 +819,14 @@ namespace SQConvert {
{
/* Find the amount of params we got */
int nparam = sq_gettop(vm);
- SQUserPointer ptr = NULL;
+ SQUserPointer ptr = nullptr;
/* Get the real function pointer */
sq_getuserdata(vm, nparam, &ptr, 0);
try {
/* Delegate it to a template that can handle this specific function */
- return HelperT<Tmethod>::SQCall((Tcls *)NULL, *(Tmethod *)ptr, vm);
+ return HelperT<Tmethod>::SQCall((Tcls *)nullptr, *(Tmethod *)ptr, vm);
} catch (SQInteger e) {
return e;
}
@@ -843,7 +843,7 @@ namespace SQConvert {
{
/* Find the amount of params we got */
int nparam = sq_gettop(vm);
- SQUserPointer ptr = NULL;
+ SQUserPointer ptr = nullptr;
/* Get the real function pointer */
sq_getuserdata(vm, nparam, &ptr, 0);
@@ -862,7 +862,7 @@ namespace SQConvert {
static SQInteger DefSQDestructorCallback(SQUserPointer p, SQInteger size)
{
/* Remove the real instance too */
- if (p != NULL) ((Tcls *)p)->Release();
+ if (p != nullptr) ((Tcls *)p)->Release();
return 0;
}
@@ -876,7 +876,7 @@ namespace SQConvert {
{
try {
/* Create the real instance */
- Tcls *instance = HelperT<Tmethod>::SQConstruct((Tcls *)NULL, (Tmethod)NULL, vm);
+ Tcls *instance = HelperT<Tmethod>::SQConstruct((Tcls *)nullptr, (Tmethod)nullptr, vm);
sq_setinstanceup(vm, -Tnparam, instance);
sq_setreleasehook(vm, -Tnparam, DefSQDestructorCallback<Tcls>);
instance->AddRef();
diff --git a/src/script/squirrel_std.cpp b/src/script/squirrel_std.cpp
index 96f087a2a..715b98934 100644
--- a/src/script/squirrel_std.cpp
+++ b/src/script/squirrel_std.cpp
@@ -51,7 +51,7 @@ SQInteger SquirrelStd::require(HSQUIRRELVM vm)
/* Get the script-name of the current file, so we can work relative from it */
SQStackInfos si;
sq_stackinfos(vm, 1, &si);
- if (si.source == NULL) {
+ if (si.source == nullptr) {
DEBUG(misc, 0, "[squirrel] Couldn't detect the script-name of the 'require'-caller; this should never happen!");
return SQ_ERROR;
}
@@ -60,7 +60,7 @@ SQInteger SquirrelStd::require(HSQUIRRELVM vm)
strecpy(path, si.source, lastof(path));
/* Keep the dir, remove the rest */
SQChar *s = strrchr(path, PATHSEPCHAR);
- if (s != NULL) {
+ if (s != nullptr) {
/* Keep the PATHSEPCHAR there, remove the rest */
s++;
*s = '\0';
diff --git a/src/settings.cpp b/src/settings.cpp
index 749050132..b111f8728 100644
--- a/src/settings.cpp
+++ b/src/settings.cpp
@@ -96,7 +96,7 @@ static const char * const _list_group_names[] = {
"newgrf",
"servers",
"server_bind_addresses",
- NULL
+ nullptr
};
/**
@@ -114,7 +114,7 @@ static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen =
if (onelen == 0) onelen = strlen(one);
/* check if it's an integer */
- if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
+ if (*one >= '0' && *one <= '9') return strtoul(one, nullptr, 0);
idx = 0;
for (;;) {
@@ -218,7 +218,7 @@ static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
int items[64];
int i, nitems;
- if (str == NULL) {
+ if (str == nullptr) {
memset(items, 0, sizeof(items));
nitems = nelems;
} else {
@@ -348,7 +348,7 @@ static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32
*/
static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
{
- const char *str = orig_str == NULL ? "" : orig_str;
+ const char *str = orig_str == nullptr ? "" : orig_str;
switch (desc->cmd) {
case SDT_NUMX: {
@@ -373,7 +373,7 @@ static const void *StringToVal(const SettingDescBase *desc, const char *orig_str
size_t r = LookupOneOfMany(desc->many, str);
/* if the first attempt of conversion from string to the appropriate value fails,
* look if we have defined a converter from old value to new value. */
- if (r == (size_t)-1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
+ if (r == (size_t)-1 && desc->proc_cnvt != nullptr) r = desc->proc_cnvt(str);
if (r != (size_t)-1) return (void*)r; // and here goes converted value
ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
@@ -409,7 +409,7 @@ static const void *StringToVal(const SettingDescBase *desc, const char *orig_str
default: break;
}
- return NULL;
+ return nullptr;
}
/**
@@ -508,7 +508,7 @@ static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grp
/* For settings.xx.yy load the settings from [xx] yy = ? */
s = strchr(sdb->name, '.');
- if (s != NULL) {
+ if (s != nullptr) {
group = ini->GetGroup(sdb->name, s - sdb->name);
s++;
} else {
@@ -517,19 +517,19 @@ static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grp
}
item = group->GetItem(s, false);
- if (item == NULL && group != group_def) {
+ if (item == nullptr && group != group_def) {
/* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
* did not exist (e.g. loading old config files with a [settings] section */
item = group_def->GetItem(s, false);
}
- if (item == NULL) {
+ if (item == nullptr) {
/* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
* did not exist (e.g. loading old config files with a [yapf] section */
const char *sc = strchr(s, '.');
- if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
+ if (sc != nullptr) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
}
- p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
+ p = (item == nullptr) ? sdb->def : StringToVal(sdb, item->value);
ptr = GetVariableAddress(object, sld);
switch (sdb->cmd) {
@@ -544,16 +544,16 @@ static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grp
switch (GetVarMemType(sld->conv)) {
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
- if (p != NULL) strecpy((char*)ptr, (const char*)p, (char*)ptr + sld->length - 1);
+ if (p != nullptr) strecpy((char*)ptr, (const char*)p, (char*)ptr + sld->length - 1);
break;
case SLE_VAR_STR:
case SLE_VAR_STRQ:
free(*(char**)ptr);
- *(char**)ptr = p == NULL ? NULL : stredup((const char*)p);
+ *(char**)ptr = p == nullptr ? nullptr : stredup((const char*)p);
break;
- case SLE_VAR_CHAR: if (p != NULL) *(char *)ptr = *(const char *)p; break;
+ case SLE_VAR_CHAR: if (p != nullptr) *(char *)ptr = *(const char *)p; break;
default: NOT_REACHED();
}
@@ -567,7 +567,7 @@ static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grp
/* Use default */
LoadIntList((const char*)sdb->def, ptr, sld->length, GetVarMemType(sld->conv));
- } else if (sd->desc.proc_cnvt != NULL) {
+ } else if (sd->desc.proc_cnvt != nullptr) {
sd->desc.proc_cnvt((const char*)p);
}
break;
@@ -591,7 +591,7 @@ static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grp
*/
static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
{
- IniGroup *group_def = NULL, *group;
+ IniGroup *group_def = nullptr, *group;
IniItem *item;
char buf[512];
const char *s;
@@ -608,11 +608,11 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
/* XXX - wtf is this?? (group override?) */
s = strchr(sdb->name, '.');
- if (s != NULL) {
+ if (s != nullptr) {
group = ini->GetGroup(sdb->name, s - sdb->name);
s++;
} else {
- if (group_def == NULL) group_def = ini->GetGroup(grpname);
+ if (group_def == nullptr) group_def = ini->GetGroup(grpname);
s = sdb->name;
group = group_def;
}
@@ -620,7 +620,7 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
item = group->GetItem(s, true);
ptr = GetVariableAddress(object, sld);
- if (item->value != NULL) {
+ if (item->value != nullptr) {
/* check if the value is the same as the old value */
const void *p = StringToVal(sdb, item->value);
@@ -633,7 +633,7 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
case SDT_MANYOFMANY:
switch (GetVarMemType(sld->conv)) {
case SLE_VAR_BL:
- if (*(bool*)ptr == (p != NULL)) continue;
+ if (*(bool*)ptr == (p != nullptr)) continue;
break;
case SLE_VAR_I8:
@@ -684,7 +684,7 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
case SLE_VAR_STR: strecpy(buf, *(char**)ptr, lastof(buf)); break;
case SLE_VAR_STRQ:
- if (*(char**)ptr == NULL) {
+ if (*(char**)ptr == nullptr) {
buf[0] = '\0';
} else {
seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
@@ -711,7 +711,7 @@ static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grp
/**
* Loads all items from a 'grpname' section into a list
- * The list parameter can be a NULL pointer, in this case nothing will be
+ * The list parameter can be a nullptr pointer, in this case nothing will be
* saved and a callback function should be defined that will take over the
* list-handling and store the data itself somewhere.
* @param ini IniFile handle to the ini file with the source data
@@ -722,18 +722,18 @@ static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList &li
{
IniGroup *group = ini->GetGroup(grpname);
- if (group == NULL) return;
+ if (group == nullptr) return;
list.clear();
- for (const IniItem *item = group->item; item != NULL; item = item->next) {
- if (item->name != NULL) list.emplace_back(item->name);
+ for (const IniItem *item = group->item; item != nullptr; item = item->next) {
+ if (item->name != nullptr) list.emplace_back(item->name);
}
}
/**
* Saves all items from a list into the 'grpname' section
- * The list parameter can be a NULL pointer, in this case a callback function
+ * The list parameter can be a nullptr pointer, in this case a callback function
* should be defined that will provide the source data to be saved.
* @param ini IniFile handle to the ini file where the destination data is saved
* @param grpname character string identifying the section-header of the ini file
@@ -744,7 +744,7 @@ static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList &li
{
IniGroup *group = ini->GetGroup(grpname);
- if (group == NULL) return;
+ if (group == nullptr) return;
group->Clear();
for (const auto &iter : list) {
@@ -805,7 +805,7 @@ SettingType SettingDesc::GetType() const
/** Reposition the main toolbar as the setting changed. */
static bool v_PositionMainToolbar(int32 p1)
{
- if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
+ if (_game_mode != GM_MENU) PositionMainToolbar(nullptr);
return true;
}
@@ -813,9 +813,9 @@ static bool v_PositionMainToolbar(int32 p1)
static bool v_PositionStatusbar(int32 p1)
{
if (_game_mode != GM_MENU) {
- PositionStatusbar(NULL);
- PositionNewsMessage(NULL);
- PositionNetworkChatWindow(NULL);
+ PositionStatusbar(nullptr);
+ PositionNewsMessage(nullptr);
+ PositionNetworkChatWindow(nullptr);
}
return true;
}
@@ -1416,14 +1416,14 @@ static void AILoadConfig(IniFile *ini, const char *grpname)
/* Clean any configured AI */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
- AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(NULL);
+ AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(nullptr);
}
/* If no group exists, return */
- if (group == NULL) return;
+ if (group == nullptr) return;
CompanyID c = COMPANY_FIRST;
- for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
+ for (item = group->item; c < MAX_COMPANIES && item != nullptr; c++, item = item->next) {
AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
config->Change(item->name);
@@ -1433,7 +1433,7 @@ static void AILoadConfig(IniFile *ini, const char *grpname)
continue;
}
}
- if (item->value != NULL) config->StringToSettings(item->value);
+ if (item->value != nullptr) config->StringToSettings(item->value);
}
}
@@ -1443,13 +1443,13 @@ static void GameLoadConfig(IniFile *ini, const char *grpname)
IniItem *item;
/* Clean any configured GameScript */
- GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(NULL);
+ GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(nullptr);
/* If no group exists, return */
- if (group == NULL) return;
+ if (group == nullptr) return;
item = group->item;
- if (item == NULL) return;
+ if (item == nullptr) return;
GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
@@ -1460,7 +1460,7 @@ static void GameLoadConfig(IniFile *ini, const char *grpname)
return;
}
}
- if (item->value != NULL) config->StringToSettings(item->value);
+ if (item->value != nullptr) config->StringToSettings(item->value);
}
/**
@@ -1507,13 +1507,13 @@ static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_stati
{
IniGroup *group = ini->GetGroup(grpname);
IniItem *item;
- GRFConfig *first = NULL;
+ GRFConfig *first = nullptr;
GRFConfig **curr = &first;
- if (group == NULL) return NULL;
+ if (group == nullptr) return nullptr;
- for (item = group->item; item != NULL; item = item->next) {
- GRFConfig *c = NULL;
+ for (item = group->item; item != nullptr; item = item->next) {
+ GRFConfig *c = nullptr;
uint8 grfid_buf[4], md5sum[16];
char *filename = item->name;
@@ -1530,14 +1530,14 @@ static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_stati
uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
if (has_md5sum) {
const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
- if (s != NULL) c = new GRFConfig(*s);
+ if (s != nullptr) c = new GRFConfig(*s);
}
- if (c == NULL && !FioCheckFileExists(filename, NEWGRF_DIR)) {
+ if (c == nullptr && !FioCheckFileExists(filename, NEWGRF_DIR)) {
const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
- if (s != NULL) c = new GRFConfig(*s);
+ if (s != nullptr) c = new GRFConfig(*s);
}
}
- if (c == NULL) c = new GRFConfig(filename);
+ if (c == nullptr) c = new GRFConfig(filename);
/* Parse parameters */
if (!StrEmpty(item->value)) {
@@ -1572,7 +1572,7 @@ static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_stati
/* Check for duplicate GRFID (will also check for duplicate filenames) */
bool duplicate = false;
- for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
+ for (const GRFConfig *gc = first; gc != nullptr; gc = gc->next) {
if (gc->ident.grfid == c->ident.grfid) {
SetDParamStr(0, c->filename);
SetDParamStr(1, gc->filename);
@@ -1601,7 +1601,7 @@ static void AISaveConfig(IniFile *ini, const char *grpname)
{
IniGroup *group = ini->GetGroup(grpname);
- if (group == NULL) return;
+ if (group == nullptr) return;
group->Clear();
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
@@ -1625,7 +1625,7 @@ static void GameSaveConfig(IniFile *ini, const char *grpname)
{
IniGroup *group = ini->GetGroup(grpname);
- if (group == NULL) return;
+ if (group == nullptr) return;
group->Clear();
GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
@@ -1671,7 +1671,7 @@ static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *li
IniGroup *group = ini->GetGroup(grpname);
const GRFConfig *c;
- for (c = list; c != NULL; c = c->next) {
+ for (c = list; c != nullptr; c = c->next) {
/* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
char key[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH];
char params[512];
@@ -1688,9 +1688,9 @@ static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *li
static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool basic_settings = true, bool other_settings = true)
{
if (basic_settings) {
- proc(ini, (const SettingDesc*)_misc_settings, "misc", NULL);
+ proc(ini, (const SettingDesc*)_misc_settings, "misc", nullptr);
#if defined(_WIN32) && !defined(DEDICATED)
- proc(ini, (const SettingDesc*)_win32_settings, "win32", NULL);
+ proc(ini, (const SettingDesc*)_win32_settings, "win32", nullptr);
#endif /* _WIN32 */
}
@@ -1739,7 +1739,7 @@ void LoadFromConfig(bool minimal)
/* Display sheduled errors */
extern void ScheduleErrorMessage(ErrorList &datas);
ScheduleErrorMessage(_settings_error_list);
- if (FindWindowById(WC_ERRMSG, 0) == NULL) ShowFirstError();
+ if (FindWindowById(WC_ERRMSG, 0) == nullptr) ShowFirstError();
}
delete ini;
@@ -1774,7 +1774,7 @@ StringList GetGRFPresetList()
StringList list;
std::unique_ptr<IniFile> ini(IniLoadConfig());
- for (IniGroup *group = ini->group; group != NULL; group = group->next) {
+ for (IniGroup *group = ini->group; group != nullptr; group = group->next) {
if (strncmp(group->name, "preset-", 7) == 0) {
list.emplace_back(group->name + 7);
}
@@ -1838,7 +1838,7 @@ void DeleteGRFPresetFromConfig(const char *config_name)
const SettingDesc *GetSettingDescription(uint index)
{
- if (index >= lengthof(_settings)) return NULL;
+ if (index >= lengthof(_settings)) return nullptr;
return &_settings[index];
}
@@ -1857,7 +1857,7 @@ CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
{
const SettingDesc *sd = GetSettingDescription(p1);
- if (sd == NULL) return CMD_ERROR;
+ if (sd == nullptr) return CMD_ERROR;
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
if (!sd->IsEditable(true)) return CMD_ERROR;
@@ -1873,7 +1873,7 @@ CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (oldval == newval) return CommandCost();
- if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
+ if (sd->desc.proc != nullptr && !sd->desc.proc(newval)) {
WriteValue(var, sd->save.conv, (int64)oldval);
return CommandCost();
}
@@ -1916,7 +1916,7 @@ CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32
if (oldval == newval) return CommandCost();
- if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
+ if (sd->desc.proc != nullptr && !sd->desc.proc(newval)) {
WriteValue(var, sd->save.conv, (int64)oldval);
return CommandCost();
}
@@ -1949,7 +1949,7 @@ bool SetSettingValue(uint index, int32 value, bool force_newgame)
void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
Write_ValidateSetting(var2, sd, value);
}
- if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
+ if (sd->desc.proc != nullptr) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
SetWindowClassesDirty(WC_GAME_OPTIONS);
@@ -1983,7 +1983,7 @@ void SetCompanySetting(uint index, int32 value)
} else {
void *var = GetVariableAddress(&_settings_client.company, &sd->save);
Write_ValidateSetting(var, sd, value);
- if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
+ if (sd->desc.proc != nullptr) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
}
}
@@ -2012,7 +2012,7 @@ void SyncCompanySettings()
const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
- if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, NULL, _local_company);
+ if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, nullptr, _local_company);
}
}
@@ -2025,7 +2025,7 @@ uint GetCompanySettingIndex(const char *name)
{
uint i;
const SettingDesc *sd = GetSettingFromName(name, &i);
- assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
+ assert(sd != nullptr && (sd->desc.flags & SGF_PER_COMPANY) != 0);
return i;
}
@@ -2044,12 +2044,12 @@ bool SetSettingValue(uint index, const char *value, bool force_newgame)
if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
free(*var);
- *var = strcmp(value, "(null)") == 0 ? NULL : stredup(value);
+ *var = strcmp(value, "(null)") == 0 ? nullptr : stredup(value);
} else {
- char *var = (char*)GetVariableAddress(NULL, &sd->save);
+ char *var = (char*)GetVariableAddress(nullptr, &sd->save);
strecpy(var, value, &var[sd->save.length - 1]);
}
- if (sd->desc.proc != NULL) sd->desc.proc(0);
+ if (sd->desc.proc != nullptr) sd->desc.proc(0);
return true;
}
@@ -2059,7 +2059,7 @@ bool SetSettingValue(uint index, const char *value, bool force_newgame)
* @param name Name of the setting to return a setting description of
* @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
* @return Pointer to the setting description of setting \a name if it can be found,
- * \c NULL indicates failure to obtain the description
+ * \c nullptr indicates failure to obtain the description
*/
const SettingDesc *GetSettingFromName(const char *name, uint *i)
{
@@ -2075,7 +2075,7 @@ const SettingDesc *GetSettingFromName(const char *name, uint *i)
for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
const char *short_name = strchr(sd->desc.name, '.');
- if (short_name != NULL) {
+ if (short_name != nullptr) {
short_name++;
if (strcmp(short_name, name) == 0) return sd;
}
@@ -2088,7 +2088,7 @@ const SettingDesc *GetSettingFromName(const char *name, uint *i)
if (strcmp(sd->desc.name, name) == 0) return sd;
}
- return NULL;
+ return nullptr;
}
/* Those 2 functions need to be here, else we have to make some stuff non-static
@@ -2098,7 +2098,7 @@ void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
uint index;
const SettingDesc *sd = GetSettingFromName(name, &index);
- if (sd == NULL) {
+ if (sd == nullptr) {
IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
return;
}
@@ -2131,7 +2131,7 @@ void IConsoleSetSetting(const char *name, int value)
{
uint index;
const SettingDesc *sd = GetSettingFromName(name, &index);
- assert(sd != NULL);
+ assert(sd != nullptr);
SetSettingValue(index, value);
}
@@ -2147,7 +2147,7 @@ void IConsoleGetSetting(const char *name, bool force_newgame)
const SettingDesc *sd = GetSettingFromName(name, &index);
const void *ptr;
- if (sd == NULL) {
+ if (sd == nullptr) {
IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
return;
}
@@ -2171,7 +2171,7 @@ void IConsoleGetSetting(const char *name, bool force_newgame)
/**
* List all settings and their value to the console
*
- * @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
+ * @param prefilter If not \c nullptr, only list settings with names that begin with \a prefilter prefix
*/
void IConsoleListSettings(const char *prefilter)
{
@@ -2179,7 +2179,7 @@ void IConsoleListSettings(const char *prefilter)
for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
- if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
+ if (prefilter != nullptr && strstr(sd->desc.name, prefilter) == nullptr) continue;
char value[80];
const void *ptr = GetVariableAddress(&GetGameSettings(), &sd->save);
@@ -2199,7 +2199,7 @@ void IConsoleListSettings(const char *prefilter)
/**
* Save and load handler for settings
* @param osd SettingDesc struct containing all information
- * @param object can be either NULL in which case we load global variables or
+ * @param object can be either nullptr in which case we load global variables or
* a pointer to a struct which is getting saved
*/
static void LoadSettings(const SettingDesc *osd, void *object)
@@ -2216,7 +2216,7 @@ static void LoadSettings(const SettingDesc *osd, void *object)
/**
* Save and load handler for settings
* @param sd SettingDesc struct containing all information
- * @param object can be either NULL in which case we load global variables or
+ * @param object can be either nullptr in which case we load global variables or
* a pointer to a struct which is getting saved
*/
static void SaveSettings(const SettingDesc *sd, void *object)
@@ -2265,8 +2265,8 @@ static void Save_PATS()
}
extern const ChunkHandler _setting_chunk_handlers[] = {
- { 'OPTS', NULL, Load_OPTS, NULL, NULL, CH_RIFF},
- { 'PATS', Save_PATS, Load_PATS, NULL, Check_PATS, CH_RIFF | CH_LAST},
+ { 'OPTS', nullptr, Load_OPTS, nullptr, nullptr, CH_RIFF},
+ { 'PATS', Save_PATS, Load_PATS, nullptr, Check_PATS, CH_RIFF | CH_LAST},
};
static bool IsSignedVarMemType(VarType vt)
diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp
index 34514c86f..51b5340e3 100644
--- a/src/settings_gui.cpp
+++ b/src/settings_gui.cpp
@@ -73,7 +73,7 @@ static const StringID _font_zoom_dropdown[] = {
};
int _nb_orig_names = SPECSTR_TOWNNAME_LAST - SPECSTR_TOWNNAME_START + 1; ///< Number of original town names.
-static StringID *_grf_names = NULL; ///< Pointer to town names defined by NewGRFs.
+static StringID *_grf_names = nullptr; ///< Pointer to town names defined by NewGRFs.
static int _nb_grf_names = 0; ///< Number of town names defined by NewGRFs.
static Dimension _circle_size; ///< Dimension of the circle +/- icon. This is here as not all users are within the class of the settings window.
@@ -198,7 +198,7 @@ struct GameOptionsWindow : Window {
* Build the dropdown list for a specific widget.
* @param widget Widget to build list for
* @param selected_index Currently selected item
- * @return the built dropdown list, or NULL if the widget has no dropdown menu.
+ * @return the built dropdown list, or nullptr if the widget has no dropdown menu.
*/
DropDownList BuildDropDownList(int widget, int *selected_index) const
{
@@ -436,19 +436,19 @@ struct GameOptionsWindow : Window {
void OnClick(Point pt, int widget, int click_count) override
{
if (widget >= WID_GO_BASE_GRF_TEXTFILE && widget < WID_GO_BASE_GRF_TEXTFILE + TFT_END) {
- if (BaseGraphics::GetUsedSet() == NULL) return;
+ if (BaseGraphics::GetUsedSet() == nullptr) return;
ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_GRF_TEXTFILE), BaseGraphics::GetUsedSet(), STR_CONTENT_TYPE_BASE_GRAPHICS);
return;
}
if (widget >= WID_GO_BASE_SFX_TEXTFILE && widget < WID_GO_BASE_SFX_TEXTFILE + TFT_END) {
- if (BaseSounds::GetUsedSet() == NULL) return;
+ if (BaseSounds::GetUsedSet() == nullptr) return;
ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_SFX_TEXTFILE), BaseSounds::GetUsedSet(), STR_CONTENT_TYPE_BASE_SOUNDS);
return;
}
if (widget >= WID_GO_BASE_MUSIC_TEXTFILE && widget < WID_GO_BASE_MUSIC_TEXTFILE + TFT_END) {
- if (BaseMusic::GetUsedSet() == NULL) return;
+ if (BaseMusic::GetUsedSet() == nullptr) return;
ShowBaseSetTextfileWindow((TextfileType)(widget - WID_GO_BASE_MUSIC_TEXTFILE), BaseMusic::GetUsedSet(), STR_CONTENT_TYPE_BASE_MUSIC);
return;
@@ -508,7 +508,7 @@ struct GameOptionsWindow : Window {
case WID_GO_ROADSIDE_DROPDOWN: // Road side
if (this->opt->vehicle.road_side != index) { // only change if setting changed
uint i;
- if (GetSettingFromName("vehicle.road_side", &i) == NULL) NOT_REACHED();
+ if (GetSettingFromName("vehicle.road_side", &i) == nullptr) NOT_REACHED();
SetSettingValue(i, index);
MarkWholeScreenDirty();
}
@@ -584,9 +584,9 @@ struct GameOptionsWindow : Window {
this->GetWidget<NWidgetCore>(WID_GO_BASE_GRF_STATUS)->SetDataTip(missing_files ? STR_EMPTY : STR_GAME_OPTIONS_BASE_GRF_STATUS, STR_NULL);
for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
- this->SetWidgetDisabledState(WID_GO_BASE_GRF_TEXTFILE + tft, BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->GetTextfile(tft) == NULL);
- this->SetWidgetDisabledState(WID_GO_BASE_SFX_TEXTFILE + tft, BaseSounds::GetUsedSet() == NULL || BaseSounds::GetUsedSet()->GetTextfile(tft) == NULL);
- this->SetWidgetDisabledState(WID_GO_BASE_MUSIC_TEXTFILE + tft, BaseMusic::GetUsedSet() == NULL || BaseMusic::GetUsedSet()->GetTextfile(tft) == NULL);
+ this->SetWidgetDisabledState(WID_GO_BASE_GRF_TEXTFILE + tft, BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->GetTextfile(tft) == nullptr);
+ this->SetWidgetDisabledState(WID_GO_BASE_SFX_TEXTFILE + tft, BaseSounds::GetUsedSet() == nullptr || BaseSounds::GetUsedSet()->GetTextfile(tft) == nullptr);
+ this->SetWidgetDisabledState(WID_GO_BASE_MUSIC_TEXTFILE + tft, BaseMusic::GetUsedSet() == nullptr || BaseMusic::GetUsedSet()->GetTextfile(tft) == nullptr);
}
missing_files = BaseMusic::GetUsedSet()->GetNumInvalid() == 0;
@@ -879,14 +879,14 @@ bool BaseSettingEntry::IsVisible(const BaseSettingEntry *item) const
* Find setting entry at row \a row_num
* @param row_num Index of entry to return
* @param cur_row Current row number
- * @return The requested setting entry or \c NULL if it not found (folded or filtered)
+ * @return The requested setting entry or \c nullptr if it not found (folded or filtered)
*/
BaseSettingEntry *BaseSettingEntry::FindEntry(uint row_num, uint *cur_row)
{
- if (this->IsFiltered()) return NULL;
+ if (this->IsFiltered()) return nullptr;
if (row_num == *cur_row) return this;
(*cur_row)++;
- return NULL;
+ return nullptr;
}
/**
@@ -961,7 +961,7 @@ uint BaseSettingEntry::Draw(GameSettings *settings_ptr, int left, int right, int
SettingEntry::SettingEntry(const char *name)
{
this->name = name;
- this->setting = NULL;
+ this->setting = nullptr;
this->index = 0;
}
@@ -973,7 +973,7 @@ void SettingEntry::Init(byte level)
{
BaseSettingEntry::Init(level);
this->setting = GetSettingFromName(this->name, &this->index);
- assert(this->setting != NULL);
+ assert(this->setting != nullptr);
}
/**
@@ -1253,14 +1253,14 @@ uint SettingsContainer::Length() const
* Find the setting entry at row number \a row_num
* @param row_num Index of entry to return
* @param cur_row Variable used for keeping track of the current row number. Should point to memory initialized to \c 0 when first called.
- * @return The requested setting entry or \c NULL if it does not exist
+ * @return The requested setting entry or \c nullptr if it does not exist
*/
BaseSettingEntry *SettingsContainer::FindEntry(uint row_num, uint *cur_row)
{
- BaseSettingEntry *pe = NULL;
+ BaseSettingEntry *pe = nullptr;
for (EntryVector::iterator it = this->entries.begin(); it != this->entries.end(); ++it) {
pe = (*it)->FindEntry(row_num, cur_row);
- if (pe != NULL) {
+ if (pe != nullptr) {
break;
}
}
@@ -1416,14 +1416,14 @@ uint SettingsPage::Length() const
* Find setting entry at row \a row_num
* @param row_num Index of entry to return
* @param cur_row Current row number
- * @return The requested setting entry or \c NULL if it not found (folded or filtered)
+ * @return The requested setting entry or \c nullptr if it not found (folded or filtered)
*/
BaseSettingEntry *SettingsPage::FindEntry(uint row_num, uint *cur_row)
{
- if (this->IsFiltered()) return NULL;
+ if (this->IsFiltered()) return nullptr;
if (row_num == *cur_row) return this;
(*cur_row)++;
- if (this->folded) return NULL;
+ if (this->folded) return nullptr;
return SettingsContainer::FindEntry(row_num, cur_row);
}
@@ -1479,9 +1479,9 @@ void SettingsPage::DrawSetting(GameSettings *settings_ptr, int left, int right,
/** Construct settings tree */
static SettingsContainer &GetSettingsTree()
{
- static SettingsContainer *main = NULL;
+ static SettingsContainer *main = nullptr;
- if (main == NULL)
+ if (main == nullptr)
{
/* Build up the dynamic settings-array only once per OpenTTD session */
main = new SettingsContainer();
@@ -1801,10 +1801,10 @@ struct GameSettingsWindow : Window {
static GameSettings *settings_ptr; ///< Pointer to the game settings being displayed and modified.
- SettingEntry *valuewindow_entry; ///< If non-NULL, pointer to setting for which a value-entering window has been opened.
- SettingEntry *clicked_entry; ///< If non-NULL, pointer to a clicked numeric setting (with a depressed left or right button).
- SettingEntry *last_clicked; ///< If non-NULL, pointer to the last clicked setting.
- SettingEntry *valuedropdown_entry; ///< If non-NULL, pointer to the value for which a dropdown window is currently opened.
+ SettingEntry *valuewindow_entry; ///< If non-nullptr, pointer to setting for which a value-entering window has been opened.
+ SettingEntry *clicked_entry; ///< If non-nullptr, pointer to a clicked numeric setting (with a depressed left or right button).
+ SettingEntry *last_clicked; ///< If non-nullptr, pointer to the last clicked setting.
+ SettingEntry *valuedropdown_entry; ///< If non-nullptr, pointer to the value for which a dropdown window is currently opened.
bool closing_dropdown; ///< True, if the dropdown list is currently closing.
SettingFilter filter; ///< Filter for the list.
@@ -1828,10 +1828,10 @@ struct GameSettingsWindow : Window {
_circle_size = maxdim(GetSpriteSize(SPR_CIRCLE_FOLDED), GetSpriteSize(SPR_CIRCLE_UNFOLDED));
GetSettingsTree().FoldAll(); // Close all sub-pages
- this->valuewindow_entry = NULL; // No setting entry for which a entry window is opened
- this->clicked_entry = NULL; // No numeric setting buttons are depressed
- this->last_clicked = NULL;
- this->valuedropdown_entry = NULL;
+ this->valuewindow_entry = nullptr; // No setting entry for which a entry window is opened
+ this->clicked_entry = nullptr; // No numeric setting buttons are depressed
+ this->last_clicked = nullptr;
+ this->valuedropdown_entry = nullptr;
this->closing_dropdown = false;
this->manually_changed_folding = false;
@@ -1885,9 +1885,9 @@ struct GameSettingsWindow : Window {
{
if (this->closing_dropdown) {
this->closing_dropdown = false;
- assert(this->valuedropdown_entry != NULL);
+ assert(this->valuedropdown_entry != nullptr);
this->valuedropdown_entry->SetButtons(0);
- this->valuedropdown_entry = NULL;
+ this->valuedropdown_entry = nullptr;
}
/* Reserve the correct number of lines for the 'some search results are hidden' notice in the central settings display panel. */
@@ -1977,7 +1977,7 @@ struct GameSettingsWindow : Window {
}
case WID_GS_HELP_TEXT:
- if (this->last_clicked != NULL) {
+ if (this->last_clicked != nullptr) {
const SettingDesc *sd = this->last_clicked->setting;
int y = r.top;
@@ -2006,7 +2006,7 @@ struct GameSettingsWindow : Window {
/**
* Set the entry that should have its help text displayed, and mark the window dirty so it gets repainted.
- * @param pe Setting to display help text of, use \c NULL to stop displaying help of the currently displayed setting.
+ * @param pe Setting to display help text of, use \c nullptr to stop displaying help of the currently displayed setting.
*/
void SetDisplayedHelpText(SettingEntry *pe)
{
@@ -2055,14 +2055,14 @@ struct GameSettingsWindow : Window {
uint cur_row = 0;
BaseSettingEntry *clicked_entry = GetSettingsTree().FindEntry(btn, &cur_row);
- if (clicked_entry == NULL) return; // Clicked below the last setting of the page
+ if (clicked_entry == nullptr) return; // Clicked below the last setting of the page
int x = (_current_text_dir == TD_RTL ? this->width - 1 - pt.x : pt.x) - SETTINGTREE_LEFT_OFFSET - (clicked_entry->level + 1) * LEVEL_WIDTH; // Shift x coordinate
if (x < 0) return; // Clicked left of the entry
SettingsPage *clicked_page = dynamic_cast<SettingsPage*>(clicked_entry);
- if (clicked_page != NULL) {
- this->SetDisplayedHelpText(NULL);
+ if (clicked_page != nullptr) {
+ this->SetDisplayedHelpText(nullptr);
clicked_page->folded = !clicked_page->folded; // Flip 'folded'-ness of the sub-page
this->manually_changed_folding = true;
@@ -2072,7 +2072,7 @@ struct GameSettingsWindow : Window {
}
SettingEntry *pe = dynamic_cast<SettingEntry*>(clicked_entry);
- assert(pe != NULL);
+ assert(pe != nullptr);
const SettingDesc *sd = pe->setting;
/* return if action is only active in network, or only settable by server */
@@ -2094,9 +2094,9 @@ struct GameSettingsWindow : Window {
HideDropDownMenu(this);
this->closing_dropdown = false;
this->valuedropdown_entry->SetButtons(0);
- this->valuedropdown_entry = NULL;
+ this->valuedropdown_entry = nullptr;
} else {
- if (this->valuedropdown_entry != NULL) this->valuedropdown_entry->SetButtons(0);
+ if (this->valuedropdown_entry != nullptr) this->valuedropdown_entry->SetButtons(0);
this->closing_dropdown = false;
const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_GS_OPTIONSPANEL);
@@ -2161,7 +2161,7 @@ struct GameSettingsWindow : Window {
/* Set up scroller timeout for numeric values */
if (value != oldvalue) {
- if (this->clicked_entry != NULL) { // Release previous buttons if any
+ if (this->clicked_entry != nullptr) { // Release previous buttons if any
this->clicked_entry->SetButtons(0);
}
this->clicked_entry = pe;
@@ -2199,9 +2199,9 @@ struct GameSettingsWindow : Window {
void OnTimeout() override
{
- if (this->clicked_entry != NULL) { // On timeout, release any depressed buttons
+ if (this->clicked_entry != nullptr) { // On timeout, release any depressed buttons
this->clicked_entry->SetButtons(0);
- this->clicked_entry = NULL;
+ this->clicked_entry = nullptr;
this->SetDirty();
}
}
@@ -2209,9 +2209,9 @@ struct GameSettingsWindow : Window {
void OnQueryTextFinished(char *str) override
{
/* The user pressed cancel */
- if (str == NULL) return;
+ if (str == nullptr) return;
- assert(this->valuewindow_entry != NULL);
+ assert(this->valuewindow_entry != nullptr);
const SettingDesc *sd = this->valuewindow_entry->setting;
int32 value;
@@ -2260,7 +2260,7 @@ struct GameSettingsWindow : Window {
default:
if (widget < 0) {
/* Deal with drop down boxes on the panel. */
- assert(this->valuedropdown_entry != NULL);
+ assert(this->valuedropdown_entry != nullptr);
const SettingDesc *sd = this->valuedropdown_entry->setting;
assert(sd->desc.flags & SGF_MULTISTRING);
@@ -2289,7 +2289,7 @@ struct GameSettingsWindow : Window {
* the same dropdown button was clicked again, and then not open the dropdown again.
* So, we only remember that it was closed, and process it on the next OnPaint, which is
* after OnClick. */
- assert(this->valuedropdown_entry != NULL);
+ assert(this->valuedropdown_entry != nullptr);
this->closing_dropdown = true;
this->SetDirty();
}
@@ -2314,8 +2314,8 @@ struct GameSettingsWindow : Window {
}
this->vscroll->SetCount(GetSettingsTree().Length() + this->warn_lines);
- if (this->last_clicked != NULL && !GetSettingsTree().IsVisible(this->last_clicked)) {
- this->SetDisplayedHelpText(NULL);
+ if (this->last_clicked != nullptr && !GetSettingsTree().IsVisible(this->last_clicked)) {
+ this->SetDisplayedHelpText(nullptr);
}
bool all_folded = true;
@@ -2344,7 +2344,7 @@ struct GameSettingsWindow : Window {
}
};
-GameSettings *GameSettingsWindow::settings_ptr = NULL;
+GameSettings *GameSettingsWindow::settings_ptr = nullptr;
static const NWidgetPart _nested_settings_selection_widgets[] = {
NWidget(NWID_HORIZONTAL),
@@ -2603,7 +2603,7 @@ struct CustomCurrencyWindow : Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
switch (this->query_widget) {
case WID_CC_RATE:
@@ -2680,7 +2680,7 @@ static const NWidgetPart _nested_cust_currency_widgets[] = {
};
static WindowDesc _cust_currency_desc(
- WDP_CENTER, NULL, 0, 0,
+ WDP_CENTER, nullptr, 0, 0,
WC_CUSTOM_CURRENCY, WC_NONE,
0,
_nested_cust_currency_widgets, lengthof(_nested_cust_currency_widgets)
diff --git a/src/settingsgen/settingsgen.cpp b/src/settingsgen/settingsgen.cpp
index 02a0d1a9a..7f024b2dc 100644
--- a/src/settingsgen/settingsgen.cpp
+++ b/src/settingsgen/settingsgen.cpp
@@ -160,10 +160,10 @@ private:
struct SettingsIniFile : IniLoadFile {
/**
* Construct a new ini loader.
- * @param list_group_names A \c NULL terminated list with group names that should be loaded as lists instead of variables. @see IGT_LIST
- * @param seq_group_names A \c NULL terminated list with group names that should be loaded as lists of names. @see IGT_SEQUENCE
+ * @param list_group_names A \c nullptr terminated list with group names that should be loaded as lists instead of variables. @see IGT_LIST
+ * @param seq_group_names A \c nullptr terminated list with group names that should be loaded as lists of names. @see IGT_SEQUENCE
*/
- SettingsIniFile(const char * const *list_group_names = NULL, const char * const *seq_group_names = NULL) :
+ SettingsIniFile(const char * const *list_group_names = nullptr, const char * const *seq_group_names = nullptr) :
IniLoadFile(list_group_names, seq_group_names)
{
}
@@ -173,7 +173,7 @@ struct SettingsIniFile : IniLoadFile {
/* Open the text file in binary mode to prevent end-of-line translations
* done by ftell() and friends, as defined by K&R. */
FILE *in = fopen(filename, "rb");
- if (in == NULL) return NULL;
+ if (in == nullptr) return nullptr;
fseek(in, 0L, SEEK_END);
*size = ftell(in);
@@ -202,9 +202,9 @@ static const char *DEFAULTS_GROUP_NAME = "defaults"; ///< Name of the group c
*/
static IniLoadFile *LoadIniFile(const char *filename)
{
- static const char * const seq_groups[] = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME, NULL};
+ static const char * const seq_groups[] = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME, nullptr};
- IniLoadFile *ini = new SettingsIniFile(NULL, seq_groups);
+ IniLoadFile *ini = new SettingsIniFile(nullptr, seq_groups);
ini->LoadFromDisk(filename, NO_DIRECTORY);
return ini;
}
@@ -217,8 +217,8 @@ static IniLoadFile *LoadIniFile(const char *filename)
static void DumpGroup(IniLoadFile *ifile, const char * const group_name)
{
IniGroup *grp = ifile->GetGroup(group_name, 0, false);
- if (grp != NULL && grp->type == IGT_SEQUENCE) {
- for (IniItem *item = grp->item; item != NULL; item = item->next) {
+ if (grp != nullptr && grp->type == IGT_SEQUENCE) {
+ for (IniItem *item = grp->item; item != nullptr; item = item->next) {
if (item->name) {
_stored_output.Add(item->name);
_stored_output.Add("\n", 1);
@@ -231,14 +231,14 @@ static void DumpGroup(IniLoadFile *ifile, const char * const group_name)
* Find the value of a template variable.
* @param name Name of the item to find.
* @param grp Group currently being expanded (searched first).
- * @param defaults Fallback group to search, \c NULL skips the search.
- * @return Text of the item if found, else \c NULL.
+ * @param defaults Fallback group to search, \c nullptr skips the search.
+ * @return Text of the item if found, else \c nullptr.
*/
static const char *FindItemValue(const char *name, IniGroup *grp, IniGroup *defaults)
{
IniItem *item = grp->GetItem(name, false);
- if (item == NULL && defaults != NULL) item = defaults->GetItem(name, false);
- if (item == NULL || item->value == NULL) return NULL;
+ if (item == nullptr && defaults != nullptr) item = defaults->GetItem(name, false);
+ if (item == nullptr || item->value == nullptr) return nullptr;
return item->value;
}
@@ -249,30 +249,30 @@ static const char *FindItemValue(const char *name, IniGroup *grp, IniGroup *defa
static void DumpSections(IniLoadFile *ifile)
{
static const int MAX_VAR_LENGTH = 64;
- static const char * const special_group_names[] = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME, DEFAULTS_GROUP_NAME, TEMPLATES_GROUP_NAME, NULL};
+ static const char * const special_group_names[] = {PREAMBLE_GROUP_NAME, POSTAMBLE_GROUP_NAME, DEFAULTS_GROUP_NAME, TEMPLATES_GROUP_NAME, nullptr};
IniGroup *default_grp = ifile->GetGroup(DEFAULTS_GROUP_NAME, 0, false);
IniGroup *templates_grp = ifile->GetGroup(TEMPLATES_GROUP_NAME, 0, false);
- if (templates_grp == NULL) return;
+ if (templates_grp == nullptr) return;
/* Output every group, using its name as template name. */
- for (IniGroup *grp = ifile->group; grp != NULL; grp = grp->next) {
+ for (IniGroup *grp = ifile->group; grp != nullptr; grp = grp->next) {
const char * const *sgn;
- for (sgn = special_group_names; *sgn != NULL; sgn++) if (strcmp(grp->name, *sgn) == 0) break;
- if (*sgn != NULL) continue;
+ for (sgn = special_group_names; *sgn != nullptr; sgn++) if (strcmp(grp->name, *sgn) == 0) break;
+ if (*sgn != nullptr) continue;
IniItem *template_item = templates_grp->GetItem(grp->name, false); // Find template value.
- if (template_item == NULL || template_item->value == NULL) {
+ if (template_item == nullptr || template_item->value == nullptr) {
fprintf(stderr, "settingsgen: Warning: Cannot find template %s\n", grp->name);
continue;
}
/* Prefix with #if/#ifdef/#ifndef */
- static const char * const pp_lines[] = {"if", "ifdef", "ifndef", NULL};
+ static const char * const pp_lines[] = {"if", "ifdef", "ifndef", nullptr};
int count = 0;
- for (const char * const *name = pp_lines; *name != NULL; name++) {
+ for (const char * const *name = pp_lines; *name != nullptr; name++) {
const char *condition = FindItemValue(*name, grp, default_grp);
- if (condition != NULL) {
+ if (condition != nullptr) {
_stored_output.Add("#", 1);
_stored_output.Add(*name);
_stored_output.Add(" ", 1);
@@ -311,7 +311,7 @@ static void DumpSections(IniLoadFile *ifile)
if (i > 0) {
/* Find the text to output. */
const char *valitem = FindItemValue(variable, grp, default_grp);
- if (valitem != NULL) _stored_output.Add(valitem);
+ if (valitem != nullptr) _stored_output.Add(valitem);
} else {
_stored_output.Add("$", 1);
}
@@ -331,10 +331,10 @@ static void DumpSections(IniLoadFile *ifile)
*/
static void CopyFile(const char *fname, FILE *out_fp)
{
- if (fname == NULL) return;
+ if (fname == nullptr) return;
FILE *in_fp = fopen(fname, "r");
- if (in_fp == NULL) {
+ if (in_fp == nullptr) {
fprintf(stderr, "settingsgen: Warning: Cannot open file %s for copying\n", fname);
return;
}
@@ -361,10 +361,10 @@ static void CopyFile(const char *fname, FILE *out_fp)
static bool CompareFiles(const char *n1, const char *n2)
{
FILE *f2 = fopen(n2, "rb");
- if (f2 == NULL) return false;
+ if (f2 == nullptr) return false;
FILE *f1 = fopen(n1, "rb");
- if (f1 == NULL) {
+ if (f1 == nullptr) {
fclose(f2);
error("can't open %s", n1);
}
@@ -392,7 +392,7 @@ static bool CompareFiles(const char *n1, const char *n2)
static const OptionData _opts[] = {
GETOPT_NOVAL( 'v', "--version"),
GETOPT_NOVAL( 'h', "--help"),
- GETOPT_GENERAL('h', '?', NULL, ODF_NO_VALUE),
+ GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE),
GETOPT_VALUE( 'o', "--output"),
GETOPT_VALUE( 'b', "--before"),
GETOPT_VALUE( 'a', "--after"),
@@ -435,9 +435,9 @@ static void ProcessIniFile(const char *fname)
*/
int CDECL main(int argc, char *argv[])
{
- const char *output_file = NULL;
- const char *before_file = NULL;
- const char *after_file = NULL;
+ const char *output_file = nullptr;
+ const char *before_file = nullptr;
+ const char *after_file = nullptr;
GetOptData mgo(argc - 1, argv + 1, _opts);
for (;;) {
@@ -483,7 +483,7 @@ int CDECL main(int argc, char *argv[])
for (int i = 0; i < mgo.numleft; i++) ProcessIniFile(mgo.argv[i]);
/* Write output. */
- if (output_file == NULL) {
+ if (output_file == nullptr) {
CopyFile(before_file, stdout);
_stored_output.Write(stdout);
CopyFile(after_file, stdout);
@@ -491,7 +491,7 @@ int CDECL main(int argc, char *argv[])
static const char * const tmp_output = "tmp2.xxx";
FILE *fp = fopen(tmp_output, "w");
- if (fp == NULL) {
+ if (fp == nullptr) {
fprintf(stderr, "settingsgen: Warning: Cannot open file %s\n", tmp_output);
return 1;
}
diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp
index 93019020a..08b07a07d 100644
--- a/src/ship_cmd.cpp
+++ b/src/ship_cmd.cpp
@@ -145,7 +145,7 @@ static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
{
/* Find the closest depot */
const Depot *depot;
- const Depot *best_depot = NULL;
+ const Depot *best_depot = nullptr;
/* If we don't have a maximum distance, i.e. distance = 0,
* we want to find any depot so the best distance of no
* depot must be more than any correct distance. On the
@@ -184,7 +184,7 @@ static void CheckIfShipNeedsService(Vehicle *v)
const Depot *depot = FindClosestShipDepot(v, max_distance);
- if (depot == NULL) {
+ if (depot == nullptr) {
if (v->current_order.IsType(OT_GOTO_DEPOT)) {
v->current_order.MakeDummy();
SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
@@ -333,7 +333,7 @@ void Ship::UpdateDeltaXY()
*/
static Vehicle *EnsureNoVisibleShipProc(Vehicle *v, void *data)
{
- return v->type == VEH_SHIP && (v->vehstatus & VS_HIDDEN) == 0 ? v : NULL;
+ return v->type == VEH_SHIP && (v->vehstatus & VS_HIDDEN) == 0 ? v : nullptr;
}
static bool CheckShipLeaveDepot(Ship *v)
@@ -352,7 +352,7 @@ static bool CheckShipLeaveDepot(Ship *v)
/* Don't leave depot if another vehicle is already entering/leaving */
/* This helps avoid CPU load if many ships are set to start at the same time */
- if (HasVehicleOnPos(v->tile, NULL, &EnsureNoVisibleShipProc)) return true;
+ if (HasVehicleOnPos(v->tile, nullptr, &EnsureNoVisibleShipProc)) return true;
TileIndex tile = v->tile;
Axis axis = GetShipDepotAxis(tile);
@@ -869,10 +869,10 @@ bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, boo
{
const Depot *depot = FindClosestShipDepot(this, 0);
- if (depot == NULL) return false;
+ if (depot == nullptr) return false;
- if (location != NULL) *location = depot->xy;
- if (destination != NULL) *destination = depot->index;
+ if (location != nullptr) *location = depot->xy;
+ if (destination != nullptr) *destination = depot->index;
return true;
}
diff --git a/src/signal.cpp b/src/signal.cpp
index b37e15074..8952000a5 100644
--- a/src/signal.cpp
+++ b/src/signal.cpp
@@ -192,7 +192,7 @@ static SmallSet<DiagDirection, SIG_GLOB_SIZE> _globset("_globset"); ///< set of
/** Check whether there is a train on rail, not in a depot */
static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
{
- if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
+ if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
return v;
}
@@ -283,13 +283,13 @@ static SigFlags ExploreSegment(Owner owner)
if (IsRailDepot(tile)) {
if (enterdir == INVALID_DIAGDIR) { // from 'inside' - train just entered or left the depot
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
exitdir = GetRailDepotDirection(tile);
tile += TileOffsByDiagDir(exitdir);
enterdir = ReverseDiagDir(exitdir);
break;
} else if (enterdir == GetRailDepotDirection(tile)) { // entered a depot
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
continue;
} else {
continue;
@@ -306,7 +306,7 @@ static SigFlags ExploreSegment(Owner owner)
if (!(flags & SF_TRAIN) && EnsureNoTrainOnTrackBits(tile, tracks).Failed()) flags |= SF_TRAIN;
} else {
if (tracks_masked == TRACK_BIT_NONE) continue; // no incidating track
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
}
if (HasSignals(tile)) { // there is exactly one track - not zero, because there is exit from this tile
@@ -358,7 +358,7 @@ static SigFlags ExploreSegment(Owner owner)
if (DiagDirToAxis(enterdir) != GetRailStationAxis(tile)) continue; // different axis
if (IsStationTileBlocked(tile)) continue; // 'eye-candy' station tile
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile += TileOffsByDiagDir(exitdir);
break;
@@ -367,7 +367,7 @@ static SigFlags ExploreSegment(Owner owner)
if (GetTileOwner(tile) != owner) continue;
if (DiagDirToAxis(enterdir) == GetCrossingRoadAxis(tile)) continue; // different axis
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile += TileOffsByDiagDir(exitdir);
break;
@@ -377,13 +377,13 @@ static SigFlags ExploreSegment(Owner owner)
DiagDirection dir = GetTunnelBridgeDirection(tile);
if (enterdir == INVALID_DIAGDIR) { // incoming from the wormhole
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
enterdir = dir;
exitdir = ReverseDiagDir(dir);
tile += TileOffsByDiagDir(exitdir); // just skip to next tile
} else { // NOT incoming from the wormhole!
if (ReverseDiagDir(enterdir) != dir) continue;
- if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, NULL, &TrainOnTileEnum)) flags |= SF_TRAIN;
+ if (!(flags & SF_TRAIN) && HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum)) flags |= SF_TRAIN;
tile = GetOtherTunnelBridgeEnd(tile); // just skip to exit tile
enterdir = INVALID_DIAGDIR;
exitdir = INVALID_DIAGDIR;
diff --git a/src/signs_cmd.cpp b/src/signs_cmd.cpp
index ea6c680c3..22b781b58 100644
--- a/src/signs_cmd.cpp
+++ b/src/signs_cmd.cpp
@@ -81,7 +81,7 @@ CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Sign *si = Sign::GetIfValid(p1);
- if (si == NULL) return CMD_ERROR;
+ if (si == nullptr) return CMD_ERROR;
if (si->owner == OWNER_DEITY && _current_company != OWNER_DEITY && _game_mode != GM_EDITOR) return CMD_ERROR;
/* Rename the signs when empty, otherwise remove it */
diff --git a/src/signs_gui.cpp b/src/signs_gui.cpp
index 64fbcad80..a06898af7 100644
--- a/src/signs_gui.cpp
+++ b/src/signs_gui.cpp
@@ -45,7 +45,7 @@ struct SignList {
StringFilter string_filter; ///< The match string to be used when the GUIList is (re)-sorted.
static bool match_case; ///< Should case sensitive matching be used?
- static char default_name[64]; ///< Default sign name, used if Sign::name is NULL.
+ static char default_name[64]; ///< Default sign name, used if Sign::name is nullptr.
/**
* Creates a SignList with filtering disabled by default.
@@ -81,8 +81,8 @@ struct SignList {
const char *a_name = (*a)->name;
const char *b_name = (*b)->name;
- if (a_name == NULL) a_name = SignList::default_name;
- if (b_name == NULL) b_name = SignList::default_name;
+ if (a_name == nullptr) a_name = SignList::default_name;
+ if (b_name == nullptr) b_name = SignList::default_name;
int r = strnatcmp(a_name, b_name); // Sort by name (natural sorting).
@@ -100,7 +100,7 @@ struct SignList {
/* Same performance benefit as above for sorting. */
const char *a_name = (*a)->name;
- if (a_name == NULL) a_name = SignList::default_name;
+ if (a_name == nullptr) a_name = SignList::default_name;
filter.ResetState();
filter.AddLine(a_name);
@@ -168,7 +168,7 @@ struct SignListWindow : Window, SignList {
void OnInit() override
{
- /* Default sign name, used if Sign::name is NULL. */
+ /* Default sign name, used if Sign::name is nullptr. */
GetString(SignList::default_name, STR_DEFAULT_SIGN_NAME, lastof(SignList::default_name));
this->signs.ForceResort();
this->SortSignsList();
@@ -352,7 +352,7 @@ static EventState SignListGlobalHotkeys(int hotkey)
{
if (_game_mode == GM_MENU) return ES_NOT_HANDLED;
Window *w = ShowSignList();
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -402,7 +402,7 @@ static WindowDesc _sign_list_desc(
/**
* Open the sign list window
*
- * @return newly opened sign list window, or NULL if the window could not be opened.
+ * @return newly opened sign list window, or nullptr if the window could not be opened.
*/
Window *ShowSignList()
{
@@ -418,7 +418,7 @@ Window *ShowSignList()
static bool RenameSign(SignID index, const char *text)
{
bool remove = StrEmpty(text);
- DoCommandP(0, index, 0, CMD_RENAME_SIGN | (StrEmpty(text) ? CMD_MSG(STR_ERROR_CAN_T_DELETE_SIGN) : CMD_MSG(STR_ERROR_CAN_T_CHANGE_SIGN_NAME)), NULL, text);
+ DoCommandP(0, index, 0, CMD_RENAME_SIGN | (StrEmpty(text) ? CMD_MSG(STR_ERROR_CAN_T_DELETE_SIGN) : CMD_MSG(STR_ERROR_CAN_T_CHANGE_SIGN_NAME)), nullptr, text);
return remove;
}
@@ -442,7 +442,7 @@ struct SignWindow : Window, SignList {
void UpdateSignEditWindow(const Sign *si)
{
/* Display an empty string when the sign hasn't been edited yet */
- if (si->name != NULL) {
+ if (si->name != nullptr) {
SetDParam(0, si->index);
this->name_editbox.text.Assign(STR_SIGN_NAME);
} else {
@@ -559,7 +559,7 @@ static WindowDesc _query_sign_edit_desc(
void HandleClickOnSign(const Sign *si)
{
if (_ctrl_pressed && (si->owner == _local_company || (si->owner == OWNER_DEITY && _game_mode == GM_EDITOR))) {
- RenameSign(si->index, NULL);
+ RenameSign(si->index, nullptr);
return;
}
ShowRenameSignWindow(si);
@@ -585,5 +585,5 @@ void DeleteRenameSignWindow(SignID sign)
{
SignWindow *w = dynamic_cast<SignWindow *>(FindWindowById(WC_QUERY_STRING, WN_QUERY_STRING_SIGN));
- if (w != NULL && w->cur_sign == sign) delete w;
+ if (w != nullptr && w->cur_sign == sign) delete w;
}
diff --git a/src/smallmap_gui.cpp b/src/smallmap_gui.cpp
index 5286d2d63..124985173 100644
--- a/src/smallmap_gui.cpp
+++ b/src/smallmap_gui.cpp
@@ -272,9 +272,9 @@ struct SmallMapColourScheme {
/** Available colour schemes for height maps. */
static SmallMapColourScheme _heightmap_schemes[] = {
- {NULL, _green_map_heights, lengthof(_green_map_heights), MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme.
- {NULL, _dark_green_map_heights, lengthof(_dark_green_map_heights), MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme.
- {NULL, _violet_map_heights, lengthof(_violet_map_heights), MKCOLOUR_XXXX(0x81)}, ///< Violet colour scheme.
+ {nullptr, _green_map_heights, lengthof(_green_map_heights), MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme.
+ {nullptr, _dark_green_map_heights, lengthof(_dark_green_map_heights), MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme.
+ {nullptr, _violet_map_heights, lengthof(_violet_map_heights), MKCOLOUR_XXXX(0x81)}, ///< Violet colour scheme.
};
/**
@@ -283,7 +283,7 @@ static SmallMapColourScheme _heightmap_schemes[] = {
void BuildLandLegend()
{
/* The smallmap window has never been initialized, so no need to change the legend. */
- if (_heightmap_schemes[0].height_colours == NULL) return;
+ if (_heightmap_schemes[0].height_colours == nullptr) return;
/*
* The general idea of this function is to fill the legend with an appropriate evenly spaced
@@ -1071,7 +1071,7 @@ SmallMapWindow::SmallMapWindow(WindowDesc *desc, int window_number) : Window(des
this->SetupWidgetData();
- this->SetZoomLevel(ZLC_INITIALIZE, NULL);
+ this->SetZoomLevel(ZLC_INITIALIZE, nullptr);
this->SmallMapCenterOnCurrentPos();
this->SetOverlayCargoMask();
}
@@ -1474,7 +1474,7 @@ int SmallMapWindow::GetPositionOnLegend(Point pt)
case WID_SM_ENABLE_ALL:
case WID_SM_DISABLE_ALL: {
- LegendAndColour *tbl = NULL;
+ LegendAndColour *tbl = nullptr;
switch (this->map_type) {
case SMT_INDUSTRY:
tbl = _legend_from_industries;
@@ -1682,7 +1682,7 @@ class NWidgetSmallmapDisplay : public NWidgetContainer {
public:
NWidgetSmallmapDisplay() : NWidgetContainer(NWID_VERTICAL)
{
- this->smallmap_window = NULL;
+ this->smallmap_window = nullptr;
}
void SetupSmallestSize(Window *w, bool init_array) override
@@ -1694,7 +1694,7 @@ public:
bar->SetupSmallestSize(w, init_array);
this->smallmap_window = dynamic_cast<SmallMapWindow *>(w);
- assert(this->smallmap_window != NULL);
+ assert(this->smallmap_window != nullptr);
this->smallest_x = max(display->smallest_x, bar->smallest_x + smallmap_window->GetMinLegendWidth());
this->smallest_y = display->smallest_y + max(bar->smallest_y, smallmap_window->GetLegendHeight(smallmap_window->min_number_of_columns));
this->fill_x = max(display->fill_x, bar->fill_x);
@@ -1729,17 +1729,17 @@ public:
NWidgetCore *GetWidgetFromPos(int x, int y) override
{
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
NWidgetCore *widget = child_wid->GetWidgetFromPos(x, y);
- if (widget != NULL) return widget;
+ if (widget != nullptr) return widget;
}
- return NULL;
+ return nullptr;
}
void Draw(const Window *w) override
{
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) child_wid->Draw(w);
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) child_wid->Draw(w);
}
};
@@ -1862,7 +1862,7 @@ bool ScrollMainWindowTo(int x, int y, int z, bool instant)
if (res) return res;
SmallMapWindow *w = dynamic_cast<SmallMapWindow*>(FindWindowById(WC_SMALLMAP, 0));
- if (w != NULL) w->SmallMapCenterOnCurrentPos();
+ if (w != nullptr) w->SmallMapCenterOnCurrentPos();
return res;
}
diff --git a/src/sortlist_type.h b/src/sortlist_type.h
index f5036903b..75730c08d 100644
--- a/src/sortlist_type.h
+++ b/src/sortlist_type.h
@@ -81,8 +81,8 @@ protected:
public:
GUIList() :
- sort_func_list(NULL),
- filter_func_list(NULL),
+ sort_func_list(nullptr),
+ filter_func_list(nullptr),
flags(VL_FIRST_SORT),
sort_type(0),
filter_type(0),
@@ -296,7 +296,7 @@ public:
*/
bool Sort()
{
- assert(this->sort_func_list != NULL);
+ assert(this->sort_func_list != nullptr);
return this->Sort(this->sort_func_list[this->sort_type]);
}
@@ -367,7 +367,7 @@ public:
*/
bool Filter(F filter_data)
{
- if (this->filter_func_list == NULL) return false;
+ if (this->filter_func_list == nullptr) return false;
return this->Filter(this->filter_func_list[this->filter_type], filter_data);
}
diff --git a/src/sound.cpp b/src/sound.cpp
index 79dd988bf..0b21ef122 100644
--- a/src/sound.cpp
+++ b/src/sound.cpp
@@ -30,7 +30,7 @@ static void OpenBankFile(const char *filename)
memset(_original_sounds, 0, sizeof(_original_sounds));
/* If there is no sound file (nosound set), don't load anything */
- if (filename == NULL) return;
+ if (filename == nullptr) return;
FioOpenFile(SOUND_SLOT, filename, BASESET_DIR);
size_t pos = FioGetPos();
@@ -110,7 +110,7 @@ static void OpenBankFile(const char *filename)
static bool SetBankSource(MixerChannel *mc, const SoundEntry *sound)
{
- assert(sound != NULL);
+ assert(sound != nullptr);
/* Check for valid sound size. */
if (sound->file_size == 0 || sound->file_size > ((size_t)-1) - 2) return false;
@@ -162,7 +162,7 @@ static void StartSound(SoundID sound_id, float pan, uint volume)
if (volume == 0) return;
SoundEntry *sound = GetSound(sound_id);
- if (sound == NULL) return;
+ if (sound == nullptr) return;
/* NewGRF sound that wasn't loaded yet? */
if (sound->rate == 0 && sound->file_slot != 0) {
@@ -177,7 +177,7 @@ static void StartSound(SoundID sound_id, float pan, uint volume)
if (sound->rate == 0) return;
MixerChannel *mc = MxAllocateChannel();
- if (mc == NULL) return;
+ if (mc == nullptr) return;
if (!SetBankSource(mc, sound)) return;
@@ -244,7 +244,7 @@ static void SndPlayScreenCoordFx(SoundID sound, int left, int right, int top, in
FOR_ALL_WINDOWS_FROM_BACK(w) {
const ViewPort *vp = w->viewport;
- if (vp != NULL &&
+ if (vp != nullptr &&
left < vp->virtual_left + vp->virtual_width && right > vp->virtual_left &&
top < vp->virtual_top + vp->virtual_height && bottom > vp->virtual_top) {
int screen_x = (left + right) / 2 - vp->virtual_left;
@@ -304,14 +304,14 @@ template <class Tbase_set>
template <class Tbase_set>
/* static */ bool BaseMedia<Tbase_set>::DetermineBestSet()
{
- if (BaseMedia<Tbase_set>::used_set != NULL) return true;
+ if (BaseMedia<Tbase_set>::used_set != nullptr) return true;
- const Tbase_set *best = NULL;
- for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) {
+ const Tbase_set *best = nullptr;
+ for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != nullptr; c = c->next) {
/* Skip unusable sets */
if (c->GetNumMissing() != 0) continue;
- if (best == NULL ||
+ if (best == nullptr ||
(best->fallback && !c->fallback) ||
best->valid_files < c->valid_files ||
(best->valid_files == c->valid_files &&
@@ -321,6 +321,6 @@ template <class Tbase_set>
}
BaseMedia<Tbase_set>::used_set = best;
- return BaseMedia<Tbase_set>::used_set != NULL;
+ return BaseMedia<Tbase_set>::used_set != nullptr;
}
diff --git a/src/sound/allegro_s.cpp b/src/sound/allegro_s.cpp
index 88a723ff8..f6bb96306 100644
--- a/src/sound/allegro_s.cpp
+++ b/src/sound/allegro_s.cpp
@@ -22,18 +22,18 @@
static FSoundDriver_Allegro iFSoundDriver_Allegro;
/** The stream we are writing too */
-static AUDIOSTREAM *_stream = NULL;
+static AUDIOSTREAM *_stream = nullptr;
/** The number of samples in the buffer */
static int _buffer_size;
void SoundDriver_Allegro::MainLoop()
{
/* We haven't opened a stream yet */
- if (_stream == NULL) return;
+ if (_stream == nullptr) return;
void *data = get_audio_stream_buffer(_stream);
/* We don't have to fill the stream yet */
- if (data == NULL) return;
+ if (data == nullptr) return;
/* Mix the samples */
MxMixSamples(data, _buffer_size);
@@ -54,14 +54,14 @@ extern int _allegro_instance_count;
const char *SoundDriver_Allegro::Start(const char * const *parm)
{
- if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) {
+ if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) {
DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
return "Failed to set up Allegro";
}
_allegro_instance_count++;
/* Initialise the sound */
- if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) {
+ if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, nullptr) != 0) {
DEBUG(driver, 0, "allegro: install_sound failed '%s'", allegro_error);
return "Failed to set up Allegro sound";
}
@@ -76,14 +76,14 @@ const char *SoundDriver_Allegro::Start(const char * const *parm)
_buffer_size = GetDriverParamInt(parm, "samples", 1024) * hz / 11025;
_stream = play_audio_stream(_buffer_size, 16, true, hz, 255, 128);
MxInitialize(hz);
- return NULL;
+ return nullptr;
}
void SoundDriver_Allegro::Stop()
{
- if (_stream != NULL) {
+ if (_stream != nullptr) {
stop_audio_stream(_stream);
- _stream = NULL;
+ _stream = nullptr;
}
remove_sound();
diff --git a/src/sound/cocoa_s.cpp b/src/sound/cocoa_s.cpp
index 8133bf62f..13fe176f5 100644
--- a/src/sound/cocoa_s.cpp
+++ b/src/sound/cocoa_s.cpp
@@ -80,9 +80,9 @@ const char *SoundDriver_Cocoa::Start(const char * const *parm)
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
- AudioComponent comp = AudioComponentFindNext (NULL, &desc);
- if (comp == NULL) {
- return "cocoa_s: Failed to start CoreAudio: AudioComponentFindNext returned NULL";
+ AudioComponent comp = AudioComponentFindNext (nullptr, &desc);
+ if (comp == nullptr) {
+ return "cocoa_s: Failed to start CoreAudio: AudioComponentFindNext returned nullptr";
}
/* Open & initialize the default output audio unit */
@@ -101,9 +101,9 @@ const char *SoundDriver_Cocoa::Start(const char * const *parm)
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
- Component comp = FindNextComponent (NULL, &desc);
- if (comp == NULL) {
- return "cocoa_s: Failed to start CoreAudio: FindNextComponent returned NULL";
+ Component comp = FindNextComponent (nullptr, &desc);
+ if (comp == nullptr) {
+ return "cocoa_s: Failed to start CoreAudio: FindNextComponent returned nullptr";
}
/* Open & initialize the default output audio unit */
@@ -126,7 +126,7 @@ const char *SoundDriver_Cocoa::Start(const char * const *parm)
/* Set the audio callback */
callback.inputProc = audioCallback;
- callback.inputProcRefCon = NULL;
+ callback.inputProcRefCon = nullptr;
if (AudioUnitSetProperty(_outputAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof(callback)) != noErr) {
return "cocoa_s: Failed to start CoreAudio: AudioUnitSetProperty (kAudioUnitProperty_SetRenderCallback)";
}
@@ -137,7 +137,7 @@ const char *SoundDriver_Cocoa::Start(const char * const *parm)
}
/* We're running! */
- return NULL;
+ return nullptr;
}
diff --git a/src/sound/null_s.h b/src/sound/null_s.h
index ca9adb546..e1e2ad460 100644
--- a/src/sound/null_s.h
+++ b/src/sound/null_s.h
@@ -17,7 +17,7 @@
/** Implementation of the null sound driver. */
class SoundDriver_Null : public SoundDriver {
public:
- const char *Start(const char * const *param) override { return NULL; }
+ const char *Start(const char * const *param) override { return nullptr; }
void Stop() override { }
const char *GetName() const override { return "null"; }
diff --git a/src/sound/sdl_s.cpp b/src/sound/sdl_s.cpp
index b37016c24..f8041aa84 100644
--- a/src/sound/sdl_s.cpp
+++ b/src/sound/sdl_s.cpp
@@ -54,7 +54,7 @@ const char *SoundDriver_SDL::Start(const char * const *parm)
MxInitialize(spec.freq);
SDL_OpenAudio(&spec, &spec);
SDL_PauseAudio(0);
- return NULL;
+ return nullptr;
}
void SoundDriver_SDL::Stop()
diff --git a/src/sound/win32_s.cpp b/src/sound/win32_s.cpp
index 493ed7fc1..d16e5be2d 100644
--- a/src/sound/win32_s.cpp
+++ b/src/sound/win32_s.cpp
@@ -50,12 +50,12 @@ static DWORD WINAPI SoundThread(LPVOID arg)
if ((hdr->dwFlags & WHDR_INQUEUE) != 0) continue;
MxMixSamples(hdr->lpData, hdr->dwBufferLength / 4);
if (waveOutWrite(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR) {
- MessageBox(NULL, _T("Sounds are disabled until restart."), _T("waveOutWrite failed"), MB_ICONINFORMATION);
+ MessageBox(nullptr, _T("Sounds are disabled until restart."), _T("waveOutWrite failed"), MB_ICONINFORMATION);
return 0;
}
}
WaitForSingleObject(_event, INFINITE);
- } while (_waveout != NULL);
+ } while (_waveout != nullptr);
return 0;
}
@@ -75,7 +75,7 @@ const char *SoundDriver_Win32::Start(const char * const *parm)
_bufsize = min(_bufsize, UINT16_MAX);
try {
- if (NULL == (_event = CreateEvent(NULL, FALSE, FALSE, NULL))) throw "Failed to create event";
+ if (nullptr == (_event = CreateEvent(nullptr, FALSE, FALSE, nullptr))) throw "Failed to create event";
if (waveOutOpen(&_waveout, WAVE_MAPPER, &wfex, (DWORD_PTR)_event, 0, CALLBACK_EVENT) != MMSYSERR_NOERROR) throw "waveOutOpen failed";
@@ -84,13 +84,13 @@ const char *SoundDriver_Win32::Start(const char * const *parm)
PrepareHeader(&_wave_hdr[0]);
PrepareHeader(&_wave_hdr[1]);
- if (NULL == (_thread = CreateThread(NULL, 8192, SoundThread, 0, 0, &_threadId))) throw "Failed to create thread";
+ if (nullptr == (_thread = CreateThread(nullptr, 8192, SoundThread, 0, 0, &_threadId))) throw "Failed to create thread";
} catch (const char *error) {
this->Stop();
return error;
}
- return NULL;
+ return nullptr;
}
void SoundDriver_Win32::Stop()
@@ -98,7 +98,7 @@ void SoundDriver_Win32::Stop()
HWAVEOUT waveout = _waveout;
/* Stop the sound thread. */
- _waveout = NULL;
+ _waveout = nullptr;
SetEvent(_event);
WaitForSingleObject(_thread, INFINITE);
diff --git a/src/sound/xaudio2_s.cpp b/src/sound/xaudio2_s.cpp
index 60311ced2..2acfd20a3 100644
--- a/src/sound/xaudio2_s.cpp
+++ b/src/sound/xaudio2_s.cpp
@@ -125,7 +125,7 @@ static StreamingVoiceContext* _voice_context = nullptr;
* Initialises the XAudio2 driver.
*
* @param parm Driver parameters.
-* @return An error message if unsuccessful, or NULL otherwise.
+* @return An error message if unsuccessful, or nullptr otherwise.
*
*/
const char *SoundDriver_XAudio2::Start(const char * const *parm)
@@ -140,7 +140,7 @@ const char *SoundDriver_XAudio2::Start(const char * const *parm)
_xaudio_dll_handle = LoadLibraryA(XAUDIO2_DLL_A);
- if (_xaudio_dll_handle == NULL)
+ if (_xaudio_dll_handle == nullptr)
{
CoUninitialize();
@@ -150,7 +150,7 @@ const char *SoundDriver_XAudio2::Start(const char * const *parm)
API_XAudio2Create xAudio2Create = (API_XAudio2Create) GetProcAddress(_xaudio_dll_handle, "XAudio2Create");
- if (xAudio2Create == NULL)
+ if (xAudio2Create == nullptr)
{
FreeLibrary(_xaudio_dll_handle);
CoUninitialize();
@@ -248,7 +248,7 @@ const char *SoundDriver_XAudio2::Start(const char * const *parm)
return "Failed to submit the first audio buffer";
}
- return NULL;
+ return nullptr;
}
/**
diff --git a/src/sprite.cpp b/src/sprite.cpp
index 22210712a..26b4c4869 100644
--- a/src/sprite.cpp
+++ b/src/sprite.cpp
@@ -75,7 +75,7 @@ void DrawCommonTileSeq(const TileInfo *ti, const DrawTileSprites *dts, Transpare
SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
pal = PALETTE_TO_TRANSPARENT;
}
- DrawGroundSprite(image, pal, NULL, offs_x, offs_y);
+ DrawGroundSprite(image, pal, nullptr, offs_x, offs_y);
}
}
}
diff --git a/src/spritecache.cpp b/src/spritecache.cpp
index 8a5a25ac0..bed8c42e3 100644
--- a/src/spritecache.cpp
+++ b/src/spritecache.cpp
@@ -44,7 +44,7 @@ struct SpriteCache {
static uint _spritecache_items = 0;
-static SpriteCache *_spritecache = NULL;
+static SpriteCache *_spritecache = nullptr;
static inline SpriteCache *GetSpriteCache(uint index)
@@ -424,7 +424,7 @@ static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_ty
}
if (sprite_avail == 0) {
- if (sprite_type == ST_MAPGEN) return NULL;
+ if (sprite_type == ST_MAPGEN) return nullptr;
if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator);
}
@@ -535,7 +535,7 @@ bool LoadNextSprite(int load_index, byte file_slot, uint file_sprite_id, byte co
byte grf_type = FioReadByte();
SpriteType type;
- void *data = NULL;
+ void *data = nullptr;
if (grf_type == 0xFF) {
/* Some NewGRF files have "empty" pseudo-sprites which are 1
* byte long. Catch these so the sprites won't be displayed. */
@@ -595,7 +595,7 @@ void DupSprite(SpriteID old_spr, SpriteID new_spr)
scnew->file_slot = scold->file_slot;
scnew->file_pos = scold->file_pos;
- scnew->ptr = NULL;
+ scnew->ptr = nullptr;
scnew->id = scold->id;
scnew->type = scold->type;
scnew->warned = false;
@@ -643,7 +643,7 @@ void IncreaseSpriteLRU()
for (i = 0; i != _spritecache_items; i++) {
SpriteCache *sc = GetSpriteCache(i);
- if (sc->ptr != NULL) {
+ if (sc->ptr != nullptr) {
if (sc->lru >= 0) {
sc->lru = -1;
} else if (sc->lru != -32768) {
@@ -715,7 +715,7 @@ static void DeleteEntryFromSpriteCache(uint item)
MemBlock *s = (MemBlock*)GetSpriteCache(item)->ptr - 1;
assert(!(s->size & S_FREE_MASK));
s->size |= S_FREE_MASK;
- GetSpriteCache(item)->ptr = NULL;
+ GetSpriteCache(item)->ptr = nullptr;
/* And coalesce adjacent free blocks */
for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
@@ -737,7 +737,7 @@ static void DeleteEntryFromSpriteCache()
cur_lru = 0xffff;
for (SpriteID i = 0; i != _spritecache_items; i++) {
SpriteCache *sc = GetSpriteCache(i);
- if (sc->type != ST_RECOLOUR && sc->ptr != NULL && sc->lru < cur_lru) {
+ if (sc->type != ST_RECOLOUR && sc->ptr != nullptr && sc->lru < cur_lru) {
cur_lru = sc->lru;
best = i;
}
@@ -807,7 +807,7 @@ static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, S
SpriteType available = sc->type;
if (requested == ST_FONT && available == ST_NORMAL) {
- if (sc->ptr == NULL) sc->type = ST_FONT;
+ if (sc->ptr == nullptr) sc->type = ST_FONT;
return GetRawSprite(sprite, sc->type, allocator);
}
@@ -837,7 +837,7 @@ static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, S
* If the sprite is not available or of wrong type, a fallback sprite is returned.
* @param sprite Sprite to read.
* @param type Expected sprite type.
- * @param allocator Allocator function to use. Set to NULL to use the usual sprite cache.
+ * @param allocator Allocator function to use. Set to nullptr to use the usual sprite cache.
* @return Sprite raw data
*/
void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator)
@@ -856,14 +856,14 @@ void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator)
if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc, allocator);
- if (allocator == NULL) {
+ if (allocator == nullptr) {
/* Load sprite into/from spritecache */
/* Update LRU */
sc->lru = ++_sprite_lru_counter;
/* Load the sprite, if it is not loaded, yet */
- if (sc->ptr == NULL) sc->ptr = ReadSprite(sc, sprite, type, AllocSprite);
+ if (sc->ptr == nullptr) sc->ptr = ReadSprite(sc, sprite, type, AllocSprite);
return sc->ptr;
} else {
@@ -882,7 +882,7 @@ static void GfxInitSpriteCache()
/* Remember 'target_size' from the previous allocation attempt, so we do not try to reach the target_size multiple times in case of failure. */
static uint last_alloc_attempt = 0;
- if (_spritecache_ptr == NULL || (_allocated_sprite_cache_size != target_size && target_size != last_alloc_attempt)) {
+ if (_spritecache_ptr == nullptr || (_allocated_sprite_cache_size != target_size && target_size != last_alloc_attempt)) {
delete[] reinterpret_cast<byte *>(_spritecache_ptr);
last_alloc_attempt = target_size;
@@ -893,10 +893,10 @@ static void GfxInitSpriteCache()
/* Try to allocate 50% more to make sure we do not allocate almost all available. */
_spritecache_ptr = reinterpret_cast<MemBlock *>(new byte[_allocated_sprite_cache_size + _allocated_sprite_cache_size / 2]);
} catch (std::bad_alloc &) {
- _spritecache_ptr = NULL;
+ _spritecache_ptr = nullptr;
}
- if (_spritecache_ptr != NULL) {
+ if (_spritecache_ptr != nullptr) {
/* Allocation succeeded, but we wanted less. */
delete[] reinterpret_cast<byte *>(_spritecache_ptr);
_spritecache_ptr = reinterpret_cast<MemBlock *>(new byte[_allocated_sprite_cache_size]);
@@ -906,7 +906,7 @@ static void GfxInitSpriteCache()
/* Try again to allocate half. */
_allocated_sprite_cache_size >>= 1;
}
- } while (_spritecache_ptr == NULL);
+ } while (_spritecache_ptr == nullptr);
if (_allocated_sprite_cache_size != target_size) {
DEBUG(misc, 0, "Not enough memory to allocate %d MiB of spritecache. Spritecache was reduced to %d MiB.", target_size / 1024 / 1024, _allocated_sprite_cache_size / 1024 / 1024);
@@ -931,7 +931,7 @@ void GfxInitSpriteMem()
/* Reset the spritecache 'pool' */
free(_spritecache);
_spritecache_items = 0;
- _spritecache = NULL;
+ _spritecache = nullptr;
_compact_cache_counter = 0;
}
@@ -945,7 +945,7 @@ void GfxClearSpriteCache()
/* Clear sprite ptr for all cached items */
for (uint i = 0; i != _spritecache_items; i++) {
SpriteCache *sc = GetSpriteCache(i);
- if (sc->type != ST_RECOLOUR && sc->ptr != NULL) DeleteEntryFromSpriteCache(i);
+ if (sc->type != ST_RECOLOUR && sc->ptr != nullptr) DeleteEntryFromSpriteCache(i);
}
}
diff --git a/src/spritecache.h b/src/spritecache.h
index 801310518..f718e687b 100644
--- a/src/spritecache.h
+++ b/src/spritecache.h
@@ -27,7 +27,7 @@ extern uint _sprite_cache_size;
typedef void *AllocatorProc(size_t size);
-void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator = NULL);
+void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator = nullptr);
bool SpriteExists(SpriteID sprite);
SpriteType GetSpriteType(SpriteID sprite);
diff --git a/src/station.cpp b/src/station.cpp
index 6f10806a4..b211c6422 100644
--- a/src/station.cpp
+++ b/src/station.cpp
@@ -108,7 +108,7 @@ Station::~Station()
for (CargoID c = 0; c < NUM_CARGO; ++c) {
LinkGraph *lg = LinkGraph::GetIfValid(this->goods[c].link_graph);
- if (lg == NULL) continue;
+ if (lg == nullptr) continue;
for (NodeID node = 0; node < lg->Size(); ++node) {
Station *st = Station::Get((*lg)[node].Station());
@@ -187,7 +187,7 @@ RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
{
RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
- for (; rs != NULL; rs = rs->next) {
+ for (; rs != nullptr; rs = rs->next) {
/* The vehicle cannot go to this roadstop (different roadtype) */
if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
/* The vehicle is articulated and can therefore not go to a standard road stop. */
@@ -326,13 +326,13 @@ uint Station::GetCatchmentRadius() const
uint ret = CA_NONE;
if (_settings_game.station.modified_catchment) {
- if (this->bus_stops != NULL) ret = max<uint>(ret, CA_BUS);
- if (this->truck_stops != NULL) ret = max<uint>(ret, CA_TRUCK);
+ if (this->bus_stops != nullptr) ret = max<uint>(ret, CA_BUS);
+ if (this->truck_stops != nullptr) ret = max<uint>(ret, CA_TRUCK);
if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
if (this->dock_tile != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
if (this->airport.tile != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
} else {
- if (this->bus_stops != NULL || this->truck_stops != NULL || this->train_station.tile != INVALID_TILE || this->dock_tile != INVALID_TILE || this->airport.tile != INVALID_TILE) {
+ if (this->bus_stops != nullptr || this->truck_stops != nullptr || this->train_station.tile != INVALID_TILE || this->dock_tile != INVALID_TILE || this->airport.tile != INVALID_TILE) {
ret = CA_UNMODIFIED;
}
}
@@ -423,7 +423,7 @@ void Station::RecomputeCatchment()
}
this->catchment_tiles.Initialize(GetCatchmentRect());
- if (!_settings_game.station.serve_neutral_industries && this->industry != NULL) {
+ if (!_settings_game.station.serve_neutral_industries && this->industry != nullptr) {
/* Station is associated with an industry, so we only need to deliver to that industry. */
TILE_AREA_LOOP(tile, this->industry->location) {
if (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == this->industry->index) {
@@ -464,7 +464,7 @@ void Station::RecomputeCatchment()
Industry *i = Industry::GetByTile(tile);
/* Ignore industry if it has a neutral station. It already can't be this station. */
- if (!_settings_game.station.serve_neutral_industries && i->neutral_station != NULL) continue;
+ if (!_settings_game.station.serve_neutral_industries && i->neutral_station != nullptr) continue;
i->stations_near.insert(this);
diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp
index 873be3be5..acffe113d 100644
--- a/src/station_cmd.cpp
+++ b/src/station_cmd.cpp
@@ -117,7 +117,7 @@ CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID c
}
}
}
- *st = (closest_station == INVALID_STATION) ? NULL : T::Get(closest_station);
+ *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
return CommandCost();
}
@@ -356,13 +356,13 @@ static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming n
/**
* Find the closest deleted station of the current company
* @param tile the tile to search from.
- * @return the closest station or NULL if too far.
+ * @return the closest station or nullptr if too far.
*/
static Station *GetClosestDeletedStation(TileIndex tile)
{
uint threshold = 8;
- Station *best_station = NULL;
+ Station *best_station = nullptr;
ForAllStationsRadius(tile, threshold, [&](Station *st) {
if (!st->IsInUse() && st->owner == _current_company) {
uint cur_dist = DistanceManhattan(tile, st->xy);
@@ -370,7 +370,7 @@ static Station *GetClosestDeletedStation(TileIndex tile)
if (cur_dist < threshold) {
threshold = cur_dist;
best_station = st;
- } else if (cur_dist == threshold && best_station != NULL) {
+ } else if (cur_dist == threshold && best_station != nullptr) {
/* In case of a tie, lowest station ID wins */
if (st->index < best_station->index) best_station = st;
}
@@ -528,7 +528,7 @@ CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
for (IndustryID industry : industries) {
const Industry *i = Industry::Get(industry);
/* Skip industry with neutral station */
- if (i->neutral_station != NULL && !_settings_game.station.serve_neutral_industries) continue;
+ if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
CargoID cargo = i->produced_cargo[j];
@@ -545,13 +545,13 @@ CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
* @param w X extent of area
* @param h Y extent of area
* @param rad Search radius in addition to given area
- * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
- * @param ind Industry associated with neutral station (e.g. oil rig) or NULL
+ * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
+ * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
*/
CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, CargoTypes *always_accepted)
{
CargoArray acceptance;
- if (always_accepted != NULL) *always_accepted = 0;
+ if (always_accepted != nullptr) *always_accepted = 0;
int x = TileX(tile);
int y = TileY(tile);
@@ -573,7 +573,7 @@ CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, Cargo
TileIndex tile = TileXY(xc, yc);
/* Ignore industry if it has a neutral station. */
- if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != NULL) continue;
+ if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
AddAcceptedCargo(tile, acceptance, always_accepted);
}
@@ -585,12 +585,12 @@ CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, Cargo
/**
* Get the acceptance of cargoes around the station in.
* @param st Station to get acceptance of.
- * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be NULL
+ * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
*/
static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
{
CargoArray acceptance;
- if (always_accepted != NULL) *always_accepted = 0;
+ if (always_accepted != nullptr) *always_accepted = 0;
BitmapTileIterator it(st->catchment_tiles);
for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
@@ -712,9 +712,9 @@ static void UpdateStationSignCoord(BaseStation *st)
static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
{
/* Find a deleted station close to us */
- if (*st == NULL && reuse) *st = GetClosestDeletedStation(area.tile);
+ if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
- if (*st != NULL) {
+ if (*st != nullptr) {
if ((*st)->owner != _current_company) {
return_cmd_error(CMD_ERROR);
}
@@ -894,7 +894,7 @@ static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag fl
uint invalid_dirs = 5 << axis;
const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
- bool slope_cb = statspec != NULL && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
+ bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
TILE_AREA_LOOP(tile_cur, tile_area) {
CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
@@ -910,7 +910,7 @@ static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag fl
/* if station is set, then we have special handling to allow building on top of already existing stations.
* so station points to INVALID_STATION if we can build on any station.
* Or it points to a station if we're only allowed to build on exactly that station. */
- if (station != NULL && IsTileType(tile_cur, MP_STATION)) {
+ if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
if (!IsRailStation(tile_cur)) {
return ClearTile_Station(tile_cur, DC_AUTO); // get error message
} else {
@@ -941,7 +941,7 @@ static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag fl
/* Check for trains having a reservation for this tile. */
if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
Train *v = GetTrainForReservation(tile_cur, track);
- if (v != NULL) {
+ if (v != nullptr) {
affected_vehicles.push_back(v);
}
}
@@ -986,7 +986,7 @@ static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags
/* If station is set, then we have special handling to allow building on top of already existing stations.
* Station points to INVALID_STATION if we can build on any station.
* Or it points to a station if we're only allowed to build on exactly that station. */
- if (station != NULL && IsTileType(cur_tile, MP_STATION)) {
+ if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
if (!IsRoadStop(cur_tile)) {
return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
} else {
@@ -1125,7 +1125,7 @@ static inline byte *CreateMulti(byte *layout, int n, byte b)
*/
void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
{
- if (statspec != NULL && statspec->lengths >= plat_len &&
+ if (statspec != nullptr && statspec->lengths >= plat_len &&
statspec->platforms[plat_len - 1] >= numtracks &&
statspec->layouts[plat_len - 1][numtracks - 1]) {
/* Custom layout defined, follow it. */
@@ -1161,7 +1161,7 @@ void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSp
template <class T, StringID error_message>
CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
{
- assert(*st == NULL);
+ assert(*st == nullptr);
bool check_surrounding = true;
if (_settings_game.station.adjacent_stations) {
@@ -1174,7 +1174,7 @@ CommandCost FindJoiningBaseStation(StationID existing_station, StationID station
/* Extend the current station, and don't check whether it will
* be near any other stations. */
*st = T::GetIfValid(existing_station);
- check_surrounding = (*st == NULL);
+ check_surrounding = (*st == nullptr);
}
} else {
/* There's no station here. Don't check the tiles surrounding this
@@ -1190,7 +1190,7 @@ CommandCost FindJoiningBaseStation(StationID existing_station, StationID station
}
/* Distant join */
- if (*st == NULL && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
+ if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
return CommandCost();
}
@@ -1318,14 +1318,14 @@ CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32
cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
- Station *st = NULL;
+ Station *st = nullptr;
ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
if (ret.Failed()) return ret;
ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
if (ret.Failed()) return ret;
- if (st != NULL && st->train_station.tile != INVALID_TILE) {
+ if (st != nullptr && st->train_station.tile != INVALID_TILE) {
CommandCost ret = CanExpandRailStation(st, new_location, axis);
if (ret.Failed()) return ret;
}
@@ -1335,7 +1335,7 @@ CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32
int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
- if (statspec != NULL) {
+ if (statspec != nullptr) {
/* Perform NewStation checks */
/* Check if the station size is permitted */
@@ -1345,7 +1345,7 @@ CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32
/* Check if the station is buildable */
if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
- uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE);
+ uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
}
}
@@ -1361,7 +1361,7 @@ CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32
st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
- if (statspec != NULL) {
+ if (statspec != nullptr) {
/* Include this station spec's animation trigger bitmask
* in the station's cached copy. */
st->cached_anim_triggers |= statspec->animation.triggers;
@@ -1385,7 +1385,7 @@ CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32
if (IsRailStationTile(tile) && HasStationReservation(tile)) {
/* Check for trains having a reservation for this tile. */
Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
- if (v != NULL) {
+ if (v != nullptr) {
affected_vehicles.push_back(v);
FreeTrainReservation(v);
}
@@ -1411,12 +1411,12 @@ CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32
if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
c->infrastructure.station++;
- if (statspec != NULL) {
+ if (statspec != nullptr) {
/* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
/* As the station is not yet completely finished, the station does not yet exist. */
- uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
+ uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
if (callback != CALLBACK_FAILED) {
if (callback < 8) {
SetStationGfx(tile, (callback & ~1) + axis);
@@ -1569,7 +1569,7 @@ CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_st
/* Check ownership of station */
T *st = T::GetByTile(tile);
- if (st == NULL) continue;
+ if (st == nullptr) continue;
if (_current_company != OWNER_WATER) {
CommandCost ret = CheckOwnership(st->owner);
@@ -1592,11 +1592,11 @@ CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_st
Track track = GetRailStationTrack(tile);
Owner owner = GetTileOwner(tile);
RailType rt = GetRailType(tile);
- Train *v = NULL;
+ Train *v = nullptr;
if (HasStationReservation(tile)) {
v = GetTrainForReservation(tile, track);
- if (v != NULL) FreeTrainReservation(v);
+ if (v != nullptr) FreeTrainReservation(v);
}
bool build_rail = keep_rail && !IsStationTileBlocked(tile);
@@ -1616,7 +1616,7 @@ CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_st
include(affected_stations, st);
- if (v != NULL) RestoreTrainReservation(v);
+ if (v != nullptr) RestoreTrainReservation(v);
}
}
@@ -1784,13 +1784,13 @@ static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
{
RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
- if (*primary_stop == NULL) {
+ if (*primary_stop == nullptr) {
/* we have no roadstop of the type yet, so write a "primary stop" */
return primary_stop;
} else {
/* there are stops already, so append to the end of the list */
RoadStop *stop = *primary_stop;
- while (stop->next != NULL) stop = stop->next;
+ while (stop->next != nullptr) stop = stop->next;
return &stop->next;
}
}
@@ -1878,7 +1878,7 @@ CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (ret.Failed()) return ret;
cost.AddCost(ret);
- Station *st = NULL;
+ Station *st = nullptr;
ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 5), roadstop_area, &st);
if (ret.Failed()) return ret;
@@ -1922,7 +1922,7 @@ CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, cur_rts | rts) {
Company *c = Company::GetIfValid(rt == ROADTYPE_ROAD ? road_owner : tram_owner);
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.road[rt] += 2 - (IsNormalRoadTile(cur_tile) && HasBit(cur_rts, rt) ? CountBits(GetRoadBits(cur_tile, rt)) : 0);
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -1941,7 +1941,7 @@ CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
}
}
- if (st != NULL) {
+ if (st != nullptr) {
st->AfterStationTileSetChange(true, type ? STATION_TRUCK: STATION_BUS);
}
return cost;
@@ -1961,7 +1961,7 @@ static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
}
- return NULL;
+ return nullptr;
}
@@ -1992,12 +1992,12 @@ static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
}
- assert(cur_stop != NULL);
+ assert(cur_stop != nullptr);
/* don't do the check for drive-through road stops when company bankrupts */
if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
/* remove the 'going through road stop' status from all vehicles on that tile */
- if (flags & DC_EXEC) FindVehicleOnPos(tile, NULL, &ClearRoadStopStatusEnum);
+ if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
} else {
CommandCost ret = EnsureNoVehicleOnGround(tile);
if (ret.Failed()) return ret;
@@ -2008,7 +2008,7 @@ static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
/* removed the first stop in the list */
*primary_stop = cur_stop->next;
/* removed the only stop? */
- if (*primary_stop == NULL) {
+ if (*primary_stop == nullptr) {
st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
}
} else {
@@ -2022,7 +2022,7 @@ static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.road[rt] -= 2;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -2055,10 +2055,10 @@ static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
/* Update the tile area of the truck/bus stop */
if (is_truck) {
st->truck_station.Clear();
- for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) st->truck_station.Add(rs->xy);
+ for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
} else {
st->bus_station.Clear();
- for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) st->bus_station.Add(rs->xy);
+ for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
}
}
@@ -2131,7 +2131,7 @@ CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, rts) {
Company *c = Company::GetIfValid(GetRoadOwner(cur_tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.road[rt] += CountBits(road_bits);
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -2198,7 +2198,7 @@ uint8 GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
*/
Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it, uint &mindist)
{
- Town *t, *nearest = NULL;
+ Town *t, *nearest = nullptr;
uint add = as->size_x + as->size_y - 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
mindist = UINT_MAX - add; // prevent overflow
FOR_ALL_TOWNS(t) {
@@ -2291,7 +2291,7 @@ CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
/* Check if local auth would allow a new airport */
StringID authority_refuse_message = STR_NULL;
- Town *authority_refuse_town = NULL;
+ Town *authority_refuse_town = nullptr;
if (_settings_game.economy.station_noise_level) {
/* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
@@ -2317,17 +2317,17 @@ CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
return_cmd_error(authority_refuse_message);
}
- Station *st = NULL;
+ Station *st = nullptr;
ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
if (ret.Failed()) return ret;
/* Distant join */
- if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
+ if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
if (ret.Failed()) return ret;
- if (st != NULL && st->airport.tile != INVALID_TILE) {
+ if (st != nullptr && st->airport.tile != INVALID_TILE) {
return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
}
@@ -2571,17 +2571,17 @@ CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
_dock_w_chk[direction], _dock_h_chk[direction]);
/* middle */
- Station *st = NULL;
+ Station *st = nullptr;
ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
if (ret.Failed()) return ret;
/* Distant join */
- if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
+ if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
if (ret.Failed()) return ret;
- if (st != NULL && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
+ if (st != nullptr && st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
if (flags & DC_EXEC) {
st->dock_tile = tile;
@@ -2671,7 +2671,7 @@ const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
* Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
* If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
* is set to the overlay to draw.
- * @param ti Positional info for the tile to decide snowyness etc. May be NULL.
+ * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
* @param[in,out] ground Groundsprite to draw.
* @param[out] overlay_offset Overlay to draw.
* @return true if overlay can be drawn.
@@ -2712,7 +2712,7 @@ bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrack
return false;
}
- if (ti != NULL) {
+ if (ti != nullptr) {
/* Decide snow/desert from tile */
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
@@ -2734,16 +2734,16 @@ bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrack
static void DrawTile_Station(TileInfo *ti)
{
- const NewGRFSpriteLayout *layout = NULL;
+ const NewGRFSpriteLayout *layout = nullptr;
DrawTileSprites tmp_rail_layout;
- const DrawTileSprites *t = NULL;
+ const DrawTileSprites *t = nullptr;
RoadTypes roadtypes;
int32 total_offset;
- const RailtypeInfo *rti = NULL;
+ const RailtypeInfo *rti = nullptr;
uint32 relocation = 0;
uint32 ground_relocation = 0;
- BaseStation *st = NULL;
- const StationSpec *statspec = NULL;
+ BaseStation *st = nullptr;
+ const StationSpec *statspec = nullptr;
uint tile_layout = 0;
if (HasStationRail(ti->tile)) {
@@ -2756,7 +2756,7 @@ static void DrawTile_Station(TileInfo *ti)
st = BaseStation::GetByTile(ti->tile);
statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
- if (statspec != NULL) {
+ if (statspec != nullptr) {
tile_layout = GetStationGfx(ti->tile);
if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
@@ -2765,11 +2765,11 @@ static void DrawTile_Station(TileInfo *ti)
}
/* Ensure the chosen tile layout is valid for this custom station */
- if (statspec->renderdata != NULL) {
+ if (statspec->renderdata != nullptr) {
layout = &statspec->renderdata[tile_layout < statspec->tiles ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
if (!layout->NeedsPreprocessing()) {
t = layout;
- layout = NULL;
+ layout = nullptr;
}
}
}
@@ -2784,7 +2784,7 @@ static void DrawTile_Station(TileInfo *ti)
gfx = GetAirportGfx(ti->tile);
if (gfx >= NEW_AIRPORTTILE_OFFSET) {
const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
- if (ats->grf_prop.spritegroup[0] != NULL && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
+ if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
return;
}
/* No sprite group (or no valid one) found, meaning no graphics associated.
@@ -2821,11 +2821,11 @@ static void DrawTile_Station(TileInfo *ti)
palette = PALETTE_TO_GREY;
}
- if (layout == NULL && (t == NULL || t->seq == NULL)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
+ if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
/* don't show foundation for docks */
if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
- if (statspec != NULL && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
+ if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
/* Station has custom foundations.
* Check whether the foundation continues beyond the tile's upper sides. */
uint edge_info = 0;
@@ -2912,7 +2912,7 @@ draw_default_foundation:
}
}
} else {
- if (layout != NULL) {
+ if (layout != nullptr) {
/* Sprite layout which needs preprocessing */
bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
@@ -2924,7 +2924,7 @@ draw_default_foundation:
tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
t = &tmp_rail_layout;
total_offset = 0;
- } else if (statspec != NULL) {
+ } else if (statspec != nullptr) {
/* Simple sprite layout */
ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
@@ -2936,7 +2936,7 @@ draw_default_foundation:
SpriteID image = t->ground.sprite;
PaletteID pal = t->ground.pal;
RailTrackOffset overlay_offset;
- if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
+ if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
DrawGroundSprite(image, PAL_NONE);
DrawGroundSprite(ground + overlay_offset, PAL_NONE);
@@ -2979,7 +2979,7 @@ void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, Ro
int32 total_offset = 0;
PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
const DrawTileSprites *t = GetStationTileLayout(st, image);
- const RailtypeInfo *rti = NULL;
+ const RailtypeInfo *rti = nullptr;
if (railtype != INVALID_RAILTYPE) {
rti = GetRailTypeInfo(railtype);
@@ -2988,7 +2988,7 @@ void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, Ro
SpriteID img = t->ground.sprite;
RailTrackOffset overlay_offset;
- if (rti != NULL && rti->UsesOverlay() && SplitGroundSpriteForOverlay(NULL, &img, &overlay_offset)) {
+ if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
DrawSprite(img, PAL_NONE, x, y);
DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
@@ -3044,11 +3044,11 @@ static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
if (HasStationTileRail(tile)) {
const StationSpec *spec = GetStationSpec(tile);
- if (spec != NULL) {
+ if (spec != nullptr) {
td->station_class = StationClass::Get(spec->cls_id)->name;
td->station_name = spec->name;
- if (spec->grf_prop.grffile != NULL) {
+ if (spec->grf_prop.grffile != nullptr) {
const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
td->grf = gc->GetName();
}
@@ -3067,10 +3067,10 @@ static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
td->airport_tile_name = ats->name;
- if (as->grf_prop.grffile != NULL) {
+ if (as->grf_prop.grffile != nullptr) {
const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
td->grf = gc->GetName();
- } else if (ats->grf_prop.grffile != NULL) {
+ } else if (ats->grf_prop.grffile != nullptr) {
const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
td->grf = gc->GetName();
}
@@ -3090,7 +3090,7 @@ static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
const IndustrySpec *is = GetIndustrySpec(i->type);
td->owner[0] = i->owner;
str = is->name;
- if (is->grf_prop.grffile != NULL) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
+ if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
break;
}
case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
@@ -3315,7 +3315,7 @@ static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UIN
ge->cargo.Truncate(amount, &waiting_per_source);
for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
Station *source_station = Station::GetIfValid(i->first);
- if (source_station == NULL) continue;
+ if (source_station == nullptr) continue;
GoodsEntry &source_ge = source_station->goods[cs->Index()];
source_ge.max_waiting_cargo = max(source_ge.max_waiting_cargo, i->second);
@@ -3494,7 +3494,7 @@ void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
/* Reroute cargo staged to be transferred. */
for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
- for (Vehicle *v = *it; v != NULL; v = v->Next()) {
+ for (Vehicle *v = *it; v != nullptr; v = v->Next()) {
if (v->cargo_type != c) continue;
v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
}
@@ -3515,7 +3515,7 @@ void DeleteStaleLinks(Station *from)
const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
GoodsEntry &ge = from->goods[c];
LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
- if (lg == NULL) continue;
+ if (lg == nullptr) continue;
Node node = (*lg)[ge.node];
for (EdgeIterator it(node.Begin()); it != node.End();) {
Edge edge = it->second;
@@ -3535,7 +3535,7 @@ void DeleteStaleLinks(Station *from)
FOR_ALL_ORDER_LISTS(l) {
bool found_from = false;
bool found_to = false;
- for (Order *order = l->GetFirstOrder(); order != NULL; order = order->next) {
+ for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
if (order->GetDestination() == from->index) {
found_from = true;
@@ -3606,7 +3606,7 @@ void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint c
GoodsEntry &ge1 = st->goods[cargo];
Station *st2 = Station::Get(next_station_id);
GoodsEntry &ge2 = st2->goods[cargo];
- LinkGraph *lg = NULL;
+ LinkGraph *lg = nullptr;
if (ge1.link_graph == INVALID_LINK_GRAPH) {
if (ge2.link_graph == INVALID_LINK_GRAPH) {
if (LinkGraph::CanAllocateItem()) {
@@ -3642,7 +3642,7 @@ void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint c
}
}
}
- if (lg != NULL) {
+ if (lg != nullptr) {
(*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, mode);
}
}
@@ -3655,7 +3655,7 @@ void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint c
*/
void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
{
- for (const Vehicle *v = front; v != NULL; v = v->Next()) {
+ for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
if (v->refit_cap > 0) {
/* The cargo count can indeed be higher than the refit_cap if
* wagons have been auto-replaced and subsequently auto-
@@ -3752,7 +3752,7 @@ static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceT
StationID next = ge.GetVia(st->index);
ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
- LinkGraph *lg = NULL;
+ LinkGraph *lg = nullptr;
if (ge.link_graph == INVALID_LINK_GRAPH) {
if (LinkGraph::CanAllocateItem()) {
lg = new LinkGraph(type);
@@ -3765,7 +3765,7 @@ static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceT
} else {
lg = LinkGraph::Get(ge.link_graph);
}
- if (lg != NULL) (*lg)[ge.node].UpdateSupply(amount);
+ if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
if (!ge.HasRating()) {
InvalidateWindowData(WC_STATION_LIST, st->index);
@@ -3786,7 +3786,7 @@ static bool IsUniqueStationName(const char *name)
const Station *st;
FOR_ALL_STATIONS(st) {
- if (st->name != NULL && strcmp(st->name, name) == 0) return false;
+ if (st->name != nullptr && strcmp(st->name, name) == 0) return false;
}
return true;
@@ -3804,7 +3804,7 @@ static bool IsUniqueStationName(const char *name)
CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Station *st = Station::GetIfValid(p1);
- if (st == NULL) return CMD_ERROR;
+ if (st == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(st->owner);
if (ret.Failed()) return ret;
@@ -3818,7 +3818,7 @@ CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (flags & DC_EXEC) {
free(st->name);
- st->name = reset ? NULL : stredup(text);
+ st->name = reset ? nullptr : stredup(text);
st->UpdateVirtCoord();
InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
@@ -3873,10 +3873,10 @@ void FindStationsAroundTiles(const TileArea &location, StationList * const stati
for (StationID stationid : seen_stations) {
Station *st = Station::GetIfValid(stationid);
- if (st == NULL) continue; /* Waypoint */
+ if (st == nullptr) continue; /* Waypoint */
/* Check if station is attached to an industry */
- if (!_settings_game.station.serve_neutral_industries && st->industry != NULL) continue;
+ if (!_settings_game.station.serve_neutral_industries && st->industry != nullptr) continue;
/* Test if the tile is within the station's catchment */
TILE_AREA_LOOP(tile, location) {
@@ -3906,8 +3906,8 @@ uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, Sourc
/* Return if nothing to do. Also the rounding below fails for 0. */
if (amount == 0) return 0;
- Station *st1 = NULL; // Station with best rating
- Station *st2 = NULL; // Second best station
+ Station *st1 = nullptr; // Station with best rating
+ Station *st2 = nullptr; // Second best station
uint best_rating1 = 0; // rating of st1
uint best_rating2 = 0; // rating of st2
@@ -3926,28 +3926,28 @@ uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, Sourc
}
/* This station can be used, add it to st1/st2 */
- if (st1 == NULL || st->goods[type].rating >= best_rating1) {
+ if (st1 == nullptr || st->goods[type].rating >= best_rating1) {
st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
- } else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
+ } else if (st2 == nullptr || st->goods[type].rating >= best_rating2) {
st2 = st; best_rating2 = st->goods[type].rating;
}
}
/* no stations around at all? */
- if (st1 == NULL) return 0;
+ if (st1 == nullptr) return 0;
/* From now we'll calculate with fractal cargo amounts.
* First determine how much cargo we really have. */
amount *= best_rating1 + 1;
- if (st2 == NULL) {
+ if (st2 == nullptr) {
/* only one station around */
return UpdateStationWaiting(st1, type, amount, source_type, source_id);
}
/* several stations around, the best two (highest rating) are in st1 and st2 */
- assert(st1 != NULL);
- assert(st2 != NULL);
+ assert(st1 != nullptr);
+ assert(st2 != nullptr);
assert(best_rating1 != 0 || best_rating2 != 0);
/* Then determine the amount the worst station gets. We do it this way as the
@@ -4598,14 +4598,14 @@ extern const TileTypeProcs _tile_type_station_procs = {
DrawTile_Station, // draw_tile_proc
GetSlopePixelZ_Station, // get_slope_z_proc
ClearTile_Station, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_Station, // get_tile_desc_proc
GetTileTrackStatus_Station, // get_tile_track_status_proc
ClickTile_Station, // click_tile_proc
AnimateTile_Station, // animate_tile_proc
TileLoop_Station, // tile_loop_proc
ChangeTileOwner_Station, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
+ nullptr, // add_produced_cargo_proc
VehicleEnter_Station, // vehicle_enter_tile_proc
GetFoundation_Station, // get_foundation_proc
TerraformTile_Station, // terraform_tile_proc
diff --git a/src/station_func.h b/src/station_func.h
index 34e996d23..bc18b038c 100644
--- a/src/station_func.h
+++ b/src/station_func.h
@@ -29,7 +29,7 @@ void ShowStationViewWindow(StationID station);
void UpdateAllStationVirtCoords();
CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad);
-CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, CargoTypes *always_accepted = NULL);
+CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, CargoTypes *always_accepted = nullptr);
void UpdateStationAcceptance(Station *st, bool show_msg);
diff --git a/src/station_gui.cpp b/src/station_gui.cpp
index edd02d6ae..a3013c847 100644
--- a/src/station_gui.cpp
+++ b/src/station_gui.cpp
@@ -296,7 +296,7 @@ protected:
if (!this->stations.Sort()) return;
/* Reset name sorter sort cache */
- this->last_station = NULL;
+ this->last_station = nullptr;
/* Set the modified widget dirty */
this->SetWidgetDirty(WID_STL_LIST);
@@ -655,7 +655,7 @@ byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_
bool CompanyStationsWindow::include_empty = true;
const CargoTypes CompanyStationsWindow::cargo_filter_max = ALL_CARGOTYPES;
CargoTypes CompanyStationsWindow::cargo_filter = ALL_CARGOTYPES;
-const Station *CompanyStationsWindow::last_station = NULL;
+const Station *CompanyStationsWindow::last_station = nullptr;
/* Available station sorting functions */
GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
@@ -903,9 +903,9 @@ public:
}
/**
- * Retrieve a child for the given station. Return NULL if it doesn't exist.
+ * Retrieve a child for the given station. Return nullptr if it doesn't exist.
* @param station ID of the station the child we're looking for is associated with.
- * @return a child entry for the given station or NULL.
+ * @return a child entry for the given station or nullptr.
*/
CargoDataEntry *Retrieve(StationID station) const
{
@@ -914,9 +914,9 @@ public:
}
/**
- * Retrieve a child for the given cargo. Return NULL if it doesn't exist.
+ * Retrieve a child for the given cargo. Return nullptr if it doesn't exist.
* @param cargo ID of the cargo the child we're looking for is associated with.
- * @return a child entry for the given cargo or NULL.
+ * @return a child entry for the given cargo or nullptr.
*/
CargoDataEntry *Retrieve(CargoID cargo) const
{
@@ -1001,7 +1001,7 @@ private:
};
CargoDataEntry::CargoDataEntry() :
- parent(NULL),
+ parent(nullptr),
station(INVALID_STATION),
num_children(0),
count(0),
@@ -1025,19 +1025,19 @@ CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *pa
{}
CargoDataEntry::CargoDataEntry(StationID station) :
- parent(NULL),
+ parent(nullptr),
station(station),
num_children(0),
count(0),
- children(NULL)
+ children(nullptr)
{}
CargoDataEntry::CargoDataEntry(CargoID cargo) :
- parent(NULL),
+ parent(nullptr),
cargo(cargo),
num_children(0),
count(0),
- children(NULL)
+ children(nullptr)
{}
CargoDataEntry::~CargoDataEntry()
@@ -1051,14 +1051,14 @@ CargoDataEntry::~CargoDataEntry()
*/
void CargoDataEntry::Clear()
{
- if (this->children != NULL) {
+ if (this->children != nullptr) {
for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
assert(*i != this);
delete *i;
}
this->children->clear();
}
- if (this->parent != NULL) this->parent->count -= this->count;
+ if (this->parent != nullptr) this->parent->count -= this->count;
this->count = 0;
this->num_children = 0;
}
@@ -1107,7 +1107,7 @@ CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
void CargoDataEntry::Update(uint count)
{
this->count += count;
- if (this->parent != NULL) this->parent->Update(count);
+ if (this->parent != nullptr) this->parent->Update(count);
}
/**
@@ -1116,7 +1116,7 @@ void CargoDataEntry::Update(uint count)
void CargoDataEntry::IncrementSize()
{
++this->num_children;
- if (this->parent != NULL) this->parent->IncrementSize();
+ if (this->parent != nullptr) this->parent->IncrementSize();
}
void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
@@ -1129,7 +1129,7 @@ void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
{
if (i == this->children->end()) {
- return NULL;
+ return nullptr;
} else {
assert(this->children->value_comp().GetSortType() != ST_COUNT);
return *i;
@@ -1330,7 +1330,7 @@ struct StationViewWindow : public Window {
if (count == 0) return;
bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
const CargoDataEntry *expand = &this->expanded_rows;
- for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
+ for (int i = 0; i < NUM_COLUMNS && expand != nullptr; ++i) {
switch (groupings[i]) {
case GR_CARGO:
assert(i == 0);
@@ -1571,13 +1571,13 @@ struct StationViewWindow : public Window {
StationID next = it.GetKey();
const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
- if (source_entry == NULL) {
+ if (source_entry == nullptr) {
this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
continue;
}
const CargoDataEntry *via_entry = source_entry->Retrieve(next);
- if (via_entry == NULL) {
+ if (via_entry == nullptr) {
this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
continue;
}
@@ -1600,7 +1600,7 @@ struct StationViewWindow : public Window {
{
for (CargoID i = 0; i < NUM_CARGO; i++) {
- if (this->cached_destinations.Retrieve(i) == NULL) {
+ if (this->cached_destinations.Retrieve(i) == nullptr) {
this->RecalcDestinations(i);
}
@@ -1620,13 +1620,13 @@ struct StationViewWindow : public Window {
{
std::list<StationID> stations;
const CargoDataEntry *parent = data->GetParent();
- if (parent->GetParent() == NULL) {
+ if (parent->GetParent() == nullptr) {
this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
return;
}
StationID next = data->GetStation();
- while (parent->GetParent()->GetParent() != NULL) {
+ while (parent->GetParent()->GetParent() != nullptr) {
stations.push_back(parent->GetStation());
parent = parent->GetParent();
}
@@ -1764,7 +1764,7 @@ struct StationViewWindow : public Window {
DrawString(text_left, text_right, y, str);
if (column < NUM_COLUMNS - 1) {
- const char *sym = NULL;
+ const char *sym = nullptr;
if (cd->GetNumChildren() > 0) {
sym = "-";
} else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
@@ -1832,7 +1832,7 @@ struct StationViewWindow : public Window {
const LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
SetDParam(0, cs->name);
- SetDParam(1, lg != NULL ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
+ SetDParam(1, lg != nullptr ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
SetDParam(3, ToPercent8(ge->rating));
DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
@@ -1849,7 +1849,7 @@ struct StationViewWindow : public Window {
template<class Tid>
void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
{
- if (filter->Retrieve(next) != NULL) {
+ if (filter->Retrieve(next) != nullptr) {
filter->Remove(next);
} else {
filter->InsertOrRetrieve(next);
@@ -2048,9 +2048,9 @@ struct StationViewWindow : public Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
- DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
+ DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), nullptr, str);
}
void OnResize() override
@@ -2201,13 +2201,13 @@ static const T *FindStationsNearby(TileArea ta, bool distant_join)
/* Only search tiles where we have a chance to stay within the station spread.
* The complete check needs to be done in the callback as we don't know the
* extent of the found station, yet. */
- if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
+ if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return nullptr;
uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
TileIndex tile = TileAddByDir(ctx.tile, DIR_N);
CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
- return NULL;
+ return nullptr;
}
static const NWidgetPart _nested_select_station_widgets[] = {
@@ -2360,7 +2360,7 @@ static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta)
/* If a window is already opened and we didn't ctrl-click,
* return true (i.e. just flash the old window) */
Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
- if (selection_window != NULL) {
+ if (selection_window != nullptr) {
/* Abort current distant-join and start new one */
delete selection_window;
UpdateTileSelection();
@@ -2376,7 +2376,7 @@ static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta)
* If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
* but join the other station immediately. */
const T *st = FindStationsNearby<T>(ta, false);
- return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.size() == 0);
+ return st == nullptr && (_settings_game.station.adjacent_stations || _stations_nearby_list.size() == 0);
}
/**
diff --git a/src/statusbar_gui.cpp b/src/statusbar_gui.cpp
index 281b4eb98..548fad5f1 100644
--- a/src/statusbar_gui.cpp
+++ b/src/statusbar_gui.cpp
@@ -149,7 +149,7 @@ struct StatusBarWindow : Window {
case WID_S_RIGHT: {
/* Draw company money, if any */
const Company *c = Company::GetIfValid(_local_company);
- if (c != NULL) {
+ if (c != nullptr) {
SetDParam(0, c->money);
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, STR_COMPANY_MONEY, TC_FROMSTRING, SA_HOR_CENTER);
}
@@ -164,7 +164,7 @@ struct StatusBarWindow : Window {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, STR_STATUSBAR_AUTOSAVE, TC_FROMSTRING, SA_HOR_CENTER);
} else if (_pause_mode != PM_UNPAUSED) {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, STR_STATUSBAR_PAUSED, TC_FROMSTRING, SA_HOR_CENTER);
- } else if (this->ticker_scroll < TICKER_STOP && FindWindowById(WC_NEWS_WINDOW, 0) == NULL && _statusbar_news_item != NULL && _statusbar_news_item->string_id != 0) {
+ } else if (this->ticker_scroll < TICKER_STOP && FindWindowById(WC_NEWS_WINDOW, 0) == nullptr && _statusbar_news_item != nullptr && _statusbar_news_item->string_id != 0) {
/* Draw the scrolling news text */
if (!DrawScrollingStatusText(_statusbar_news_item, this->ticker_scroll, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, r.bottom)) {
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED);
@@ -248,7 +248,7 @@ static const NWidgetPart _nested_main_status_widgets[] = {
};
static WindowDesc _main_status_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_STATUS_BAR, WC_NONE,
WDF_NO_FOCUS,
_nested_main_status_widgets, lengthof(_nested_main_status_widgets)
@@ -260,7 +260,7 @@ static WindowDesc _main_status_desc(
bool IsNewsTickerShown()
{
const StatusBarWindow *w = dynamic_cast<StatusBarWindow*>(FindWindowById(WC_STATUS_BAR, 0));
- return w != NULL && w->ticker_scroll < StatusBarWindow::TICKER_STOP;
+ return w != nullptr && w->ticker_scroll < StatusBarWindow::TICKER_STOP;
}
/**
diff --git a/src/story.cpp b/src/story.cpp
index 602dc2724..38faafd2f 100644
--- a/src/story.cpp
+++ b/src/story.cpp
@@ -124,7 +124,7 @@ CommandCost CmdCreateStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, u
s->date = _date;
s->company = company;
if (StrEmpty(text)) {
- s->title = NULL;
+ s->title = nullptr;
} else {
s->title = stredup(text);
}
@@ -241,7 +241,7 @@ CommandCost CmdSetStoryPageTitle(TileIndex tile, DoCommandFlag flags, uint32 p1,
StoryPage *p = StoryPage::Get(page_id);
free(p->title);
if (StrEmpty(text)) {
- p->title = NULL;
+ p->title = nullptr;
} else {
p->title = stredup(text);
}
diff --git a/src/story_base.h b/src/story_base.h
index 3db1ba4a8..139c41dab 100644
--- a/src/story_base.h
+++ b/src/story_base.h
@@ -58,7 +58,7 @@ struct StoryPageElement : StoryPageElementPool::PoolItem<&_story_page_element_po
inline StoryPageElement() { }
/**
- * (Empty) destructor has to be defined else operator delete might be called with NULL parameter
+ * (Empty) destructor has to be defined else operator delete might be called with nullptr parameter
*/
inline ~StoryPageElement() { free(this->text); }
};
@@ -80,7 +80,7 @@ struct StoryPage : StoryPagePool::PoolItem<&_story_page_pool> {
inline StoryPage() { }
/**
- * (Empty) destructor has to be defined else operator delete might be called with NULL parameter
+ * (Empty) destructor has to be defined else operator delete might be called with nullptr parameter
*/
inline ~StoryPage()
{
diff --git a/src/story_gui.cpp b/src/story_gui.cpp
index c90992c6b..944e7bd50 100644
--- a/src/story_gui.cpp
+++ b/src/story_gui.cpp
@@ -81,7 +81,7 @@ protected:
this->story_page_elements.clear();
const StoryPage *p = GetSelPage();
- if (p != NULL) {
+ if (p != nullptr) {
const StoryPageElement *pe;
FOR_ALL_STORY_PAGE_ELEMENTS(pe) {
if (pe->page == p->index) {
@@ -115,11 +115,11 @@ protected:
/**
* Get instance of selected page.
- * @return Instance of selected page or NULL if no page is selected.
+ * @return Instance of selected page or nullptr if no page is selected.
*/
StoryPage *GetSelPage() const
{
- if (!_story_page_pool.IsValidID(selected_page_id)) return NULL;
+ if (!_story_page_pool.IsValidID(selected_page_id)) return nullptr;
return _story_page_pool.Get(selected_page_id);
}
@@ -170,7 +170,7 @@ protected:
{
/* Generate generic title if selected page have no custom title. */
StoryPage *page = this->GetSelPage();
- if (page != NULL && page->title == NULL) {
+ if (page != nullptr && page->title == nullptr) {
SetDParam(0, GetSelPageNum() + 1);
GetString(selected_generic_title, STR_STORY_BOOK_GENERIC_PAGE_ITEM, lastof(selected_generic_title));
}
@@ -193,10 +193,10 @@ protected:
/* Find the last available page which is previous to the current selected page. */
const StoryPage *last_available;
- last_available = NULL;
+ last_available = nullptr;
for (const StoryPage *p : this->story_pages) {
if (p->index == this->selected_page_id) {
- if (last_available == NULL) return; // No previous page available.
+ if (last_available == nullptr) return; // No previous page available.
this->SetSelectedPage(last_available->index);
return;
}
@@ -234,8 +234,8 @@ protected:
uint16 page_num = 1;
for (const StoryPage *p : this->story_pages) {
bool current_page = p->index == this->selected_page_id;
- DropDownListStringItem *item = NULL;
- if (p->title != NULL) {
+ DropDownListStringItem *item = nullptr;
+ if (p->title != nullptr) {
item = new DropDownListCharStringItem(p->title, p->index, current_page);
} else {
/* No custom title => use a generic page title with page number. */
@@ -270,12 +270,12 @@ protected:
uint GetHeadHeight(int max_width) const
{
StoryPage *page = this->GetSelPage();
- if (page == NULL) return 0;
+ if (page == nullptr) return 0;
int height = 0;
/* Title lines */
height += FONT_HEIGHT_NORMAL; // Date always use exactly one line.
- SetDParamStr(0, page->title != NULL ? page->title : this->selected_generic_title);
+ SetDParamStr(0, page->title != nullptr ? page->title : this->selected_generic_title);
height += GetStringHeight(STR_STORY_BOOK_TITLE, max_width);
return height;
@@ -292,7 +292,7 @@ protected:
switch (pe.type) {
case SPET_GOAL: {
Goal *g = Goal::Get((GoalID) pe.referenced_id);
- if (g == NULL) return SPR_IMG_GOAL_BROKEN_REF;
+ if (g == nullptr) return SPR_IMG_GOAL_BROKEN_REF;
return g->completed ? SPR_IMG_GOAL_COMPLETED : SPR_IMG_GOAL;
}
case SPET_LOCATION:
@@ -336,7 +336,7 @@ protected:
uint GetContentHeight()
{
StoryPage *page = this->GetSelPage();
- if (page == NULL) return 0;
+ if (page == nullptr) return 0;
int max_width = GetAvailablePageContentWidth();
uint element_vertical_dist = FONT_HEIGHT_NORMAL;
@@ -458,7 +458,7 @@ public:
switch (widget) {
case WID_SB_SEL_PAGE: {
StoryPage *page = this->GetSelPage();
- SetDParamStr(0, page != NULL && page->title != NULL ? page->title : this->selected_generic_title);
+ SetDParamStr(0, page != nullptr && page->title != nullptr ? page->title : this->selected_generic_title);
break;
}
case WID_SB_CAPTION:
@@ -492,7 +492,7 @@ public:
if (widget != WID_SB_PAGE_PANEL) return;
StoryPage *page = this->GetSelPage();
- if (page == NULL) return;
+ if (page == nullptr) return;
const int x = r.left + WD_FRAMETEXT_LEFT;
const int y = r.top + WD_FRAMETEXT_TOP;
@@ -518,7 +518,7 @@ public:
y_offset += line_height;
/* Title */
- SetDParamStr(0, page->title != NULL ? page->title : this->selected_generic_title);
+ SetDParamStr(0, page->title != nullptr ? page->title : this->selected_generic_title);
y_offset = DrawStringMultiLine(0, right - x, y_offset, bottom - y, STR_STORY_BOOK_TITLE, TC_BLACK, SA_TOP | SA_HOR_CENTER);
/* Page elements */
@@ -533,8 +533,8 @@ public:
case SPET_GOAL: {
Goal *g = Goal::Get((GoalID) pe->referenced_id);
- StringID string_id = g == NULL ? STR_STORY_BOOK_INVALID_GOAL_REF : STR_JUST_RAW_STRING;
- if (g != NULL) SetDParamStr(0, g->text);
+ StringID string_id = g == nullptr ? STR_STORY_BOOK_INVALID_GOAL_REF : STR_JUST_RAW_STRING;
+ if (g != nullptr) SetDParamStr(0, g->text);
DrawActionElement(y_offset, right - x, line_height, GetPageElementSprite(*pe), string_id);
break;
}
@@ -567,7 +567,7 @@ public:
for (uint16 i = 0; i < this->story_pages.size(); i++) {
const StoryPage *s = this->story_pages[i];
- if (s->title != NULL) {
+ if (s->title != nullptr) {
SetDParamStr(0, s->title);
} else {
SetDParamStr(0, this->selected_generic_title);
diff --git a/src/strgen/strgen.cpp b/src/strgen/strgen.cpp
index 5b361430f..a4c9da08e 100644
--- a/src/strgen/strgen.cpp
+++ b/src/strgen/strgen.cpp
@@ -106,7 +106,7 @@ struct FileStringReader : StringReader {
StringReader(data, file, master, translation)
{
this->fh = fopen(file, "rb");
- if (this->fh == NULL) error("Could not open %s", file);
+ if (this->fh == nullptr) error("Could not open %s", file);
}
/** Free/close the file. */
@@ -135,7 +135,7 @@ struct FileStringReader : StringReader {
void FileStringReader::HandlePragma(char *str)
{
if (!memcmp(str, "id ", 3)) {
- this->data.next_string_id = strtoul(str + 3, NULL, 0);
+ this->data.next_string_id = strtoul(str + 3, nullptr, 0);
} else if (!memcmp(str, "name ", 5)) {
strecpy(_lang.name, str + 5, lastof(_lang.name));
} else if (!memcmp(str, "ownname ", 8)) {
@@ -161,14 +161,14 @@ void FileStringReader::HandlePragma(char *str)
strecpy(_lang.digit_decimal_separator, strcmp(str, "{NBSP}") == 0 ? NBSP : str, lastof(_lang.digit_decimal_separator));
} else if (!memcmp(str, "winlangid ", 10)) {
const char *buf = str + 10;
- long langid = strtol(buf, NULL, 16);
+ long langid = strtol(buf, nullptr, 16);
if (langid > (long)UINT16_MAX || langid < 0) {
error("Invalid winlangid %s", buf);
}
_lang.winlangid = (uint16)langid;
} else if (!memcmp(str, "grflangid ", 10)) {
const char *buf = str + 10;
- long langid = strtol(buf, NULL, 16);
+ long langid = strtol(buf, nullptr, 16);
if (langid >= 0x7F || langid < 0) {
error("Invalid grflangid %s", buf);
}
@@ -180,7 +180,7 @@ void FileStringReader::HandlePragma(char *str)
for (;;) {
const char *s = ParseWord(&buf);
- if (s == NULL) break;
+ if (s == nullptr) break;
if (_lang.num_genders >= MAX_NUM_GENDERS) error("Too many genders, max %d", MAX_NUM_GENDERS);
strecpy(_lang.genders[_lang.num_genders], s, lastof(_lang.genders[_lang.num_genders]));
_lang.num_genders++;
@@ -192,7 +192,7 @@ void FileStringReader::HandlePragma(char *str)
for (;;) {
const char *s = ParseWord(&buf);
- if (s == NULL) break;
+ if (s == nullptr) break;
if (_lang.num_cases >= MAX_NUM_CASES) error("Too many cases, max %d", MAX_NUM_CASES);
strecpy(_lang.cases[_lang.num_cases], s, lastof(_lang.cases[_lang.num_cases]));
_lang.num_cases++;
@@ -205,10 +205,10 @@ void FileStringReader::HandlePragma(char *str)
bool CompareFiles(const char *n1, const char *n2)
{
FILE *f2 = fopen(n2, "rb");
- if (f2 == NULL) return false;
+ if (f2 == nullptr) return false;
FILE *f1 = fopen(n1, "rb");
- if (f1 == NULL) {
+ if (f1 == nullptr) {
fclose(f2);
error("can't open %s", n1);
}
@@ -246,7 +246,7 @@ struct FileWriter {
this->filename = stredup(filename);
this->fh = fopen(this->filename, "wb");
- if (this->fh == NULL) {
+ if (this->fh == nullptr) {
error("Could not open %s", this->filename);
}
}
@@ -255,14 +255,14 @@ struct FileWriter {
void Finalise()
{
fclose(this->fh);
- this->fh = NULL;
+ this->fh = nullptr;
}
/** Make sure the file is closed. */
virtual ~FileWriter()
{
/* If we weren't closed an exception was thrown, so remove the temporary file. */
- if (fh != NULL) {
+ if (fh != nullptr) {
fclose(this->fh);
unlink(this->filename);
}
@@ -418,7 +418,7 @@ static const OptionData _opts[] = {
GETOPT_NOVAL( 't', "--todo"),
GETOPT_NOVAL( 'w', "--warning"),
GETOPT_NOVAL( 'h', "--help"),
- GETOPT_GENERAL('h', '?', NULL, ODF_NO_VALUE),
+ GETOPT_GENERAL('h', '?', nullptr, ODF_NO_VALUE),
GETOPT_VALUE( 's', "--source_dir"),
GETOPT_VALUE( 'd', "--dest_dir"),
GETOPT_END(),
@@ -428,7 +428,7 @@ int CDECL main(int argc, char *argv[])
{
char pathbuf[MAX_PATH];
const char *src_dir = ".";
- const char *dest_dir = NULL;
+ const char *dest_dir = nullptr;
GetOptData mgo(argc - 1, argv + 1, _opts);
for (;;) {
@@ -512,7 +512,7 @@ int CDECL main(int argc, char *argv[])
}
}
- if (dest_dir == NULL) dest_dir = src_dir; // if dest_dir is not specified, it equals src_dir
+ if (dest_dir == nullptr) dest_dir = src_dir; // if dest_dir is not specified, it equals src_dir
try {
/* strgen has two modes of operation. If no (free) arguments are passed
@@ -551,17 +551,17 @@ int CDECL main(int argc, char *argv[])
const char *translation = replace_pathsep(mgo.argv[i]);
const char *file = strrchr(translation, PATHSEPCHAR);
- FileStringReader translation_reader(data, translation, false, file == NULL || strcmp(file + 1, "english.txt") != 0);
+ FileStringReader translation_reader(data, translation, false, file == nullptr || strcmp(file + 1, "english.txt") != 0);
translation_reader.ParseFile(); // target file
if (_errors != 0) return 1;
/* get the targetfile, strip any directories and append to destination path */
r = strrchr(mgo.argv[i], PATHSEPCHAR);
- mkpath(pathbuf, lastof(pathbuf), dest_dir, (r != NULL) ? &r[1] : mgo.argv[i]);
+ mkpath(pathbuf, lastof(pathbuf), dest_dir, (r != nullptr) ? &r[1] : mgo.argv[i]);
/* rename the .txt (input-extension) to .lng */
r = strrchr(pathbuf, '.');
- if (r == NULL || strcmp(r, ".txt") != 0) r = strchr(pathbuf, '\0');
+ if (r == nullptr || strcmp(r, ".txt") != 0) r = strchr(pathbuf, '\0');
strecpy(r, ".lng", lastof(pathbuf));
LanguageFileWriter writer(pathbuf);
diff --git a/src/strgen/strgen.h b/src/strgen/strgen.h
index ecae71a72..fd527203b 100644
--- a/src/strgen/strgen.h
+++ b/src/strgen/strgen.h
@@ -73,7 +73,7 @@ struct StringReader {
* Read a single line from the source of strings.
* @param buffer The buffer to read the data in to.
* @param last The last element in the buffer.
- * @return The buffer, or NULL if at the end of the file.
+ * @return The buffer, or nullptr if at the end of the file.
*/
virtual char *ReadLine(char *buffer, const char *last) = 0;
diff --git a/src/strgen/strgen_base.cpp b/src/strgen/strgen_base.cpp
index 00c3fb9f6..804ce6498 100644
--- a/src/strgen/strgen_base.cpp
+++ b/src/strgen/strgen_base.cpp
@@ -59,8 +59,8 @@ Case::~Case()
* @param line The line this string was found on.
*/
LangString::LangString(const char *name, const char *english, int index, int line) :
- name(stredup(name)), english(stredup(english)), translated(NULL),
- hash_next(0), index(index), line(line), translated_case(NULL)
+ name(stredup(name)), english(stredup(english)), translated(nullptr),
+ hash_next(0), index(index), line(line), translated_case(nullptr)
{
}
@@ -77,10 +77,10 @@ LangString::~LangString()
void LangString::FreeTranslation()
{
free(this->translated);
- this->translated = NULL;
+ this->translated = nullptr;
delete this->translated_case;
- this->translated_case = NULL;
+ this->translated_case = nullptr;
}
/**
@@ -107,7 +107,7 @@ void StringData::FreeTranslation()
{
for (size_t i = 0; i < this->max_strings; i++) {
LangString *ls = this->strings[i];
- if (ls != NULL) ls->FreeTranslation();
+ if (ls != nullptr) ls->FreeTranslation();
}
}
@@ -140,7 +140,7 @@ void StringData::Add(const char *s, LangString *ls)
/**
* Find a LangString based on the string name.
* @param s The string name to search on.
- * @return The LangString or NULL if it is not known.
+ * @return The LangString or nullptr if it is not known.
*/
LangString *StringData::Find(const char *s)
{
@@ -152,7 +152,7 @@ LangString *StringData::Find(const char *s)
if (strcmp(ls->name, s) == 0) return ls;
idx = ls->hash_next;
}
- return NULL;
+ return nullptr;
}
/**
@@ -181,7 +181,7 @@ uint StringData::Version() const
for (size_t i = 0; i < this->max_strings; i++) {
const LangString *ls = this->strings[i];
- if (ls != NULL) {
+ if (ls != nullptr) {
const CmdStruct *cs;
const char *s;
char buf[MAX_COMMAND_PARAM_SIZE];
@@ -194,7 +194,7 @@ uint StringData::Version() const
hash = this->VersionHashStr(hash, s + 1);
s = ls->english;
- while ((cs = ParseCommandString(&s, buf, &argno, &casei)) != NULL) {
+ while ((cs = ParseCommandString(&s, buf, &argno, &casei)) != nullptr) {
if (cs->flags & C_DONTCOUNT) continue;
hash ^= (cs - _cmd_structs) * 0x1234567;
@@ -213,7 +213,7 @@ uint StringData::Version() const
uint StringData::CountInUse(uint tab) const
{
int i;
- for (i = TAB_SIZE; --i >= 0;) if (this->strings[(tab * TAB_SIZE) + i] != NULL) break;
+ for (i = TAB_SIZE; --i >= 0;) if (this->strings[(tab * TAB_SIZE) + i] != nullptr) break;
return i + 1;
}
@@ -327,7 +327,7 @@ bool ParseRelNum(char **buf, int *value, int *offset)
} else {
*value = v;
}
- if (offset != NULL && *end == ':') {
+ if (offset != nullptr && *end == ':') {
/* Take the Nth within */
s = end + 1;
*offset = strtol(s, &end, 0);
@@ -337,13 +337,13 @@ bool ParseRelNum(char **buf, int *value, int *offset)
return true;
}
-/* Parse out the next word, or NULL */
+/* Parse out the next word, or nullptr */
char *ParseWord(char **buf)
{
char *s = *buf, *r;
while (*s == ' ' || *s == '\t') s++;
- if (*s == '\0') return NULL;
+ if (*s == '\0') return nullptr;
if (*s == '"') {
r = ++s;
@@ -399,8 +399,8 @@ void EmitPlural(Buffer *buffer, char *buf, int value)
const CmdStruct *cmd = _cur_pcs.cmd[argidx];
if (offset == -1) {
/* Use default offset */
- if (cmd == NULL || cmd->default_plural_offset < 0) {
- strgen_fatal("Command '%s' has no (default) plural position", cmd == NULL ? "<empty>" : cmd->cmd);
+ if (cmd == nullptr || cmd->default_plural_offset < 0) {
+ strgen_fatal("Command '%s' has no (default) plural position", cmd == nullptr ? "<empty>" : cmd->cmd);
}
offset = cmd->default_plural_offset;
}
@@ -408,7 +408,7 @@ void EmitPlural(Buffer *buffer, char *buf, int value)
/* Parse each string */
for (nw = 0; nw < MAX_PLURALS; nw++) {
words[nw] = ParseWord(&buf);
- if (words[nw] == NULL) break;
+ if (words[nw] == nullptr) break;
}
if (nw == 0) {
@@ -462,13 +462,13 @@ void EmitGender(Buffer *buffer, char *buf, int value)
if (!ParseRelNum(&buf, &argidx, &offset)) {}
const CmdStruct *cmd = _cur_pcs.cmd[argidx];
- if (cmd == NULL || (cmd->flags & C_GENDER) == 0) {
- strgen_fatal("Command '%s' can't have a gender", cmd == NULL ? "<empty>" : cmd->cmd);
+ if (cmd == nullptr || (cmd->flags & C_GENDER) == 0) {
+ strgen_fatal("Command '%s' can't have a gender", cmd == nullptr ? "<empty>" : cmd->cmd);
}
for (nw = 0; nw < MAX_NUM_GENDERS; nw++) {
words[nw] = ParseWord(&buf);
- if (words[nw] == NULL) break;
+ if (words[nw] == nullptr) break;
}
if (nw != _lang.num_genders) strgen_fatal("Bad # of arguments for gender command");
@@ -484,7 +484,7 @@ static const CmdStruct *FindCmd(const char *s, int len)
for (const CmdStruct *cs = _cmd_structs; cs != endof(_cmd_structs); cs++) {
if (strncmp(cs->cmd, s, len) == 0 && cs->cmd[len] == '\0') return cs;
}
- return NULL;
+ return nullptr;
}
static uint ResolveCaseName(const char *str, size_t len)
@@ -501,7 +501,7 @@ static uint ResolveCaseName(const char *str, size_t len)
}
-/* returns NULL on eof
+/* returns nullptr on eof
* else returns command struct */
static const CmdStruct *ParseCommandString(const char **str, char *param, int *argno, int *casei)
{
@@ -513,7 +513,7 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a
/* Scan to the next command, exit if there's no next command. */
for (; *s != '{'; s++) {
- if (*s == '\0') return NULL;
+ if (*s == '\0') return nullptr;
}
s++; // Skip past the {
@@ -532,9 +532,9 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a
} while (c != '}' && c != ' ' && c != '=' && c != '.' && c != 0);
const CmdStruct *cmd = FindCmd(start, s - start - 1);
- if (cmd == NULL) {
+ if (cmd == nullptr) {
strgen_error("Undefined command '%.*s'", (int)(s - start - 1), start);
- return NULL;
+ return nullptr;
}
if (c == '.') {
@@ -552,7 +552,7 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a
if (c == '\0') {
strgen_error("Missing } from command '%s'", start);
- return NULL;
+ return nullptr;
}
@@ -565,7 +565,7 @@ static const CmdStruct *ParseCommandString(const char **str, char *param, int *a
if (c == '}') break;
if (c == '\0') {
strgen_error("Missing } from command '%s'", start);
- return NULL;
+ return nullptr;
}
if (s - start == MAX_COMMAND_PARAM_SIZE) error("param command too long");
*param++ = c;
@@ -609,7 +609,7 @@ static void ExtractCommandString(ParsedCommandStruct *p, const char *s, bool war
/* read until next command from a. */
const CmdStruct *ar = ParseCommandString(&s, param, &argno, &casei);
- if (ar == NULL) break;
+ if (ar == nullptr) break;
/* Sanity checking */
if (argno != -1 && ar->consumes == 0) strgen_fatal("Non consumer param can't have a paramindex");
@@ -617,7 +617,7 @@ static void ExtractCommandString(ParsedCommandStruct *p, const char *s, bool war
if (ar->consumes) {
if (argno != -1) argidx = argno;
if (argidx < 0 || (uint)argidx >= lengthof(p->cmd)) strgen_fatal("invalid param idx %d", argidx);
- if (p->cmd[argidx] != NULL && p->cmd[argidx] != ar) strgen_fatal("duplicate param idx %d", argidx);
+ if (p->cmd[argidx] != nullptr && p->cmd[argidx] != ar) strgen_fatal("duplicate param idx %d", argidx);
p->cmd[argidx++] = ar;
} else if (!(ar->flags & C_DONTCOUNT)) { // Ignore some of them
@@ -632,7 +632,7 @@ static void ExtractCommandString(ParsedCommandStruct *p, const char *s, bool war
static const CmdStruct *TranslateCmdForCompare(const CmdStruct *a)
{
- if (a == NULL) return NULL;
+ if (a == nullptr) return nullptr;
if (strcmp(a->cmd, "STRING1") == 0 ||
strcmp(a->cmd, "STRING2") == 0 ||
@@ -677,7 +677,7 @@ static bool CheckCommandsMatch(char *a, char *b, const char *name)
if (templ.pairs[i].a == lang.pairs[j].a &&
strcmp(templ.pairs[i].v, lang.pairs[j].v) == 0) {
/* it was found in both. zero it out from lang so we don't find it again */
- lang.pairs[j].a = NULL;
+ lang.pairs[j].a = nullptr;
found = true;
break;
}
@@ -694,8 +694,8 @@ static bool CheckCommandsMatch(char *a, char *b, const char *name)
for (uint i = 0; i < lengthof(templ.cmd); i++) {
if (TranslateCmdForCompare(templ.cmd[i]) != lang.cmd[i]) {
strgen_warning("%s: Param idx #%d '%s' doesn't match with template command '%s'", name, i,
- lang.cmd[i] == NULL ? "<empty>" : TranslateCmdForCompare(lang.cmd[i])->cmd,
- templ.cmd[i] == NULL ? "<empty>" : templ.cmd[i]->cmd);
+ lang.cmd[i] == nullptr ? "<empty>" : TranslateCmdForCompare(lang.cmd[i])->cmd,
+ templ.cmd[i] == nullptr ? "<empty>" : templ.cmd[i]->cmd);
result = false;
}
}
@@ -714,7 +714,7 @@ void StringReader::HandleString(char *str)
if (*str == ';' || *str == ' ' || *str == '\0') return;
char *s = strchr(str, ':');
- if (s == NULL) {
+ if (s == nullptr) {
strgen_error("Line has no ':' delimiter");
return;
}
@@ -747,23 +747,23 @@ void StringReader::HandleString(char *str)
/* Check if the string has a case..
* The syntax for cases is IDENTNAME.case */
char *casep = strchr(str, '.');
- if (casep != NULL) *casep++ = '\0';
+ if (casep != nullptr) *casep++ = '\0';
/* Check if this string already exists.. */
LangString *ent = this->data.Find(str);
if (this->master) {
- if (casep != NULL) {
+ if (casep != nullptr) {
strgen_error("Cases in the base translation are not supported.");
return;
}
- if (ent != NULL) {
+ if (ent != nullptr) {
strgen_error("String name '%s' is used multiple times", str);
return;
}
- if (this->data.strings[this->data.next_string_id] != NULL) {
+ if (this->data.strings[this->data.next_string_id] != nullptr) {
strgen_error("String ID 0x%X for '%s' already in use by '%s'", this->data.next_string_id, str, this->data.strings[this->data.next_string_id]->name);
return;
}
@@ -771,12 +771,12 @@ void StringReader::HandleString(char *str)
/* Allocate a new LangString */
this->data.Add(str, new LangString(str, s, this->data.next_string_id++, _cur_line));
} else {
- if (ent == NULL) {
+ if (ent == nullptr) {
strgen_warning("String name '%s' does not exist in master file", str);
return;
}
- if (ent->translated && casep == NULL) {
+ if (ent->translated && casep == nullptr) {
strgen_error("String name '%s' is used multiple times", str);
return;
}
@@ -784,7 +784,7 @@ void StringReader::HandleString(char *str)
/* make sure that the commands match */
if (!CheckCommandsMatch(s, ent->english, str)) return;
- if (casep != NULL) {
+ if (casep != nullptr) {
ent->translated_case = new Case(ResolveCaseName(casep, strlen(casep)), s, ent->translated_case);
} else {
ent->translated = stredup(s);
@@ -830,7 +830,7 @@ void StringReader::ParseFile()
strecpy(_lang.digit_decimal_separator, ".", lastof(_lang.digit_decimal_separator));
_cur_line = 1;
- while (this->ReadLine(buf, lastof(buf)) != NULL) {
+ while (this->ReadLine(buf, lastof(buf)) != nullptr) {
rstrip(buf);
this->HandleString(buf);
_cur_line++;
@@ -845,7 +845,7 @@ void HeaderWriter::WriteHeader(const StringData &data)
{
int last = 0;
for (size_t i = 0; i < data.max_strings; i++) {
- if (data.strings[i] != NULL) {
+ if (data.strings[i] != nullptr) {
this->WriteStringID(data.strings[i]->name, (int)i);
last = (int)i;
}
@@ -862,18 +862,18 @@ static int TranslateArgumentIdx(int argidx, int offset)
strgen_fatal("invalid argidx %d", argidx);
}
const CmdStruct *cs = _cur_pcs.cmd[argidx];
- if (cs != NULL && cs->consumes <= offset) {
+ if (cs != nullptr && cs->consumes <= offset) {
strgen_fatal("invalid argidx offset %d:%d", argidx, offset);
}
- if (_cur_pcs.cmd[argidx] == NULL) {
+ if (_cur_pcs.cmd[argidx] == nullptr) {
strgen_fatal("no command for this argidx %d", argidx);
}
for (int i = sum = 0; i < argidx; i++) {
const CmdStruct *cs = _cur_pcs.cmd[i];
- sum += (cs != NULL) ? cs->consumes : 1;
+ sum += (cs != nullptr) ? cs->consumes : 1;
}
return sum + offset;
@@ -901,7 +901,7 @@ static void PutCommandString(Buffer *buffer, const char *str)
int argno;
int casei;
const CmdStruct *cs = ParseCommandString(&str, param, &argno, &casei);
- if (cs == NULL) break;
+ if (cs == nullptr) break;
if (casei != -1) {
buffer->AppendUtf8(SCC_SET_CASE); // {SET_CASE}
@@ -918,7 +918,7 @@ static void PutCommandString(Buffer *buffer, const char *str)
/* Output the one from the master string... it's always accurate. */
cs = _cur_pcs.cmd[_cur_argidx++];
- if (cs == NULL) {
+ if (cs == nullptr) {
strgen_fatal("%s: No argument exists at position %d", _cur_ident, _cur_argidx - 1);
}
}
@@ -961,7 +961,7 @@ void LanguageWriter::WriteLang(const StringData &data)
for (uint j = 0; j != in_use[tab]; j++) {
const LangString *ls = data.strings[(tab * TAB_SIZE) + j];
- if (ls != NULL && ls->translated == NULL) _lang.missing++;
+ if (ls != nullptr && ls->translated == nullptr) _lang.missing++;
}
}
@@ -980,7 +980,7 @@ void LanguageWriter::WriteLang(const StringData &data)
const char *cmdp;
/* For undefined strings, just set that it's an empty string */
- if (ls == NULL) {
+ if (ls == nullptr) {
this->WriteLength(0);
continue;
}
@@ -989,7 +989,7 @@ void LanguageWriter::WriteLang(const StringData &data)
_cur_line = ls->line;
/* Produce a message if a string doesn't have a translation. */
- if (_show_todo > 0 && ls->translated == NULL) {
+ if (_show_todo > 0 && ls->translated == nullptr) {
if ((_show_todo & 2) != 0) {
strgen_warning("'%s' is untranslated", ls->name);
}
@@ -1002,17 +1002,17 @@ void LanguageWriter::WriteLang(const StringData &data)
/* Extract the strings and stuff from the english command string */
ExtractCommandString(&_cur_pcs, ls->english, false);
- if (ls->translated_case != NULL || ls->translated != NULL) {
+ if (ls->translated_case != nullptr || ls->translated != nullptr) {
casep = ls->translated_case;
cmdp = ls->translated;
} else {
- casep = NULL;
+ casep = nullptr;
cmdp = ls->english;
}
_translated = cmdp != ls->english;
- if (casep != NULL) {
+ if (casep != nullptr) {
const Case *c;
uint num;
@@ -1026,7 +1026,7 @@ void LanguageWriter::WriteLang(const StringData &data)
buffer.AppendByte(num);
/* Write each case */
- for (c = casep; c != NULL; c = c->next) {
+ for (c = casep; c != nullptr; c = c->next) {
buffer.AppendByte(c->caseidx);
/* Make some space for the 16-bit length */
uint pos = (uint)buffer.size();
@@ -1042,7 +1042,7 @@ void LanguageWriter::WriteLang(const StringData &data)
}
}
- if (cmdp != NULL) PutCommandString(&buffer, cmdp);
+ if (cmdp != nullptr) PutCommandString(&buffer, cmdp);
this->WriteLength((uint)buffer.size());
this->Write(buffer.data(), buffer.size());
diff --git a/src/string.cpp b/src/string.cpp
index 208f5e856..ed3f7cc66 100644
--- a/src/string.cpp
+++ b/src/string.cpp
@@ -71,7 +71,7 @@ int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
*
* Appends the source string to the destination string with respect of the
* terminating null-character and and the last pointer to the last element
- * in the destination buffer. If the last pointer is set to NULL no
+ * in the destination buffer. If the last pointer is set to nullptr no
* boundary check is performed.
*
* @note usage: strecat(dst, src, lastof(dst));
@@ -99,7 +99,7 @@ char *strecat(char *dst, const char *src, const char *last)
*
* Copies the source string to the destination buffer with respect of the
* terminating null-character and the last pointer to the last element in
- * the destination buffer. If the last pointer is set to NULL no boundary
+ * the destination buffer. If the last pointer is set to nullptr no boundary
* check is performed.
*
* @note usage: strecpy(dst, src, lastof(dst));
@@ -131,13 +131,13 @@ char *strecpy(char *dst, const char *src, const char *last)
/**
* Create a duplicate of the given string.
* @param s The string to duplicate.
- * @param last The last character that is safe to duplicate. If NULL, the whole string is duplicated.
+ * @param last The last character that is safe to duplicate. If nullptr, the whole string is duplicated.
* @note The maximum length of the resulting string might therefore be last - s + 1.
* @return The duplicate of the string.
*/
char *stredup(const char *s, const char *last)
{
- size_t len = last == NULL ? strlen(s) : ttd_strnlen(s, last - s + 1);
+ size_t len = last == nullptr ? strlen(s) : ttd_strnlen(s, last - s + 1);
char *tmp = CallocT<char>(len + 1);
memcpy(tmp, s, len);
return tmp;
@@ -447,7 +447,7 @@ char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
*/
size_t Utf8Decode(WChar *c, const char *s)
{
- assert(c != NULL);
+ assert(c != nullptr);
if (!HasBit(s[0], 7)) {
/* Single byte character: 0xxxxxxx */
@@ -551,7 +551,7 @@ char *strcasestr(const char *haystack, const char *needle)
hay_len--;
}
- return NULL;
+ return nullptr;
}
#endif /* DEFINE_STRCASESTR */
@@ -585,7 +585,7 @@ int strnatcmp(const char *s1, const char *s2, bool ignore_garbage_at_front)
}
#ifdef WITH_ICU_I18N
- if (_current_collator != NULL) {
+ if (_current_collator != nullptr) {
UErrorCode status = U_ZERO_ERROR;
int result = _current_collator->compareUTF8(s1, s2, status);
if (U_SUCCESS(status)) return result;
@@ -628,11 +628,11 @@ class IcuStringIterator : public StringIterator
std::vector<size_t> utf16_to_utf8; ///< Mapping from UTF-16 code point position to index in the UTF-8 source string.
public:
- IcuStringIterator() : char_itr(NULL), word_itr(NULL)
+ IcuStringIterator() : char_itr(nullptr), word_itr(nullptr)
{
UErrorCode status = U_ZERO_ERROR;
- this->char_itr = icu::BreakIterator::createCharacterInstance(icu::Locale(_current_language != NULL ? _current_language->isocode : "en"), status);
- this->word_itr = icu::BreakIterator::createWordInstance(icu::Locale(_current_language != NULL ? _current_language->isocode : "en"), status);
+ this->char_itr = icu::BreakIterator::createCharacterInstance(icu::Locale(_current_language != nullptr ? _current_language->isocode : "en"), status);
+ this->word_itr = icu::BreakIterator::createWordInstance(icu::Locale(_current_language != nullptr ? _current_language->isocode : "en"), status);
this->utf16_str.push_back('\0');
this->utf16_to_utf8.push_back(0);
@@ -779,7 +779,7 @@ class DefaultStringIterator : public StringIterator
size_t cur_pos; ///< Current iteration position.
public:
- DefaultStringIterator() : string(NULL), len(0), cur_pos(0)
+ DefaultStringIterator() : string(nullptr), len(0), cur_pos(0)
{
}
@@ -792,7 +792,7 @@ public:
virtual size_t SetCurPosition(size_t pos)
{
- assert(this->string != NULL && pos <= this->len);
+ assert(this->string != nullptr && pos <= this->len);
/* Sanitize in case we get a position inside an UTF-8 sequence. */
while (pos > 0 && IsUtf8Part(this->string[pos])) pos--;
return this->cur_pos = pos;
@@ -800,7 +800,7 @@ public:
virtual size_t Next(IterType what)
{
- assert(this->string != NULL);
+ assert(this->string != nullptr);
/* Already at the end? */
if (this->cur_pos >= this->len) return END;
@@ -838,7 +838,7 @@ public:
virtual size_t Prev(IterType what)
{
- assert(this->string != NULL);
+ assert(this->string != nullptr);
/* Already at the beginning? */
if (this->cur_pos == 0) return END;
@@ -878,7 +878,7 @@ public:
/* static */ StringIterator *StringIterator::Create()
{
StringIterator *i = OSXStringIterator::Create();
- if (i != NULL) return i;
+ if (i != nullptr) return i;
return new DefaultStringIterator();
}
diff --git a/src/string_func.h b/src/string_func.h
index ff12f3747..1f622870e 100644
--- a/src/string_func.h
+++ b/src/string_func.h
@@ -33,7 +33,7 @@
char *strecat(char *dst, const char *src, const char *last);
char *strecpy(char *dst, const char *src, const char *last);
-char *stredup(const char *src, const char *last = NULL);
+char *stredup(const char *src, const char *last = nullptr);
int CDECL seprintf(char *str, const char *last, const char *format, ...) WARN_FORMAT(3, 4);
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap);
@@ -54,11 +54,11 @@ bool StrValid(const char *str, const char *last);
*
* @param s The pointer to the first element of the buffer
* @return true if the buffer starts with the terminating null-character or
- * if the given pointer points to NULL else return false
+ * if the given pointer points to nullptr else return false
*/
static inline bool StrEmpty(const char *s)
{
- return s == NULL || s[0] == '\0';
+ return s == nullptr || s[0] == '\0';
}
/**
diff --git a/src/stringfilter.cpp b/src/stringfilter.cpp
index 88eb5f28a..d0bffb270 100644
--- a/src/stringfilter.cpp
+++ b/src/stringfilter.cpp
@@ -33,14 +33,14 @@ void StringFilter::SetFilterTerm(const char *str)
this->word_matches = 0;
free(this->filter_buffer);
- assert(str != NULL);
+ assert(str != nullptr);
char *dest = MallocT<char>(strlen(str) + 1);
this->filter_buffer = dest;
WChar state = STATE_WHITESPACE;
const char *pos = str;
- WordState *word = NULL;
+ WordState *word = nullptr;
size_t len;
for (;; pos += len) {
WChar c;
@@ -48,9 +48,9 @@ void StringFilter::SetFilterTerm(const char *str)
if (c == 0 || (state == STATE_WORD && IsWhitespace(c))) {
/* Finish word */
- if (word != NULL) {
+ if (word != nullptr) {
*(dest++) = '\0';
- word = NULL;
+ word = nullptr;
}
state = STATE_WHITESPACE;
if (c != 0) continue; else break;
@@ -75,7 +75,7 @@ void StringFilter::SetFilterTerm(const char *str)
}
/* Add to word */
- if (word == NULL) {
+ if (word == nullptr) {
/*C++17: word = &*/ this->word_index.push_back({dest, false});
word = &this->word_index.back();
}
@@ -106,12 +106,12 @@ void StringFilter::ResetState()
*/
void StringFilter::AddLine(const char *str)
{
- if (str == NULL) return;
+ if (str == nullptr) return;
- bool match_case = this->case_sensitive != NULL && *this->case_sensitive;
+ bool match_case = this->case_sensitive != nullptr && *this->case_sensitive;
for (WordState &ws : this->word_index) {
if (!ws.match) {
- if ((match_case ? strstr(str, ws.start) : strcasestr(str, ws.start)) != NULL) {
+ if ((match_case ? strstr(str, ws.start) : strcasestr(str, ws.start)) != nullptr) {
ws.match = true;
this->word_matches++;
}
diff --git a/src/stringfilter_type.h b/src/stringfilter_type.h
index 5ba8e876b..c2acffc35 100644
--- a/src/stringfilter_type.h
+++ b/src/stringfilter_type.h
@@ -47,9 +47,9 @@ private:
public:
/**
* Constructor for filter.
- * @param case_sensitive Pointer to a (usually static) variable controlling the case-sensitivity. NULL means always case-insensitive.
+ * @param case_sensitive Pointer to a (usually static) variable controlling the case-sensitivity. nullptr means always case-insensitive.
*/
- StringFilter(const bool *case_sensitive = NULL) : filter_buffer(NULL), word_matches(0), case_sensitive(case_sensitive) {}
+ StringFilter(const bool *case_sensitive = nullptr) : filter_buffer(nullptr), word_matches(0), case_sensitive(case_sensitive) {}
~StringFilter() { free(this->filter_buffer); }
void SetFilterTerm(const char *str);
diff --git a/src/strings.cpp b/src/strings.cpp
index be45a098b..ed8d439b4 100644
--- a/src/strings.cpp
+++ b/src/strings.cpp
@@ -45,12 +45,12 @@
char _config_language_file[MAX_PATH]; ///< The file (name) stored in the configuration.
LanguageList _languages; ///< The actual list of language meta data.
-const LanguageMetadata *_current_language = NULL; ///< The currently loaded language.
+const LanguageMetadata *_current_language = nullptr; ///< The currently loaded language.
TextDirection _current_text_dir; ///< Text direction of the currently selected language.
#ifdef WITH_ICU_I18N
-icu::Collator *_current_collator = NULL; ///< Collator for the language currently in use.
+icu::Collator *_current_collator = nullptr; ///< Collator for the language currently in use.
#endif /* WITH_ICU_I18N */
static uint64 _global_string_params_data[20]; ///< Global array of string parameters. To access, use #SetDParam.
@@ -60,7 +60,7 @@ StringParameters _global_string_params(_global_string_params_data, 20, _global_s
/** Reset the type array. */
void StringParameters::ClearTypeInformation()
{
- assert(this->type != NULL);
+ assert(this->type != nullptr);
MemSetT(this->type, 0, this->num_param);
}
@@ -75,7 +75,7 @@ int64 StringParameters::GetInt64(WChar type)
DEBUG(misc, 0, "Trying to read invalid string parameter");
return 0;
}
- if (this->type != NULL) {
+ if (this->type != nullptr) {
if (this->type[this->offset] != 0 && this->type[this->offset] != type) {
DEBUG(misc, 0, "Trying to read string parameter with wrong type");
return 0;
@@ -172,7 +172,7 @@ void CopyOutDParam(uint64 *dst, const char **strings, StringID string, int num)
strings[i] = stredup((const char *)(size_t)_global_string_params.GetParam(i));
dst[i] = (size_t)strings[i];
} else {
- strings[i] = NULL;
+ strings[i] = nullptr;
}
}
}
@@ -320,7 +320,7 @@ static char *FormatNumber(char *buff, int64 number, const char *last, const char
for (int i = 0; i < max_digits; i++) {
if (i == max_digits - fractional_digits) {
const char *decimal_separator = _settings_game.locale.digit_decimal_separator;
- if (decimal_separator == NULL) decimal_separator = _langpack->digit_decimal_separator;
+ if (decimal_separator == nullptr) decimal_separator = _langpack->digit_decimal_separator;
buff += seprintf(buff, last, "%s", decimal_separator);
}
@@ -345,7 +345,7 @@ static char *FormatNumber(char *buff, int64 number, const char *last, const char
static char *FormatCommaNumber(char *buff, int64 number, const char *last, int fractional_digits = 0)
{
const char *separator = _settings_game.locale.digit_group_separator;
- if (separator == NULL) separator = _langpack->digit_group_separator;
+ if (separator == nullptr) separator = _langpack->digit_group_separator;
return FormatNumber(buff, number, last, separator, 1, fractional_digits);
}
@@ -384,7 +384,7 @@ static char *FormatBytes(char *buff, int64 number, const char *last)
}
const char *decimal_separator = _settings_game.locale.digit_decimal_separator;
- if (decimal_separator == NULL) decimal_separator = _langpack->digit_decimal_separator;
+ if (decimal_separator == nullptr) decimal_separator = _langpack->digit_decimal_separator;
if (number < 1024) {
id = 0;
@@ -478,8 +478,8 @@ static char *FormatGenericCurrency(char *buff, const CurrencySpec *spec, Money n
}
const char *separator = _settings_game.locale.digit_group_separator_currency;
- if (separator == NULL && !StrEmpty(_currency->separator)) separator = _currency->separator;
- if (separator == NULL) separator = _langpack->digit_group_separator_currency;
+ if (separator == nullptr && !StrEmpty(_currency->separator)) separator = _currency->separator;
+ if (separator == nullptr) separator = _langpack->digit_group_separator_currency;
buff = FormatNumber(buff, number, last, separator);
buff = strecpy(buff, multiplier, last);
@@ -937,7 +937,7 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
char buf[256];
bool old_sgd = _scan_for_gender_data;
_scan_for_gender_data = true;
- StringParameters tmp_params(args->GetPointerToOffset(offset), args->num_param - offset, NULL);
+ StringParameters tmp_params(args->GetPointerToOffset(offset), args->num_param - offset, nullptr);
p = FormatString(buf, input, &tmp_params, lastof(buf));
_scan_for_gender_data = old_sgd;
*p = '\0';
@@ -1016,8 +1016,8 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
if (game_script && GetStringTab(str) != TEXT_TAB_GAMESCRIPT_START) break;
/* WARNING. It's prohibited for the included string to consume any arguments.
* For included strings that consume argument, you should use STRING1, STRING2 etc.
- * To debug stuff you can set argv to NULL and it will tell you */
- StringParameters tmp_params(args->GetDataPointer(), args->GetDataLeft(), NULL);
+ * To debug stuff you can set argv to nullptr and it will tell you */
+ StringParameters tmp_params(args->GetDataPointer(), args->GetDataLeft(), nullptr);
buff = GetStringWithArgs(buff, str, &tmp_params, last, next_substr_case_index, game_script);
next_substr_case_index = 0;
break;
@@ -1270,9 +1270,9 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_COMPANY_NAME: { // {COMPANY}
const Company *c = Company::GetIfValid(args->GetInt32());
- if (c == NULL) break;
+ if (c == nullptr) break;
- if (c->name != NULL) {
+ if (c->name != nullptr) {
int64 args_array[] = {(int64)(size_t)c->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1307,7 +1307,7 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
}
const Depot *d = Depot::Get(args->GetInt32());
- if (d->name != NULL) {
+ if (d->name != nullptr) {
int64 args_array[] = {(int64)(size_t)d->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1321,14 +1321,14 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_ENGINE_NAME: { // {ENGINE}
const Engine *e = Engine::GetIfValid(args->GetInt32(SCC_ENGINE_NAME));
- if (e == NULL) break;
+ if (e == nullptr) break;
- if (e->name != NULL && e->IsEnabled()) {
+ if (e->name != nullptr && e->IsEnabled()) {
int64 args_array[] = {(int64)(size_t)e->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
} else {
- StringParameters tmp_params(NULL, 0, NULL);
+ StringParameters tmp_params(nullptr, 0, nullptr);
buff = GetStringWithArgs(buff, e->info.string_id, &tmp_params, last);
}
break;
@@ -1336,9 +1336,9 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_GROUP_NAME: { // {GROUP}
const Group *g = Group::GetIfValid(args->GetInt32());
- if (g == NULL) break;
+ if (g == nullptr) break;
- if (g->name != NULL) {
+ if (g->name != nullptr) {
int64 args_array[] = {(int64)(size_t)g->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1353,12 +1353,12 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_INDUSTRY_NAME: { // {INDUSTRY}
const Industry *i = Industry::GetIfValid(args->GetInt32(SCC_INDUSTRY_NAME));
- if (i == NULL) break;
+ if (i == nullptr) break;
if (_scan_for_gender_data) {
/* Gender is defined by the industry type.
* STR_FORMAT_INDUSTRY_NAME may have the town first, so it would result in the gender of the town name */
- StringParameters tmp_params(NULL, 0, NULL);
+ StringParameters tmp_params(nullptr, 0, nullptr);
buff = FormatString(buff, GetStringPtr(GetIndustrySpec(i->type)->name), &tmp_params, last, next_substr_case_index);
} else {
/* First print the town name and the industry type name. */
@@ -1373,9 +1373,9 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_PRESIDENT_NAME: { // {PRESIDENT_NAME}
const Company *c = Company::GetIfValid(args->GetInt32(SCC_PRESIDENT_NAME));
- if (c == NULL) break;
+ if (c == nullptr) break;
- if (c->president_name != NULL) {
+ if (c->president_name != nullptr) {
int64 args_array[] = {(int64)(size_t)c->president_name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1391,16 +1391,16 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
StationID sid = args->GetInt32(SCC_STATION_NAME);
const Station *st = Station::GetIfValid(sid);
- if (st == NULL) {
+ if (st == nullptr) {
/* The station doesn't exist anymore. The only place where we might
* be "drawing" an invalid station is in the case of cargo that is
* in transit. */
- StringParameters tmp_params(NULL, 0, NULL);
+ StringParameters tmp_params(nullptr, 0, nullptr);
buff = GetStringWithArgs(buff, STR_UNKNOWN_STATION, &tmp_params, last);
break;
}
- if (st->name != NULL) {
+ if (st->name != nullptr) {
int64 args_array[] = {(int64)(size_t)st->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1428,9 +1428,9 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_TOWN_NAME: { // {TOWN}
const Town *t = Town::GetIfValid(args->GetInt32(SCC_TOWN_NAME));
- if (t == NULL) break;
+ if (t == nullptr) break;
- if (t->name != NULL) {
+ if (t->name != nullptr) {
int64 args_array[] = {(int64)(size_t)t->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1442,9 +1442,9 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_WAYPOINT_NAME: { // {WAYPOINT}
Waypoint *wp = Waypoint::GetIfValid(args->GetInt32(SCC_WAYPOINT_NAME));
- if (wp == NULL) break;
+ if (wp == nullptr) break;
- if (wp->name != NULL) {
+ if (wp->name != nullptr) {
int64 args_array[] = {(int64)(size_t)wp->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1460,9 +1460,9 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_VEHICLE_NAME: { // {VEHICLE}
const Vehicle *v = Vehicle::GetIfValid(args->GetInt32(SCC_VEHICLE_NAME));
- if (v == NULL) break;
+ if (v == nullptr) break;
- if (v->name != NULL) {
+ if (v->name != nullptr) {
int64 args_array[] = {(int64)(size_t)v->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
@@ -1486,14 +1486,14 @@ static char *FormatString(char *buff, const char *str_arg, StringParameters *arg
case SCC_SIGN_NAME: { // {SIGN}
const Sign *si = Sign::GetIfValid(args->GetInt32());
- if (si == NULL) break;
+ if (si == nullptr) break;
- if (si->name != NULL) {
+ if (si->name != nullptr) {
int64 args_array[] = {(int64)(size_t)si->name};
StringParameters tmp_params(args_array);
buff = GetStringWithArgs(buff, STR_JUST_RAW_STRING, &tmp_params, last);
} else {
- StringParameters tmp_params(NULL, 0, NULL);
+ StringParameters tmp_params(nullptr, 0, nullptr);
buff = GetStringWithArgs(buff, STR_DEFAULT_SIGN_NAME, &tmp_params, last);
}
break;
@@ -1717,7 +1717,7 @@ bool ReadLanguagePack(const LanguageMetadata *lang)
/* Current language pack */
size_t len;
LanguagePack *lang_pack = (LanguagePack *)ReadFileToMem(lang->file, &len, 1U << 20);
- if (lang_pack == NULL) return false;
+ if (lang_pack == nullptr) return false;
/* End of read data (+ terminating zero added in ReadFileToMem()) */
const char *end = (char *)lang_pack + len + 1;
@@ -1797,20 +1797,20 @@ bool ReadLanguagePack(const LanguageMetadata *lang)
#ifdef WITH_ICU_I18N
/* Delete previous collator. */
- if (_current_collator != NULL) {
+ if (_current_collator != nullptr) {
delete _current_collator;
- _current_collator = NULL;
+ _current_collator = nullptr;
}
/* Create a collator instance for our current locale. */
UErrorCode status = U_ZERO_ERROR;
_current_collator = icu::Collator::createInstance(icu::Locale(_current_language->isocode), status);
/* Sort number substrings by their numerical value. */
- if (_current_collator != NULL) _current_collator->setAttribute(UCOL_NUMERIC_COLLATION, UCOL_ON, status);
+ if (_current_collator != nullptr) _current_collator->setAttribute(UCOL_NUMERIC_COLLATION, UCOL_ON, status);
/* Avoid using the collator if it is not correctly set. */
if (U_FAILURE(status)) {
delete _current_collator;
- _current_collator = NULL;
+ _current_collator = nullptr;
}
#endif /* WITH_ICU_I18N */
@@ -1840,22 +1840,22 @@ bool ReadLanguagePack(const LanguageMetadata *lang)
* First check some default values, after this one we passed ourselves
* and if none exist return the value for $LANG
* @param param environment variable to check conditionally if default ones are not
- * set. Pass NULL if you don't want additional checks.
- * @return return string containing current charset, or NULL if not-determinable
+ * set. Pass nullptr if you don't want additional checks.
+ * @return return string containing current charset, or nullptr if not-determinable
*/
const char *GetCurrentLocale(const char *param)
{
const char *env;
env = getenv("LANGUAGE");
- if (env != NULL) return env;
+ if (env != nullptr) return env;
env = getenv("LC_ALL");
- if (env != NULL) return env;
+ if (env != nullptr) return env;
- if (param != NULL) {
+ if (param != nullptr) {
env = getenv(param);
- if (env != NULL) return env;
+ if (env != nullptr) return env;
}
return getenv("LANG");
@@ -1877,7 +1877,7 @@ int CDECL StringIDSorter(const StringID *a, const StringID *b)
/**
* Get the language with the given NewGRF language ID.
* @param newgrflangid NewGRF languages ID to check.
- * @return The language's metadata, or NULL if it is not known.
+ * @return The language's metadata, or nullptr if it is not known.
*/
const LanguageMetadata *GetLanguage(byte newgrflangid)
{
@@ -1885,7 +1885,7 @@ const LanguageMetadata *GetLanguage(byte newgrflangid)
if (newgrflangid == lang.newgrflangid) return &lang;
}
- return NULL;
+ return nullptr;
}
/**
@@ -1897,7 +1897,7 @@ const LanguageMetadata *GetLanguage(byte newgrflangid)
static bool GetLanguageFileHeader(const char *file, LanguagePackHeader *hdr)
{
FILE *f = fopen(file, "rb");
- if (f == NULL) return false;
+ if (f == nullptr) return false;
size_t read = fread(hdr, sizeof(*hdr), 1, f);
fclose(f);
@@ -1919,14 +1919,14 @@ static bool GetLanguageFileHeader(const char *file, LanguagePackHeader *hdr)
static void GetLanguageList(const char *path)
{
DIR *dir = ttd_opendir(path);
- if (dir != NULL) {
+ if (dir != nullptr) {
struct dirent *dirent;
- while ((dirent = readdir(dir)) != NULL) {
+ while ((dirent = readdir(dir)) != nullptr) {
const char *d_name = FS2OTTD(dirent->d_name);
const char *extension = strrchr(d_name, '.');
/* Not a language file */
- if (extension == NULL || strcmp(extension, ".lng") != 0) continue;
+ if (extension == nullptr || strcmp(extension, ".lng") != 0) continue;
LanguageMetadata lmd;
seprintf(lmd.file, lastof(lmd.file), "%s%s", path, d_name);
@@ -1934,7 +1934,7 @@ static void GetLanguageList(const char *path)
/* Check whether the file is of the correct version */
if (!GetLanguageFileHeader(lmd.file, &lmd)) {
DEBUG(misc, 3, "%s is not a valid language file", lmd.file);
- } else if (GetLanguage(lmd.newgrflangid) != NULL) {
+ } else if (GetLanguage(lmd.newgrflangid) != nullptr) {
DEBUG(misc, 3, "%s's language ID is already known", lmd.file);
} else {
_languages.push_back(lmd);
@@ -1961,10 +1961,10 @@ void InitializeLanguagePacks()
/* Acquire the locale of the current system */
const char *lang = GetCurrentLocale("LC_MESSAGES");
- if (lang == NULL) lang = "en_GB";
+ if (lang == nullptr) lang = "en_GB";
- const LanguageMetadata *chosen_language = NULL; ///< Matching the language in the configuration file or the current locale
- const LanguageMetadata *language_fallback = NULL; ///< Using pt_PT for pt_BR locale when pt_BR is not available
+ const LanguageMetadata *chosen_language = nullptr; ///< Matching the language in the configuration file or the current locale
+ const LanguageMetadata *language_fallback = nullptr; ///< Using pt_PT for pt_BR locale when pt_BR is not available
const LanguageMetadata *en_GB_fallback = _languages.data(); ///< Fallback when no locale-matching language has been found
/* Find a proper language. */
@@ -1985,8 +1985,8 @@ void InitializeLanguagePacks()
/* We haven't found the language in the config nor the one in the locale.
* Now we set it to one of the fallback languages */
- if (chosen_language == NULL) {
- chosen_language = (language_fallback != NULL) ? language_fallback : en_GB_fallback;
+ if (chosen_language == nullptr) {
+ chosen_language = (language_fallback != nullptr) ? language_fallback : en_GB_fallback;
}
if (!ReadLanguagePack(chosen_language)) usererror("Can't read language pack '%s'", chosen_language->file);
@@ -2005,7 +2005,7 @@ const char *GetCurrentLanguageIsoCode()
* Check whether there are glyphs missing in the current language.
* @param[out] str Pointer to an address for storing the text pointer.
* @return If glyphs are missing, return \c true, else return \c false.
- * @post If \c true is returned and str is not NULL, *str points to a string that is found to contain at least one missing glyph.
+ * @post If \c true is returned and str is not nullptr, *str points to a string that is found to contain at least one missing glyph.
*/
bool MissingGlyphSearcher::FindMissingGlyphs(const char **str)
{
@@ -2017,9 +2017,9 @@ bool MissingGlyphSearcher::FindMissingGlyphs(const char **str)
}
this->Reset();
- for (const char *text = this->NextString(); text != NULL; text = this->NextString()) {
+ for (const char *text = this->NextString(); text != nullptr; text = this->NextString()) {
FontSize size = this->DefaultSize();
- if (str != NULL) *str = text;
+ if (str != nullptr) *str = text;
for (WChar c = Utf8Consume(&text); c != '\0'; c = Utf8Consume(&text)) {
if (c >= SCC_FIRST_FONT && c <= SCC_LAST_FONT) {
size = (FontSize)(c - SCC_FIRST_FONT);
@@ -2050,7 +2050,7 @@ class LanguagePackGlyphSearcher : public MissingGlyphSearcher {
const char *NextString() override
{
- if (this->i >= TEXT_TAB_END) return NULL;
+ if (this->i >= TEXT_TAB_END) return nullptr;
const char *ret = _langpack_offs[_langtab_start[this->i] + this->j];
@@ -2089,13 +2089,13 @@ class LanguagePackGlyphSearcher : public MissingGlyphSearcher {
* been added.
* @param base_font Whether to look at the base font as well.
* @param searcher The methods to use to search for strings to check.
- * If NULL the loaded language pack searcher is used.
+ * If nullptr the loaded language pack searcher is used.
*/
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
{
static LanguagePackGlyphSearcher pack_searcher;
- if (searcher == NULL) searcher = &pack_searcher;
- bool bad_font = !base_font || searcher->FindMissingGlyphs(NULL);
+ if (searcher == nullptr) searcher = &pack_searcher;
+ bool bad_font = !base_font || searcher->FindMissingGlyphs(nullptr);
#ifdef WITH_FREETYPE
if (bad_font) {
/* We found an unprintable character... lets try whether we can find
diff --git a/src/strings_func.h b/src/strings_func.h
index 0da711bc4..a5e2e1ca2 100644
--- a/src/strings_func.h
+++ b/src/strings_func.h
@@ -60,9 +60,9 @@ static inline StringID MakeStringID(StringTab tab, uint index)
}
class StringParameters {
- StringParameters *parent; ///< If not NULL, this instance references data from this parent instance.
+ StringParameters *parent; ///< If not nullptr, this instance references data from this parent instance.
uint64 *data; ///< Array with the actual data.
- WChar *type; ///< Array with type information about the data. Can be NULL when no type information is needed. See #StringControlCode.
+ WChar *type; ///< Array with type information about the data. Can be nullptr when no type information is needed. See #StringControlCode.
public:
uint offset; ///< Current offset in the data/type arrays.
@@ -70,7 +70,7 @@ public:
/** Create a new StringParameters instance. */
StringParameters(uint64 *data, uint num_param, WChar *type) :
- parent(NULL),
+ parent(nullptr),
data(data),
type(type),
offset(0),
@@ -80,9 +80,9 @@ public:
/** Create a new StringParameters instance. */
template <size_t Tnum_param>
StringParameters(int64 (&data)[Tnum_param]) :
- parent(NULL),
+ parent(nullptr),
data((uint64 *)data),
- type(NULL),
+ type(nullptr),
offset(0),
num_param(Tnum_param)
{
@@ -100,8 +100,8 @@ public:
num_param(size)
{
assert(size <= parent.GetDataLeft());
- if (parent.type == NULL) {
- this->type = NULL;
+ if (parent.type == nullptr) {
+ this->type = nullptr;
} else {
this->type = parent.type + parent.offset;
}
@@ -109,7 +109,7 @@ public:
~StringParameters()
{
- if (this->parent != NULL) {
+ if (this->parent != nullptr) {
this->parent->offset += this->num_param;
}
}
@@ -148,7 +148,7 @@ public:
/** Does this instance store information about the type of the parameters. */
bool HasTypeInformation() const
{
- return this->type != NULL;
+ return this->type != nullptr;
}
/** Get the type of a specific element. */
@@ -250,7 +250,7 @@ public:
/**
* Get the next string to search through.
- * @return The next string or NULL if there is none.
+ * @return The next string or nullptr if there is none.
*/
virtual const char *NextString() = 0;
@@ -281,6 +281,6 @@ public:
bool FindMissingGlyphs(const char **str);
};
-void CheckForMissingGlyphs(bool base_font = true, MissingGlyphSearcher *search = NULL);
+void CheckForMissingGlyphs(bool base_font = true, MissingGlyphSearcher *search = nullptr);
#endif /* STRINGS_FUNC_H */
diff --git a/src/subsidy.cpp b/src/subsidy.cpp
index 2b851048b..53a363922 100644
--- a/src/subsidy.cpp
+++ b/src/subsidy.cpp
@@ -376,7 +376,7 @@ bool FindSubsidyIndustryCargoRoute()
/* Select a random industry. */
const Industry *src_ind = Industry::GetRandom();
- if (src_ind == NULL) return false;
+ if (src_ind == nullptr) return false;
uint trans, total;
@@ -441,7 +441,7 @@ bool FindSubsidyCargoDestination(CargoID cid, SourceType src_type, SourceID src)
case ST_INDUSTRY: {
/* Select a random industry. */
const Industry *dst_ind = Industry::GetRandom();
- if (dst_ind == NULL) return false;
+ if (dst_ind == nullptr) return false;
/* The industry must accept the cargo */
bool valid = std::find(dst_ind->accepts_cargo, endof(dst_ind->accepts_cargo), cid) != endof(dst_ind->accepts_cargo);
diff --git a/src/subsidy_base.h b/src/subsidy_base.h
index f12fbc4b9..780302e0a 100644
--- a/src/subsidy_base.h
+++ b/src/subsidy_base.h
@@ -36,7 +36,7 @@ struct Subsidy : SubsidyPool::PoolItem<&_subsidy_pool> {
inline Subsidy() { }
/**
- * (Empty) destructor has to be defined else operator delete might be called with NULL parameter
+ * (Empty) destructor has to be defined else operator delete might be called with nullptr parameter
*/
inline ~Subsidy() { }
diff --git a/src/table/airport_defaults.h b/src/table/airport_defaults.h
index 593e157ac..89989ee98 100644
--- a/src/table/airport_defaults.h
+++ b/src/table/airport_defaults.h
@@ -386,7 +386,7 @@ static const Direction _default_airports_rotation[] = {
/** AirportSpec definition for airports without any depot. */
#define AS_ND(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview) \
- AS_GENERIC(&_airportfta_##ap_name, _tile_table_##ap_name, _default_airports_rotation, lengthof(_tile_table_##ap_name), NULL, 0, \
+ AS_GENERIC(&_airportfta_##ap_name, _tile_table_##ap_name, _default_airports_rotation, lengthof(_tile_table_##ap_name), nullptr, 0, \
size_x, size_y, noise, catchment, min_year, max_year, maint_cost, ttdpatch_type, class_id, name, preview, true)
/** AirportSpec definition for airports with at least one depot. */
@@ -405,12 +405,12 @@ extern const AirportSpec _origin_airport_specs[] = {
AS(helidepot, 2, 2, 1976, MAX_YEAR, 4, 2, 7, ATP_TTDP_SMALL, APC_HELIPORT, STR_AIRPORT_HELIDEPOT, SPR_AIRPORT_PREVIEW_HELIDEPOT),
AS(intercontinental, 9, 11, 2002, MAX_YEAR, 10, 25, 72, ATP_TTDP_LARGE, APC_HUB, STR_AIRPORT_INTERCONTINENTAL, SPR_AIRPORT_PREVIEW_INTERCONTINENTAL),
AS(helistation, 4, 2, 1980, MAX_YEAR, 4, 3, 14, ATP_TTDP_SMALL, APC_HELIPORT, STR_AIRPORT_HELISTATION, SPR_AIRPORT_PREVIEW_HELISTATION),
- AS_GENERIC(&_airportfta_oilrig, NULL, _default_airports_rotation, 0, NULL, 0, 1, 1, 0, 4, 0, 0, 0, ATP_TTDP_OILRIG, APC_HELIPORT, STR_NULL, 0, false),
+ AS_GENERIC(&_airportfta_oilrig, nullptr, _default_airports_rotation, 0, nullptr, 0, 1, 1, 0, 4, 0, 0, 0, ATP_TTDP_OILRIG, APC_HELIPORT, STR_NULL, 0, false),
};
assert_compile(NEW_AIRPORT_OFFSET == lengthof(_origin_airport_specs));
-const AirportSpec AirportSpec::dummy = AS_GENERIC(&_airportfta_dummy, NULL, _default_airports_rotation, 0, NULL, 0, 0, 0, 0, 0, MIN_YEAR, MIN_YEAR, 0, ATP_TTDP_LARGE, APC_BEGIN, STR_NULL, 0, false);
+const AirportSpec AirportSpec::dummy = AS_GENERIC(&_airportfta_dummy, nullptr, _default_airports_rotation, 0, nullptr, 0, 0, 0, 0, 0, MIN_YEAR, MIN_YEAR, 0, ATP_TTDP_LARGE, APC_BEGIN, STR_NULL, 0, false);
#undef AS
#undef AS_ND
diff --git a/src/table/bridge_land.h b/src/table/bridge_land.h
index 4f6f94bb0..b06a4076b 100644
--- a/src/table/bridge_land.h
+++ b/src/table/bridge_land.h
@@ -741,7 +741,7 @@ static const PalSpriteID * const * const _bridge_sprite_table[MAX_BRIDGES] = {
* @param nrd description of the road bridge in query tool
*/
#define MBR(y, mnl, mxl, p, mxs, spr, plt, dsc, nrl, nrd) \
- {y, mnl, mxl, p, mxs, spr, plt, dsc, { nrl, nrd }, NULL, 0}
+ {y, mnl, mxl, p, mxs, spr, plt, dsc, { nrl, nrd }, nullptr, 0}
const BridgeSpec _orig_bridge[] = {
/*
diff --git a/src/table/build_industry.h b/src/table/build_industry.h
index 62264eb6f..6e07f59a3 100644
--- a/src/table/build_industry.h
+++ b/src/table/build_industry.h
@@ -1213,7 +1213,7 @@ enum IndustryTypes {
industry name building text
messages : Closure production up production down */
static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
- MI(_tile_table_coal_mine, 0, NULL,
+ MI(_tile_table_coal_mine, 0, nullptr,
210, 0xB3333333, 2, 3, 0, 0, 8, 8, 0, 0, 1,
IT_POWER_STATION, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_COAL, 15, CT_INVALID, 0, 5,
@@ -1223,7 +1223,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_COAL_MINE, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_COAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_power_station, 0, NULL,
+ MI(_tile_table_power_station, 0, nullptr,
240, 0xFFFFFFFF, 2, 2, 0, 0, 5, 5, 0, 0, 184,
IT_COAL_MINE, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_INVALID, 0, CT_INVALID, 0, 5,
@@ -1243,7 +1243,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_SAWMILL, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_forest, 0, NULL,
+ MI(_tile_table_forest, 0, nullptr,
200, 0xBFFFFFFF, 3, 4, 0, 0, 5, 5, 0, 0, 86,
IT_SAWMILL, IT_PAPER_MILL, IT_INVALID, CHECK_FOREST,
CT_WOOD, 13, CT_INVALID, 0, 30,
@@ -1253,7 +1253,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_FOREST, STR_NEWS_INDUSTRY_PLANTED,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM),
- MI(_tile_table_oil_refinery, 0, NULL,
+ MI(_tile_table_oil_refinery, 0, nullptr,
244, 0xFFFFFFFF, 2, 2, 2, 0, 4, 4, 4, 0, 191,
IT_OIL_RIG, IT_INVALID, IT_INVALID, CHECK_REFINERY,
CT_GOODS, 0, CT_INVALID, 0, 5,
@@ -1263,7 +1263,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_OIL_REFINERY, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_oil_rig, 0, NULL,
+ MI(_tile_table_oil_rig, 0, nullptr,
240, 0x99999999, 6, 0, 0, 0, 0, 0, 0, 0, 152,
IT_OIL_REFINERY, IT_INVALID, IT_INVALID, CHECK_OIL_RIG,
CT_OIL, 15, CT_PASSENGERS, 2, 5,
@@ -1293,7 +1293,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_PRINTING_WORKS, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_steel_mill, 0, NULL,
+ MI(_tile_table_steel_mill, 0, nullptr,
215, 0xFFFFFFFF, 2, 0, 0, 0, 5, 0, 0, 0, 10,
IT_IRON_MINE, IT_FACTORY, IT_INVALID, CHECK_NOTHING,
CT_STEEL, 0, CT_INVALID, 0, 5,
@@ -1313,7 +1313,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_FARM, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM),
- MI(_tile_table_copper_mine, 0, NULL,
+ MI(_tile_table_copper_mine, 0, nullptr,
205, 0xB3333333, 0, 0, 3, 0, 0, 0, 4, 0, 10,
IT_FACTORY_2, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_COPPER_ORE, 10, CT_INVALID, 0, 5,
@@ -1323,7 +1323,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_COPPER_ORE_MINE, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_oil_well, 0, NULL,
+ MI(_tile_table_oil_well, 0, nullptr,
220, 0x99999999, 0, 5, 3, 0, 4, 5, 5, 0, 152,
IT_OIL_REFINERY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_OIL, 12, CT_INVALID, 0, 5,
@@ -1333,7 +1333,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_OIL_WELLS, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_OIL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_bank, 0, NULL,
+ MI(_tile_table_bank, 0, nullptr,
255, 0xA6666666, 7, 0, 0, 0, 0, 0, 0, 0, 15,
IT_BANK_TEMP, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_VALUABLES, 6, CT_INVALID, 0, 5,
@@ -1343,7 +1343,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_BANK, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_food_process, 0, NULL,
+ MI(_tile_table_food_process, 0, nullptr,
206, 0xFFFFFFFF, 0, 2, 2, 0, 0, 3, 4, 0, 55,
IT_FRUIT_PLANTATION, IT_FARM, IT_FARM_2, CHECK_NOTHING,
CT_FOOD, 0, CT_INVALID, 0, 5,
@@ -1363,7 +1363,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_PAPER_MILL, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_gold_mine, 0, NULL,
+ MI(_tile_table_gold_mine, 0, nullptr,
208, 0x99999999, 0, 3, 0, 0, 0, 4, 0, 0, 194,
IT_BANK_TROPIC_ARCTIC, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_GOLD, 7, CT_INVALID, 0, 5,
@@ -1373,7 +1373,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_GOLD_MINE, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_bank2, 0, NULL,
+ MI(_tile_table_bank2, 0, nullptr,
151, 0xA6666666, 0, 3, 3, 0, 0, 6, 5, 0, 15,
IT_GOLD_MINE, IT_DIAMOND_MINE, IT_INVALID, CHECK_NOTHING,
CT_INVALID, 0, CT_INVALID, 0, 5,
@@ -1383,7 +1383,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_BANK_TROPIC_ARCTIC, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_diamond_mine, 0, NULL,
+ MI(_tile_table_diamond_mine, 0, nullptr,
213, 0x99999999, 0, 0, 3, 0, 0, 0, 4, 0, 184,
IT_BANK_TROPIC_ARCTIC, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_DIAMONDS, 7, CT_INVALID, 0, 5,
@@ -1393,7 +1393,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_DIAMOND_MINE, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_iron_mine, 0, NULL,
+ MI(_tile_table_iron_mine, 0, nullptr,
220, 0xB3333333, 2, 0, 0, 0, 5, 0, 0, 0, 55,
IT_STEEL_MILL, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_IRON_ORE, 10, CT_INVALID, 0, 5,
@@ -1403,7 +1403,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_IRON_ORE_MINE, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_fruit_plantation, 0, NULL,
+ MI(_tile_table_fruit_plantation, 0, nullptr,
225, 0xBFFFFFFF, 0, 0, 2, 0, 0, 0, 4, 0, 86,
IT_FOOD_PROCESS, IT_INVALID, IT_INVALID, CHECK_PLANTATION,
CT_FRUIT, 10, CT_INVALID, 0, 15,
@@ -1413,7 +1413,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_FRUIT_PLANTATION, STR_NEWS_INDUSTRY_PLANTED,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM),
- MI(_tile_table_rubber_plantation, 0, NULL,
+ MI(_tile_table_rubber_plantation, 0, nullptr,
218, 0xBFFFFFFF, 0, 0, 3, 0, 0, 0, 4, 0, 39,
IT_FACTORY_2, IT_INVALID, IT_INVALID, CHECK_PLANTATION,
CT_RUBBER, 10, CT_INVALID, 0, 15,
@@ -1423,7 +1423,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_RUBBER_PLANTATION, STR_NEWS_INDUSTRY_PLANTED,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM),
- MI(_tile_table_water_supply, 0, NULL,
+ MI(_tile_table_water_supply, 0, nullptr,
199, 0xB3333333, 0, 0, 3, 0, 0, 0, 4, 0, 37,
IT_WATER_TOWER, IT_INVALID, IT_INVALID, CHECK_WATER,
CT_WATER, 12, CT_INVALID, 0, 5,
@@ -1433,7 +1433,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_WATER_SUPPLY, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_water_tower, 0, NULL,
+ MI(_tile_table_water_tower, 0, nullptr,
115, 0xFFFFFFFF, 0, 0, 4, 0, 0, 0, 8, 0, 208,
IT_WATER_SUPPLY, IT_INVALID, IT_INVALID, CHECK_WATER,
CT_INVALID, 0, CT_INVALID, 0, 5,
@@ -1453,7 +1453,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_FACTORY_2, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_farm2, 0, NULL,
+ MI(_tile_table_farm2, 0, nullptr,
250, 0xD9999999, 0, 0, 1, 0, 0, 0, 2, 0, 48,
IT_FOOD_PROCESS, IT_INVALID, IT_INVALID, CHECK_PLANTATION,
CT_MAIZE, 11, CT_INVALID, 0, 5,
@@ -1463,7 +1463,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_FARM_2, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM),
- MI(_tile_table_lumber_mill, 0, NULL,
+ MI(_tile_table_lumber_mill, 0, nullptr,
135, 0xFFFFFFFF, 0, 0, 0, 0, 0, 0, 0, 0, 194,
IT_FACTORY_2, IT_INVALID, IT_INVALID, CHECK_LUMBERMILL,
CT_WOOD, 0, CT_INVALID, 0, 5,
@@ -1473,7 +1473,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_LUMBER_MILL, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_cotton_candy, 0, NULL,
+ MI(_tile_table_cotton_candy, 0, nullptr,
195, 0xBFFFFFFF, 0, 0, 0, 3, 0, 0, 0, 5, 48,
IT_CANDY_FACTORY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_COTTON_CANDY, 13, CT_INVALID, 0, 30,
@@ -1483,7 +1483,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_COTTON_CANDY_FOREST, STR_NEWS_INDUSTRY_PLANTED,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_candy_factory, 0, NULL,
+ MI(_tile_table_candy_factory, 0, nullptr,
206, 0xFFFFFFFF, 0, 0, 0, 3, 0, 0, 0, 5, 174,
IT_COTTON_CANDY, IT_TOFFEE_QUARRY, IT_SUGAR_MINE, CHECK_NOTHING,
CT_CANDY, 0, CT_INVALID, 0, 5,
@@ -1493,7 +1493,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_CANDY_FACTORY, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_battery_farm, 0, NULL,
+ MI(_tile_table_battery_farm, 0, nullptr,
187, 0xB3333333, 0, 0, 0, 3, 0, 0, 0, 4, 39,
IT_TOY_FACTORY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_BATTERIES, 11, CT_INVALID, 0, 30,
@@ -1503,7 +1503,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_BATTERY_FARM, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM),
- MI(_tile_table_cola_wells, 0, NULL,
+ MI(_tile_table_cola_wells, 0, nullptr,
193, 0x99999999, 0, 0, 0, 3, 0, 0, 0, 5, 55,
IT_FIZZY_DRINK_FACTORY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_COLA, 12, CT_INVALID, 0, 5,
@@ -1513,7 +1513,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_COLA_WELLS, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_toy_shop, 0, NULL,
+ MI(_tile_table_toy_shop, 0, nullptr,
133, 0xFFFFFFFF, 0, 0, 0, 3, 0, 0, 0, 4, 208,
IT_TOY_FACTORY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_INVALID, 0, CT_INVALID, 0, 5,
@@ -1523,7 +1523,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_TOY_SHOP, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_toy_factory, 0, NULL,
+ MI(_tile_table_toy_factory, 0, nullptr,
163, 0xFFFFFFFF, 0, 0, 0, 3, 0, 0, 0, 5, 10,
IT_PLASTIC_FOUNTAINS, IT_BATTERY_FARM, IT_TOY_SHOP, CHECK_NOTHING,
CT_TOYS, 0, CT_INVALID, 0, 5,
@@ -1543,7 +1543,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_PLASTIC_FOUNTAINS, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_fizzy_drink, 0, NULL,
+ MI(_tile_table_fizzy_drink, 0, nullptr,
177, 0xFFFFFFFF, 0, 0, 0, 3, 0, 0, 0, 4, 184,
IT_COLA_WELLS, IT_BUBBLE_GENERATOR, IT_INVALID, CHECK_NOTHING,
CT_FIZZY_DRINKS, 0, CT_INVALID, 0, 5,
@@ -1553,7 +1553,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_FIZZY_DRINK_FACTORY, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_SUPPLY_PROBLEMS, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_bubble_generator, 0, NULL,
+ MI(_tile_table_bubble_generator, 0, nullptr,
203, 0xB3333333, 0, 0, 0, 3, 0, 0, 0, 5, 152,
IT_FIZZY_DRINK_FACTORY, IT_INVALID, IT_INVALID, CHECK_BUBBLEGEN,
CT_BUBBLES, 13, CT_INVALID, 0, 5,
@@ -1563,7 +1563,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_BUBBLE_GENERATOR, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_toffee_quarry, 0, NULL,
+ MI(_tile_table_toffee_quarry, 0, nullptr,
213, 0xCCCCCCCC, 0, 0, 0, 3, 0, 0, 0, 5, 194,
IT_CANDY_FACTORY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_TOFFEE, 10, CT_INVALID, 0, 5,
@@ -1573,7 +1573,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
STR_INDUSTRY_NAME_TOFFEE_QUARRY, STR_NEWS_INDUSTRY_CONSTRUCTION,
STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL),
- MI(_tile_table_sugar_mine, 0, NULL,
+ MI(_tile_table_sugar_mine, 0, nullptr,
210, 0xBFFFFFFF, 0, 0, 0, 2, 0, 0, 0, 4, 15,
IT_CANDY_FACTORY, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_SUGAR, 11, CT_INVALID, 0, 5,
diff --git a/src/table/cargo_const.h b/src/table/cargo_const.h
index c2ce5bc78..bc3f13956 100644
--- a/src/table/cargo_const.h
+++ b/src/table/cargo_const.h
@@ -11,7 +11,7 @@
/** Construction macro for a #CargoSpec structure. */
#define MK(bt, label, c, e, f, g, h, fr, te, ks1, ks2, ks3, ks4, ks5, l, m, cmult) \
- {bt, label, c, c, e, cmult, f, {g, h}, fr, te, 0, 0, ks1, ks2, ks3, ks4, ks5, l, m, NULL, NULL, 0}
+ {bt, label, c, c, e, cmult, f, {g, h}, fr, te, 0, 0, ks1, ks2, ks3, ks4, ks5, l, m, nullptr, nullptr, 0}
/** Cargo types available by default. */
static const CargoSpec _default_cargo[] = {
MK( 0, 'PASS', 152, 1, 3185, 0, 24, false, TE_PASSENGERS,
diff --git a/src/table/newgrf_debug_data.h b/src/table/newgrf_debug_data.h
index d04827c77..0b3c92499 100644
--- a/src/table/newgrf_debug_data.h
+++ b/src/table/newgrf_debug_data.h
@@ -14,15 +14,15 @@
/* Helper for filling property tables */
#define NIP(prop, base, variable, type, name) { name, (ptrdiff_t)cpp_offsetof(base, variable), cpp_sizeof(base, variable), prop, type }
-#define NIP_END() { NULL, 0, 0, 0, 0 }
+#define NIP_END() { nullptr, 0, 0, 0, 0 }
/* Helper for filling callback tables */
#define NIC(cb_id, base, variable, bit) { #cb_id, (ptrdiff_t)cpp_offsetof(base, variable), cpp_sizeof(base, variable), bit, cb_id }
-#define NIC_END() { NULL, 0, 0, 0, 0 }
+#define NIC_END() { nullptr, 0, 0, 0, 0 }
/* Helper for filling variable tables */
#define NIV(var, name) { name, var }
-#define NIV_END() { NULL, 0 }
+#define NIV_END() { nullptr, 0 }
/*** NewGRF Vehicles ***/
@@ -69,7 +69,7 @@ static const NIVariable _niv_vehicles[] = {
};
class NIHVehicle : public NIHelper {
- bool IsInspectable(uint index) const override { return Vehicle::Get(index)->GetGRF() != NULL; }
+ bool IsInspectable(uint index) const override { return Vehicle::Get(index)->GetGRF() != nullptr; }
uint GetParent(uint index) const override { const Vehicle *first = Vehicle::Get(index)->First(); return GetInspectWindowNumber(GetGrfSpecFeature(first->type), first->index); }
const void *GetInstance(uint index)const override { return Vehicle::Get(index); }
const void *GetSpec(uint index) const override { return Vehicle::Get(index)->GetEngine(); }
@@ -85,7 +85,7 @@ class NIHVehicle : public NIHelper {
};
static const NIFeature _nif_vehicle = {
- NULL,
+ nullptr,
_nic_vehicles,
_niv_vehicles,
new NIHVehicle(),
@@ -132,9 +132,9 @@ static const NIVariable _niv_stations[] = {
};
class NIHStation : public NIHelper {
- bool IsInspectable(uint index) const override { return GetStationSpec(index) != NULL; }
+ bool IsInspectable(uint index) const override { return GetStationSpec(index) != nullptr; }
uint GetParent(uint index) const override { return GetInspectWindowNumber(GSF_FAKE_TOWNS, Station::GetByTile(index)->town->index); }
- const void *GetInstance(uint index)const override { return NULL; }
+ const void *GetInstance(uint index)const override { return nullptr; }
const void *GetSpec(uint index) const override { return GetStationSpec(index); }
void SetStringParameters(uint index) const override { this->SetObjectAtStringParameters(STR_STATION_NAME, GetStationIndex(index), index); }
uint32 GetGRFID(uint index) const override { return (this->IsInspectable(index)) ? GetStationSpec(index)->grf_prop.grffile->grfid : 0; }
@@ -147,7 +147,7 @@ class NIHStation : public NIHelper {
};
static const NIFeature _nif_station = {
- NULL,
+ nullptr,
_nic_stations,
_niv_stations,
new NIHStation(),
@@ -197,9 +197,9 @@ static const NIVariable _niv_house[] = {
};
class NIHHouse : public NIHelper {
- bool IsInspectable(uint index) const override { return HouseSpec::Get(GetHouseType(index))->grf_prop.grffile != NULL; }
+ bool IsInspectable(uint index) const override { return HouseSpec::Get(GetHouseType(index))->grf_prop.grffile != nullptr; }
uint GetParent(uint index) const override { return GetInspectWindowNumber(GSF_FAKE_TOWNS, GetTownIndex(index)); }
- const void *GetInstance(uint index)const override { return NULL; }
+ const void *GetInstance(uint index)const override { return nullptr; }
const void *GetSpec(uint index) const override { return HouseSpec::Get(GetHouseType(index)); }
void SetStringParameters(uint index) const override { this->SetObjectAtStringParameters(STR_TOWN_NAME, GetTownIndex(index), index); }
uint32 GetGRFID(uint index) const override { return (this->IsInspectable(index)) ? HouseSpec::Get(GetHouseType(index))->grf_prop.grffile->grfid : 0; }
@@ -212,7 +212,7 @@ class NIHHouse : public NIHelper {
};
static const NIFeature _nif_house = {
- NULL,
+ nullptr,
_nic_house,
_niv_house,
new NIHHouse(),
@@ -247,9 +247,9 @@ static const NIVariable _niv_industrytiles[] = {
};
class NIHIndustryTile : public NIHelper {
- bool IsInspectable(uint index) const override { return GetIndustryTileSpec(GetIndustryGfx(index))->grf_prop.grffile != NULL; }
+ bool IsInspectable(uint index) const override { return GetIndustryTileSpec(GetIndustryGfx(index))->grf_prop.grffile != nullptr; }
uint GetParent(uint index) const override { return GetInspectWindowNumber(GSF_INDUSTRIES, GetIndustryIndex(index)); }
- const void *GetInstance(uint index)const override { return NULL; }
+ const void *GetInstance(uint index)const override { return nullptr; }
const void *GetSpec(uint index) const override { return GetIndustryTileSpec(GetIndustryGfx(index)); }
void SetStringParameters(uint index) const override { this->SetObjectAtStringParameters(STR_INDUSTRY_NAME, GetIndustryIndex(index), index); }
uint32 GetGRFID(uint index) const override { return (this->IsInspectable(index)) ? GetIndustryTileSpec(GetIndustryGfx(index))->grf_prop.grffile->grfid : 0; }
@@ -262,7 +262,7 @@ class NIHIndustryTile : public NIHelper {
};
static const NIFeature _nif_industrytile = {
- NULL,
+ nullptr,
_nic_industrytiles,
_niv_industrytiles,
new NIHIndustryTile(),
@@ -346,7 +346,7 @@ static const NIVariable _niv_industries[] = {
};
class NIHIndustry : public NIHelper {
- bool IsInspectable(uint index) const override { return GetIndustrySpec(Industry::Get(index)->type)->grf_prop.grffile != NULL; }
+ bool IsInspectable(uint index) const override { return GetIndustrySpec(Industry::Get(index)->type)->grf_prop.grffile != nullptr; }
uint GetParent(uint index) const override { return GetInspectWindowNumber(GSF_FAKE_TOWNS, Industry::Get(index)->town->index); }
const void *GetInstance(uint index)const override { return Industry::Get(index); }
const void *GetSpec(uint index) const override { return GetIndustrySpec(Industry::Get(index)->type); }
@@ -365,7 +365,7 @@ class NIHIndustry : public NIHelper {
const int32 *GetPSAFirstPosition(uint index, uint32 grfid) const override
{
const Industry *i = (const Industry *)this->GetInstance(index);
- if (i->psa == NULL) return NULL;
+ if (i->psa == nullptr) return nullptr;
return (int32 *)(&i->psa->storage);
}
};
@@ -411,7 +411,7 @@ static const NIVariable _niv_objects[] = {
};
class NIHObject : public NIHelper {
- bool IsInspectable(uint index) const override { return ObjectSpec::GetByTile(index)->grf_prop.grffile != NULL; }
+ bool IsInspectable(uint index) const override { return ObjectSpec::GetByTile(index)->grf_prop.grffile != nullptr; }
uint GetParent(uint index) const override { return GetInspectWindowNumber(GSF_FAKE_TOWNS, Object::GetByTile(index)->town->index); }
const void *GetInstance(uint index)const override { return Object::GetByTile(index); }
const void *GetSpec(uint index) const override { return ObjectSpec::GetByTile(index); }
@@ -426,7 +426,7 @@ class NIHObject : public NIHelper {
};
static const NIFeature _nif_object = {
- NULL,
+ nullptr,
_nic_objects,
_niv_objects,
new NIHObject(),
@@ -447,8 +447,8 @@ static const NIVariable _niv_railtypes[] = {
class NIHRailType : public NIHelper {
bool IsInspectable(uint index) const override { return true; }
uint GetParent(uint index) const override { return UINT32_MAX; }
- const void *GetInstance(uint index)const override { return NULL; }
- const void *GetSpec(uint index) const override { return NULL; }
+ const void *GetInstance(uint index)const override { return nullptr; }
+ const void *GetSpec(uint index) const override { return nullptr; }
void SetStringParameters(uint index) const override { this->SetObjectAtStringParameters(STR_NEWGRF_INSPECT_CAPTION_OBJECT_AT_RAIL_TYPE, INVALID_STRING_ID, index); }
uint32 GetGRFID(uint index) const override { return 0; }
@@ -456,14 +456,14 @@ class NIHRailType : public NIHelper {
{
/* There is no unique GRFFile for the tile. Multiple GRFs can define different parts of the railtype.
* However, currently the NewGRF Debug GUI does not display variables depending on the GRF (like 0x7F) anyway. */
- RailTypeResolverObject ro(NULL, index, TCX_NORMAL, RTSG_END);
+ RailTypeResolverObject ro(nullptr, index, TCX_NORMAL, RTSG_END);
return ro.GetScope(VSG_SCOPE_SELF)->GetVariable(var, param, avail);
}
};
static const NIFeature _nif_railtype = {
- NULL,
- NULL,
+ nullptr,
+ nullptr,
_niv_railtypes,
new NIHRailType(),
};
@@ -481,9 +481,9 @@ static const NICallback _nic_airporttiles[] = {
};
class NIHAirportTile : public NIHelper {
- bool IsInspectable(uint index) const override { return AirportTileSpec::Get(GetAirportGfx(index))->grf_prop.grffile != NULL; }
+ bool IsInspectable(uint index) const override { return AirportTileSpec::Get(GetAirportGfx(index))->grf_prop.grffile != nullptr; }
uint GetParent(uint index) const override { return GetInspectWindowNumber(GSF_FAKE_TOWNS, Station::GetByTile(index)->town->index); }
- const void *GetInstance(uint index)const override { return NULL; }
+ const void *GetInstance(uint index)const override { return nullptr; }
const void *GetSpec(uint index) const override { return AirportTileSpec::Get(GetAirportGfx(index)); }
void SetStringParameters(uint index) const override { this->SetObjectAtStringParameters(STR_STATION_NAME, GetStationIndex(index), index); }
uint32 GetGRFID(uint index) const override { return (this->IsInspectable(index)) ? AirportTileSpec::Get(GetAirportGfx(index))->grf_prop.grffile->grfid : 0; }
@@ -496,7 +496,7 @@ class NIHAirportTile : public NIHelper {
};
static const NIFeature _nif_airporttile = {
- NULL,
+ nullptr,
_nic_airporttiles,
_niv_industrytiles, // Yes, they share this (at least now)
new NIHAirportTile(),
@@ -522,7 +522,7 @@ class NIHTown : public NIHelper {
bool IsInspectable(uint index) const override { return Town::IsValidID(index); }
uint GetParent(uint index) const override { return UINT32_MAX; }
const void *GetInstance(uint index)const override { return Town::Get(index); }
- const void *GetSpec(uint index) const override { return NULL; }
+ const void *GetSpec(uint index) const override { return nullptr; }
void SetStringParameters(uint index) const override { this->SetSimpleStringParameters(STR_TOWN_NAME, index); }
uint32 GetGRFID(uint index) const override { return 0; }
bool PSAWithParameter() const override { return true; }
@@ -530,7 +530,7 @@ class NIHTown : public NIHelper {
uint Resolve(uint index, uint var, uint param, bool *avail) const override
{
- TownResolverObject ro(NULL, Town::Get(index), true);
+ TownResolverObject ro(nullptr, Town::Get(index), true);
return ro.GetScope(VSG_SCOPE_SELF)->GetVariable(var, param, avail);
}
@@ -543,13 +543,13 @@ class NIHTown : public NIHelper {
if ((*iter)->grfid == grfid) return (int32 *)(&(*iter)->storage[0]);
}
- return NULL;
+ return nullptr;
}
};
static const NIFeature _nif_town = {
- NULL,
- NULL,
+ nullptr,
+ nullptr,
_niv_towns,
new NIHTown(),
};
@@ -561,16 +561,16 @@ static const NIFeature * const _nifeatures[] = {
&_nif_vehicle, // GSF_SHIPS
&_nif_vehicle, // GSF_AIRCRAFT
&_nif_station, // GSF_STATIONS
- NULL, // GSF_CANALS (no callbacks/action2 implemented)
- NULL, // GSF_BRIDGES (no callbacks/action2)
+ nullptr, // GSF_CANALS (no callbacks/action2 implemented)
+ nullptr, // GSF_BRIDGES (no callbacks/action2)
&_nif_house, // GSF_HOUSES
- NULL, // GSF_GLOBALVAR (has no "physical" objects)
+ nullptr, // GSF_GLOBALVAR (has no "physical" objects)
&_nif_industrytile, // GSF_INDUSTRYTILES
&_nif_industry, // GSF_INDUSTRIES
- NULL, // GSF_CARGOES (has no "physical" objects)
- NULL, // GSF_SOUNDFX (has no "physical" objects)
- NULL, // GSF_AIRPORTS (feature not implemented)
- NULL, // GSF_SIGNALS (feature not implemented)
+ nullptr, // GSF_CARGOES (has no "physical" objects)
+ nullptr, // GSF_SOUNDFX (has no "physical" objects)
+ nullptr, // GSF_AIRPORTS (feature not implemented)
+ nullptr, // GSF_SIGNALS (feature not implemented)
&_nif_object, // GSF_OBJECTS
&_nif_railtype, // GSF_RAILTYPES
&_nif_airporttile, // GSF_AIRPORTTILES
diff --git a/src/table/railtypes.h b/src/table/railtypes.h
index f52a1524b..73b73ff80 100644
--- a/src/table/railtypes.h
+++ b/src/table/railtypes.h
@@ -112,8 +112,8 @@ static const RailtypeInfo _original_railtypes[] = {
/* sort order */
0 << 4 | 7,
- { NULL },
- { NULL },
+ { nullptr },
+ { nullptr },
},
/** Electrified railway */
@@ -213,8 +213,8 @@ static const RailtypeInfo _original_railtypes[] = {
/* sort order */
1 << 4 | 7,
- { NULL },
- { NULL },
+ { nullptr },
+ { nullptr },
},
/** Monorail */
@@ -310,8 +310,8 @@ static const RailtypeInfo _original_railtypes[] = {
/* sort order */
2 << 4 | 7,
- { NULL },
- { NULL },
+ { nullptr },
+ { nullptr },
},
/** Maglev */
@@ -407,8 +407,8 @@ static const RailtypeInfo _original_railtypes[] = {
/* sort order */
3 << 4 | 7,
- { NULL },
- { NULL },
+ { nullptr },
+ { nullptr },
},
};
diff --git a/src/table/roadveh_movement.h b/src/table/roadveh_movement.h
index 5b202b2b5..f6f75c834 100644
--- a/src/table/roadveh_movement.h
+++ b/src/table/roadveh_movement.h
@@ -1445,39 +1445,39 @@ static const RoadDriveEntry * const _road_tram_drive_data[] = {
_roadveh_drive_data_29,
_roadveh_tram_turn_sw_1,
_roadveh_tram_turn_nw_1,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
};
static const RoadDriveEntry * const * const _road_drive_data[2] = {
diff --git a/src/table/station_land.h b/src/table/station_land.h
index 3327dab5d..b678297d9 100644
--- a/src/table/station_land.h
+++ b/src/table/station_land.h
@@ -789,7 +789,7 @@ static const DrawTileSeqStruct _station_display_datas_waypoint_Y[] = {
* @param dtss Sequence child sprites of the tile
*/
#define TILE_SPRITE_LINE(img, dtss) { {img, PAL_NONE}, dtss },
-#define TILE_SPRITE_NULL() { {0, 0}, NULL },
+#define TILE_SPRITE_NULL() { {0, 0}, nullptr },
extern const DrawTileSprites _station_display_datas_rail[] = {
TILE_SPRITE_LINE(SPR_RAIL_TRACK_X, _station_display_datas_0)
diff --git a/src/tar_type.h b/src/tar_type.h
index 6306fb650..14b23aea6 100644
--- a/src/tar_type.h
+++ b/src/tar_type.h
@@ -25,7 +25,7 @@ struct TarListEntry {
/* MSVC goes copying around this struct after initialisation, so it tries
* to free filename, which isn't set at that moment... but because it
* initializes the variable with garbage, it's going to segfault. */
- TarListEntry() : filename(NULL), dirname(NULL) {}
+ TarListEntry() : filename(nullptr), dirname(nullptr) {}
~TarListEntry() { free(this->filename); free(this->dirname); }
};
diff --git a/src/terraform_cmd.cpp b/src/terraform_cmd.cpp
index 9839f5e34..eb6ec2b53 100644
--- a/src/terraform_cmd.cpp
+++ b/src/terraform_cmd.cpp
@@ -278,7 +278,7 @@ CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
/* Is the tile already cleared? */
const ClearedObjectArea *coa = FindClearedObject(tile);
- bool indirectly_cleared = coa != NULL && coa->first_tile != tile;
+ bool indirectly_cleared = coa != nullptr && coa->first_tile != tile;
/* Check tiletype-specific things, and add extra-cost */
const bool curr_gen = _generating_world;
@@ -304,7 +304,7 @@ CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
}
Company *c = Company::GetIfValid(_current_company);
- if (c != NULL && GB(c->terraform_limit, 16, 16) < ts.tile_to_new_height.size()) {
+ if (c != nullptr && GB(c->terraform_limit, 16, 16) < ts.tile_to_new_height.size()) {
return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
}
@@ -326,7 +326,7 @@ CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
SetTileHeight(tile, (uint)height);
}
- if (c != NULL) c->terraform_limit -= (uint32)ts.tile_to_new_height.size() << 16;
+ if (c != nullptr) c->terraform_limit -= (uint32)ts.tile_to_new_height.size() << 16;
}
return total_cost;
}
@@ -371,7 +371,7 @@ CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
bool had_success = false;
const Company *c = Company::GetIfValid(_current_company);
- int limit = (c == NULL ? INT32_MAX : GB(c->terraform_limit, 16, 16));
+ int limit = (c == nullptr ? INT32_MAX : GB(c->terraform_limit, 16, 16));
if (limit == 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
TileIterator *iter = HasBit(p2, 0) ? (TileIterator *)new DiagonalTileIterator(tile, p1) : new OrthogonalTileIterator(tile, p1);
diff --git a/src/terraform_gui.cpp b/src/terraform_gui.cpp
index a69917040..70c7be149 100644
--- a/src/terraform_gui.cpp
+++ b/src/terraform_gui.cpp
@@ -293,8 +293,8 @@ struct TerraformToolbarWindow : Window {
static EventState TerraformToolbarGlobalHotkeys(int hotkey)
{
if (_game_mode != GM_NORMAL) return ES_NOT_HANDLED;
- Window *w = ShowTerraformToolbar(NULL);
- if (w == NULL) return ES_NOT_HANDLED;
+ Window *w = ShowTerraformToolbar(nullptr);
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -353,14 +353,14 @@ static WindowDesc _terraform_desc(
/**
* Show the toolbar for terraforming in the game.
* @param link The toolbar we might want to link to.
- * @return The allocated toolbar if the window was newly opened, else \c NULL.
+ * @return The allocated toolbar if the window was newly opened, else \c nullptr.
*/
Window *ShowTerraformToolbar(Window *link)
{
- if (!Company::IsValidID(_local_company)) return NULL;
+ if (!Company::IsValidID(_local_company)) return nullptr;
Window *w;
- if (link == NULL) {
+ if (link == nullptr) {
w = AllocateWindowDescFront<TerraformToolbarWindow>(&_terraform_desc, 0);
return w;
}
@@ -631,7 +631,7 @@ struct ScenarioEditorLandscapeGenerationWindow : Window {
break;
case WID_ETT_RESET_LANDSCAPE: // Reset landscape
- ShowQuery(STR_QUERY_RESET_LANDSCAPE_CAPTION, STR_RESET_LANDSCAPE_CONFIRMATION_TEXT, NULL, ResetLandscapeConfirmationCallback);
+ ShowQuery(STR_QUERY_RESET_LANDSCAPE_CAPTION, STR_RESET_LANDSCAPE_CONFIRMATION_TEXT, nullptr, ResetLandscapeConfirmationCallback);
break;
default: NOT_REACHED();
@@ -720,7 +720,7 @@ static EventState TerraformToolbarEditorGlobalHotkeys(int hotkey)
{
if (_game_mode != GM_EDITOR) return ES_NOT_HANDLED;
Window *w = ShowEditorTerraformToolbar();
- if (w == NULL) return ES_NOT_HANDLED;
+ if (w == nullptr) return ES_NOT_HANDLED;
return w->OnHotkey(hotkey);
}
@@ -747,7 +747,7 @@ static WindowDesc _scen_edit_land_gen_desc(
/**
* Show the toolbar for terraforming in the scenario editor.
- * @return The allocated toolbar if the window was newly opened, else \c NULL.
+ * @return The allocated toolbar if the window was newly opened, else \c nullptr.
*/
Window *ShowEditorTerraformToolbar()
{
diff --git a/src/terraform_gui.h b/src/terraform_gui.h
index 26a1c5e9a..22cfe79c5 100644
--- a/src/terraform_gui.h
+++ b/src/terraform_gui.h
@@ -14,7 +14,7 @@
#include "window_type.h"
-Window *ShowTerraformToolbar(Window *link = NULL);
+Window *ShowTerraformToolbar(Window *link = nullptr);
Window *ShowEditorTerraformToolbar();
#endif /* TERRAFORM_GUI_H */
diff --git a/src/textbuf.cpp b/src/textbuf.cpp
index 61e449d3a..384757566 100644
--- a/src/textbuf.cpp
+++ b/src/textbuf.cpp
@@ -164,18 +164,18 @@ bool Textbuf::InsertChar(WChar key)
bool Textbuf::InsertString(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
{
uint16 insertpos = (marked && this->marklength != 0) ? this->markpos : this->caretpos;
- if (insert_location != NULL) {
+ if (insert_location != nullptr) {
insertpos = insert_location - this->buf;
if (insertpos > this->bytes) return false;
- if (replacement_end != NULL) {
- this->DeleteText(insertpos, replacement_end - this->buf, str == NULL);
+ if (replacement_end != nullptr) {
+ this->DeleteText(insertpos, replacement_end - this->buf, str == nullptr);
}
} else {
- if (marked) this->DiscardMarkedText(str == NULL);
+ if (marked) this->DiscardMarkedText(str == nullptr);
}
- if (str == NULL) return false;
+ if (str == nullptr) return false;
uint16 bytes = 0, chars = 0;
WChar c;
@@ -205,7 +205,7 @@ bool Textbuf::InsertString(const char *str, bool marked, const char *caret, cons
this->bytes += bytes;
this->chars += chars;
- if (!marked && caret == NULL) this->caretpos += bytes;
+ if (!marked && caret == nullptr) this->caretpos += bytes;
assert(this->bytes <= this->max_bytes);
assert(this->chars <= this->max_chars);
this->buf[this->bytes - 1] = '\0'; // terminating zero
diff --git a/src/textbuf_type.h b/src/textbuf_type.h
index 1d927b72d..22dfd3ffd 100644
--- a/src/textbuf_type.h
+++ b/src/textbuf_type.h
@@ -56,7 +56,7 @@ struct Textbuf {
bool InsertClipboard();
bool InsertChar(uint32 key);
- bool InsertString(const char *str, bool marked, const char *caret = NULL, const char *insert_location = NULL, const char *replacement_end = NULL);
+ bool InsertString(const char *str, bool marked, const char *caret = nullptr, const char *insert_location = nullptr, const char *replacement_end = nullptr);
bool DeleteChar(uint16 keycode);
bool MovePos(uint16 keycode);
diff --git a/src/textfile_gui.cpp b/src/textfile_gui.cpp
index b70d183bd..7a2eb44ca 100644
--- a/src/textfile_gui.cpp
+++ b/src/textfile_gui.cpp
@@ -184,7 +184,7 @@ void TextfileWindow::SetupScrollbars()
/* virtual */ const char *TextfileWindow::NextString()
{
- if (this->search_iterator >= this->lines.size()) return NULL;
+ if (this->search_iterator >= this->lines.size()) return nullptr;
return this->lines[this->search_iterator++];
}
@@ -214,13 +214,13 @@ void TextfileWindow::SetupScrollbars()
* After the call, it contains the size of the uncompressed
* data.
*
- * When decompressing fails, *bufp is set to NULL and *sizep to 0. The
+ * When decompressing fails, *bufp is set to nullptr and *sizep to 0. The
* compressed buffer passed in is still freed in this case.
*/
static void Gunzip(byte **bufp, size_t *sizep)
{
static const int BLOCKSIZE = 8192;
- byte *buf = NULL;
+ byte *buf = nullptr;
size_t alloc_size = 0;
z_stream z;
int res;
@@ -250,7 +250,7 @@ static void Gunzip(byte **bufp, size_t *sizep)
*sizep = alloc_size - z.avail_out;
} else {
/* Something went wrong */
- *bufp = NULL;
+ *bufp = nullptr;
*sizep = 0;
free(buf);
}
@@ -270,13 +270,13 @@ static void Gunzip(byte **bufp, size_t *sizep)
* After the call, it contains the size of the uncompressed
* data.
*
- * When decompressing fails, *bufp is set to NULL and *sizep to 0. The
+ * When decompressing fails, *bufp is set to nullptr and *sizep to 0. The
* compressed buffer passed in is still freed in this case.
*/
static void Xunzip(byte **bufp, size_t *sizep)
{
static const int BLOCKSIZE = 8192;
- byte *buf = NULL;
+ byte *buf = nullptr;
size_t alloc_size = 0;
lzma_stream z = LZMA_STREAM_INIT;
int res;
@@ -304,7 +304,7 @@ static void Xunzip(byte **bufp, size_t *sizep)
*sizep = alloc_size - z.avail_out;
} else {
/* Something went wrong */
- *bufp = NULL;
+ *bufp = nullptr;
*sizep = 0;
free(buf);
}
@@ -317,14 +317,14 @@ static void Xunzip(byte **bufp, size_t *sizep)
*/
/* virtual */ void TextfileWindow::LoadTextfile(const char *textfile, Subdirectory dir)
{
- if (textfile == NULL) return;
+ if (textfile == nullptr) return;
this->lines.clear();
/* Get text from file */
size_t filesize;
FILE *handle = FioFOpenFile(textfile, "rb", dir, &filesize);
- if (handle == NULL) return;
+ if (handle == nullptr) return;
this->text = ReallocT(this->text, filesize);
size_t read = fread(this->text, 1, filesize, handle);
@@ -334,7 +334,7 @@ static void Xunzip(byte **bufp, size_t *sizep)
#if defined(WITH_ZLIB) || defined(WITH_LIBLZMA)
const char *suffix = strrchr(textfile, '.');
- if (suffix == NULL) return;
+ if (suffix == nullptr) return;
#endif
#if defined(WITH_ZLIB)
@@ -381,7 +381,7 @@ static void Xunzip(byte **bufp, size_t *sizep)
* @param type The type of the textfile to search for.
* @param dir The subdirectory to search in.
* @param filename The filename of the content to look for.
- * @return The path to the textfile, \c NULL otherwise.
+ * @return The path to the textfile, \c nullptr otherwise.
*/
const char *GetTextfile(TextfileType type, Subdirectory dir, const char *filename)
{
@@ -394,13 +394,13 @@ const char *GetTextfile(TextfileType type, Subdirectory dir, const char *filenam
const char *prefix = prefixes[type];
- if (filename == NULL) return NULL;
+ if (filename == nullptr) return nullptr;
static char file_path[MAX_PATH];
strecpy(file_path, filename, lastof(file_path));
char *slash = strrchr(file_path, PATHSEPCHAR);
- if (slash == NULL) return NULL;
+ if (slash == nullptr) return nullptr;
static const char * const exts[] = {
"txt",
@@ -422,5 +422,5 @@ const char *GetTextfile(TextfileType type, Subdirectory dir, const char *filenam
seprintf(slash + 1, lastof(file_path), "%s.%s", prefix, exts[i]);
if (FioCheckFileExists(file_path, dir)) return file_path;
}
- return NULL;
+ return nullptr;
}
diff --git a/src/tgp.cpp b/src/tgp.cpp
index 4dbb79aa8..3fd42e0fd 100644
--- a/src/tgp.cpp
+++ b/src/tgp.cpp
@@ -184,7 +184,7 @@ struct HeightMap
};
/** Global height map instance */
-static HeightMap _height_map = {NULL, 0, 0, 0, 0};
+static HeightMap _height_map = {nullptr, 0, 0, 0, 0};
/** Conversion: int to height_t */
#define I2H(i) ((i) << height_decimal_bits)
@@ -325,7 +325,7 @@ static inline bool AllocHeightMap()
static inline void FreeHeightMap()
{
free(_height_map.h);
- _height_map.h = NULL;
+ _height_map.h = nullptr;
}
/**
@@ -349,7 +349,7 @@ static inline height_t RandomHeight(amplitude_t rMax)
static void HeightMapGenerate()
{
/* Trying to apply noise to uninitialized height map */
- assert(_height_map.h != NULL);
+ assert(_height_map.h != nullptr);
int start = max(MAX_TGP_FREQUENCIES - (int)min(MapLogX(), MapLogY()), 0);
bool first = true;
@@ -423,9 +423,9 @@ static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t
h_avg = (height_t)(h_accu / (_height_map.size_x * _height_map.size_y));
/* Return required results */
- if (min_ptr != NULL) *min_ptr = h_min;
- if (max_ptr != NULL) *max_ptr = h_max;
- if (avg_ptr != NULL) *avg_ptr = h_avg;
+ if (min_ptr != nullptr) *min_ptr = h_min;
+ if (max_ptr != nullptr) *max_ptr = h_max;
+ if (avg_ptr != nullptr) *avg_ptr = h_avg;
}
/** Dill histogram and return pointer to its base point - to the count of zero heights */
@@ -1011,5 +1011,5 @@ void GenerateTerrainPerlin()
IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
FreeHeightMap();
- GenerateWorldSetAbortCallback(NULL);
+ GenerateWorldSetAbortCallback(nullptr);
}
diff --git a/src/thread.h b/src/thread.h
index 53548cc06..be1d7d463 100644
--- a/src/thread.h
+++ b/src/thread.h
@@ -40,7 +40,7 @@ void SetCurrentThreadName(const char *name);
* Start a new thread.
* @tparam TFn Type of the function to call on the thread.
* @tparam TArgs Type of the parameters of the thread function.
- * @param thr Pointer to a thread object; may be \c NULL if a detached thread is wanted.
+ * @param thr Pointer to a thread object; may be \c nullptr if a detached thread is wanted.
* @param name Name of the thread.
* @param _Fx Function to call on the thread.
* @param _Ax Arguments for the thread function.
@@ -62,7 +62,7 @@ inline bool StartNewThread(std::thread *thr, const char *name, TFn&& _Fx, TArgs&
}
}, name, std::forward<TFn>(_Fx), std::forward<TArgs>(_Ax)...);
- if (thr != NULL) {
+ if (thr != nullptr) {
*thr = std::move(t);
} else {
t.detach();
diff --git a/src/tile_cmd.h b/src/tile_cmd.h
index ce70232a0..855aa297d 100644
--- a/src/tile_cmd.h
+++ b/src/tile_cmd.h
@@ -168,29 +168,29 @@ void GetTileDesc(TileIndex tile, TileDesc *td);
static inline void AddAcceptedCargo(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
{
AddAcceptedCargoProc *proc = _tile_type_procs[GetTileType(tile)]->add_accepted_cargo_proc;
- if (proc == NULL) return;
- CargoTypes dummy = 0; // use dummy bitmask so there don't need to be several 'always_accepted != NULL' checks
- proc(tile, acceptance, always_accepted == NULL ? &dummy : always_accepted);
+ if (proc == nullptr) return;
+ CargoTypes dummy = 0; // use dummy bitmask so there don't need to be several 'always_accepted != nullptr' checks
+ proc(tile, acceptance, always_accepted == nullptr ? &dummy : always_accepted);
}
static inline void AddProducedCargo(TileIndex tile, CargoArray &produced)
{
AddProducedCargoProc *proc = _tile_type_procs[GetTileType(tile)]->add_produced_cargo_proc;
- if (proc == NULL) return;
+ if (proc == nullptr) return;
proc(tile, produced);
}
static inline void AnimateTile(TileIndex tile)
{
AnimateTileProc *proc = _tile_type_procs[GetTileType(tile)]->animate_tile_proc;
- assert(proc != NULL);
+ assert(proc != nullptr);
proc(tile);
}
static inline bool ClickTile(TileIndex tile)
{
ClickTileProc *proc = _tile_type_procs[GetTileType(tile)]->click_tile_proc;
- if (proc == NULL) return false;
+ if (proc == nullptr) return false;
return proc(tile);
}
diff --git a/src/tile_map.cpp b/src/tile_map.cpp
index 200a20308..5d85ef966 100644
--- a/src/tile_map.cpp
+++ b/src/tile_map.cpp
@@ -34,7 +34,7 @@ static Slope GetTileSlopeGivenHeight(int hnorth, int hwest, int heast, int hsout
int hmines = min(heast, hsouth);
int hmin = min(hminnw, hmines);
- if (h != NULL) *h = hmin;
+ if (h != nullptr) *h = hmin;
int hmaxnw = max(hnorth, hwest);
int hmaxes = max(heast, hsouth);
@@ -55,7 +55,7 @@ static Slope GetTileSlopeGivenHeight(int hnorth, int hwest, int heast, int hsout
/**
* Return the slope of a given tile inside the map.
* @param tile Tile to compute slope of
- * @param h If not \c NULL, pointer to storage of z height
+ * @param h If not \c nullptr, pointer to storage of z height
* @return Slope of the tile, except for the HALFTILE part
*/
Slope GetTileSlope(TileIndex tile, int *h)
@@ -78,7 +78,7 @@ Slope GetTileSlope(TileIndex tile, int *h)
*
* @param x X coordinate of the tile to compute slope of, may be ouside the map.
* @param y Y coordinate of the tile to compute slope of, may be ouside the map.
- * @param h If not \c NULL, pointer to storage of z height.
+ * @param h If not \c nullptr, pointer to storage of z height.
* @return Slope of the tile, except for the HALFTILE part.
*/
Slope GetTilePixelSlopeOutsideMap(int x, int y, int *h)
@@ -89,14 +89,14 @@ Slope GetTilePixelSlopeOutsideMap(int x, int y, int *h)
int hsouth = TileHeightOutsideMap(x + 1, y + 1); // S corner.
Slope s = GetTileSlopeGivenHeight(hnorth, hwest, heast, hsouth, h);
- if (h != NULL) *h *= TILE_HEIGHT;
+ if (h != nullptr) *h *= TILE_HEIGHT;
return s;
}
/**
* Check if a given tile is flat
* @param tile Tile to check
- * @param h If not \c NULL, pointer to storage of z height (only if tile is flat)
+ * @param h If not \c nullptr, pointer to storage of z height (only if tile is flat)
* @return Whether the tile is flat
*/
bool IsTileFlat(TileIndex tile, int *h)
@@ -111,7 +111,7 @@ bool IsTileFlat(TileIndex tile, int *h)
if (TileHeight(TileXY(x1, y2)) != z) return false;
if (TileHeight(TileXY(x2, y2)) != z) return false;
- if (h != NULL) *h = z;
+ if (h != nullptr) *h = z;
return true;
}
diff --git a/src/tile_map.h b/src/tile_map.h
index 7a76f2b97..0cb28122d 100644
--- a/src/tile_map.h
+++ b/src/tile_map.h
@@ -267,22 +267,22 @@ static inline void SetAnimationFrame(TileIndex t, byte frame)
_me[t].m7 = frame;
}
-Slope GetTileSlope(TileIndex tile, int *h = NULL);
+Slope GetTileSlope(TileIndex tile, int *h = nullptr);
int GetTileZ(TileIndex tile);
int GetTileMaxZ(TileIndex tile);
-bool IsTileFlat(TileIndex tile, int *h = NULL);
+bool IsTileFlat(TileIndex tile, int *h = nullptr);
/**
* Return the slope of a given tile
* @param tile Tile to compute slope of
- * @param h If not \c NULL, pointer to storage of z height
+ * @param h If not \c nullptr, pointer to storage of z height
* @return Slope of the tile, except for the HALFTILE part
*/
static inline Slope GetTilePixelSlope(TileIndex tile, int *h)
{
Slope s = GetTileSlope(tile, h);
- if (h != NULL) *h *= TILE_HEIGHT;
+ if (h != nullptr) *h *= TILE_HEIGHT;
return s;
}
diff --git a/src/tilematrix_type.hpp b/src/tilematrix_type.hpp
index f9c7392b2..78cde1643 100644
--- a/src/tilematrix_type.hpp
+++ b/src/tilematrix_type.hpp
@@ -69,7 +69,7 @@ public:
T *data; ///< Pointer to data array.
- TileMatrix() : area(INVALID_TILE, 0, 0), data(NULL) {}
+ TileMatrix() : area(INVALID_TILE, 0, 0), data(nullptr) {}
~TileMatrix()
{
diff --git a/src/timetable_cmd.cpp b/src/timetable_cmd.cpp
index c6c5afe9b..4ab7c746f 100644
--- a/src/timetable_cmd.cpp
+++ b/src/timetable_cmd.cpp
@@ -61,7 +61,7 @@ static void ChangeTimetable(Vehicle *v, VehicleOrderID order_number, uint16 val,
v->orders.list->UpdateTotalDuration(total_delta);
v->orders.list->UpdateTimetableDuration(timetable_delta);
- for (v = v->FirstShared(); v != NULL; v = v->NextShared()) {
+ for (v = v->FirstShared(); v != nullptr; v = v->NextShared()) {
if (v->cur_real_order_index == order_number && v->current_order.Equals(*order)) {
switch (mtf) {
case MTF_WAIT_TIME:
@@ -105,14 +105,14 @@ CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, u
VehicleID veh = GB(p1, 0, 20);
Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
VehicleOrderID order_number = GB(p1, 20, 8);
Order *order = v->GetOrder(order_number);
- if (order == NULL || order->IsType(OT_IMPLICIT)) return CMD_ERROR;
+ if (order == nullptr || order->IsType(OT_IMPLICIT)) return CMD_ERROR;
ModifyTimetableFlags mtf = Extract<ModifyTimetableFlags, 28, 2>(p1);
if (mtf >= MTF_END) return CMD_ERROR;
@@ -199,7 +199,7 @@ CommandCost CmdSetVehicleOnTime(TileIndex tile, DoCommandFlag flags, uint32 p1,
VehicleID veh = GB(p1, 0, 20);
Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle() || v->orders.list == NULL) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle() || v->orders.list == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -268,7 +268,7 @@ CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1,
{
bool timetable_all = HasBit(p1, 20);
Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
- if (v == NULL || !v->IsPrimaryVehicle() || v->orders.list == NULL) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle() || v->orders.list == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -284,7 +284,7 @@ CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1,
std::vector<Vehicle *> vehs;
if (timetable_all) {
- for (Vehicle *w = v->orders.list->GetFirstSharedVehicle(); w != NULL; w = w->NextShared()) {
+ for (Vehicle *w = v->orders.list->GetFirstSharedVehicle(); w != nullptr; w = w->NextShared()) {
vehs.push_back(w);
}
} else {
@@ -334,7 +334,7 @@ CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1,
VehicleID veh = GB(p1, 0, 20);
Vehicle *v = Vehicle::GetIfValid(veh);
- if (v == NULL || !v->IsPrimaryVehicle() || v->orders.list == NULL) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle() || v->orders.list == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -357,7 +357,7 @@ CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1,
ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
}
- for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
+ for (Vehicle *v2 = v->FirstShared(); v2 != nullptr; v2 = v2->NextShared()) {
if (v2 != v) {
/* Stop autofilling; only one vehicle at a time can perform autofill */
ClrBit(v2->vehicle_flags, VF_AUTOFILL_TIMETABLE);
@@ -387,7 +387,7 @@ void UpdateVehicleTimetable(Vehicle *v, bool travelling)
Order *real_current_order = v->GetOrder(v->cur_real_order_index);
VehicleOrderID first_manual_order = 0;
- for (Order *o = v->GetFirstOrder(); o != NULL && o->IsType(OT_IMPLICIT); o = o->next) {
+ for (Order *o = v->GetFirstOrder(); o != nullptr && o->IsType(OT_IMPLICIT); o = o->next) {
++first_manual_order;
}
@@ -477,7 +477,7 @@ void UpdateVehicleTimetable(Vehicle *v, bool travelling)
}
}
- for (v = v->FirstShared(); v != NULL; v = v->NextShared()) {
+ for (v = v->FirstShared(); v != nullptr; v = v->NextShared()) {
SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
}
}
diff --git a/src/timetable_gui.cpp b/src/timetable_gui.cpp
index 8280c0e89..087f3f66f 100644
--- a/src/timetable_gui.cpp
+++ b/src/timetable_gui.cpp
@@ -87,7 +87,7 @@ static bool CanDetermineTimeTaken(const Order *order, bool travelling)
*/
static void FillTimetableArrivalDepartureTable(const Vehicle *v, VehicleOrderID start, bool travelling, TimetableArrivalDeparture *table, Ticks offset)
{
- assert(table != NULL);
+ assert(table != nullptr);
assert(v->GetNumOrders() >= 2);
assert(start < v->GetNumOrders());
@@ -122,7 +122,7 @@ static void FillTimetableArrivalDepartureTable(const Vehicle *v, VehicleOrderID
order = order->next;
if (i >= v->GetNumOrders()) {
i = 0;
- assert(order == NULL);
+ assert(order == nullptr);
order = v->orders.list->GetFirstOrder();
}
} while (i != start);
@@ -309,9 +309,9 @@ struct TimetableWindow : Window {
if (selected != -1) {
const Order *order = v->GetOrder(((selected + 1) / 2) % v->GetNumOrders());
if (selected % 2 == 1) {
- disable = order != NULL && (order->IsType(OT_CONDITIONAL) || order->IsType(OT_IMPLICIT));
+ disable = order != nullptr && (order->IsType(OT_CONDITIONAL) || order->IsType(OT_IMPLICIT));
} else {
- disable = order == NULL || ((!order->IsType(OT_GOTO_STATION) || (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) && !order->IsType(OT_CONDITIONAL));
+ disable = order == nullptr || ((!order->IsType(OT_GOTO_STATION) || (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION)) && !order->IsType(OT_CONDITIONAL));
}
}
bool disable_speed = disable || selected % 2 != 1 || v->type == VEH_AIRCRAFT;
@@ -322,9 +322,9 @@ struct TimetableWindow : Window {
this->SetWidgetDisabledState(WID_VT_CLEAR_SPEED, disable_speed);
this->SetWidgetDisabledState(WID_VT_SHARED_ORDER_LIST, !v->IsOrderListShared());
- this->SetWidgetDisabledState(WID_VT_START_DATE, v->orders.list == NULL);
- this->SetWidgetDisabledState(WID_VT_RESET_LATENESS, v->orders.list == NULL);
- this->SetWidgetDisabledState(WID_VT_AUTOFILL, v->orders.list == NULL);
+ this->SetWidgetDisabledState(WID_VT_START_DATE, v->orders.list == nullptr);
+ this->SetWidgetDisabledState(WID_VT_RESET_LATENESS, v->orders.list == nullptr);
+ this->SetWidgetDisabledState(WID_VT_AUTOFILL, v->orders.list == nullptr);
} else {
this->DisableWidget(WID_VT_START_DATE);
this->DisableWidget(WID_VT_CHANGE_TIME);
@@ -367,7 +367,7 @@ struct TimetableWindow : Window {
int middle = rtl ? r.right - WD_FRAMERECT_RIGHT - index_column_width : r.left + WD_FRAMERECT_LEFT + index_column_width;
const Order *order = v->GetOrder(order_id);
- while (order != NULL) {
+ while (order != nullptr) {
/* Don't draw anything if it extends past the end of the window. */
if (!this->vscroll->IsVisible(i)) break;
@@ -424,7 +424,7 @@ struct TimetableWindow : Window {
* i.e. are only shown if we can calculate all times.
* Excluding order lists with only one order makes some things easier.
*/
- Ticks total_time = v->orders.list != NULL ? v->orders.list->GetTimetableDurationIncomplete() : 0;
+ Ticks total_time = v->orders.list != nullptr ? v->orders.list->GetTimetableDurationIncomplete() : 0;
if (total_time <= 0 || v->GetNumOrders() <= 1 || !HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)) break;
TimetableArrivalDeparture *arr_dep = AllocaM(TimetableArrivalDeparture, v->GetNumOrders());
@@ -475,7 +475,7 @@ struct TimetableWindow : Window {
case WID_VT_SUMMARY_PANEL: {
int y = r.top + WD_FRAMERECT_TOP;
- Ticks total_time = v->orders.list != NULL ? v->orders.list->GetTimetableDurationIncomplete() : 0;
+ Ticks total_time = v->orders.list != nullptr ? v->orders.list->GetTimetableDurationIncomplete() : 0;
if (total_time != 0) {
SetTimetableParams(0, 1, total_time);
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, v->orders.list->IsCompleteTimetable() ? STR_TIMETABLE_TOTAL_TIME : STR_TIMETABLE_TOTAL_TIME_INCOMPLETE);
@@ -543,7 +543,7 @@ struct TimetableWindow : Window {
const Order *order = v->GetOrder(real);
StringID current = STR_EMPTY;
- if (order != NULL) {
+ if (order != nullptr) {
uint time = (selected % 2 == 1) ? order->GetTravelTime() : order->GetWaitTime();
if (!_settings_client.gui.timetable_in_ticks) time /= DAY_TICKS;
@@ -566,7 +566,7 @@ struct TimetableWindow : Window {
StringID current = STR_EMPTY;
const Order *order = v->GetOrder(real);
- if (order != NULL) {
+ if (order != nullptr) {
if (order->GetMaxSpeed() != UINT16_MAX) {
SetDParam(0, ConvertKmhishSpeedToDisplaySpeed(order->GetMaxSpeed()));
current = STR_JUST_INT;
@@ -616,13 +616,13 @@ struct TimetableWindow : Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
const Vehicle *v = this->vehicle;
uint32 p1 = PackTimetableArgs(v, this->sel_index, this->query_is_speed_query);
- uint64 val = StrEmpty(str) ? 0 : strtoul(str, NULL, 10);
+ uint64 val = StrEmpty(str) ? 0 : strtoul(str, nullptr, 10);
if (this->query_is_speed_query) {
val = ConvertDisplaySpeedToKmhishSpeed(val);
} else {
diff --git a/src/toolbar_gui.cpp b/src/toolbar_gui.cpp
index 00d0bba0b..bd7472ecd 100644
--- a/src/toolbar_gui.cpp
+++ b/src/toolbar_gui.cpp
@@ -616,7 +616,7 @@ static CallBackFunction MenuClickCompany(int index)
if (_network_server) {
DoCommandP(0, CCA_NEW, _network_own_client_id, CMD_COMPANY_CTRL);
} else {
- NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
+ NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company);
}
return CBF_NONE;
@@ -1055,7 +1055,7 @@ static CallBackFunction ToolbarHelpClick(Window *w)
static void MenuClickSmallScreenshot()
{
- MakeScreenshot(SC_VIEWPORT, NULL);
+ MakeScreenshot(SC_VIEWPORT, nullptr);
}
/**
@@ -1065,7 +1065,7 @@ static void MenuClickSmallScreenshot()
*/
static void ScreenshotConfirmCallback(Window *w, bool confirmed)
{
- if (confirmed) MakeScreenshot(_confirmed_screenshot_type, NULL);
+ if (confirmed) MakeScreenshot(_confirmed_screenshot_type, nullptr);
}
/**
@@ -1082,10 +1082,10 @@ static void MenuClickLargeWorldScreenshot(ScreenshotType t)
SetDParam(0, vp.width);
SetDParam(1, vp.height);
_confirmed_screenshot_type = t;
- ShowQuery(STR_WARNING_SCREENSHOT_SIZE_CAPTION, STR_WARNING_SCREENSHOT_SIZE_MESSAGE, NULL, ScreenshotConfirmCallback);
+ ShowQuery(STR_WARNING_SCREENSHOT_SIZE_CAPTION, STR_WARNING_SCREENSHOT_SIZE_MESSAGE, nullptr, ScreenshotConfirmCallback);
} else {
/* Less than 64M pixels, just do it */
- MakeScreenshot(t, NULL);
+ MakeScreenshot(t, nullptr);
}
}
@@ -1280,8 +1280,8 @@ static CallBackFunction ToolbarBtn_NULL(Window *w)
typedef CallBackFunction MenuClickedProc(int index);
static MenuClickedProc * const _menu_clicked_procs[] = {
- NULL, // 0
- NULL, // 1
+ nullptr, // 0
+ nullptr, // 1
MenuClickSettings, // 2
MenuClickSaveLoad, // 3
MenuClickMap, // 4
@@ -1300,7 +1300,7 @@ static MenuClickedProc * const _menu_clicked_procs[] = {
MenuClickShowShips, // 17
MenuClickShowAir, // 18
MenuClickMap, // 19
- NULL, // 20
+ nullptr, // 20
MenuClickBuildRail, // 21
MenuClickBuildRoad, // 22
MenuClickBuildWater, // 23
@@ -1344,7 +1344,7 @@ public:
uint nbuttons = 0;
/* First initialise some variables... */
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->SetupSmallestSize(w, init_array);
this->smallest_y = max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
if (this->IsButton(child_wid->type)) {
@@ -1356,7 +1356,7 @@ public:
}
/* ... then in a second pass make sure the 'current' heights are set. Won't change ever. */
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->current_y = this->smallest_y;
if (!this->IsButton(child_wid->type)) {
child_wid->current_x = child_wid->smallest_x;
@@ -1384,7 +1384,7 @@ public:
/* Create us ourselves a quick lookup table */
NWidgetBase *widgets[WID_TN_END];
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (child_wid->type == NWID_SPACER) continue;
widgets[((NWidgetCore*)child_wid)->index] = child_wid;
}
@@ -1403,7 +1403,7 @@ public:
/* If we have to give space to the spacers, do that */
if (spacer_space != 0) {
NWidgetBase *possible_spacer = rtl ? child_wid->next : child_wid->prev;
- if (possible_spacer != NULL && possible_spacer->type == NWID_SPACER) {
+ if (possible_spacer != nullptr && possible_spacer->type == NWID_SPACER) {
uint add = spacer_space / (spacer_count - spacer_i);
position += add;
spacer_space -= add;
@@ -1435,7 +1435,7 @@ public:
GfxFillRect(this->pos_x, this->pos_y, this->pos_x + this->current_x - 1, this->pos_y + this->current_y - 1, PC_DARK_RED, FILLRECT_CHECKER);
bool rtl = _current_text_dir == TD_RTL;
- for (NWidgetBase *child_wid = rtl ? this->tail : this->head; child_wid != NULL; child_wid = rtl ? child_wid->prev : child_wid->next) {
+ for (NWidgetBase *child_wid = rtl ? this->tail : this->head; child_wid != nullptr; child_wid = rtl ? child_wid->prev : child_wid->next) {
if (child_wid->type == NWID_SPACER) continue;
if (!this->visible[((NWidgetCore*)child_wid)->index]) continue;
@@ -1445,16 +1445,16 @@ public:
NWidgetCore *GetWidgetFromPos(int x, int y) override
{
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (child_wid->type == NWID_SPACER) continue;
if (!this->visible[((NWidgetCore*)child_wid)->index]) continue;
NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
- if (nwid != NULL) return nwid;
+ if (nwid != nullptr) return nwid;
}
- return NULL;
+ return nullptr;
}
/**
@@ -1799,7 +1799,7 @@ class NWidgetScenarioToolbarContainer : public NWidgetToolbarContainer {
/* Find the size of panel_widths */
uint i = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (child_wid->type == NWID_SPACER || this->IsButton(child_wid->type)) continue;
assert(i < lengthof(this->panel_widths));
@@ -2133,7 +2133,7 @@ struct MainToolbarWindow : Window {
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (!gui_scope) return;
- if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) HandleZoomMessage(this, FindWindowById(WC_MAIN_WINDOW, 0)->viewport, WID_TN_ZOOM_IN, WID_TN_ZOOM_OUT);
+ if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) HandleZoomMessage(this, FindWindowById(WC_MAIN_WINDOW, 0)->viewport, WID_TN_ZOOM_IN, WID_TN_ZOOM_OUT);
}
static HotkeyList hotkeys;
@@ -2247,7 +2247,7 @@ static const NWidgetPart _nested_toolbar_normal_widgets[] = {
};
static WindowDesc _toolb_normal_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_MAIN_TOOLBAR, WC_NONE,
WDF_NO_FOCUS,
_nested_toolbar_normal_widgets, lengthof(_nested_toolbar_normal_widgets),
@@ -2277,15 +2277,15 @@ static ToolbarButtonProc * const _scen_toolbar_button_procs[] = {
ToolbarScenPlantTrees,
ToolbarScenPlaceSign,
ToolbarBtn_NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
ToolbarMusicClick,
- NULL,
+ nullptr,
ToolbarHelpClick,
ToolbarSwitchClick,
};
@@ -2479,13 +2479,13 @@ struct ScenarioEditorToolbarWindow : Window {
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (!gui_scope) return;
- if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) HandleZoomMessage(this, FindWindowById(WC_MAIN_WINDOW, 0)->viewport, WID_TE_ZOOM_IN, WID_TE_ZOOM_OUT);
+ if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) HandleZoomMessage(this, FindWindowById(WC_MAIN_WINDOW, 0)->viewport, WID_TE_ZOOM_IN, WID_TE_ZOOM_OUT);
}
void OnQueryTextFinished(char *str) override
{
/* Was 'cancel' pressed? */
- if (str == NULL) return;
+ if (str == nullptr) return;
int32 value;
if (!StrEmpty(str)) {
@@ -2573,7 +2573,7 @@ static const NWidgetPart _nested_toolb_scen_widgets[] = {
};
static WindowDesc _toolb_scen_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_MAIN_TOOLBAR, WC_NONE,
WDF_NO_FOCUS,
_nested_toolb_scen_widgets, lengthof(_nested_toolb_scen_widgets),
diff --git a/src/town.h b/src/town.h
index 76c3b770d..3d7d00b75 100644
--- a/src/town.h
+++ b/src/town.h
@@ -61,7 +61,7 @@ struct Town : TownPool::PoolItem<&_town_pool> {
uint32 townnamegrfid;
uint16 townnametype;
uint32 townnameparts;
- char *name; ///< Custom town name. If NULL, the town was not renamed and uses the generated name.
+ char *name; ///< Custom town name. If nullptr, the town was not renamed and uses the generated name.
byte flags; ///< See #TownFlags.
@@ -233,7 +233,7 @@ template <class T>
void MakeDefaultName(T *obj)
{
/* We only want to set names if it hasn't been set before, or when we're calling from afterload. */
- assert(obj->name == NULL || obj->town_cn == UINT16_MAX);
+ assert(obj->name == nullptr || obj->town_cn == UINT16_MAX);
obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
@@ -257,7 +257,7 @@ void MakeDefaultName(T *obj)
T *lobj = T::GetIfValid(cid);
/* check only valid waypoints... */
- if (lobj != NULL && obj != lobj) {
+ if (lobj != nullptr && obj != lobj) {
/* only objects within the same city and with the same type */
if (lobj->town == obj->town && lobj->IsOfType(obj)) {
/* if lobj->town_cn < next, uint will overflow to '+inf' */
diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp
index d918fbced..367eba45f 100644
--- a/src/town_cmd.cpp
+++ b/src/town_cmd.cpp
@@ -163,7 +163,7 @@ void Town::PostDestructor(size_t index)
/* Give objects a new home! */
Object *o;
FOR_ALL_OBJECTS(o) {
- if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
+ if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
}
}
@@ -182,11 +182,11 @@ void Town::InitializeLayout(TownLayout layout)
/**
* Return a random valid town.
- * @return random town, NULL if there are no towns
+ * @return random town, nullptr if there are no towns
*/
/* static */ Town *Town::GetRandom()
{
- if (Town::GetNumItems() == 0) return NULL;
+ if (Town::GetNumItems() == 0) return nullptr;
int num = RandomRange((uint16)Town::GetNumItems());
size_t index = MAX_UVALUE(size_t);
@@ -259,7 +259,7 @@ static void DrawTile_Town(TileInfo *ti)
/* Houses don't necessarily need new graphics. If they don't have a
* spritegroup associated with them, then the sprite for the substitute
* house id is drawn instead. */
- if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
+ if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
DrawNewHouseTile(ti, house_id);
return;
} else {
@@ -316,7 +316,7 @@ static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
*/
if (hid >= NEW_HOUSE_OFFSET) {
const HouseSpec *hs = HouseSpec::Get(hid);
- if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
+ if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
}
@@ -752,7 +752,7 @@ static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
}
- if (hs->grf_prop.grffile != NULL) {
+ if (hs->grf_prop.grffile != nullptr) {
const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
td->grf = gc->GetName();
}
@@ -1683,12 +1683,12 @@ static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize
/* Set the default cargo requirement for town growth */
switch (_settings_game.game_creation.landscape) {
case LT_ARCTIC:
- if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
+ if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
break;
case LT_TROPIC:
- if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
- if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
+ if (FindFirstCargoWithTownEffect(TE_FOOD) != nullptr) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
+ if (FindFirstCargoWithTownEffect(TE_WATER) != nullptr) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
break;
}
@@ -1776,7 +1776,7 @@ static bool IsUniqueTownName(const char *name)
const Town *t;
FOR_ALL_TOWNS(t) {
- if (t->name != NULL && strcmp(t->name, name) == 0) return false;
+ if (t->name != nullptr && strcmp(t->name, name) == 0) return false;
}
return true;
@@ -1857,7 +1857,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
Town *t;
if (random) {
t = CreateRandomTown(20, townnameparts, size, city, layout);
- if (t == NULL) {
+ if (t == nullptr) {
cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
} else {
_new_town_id = t->index;
@@ -1869,13 +1869,13 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
UpdateNearestTownForRoadTiles(false);
old_generating_world.Restore();
- if (t != NULL && !StrEmpty(text)) {
+ if (t != nullptr && !StrEmpty(text)) {
t->name = stredup(text);
t->UpdateVirtCoord();
}
if (_game_mode != GM_EDITOR) {
- /* 't' can't be NULL since 'random' is false outside scenedit */
+ /* 't' can't be nullptr since 'random' is false outside scenedit */
assert(!random);
if (_current_company == OWNER_DEITY) {
@@ -2004,7 +2004,7 @@ static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layou
SpotData sp = { INVALID_TILE, 0, layout };
TileIndex coast = tile;
- if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
+ if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
return sp.tile;
}
@@ -2017,7 +2017,7 @@ static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size
{
assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
- if (!Town::CanAllocateItem()) return NULL;
+ if (!Town::CanAllocateItem()) return nullptr;
do {
/* Generate a tile index not too close from the edge */
@@ -2054,7 +2054,7 @@ static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size
assert(Town::CanAllocateItem());
} while (--attempts != 0);
- return NULL;
+ return nullptr;
}
static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
@@ -2086,7 +2086,7 @@ bool GenerateTowns(TownLayout layout)
/* Get a unique name for the town. */
if (!GenerateTownName(&townnameparts, &town_names)) continue;
/* try 20 times to create a random-sized town for the first loop. */
- if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
+ if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
} while (--total);
town_names.clear();
@@ -2099,7 +2099,7 @@ bool GenerateTowns(TownLayout layout)
/* If current_number is still zero at this point, it means that not a single town has been created.
* So give it a last try, but now more aggressive */
if (GenerateTownName(&townnameparts) &&
- CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
+ CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
return true;
}
@@ -2608,7 +2608,7 @@ void ClearTownHouse(Town *t, TileIndex tile)
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Town *t = Town::GetIfValid(p1);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
bool reset = StrEmpty(text);
@@ -2619,7 +2619,7 @@ CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (flags & DC_EXEC) {
free(t->name);
- t->name = reset ? NULL : stredup(text);
+ t->name = reset ? nullptr : stredup(text);
t->UpdateVirtCoord();
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
@@ -2639,7 +2639,7 @@ const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
FOR_ALL_CARGOSPECS(cs) {
if (cs->town_effect == effect) return cs;
}
- return NULL;
+ return nullptr;
}
/**
@@ -2662,11 +2662,11 @@ CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
uint16 index = GB(p1, 0, 16);
Town *t = Town::GetIfValid(index);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
/* Validate if there is a cargo which is the requested TownEffect */
const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
- if (cargo == NULL) return CMD_ERROR;
+ if (cargo == nullptr) return CMD_ERROR;
if (flags & DC_EXEC) {
t->goal[te] = p2;
@@ -2690,11 +2690,11 @@ CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
{
if (_current_company != OWNER_DEITY) return CMD_ERROR;
Town *t = Town::GetIfValid(p1);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
if (flags & DC_EXEC) {
free(t->text);
- t->text = StrEmpty(text) ? NULL : stredup(text);
+ t->text = StrEmpty(text) ? nullptr : stredup(text);
InvalidateWindowData(WC_TOWN_VIEW, p1);
}
@@ -2716,7 +2716,7 @@ CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
if (GB(p2, 16, 16) != 0) return CMD_ERROR;
Town *t = Town::GetIfValid(p1);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
if (flags & DC_EXEC) {
if (p2 == 0) {
@@ -2754,7 +2754,7 @@ CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
{
if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
Town *t = Town::GetIfValid(p1);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
if (flags & DC_EXEC) {
/* The more houses, the faster we grow */
@@ -2794,7 +2794,7 @@ CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
{
if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
Town *t = Town::GetIfValid(p1);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
/* Stations refer to towns. */
const Station *st;
@@ -2853,7 +2853,7 @@ CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
try_clear = true;
} else {
/* Tell to find a new town. */
- if (flags & DC_EXEC) o->town = NULL;
+ if (flags & DC_EXEC) o->town = nullptr;
}
}
}
@@ -3124,7 +3124,7 @@ static TownActionProc * const _town_action_proc[] = {
/**
* Get a list of available actions to do at a town.
- * @param nump if not NULL add put the number of available actions in it
+ * @param nump if not nullptr add put the number of available actions in it
* @param cid the company that is querying the town
* @param t the town that is queried
* @return bitmasked value of enabled actions
@@ -3167,7 +3167,7 @@ uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
}
}
- if (nump != NULL) *nump = num;
+ if (nump != nullptr) *nump = num;
return buttons;
}
@@ -3185,9 +3185,9 @@ uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Town *t = Town::GetIfValid(p1);
- if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
+ if (t == nullptr || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
- if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
+ if (!HasBit(GetMaskOfTownActions(nullptr, _current_company, t), p2)) return CMD_ERROR;
CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
@@ -3389,7 +3389,7 @@ CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags
if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
- if (t == NULL) return CommandCost();
+ if (t == nullptr) return CommandCost();
if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
@@ -3401,25 +3401,25 @@ CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags
* Return the town closest to the given tile within \a threshold.
* @param tile Starting point of the search.
* @param threshold Biggest allowed distance to the town.
- * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
+ * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
*
* @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
*/
Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
{
- if (Town::GetNumItems() == 0) return NULL;
+ if (Town::GetNumItems() == 0) return nullptr;
TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
Town *town = Town::Get(tid);
if (DistanceManhattan(tile, town->xy) < threshold) return town;
- return NULL;
+ return nullptr;
}
/**
* Return the town closest (in distance or ownership) to a given tile, within a given threshold.
* @param tile Starting point of the search.
* @param threshold Biggest allowed distance to the town.
- * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
+ * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
*
* @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
*/
@@ -3436,13 +3436,13 @@ Town *ClosestTownFromTile(TileIndex tile, uint threshold)
/* in the case we are generating "many random towns", this value may be INVALID_TOWN */
if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
assert(Town::GetNumItems() == 0);
- return NULL;
+ return nullptr;
}
assert(Town::IsValidID(tid));
Town *town = Town::Get(tid);
- if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
+ if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
return town;
}
@@ -3505,7 +3505,7 @@ static int GetRating(const Town *t)
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
{
/* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
- if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
+ if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
!Company::IsValidID(_current_company) ||
(_cheats.magic_bulldozer.value && add < 0)) {
return;
@@ -3542,7 +3542,7 @@ void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
{
/* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
- if (t == NULL || !Company::IsValidID(_current_company) ||
+ if (t == nullptr || !Company::IsValidID(_current_company) ||
_cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
return CommandCost();
}
@@ -3635,12 +3635,12 @@ extern const TileTypeProcs _tile_type_town_procs = {
AddAcceptedCargo_Town, // add_accepted_cargo_proc
GetTileDesc_Town, // get_tile_desc_proc
GetTileTrackStatus_Town, // get_tile_track_status_proc
- NULL, // click_tile_proc
+ nullptr, // click_tile_proc
AnimateTile_Town, // animate_tile_proc
TileLoop_Town, // tile_loop_proc
ChangeTileOwner_Town, // change_tile_owner_proc
AddProducedCargo_Town, // add_produced_cargo_proc
- NULL, // vehicle_enter_tile_proc
+ nullptr, // vehicle_enter_tile_proc
GetFoundation_Town, // get_foundation_proc
TerraformTile_Town, // terraform_tile_proc
};
diff --git a/src/town_gui.cpp b/src/town_gui.cpp
index cf5d43026..0f35341f6 100644
--- a/src/town_gui.cpp
+++ b/src/town_gui.cpp
@@ -261,7 +261,7 @@ public:
int y = this->GetRowFromWidget(pt.y, WID_TA_COMMAND_LIST, 1, FONT_HEIGHT_NORMAL);
if (!IsInsideMM(y, 0, 5)) return;
- y = GetNthSetBit(GetMaskOfTownActions(NULL, _local_company, this->town), y + this->vscroll->GetPosition() - 1);
+ y = GetNthSetBit(GetMaskOfTownActions(nullptr, _local_company, this->town), y + this->vscroll->GetPosition() - 1);
if (y >= 0) {
this->sel_index = y;
this->SetDirty();
@@ -362,7 +362,7 @@ public:
uint cargo_text_right = r.right - WD_FRAMERECT_RIGHT - (rtl ? 20 : 0);
const CargoSpec *cargo = FindFirstCargoWithTownEffect((TownEffect)i);
- assert(cargo != NULL);
+ assert(cargo != nullptr);
StringID string;
@@ -406,7 +406,7 @@ public:
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_LEFT, y += FONT_HEIGHT_NORMAL, STR_TOWN_VIEW_NOISE_IN_TOWN);
}
- if (this->town->text != NULL) {
+ if (this->town->text != nullptr) {
SetDParamStr(0, this->town->text);
DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y += FONT_HEIGHT_NORMAL, UINT16_MAX, STR_JUST_RAW_STRING, TC_BLACK);
}
@@ -484,7 +484,7 @@ public:
if (_settings_game.economy.station_noise_level) aimed_height += FONT_HEIGHT_NORMAL;
- if (this->town->text != NULL) {
+ if (this->town->text != nullptr) {
SetDParamStr(0, this->town->text);
aimed_height += GetStringHeight(STR_JUST_RAW_STRING, width - WD_FRAMERECT_LEFT - WD_FRAMERECT_RIGHT);
}
@@ -503,7 +503,7 @@ public:
void OnResize() override
{
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_TV_VIEWPORT);
nvp->UpdateViewportCoordinates(this);
@@ -526,9 +526,9 @@ public:
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
- DoCommandP(0, this->window_number, 0, CMD_RENAME_TOWN | CMD_MSG(STR_ERROR_CAN_T_RENAME_TOWN), NULL, str);
+ DoCommandP(0, this->window_number, 0, CMD_RENAME_TOWN | CMD_MSG(STR_ERROR_CAN_T_RENAME_TOWN), nullptr, str);
}
};
@@ -662,7 +662,7 @@ private:
this->vscroll->SetCount((uint)this->towns.size()); // Update scrollbar as well.
}
/* Always sort the towns. */
- this->last_town = NULL;
+ this->last_town = nullptr;
this->towns.Sort();
this->SetWidgetDirty(WID_TD_LIST); // Force repaint of the displayed towns.
}
@@ -829,7 +829,7 @@ public:
for (uint i = 0; i < this->towns.size(); i++) {
const Town *t = this->towns[i];
- assert(t != NULL);
+ assert(t != nullptr);
SetDParam(0, t->index);
SetDParamMaxDigits(1, 8);
@@ -882,7 +882,7 @@ public:
if (id_v >= this->towns.size()) return; // click out of town bounds
const Town *t = this->towns[id_v];
- assert(t != NULL);
+ assert(t != nullptr);
if (_ctrl_pressed) {
ShowExtraViewPortWindow(t->xy);
} else {
@@ -938,7 +938,7 @@ public:
};
Listing TownDirectoryWindow::last_sorting = {false, 0};
-const Town *TownDirectoryWindow::last_town = NULL;
+const Town *TownDirectoryWindow::last_town = nullptr;
/** Names of the sorting functions. */
const StringID TownDirectoryWindow::sorter_names[] = {
@@ -1111,7 +1111,7 @@ public:
void ExecuteFoundTownCommand(TileIndex tile, bool random, StringID errstr, CommandCallback cc)
{
- const char *name = NULL;
+ const char *name = nullptr;
if (!this->townnamevalid) {
name = this->townname_editbox.text.buf;
diff --git a/src/townname.cpp b/src/townname.cpp
index b6d55f1ef..d382adf34 100644
--- a/src/townname.cpp
+++ b/src/townname.cpp
@@ -31,7 +31,7 @@ TownNameParams::TownNameParams(const Town *t) :
grfid(t->townnamegrfid), // by default, use supplied data
type(t->townnametype)
{
- if (t->townnamegrfid != 0 && GetGRFTownName(t->townnamegrfid) == NULL) {
+ if (t->townnamegrfid != 0 && GetGRFTownName(t->townnamegrfid) == nullptr) {
/* Fallback to english original */
this->grfid = 0;
this->type = SPECSTR_TOWNNAME_ENGLISH;
@@ -92,7 +92,7 @@ bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
/* Check size and width */
if (Utf8StringLength(buf1) >= MAX_LENGTH_TOWN_NAME_CHARS) return false;
- if (town_names != NULL) {
+ if (town_names != nullptr) {
if (town_names->find(buf1) != town_names->end()) return false;
town_names->insert(buf1);
} else {
@@ -101,7 +101,7 @@ bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
/* We can't just compare the numbers since
* several numbers may map to a single name. */
const char *buf = t->name;
- if (buf == NULL) {
+ if (buf == nullptr) {
GetTownName(buf2, t, lastof(buf2));
buf = buf2;
}
@@ -504,8 +504,8 @@ static char *MakeFinnishTownName(char *buf, const char *last, uint32 seed)
char *end = buf - 1;
assert(end >= orig);
if (*end == 'i') *end = 'e';
- if (strstr(orig, "a") != NULL || strstr(orig, "o") != NULL || strstr(orig, "u") != NULL ||
- strstr(orig, "A") != NULL || strstr(orig, "O") != NULL || strstr(orig, "U") != NULL) {
+ if (strstr(orig, "a") != nullptr || strstr(orig, "o") != nullptr || strstr(orig, "u") != nullptr ||
+ strstr(orig, "A") != nullptr || strstr(orig, "O") != nullptr || strstr(orig, "U") != nullptr) {
buf = strecpy(buf, "la", last);
} else {
buf = strecpy(buf, "l\xC3\xA4", last);
diff --git a/src/townname_func.h b/src/townname_func.h
index 409993e42..b175f3daf 100644
--- a/src/townname_func.h
+++ b/src/townname_func.h
@@ -17,7 +17,7 @@
char *GenerateTownNameString(char *buf, const char *last, size_t lang, uint32 seed);
char *GetTownName(char *buff, const TownNameParams *par, uint32 townnameparts, const char *last);
char *GetTownName(char *buff, const Town *t, const char *last);
-bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names = NULL);
-bool GenerateTownName(uint32 *townnameparts, TownNames *town_names = NULL);
+bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names = nullptr);
+bool GenerateTownName(uint32 *townnameparts, TownNames *town_names = nullptr);
#endif /* TOWNNAME_FUNC_H */
diff --git a/src/train.h b/src/train.h
index 5958cde1a..3bbb6cafb 100644
--- a/src/train.h
+++ b/src/train.h
@@ -118,7 +118,7 @@ struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
int GetDisplaySpeed() const { return this->gcache.last_speed; }
int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed; }
Money GetRunningCost() const;
- int GetDisplayImageWidth(Point *offset = NULL) const;
+ int GetDisplayImageWidth(Point *offset = nullptr) const;
bool IsInDepot() const { return this->track == TRACK_BIT_DEPOT; }
bool Tick();
void OnNewDay();
@@ -146,7 +146,7 @@ struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
inline Train *GetNextUnit() const
{
Train *v = this->GetNextVehicle();
- if (v != NULL && v->IsRearDualheaded()) v = v->GetNextVehicle();
+ if (v != nullptr && v->IsRearDualheaded()) v = v->GetNextVehicle();
return v;
}
@@ -158,7 +158,7 @@ struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
inline Train *GetPrevUnit()
{
Train *v = this->GetPrevVehicle();
- if (v != NULL && v->IsRearDualheaded()) v = v->GetPrevVehicle();
+ if (v != nullptr && v->IsRearDualheaded()) v = v->GetPrevVehicle();
return v;
}
@@ -173,7 +173,7 @@ struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
* longer than the part after the center. This means we have to round up the
* length of the next vehicle but may not round the length of the current
* vehicle. */
- return this->gcache.cached_veh_length / 2 + (this->Next() != NULL ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
+ return this->gcache.cached_veh_length / 2 + (this->Next() != nullptr ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
}
protected: // These functions should not be called outside acceleration code.
diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp
index 008d51557..71b34d6ba 100644
--- a/src/train_cmd.cpp
+++ b/src/train_cmd.cpp
@@ -78,7 +78,7 @@ void CheckTrainsLengths()
FOR_ALL_TRAINS(v) {
if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
- for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
+ for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
if (u->track != TRACK_BIT_DEPOT) {
if ((w->track != TRACK_BIT_DEPOT &&
max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
@@ -119,7 +119,7 @@ void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
bool train_can_tilt = true;
- for (Train *u = this; u != NULL; u = u->Next()) {
+ for (Train *u = this; u != nullptr; u = u->Next()) {
const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
/* Check the this->first cache. */
@@ -137,20 +137,20 @@ void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
u->InvalidateNewGRFCache();
}
- for (Train *u = this; u != NULL; u = u->Next()) {
+ for (Train *u = this; u != nullptr; u = u->Next()) {
/* Update user defined data (must be done before other properties) */
u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
this->InvalidateNewGRFCache();
u->InvalidateNewGRFCache();
}
- for (Train *u = this; u != NULL; u = u->Next()) {
+ for (Train *u = this; u != nullptr; u = u->Next()) {
const Engine *e_u = u->GetEngine();
const RailVehicleInfo *rvi_u = &e_u->u.rail;
if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
- /* Cache wagon override sprite group. NULL is returned if there is none */
+ /* Cache wagon override sprite group. nullptr is returned if there is none */
u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
/* Reset colour map */
@@ -202,7 +202,7 @@ void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
/* check the vehicle length (callback) */
uint16 veh_len = CALLBACK_FAILED;
- if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
+ if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
/* Use callback 36 */
veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
@@ -316,7 +316,7 @@ int Train::GetCurveSpeedLimit() const
int sum = 0;
int pos = 0;
int lastpos = -1;
- for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
+ for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
Direction this_dir = u->direction;
Direction next_dir = u->Next()->direction;
@@ -400,7 +400,7 @@ int Train::GetCurrentMaxSpeed() const
}
}
- for (const Train *u = this; u != NULL; u = u->Next()) {
+ for (const Train *u = this; u != nullptr; u = u->Next()) {
if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
max_speed = min(max_speed, 61);
break;
@@ -429,7 +429,7 @@ void Train::UpdateAcceleration()
/**
* Get the width of a train vehicle image in the GUI.
- * @param offset Additional offset for positioning the sprite; set to NULL if not needed
+ * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
* @return Width in pixels
*/
int Train::GetDisplayImageWidth(Point *offset) const
@@ -438,12 +438,12 @@ int Train::GetDisplayImageWidth(Point *offset) const
int vehicle_pitch = 0;
const Engine *e = this->GetEngine();
- if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
+ if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
reference_width = e->GetGRF()->traininfo_vehicle_width;
vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
}
- if (offset != NULL) {
+ if (offset != nullptr) {
offset->x = ScaleGUITrad(reference_width) / 2;
offset->y = ScaleGUITrad(vehicle_pitch);
}
@@ -492,7 +492,7 @@ static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType
if (is_custom_sprite(spritenum)) {
GetCustomVehicleIcon(engine, dir, image_type, result);
if (result->IsValid()) {
- if (e->GetGRF() != NULL) {
+ if (e->GetGRF() != nullptr) {
y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
}
return;
@@ -805,12 +805,12 @@ static Train *FindGoodVehiclePos(const Train *src)
Train *t = dst;
while (t->engine_type == eng) {
t = t->Next();
- if (t == NULL) return dst;
+ if (t == nullptr) return dst;
}
}
}
- return NULL;
+ return nullptr;
}
/** Helper type for lists/vectors of trains */
@@ -823,7 +823,7 @@ typedef std::vector<Train *> TrainList;
*/
static void MakeTrainBackup(TrainList &list, Train *t)
{
- for (; t != NULL; t = t->Next()) list.push_back(t);
+ for (; t != nullptr; t = t->Next()) list.push_back(t);
}
/**
@@ -835,14 +835,14 @@ static void RestoreTrainBackup(TrainList &list)
/* No train, nothing to do. */
if (list.size() == 0) return;
- Train *prev = NULL;
+ Train *prev = nullptr;
/* Iterate over the list and rebuild it. */
for (Train *t : list) {
- if (prev != NULL) {
+ if (prev != nullptr) {
prev->SetNext(t);
- } else if (t->Previous() != NULL) {
+ } else if (t->Previous() != nullptr) {
/* Make sure the head of the train is always the first in the chain. */
- t->Previous()->SetNext(NULL);
+ t->Previous()->SetNext(nullptr);
}
prev = t;
}
@@ -859,10 +859,10 @@ static void RemoveFromConsist(Train *part, bool chain = false)
/* Unlink at the front, but make it point to the next
* vehicle after the to be remove part. */
- if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
+ if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
/* Unlink at the back */
- tail->SetNext(NULL);
+ tail->SetNext(nullptr);
}
/**
@@ -873,7 +873,7 @@ static void RemoveFromConsist(Train *part, bool chain = false)
static void InsertInConsist(Train *dst, Train *chain)
{
/* We do not want to add something in the middle of an articulated part. */
- assert(dst != NULL && (dst->Next() == NULL || !dst->Next()->IsArticulatedPart()));
+ assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
chain->Last()->SetNext(dst->Next());
dst->SetNext(chain);
@@ -886,12 +886,12 @@ static void InsertInConsist(Train *dst, Train *chain)
*/
static void NormaliseDualHeads(Train *t)
{
- for (; t != NULL; t = t->GetNextVehicle()) {
+ for (; t != nullptr; t = t->GetNextVehicle()) {
if (!t->IsMultiheaded() || !t->IsEngine()) continue;
/* Make sure that there are no free cars before next engine */
Train *u;
- for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
+ for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
if (u == t->other_multiheaded_part) continue;
@@ -909,10 +909,10 @@ static void NormaliseDualHeads(Train *t)
static void NormaliseSubtypes(Train *chain)
{
/* Nothing to do */
- if (chain == NULL) return;
+ if (chain == nullptr) return;
/* We must be the first in the chain. */
- assert(chain->Previous() == NULL);
+ assert(chain->Previous() == nullptr);
/* Set the appropriate bits for the first in the chain. */
if (chain->IsWagon()) {
@@ -923,7 +923,7 @@ static void NormaliseSubtypes(Train *chain)
}
/* Now clear the bits for the rest of the chain */
- for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
+ for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
t->ClearFreeWagon();
t->ClearFrontEngine();
}
@@ -943,10 +943,10 @@ static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *origina
/* Just add 'new' engines and subtract the original ones.
* If that's less than or equal to 0 we can be sure we did
* not add any engines (read: trains) along the way. */
- if ((src != NULL && src->IsEngine() ? 1 : 0) +
- (dst != NULL && dst->IsEngine() ? 1 : 0) -
- (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
- (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
+ if ((src != nullptr && src->IsEngine() ? 1 : 0) +
+ (dst != nullptr && dst->IsEngine() ? 1 : 0) -
+ (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
+ (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
return CommandCost();
}
@@ -965,7 +965,7 @@ static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *origina
static CommandCost CheckTrainAttachment(Train *t)
{
/* No multi-part train, no need to check. */
- if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
+ if (t == nullptr || t->Next() == nullptr || !t->IsEngine()) return CommandCost();
/* The maximum length for a train. For each part we decrease this by one
* and if the result is negative the train is simply too long. */
@@ -976,19 +976,19 @@ static CommandCost CheckTrainAttachment(Train *t)
/* Break the prev -> t link so it always holds within the loop. */
t = t->Next();
- prev->SetNext(NULL);
+ prev->SetNext(nullptr);
/* Make sure the cache is cleared. */
head->InvalidateNewGRFCache();
- while (t != NULL) {
+ while (t != nullptr) {
allowed_len -= t->gcache.cached_veh_length;
Train *next = t->Next();
/* Unlink the to-be-added piece; it is already unlinked from the previous
* part due to the fact that the prev -> t link is broken. */
- t->SetNext(NULL);
+ t->SetNext(nullptr);
/* Don't check callback for articulated or rear dual headed parts */
if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
@@ -1084,8 +1084,8 @@ static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train
if (*src_head == *dst_head) {
/* If we aren't moving part(s) to a new train, we are just moving the
* front back and there is not destination head. */
- *dst_head = NULL;
- } else if (*dst_head == NULL) {
+ *dst_head = nullptr;
+ } else if (*dst_head == nullptr) {
/* If we are moving to a new train the head of the move train would become
* the head of the new vehicle. */
*dst_head = src;
@@ -1098,7 +1098,7 @@ static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train
* In case we are a multiheaded part we want the complete thing to come
* with us, so src->GetNextUnit(), however... when we are e.g. a wagon
* that is followed by a rear multihead we do not want to include that. */
- *src_head = move_chain ? NULL :
+ *src_head = move_chain ? nullptr :
(src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
}
@@ -1122,7 +1122,7 @@ static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train
static void NormaliseTrainHead(Train *head)
{
/* Not much to do! */
- if (head == NULL) return;
+ if (head == nullptr) return;
/* Tell the 'world' the train changed. */
head->ConsistChanged(CCF_ARRANGE);
@@ -1159,7 +1159,7 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
bool move_chain = HasBit(p1, 20);
Train *src = Train::GetIfValid(s);
- if (src == NULL) return CMD_ERROR;
+ if (src == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(src->owner);
if (ret.Failed()) return ret;
@@ -1170,10 +1170,10 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
/* if nothing is selected as destination, try and find a matching vehicle to drag to. */
Train *dst;
if (d == INVALID_VEHICLE) {
- dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
+ dst = src->IsEngine() ? nullptr : FindGoodVehiclePos(src);
} else {
dst = Train::GetIfValid(d);
- if (dst == NULL) return CMD_ERROR;
+ if (dst == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(dst->owner);
if (ret.Failed()) return ret;
@@ -1184,7 +1184,7 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
/* if an articulated part is being handled, deal with its parent vehicle */
src = src->GetFirstEnginePart();
- if (dst != NULL) {
+ if (dst != nullptr) {
dst = dst->GetFirstEnginePart();
}
@@ -1194,13 +1194,13 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
/* locate the head of the two chains */
Train *src_head = src->First();
Train *dst_head;
- if (dst != NULL) {
+ if (dst != nullptr) {
dst_head = dst->First();
if (dst_head->tile != src_head->tile) return CMD_ERROR;
/* Now deal with articulated part of destination wagon */
dst = dst->GetLastEnginePart();
} else {
- dst_head = NULL;
+ dst_head = nullptr;
}
if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
@@ -1209,13 +1209,13 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
if (move_chain && src_head == dst_head) return CommandCost();
/* When moving a multiheaded part to be place after itself, bail out. */
- if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
+ if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
/* Check if all vehicles in the source train are stopped inside a depot. */
if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
/* Check if all vehicles in the destination train are stopped inside a depot. */
- if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
+ if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
/* First make a backup of the order of the trains. That way we can do
* whatever we want with the order and later on easily revert. */
@@ -1229,13 +1229,13 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
* For the destination head we do not care if it is the same as the source
* head because in that case it's just a copy. */
Train *original_src_head = src_head;
- Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
+ Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
/* We want this information from before the rearrangement, but execute this after the validation.
- * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
- * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
+ * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
+ * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
bool original_src_head_front_engine = original_src_head->IsFrontEngine();
- bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
+ bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
/* (Re)arrange the trains in the wanted arrangement. */
ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
@@ -1308,8 +1308,8 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
}
/* Add new heads to statistics */
- if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
- if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
+ if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
+ if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
/* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
NormaliseTrainHead(src_head);
@@ -1320,8 +1320,8 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u
CheckCargoCapacity(dst_head);
}
- if (src_head != NULL) src_head->First()->MarkDirty();
- if (dst_head != NULL) dst_head->First()->MarkDirty();
+ if (src_head != nullptr) src_head->First()->MarkDirty();
+ if (dst_head != nullptr) dst_head->First()->MarkDirty();
/* We are undoubtedly changing something in the depot and train list. */
InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
@@ -1363,34 +1363,34 @@ CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint3
/* We need to keep track of the new head and the head of what we're going to sell. */
Train *new_head = first;
- Train *sell_head = NULL;
+ Train *sell_head = nullptr;
/* Split the train in the wanted way. */
- ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
+ ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
/* We don't need to validate the second train; it's going to be sold. */
- CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
+ CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
if (ret.Failed()) {
/* Restore the train we had. */
RestoreTrainBackup(original);
return ret;
}
- if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
+ if (first->orders.list == nullptr && !OrderList::CanAllocateItem()) {
/* Restore the train we had. */
RestoreTrainBackup(original);
return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
}
CommandCost cost(EXPENSES_NEW_VEHICLES);
- for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
+ for (Train *t = sell_head; t != nullptr; t = t->Next()) cost.AddCost(-t->value);
/* do it? */
if (flags & DC_EXEC) {
/* First normalise the sub types of the chain. */
NormaliseSubtypes(new_head);
- if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
+ if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
/* We are selling the front engine. In this case we want to
* 'give' the order, unit number and such to the new head. */
new_head->orders.list = first->orders.list;
@@ -1618,11 +1618,11 @@ void ReverseTrainSwapVeh(Train *v, int l, int r)
/**
* Check if the vehicle is a train
* @param v vehicle on tile
- * @return v if it is a train, NULL otherwise
+ * @return v if it is a train, nullptr otherwise
*/
static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
{
- return (v->type == VEH_TRAIN) ? v : NULL;
+ return (v->type == VEH_TRAIN) ? v : nullptr;
}
@@ -1630,18 +1630,18 @@ static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
* Checks if a train is approaching a rail-road crossing
* @param v vehicle on tile
* @param data tile with crossing we are testing
- * @return v if it is approaching a crossing, NULL otherwise
+ * @return v if it is approaching a crossing, nullptr otherwise
*/
static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
{
- if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
+ if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
Train *t = Train::From(v);
- if (!t->IsFrontEngine()) return NULL;
+ if (!t->IsFrontEngine()) return nullptr;
TileIndex tile = *(TileIndex *)data;
- if (TrainApproachingCrossingTile(t) != tile) return NULL;
+ if (TrainApproachingCrossingTile(t) != tile) return nullptr;
return t;
}
@@ -1680,7 +1680,7 @@ void UpdateLevelCrossing(TileIndex tile, bool sound)
assert(IsLevelCrossingTile(tile));
/* reserved || train on crossing || train approaching crossing */
- bool new_state = HasCrossingReservation(tile) || HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
+ bool new_state = HasCrossingReservation(tile) || HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
if (new_state != IsCrossingBarred(tile)) {
if (new_state && sound) {
@@ -1744,23 +1744,23 @@ static void AdvanceWagonsAfterSwap(Train *v)
{
/* first of all, fix the situation when the train was entering a depot */
Train *dep = v; // last vehicle in front of just left depot
- while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
+ while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
}
Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
- if (leave != NULL) {
+ if (leave != nullptr) {
/* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
int d = TicksToLeaveDepot(dep);
if (d <= 0) {
leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
- for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
+ for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
}
} else {
- dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
+ dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
}
Train *base = v;
@@ -1770,7 +1770,7 @@ static void AdvanceWagonsAfterSwap(Train *v)
/* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
* they have already correct spacing, so we have to make sure they are moved how they should */
- bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
+ bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
while (length > 2) {
/* we reached vehicle (originally) in front of a depot, stop now
@@ -1786,7 +1786,7 @@ static void AdvanceWagonsAfterSwap(Train *v)
int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
/* do not update images now */
- for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
+ for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
base = first; // == base->Next()
length -= 2;
@@ -1834,7 +1834,7 @@ void ReverseTrainDirection(Train *v)
v->ConsistChanged(CCF_TRACK);
/* update all images */
- for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
+ for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
/* update crossing we were approaching */
if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
@@ -1893,7 +1893,7 @@ void ReverseTrainDirection(Train *v)
CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Train *v = Train::GetIfValid(p1);
- if (v == NULL) return CMD_ERROR;
+ if (v == nullptr) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -1929,7 +1929,7 @@ CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32
/* Properly leave the station if we are loading and won't be loading anymore */
if (v->current_order.IsType(OT_LOADING)) {
const Vehicle *last = v;
- while (last->Next() != NULL) last = last->Next();
+ while (last->Next() != nullptr) last = last->Next();
/* not a station || different station --> leave the station */
if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
@@ -1966,7 +1966,7 @@ CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32
CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Train *t = Train::GetIfValid(p1);
- if (t == NULL) return CMD_ERROR;
+ if (t == nullptr) return CMD_ERROR;
if (!t->IsPrimaryVehicle()) return CMD_ERROR;
@@ -2013,9 +2013,9 @@ static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
/**
* Locate the closest depot for this consist, and return the information to the caller.
- * @param[out] location If not \c NULL and a depot is found, store its location in the given address.
- * @param[out] destination If not \c NULL and a depot is found, store its index in the given address.
- * @param[out] reverse If not \c NULL and a depot is found, store reversal information in the given address.
+ * @param[out] location If not \c nullptr and a depot is found, store its location in the given address.
+ * @param[out] destination If not \c nullptr and a depot is found, store its index in the given address.
+ * @param[out] reverse If not \c nullptr and a depot is found, store reversal information in the given address.
* @return A depot has been found.
*/
bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
@@ -2023,9 +2023,9 @@ bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bo
FindDepotData tfdd = FindClosestTrainDepot(this, 0);
if (tfdd.best_length == UINT_MAX) return false;
- if (location != NULL) *location = tfdd.tile;
- if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
- if (reverse != NULL) *reverse = tfdd.reverse;
+ if (location != nullptr) *location = tfdd.tile;
+ if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
+ if (reverse != nullptr) *reverse = tfdd.reverse;
return true;
}
@@ -2102,7 +2102,7 @@ static void CheckNextTrainTile(Train *v)
if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
}
- ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
+ ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
}
}
}
@@ -2116,7 +2116,7 @@ static void CheckNextTrainTile(Train *v)
static bool CheckTrainStayInDepot(Train *v)
{
/* bail out if not all wagons are in the same depot or not in a depot at all */
- for (const Train *u = v; u != NULL; u = u->Next()) {
+ for (const Train *u = v; u != nullptr; u = u->Next()) {
if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
}
@@ -2245,7 +2245,7 @@ void FreeTrainTrackReservation(const Train *v)
if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
if (v->track == TRACK_BIT_DEPOT) {
/* Front engine is in a depot. We enter if some part is not in the depot. */
- for (const Train *u = v; u != NULL; u = u->Next()) {
+ for (const Train *u = v; u != nullptr; u = u->Next()) {
if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
}
}
@@ -2359,8 +2359,8 @@ static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks,
if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
/* Choice found, path valid but not okay. Save info about the choice tile as well. */
- if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
- if (enterdir != NULL) *enterdir = ft.m_exitdir;
+ if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
+ if (enterdir != nullptr) *enterdir = ft.m_exitdir;
return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
}
@@ -2473,7 +2473,7 @@ public:
if (this->index >= this->v->GetNumOrders()) this->index = 0;
Order *order = this->v->GetOrder(this->index);
- assert(order != NULL);
+ assert(order != nullptr);
switch (order->GetType()) {
case OT_GOTO_DEPOT:
@@ -2516,7 +2516,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir,
assert((tracks & ~TRACK_BIT_MASK) == 0);
- if (got_reservation != NULL) *got_reservation = false;
+ if (got_reservation != nullptr) *got_reservation = false;
/* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
@@ -2549,7 +2549,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir,
}
if (res_dest.okay) {
/* Got a valid reservation that ends at a safe target, quick exit. */
- if (got_reservation != NULL) *got_reservation = true;
+ if (got_reservation != nullptr) *got_reservation = true;
if (changed_signal) MarkTileDirtyByTile(tile);
TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
return best_track;
@@ -2608,7 +2608,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir,
TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
best_track = FindFirstTrack(res);
TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
- if (got_reservation != NULL) *got_reservation = true;
+ if (got_reservation != nullptr) *got_reservation = true;
if (changed_signal) MarkTileDirtyByTile(tile);
} else {
FreeTrainTrackReservation(v);
@@ -2617,7 +2617,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir,
return best_track;
}
- if (got_reservation != NULL) *got_reservation = true;
+ if (got_reservation != nullptr) *got_reservation = true;
/* Reservation target found and free, check if it is safe. */
while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
@@ -2640,7 +2640,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir,
/* Path found, but could not be reserved. */
FreeTrainTrackReservation(v);
if (mark_stuck) MarkTrainAsStuck(v);
- if (got_reservation != NULL) *got_reservation = false;
+ if (got_reservation != nullptr) *got_reservation = false;
changed_signal = false;
break;
}
@@ -2649,7 +2649,7 @@ static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir,
if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
FreeTrainTrackReservation(v);
if (mark_stuck) MarkTrainAsStuck(v);
- if (got_reservation != NULL) *got_reservation = false;
+ if (got_reservation != nullptr) *got_reservation = false;
changed_signal = false;
}
break;
@@ -2688,14 +2688,14 @@ bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
}
}
- Vehicle *other_train = NULL;
+ Vehicle *other_train = nullptr;
PBSTileInfo origin = FollowTrainReservation(v, &other_train);
/* The path we are driving on is already blocked by some other train.
* This can only happen in certain situations when mixing path and
* block signals or when changing tracks and/or signals.
* Exit here as doing any further reservations will probably just
* make matters worse. */
- if (other_train != NULL && other_train->index != v->index) {
+ if (other_train != nullptr && other_train->index != v->index) {
if (mark_as_stuck) MarkTrainAsStuck(v);
return false;
}
@@ -2781,7 +2781,7 @@ void Train::MarkDirty()
do {
v->colourmap = PAL_NONE;
v->UpdateViewport(true, false);
- } while ((v = v->Next()) != NULL);
+ } while ((v = v->Next()) != nullptr);
/* need to update acceleration and cached values since the goods on the train changed. */
this->CargoChanged();
@@ -2899,7 +2899,7 @@ static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
/** Tries to reserve track under whole train consist. */
void Train::ReserveTrackUnderConsist() const
{
- for (const Train *u = this; u != NULL; u = u->Next()) {
+ for (const Train *u = this; u != nullptr; u = u->Next()) {
switch (u->track) {
case TRACK_BIT_WORMHOLE:
TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
@@ -2928,7 +2928,7 @@ uint Train::Crash(bool flooded)
/* Remove the reserved path in front of the train if it is not stuck.
* Also clear all reserved tracks the train is currently on. */
if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
- for (const Train *v = this; v != NULL; v = v->Next()) {
+ for (const Train *v = this; v != nullptr; v = v->Next()) {
ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
/* ClearPathReservation will not free the wormhole exit
@@ -2986,23 +2986,23 @@ struct TrainCollideChecker {
* Collision test function.
* @param v %Train vehicle to test collision with.
* @param data %Train being examined.
- * @return \c NULL (always continue search)
+ * @return \c nullptr (always continue search)
*/
static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
{
TrainCollideChecker *tcc = (TrainCollideChecker*)data;
/* not a train or in depot */
- if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
+ if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
/* do not crash into trains of another company. */
- if (v->owner != tcc->v->owner) return NULL;
+ if (v->owner != tcc->v->owner) return nullptr;
/* get first vehicle now to make most usual checks faster */
Train *coll = Train::From(v)->First();
/* can't collide with own wagons */
- if (coll == tcc->v) return NULL;
+ if (coll == tcc->v) return nullptr;
int x_diff = v->x_pos - tcc->v->x_pos;
int y_diff = v->y_pos - tcc->v->y_pos;
@@ -3012,20 +3012,20 @@ static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
* Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
* Differences are then ORed and then we check for any higher bits */
uint hash = (y_diff + 7) | (x_diff + 7);
- if (hash & ~15) return NULL;
+ if (hash & ~15) return nullptr;
/* Slower check using multiplication */
int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
- if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
+ if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
/* Happens when there is a train under bridge next to bridge head */
- if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
+ if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
/* crash both trains */
tcc->num += TrainCrashed(tcc->v);
tcc->num += TrainCrashed(coll);
- return NULL; // continue searching
+ return nullptr; // continue searching
}
/**
@@ -3067,15 +3067,15 @@ static bool CheckTrainCollision(Train *v)
static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
{
- if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
+ if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
Train *t = Train::From(v);
DiagDirection exitdir = *(DiagDirection *)data;
/* not front engine of a train, inside wormhole or depot, crashed */
- if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
+ if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
- if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return NULL;
+ if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
return t;
}
@@ -3138,7 +3138,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
- if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == NULL) {
+ if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
/* We allow wagons to make 90 deg turns, because forbid_90_deg
* can be switched on halfway a turn */
bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
@@ -3151,10 +3151,10 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
TrackBits chosen_track;
- if (prev == NULL) {
+ if (prev == nullptr) {
/* Currently the locomotive is active. Determine which one of the
* available tracks to choose */
- chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
+ chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
@@ -3274,7 +3274,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
}
/* Clear any track reservation when the last vehicle leaves the tile */
- if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
+ if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
v->tile = gp.new_tile;
@@ -3291,7 +3291,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
update_signals_crossing = true;
if (chosen_dir != v->direction) {
- if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
+ if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
DirDiff diff = DirDifference(v->direction, chosen_dir);
v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
@@ -3347,7 +3347,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
/* update the Z position of the vehicle */
int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
- if (prev == NULL) {
+ if (prev == nullptr) {
/* This is the first vehicle in the train */
AffectSpeedByZChange(v, old_z);
}
@@ -3373,7 +3373,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
/* Signals can only change when the first
* (above) or the last vehicle moves. */
- if (v->Next() == NULL) {
+ if (v->Next() == nullptr) {
TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
}
@@ -3389,7 +3389,7 @@ bool TrainController(Train *v, Vehicle *nomove, bool reverse)
invalid_rail:
/* We've reached end of line?? */
- if (prev != NULL) error("Disconnecting train");
+ if (prev != nullptr) error("Disconnecting train");
reverse_train_direction:
if (reverse) {
@@ -3406,7 +3406,7 @@ reverse_train_direction:
* Collect trackbits of all crashed train vehicles on a tile
* @param v Vehicle passed from Find/HasVehicleOnPos()
* @param data trackdirbits for the result
- * @return NULL to iterate over all vehicles on the tile.
+ * @return nullptr to iterate over all vehicles on the tile.
*/
static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
{
@@ -3422,7 +3422,7 @@ static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -3440,8 +3440,8 @@ static void DeleteLastWagon(Train *v)
* *u is then the one-before-last wagon, and *v the last
* one which will physically be removed */
Train *u = v;
- for (; v->Next() != NULL; v = v->Next()) u = v;
- u->SetNext(NULL);
+ for (; v->Next() != nullptr; v = v->Next()) u = v;
+ u->SetNext(nullptr);
if (first != v) {
/* Recalculate cached train properties */
@@ -3460,7 +3460,7 @@ static void DeleteLastWagon(Train *v)
Owner owner = v->owner;
delete v;
- v = NULL; // make sure nobody will try to read 'v' anymore
+ v = nullptr; // make sure nobody will try to read 'v' anymore
if (trackbits == TRACK_BIT_WORMHOLE) {
/* Vehicle is inside a wormhole, v->track contains no useful value then. */
@@ -3516,7 +3516,7 @@ static void ChangeTrainDirRandomly(Train *v)
v->UpdateViewport(false, true);
}
}
- } while ((v = v->Next()) != NULL);
+ } while ((v = v->Next()) != nullptr);
}
/**
@@ -3548,13 +3548,13 @@ static bool HandleCrashedTrain(Train *v)
EV_EXPLOSION_SMALL);
break;
}
- } while ((u = u->Next()) != NULL);
+ } while ((u = u->Next()) != nullptr);
}
if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
if (state >= 4440 && !(v->tick_counter & 0x1F)) {
- bool ret = v->Next() != NULL;
+ bool ret = v->Next() != nullptr;
DeleteLastWagon(v);
return ret;
}
@@ -3837,7 +3837,7 @@ static bool TrainLocoHandler(Train *v, bool mode)
/* Loop until the train has finished moving. */
for (;;) {
j -= adv_spd;
- TrainController(v, NULL);
+ TrainController(v, nullptr);
/* Don't continue to move if the train crashed. */
if (CheckTrainCollision(v)) break;
/* Determine distance to next map position */
@@ -3858,7 +3858,7 @@ static bool TrainLocoHandler(Train *v, bool mode)
v->SetLastSpeed();
}
- for (Train *u = v; u != NULL; u = u->Next()) {
+ for (Train *u = v; u != nullptr; u = u->Next()) {
if ((u->vehstatus & VS_HIDDEN) != 0) continue;
u->UpdateViewport(false, false);
@@ -3889,7 +3889,7 @@ Money Train::GetRunningCost() const
if (v->IsMultiheaded()) cost_factor /= 2;
cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
- } while ((v = v->GetNextVehicle()) != NULL);
+ } while ((v = v->GetNextVehicle()) != nullptr);
return cost;
}
diff --git a/src/train_gui.cpp b/src/train_gui.cpp
index 31b7a2ec0..c927d42ce 100644
--- a/src/train_gui.cpp
+++ b/src/train_gui.cpp
@@ -33,17 +33,17 @@ void CcBuildWagon(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p
if (result.Failed()) return;
/* find a locomotive in the depot. */
- const Vehicle *found = NULL;
+ const Vehicle *found = nullptr;
const Train *t;
FOR_ALL_TRAINS(t) {
if (t->IsFrontEngine() && t->tile == tile && t->IsStoppedInDepot()) {
- if (found != NULL) return; // must be exactly one.
+ if (found != nullptr) return; // must be exactly one.
found = t;
}
}
/* if we found a loco, */
- if (found != NULL) {
+ if (found != nullptr) {
found = found->Last();
/* put the new wagon at the end of the loco. */
DoCommandP(0, _new_vehicle_id, found->index, CMD_MOVE_RAIL_VEHICLE);
@@ -65,8 +65,8 @@ static int HighlightDragPosition(int px, int max_width, VehicleID selection, boo
assert(selection != INVALID_VEHICLE);
int dragged_width = 0;
- for (Train *t = Train::Get(selection); t != NULL; t = chain ? t->Next() : (t->HasArticulatedPart() ? t->GetNextArticulatedPart() : NULL)) {
- dragged_width += t->GetDisplayImageWidth(NULL);
+ for (Train *t = Train::Get(selection); t != nullptr; t = chain ? t->Next() : (t->HasArticulatedPart() ? t->GetNextArticulatedPart() : nullptr)) {
+ dragged_width += t->GetDisplayImageWidth(nullptr);
}
int drag_hlight_left = rtl ? max(px - dragged_width + 1, 0) : px;
@@ -112,7 +112,7 @@ void DrawTrainImage(const Train *v, int left, int right, int y, VehicleID select
bool sel_articulated = false;
bool dragging = (drag_dest != INVALID_VEHICLE);
bool drag_at_end_of_train = (drag_dest == v->index); // Head index is used to mark dragging at end of train.
- for (; v != NULL && (rtl ? px > 0 : px < max_width); v = v->Next()) {
+ for (; v != nullptr && (rtl ? px > 0 : px < max_width); v = v->Next()) {
if (dragging && !drag_at_end_of_train && drag_dest == v->index) {
/* Highlight the drag-and-drop destination inside the train. */
int drag_hlight_width = HighlightDragPosition(px, max_width, selection, _cursor.vehchain);
@@ -292,7 +292,7 @@ static void GetCargoSummaryOfArticulatedVehicle(const Train *v, CargoSummary *su
item->capacity += v->cargo_cap;
item->amount += v->cargo.StoredCount();
if (item->source == INVALID_STATION) item->source = v->cargo.Source();
- } while ((v = v->Next()) != NULL && v->IsArticulatedPart());
+ } while ((v = v->Next()) != nullptr && v->IsArticulatedPart());
}
/**
@@ -306,7 +306,7 @@ static uint GetLengthOfArticulatedVehicle(const Train *v)
do {
length += v->GetDisplayImageWidth();
- } while ((v = v->Next()) != NULL && v->IsArticulatedPart());
+ } while ((v = v->Next()) != nullptr && v->IsArticulatedPart());
return length;
}
@@ -324,7 +324,7 @@ int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab)
if (det_tab == TDW_TAB_TOTALS) { // Total cargo tab
CargoArray act_cargo;
CargoArray max_cargo;
- for (const Vehicle *v = Vehicle::Get(veh_id); v != NULL; v = v->Next()) {
+ for (const Vehicle *v = Vehicle::Get(veh_id); v != nullptr; v = v->Next()) {
act_cargo[v->cargo_type] += v->cargo.StoredCount();
max_cargo[v->cargo_type] += v->cargo_cap;
}
@@ -337,7 +337,7 @@ int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab)
}
num++; // needs one more because first line is description string
} else {
- for (const Train *v = Train::Get(veh_id); v != NULL; v = v->GetNextVehicle()) {
+ for (const Train *v = Train::Get(veh_id); v != nullptr; v = v->GetNextVehicle()) {
GetCargoSummaryOfArticulatedVehicle(v, &_cargo_summary);
num += max(1u, (unsigned)_cargo_summary.size());
@@ -375,7 +375,7 @@ void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_po
bool rtl = _current_text_dir == TD_RTL;
Direction dir = rtl ? DIR_E : DIR_W;
int x = rtl ? right : left;
- for (; v != NULL && vscroll_pos > -vscroll_cap; v = v->GetNextVehicle()) {
+ for (; v != nullptr && vscroll_pos > -vscroll_cap; v = v->GetNextVehicle()) {
GetCargoSummaryOfArticulatedVehicle(v, &_cargo_summary);
/* Draw sprites */
@@ -388,7 +388,7 @@ void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_po
if (vscroll_pos <= 0 && vscroll_pos > -vscroll_cap) {
int pitch = 0;
const Engine *e = Engine::Get(v->engine_type);
- if (e->GetGRF() != NULL) {
+ if (e->GetGRF() != nullptr) {
pitch = ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
}
PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
@@ -399,7 +399,7 @@ void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_po
px += rtl ? -width : width;
dx += width;
u = u->Next();
- } while (u != NULL && u->IsArticulatedPart());
+ } while (u != nullptr && u->IsArticulatedPart());
bool separate_sprite_row = (dx > (uint)ScaleGUITrad(TRAIN_DETAILS_MAX_INDENT));
if (separate_sprite_row) {
@@ -450,7 +450,7 @@ void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_po
CargoArray max_cargo;
Money feeder_share = 0;
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
act_cargo[u->cargo_type] += u->cargo.StoredCount();
max_cargo[u->cargo_type] += u->cargo_cap;
feeder_share += u->cargo.FeederShare();
diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp
index 7240cf86d..e982abfb2 100644
--- a/src/tree_cmd.cpp
+++ b/src/tree_cmd.cpp
@@ -342,8 +342,8 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Check the tree type within the current climate */
if (tree_to_plant != TREE_INVALID && !IsInsideBS(tree_to_plant, _tree_base_by_landscape[_settings_game.game_creation.landscape], _tree_count_by_landscape[_settings_game.game_creation.landscape])) return CMD_ERROR;
- Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : NULL;
- int limit = (c == NULL ? INT32_MAX : GB(c->tree_limit, 16, 16));
+ Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : nullptr;
+ int limit = (c == nullptr ? INT32_MAX : GB(c->tree_limit, 16, 16));
TileArea ta(tile, p2);
TILE_AREA_LOOP(tile, ta) {
@@ -364,7 +364,7 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (flags & DC_EXEC) {
AddTreeCount(tile, 1);
MarkTileDirtyByTile(tile);
- if (c != NULL) c->tree_limit -= 1 << 16;
+ if (c != nullptr) c->tree_limit -= 1 << 16;
}
/* 2x as expensive to add more trees to an existing tile */
cost.AddCost(_price[PR_BUILD_TREES] * 2);
@@ -419,7 +419,7 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) {
Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
- if (t != NULL) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
+ if (t != nullptr) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
}
if (flags & DC_EXEC) {
@@ -431,7 +431,7 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Plant full grown trees in scenario editor */
PlantTreesOnTile(tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0);
MarkTileDirtyByTile(tile);
- if (c != NULL) c->tree_limit -= 1 << 16;
+ if (c != nullptr) c->tree_limit -= 1 << 16;
/* When planting rainforest-trees, set tropiczone to rainforest in editor. */
if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
@@ -552,7 +552,7 @@ static CommandCost ClearTile_Trees(TileIndex tile, DoCommandFlag flags)
if (Company::IsValidID(_current_company)) {
Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
- if (t != NULL) ChangeTownRating(t, RATING_TREE_DOWN_STEP, RATING_TREE_MINIMUM, flags);
+ if (t != nullptr) ChangeTownRating(t, RATING_TREE_DOWN_STEP, RATING_TREE_MINIMUM, flags);
}
num = GetTreeCount(tile);
@@ -803,15 +803,15 @@ extern const TileTypeProcs _tile_type_trees_procs = {
DrawTile_Trees, // draw_tile_proc
GetSlopePixelZ_Trees, // get_slope_z_proc
ClearTile_Trees, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_Trees, // get_tile_desc_proc
GetTileTrackStatus_Trees, // get_tile_track_status_proc
- NULL, // click_tile_proc
- NULL, // animate_tile_proc
+ nullptr, // click_tile_proc
+ nullptr, // animate_tile_proc
TileLoop_Trees, // tile_loop_proc
ChangeTileOwner_Trees, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
- NULL, // vehicle_enter_tile_proc
+ nullptr, // add_produced_cargo_proc
+ nullptr, // vehicle_enter_tile_proc
GetFoundation_Trees, // get_foundation_proc
TerraformTile_Trees, // terraform_tile_proc
};
diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp
index 79011a3bd..78586b1a2 100644
--- a/src/tunnelbridge_cmd.cpp
+++ b/src/tunnelbridge_cmd.cpp
@@ -84,7 +84,7 @@ void ResetBridges()
{
/* First, free sprite table data */
for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
- if (_bridge[i].sprite_table != NULL) {
+ if (_bridge[i].sprite_table != nullptr) {
for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
free(_bridge[i].sprite_table);
}
@@ -150,7 +150,7 @@ static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces ta
{
const BridgeSpec *bridge = GetBridgeSpec(index);
assert(table < BRIDGE_PIECE_INVALID);
- if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
+ if (bridge->sprite_table == nullptr || bridge->sprite_table[table] == nullptr) {
return _bridge_sprite_table[index][table];
} else {
return bridge->sprite_table[table];
@@ -268,7 +268,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
company = OWNER_TOWN;
/* If we are not within a town, we are not owned by the town */
- if (town == NULL || DistanceSquare(tile_start, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
+ if (town == nullptr || DistanceSquare(tile_start, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
company = OWNER_NONE;
}
}
@@ -329,7 +329,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
_game_mode != GM_EDITOR) {
Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
- if (t == NULL) {
+ if (t == nullptr) {
return CMD_ERROR;
} else {
SetDParam(0, t->index);
@@ -479,7 +479,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
switch (transport_type) {
case TRANSPORT_RAIL:
/* Add to company infrastructure count if required. */
- if (is_new_owner && c != NULL) c->infrastructure.rail[railtype] += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
+ if (is_new_owner && c != nullptr) c->infrastructure.rail[railtype] += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
MakeRailBridgeRamp(tile_start, owner, bridge_type, dir, railtype);
MakeRailBridgeRamp(tile_end, owner, bridge_type, ReverseDiagDir(dir), railtype);
SetTunnelBridgeReservation(tile_start, pbs_reservation);
@@ -493,7 +493,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
if (HasBit(prev_roadtypes, ROADTYPE_ROAD) && GetRoadOwner(tile_start, ROADTYPE_ROAD) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_ROAD);
if (HasBit(prev_roadtypes, ROADTYPE_TRAM) && GetRoadOwner(tile_start, ROADTYPE_TRAM) == OWNER_NONE) ClrBit(prev_roadtypes, ROADTYPE_TRAM);
}
- if (c != NULL) {
+ if (c != nullptr) {
/* Add all new road types to the company infrastructure counter. */
RoadType new_rt;
FOR_EACH_SET_ROADTYPE(new_rt, roadtypes ^ prev_roadtypes) {
@@ -509,7 +509,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
}
case TRANSPORT_WATER:
- if (is_new_owner && c != NULL) c->infrastructure.water += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
+ if (is_new_owner && c != nullptr) c->infrastructure.water += (bridge_len + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
MakeAqueductBridgeRamp(tile_start, owner, dir);
MakeAqueductBridgeRamp(tile_end, owner, ReverseDiagDir(dir));
break;
@@ -534,7 +534,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
* and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
*/
Company *c = Company::GetIfValid(company);
- if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
+ if (!(flags & DC_QUERY_COST) || (c != nullptr && c->is_ai)) {
bridge_len += 2; // begin and end tiles/ramps
switch (transport_type) {
@@ -543,7 +543,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u
default: break;
}
- if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
+ if (c != nullptr) bridge_len = CalcBridgeLenCostFactor(bridge_len);
if (transport_type != TRANSPORT_WATER) {
cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
@@ -598,7 +598,7 @@ CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1,
company = OWNER_TOWN;
/* If we are not within a town, we are not owned by the town */
- if (town == NULL || DistanceSquare(start_tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
+ if (town == nullptr || DistanceSquare(start_tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
company = OWNER_NONE;
}
}
@@ -680,7 +680,7 @@ CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1,
/* Mark the tile as already cleared for the terraform command.
* Do this for all tiles (like trees), not only objects. */
ClearedObjectArea *coa = FindClearedObject(end_tile);
- if (coa == NULL) {
+ if (coa == nullptr) {
/*C++17: coa = &*/ _cleared_object_areas.push_back({end_tile, TileArea(end_tile, 1, 1)});
coa = &_cleared_object_areas.back();
}
@@ -702,7 +702,7 @@ CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1,
assert(coa >= begin && coa < begin + _cleared_object_areas.size());
size_t coa_index = coa - begin;
assert(coa_index < UINT_MAX); // more than 2**32 cleared areas would be a bug in itself
- coa = NULL;
+ coa = nullptr;
ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
_cleared_object_areas[(uint)coa_index].first_tile = old_first_tile;
@@ -722,13 +722,13 @@ CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1,
Company *c = Company::GetIfValid(company);
uint num_pieces = (tiles + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
if (transport_type == TRANSPORT_RAIL) {
- if (!IsTunnelTile(start_tile) && c != NULL) c->infrastructure.rail[railtype] += num_pieces;
+ if (!IsTunnelTile(start_tile) && c != nullptr) c->infrastructure.rail[railtype] += num_pieces;
MakeRailTunnel(start_tile, company, direction, railtype);
MakeRailTunnel(end_tile, company, ReverseDiagDir(direction), railtype);
AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, company);
YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
} else {
- if (c != NULL) {
+ if (c != nullptr) {
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, rts ^ (IsTunnelTile(start_tile) ? GetRoadTypes(start_tile) : ROADTYPES_NONE)) {
c->infrastructure.road[rt] += num_pieces * 2; // A full diagonal road has two road bits.
@@ -808,7 +808,7 @@ static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
_build_tunnel_endtile = endtile;
- Town *t = NULL;
+ Town *t = nullptr;
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
@@ -833,10 +833,10 @@ static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
Track track = DiagDirToDiagTrack(dir);
Owner owner = GetTileOwner(tile);
- Train *v = NULL;
+ Train *v = nullptr;
if (HasTunnelBridgeReservation(tile)) {
v = GetTrainForReservation(tile, track);
- if (v != NULL) FreeTrainTrackReservation(v);
+ if (v != nullptr) FreeTrainTrackReservation(v);
}
if (Company::IsValidID(owner)) {
@@ -854,13 +854,13 @@ static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
YapfNotifyTrackLayoutChange(tile, track);
YapfNotifyTrackLayoutChange(endtile, track);
- if (v != NULL) TryPathReserve(v);
+ if (v != nullptr) TryPathReserve(v);
} else {
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
/* A full diagonal road tile has two road bits. */
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -893,7 +893,7 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
DiagDirection direction = GetTunnelBridgeDirection(tile);
TileIndexDiff delta = TileOffsByDiagDir(direction);
- Town *t = NULL;
+ Town *t = nullptr;
if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
@@ -917,11 +917,11 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
Owner owner = GetTileOwner(tile);
int height = GetBridgeHeight(tile);
- Train *v = NULL;
+ Train *v = nullptr;
if (rail && HasTunnelBridgeReservation(tile)) {
v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
- if (v != NULL) FreeTrainTrackReservation(v);
+ if (v != nullptr) FreeTrainTrackReservation(v);
}
/* Update company infrastructure counts. */
@@ -931,7 +931,7 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
RoadType rt;
FOR_EACH_SET_ROADTYPE(rt, GetRoadTypes(tile)) {
Company *c = Company::GetIfValid(GetRoadOwner(tile, rt));
- if (c != NULL) {
+ if (c != nullptr) {
/* A full diagonal road tile has two road bits. */
c->infrastructure.road[rt] -= len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR;
DirtyCompanyInfrastructureWindows(c->index);
@@ -963,7 +963,7 @@ static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
YapfNotifyTrackLayoutChange(tile, track);
YapfNotifyTrackLayoutChange(endtile, track);
- if (v != NULL) TryPathReserve(v, true);
+ if (v != nullptr) TryPathReserve(v, true);
}
}
@@ -1018,7 +1018,7 @@ static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, in
{
int cur_z;
for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
- DrawPillar(psid, x, y, cur_z, w, h, NULL);
+ DrawPillar(psid, x, y, cur_z, w, h, nullptr);
}
return cur_z;
}
@@ -1906,14 +1906,14 @@ extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
DrawTile_TunnelBridge, // draw_tile_proc
GetSlopePixelZ_TunnelBridge, // get_slope_z_proc
ClearTile_TunnelBridge, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_TunnelBridge, // get_tile_desc_proc
GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
- NULL, // click_tile_proc
- NULL, // animate_tile_proc
+ nullptr, // click_tile_proc
+ nullptr, // animate_tile_proc
TileLoop_TunnelBridge, // tile_loop_proc
ChangeTileOwner_TunnelBridge, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
+ nullptr, // add_produced_cargo_proc
VehicleEnter_TunnelBridge, // vehicle_enter_tile_proc
GetFoundation_TunnelBridge, // get_foundation_proc
TerraformTile_TunnelBridge, // terraform_tile_proc
diff --git a/src/vehicle.cpp b/src/vehicle.cpp
index 856fc6737..e6df365b0 100644
--- a/src/vehicle.cpp
+++ b/src/vehicle.cpp
@@ -163,7 +163,7 @@ bool Vehicle::NeedsAutorenewing(const Company *c, bool use_renew_setting) const
*/
void VehicleServiceInDepot(Vehicle *v)
{
- assert(v != NULL);
+ assert(v != nullptr);
SetWindowDirty(WC_VEHICLE_DETAILS, v->index); // ensure that last service date and reliability are updated
do {
@@ -173,7 +173,7 @@ void VehicleServiceInDepot(Vehicle *v)
/* Prevent vehicles from breaking down directly after exiting the depot. */
v->breakdown_chance /= 4;
v = v->Next();
- } while (v != NULL && v->HasEngineType());
+ } while (v != nullptr && v->HasEngineType());
}
/**
@@ -210,7 +210,7 @@ bool Vehicle::NeedsServicing() const
Money needed_money = c->settings.engine_renew_money;
if (needed_money > c->money) return false;
- for (const Vehicle *v = this; v != NULL; v = (v->type == VEH_TRAIN) ? Train::From(v)->GetNextUnit() : NULL) {
+ for (const Vehicle *v = this; v != nullptr; v = (v->type == VEH_TRAIN) ? Train::From(v)->GetNextUnit() : nullptr) {
bool replace_when_old = false;
EngineID new_engine = EngineReplacementForCompany(c, v->engine_type, v->group_id, &replace_when_old);
@@ -261,13 +261,13 @@ bool Vehicle::NeedsAutomaticServicing() const
uint Vehicle::Crash(bool flooded)
{
assert((this->vehstatus & VS_CRASHED) == 0);
- assert(this->Previous() == NULL); // IsPrimaryVehicle fails for free-wagon-chains
+ assert(this->Previous() == nullptr); // IsPrimaryVehicle fails for free-wagon-chains
uint pass = 0;
/* Stop the vehicle. */
if (this->IsPrimaryVehicle()) this->vehstatus |= VS_STOPPED;
/* crash all wagons, and count passengers */
- for (Vehicle *v = this; v != NULL; v = v->Next()) {
+ for (Vehicle *v = this; v != nullptr; v = v->Next()) {
/* We do not transfer reserver cargo back, so TotalCount() instead of StoredCount() */
if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) pass += v->cargo.TotalCount();
v->vehstatus |= VS_CRASHED;
@@ -281,7 +281,7 @@ uint Vehicle::Crash(bool flooded)
SetWindowDirty(WC_VEHICLE_DEPOT, this->tile);
delete this->cargo_payment;
- assert(this->cargo_payment == NULL); // cleared by ~CargoPayment
+ assert(this->cargo_payment == nullptr); // cleared by ~CargoPayment
return RandomRange(pass + 1); // Randomise deceased passengers.
}
@@ -301,7 +301,7 @@ void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRF
GRFConfig *grfconfig = GetGRFConfig(e->GetGRFID());
/* Missing GRF. Nothing useful can be done in this situation. */
- if (grfconfig == NULL) return;
+ if (grfconfig == nullptr) return;
if (!HasBit(grfconfig->grf_bugs, bug_type)) {
SetBit(grfconfig->grf_bugs, bug_type);
@@ -384,16 +384,16 @@ static Vehicle *VehicleFromTileHash(int xl, int yl, int xu, int yu, void *data,
for (int y = yl; ; y = (y + (1 << HASH_BITS)) & (HASH_MASK << HASH_BITS)) {
for (int x = xl; ; x = (x + 1) & HASH_MASK) {
Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
- for (; v != NULL; v = v->hash_tile_next) {
+ for (; v != nullptr; v = v->hash_tile_next) {
Vehicle *a = proc(v, data);
- if (find_first && a != NULL) return a;
+ if (find_first && a != nullptr) return a;
}
if (x == xu) break;
}
if (y == yu) break;
}
- return NULL;
+ return nullptr;
}
@@ -442,18 +442,18 @@ void FindVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
/**
* Checks whether a vehicle in on a specific location. It will call proc for
- * vehicles until it returns non-NULL.
+ * vehicles until it returns non-nullptr.
* @note Use FindVehicleOnPosXY when you have the intention that all vehicles
* should be iterated over.
* @param x The X location on the map
* @param y The Y location on the map
* @param data Arbitrary data passed to proc
* @param proc The proc that determines whether a vehicle will be "found".
- * @return True if proc returned non-NULL.
+ * @return True if proc returned non-nullptr.
*/
bool HasVehicleOnPosXY(int x, int y, void *data, VehicleFromPosProc *proc)
{
- return VehicleFromPosXY(x, y, data, proc, true) != NULL;
+ return VehicleFromPosXY(x, y, data, proc, true) != nullptr;
}
/**
@@ -472,14 +472,14 @@ static Vehicle *VehicleFromPos(TileIndex tile, void *data, VehicleFromPosProc *p
int y = GB(TileY(tile), HASH_RES, HASH_BITS) << HASH_BITS;
Vehicle *v = _vehicle_tile_hash[(x + y) & TOTAL_HASH_MASK];
- for (; v != NULL; v = v->hash_tile_next) {
+ for (; v != nullptr; v = v->hash_tile_next) {
if (v->tile != tile) continue;
Vehicle *a = proc(v, data);
- if (find_first && a != NULL) return a;
+ if (find_first && a != nullptr) return a;
}
- return NULL;
+ return nullptr;
}
/**
@@ -502,31 +502,31 @@ void FindVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
/**
* Checks whether a vehicle is on a specific location. It will call \a proc for
- * vehicles until it returns non-NULL.
+ * vehicles until it returns non-nullptr.
* @note Use #FindVehicleOnPos when you have the intention that all vehicles
* should be iterated over.
* @param tile The location on the map
* @param data Arbitrary data passed to \a proc.
* @param proc The \a proc that determines whether a vehicle will be "found".
- * @return True if proc returned non-NULL.
+ * @return True if proc returned non-nullptr.
*/
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
{
- return VehicleFromPos(tile, data, proc, true) != NULL;
+ return VehicleFromPos(tile, data, proc, true) != nullptr;
}
/**
* Callback that returns 'real' vehicles lower or at height \c *(int*)data .
* @param v Vehicle to examine.
* @param data Pointer to height data.
- * @return \a v if conditions are met, else \c NULL.
+ * @return \a v if conditions are met, else \c nullptr.
*/
static Vehicle *EnsureNoVehicleProcZ(Vehicle *v, void *data)
{
int z = *(int*)data;
- if (v->type == VEH_DISASTER || (v->type == VEH_AIRCRAFT && v->subtype == AIR_SHADOW)) return NULL;
- if (v->z_pos > z) return NULL;
+ if (v->type == VEH_DISASTER || (v->type == VEH_AIRCRAFT && v->subtype == AIR_SHADOW)) return nullptr;
+ if (v->z_pos > z) return nullptr;
return v;
}
@@ -545,15 +545,15 @@ CommandCost EnsureNoVehicleOnGround(TileIndex tile)
* Such a message does not affect MP synchronisation.
*/
Vehicle *v = VehicleFromPos(tile, &z, &EnsureNoVehicleProcZ, true);
- if (v != NULL) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
+ if (v != nullptr) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
return CommandCost();
}
/** Procedure called for every vehicle found in tunnel/bridge in the hash map */
static Vehicle *GetVehicleTunnelBridgeProc(Vehicle *v, void *data)
{
- if (v->type != VEH_TRAIN && v->type != VEH_ROAD && v->type != VEH_SHIP) return NULL;
- if (v == (const Vehicle *)data) return NULL;
+ if (v->type != VEH_TRAIN && v->type != VEH_ROAD && v->type != VEH_SHIP) return nullptr;
+ if (v == (const Vehicle *)data) return nullptr;
return v;
}
@@ -572,9 +572,9 @@ CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle
* Such a message does not affect MP synchronisation.
*/
Vehicle *v = VehicleFromPos(tile, const_cast<Vehicle *>(ignore), &GetVehicleTunnelBridgeProc, true);
- if (v == NULL) v = VehicleFromPos(endtile, const_cast<Vehicle *>(ignore), &GetVehicleTunnelBridgeProc, true);
+ if (v == nullptr) v = VehicleFromPos(endtile, const_cast<Vehicle *>(ignore), &GetVehicleTunnelBridgeProc, true);
- if (v != NULL) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
+ if (v != nullptr) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
return CommandCost();
}
@@ -582,10 +582,10 @@ static Vehicle *EnsureNoTrainOnTrackProc(Vehicle *v, void *data)
{
TrackBits rail_bits = *(TrackBits *)data;
- if (v->type != VEH_TRAIN) return NULL;
+ if (v->type != VEH_TRAIN) return nullptr;
Train *t = Train::From(v);
- if ((t->track != rail_bits) && !TracksOverlap(t->track | rail_bits)) return NULL;
+ if ((t->track != rail_bits) && !TracksOverlap(t->track | rail_bits)) return nullptr;
return v;
}
@@ -605,7 +605,7 @@ CommandCost EnsureNoTrainOnTrackBits(TileIndex tile, TrackBits track_bits)
* Such a message does not affect MP synchronisation.
*/
Vehicle *v = VehicleFromPos(tile, &track_bits, &EnsureNoTrainOnTrackProc, true);
- if (v != NULL) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
+ if (v != nullptr) return_cmd_error(STR_ERROR_TRAIN_IN_THE_WAY + v->type);
return CommandCost();
}
@@ -615,7 +615,7 @@ static void UpdateVehicleTileHash(Vehicle *v, bool remove)
Vehicle **new_hash;
if (remove) {
- new_hash = NULL;
+ new_hash = nullptr;
} else {
int x = GB(TileX(v->tile), HASH_RES, HASH_BITS);
int y = GB(TileY(v->tile), HASH_RES, HASH_BITS) << HASH_BITS;
@@ -625,15 +625,15 @@ static void UpdateVehicleTileHash(Vehicle *v, bool remove)
if (old_hash == new_hash) return;
/* Remove from the old position in the hash table */
- if (old_hash != NULL) {
- if (v->hash_tile_next != NULL) v->hash_tile_next->hash_tile_prev = v->hash_tile_prev;
+ if (old_hash != nullptr) {
+ if (v->hash_tile_next != nullptr) v->hash_tile_next->hash_tile_prev = v->hash_tile_prev;
*v->hash_tile_prev = v->hash_tile_next;
}
/* Insert vehicle at beginning of the new position in the hash table */
- if (new_hash != NULL) {
+ if (new_hash != nullptr) {
v->hash_tile_next = *new_hash;
- if (v->hash_tile_next != NULL) v->hash_tile_next->hash_tile_prev = &v->hash_tile_next;
+ if (v->hash_tile_next != nullptr) v->hash_tile_next->hash_tile_prev = &v->hash_tile_next;
v->hash_tile_prev = new_hash;
*new_hash = v;
}
@@ -650,21 +650,21 @@ static void UpdateVehicleViewportHash(Vehicle *v, int x, int y)
int old_x = v->coord.left;
int old_y = v->coord.top;
- new_hash = (x == INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(x, y)];
- old_hash = (old_x == INVALID_COORD) ? NULL : &_vehicle_viewport_hash[GEN_HASH(old_x, old_y)];
+ new_hash = (x == INVALID_COORD) ? nullptr : &_vehicle_viewport_hash[GEN_HASH(x, y)];
+ old_hash = (old_x == INVALID_COORD) ? nullptr : &_vehicle_viewport_hash[GEN_HASH(old_x, old_y)];
if (old_hash == new_hash) return;
/* remove from hash table? */
- if (old_hash != NULL) {
- if (v->hash_viewport_next != NULL) v->hash_viewport_next->hash_viewport_prev = v->hash_viewport_prev;
+ if (old_hash != nullptr) {
+ if (v->hash_viewport_next != nullptr) v->hash_viewport_next->hash_viewport_prev = v->hash_viewport_prev;
*v->hash_viewport_prev = v->hash_viewport_next;
}
/* insert into hash table? */
- if (new_hash != NULL) {
+ if (new_hash != nullptr) {
v->hash_viewport_next = *new_hash;
- if (v->hash_viewport_next != NULL) v->hash_viewport_next->hash_viewport_prev = &v->hash_viewport_next;
+ if (v->hash_viewport_next != nullptr) v->hash_viewport_next->hash_viewport_prev = &v->hash_viewport_next;
v->hash_viewport_prev = new_hash;
*new_hash = v;
}
@@ -673,7 +673,7 @@ static void UpdateVehicleViewportHash(Vehicle *v, int x, int y)
void ResetVehicleHash()
{
Vehicle *v;
- FOR_ALL_VEHICLES(v) { v->hash_tile_current = NULL; }
+ FOR_ALL_VEHICLES(v) { v->hash_tile_current = nullptr; }
memset(_vehicle_viewport_hash, 0, sizeof(_vehicle_viewport_hash));
memset(_vehicle_tile_hash, 0, sizeof(_vehicle_tile_hash));
}
@@ -701,7 +701,7 @@ void InitializeVehicles()
uint CountVehiclesInChain(const Vehicle *v)
{
uint count = 0;
- do count++; while ((v = v->Next()) != NULL);
+ do count++; while ((v = v->Next()) != nullptr);
return count;
}
@@ -812,7 +812,7 @@ void Vehicle::PreDestructor()
HideFillingPercent(&this->fill_percent_te_id);
this->CancelReservation(INVALID_STATION, st);
delete this->cargo_payment;
- assert(this->cargo_payment == NULL); // cleared by ~CargoPayment
+ assert(this->cargo_payment == nullptr); // cleared by ~CargoPayment
}
if (this->IsEngineCountable()) {
@@ -827,7 +827,7 @@ void Vehicle::PreDestructor()
if (this->type == VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
Aircraft *a = Aircraft::From(this);
Station *st = GetTargetAirportIfValid(a);
- if (st != NULL) {
+ if (st != nullptr) {
const AirportFTA *layout = st->airport.GetFTA()->layout;
CLRBITS(st->airport.flags, layout[a->previous_pos].block | layout[a->pos].block);
}
@@ -842,7 +842,7 @@ void Vehicle::PreDestructor()
}
}
- if (this->Previous() == NULL) {
+ if (this->Previous() == nullptr) {
InvalidateWindowData(WC_VEHICLE_DEPOT, this->tile);
}
@@ -879,7 +879,7 @@ Vehicle::~Vehicle()
if (!(this->vehstatus & VS_HIDDEN)) this->MarkAllViewportsDirty();
Vehicle *v = this->Next();
- this->SetNext(NULL);
+ this->SetNext(nullptr);
delete v;
@@ -918,7 +918,7 @@ static void RunVehicleDayProc()
/* Run the day_proc for every DAY_TICKS vehicle starting at _date_fract. */
for (size_t i = _date_fract; i < Vehicle::GetPoolSize(); i += DAY_TICKS) {
Vehicle *v = Vehicle::Get(i);
- if (v == NULL) continue;
+ if (v == nullptr) continue;
/* Call the 32-day callback if needed */
if ((v->day_counter & 0x1F) == 0 && v->HasEngineType()) {
@@ -961,7 +961,7 @@ void CallVehicleTicks()
FOR_ALL_VEHICLES(v) {
/* Vehicle could be deleted in this tick */
if (!v->Tick()) {
- assert(Vehicle::Get(vehicle_index) == NULL);
+ assert(Vehicle::Get(vehicle_index) == nullptr);
continue;
}
@@ -1142,7 +1142,7 @@ void ViewportAddVehicles(DrawPixelInfo *dpi)
for (int x = xl;; x = (x + GEN_HASHX_INC) & GEN_HASHX_MASK) {
const Vehicle *v = _vehicle_viewport_hash[x + y]; // already masked & 0xFFF
- while (v != NULL) {
+ while (v != nullptr) {
if (!(v->vehstatus & VS_HIDDEN) &&
l <= v->coord.right &&
t <= v->coord.bottom &&
@@ -1165,14 +1165,14 @@ void ViewportAddVehicles(DrawPixelInfo *dpi)
* @param vp Viewport clicked in.
* @param x X coordinate in the viewport.
* @param y Y coordinate in the viewport.
- * @return Closest vehicle, or \c NULL if none found.
+ * @return Closest vehicle, or \c nullptr if none found.
*/
Vehicle *CheckClickOnVehicle(const ViewPort *vp, int x, int y)
{
- Vehicle *found = NULL, *v;
+ Vehicle *found = nullptr, *v;
uint dist, best_dist = UINT_MAX;
- if ((uint)(x -= vp->left) >= (uint)vp->width || (uint)(y -= vp->top) >= (uint)vp->height) return NULL;
+ if ((uint)(x -= vp->left) >= (uint)vp->width || (uint)(y -= vp->top) >= (uint)vp->height) return nullptr;
x = ScaleByZoom(x, vp->zoom) + vp->virtual_left;
y = ScaleByZoom(y, vp->zoom) + vp->virtual_top;
@@ -1296,7 +1296,7 @@ bool Vehicle::HandleBreakdown()
if (!(this->vehstatus & VS_HIDDEN) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_NO_BREAKDOWN_SMOKE)) {
EffectVehicle *u = CreateEffectVehicleRel(this, 4, 4, 5, EV_BREAKDOWN_SMOKE);
- if (u != NULL) u->animation_state = this->breakdown_delay * 2;
+ if (u != nullptr) u->animation_state = this->breakdown_delay * 2;
}
}
@@ -1347,7 +1347,7 @@ void AgeVehicle(Vehicle *v)
SetWindowDirty(WC_VEHICLE_DETAILS, v->index);
/* Don't warn about non-primary or not ours vehicles or vehicles that are crashed */
- if (v->Previous() != NULL || v->owner != _local_company || (v->vehstatus & VS_CRASHED) != 0) return;
+ if (v->Previous() != nullptr || v->owner != _local_company || (v->vehstatus & VS_CRASHED) != 0) return;
const Company *c = Company::Get(v->owner);
/* Don't warn if a renew is active */
@@ -1389,18 +1389,18 @@ uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
bool is_loading = front->current_order.IsType(OT_LOADING);
- /* The station may be NULL when the (colour) string does not need to be set. */
+ /* The station may be nullptr when the (colour) string does not need to be set. */
const Station *st = Station::GetIfValid(front->last_station_visited);
- assert(colour == NULL || (st != NULL && is_loading));
+ assert(colour == nullptr || (st != nullptr && is_loading));
bool order_no_load = is_loading && (front->current_order.GetLoadType() & OLFB_NO_LOAD);
bool order_full_load = is_loading && (front->current_order.GetLoadType() & OLFB_FULL_LOAD);
/* Count up max and used */
- for (const Vehicle *v = front; v != NULL; v = v->Next()) {
+ for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
count += v->cargo.StoredCount();
max += v->cargo_cap;
- if (v->cargo_cap != 0 && colour != NULL) {
+ if (v->cargo_cap != 0 && colour != nullptr) {
unloading += HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) ? 1 : 0;
loading |= !order_no_load &&
(order_full_load || st->goods[v->cargo_type].HasRating()) &&
@@ -1409,7 +1409,7 @@ uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
}
}
- if (colour != NULL) {
+ if (colour != nullptr) {
if (unloading == 0 && loading) {
*colour = STR_PERCENT_UP;
} else if (unloading == 0 && !loading) {
@@ -1507,7 +1507,7 @@ void VehicleEnterDepot(Vehicle *v)
/* Test whether we are heading for this depot. If not, do nothing.
* Note: The target depot for nearest-/manual-depot-orders is only updated on junctions, but we want to accept every depot. */
if ((v->current_order.GetDepotOrderType() & ODTFB_PART_OF_ORDERS) &&
- real_order != NULL && !(real_order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) &&
+ real_order != nullptr && !(real_order->GetDepotActionType() & ODATFB_NEAREST_DEPOT) &&
(v->type == VEH_AIRCRAFT ? v->current_order.GetDestination() != GetStationIndex(v->tile) : v->dest_tile != v->tile)) {
/* We are heading for another depot, keep driving. */
return;
@@ -1688,7 +1688,7 @@ VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y
* @param type type of vehicle
* @param owner owner of vehicles
*/
-FreeUnitIDGenerator::FreeUnitIDGenerator(VehicleType type, CompanyID owner) : cache(NULL), maxid(0), curid(0)
+FreeUnitIDGenerator::FreeUnitIDGenerator(VehicleType type, CompanyID owner) : cache(nullptr), maxid(0), curid(0)
{
/* Find maximum */
const Vehicle *v;
@@ -1800,17 +1800,17 @@ bool CanBuildVehicleInfrastructure(VehicleType type)
* Determines the #LiveryScheme for a vehicle.
* @param engine_type Engine of the vehicle.
* @param parent_engine_type Engine of the front vehicle, #INVALID_ENGINE if vehicle is at front itself.
- * @param v the vehicle, \c NULL if in purchase list etc.
+ * @param v the vehicle, \c nullptr if in purchase list etc.
* @return livery scheme to use.
*/
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
{
- CargoID cargo_type = v == NULL ? (CargoID)CT_INVALID : v->cargo_type;
+ CargoID cargo_type = v == nullptr ? (CargoID)CT_INVALID : v->cargo_type;
const Engine *e = Engine::Get(engine_type);
switch (e->type) {
default: NOT_REACHED();
case VEH_TRAIN:
- if (v != NULL && parent_engine_type != INVALID_ENGINE && (UsesWagonOverride(v) || (v->IsArticulatedPart() && e->u.rail.railveh_type != RAILVEH_WAGON))) {
+ if (v != nullptr && parent_engine_type != INVALID_ENGINE && (UsesWagonOverride(v) || (v->IsArticulatedPart() && e->u.rail.railveh_type != RAILVEH_WAGON))) {
/* Wagonoverrides use the colour scheme of the front engine.
* Articulated parts use the colour scheme of the first part. (Not supported for articulated wagons) */
engine_type = parent_engine_type;
@@ -1853,7 +1853,7 @@ LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_
case VEH_ROAD:
/* Always use the livery of the front */
- if (v != NULL && parent_engine_type != INVALID_ENGINE) {
+ if (v != nullptr && parent_engine_type != INVALID_ENGINE) {
engine_type = parent_engine_type;
e = Engine::Get(engine_type);
cargo_type = v->First()->cargo_type;
@@ -1890,7 +1890,7 @@ LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_
* @param engine_type EngineID of the vehicle
* @param company Owner of the vehicle
* @param parent_engine_type EngineID of the front vehicle. INVALID_VEHICLE if vehicle is at front itself.
- * @param v the vehicle. NULL if in purchase list etc.
+ * @param v the vehicle. nullptr if in purchase list etc.
* @param livery_setting The livery settings to use for acquiring the livery information.
* @return livery to use
*/
@@ -1900,9 +1900,9 @@ const Livery *GetEngineLivery(EngineID engine_type, CompanyID company, EngineID
LiveryScheme scheme = LS_DEFAULT;
if (livery_setting == LIT_ALL || (livery_setting == LIT_COMPANY && company == _local_company)) {
- if (v != NULL) {
+ if (v != nullptr) {
const Group *g = Group::GetIfValid(v->First()->group_id);
- if (g != NULL) {
+ if (g != nullptr) {
/* Traverse parents until we find a livery or reach the top */
while (g->livery.in_use == 0 && g->parent != INVALID_GROUP) {
g = Group::Get(g->parent);
@@ -1925,7 +1925,7 @@ const Livery *GetEngineLivery(EngineID engine_type, CompanyID company, EngineID
static PaletteID GetEngineColourMap(EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v)
{
- PaletteID map = (v != NULL) ? v->colourmap : PAL_NONE;
+ PaletteID map = (v != nullptr) ? v->colourmap : PAL_NONE;
/* Return cached value if any */
if (map != PAL_NONE) return map;
@@ -1943,7 +1943,7 @@ static PaletteID GetEngineColourMap(EngineID engine_type, CompanyID company, Eng
* map else it's returned as-is. */
if (!HasBit(callback, 14)) {
/* Update cache */
- if (v != NULL) const_cast<Vehicle *>(v)->colourmap = map;
+ if (v != nullptr) const_cast<Vehicle *>(v)->colourmap = map;
return map;
}
}
@@ -1962,7 +1962,7 @@ static PaletteID GetEngineColourMap(EngineID engine_type, CompanyID company, Eng
if (twocc) map += livery->colour2 * 16;
/* Update cache */
- if (v != NULL) const_cast<Vehicle *>(v)->colourmap = map;
+ if (v != nullptr) const_cast<Vehicle *>(v)->colourmap = map;
return map;
}
@@ -1974,7 +1974,7 @@ static PaletteID GetEngineColourMap(EngineID engine_type, CompanyID company, Eng
*/
PaletteID GetEnginePalette(EngineID engine_type, CompanyID company)
{
- return GetEngineColourMap(engine_type, company, INVALID_ENGINE, NULL);
+ return GetEngineColourMap(engine_type, company, INVALID_ENGINE, nullptr);
}
/**
@@ -2008,7 +2008,7 @@ void Vehicle::DeleteUnreachedImplicitOrders()
}
const Order *order = this->GetOrder(this->cur_implicit_order_index);
- while (order != NULL) {
+ while (order != nullptr) {
if (this->cur_implicit_order_index == this->cur_real_order_index) break;
if (order->IsType(OT_IMPLICIT)) {
@@ -2022,7 +2022,7 @@ void Vehicle::DeleteUnreachedImplicitOrders()
}
/* Wrap around */
- if (order == NULL) {
+ if (order == nullptr) {
order = this->GetOrder(0);
this->cur_implicit_order_index = 0;
}
@@ -2059,12 +2059,12 @@ void Vehicle::BeginLoading()
* the 'wrong' terminal when skipping orders etc. */
Order *in_list = this->GetOrder(this->cur_implicit_order_index);
if (this->IsGroundVehicle() &&
- (in_list == NULL || !in_list->IsType(OT_IMPLICIT) ||
+ (in_list == nullptr || !in_list->IsType(OT_IMPLICIT) ||
in_list->GetDestination() != this->last_station_visited)) {
bool suppress_implicit_orders = HasBit(this->GetGroundVehicleFlags(), GVF_SUPPRESS_IMPLICIT_ORDERS);
/* Do not create consecutive duplicates of implicit orders */
- Order *prev_order = this->cur_implicit_order_index > 0 ? this->GetOrder(this->cur_implicit_order_index - 1) : (this->GetNumOrders() > 1 ? this->GetLastOrder() : NULL);
- if (prev_order == NULL ||
+ Order *prev_order = this->cur_implicit_order_index > 0 ? this->GetOrder(this->cur_implicit_order_index - 1) : (this->GetNumOrders() > 1 ? this->GetLastOrder() : nullptr);
+ if (prev_order == nullptr ||
(!prev_order->IsType(OT_IMPLICIT) && !prev_order->IsType(OT_GOTO_STATION)) ||
prev_order->GetDestination() != this->last_station_visited) {
@@ -2077,7 +2077,7 @@ void Vehicle::BeginLoading()
bool found = false;
while (target_index != this->cur_real_order_index || this->GetNumManualOrders() == 0) {
const Order *order = this->GetOrder(target_index);
- if (order == NULL) break; // No orders.
+ if (order == nullptr) break; // No orders.
if (order->IsType(OT_IMPLICIT) && order->GetDestination() == this->last_station_visited) {
found = true;
break;
@@ -2113,15 +2113,15 @@ void Vehicle::BeginLoading()
}
/* Wrap around */
- if (order == NULL) {
+ if (order == nullptr) {
order = this->GetOrder(0);
this->cur_implicit_order_index = 0;
}
- assert(order != NULL);
+ assert(order != nullptr);
}
}
} else if (!suppress_implicit_orders &&
- ((this->orders.list == NULL ? OrderList::CanAllocateItem() : this->orders.list->GetNumOrders() < MAX_VEH_ORDER_ID)) &&
+ ((this->orders.list == nullptr ? OrderList::CanAllocateItem() : this->orders.list->GetNumOrders() < MAX_VEH_ORDER_ID)) &&
Order::CanAllocateItem()) {
/* Insert new implicit order */
Order *implicit_order = new Order();
@@ -2165,7 +2165,7 @@ void Vehicle::BeginLoading()
*/
void Vehicle::CancelReservation(StationID next, Station *st)
{
- for (Vehicle *v = this; v != NULL; v = v->next) {
+ for (Vehicle *v = this; v != nullptr; v = v->next) {
VehicleCargoList &cargo = v->cargo;
if (cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
DEBUG(misc, 1, "cancelling cargo reservation");
@@ -2185,7 +2185,7 @@ void Vehicle::LeaveStation()
assert(this->current_order.IsType(OT_LOADING));
delete this->cargo_payment;
- assert(this->cargo_payment == NULL); // cleared by ~CargoPayment
+ assert(this->cargo_payment == nullptr); // cleared by ~CargoPayment
/* Only update the timetable if the vehicle was supposed to stop here. */
if (this->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE) UpdateVehicleTimetable(this, false);
@@ -2214,7 +2214,7 @@ void Vehicle::LeaveStation()
st->loading_vehicles.remove(this);
HideFillingPercent(&this->fill_percent_te_id);
- trip_occupancy = CalcPercentVehicleFilled(this, NULL);
+ trip_occupancy = CalcPercentVehicleFilled(this, nullptr);
if (this->type == VEH_TRAIN && !(this->vehstatus & VS_CRASHED)) {
/* Trigger station animation (trains only) */
@@ -2234,7 +2234,7 @@ void Vehicle::LeaveStation()
*/
void Vehicle::ResetRefitCaps()
{
- for (Vehicle *v = this; v != NULL; v = v->Next()) v->refit_cap = v->cargo_cap;
+ for (Vehicle *v = this; v != nullptr; v = v->Next()) v->refit_cap = v->cargo_cap;
}
/**
@@ -2257,7 +2257,7 @@ void Vehicle::HandleLoading(bool mode)
/* Only advance to next order if we just loaded at the current one */
const Order *order = this->GetOrder(this->cur_implicit_order_index);
- if (order == NULL ||
+ if (order == nullptr ||
(!order->IsType(OT_IMPLICIT) && !order->IsType(OT_GOTO_STATION)) ||
order->GetDestination() != this->last_station_visited) {
return;
@@ -2279,7 +2279,7 @@ void Vehicle::HandleLoading(bool mode)
*/
void Vehicle::GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const
{
- for (const Vehicle *v = this; v != NULL; v = v->Next()) {
+ for (const Vehicle *v = this; v != nullptr; v = v->Next()) {
if (v->cargo_cap == 0) continue;
SmallPair<CargoID, uint> *pair = capacities.Find(v->cargo_type);
if (pair == capacities.End()) {
@@ -2293,7 +2293,7 @@ void Vehicle::GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) cons
uint Vehicle::GetConsistTotalCapacity() const
{
uint result = 0;
- for (const Vehicle *v = this; v != NULL; v = v->Next()) {
+ for (const Vehicle *v = this; v != nullptr; v = v->Next()) {
result += v->cargo_cap;
}
return result;
@@ -2650,34 +2650,34 @@ void Vehicle::ShowVisualEffect() const
CreateEffectVehicleRel(v, x, y, 10, evt);
}
- } while ((v = v->Next()) != NULL);
+ } while ((v = v->Next()) != nullptr);
if (sound) PlayVehicleSound(this, VSE_VISUAL_EFFECT);
}
/**
* Set the next vehicle of this vehicle.
- * @param next the next vehicle. NULL removes the next vehicle.
+ * @param next the next vehicle. nullptr removes the next vehicle.
*/
void Vehicle::SetNext(Vehicle *next)
{
assert(this != next);
- if (this->next != NULL) {
+ if (this->next != nullptr) {
/* We had an old next vehicle. Update the first and previous pointers */
- for (Vehicle *v = this->next; v != NULL; v = v->Next()) {
+ for (Vehicle *v = this->next; v != nullptr; v = v->Next()) {
v->first = this->next;
}
- this->next->previous = NULL;
+ this->next->previous = nullptr;
}
this->next = next;
- if (this->next != NULL) {
+ if (this->next != nullptr) {
/* A new next vehicle. Update the first and previous pointers */
- if (this->next->previous != NULL) this->next->previous->next = NULL;
+ if (this->next->previous != nullptr) this->next->previous->next = nullptr;
this->next->previous = this;
- for (Vehicle *v = this->next; v != NULL; v = v->Next()) {
+ for (Vehicle *v = this->next; v != nullptr; v = v->Next()) {
v->first = this->first;
}
}
@@ -2690,12 +2690,12 @@ void Vehicle::SetNext(Vehicle *next)
*/
void Vehicle::AddToShared(Vehicle *shared_chain)
{
- assert(this->previous_shared == NULL && this->next_shared == NULL);
+ assert(this->previous_shared == nullptr && this->next_shared == nullptr);
- if (shared_chain->orders.list == NULL) {
- assert(shared_chain->previous_shared == NULL);
- assert(shared_chain->next_shared == NULL);
- this->orders.list = shared_chain->orders.list = new OrderList(NULL, shared_chain);
+ if (shared_chain->orders.list == nullptr) {
+ assert(shared_chain->previous_shared == nullptr);
+ assert(shared_chain->next_shared == nullptr);
+ this->orders.list = shared_chain->orders.list = new OrderList(nullptr, shared_chain);
}
this->next_shared = shared_chain->next_shared;
@@ -2703,7 +2703,7 @@ void Vehicle::AddToShared(Vehicle *shared_chain)
shared_chain->next_shared = this;
- if (this->next_shared != NULL) this->next_shared->previous_shared = this;
+ if (this->next_shared != nullptr) this->next_shared->previous_shared = this;
shared_chain->orders.list->AddVehicle(this);
}
@@ -2725,7 +2725,7 @@ void Vehicle::RemoveFromShared()
this->previous_shared->next_shared = this->NextShared();
}
- if (this->next_shared != NULL) this->next_shared->previous_shared = this->previous_shared;
+ if (this->next_shared != nullptr) this->next_shared->previous_shared = this->previous_shared;
if (this->orders.list->GetNumVehicles() == 1) {
@@ -2738,8 +2738,8 @@ void Vehicle::RemoveFromShared()
InvalidateWindowData(GetWindowClassForVehicleType(this->type), vli.Pack(), this->FirstShared()->index | (1U << 31));
}
- this->next_shared = NULL;
- this->previous_shared = NULL;
+ this->next_shared = nullptr;
+ this->previous_shared = nullptr;
}
void VehiclesYearlyLoop()
@@ -2783,7 +2783,7 @@ void VehiclesYearlyLoop()
bool CanVehicleUseStation(EngineID engine_type, const Station *st)
{
const Engine *e = Engine::GetIfValid(engine_type);
- assert(e != NULL);
+ assert(e != nullptr);
switch (e->type) {
case VEH_TRAIN:
@@ -2815,7 +2815,7 @@ bool CanVehicleUseStation(EngineID engine_type, const Station *st)
*/
bool CanVehicleUseStation(const Vehicle *v, const Station *st)
{
- if (v->type == VEH_ROAD) return st->GetPrimaryRoadStop(RoadVehicle::From(v)) != NULL;
+ if (v->type == VEH_ROAD) return st->GetPrimaryRoadStop(RoadVehicle::From(v)) != nullptr;
return CanVehicleUseStation(v->engine_type, st);
}
@@ -2896,7 +2896,7 @@ void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
u = u->GetFirstEnginePart();
/* Include num_vehicles vehicles, not counting articulated parts */
- for (; u != NULL && num_vehicles > 0; num_vehicles--) {
+ for (; u != nullptr && num_vehicles > 0; num_vehicles--) {
do {
/* Include current vehicle in the selection. */
include(set, u->index);
@@ -2905,7 +2905,7 @@ void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
if (u->IsMultiheaded()) include(set, u->other_multiheaded_part->index);
u = u->Next();
- } while (u != NULL && u->IsArticulatedPart());
+ } while (u != nullptr && u->IsArticulatedPart());
}
}
}
diff --git a/src/vehicle_base.h b/src/vehicle_base.h
index d02d33e2c..523f1c263 100644
--- a/src/vehicle_base.h
+++ b/src/vehicle_base.h
@@ -459,7 +459,7 @@ public:
*/
inline void InvalidateNewGRFCacheOfChain()
{
- for (Vehicle *u = this; u != NULL; u = u->Next()) {
+ for (Vehicle *u = this; u != nullptr; u = u->Next()) {
u->InvalidateNewGRFCache();
}
}
@@ -576,14 +576,14 @@ public:
/**
* Get the next vehicle of this vehicle.
* @note articulated parts are also counted as vehicles.
- * @return the next vehicle or NULL when there isn't a next vehicle.
+ * @return the next vehicle or nullptr when there isn't a next vehicle.
*/
inline Vehicle *Next() const { return this->next; }
/**
* Get the previous vehicle of this vehicle.
* @note articulated parts are also counted as vehicles.
- * @return the previous vehicle or NULL when there isn't a previous vehicle.
+ * @return the previous vehicle or nullptr when there isn't a previous vehicle.
*/
inline Vehicle *Previous() const { return this->previous; }
@@ -600,7 +600,7 @@ public:
inline Vehicle *Last()
{
Vehicle *v = this;
- while (v->Next() != NULL) v = v->Next();
+ while (v->Next() != nullptr) v = v->Next();
return v;
}
@@ -611,22 +611,22 @@ public:
inline const Vehicle *Last() const
{
const Vehicle *v = this;
- while (v->Next() != NULL) v = v->Next();
+ while (v->Next() != nullptr) v = v->Next();
return v;
}
/**
* Get the vehicle at offset \a n of this vehicle chain.
* @param n Offset from the current vehicle.
- * @return The new vehicle or NULL if the offset is out-of-bounds.
+ * @return The new vehicle or nullptr if the offset is out-of-bounds.
*/
inline Vehicle *Move(int n)
{
Vehicle *v = this;
if (n < 0) {
- for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
+ for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
} else {
- for (int i = 0; i != n && v != NULL; i++) v = v->Next();
+ for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
}
return v;
}
@@ -634,15 +634,15 @@ public:
/**
* Get the vehicle at offset \a n of this vehicle chain.
* @param n Offset from the current vehicle.
- * @return The new vehicle or NULL if the offset is out-of-bounds.
+ * @return The new vehicle or nullptr if the offset is out-of-bounds.
*/
inline const Vehicle *Move(int n) const
{
const Vehicle *v = this;
if (n < 0) {
- for (int i = 0; i != n && v != NULL; i--) v = v->Previous();
+ for (int i = 0; i != n && v != nullptr; i--) v = v->Previous();
} else {
- for (int i = 0; i != n && v != NULL; i++) v = v->Next();
+ for (int i = 0; i != n && v != nullptr; i++) v = v->Next();
}
return v;
}
@@ -651,20 +651,20 @@ public:
* Get the first order of the vehicles order list.
* @return first order of order list.
*/
- inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
+ inline Order *GetFirstOrder() const { return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetFirstOrder(); }
void AddToShared(Vehicle *shared_chain);
void RemoveFromShared();
/**
* Get the next vehicle of the shared vehicle chain.
- * @return the next shared vehicle or NULL when there isn't a next vehicle.
+ * @return the next shared vehicle or nullptr when there isn't a next vehicle.
*/
inline Vehicle *NextShared() const { return this->next_shared; }
/**
* Get the previous vehicle of the shared vehicle chain
- * @return the previous shared vehicle or NULL when there isn't a previous vehicle.
+ * @return the previous shared vehicle or nullptr when there isn't a previous vehicle.
*/
inline Vehicle *PreviousShared() const { return this->previous_shared; }
@@ -672,25 +672,25 @@ public:
* Get the first vehicle of this vehicle chain.
* @return the first vehicle of the chain.
*/
- inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
+ inline Vehicle *FirstShared() const { return (this->orders.list == nullptr) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
/**
* Check if we share our orders with another vehicle.
* @return true if there are other vehicles sharing the same order
*/
- inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
+ inline bool IsOrderListShared() const { return this->orders.list != nullptr && this->orders.list->IsShared(); }
/**
* Get the number of orders this vehicle has.
* @return the number of orders this vehicle has.
*/
- inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
+ inline VehicleOrderID GetNumOrders() const { return (this->orders.list == nullptr) ? 0 : this->orders.list->GetNumOrders(); }
/**
* Get the number of manually added orders this vehicle has.
* @return the number of manually added orders this vehicle has.
*/
- inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
+ inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == nullptr) ? 0 : this->orders.list->GetNumManualOrders(); }
/**
* Get the next station the vehicle will stop at.
@@ -698,7 +698,7 @@ public:
*/
inline StationIDStack GetNextStoppingStation() const
{
- return (this->orders.list == NULL) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
+ return (this->orders.list == nullptr) ? INVALID_STATION : this->orders.list->GetNextStoppingStation(this);
}
void ResetRefitCaps();
@@ -853,22 +853,22 @@ public:
}
/**
- * Returns order 'index' of a vehicle or NULL when it doesn't exists
+ * Returns order 'index' of a vehicle or nullptr when it doesn't exists
* @param index the order to fetch
* @return the found (or not) order
*/
inline Order *GetOrder(int index) const
{
- return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
+ return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetOrderAt(index);
}
/**
- * Returns the last order of a vehicle, or NULL if it doesn't exists
+ * Returns the last order of a vehicle, or nullptr if it doesn't exists
* @return last order of a vehicle, if available
*/
inline Order *GetLastOrder() const
{
- return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
+ return (this->orders.list == nullptr) ? nullptr : this->orders.list->GetLastOrder();
}
bool IsEngineCountable() const;
@@ -900,7 +900,7 @@ public:
*/
inline bool HasArticulatedPart() const
{
- return this->Next() != NULL && this->Next()->IsArticulatedPart();
+ return this->Next() != nullptr && this->Next()->IsArticulatedPart();
}
/**
@@ -967,7 +967,7 @@ public:
inline Vehicle *GetPrevVehicle() const
{
Vehicle *v = this->Previous();
- while (v != NULL && v->IsArticulatedPart()) v = v->Previous();
+ while (v != nullptr && v->IsArticulatedPart()) v = v->Previous();
return v;
}
@@ -1103,7 +1103,7 @@ struct SpecializedVehicle : public Vehicle {
*/
static inline T *GetIfValid(size_t index)
{
- return IsValidID(index) ? Get(index) : NULL;
+ return IsValidID(index) ? Get(index) : nullptr;
}
/**
diff --git a/src/vehicle_cmd.cpp b/src/vehicle_cmd.cpp
index eb7fc9654..94492e344 100644
--- a/src/vehicle_cmd.cpp
+++ b/src/vehicle_cmd.cpp
@@ -137,7 +137,7 @@ CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
SavedRandomSeeds saved_seeds;
if (flags != subflags) SaveRandomSeeds(&saved_seeds);
- Vehicle *v = NULL;
+ Vehicle *v = nullptr;
switch (type) {
case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(tile, subflags, e, GB(p1, 24, 8), &v)); break;
case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(tile, subflags, e, GB(p1, 24, 8), &v)); break;
@@ -153,7 +153,7 @@ CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
}
if (refitting) {
- value.AddCost(CmdRefitVehicle(tile, flags, v->index, cargo, NULL));
+ value.AddCost(CmdRefitVehicle(tile, flags, v->index, cargo, nullptr));
} else {
/* Fill in non-refitted capacities */
_returned_refit_capacity = e->GetDisplayDefaultCapacity(&_returned_mail_refit_capacity);
@@ -207,7 +207,7 @@ CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint3
CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
- if (v == NULL) return CMD_ERROR;
+ if (v == nullptr) return CMD_ERROR;
Vehicle *front = v->First();
@@ -220,7 +220,7 @@ CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
/* Can we actually make the order backup, i.e. are there enough orders? */
if (p1 & MAKE_ORDER_BACKUP_FLAG &&
- front->orders.list != NULL &&
+ front->orders.list != nullptr &&
!front->orders.list->IsShared() &&
!Order::CanAllocateItem(front->orders.list->GetNumOrders())) {
/* Only happens in exceptional cases when there aren't enough orders anyhow.
@@ -244,7 +244,7 @@ CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3
/**
* Helper to run the refit cost callback.
- * @param v The vehicle we are refitting, can be NULL.
+ * @param v The vehicle we are refitting, can be nullptr.
* @param engine_type Which engine to refit
* @param new_cid Cargo type we are refitting to.
* @param new_subtype New cargo subtype.
@@ -257,7 +257,7 @@ static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID ne
const Engine *e = Engine::Get(engine_type);
/* Is this vehicle a NewGRF vehicle? */
- if (e->GetGRF() != NULL) {
+ if (e->GetGRF() != nullptr) {
const CargoSpec *cs = CargoSpec::Get(new_cid);
uint32 param1 = (cs->classes << 16) | (new_subtype << 8) | e->GetGRF()->cargo_map[new_cid];
@@ -271,12 +271,12 @@ static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID ne
}
*auto_refit_allowed = e->info.refit_cost == 0;
- return (v == NULL || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
+ return (v == nullptr || v->cargo_type != new_cid) ? e->info.refit_cost : 0;
}
/**
* Learn the price of refitting a certain engine
- * @param v The vehicle we are refitting, can be NULL.
+ * @param v The vehicle we are refitting, can be nullptr.
* @param engine_type Which engine to refit
* @param new_cid Cargo type we are refitting to.
* @param new_subtype New cargo subtype.
@@ -358,7 +358,7 @@ static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles,
v->InvalidateNewGRFCacheOfChain();
byte actual_subtype = new_subtype;
- for (; v != NULL; v = (only_this ? NULL : v->Next())) {
+ for (; v != nullptr; v = (only_this ? nullptr : v->Next())) {
/* Reset actual_subtype for every new vehicle */
if (!v->IsArticulatedPart()) actual_subtype = new_subtype;
@@ -469,7 +469,7 @@ static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles,
CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL) return CMD_ERROR;
+ if (v == nullptr) return CMD_ERROR;
/* Don't allow disasters and sparks and such to be refitted.
* We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */
@@ -560,7 +560,7 @@ CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1,
if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -652,7 +652,7 @@ CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32
if (!GenerateVehicleSortList(&list, vli)) return CMD_ERROR;
} else {
/* Get the list of vehicles in the depot */
- BuildDepotVehicleList(vli.vtype, tile, &list, NULL);
+ BuildDepotVehicleList(vli.vtype, tile, &list, nullptr);
}
for (uint i = 0; i < list.size(); i++) {
@@ -751,7 +751,7 @@ static bool IsUniqueVehicleName(const char *name)
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
- if (v->name != NULL && strcmp(v->name, name) == 0) return false;
+ if (v->name != nullptr && strcmp(v->name, name) == 0) return false;
}
return true;
@@ -821,11 +821,11 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
CommandCost total_cost(EXPENSES_NEW_VEHICLES);
Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
Vehicle *v_front = v;
- Vehicle *w = NULL;
- Vehicle *w_front = NULL;
- Vehicle *w_rear = NULL;
+ Vehicle *w = nullptr;
+ Vehicle *w_front = nullptr;
+ Vehicle *w_rear = nullptr;
/*
* v_front is the front engine in the original vehicle
@@ -845,7 +845,7 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
int veh_counter = 0;
do {
veh_counter++;
- } while ((v = v->Next()) != NULL);
+ } while ((v = v->Next()) != nullptr);
if (!Vehicle::CanAllocateItem(veh_counter)) {
return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
@@ -873,7 +873,7 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
if (cost.Failed()) {
/* Can't build a part, then sell the stuff we already made; clear up the mess */
- if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
+ if (w_front != nullptr) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
return cost;
}
@@ -906,7 +906,7 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
}
w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
}
- } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
+ } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
/* for trains this needs to be the front engine due to the callback function */
@@ -932,7 +932,7 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
do {
do {
if (flags & DC_EXEC) {
- assert(w != NULL);
+ assert(w != nullptr);
/* Find out what's the best sub type */
byte subtype = GetBestFittingSubType(v, w, v->cargo_type);
@@ -952,7 +952,7 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
bool dummy;
- total_cost.AddCost(GetRefitCost(NULL, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
+ total_cost.AddCost(GetRefitCost(nullptr, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy));
}
}
@@ -961,10 +961,10 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
} else {
break;
}
- } while (v != NULL);
+ } while (v != nullptr);
if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle();
- } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL);
+ } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != nullptr);
if (flags & DC_EXEC) {
/*
@@ -975,7 +975,7 @@ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint
DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER);
/* Now clone the vehicle's name, if it has one. */
- if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
+ if (v_front->name != nullptr) CloneVehicleName(v_front, w_front);
}
/* Since we can't estimate the cost of cloning a vehicle accurately we must
@@ -1045,7 +1045,7 @@ CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1
}
Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
- if (v == NULL) return CMD_ERROR;
+ if (v == nullptr) return CMD_ERROR;
if (!v->IsPrimaryVehicle()) return CMD_ERROR;
return v->SendToDepot(flags, (DepotCommand)(p1 & DEPOT_COMMAND_MASK));
@@ -1063,7 +1063,7 @@ CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1
CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
@@ -1077,7 +1077,7 @@ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
if (flags & DC_EXEC) {
free(v->name);
- v->name = reset ? NULL : stredup(text);
+ v->name = reset ? nullptr : stredup(text);
InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1);
MarkWholeScreenDirty();
}
@@ -1101,7 +1101,7 @@ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uin
CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
+ if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR;
CommandCost ret = CheckOwnership(v->owner);
if (ret.Failed()) return ret;
diff --git a/src/vehicle_func.h b/src/vehicle_func.h
index b4e1c0074..e61f6e233 100644
--- a/src/vehicle_func.h
+++ b/src/vehicle_func.h
@@ -60,7 +60,7 @@ byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_t
void ViewportAddVehicles(DrawPixelInfo *dpi);
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical);
-CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore = NULL);
+CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore = nullptr);
void DecreaseVehicleValue(Vehicle *v);
void CheckVehicleBreakdown(Vehicle *v);
diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp
index f94092650..b2517f967 100644
--- a/src/vehicle_gui.cpp
+++ b/src/vehicle_gui.cpp
@@ -181,14 +181,14 @@ DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplac
}
/* cached values for VehicleNameSorter to spare many GetString() calls */
-static const Vehicle *_last_vehicle[2] = { NULL, NULL };
+static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
void BaseVehicleListWindow::SortVehicleList()
{
if (this->vehicles.Sort()) return;
/* invalidate cached values for name sorter - vehicle names could change */
- _last_vehicle[0] = _last_vehicle[1] = NULL;
+ _last_vehicle[0] = _last_vehicle[1] = nullptr;
}
void DepotSortList(VehicleList *list)
@@ -235,7 +235,7 @@ byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_t
/* Create a list of subtypes used by the various parts of v_for */
static std::vector<StringID> subtypes;
subtypes.clear();
- for (; v_from != NULL; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : NULL) {
+ for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
const Engine *e_from = v_from->GetEngine();
if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
include(subtypes, GetCargoSubtypeText(v_from));
@@ -245,7 +245,7 @@ byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_t
bool success = false;
if (subtypes.size() > 0) {
/* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
- for (Vehicle *v = v_for; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
+ for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
const Engine *e = v->GetEngine();
if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
@@ -507,7 +507,7 @@ struct RefitWindow : public Window {
}
current_index++;
}
- } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
+ } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
}
/**
@@ -570,10 +570,10 @@ struct RefitWindow : public Window {
*/
RefitOption *GetRefitOption()
{
- if (this->sel[0] < 0) return NULL;
+ if (this->sel[0] < 0) return nullptr;
SubtypeList &l = this->list[this->sel[0]];
- if ((uint)this->sel[1] >= l.size()) return NULL;
+ if ((uint)this->sel[1] >= l.size()) return nullptr;
return &l[this->sel[1]];
}
@@ -587,7 +587,7 @@ struct RefitWindow : public Window {
this->CreateNestedTree();
this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
- this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : NULL);
+ this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
@@ -604,7 +604,7 @@ struct RefitWindow : public Window {
void OnInit() override
{
- if (this->cargo != NULL) {
+ if (this->cargo != nullptr) {
/* Store the RefitOption currently in use. */
RefitOption current_refit_option = *(this->cargo);
@@ -612,8 +612,8 @@ struct RefitWindow : public Window {
this->BuildRefitList();
this->sel[0] = -1;
this->sel[1] = 0;
- this->cargo = NULL;
- for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
+ this->cargo = nullptr;
+ for (uint i = 0; this->cargo == nullptr && i < NUM_CARGO; i++) {
for (uint j = 0; j < list[i].size(); j++) {
if (list[i][j] == current_refit_option) {
this->sel[0] = i;
@@ -635,7 +635,7 @@ struct RefitWindow : public Window {
void OnPaint() override
{
/* Determine amount of items for scroller. */
- if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
+ if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
/* Calculate sprite position. */
NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
@@ -729,7 +729,7 @@ struct RefitWindow : public Window {
case WID_VR_VEHICLE_PANEL_DISPLAY: {
Vehicle *v = Vehicle::Get(this->window_number);
DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
- r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
+ r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
/* Highlight selected vehicles. */
if (this->order != INVALID_VEH_ORDER_ID) break;
@@ -742,7 +742,7 @@ struct RefitWindow : public Window {
int left = INT32_MIN;
int width = 0;
- for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
+ for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
/* Start checking. */
const bool contained = std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), u->index) != vehicles_to_refit.end();
if (contained && left == INT32_MIN) {
@@ -751,8 +751,8 @@ struct RefitWindow : public Window {
}
/* Draw a selection. */
- if ((!contained || u->Next() == NULL) && left != INT32_MIN) {
- if (u->Next() == NULL && contained) {
+ if ((!contained || u->Next() == nullptr) && left != INT32_MIN) {
+ if (u->Next() == nullptr && contained) {
int current_width = u->GetDisplayImageWidth();
width += current_width;
x += current_width;
@@ -790,7 +790,7 @@ struct RefitWindow : public Window {
break;
case WID_VR_INFO:
- if (this->cargo != NULL) {
+ if (this->cargo != nullptr) {
StringID string = this->GetCapacityString(this->cargo);
if (string != INVALID_STRING_ID) {
DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
@@ -857,7 +857,7 @@ struct RefitWindow : public Window {
const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
click_x -= this->vehicle_margin;
- if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
+ if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
return click_x;
}
@@ -878,7 +878,7 @@ struct RefitWindow : public Window {
if (left_x >= 0) {
const Train *u = Train::From(v);
bool start_counting = false;
- for (; u != NULL; u = u->Next()) {
+ for (; u != nullptr; u = u->Next()) {
int current_width = u->GetDisplayImageWidth();
left_x -= current_width;
right_x -= current_width;
@@ -942,7 +942,7 @@ struct RefitWindow : public Window {
}
case WID_VR_REFIT: // refit button
- if (this->cargo != NULL) {
+ if (this->cargo != nullptr) {
const Vehicle *v = Vehicle::Get(this->window_number);
if (this->order == INVALID_VEH_ORDER_ID) {
@@ -986,7 +986,7 @@ struct RefitWindow : public Window {
{
this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
- if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
+ if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
}
};
@@ -1137,8 +1137,8 @@ static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * co
CargoArray diff;
/* Append the cargo of the connected waggons */
- for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
- for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
+ for (v = *a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
+ for (v = *b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
int r = 0;
for (CargoID i = 0; i < NUM_CARGO; i++) {
@@ -1176,8 +1176,8 @@ static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * co
const Vehicle *u;
Money diff = 0;
- for (u = *a; u != NULL; u = u->Next()) diff += u->value;
- for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
+ for (u = *a; u != nullptr; u = u->Next()) diff += u->value;
+ for (u = *b; u != nullptr; u = u->Next()) diff -= u->value;
int r = ClampToI32(diff);
return (r != 0) ? r : VehicleNumberSorter(a, b);
@@ -1218,10 +1218,10 @@ void InitializeGUI()
static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
{
Window *w = FindWindowById(window_class, from_index);
- if (w != NULL) {
+ if (w != nullptr) {
/* Update window_number */
w->window_number = to_index;
- if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
+ if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
/* Update vehicle drag data */
if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
@@ -1291,7 +1291,7 @@ static const NWidgetPart _nested_vehicle_list[] = {
static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
{
const Order *order = v->GetOrder(start);
- if (order == NULL) return;
+ if (order == nullptr) return;
bool rtl = _current_text_dir == TD_RTL;
int l_offset = rtl ? 0 : ScaleGUITrad(6);
@@ -1312,7 +1312,7 @@ static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, Veh
oid++;
order = order->next;
- if (order == NULL) {
+ if (order == nullptr) {
order = v->orders.list->GetFirstOrder();
oid = 0;
}
@@ -1397,7 +1397,7 @@ void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int
DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
- if (v->name != NULL) {
+ if (v->name != nullptr) {
/* The vehicle got a name so we will print it */
SetDParam(0, v->index);
DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
@@ -1869,7 +1869,7 @@ struct VehicleDetailsWindow : Window {
const Vehicle *v = Vehicle::Get(window_number);
this->CreateNestedTree();
- this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
+ this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
this->FinishInitNested(window_number);
this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
@@ -1914,7 +1914,7 @@ struct VehicleDetailsWindow : Window {
/* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
/* Add space for the cargo amount for each part. */
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
}
} else {
@@ -2219,15 +2219,15 @@ struct VehicleDetailsWindow : Window {
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
- DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type), NULL, str);
+ DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type), nullptr, str);
}
void OnResize() override
{
NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
- if (nwi != NULL) {
+ if (nwi != nullptr) {
this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
}
}
@@ -2382,7 +2382,7 @@ void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, ui
if (result.Failed()) return;
const Vehicle *v = Vehicle::GetIfValid(p1);
- if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
+ if (v == nullptr || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
@@ -2397,7 +2397,7 @@ void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, ui
void StartStopVehicle(const Vehicle *v, bool texteffect)
{
assert(v->IsPrimaryVehicle());
- DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : NULL);
+ DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr);
}
/** Checks whether the vehicle may be refitted at the moment.*/
@@ -2407,7 +2407,7 @@ static bool IsVehicleRefitable(const Vehicle *v)
do {
if (IsEngineRefittable(v->engine_type)) return true;
- } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
+ } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
return false;
}
@@ -2709,7 +2709,7 @@ public:
* most likely already open, but is also visible in the vehicle viewport. */
DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
_vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
- _ctrl_pressed ? NULL : CcCloneVehicle);
+ _ctrl_pressed ? nullptr : CcCloneVehicle);
break;
case WID_VV_TURN_AROUND: // turn around
assert(v->IsGroundVehicle());
@@ -2725,7 +2725,7 @@ public:
void OnResize() override
{
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
nvp->UpdateViewportCoordinates(this);
}
@@ -2797,7 +2797,7 @@ void ShowVehicleViewWindow(const Vehicle *v)
*/
bool VehicleClicked(const Vehicle *v)
{
- assert(v != NULL);
+ assert(v != nullptr);
if (!(_thd.place_mode & HT_VEHICLE)) return false;
v = v->First();
@@ -2809,7 +2809,7 @@ bool VehicleClicked(const Vehicle *v)
void StopGlobalFollowVehicle(const Vehicle *v)
{
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
- if (w != NULL && w->viewport->follow_vehicle == v->index) {
+ if (w != nullptr && w->viewport->follow_vehicle == v->index) {
ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
w->viewport->follow_vehicle = INVALID_VEHICLE;
}
@@ -2864,7 +2864,7 @@ int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
{
if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
int vehicle_width = 0;
- for (const Vehicle *u = v; u != NULL; u = u->Next()) {
+ for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
vehicle_width += GetSingleVehicleWidth(u, image_type);
}
return vehicle_width;
@@ -2884,7 +2884,7 @@ void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
_cursor.sprite_count = 0;
int total_width = 0;
- for (; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
+ for (; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
if (total_width >= 2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH) break;
PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
diff --git a/src/vehiclelist.cpp b/src/vehiclelist.cpp
index c98797573..acb848982 100644
--- a/src/vehiclelist.cpp
+++ b/src/vehiclelist.cpp
@@ -65,13 +65,13 @@ bool VehicleListIdentifier::UnpackIfValid(uint32 data)
* @param type Type of vehicle
* @param tile The tile the depot is located on
* @param engines Pointer to list to add vehicles to
- * @param wagons Pointer to list to add wagons to (can be NULL)
+ * @param wagons Pointer to list to add wagons to (can be nullptr)
* @param individual_wagons If true add every wagon to \a wagons which is not attached to an engine. If false only add the first wagon of every row.
*/
void BuildDepotVehicleList(VehicleType type, TileIndex tile, VehicleList *engines, VehicleList *wagons, bool individual_wagons)
{
engines->clear();
- if (wagons != NULL && wagons != engines) wagons->clear();
+ if (wagons != nullptr && wagons != engines) wagons->clear();
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
@@ -84,7 +84,7 @@ void BuildDepotVehicleList(VehicleType type, TileIndex tile, VehicleList *engine
const Train *t = Train::From(v);
if (t->IsArticulatedPart() || t->IsRearDualheaded()) continue;
if (t->track != TRACK_BIT_DEPOT) continue;
- if (wagons != NULL && t->First()->IsFreeWagon()) {
+ if (wagons != nullptr && t->First()->IsFreeWagon()) {
if (individual_wagons || t->IsFreeWagon()) wagons->push_back(t);
continue;
}
@@ -104,7 +104,7 @@ void BuildDepotVehicleList(VehicleType type, TileIndex tile, VehicleList *engine
/* Ensure the lists are not wasting too much space. If the lists are fresh
* (i.e. built within a command) then this will actually do nothing. */
engines->shrink_to_fit();
- if (wagons != NULL && wagons != engines) wagons->shrink_to_fit();
+ if (wagons != nullptr && wagons != engines) wagons->shrink_to_fit();
}
/**
@@ -139,9 +139,9 @@ bool GenerateVehicleSortList(VehicleList *list, const VehicleListIdentifier &vli
case VL_SHARED_ORDERS:
/* Add all vehicles from this vehicle's shared order list */
v = Vehicle::GetIfValid(vli.index);
- if (v == NULL || v->type != vli.vtype || !v->IsPrimaryVehicle()) return false;
+ if (v == nullptr || v->type != vli.vtype || !v->IsPrimaryVehicle()) return false;
- for (; v != NULL; v = v->NextShared()) {
+ for (; v != nullptr; v = v->NextShared()) {
list->push_back(v);
}
break;
diff --git a/src/video/allegro_v.cpp b/src/video/allegro_v.cpp
index c21f88d67..47dd92e1e 100644
--- a/src/video/allegro_v.cpp
+++ b/src/video/allegro_v.cpp
@@ -140,7 +140,7 @@ static void GetVideoModes()
set_gfx_mode(_fullscreen ? GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
GFX_MODE_LIST *mode_list = get_gfx_mode_list(gfx_driver->id);
- if (mode_list == NULL) {
+ if (mode_list == nullptr) {
memcpy(_resolutions, default_resolutions, sizeof(default_resolutions));
_num_resolutions = lengthof(default_resolutions);
return;
@@ -243,7 +243,7 @@ static bool CreateMainSurface(uint w, uint h)
bool VideoDriver_Allegro::ClaimMousePointer()
{
select_mouse_cursor(MOUSE_CURSOR_NONE);
- show_mouse(NULL);
+ show_mouse(nullptr);
disable_hardware_cursor();
return true;
}
@@ -424,7 +424,7 @@ int _allegro_instance_count = 0;
const char *VideoDriver_Allegro::Start(const char * const *parm)
{
- if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) {
+ if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) {
DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
return "Failed to set up Allegro";
}
@@ -437,8 +437,8 @@ const char *VideoDriver_Allegro::Start(const char * const *parm)
#if defined _DEBUG
/* Allegro replaces SEGV/ABRT signals meaning that the debugger will never
* be triggered, so rereplace the signals and make the debugger useful. */
- signal(SIGABRT, NULL);
- signal(SIGSEGV, NULL);
+ signal(SIGABRT, nullptr);
+ signal(SIGSEGV, nullptr);
#endif
GetVideoModes();
@@ -448,7 +448,7 @@ const char *VideoDriver_Allegro::Start(const char * const *parm)
MarkWholeScreenDirty();
set_close_button_callback(HandleExitGameRequest);
- return NULL;
+ return nullptr;
}
void VideoDriver_Allegro::Stop()
@@ -463,7 +463,7 @@ static uint32 GetTime()
{
struct timeval tim;
- gettimeofday(&tim, NULL);
+ gettimeofday(&tim, nullptr);
return tim.tv_usec / 1000 + tim.tv_sec * 1000;
}
#else
diff --git a/src/video/dedicated_v.cpp b/src/video/dedicated_v.cpp
index 5af900080..8d767ce4d 100644
--- a/src/video/dedicated_v.cpp
+++ b/src/video/dedicated_v.cpp
@@ -87,7 +87,7 @@ static void WINAPI CheckForConsoleInput()
DWORD nb;
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
for (;;) {
- ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, NULL);
+ ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, nullptr);
if (nb >= lengthof(_win_console_thread_buffer)) nb = lengthof(_win_console_thread_buffer) - 1;
_win_console_thread_buffer[nb] = '\0';
@@ -102,12 +102,12 @@ static void CreateWindowsConsoleThread()
{
DWORD dwThreadId;
/* Create event to signal when console input is ready */
- _hInputReady = CreateEvent(NULL, false, false, NULL);
- _hWaitForInputHandling = CreateEvent(NULL, false, false, NULL);
- if (_hInputReady == NULL || _hWaitForInputHandling == NULL) usererror("Cannot create console event!");
+ _hInputReady = CreateEvent(nullptr, false, false, nullptr);
+ _hWaitForInputHandling = CreateEvent(nullptr, false, false, nullptr);
+ if (_hInputReady == nullptr || _hWaitForInputHandling == nullptr) usererror("Cannot create console event!");
- _hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, NULL, 0, &dwThreadId);
- if (_hThread == NULL) usererror("Cannot create console thread!");
+ _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId);
+ if (_hThread == nullptr) usererror("Cannot create console thread!");
DEBUG(driver, 2, "Windows console thread started");
}
@@ -130,7 +130,7 @@ static void *_dedicated_video_mem;
/* Whether a fork has been done. */
bool _dedicated_forks;
-extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
+extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
@@ -138,7 +138,7 @@ static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
const char *VideoDriver_Dedicated::Start(const char * const *parm)
{
int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
- _dedicated_video_mem = (bpp == 0) ? NULL : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
+ _dedicated_video_mem = (bpp == 0) ? nullptr : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
_screen.width = _screen.pitch = _cur_resolution.width;
_screen.height = _cur_resolution.height;
@@ -164,7 +164,7 @@ const char *VideoDriver_Dedicated::Start(const char * const *parm)
#endif
DEBUG(driver, 1, "Loading dedicated server");
- return NULL;
+ return nullptr;
}
void VideoDriver_Dedicated::Stop()
@@ -192,14 +192,14 @@ static bool InputWaiting()
FD_SET(STDIN, &readfds);
/* don't care about writefds and exceptfds: */
- return select(STDIN + 1, &readfds, NULL, NULL, &tv) > 0;
+ return select(STDIN + 1, &readfds, nullptr, nullptr, &tv) > 0;
}
static uint32 GetTime()
{
struct timeval tim;
- gettimeofday(&tim, NULL);
+ gettimeofday(&tim, nullptr);
return tim.tv_usec / 1000 + tim.tv_sec * 1000;
}
@@ -226,7 +226,7 @@ static void DedicatedHandleKeyInput()
if (_exit_game) return;
#if defined(UNIX) || defined(__OS2__)
- if (fgets(input_line, lengthof(input_line), stdin) == NULL) return;
+ if (fgets(input_line, lengthof(input_line), stdin) == nullptr) return;
#else
/* Handle console input, and signal console thread, it can accept input again */
assert_compile(lengthof(_win_console_thread_buffer) <= lengthof(input_line));
diff --git a/src/video/null_v.cpp b/src/video/null_v.cpp
index 5037814e5..4ee2d05ce 100644
--- a/src/video/null_v.cpp
+++ b/src/video/null_v.cpp
@@ -29,13 +29,13 @@ const char *VideoDriver_Null::Start(const char * const *parm)
this->ticks = GetDriverParamInt(parm, "ticks", 1000);
_screen.width = _screen.pitch = _cur_resolution.width;
_screen.height = _cur_resolution.height;
- _screen.dst_ptr = NULL;
+ _screen.dst_ptr = nullptr;
ScreenSizeChanged();
/* Do not render, nor blit */
DEBUG(misc, 1, "Forcing blitter 'null'...");
BlitterFactory::SelectBlitter("null");
- return NULL;
+ return nullptr;
}
void VideoDriver_Null::Stop() { }
diff --git a/src/video/sdl_v.cpp b/src/video/sdl_v.cpp
index 5e3fb4552..2f6184e85 100644
--- a/src/video/sdl_v.cpp
+++ b/src/video/sdl_v.cpp
@@ -39,9 +39,9 @@ static bool _all_modes;
/** Whether the drawing is/may be done in a separate thread. */
static bool _draw_threaded;
/** Mutex to keep the access to the shared memory controlled. */
-static std::recursive_mutex *_draw_mutex = NULL;
+static std::recursive_mutex *_draw_mutex = nullptr;
/** Signal to draw the next frame. */
-static std::condition_variable_any *_draw_signal = NULL;
+static std::condition_variable_any *_draw_signal = nullptr;
/** Should we keep continue drawing? */
static volatile bool _draw_continue;
static Palette _local_palette;
@@ -111,7 +111,7 @@ static void UpdatePalette(bool init = false)
* best mapping of shadow palette colors to real palette
* colors from scratch.
*/
- SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
+ SDL_BlitSurface(_sdl_screen, nullptr, _sdl_realscreen, nullptr);
SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
}
}
@@ -158,7 +158,7 @@ static void DrawSurfaceToScreen()
_num_dirty_rects = 0;
if (n > MAX_DIRTY_RECTS) {
if (_sdl_screen != _sdl_realscreen) {
- SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
+ SDL_BlitSurface(_sdl_screen, nullptr, _sdl_realscreen, nullptr);
}
SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
} else {
@@ -204,10 +204,10 @@ static const Dimension _default_resolutions[] = {
static void GetVideoModes()
{
- SDL_Rect **modes = SDL_ListModes(NULL, SDL_SWSURFACE | SDL_FULLSCREEN);
- if (modes == NULL) usererror("sdl: no modes available");
+ SDL_Rect **modes = SDL_ListModes(nullptr, SDL_SWSURFACE | SDL_FULLSCREEN);
+ if (modes == nullptr) usererror("sdl: no modes available");
- _all_modes = (SDL_ListModes(NULL, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
+ _all_modes = (SDL_ListModes(nullptr, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
if (modes == (void*)-1) {
int n = 0;
for (uint i = 0; i < lengthof(_default_resolutions); i++) {
@@ -278,15 +278,15 @@ bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
char icon_path[MAX_PATH];
- if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
+ if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != nullptr) {
/* Give the application an icon */
icon = SDL_LoadBMP(icon_path);
- if (icon != NULL) {
+ if (icon != nullptr) {
/* Get the colourkey, which will be magenta */
uint32 rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
- SDL_WM_SetIcon(icon, NULL);
+ SDL_WM_SetIcon(icon, nullptr);
SDL_FreeSurface(icon);
}
}
@@ -322,9 +322,9 @@ bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palette");
/* Free any previously allocated shadow surface */
- if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_FreeSurface(_sdl_screen);
+ if (_sdl_screen != nullptr && _sdl_screen != _sdl_realscreen) SDL_FreeSurface(_sdl_screen);
- if (_sdl_realscreen != NULL) {
+ if (_sdl_realscreen != nullptr) {
if (_requested_hwpalette != want_hwpalette) {
/* SDL (at least the X11 driver), reuses the
* same window and palette settings when the bpp
@@ -349,7 +349,7 @@ bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
/* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
newscreen = SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
- if (newscreen == NULL) {
+ if (newscreen == nullptr) {
DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
return false;
}
@@ -376,7 +376,7 @@ bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
*/
DEBUG(driver, 1, "SDL: using shadow surface");
newscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
- if (newscreen == NULL) {
+ if (newscreen == nullptr) {
DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
return false;
}
@@ -637,9 +637,9 @@ const char *VideoDriver_SDL::Start(const char * const *parm)
MarkWholeScreenDirty();
SetupKeyboard();
- _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL;
+ _draw_threaded = GetDriverParam(parm, "no_threads") == nullptr && GetDriverParam(parm, "no_thread") == nullptr;
- return NULL;
+ return nullptr;
}
void VideoDriver_SDL::SetupKeyboard()
@@ -673,7 +673,7 @@ void VideoDriver_SDL::MainLoop()
/* Initialise the mutex first, because that's the thing we *need*
* directly in the newly created thread. */
_draw_mutex = new std::recursive_mutex();
- if (_draw_mutex == NULL) {
+ if (_draw_mutex == nullptr) {
_draw_threaded = false;
} else {
draw_lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
@@ -688,8 +688,8 @@ void VideoDriver_SDL::MainLoop()
draw_lock.release();
delete _draw_mutex;
delete _draw_signal;
- _draw_mutex = NULL;
- _draw_signal = NULL;
+ _draw_mutex = nullptr;
+ _draw_signal = nullptr;
} else {
/* Wait till the draw mutex has started itself. */
_draw_signal->wait(*_draw_mutex);
@@ -757,26 +757,26 @@ void VideoDriver_SDL::MainLoop()
/* The gameloop is the part that can run asynchronously. The rest
* except sleeping can't. */
- if (_draw_mutex != NULL) draw_lock.unlock();
+ if (_draw_mutex != nullptr) draw_lock.unlock();
GameLoop();
- if (_draw_mutex != NULL) draw_lock.lock();
+ if (_draw_mutex != nullptr) draw_lock.lock();
UpdateWindows();
_local_palette = _cur_palette;
} else {
/* Release the thread while sleeping */
- if (_draw_mutex != NULL) draw_lock.unlock();
+ if (_draw_mutex != nullptr) draw_lock.unlock();
CSleep(1);
- if (_draw_mutex != NULL) draw_lock.lock();
+ if (_draw_mutex != nullptr) draw_lock.lock();
NetworkDrawChatMessage();
DrawMouseCursor();
}
/* End of the critical part. */
- if (_draw_mutex != NULL && !HasModalProgress()) {
+ if (_draw_mutex != nullptr && !HasModalProgress()) {
_draw_signal->notify_one();
} else {
/* Oh, we didn't have threads, then just draw unthreaded */
@@ -785,7 +785,7 @@ void VideoDriver_SDL::MainLoop()
}
}
- if (_draw_mutex != NULL) {
+ if (_draw_mutex != nullptr) {
_draw_continue = false;
/* Sending signal if there is no thread blocked
* is very valid and results in noop */
@@ -797,15 +797,15 @@ void VideoDriver_SDL::MainLoop()
delete _draw_mutex;
delete _draw_signal;
- _draw_mutex = NULL;
- _draw_signal = NULL;
+ _draw_mutex = nullptr;
+ _draw_signal = nullptr;
}
}
bool VideoDriver_SDL::ChangeResolution(int w, int h)
{
std::unique_lock<std::recursive_mutex> lock;
- if (_draw_mutex != NULL) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
+ if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
return CreateMainSurface(w, h);
}
@@ -813,7 +813,7 @@ bool VideoDriver_SDL::ChangeResolution(int w, int h)
bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
{
std::unique_lock<std::recursive_mutex> lock;
- if (_draw_mutex != NULL) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
+ if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
_fullscreen = fullscreen;
GetVideoModes(); // get the list of available video modes
@@ -834,12 +834,12 @@ bool VideoDriver_SDL::AfterBlitterChange()
void VideoDriver_SDL::AcquireBlitterLock()
{
- if (_draw_mutex != NULL) _draw_mutex->lock();
+ if (_draw_mutex != nullptr) _draw_mutex->lock();
}
void VideoDriver_SDL::ReleaseBlitterLock()
{
- if (_draw_mutex != NULL) _draw_mutex->unlock();
+ if (_draw_mutex != nullptr) _draw_mutex->unlock();
}
#endif /* WITH_SDL */
diff --git a/src/video/win32_v.cpp b/src/video/win32_v.cpp
index 382c0d8fc..7eea4782a 100644
--- a/src/video/win32_v.cpp
+++ b/src/video/win32_v.cpp
@@ -42,7 +42,7 @@
#endif
typedef BOOL (WINAPI *PFNTRACKMOUSEEVENT)(LPTRACKMOUSEEVENT lpEventTrack);
-static PFNTRACKMOUSEEVENT _pTrackMouseEvent = NULL;
+static PFNTRACKMOUSEEVENT _pTrackMouseEvent = nullptr;
static struct {
HWND main_wnd;
@@ -68,9 +68,9 @@ DWORD _imm_props;
/** Whether the drawing is/may be done in a separate thread. */
static bool _draw_threaded;
/** Mutex to keep the access to the shared memory controlled. */
-static std::recursive_mutex *_draw_mutex = NULL;
+static std::recursive_mutex *_draw_mutex = nullptr;
/** Signal to draw the next frame. */
-static std::condition_variable_any *_draw_signal = NULL;
+static std::condition_variable_any *_draw_signal = nullptr;
/** Should we keep continue drawing? */
static volatile bool _draw_continue;
/** Local copy of the palette for use in the drawing thread. */
@@ -91,7 +91,7 @@ static void MakePalette()
}
_wnd.gdi_palette = CreatePalette(pal);
- if (_wnd.gdi_palette == NULL) usererror("CreatePalette failed!\n");
+ if (_wnd.gdi_palette == nullptr) usererror("CreatePalette failed!\n");
_cur_palette.first_dirty = 0;
_cur_palette.count_dirty = 256;
@@ -309,7 +309,7 @@ bool VideoDriver_Win32::MakeWindow(bool full_screen)
}
} else if (_wnd.fullscreen) {
/* restore display? */
- ChangeDisplaySettings(NULL, 0);
+ ChangeDisplaySettings(nullptr, 0);
/* restore the resolution */
_wnd.width = _bck_resolution.width;
_wnd.height = _bck_resolution.height;
@@ -336,7 +336,7 @@ bool VideoDriver_Win32::MakeWindow(bool full_screen)
w = r.right - r.left;
h = r.bottom - r.top;
- if (_wnd.main_wnd != NULL) {
+ if (_wnd.main_wnd != nullptr) {
if (!_window_maximize) SetWindowPos(_wnd.main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
} else {
int x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
@@ -345,8 +345,8 @@ bool VideoDriver_Win32::MakeWindow(bool full_screen)
char window_title[64];
seprintf(window_title, lastof(window_title), "OpenTTD %s", _openttd_revision);
- _wnd.main_wnd = CreateWindow(_T("OTTD"), MB_TO_WIDE(window_title), style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
- if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
+ _wnd.main_wnd = CreateWindow(_T("OTTD"), MB_TO_WIDE(window_title), style, x, y, w, h, 0, 0, GetModuleHandle(nullptr), 0);
+ if (_wnd.main_wnd == nullptr) usererror("CreateWindow failed");
ShowWindow(_wnd.main_wnd, showstyle);
}
}
@@ -559,14 +559,14 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
if (hIMC != NULL) {
if (lParam & GCS_RESULTSTR) {
/* Read result string from the IME. */
- LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, NULL, 0); // Length is always in bytes, even in UNICODE build.
+ LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
TCHAR *str = (TCHAR *)_alloca(len + sizeof(TCHAR));
len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str, len);
str[len / sizeof(TCHAR)] = '\0';
/* Transmit text to windowing system. */
if (len > 0) {
- HandleTextInput(NULL, true); // Clear marked string.
+ HandleTextInput(nullptr, true); // Clear marked string.
HandleTextInput(FS2OTTD(str));
}
SetCompositionPos(hwnd);
@@ -577,7 +577,7 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
if ((lParam & GCS_COMPSTR) && DrawIMECompositionString()) {
/* Read composition string from the IME. */
- LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR, NULL, 0); // Length is always in bytes, even in UNICODE build.
+ LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
TCHAR *str = (TCHAR *)_alloca(len + sizeof(TCHAR));
len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str, len);
str[len / sizeof(TCHAR)] = '\0';
@@ -587,7 +587,7 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
convert_from_fs(str, utf8_buf, lengthof(utf8_buf));
/* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */
- LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, NULL, 0);
+ LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0);
const char *caret = utf8_buf;
for (const TCHAR *c = str; *c != '\0' && *caret != '\0' && caret_bytes > 0; c++, caret_bytes--) {
/* Skip DBCS lead bytes or leading surrogates. */
@@ -604,7 +604,7 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
HandleTextInput(utf8_buf, true, caret);
} else {
- HandleTextInput(NULL, true);
+ HandleTextInput(nullptr, true);
}
lParam &= ~(GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART);
@@ -622,7 +622,7 @@ static void CancelIMEComposition(HWND hwnd)
if (hIMC != NULL) ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
ImmReleaseContext(hwnd, hIMC);
/* Clear any marked string from the current edit box. */
- HandleTextInput(NULL, true);
+ HandleTextInput(nullptr, true);
}
static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
@@ -647,14 +647,14 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
break;
case WM_PAINT:
- if (!in_sizemove && _draw_mutex != NULL && !HasModalProgress()) {
+ if (!in_sizemove && _draw_mutex != nullptr && !HasModalProgress()) {
/* Get the union of the old update rect and the new update rect. */
RECT r;
GetUpdateRect(hwnd, &r, FALSE);
UnionRect(&_wnd.update_rect, &_wnd.update_rect, &r);
/* Mark the window as updated, otherwise Windows would send more WM_PAINT messages. */
- ValidateRect(hwnd, NULL);
+ ValidateRect(hwnd, nullptr);
_draw_signal->notify_one();
} else {
PAINTSTRUCT ps;
@@ -676,7 +676,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
SelectPalette(hDC, hOldPalette, TRUE);
ReleaseDC(hwnd, hDC);
- if (nChanged != 0) InvalidateRect(hwnd, NULL, FALSE);
+ if (nChanged != 0) InvalidateRect(hwnd, nullptr, FALSE);
return 0;
}
@@ -730,7 +730,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
* tracking the mouse for exiting the window */
if (!_cursor.in_window) {
_cursor.in_window = true;
- if (_pTrackMouseEvent != NULL) {
+ if (_pTrackMouseEvent != nullptr) {
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE;
@@ -783,7 +783,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
case WM_IME_ENDCOMPOSITION:
/* Clear any pending composition string. */
- HandleTextInput(NULL, true);
+ HandleTextInput(nullptr, true);
if (DrawIMECompositionString()) return 0;
break;
@@ -831,7 +831,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
/* Silently drop all messages handled by WM_CHAR. */
MSG msg;
- if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
+ if (PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) {
if ((msg.message == WM_CHAR || msg.message == WM_DEADCHAR) && GB(lParam, 16, 8) == GB(msg.lParam, 16, 8)) {
return 0;
}
@@ -993,7 +993,7 @@ static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lP
} else if (!active && !minimized) {
/* Minimise the window and restore desktop */
ShowWindow(hwnd, SW_MINIMIZE);
- ChangeDisplaySettings(NULL, 0);
+ ChangeDisplaySettings(nullptr, 0);
}
}
break;
@@ -1008,7 +1008,7 @@ static void RegisterWndClass()
static bool registered = false;
if (!registered) {
- HINSTANCE hinst = GetModuleHandle(NULL);
+ HINSTANCE hinst = GetModuleHandle(nullptr);
WNDCLASS wnd = {
CS_OWNDC,
WndProcGdi,
@@ -1016,7 +1016,7 @@ static void RegisterWndClass()
0,
hinst,
LoadIcon(hinst, MAKEINTRESOURCE(100)),
- LoadCursor(NULL, IDC_ARROW),
+ LoadCursor(nullptr, IDC_ARROW),
0,
0,
_T("OTTD")
@@ -1057,8 +1057,8 @@ static bool AllocateDibSection(int w, int h, bool force)
if (_wnd.dib_sect) DeleteObject(_wnd.dib_sect);
dc = GetDC(0);
- _wnd.dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID**)&_wnd.buffer_bits, NULL, 0);
- if (_wnd.dib_sect == NULL) usererror("CreateDIBSection failed");
+ _wnd.dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID**)&_wnd.buffer_bits, nullptr, 0);
+ if (_wnd.dib_sect == nullptr) usererror("CreateDIBSection failed");
ReleaseDC(0, dc);
_screen.width = w;
@@ -1095,7 +1095,7 @@ static void FindResolutions()
/* XXX - EnumDisplaySettingsW crashes with unicows.dll on Windows95
* Doesn't really matter since we don't pass a string anyways, but still
* a letdown */
- for (i = 0; EnumDisplaySettingsA(NULL, i, &dm) != 0; i++) {
+ for (i = 0; EnumDisplaySettingsA(nullptr, i, &dm) != 0; i++) {
if (dm.dmBitsPerPel == bpp &&
dm.dmPelsWidth >= 640 && dm.dmPelsHeight >= 480) {
uint j;
@@ -1149,9 +1149,9 @@ const char *VideoDriver_Win32::Start(const char * const *parm)
MarkWholeScreenDirty();
- _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL && std::thread::hardware_concurrency() > 1;
+ _draw_threaded = GetDriverParam(parm, "no_threads") == nullptr && GetDriverParam(parm, "no_thread") == nullptr && std::thread::hardware_concurrency() > 1;
- return NULL;
+ return nullptr;
}
void VideoDriver_Win32::Stop()
@@ -1160,7 +1160,7 @@ void VideoDriver_Win32::Stop()
DeleteObject(_wnd.dib_sect);
DestroyWindow(_wnd.main_wnd);
- if (_wnd.fullscreen) ChangeDisplaySettings(NULL, 0);
+ if (_wnd.fullscreen) ChangeDisplaySettings(nullptr, 0);
MyShowCursor(true);
}
@@ -1176,7 +1176,7 @@ static void CheckPaletteAnim()
if (_cur_palette.count_dirty == 0) return;
_local_palette = _cur_palette;
- InvalidateRect(_wnd.main_wnd, NULL, FALSE);
+ InvalidateRect(_wnd.main_wnd, nullptr, FALSE);
}
void VideoDriver_Win32::MainLoop()
@@ -1211,8 +1211,8 @@ void VideoDriver_Win32::MainLoop()
draw_lock.release();
delete _draw_mutex;
delete _draw_signal;
- _draw_mutex = NULL;
- _draw_signal = NULL;
+ _draw_mutex = nullptr;
+ _draw_signal = nullptr;
} else {
DEBUG(driver, 1, "Threaded drawing enabled");
/* Wait till the draw thread has started itself. */
@@ -1227,7 +1227,7 @@ void VideoDriver_Win32::MainLoop()
for (;;) {
uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
- while (PeekMessage(&mesg, NULL, 0, 0, PM_REMOVE)) {
+ while (PeekMessage(&mesg, nullptr, 0, 0, PM_REMOVE)) {
InteractiveRandom(); // randomness
/* Convert key messages to char messages if we want text input. */
if (EditBoxInGlobalFocus()) TranslateMessage(&mesg);
@@ -1310,14 +1310,14 @@ void VideoDriver_Win32::MainLoop()
delete _draw_mutex;
delete _draw_signal;
- _draw_mutex = NULL;
+ _draw_mutex = nullptr;
}
}
bool VideoDriver_Win32::ChangeResolution(int w, int h)
{
std::unique_lock<std::recursive_mutex> lock;
- if (_draw_mutex != NULL) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
+ if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
if (_window_maximize) ShowWindow(_wnd.main_wnd, SW_SHOWNORMAL);
@@ -1330,7 +1330,7 @@ bool VideoDriver_Win32::ChangeResolution(int w, int h)
bool VideoDriver_Win32::ToggleFullscreen(bool full_screen)
{
std::unique_lock<std::recursive_mutex> lock;
- if (_draw_mutex != NULL) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
+ if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
return this->MakeWindow(full_screen);
}
@@ -1342,18 +1342,18 @@ bool VideoDriver_Win32::AfterBlitterChange()
void VideoDriver_Win32::AcquireBlitterLock()
{
- if (_draw_mutex != NULL) _draw_mutex->lock();
+ if (_draw_mutex != nullptr) _draw_mutex->lock();
}
void VideoDriver_Win32::ReleaseBlitterLock()
{
- if (_draw_mutex != NULL) _draw_mutex->unlock();
+ if (_draw_mutex != nullptr) _draw_mutex->unlock();
}
void VideoDriver_Win32::EditBoxLostFocus()
{
std::unique_lock<std::recursive_mutex> lock;
- if (_draw_mutex != NULL) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
+ if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
CancelIMEComposition(_wnd.main_wnd);
SetCompositionPos(_wnd.main_wnd);
diff --git a/src/viewport.cpp b/src/viewport.cpp
index 9bbe6a462..804aa1cc6 100644
--- a/src/viewport.cpp
+++ b/src/viewport.cpp
@@ -187,7 +187,7 @@ static TileInfo *_cur_ti;
bool _draw_bounding_boxes = false;
bool _draw_dirty_blocks = false;
uint _dirty_block_colour = 0;
-static VpSpriteSorter _vp_sprite_sorter = NULL;
+static VpSpriteSorter _vp_sprite_sorter = nullptr;
static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
{
@@ -199,11 +199,11 @@ static Point MapXYZToViewport(const ViewPort *vp, int x, int y, int z)
void DeleteWindowViewport(Window *w)
{
- if (w->viewport == NULL) return;
+ if (w->viewport == nullptr) return;
delete w->viewport->overlay;
free(w->viewport);
- w->viewport = NULL;
+ w->viewport = nullptr;
}
/**
@@ -221,7 +221,7 @@ void DeleteWindowViewport(Window *w)
void InitializeWindowViewport(Window *w, int x, int y,
int width, int height, uint32 follow_flags, ZoomLevel zoom)
{
- assert(w->viewport == NULL);
+ assert(w->viewport == nullptr);
ViewportData *vp = CallocT<ViewportData>(1);
@@ -256,7 +256,7 @@ void InitializeWindowViewport(Window *w, int x, int y,
vp->dest_scrollpos_x = pt.x;
vp->dest_scrollpos_y = pt.y;
- vp->overlay = NULL;
+ vp->overlay = nullptr;
w->viewport = vp;
vp->virtual_left = 0; // pt.x;
@@ -389,18 +389,18 @@ static void SetViewportPosition(Window *w, int x, int y)
* @param x X coordinate of the xy position
* @param y Y coordinate of the xy position
* @return Pointer to the viewport if the xy position is in the viewport of the window,
- * otherwise \c NULL is returned.
+ * otherwise \c nullptr is returned.
*/
ViewPort *IsPtInWindowViewport(const Window *w, int x, int y)
{
ViewPort *vp = w->viewport;
- if (vp != NULL &&
+ if (vp != nullptr &&
IsInsideMM(x, vp->left, vp->left + vp->width) &&
IsInsideMM(y, vp->top, vp->top + vp->height))
return vp;
- return NULL;
+ return nullptr;
}
/**
@@ -436,8 +436,8 @@ static Point GetTileFromScreenXY(int x, int y, int zoom_x, int zoom_y)
ViewPort *vp;
Point pt;
- if ( (w = FindWindowFromPt(x, y)) != NULL &&
- (vp = IsPtInWindowViewport(w, x, y)) != NULL)
+ if ( (w = FindWindowFromPt(x, y)) != nullptr &&
+ (vp = IsPtInWindowViewport(w, x, y)) != nullptr)
return TranslateXYToTileCoord(vp, zoom_x, zoom_y);
pt.y = pt.x = -1;
@@ -495,7 +495,7 @@ void HandleZoomMessage(Window *w, const ViewPort *vp, byte widget_zoom_in, byte
* @param extra_offs_x Pixel X offset for the sprite position.
* @param extra_offs_y Pixel Y offset for the sprite position.
*/
-static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0)
+static void AddTileSpriteToDraw(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = nullptr, int extra_offs_x = 0, int extra_offs_y = 0)
{
assert((image & SPRITE_MASK) < MAX_SPRITES);
@@ -598,8 +598,8 @@ void OffsetGroundSprite(int x, int y)
default: NOT_REACHED();
}
- /* _vd.last_child == NULL if foundation sprite was clipped by the viewport bounds */
- if (_vd.last_child != NULL) _vd.foundation[_vd.foundation_part] = (uint)_vd.parent_sprites_to_draw.size() - 1;
+ /* _vd.last_child == nullptr if foundation sprite was clipped by the viewport bounds */
+ if (_vd.last_child != nullptr) _vd.foundation[_vd.foundation_part] = (uint)_vd.parent_sprites_to_draw.size() - 1;
_vd.foundation_offset[_vd.foundation_part].x = x * ZOOM_LVL_BASE;
_vd.foundation_offset[_vd.foundation_part].y = y * ZOOM_LVL_BASE;
@@ -674,7 +674,7 @@ void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w,
return;
}
- _vd.last_child = NULL;
+ _vd.last_child = nullptr;
Point pt = RemapCoords(x, y, z);
int tmp_left, tmp_top, tmp_x = pt.x, tmp_y = pt.y;
@@ -818,7 +818,7 @@ void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool tran
assert((image & SPRITE_MASK) < MAX_SPRITES);
/* If the ParentSprite was clipped by the viewport bounds, do not draw the ChildSprites either */
- if (_vd.last_child == NULL) return;
+ if (_vd.last_child == nullptr) return;
/* make the sprites transparent with the right palette */
if (transparent) {
@@ -879,7 +879,7 @@ static void DrawSelectionSprite(SpriteID image, PaletteID pal, const TileInfo *t
AddTileSpriteToDraw(image, pal, ti->x, ti->y, ti->z + z_offset);
} else {
/* draw on top of foundation */
- AddChildSpriteToFoundation(image, pal, NULL, foundation_part, 0, -z_offset * ZOOM_LVL_BASE);
+ AddChildSpriteToFoundation(image, pal, nullptr, foundation_part, 0, -z_offset * ZOOM_LVL_BASE);
}
}
@@ -1171,8 +1171,8 @@ static void ViewportAddLandscape()
_vd.foundation_part = FOUNDATION_PART_NONE;
_vd.foundation[0] = -1;
_vd.foundation[1] = -1;
- _vd.last_foundation_child[0] = NULL;
- _vd.last_foundation_child[1] = NULL;
+ _vd.last_foundation_child[0] = nullptr;
+ _vd.last_foundation_child[1] = nullptr;
_tile_type_procs[tile_type]->draw_tile_proc(&tile_info);
if (tile_info.tile != INVALID_TILE) DrawTileSelection(&tile_info);
@@ -1383,7 +1383,7 @@ void ViewportSign::MarkDirty(ZoomLevel maxzoom) const
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
ViewPort *vp = w->viewport;
- if (vp != NULL && vp->zoom <= maxzoom) {
+ if (vp != nullptr && vp->zoom <= maxzoom) {
assert(vp->width != 0);
Rect &zl = zoomlevels[vp->zoom];
MarkViewportDirty(vp, zl.left, zl.top, zl.right, zl.bottom);
@@ -1568,7 +1568,7 @@ void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom
_vd.dpi.left = left & mask;
_vd.dpi.top = top & mask;
_vd.dpi.pitch = old_dpi->pitch;
- _vd.last_child = NULL;
+ _vd.last_child = nullptr;
int x = UnScaleByZoom(_vd.dpi.left - (vp->virtual_left & mask), vp->zoom) + vp->left;
int y = UnScaleByZoom(_vd.dpi.top - (vp->virtual_top & mask), vp->zoom) + vp->top;
@@ -1601,7 +1601,7 @@ void ViewportDoDraw(const ViewPort *vp, int left, int top, int right, int bottom
dp.height = UnScaleByZoom(dp.height, zoom);
_cur_dpi = &dp;
- if (vp->overlay != NULL && vp->overlay->GetCargoMask() != 0 && vp->overlay->GetCompanyMask() != 0) {
+ if (vp->overlay != nullptr && vp->overlay->GetCargoMask() != 0 && vp->overlay->GetCompanyMask() != 0) {
/* translate to window coordinates */
dp.left = x;
dp.top = y;
@@ -1809,7 +1809,7 @@ void MarkAllViewportsDirty(int left, int top, int right, int bottom)
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
ViewPort *vp = w->viewport;
- if (vp != NULL) {
+ if (vp != nullptr) {
assert(vp->width != 0);
MarkViewportDirty(vp, left, top, right, bottom);
}
@@ -1820,7 +1820,7 @@ void ConstrainAllViewportsZoom()
{
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
- if (w->viewport == NULL) continue;
+ if (w->viewport == nullptr) continue;
ZoomLevel zoom = static_cast<ZoomLevel>(Clamp(w->viewport->zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max));
if (zoom != w->viewport->zoom) {
@@ -2012,9 +2012,9 @@ static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y)
bool show_competitors = HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS);
/* Topmost of each type that was hit */
- BaseStation *st = NULL, *last_st = NULL;
- Town *t = NULL, *last_t = NULL;
- Sign *si = NULL, *last_si = NULL;
+ BaseStation *st = nullptr, *last_st = nullptr;
+ Town *t = nullptr, *last_t = nullptr;
+ Sign *si = nullptr, *last_si = nullptr;
/* See ViewportAddKdtreeSigns() for details on the search logic */
_viewport_sign_kdtree.FindContained(search_rect.left, search_rect.top, search_rect.right, search_rect.bottom, [&](const ViewportSignKdtreeItem & item) {
@@ -2052,17 +2052,17 @@ static bool CheckClickOnViewportSign(const ViewPort *vp, int x, int y)
});
/* Select which hit to handle based on priority */
- if (last_st != NULL) {
+ if (last_st != nullptr) {
if (Station::IsExpected(last_st)) {
ShowStationViewWindow(last_st->index);
} else {
ShowWaypointWindow(Waypoint::From(last_st));
}
return true;
- } else if (last_t != NULL) {
+ } else if (last_t != nullptr) {
ShowTownViewWindow(last_t->index);
return true;
- } else if (last_si != NULL) {
+ } else if (last_si != nullptr) {
HandleClickOnSign(last_si);
return true;
} else {
@@ -2209,7 +2209,7 @@ static void PlaceObject()
_tile_fract_coords.y = pt.y & TILE_UNIT_MASK;
w = _thd.GetCallbackWnd();
- if (w != NULL) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
+ if (w != nullptr) w->OnPlaceObject(pt, TileVirtXY(pt.x, pt.y));
}
@@ -2218,7 +2218,7 @@ bool HandleViewportClicked(const ViewPort *vp, int x, int y)
const Vehicle *v = CheckClickOnVehicle(vp, x, y);
if (_thd.place_mode & HT_VEHICLE) {
- if (v != NULL && VehicleClicked(v)) return true;
+ if (v != nullptr && VehicleClicked(v)) return true;
}
/* Vehicle placement mode already handled above. */
@@ -2230,7 +2230,7 @@ bool HandleViewportClicked(const ViewPort *vp, int x, int y)
if (CheckClickOnViewportSign(vp, x, y)) return true;
bool result = CheckClickOnLandscape(vp, x, y);
- if (v != NULL) {
+ if (v != nullptr) {
DEBUG(misc, 2, "Vehicle %d (index %d) at %p", v->unitnumber, v->index, v);
if (IsCompanyBuildableVehicleType(v)) {
v = v->First();
@@ -2247,7 +2247,7 @@ bool HandleViewportClicked(const ViewPort *vp, int x, int y)
void RebuildViewportOverlay(Window *w)
{
- if (w->viewport->overlay != NULL &&
+ if (w->viewport->overlay != nullptr &&
w->viewport->overlay->GetCompanyMask() != 0 &&
w->viewport->overlay->GetCargoMask() != 0) {
w->viewport->overlay->SetDirty();
@@ -2381,7 +2381,7 @@ bool TileHighlightData::IsDraggingDiagonal()
/**
* Get the window that started the current highlighting.
- * @return The window that requested the current tile highlighting, or \c NULL if not available.
+ * @return The window that requested the current tile highlighting, or \c nullptr if not available.
*/
Window *TileHighlightData::GetCallbackWnd()
{
@@ -3163,7 +3163,7 @@ EventState VpHandlePlaceSizingDrag()
/* stop drag mode if the window has been closed */
Window *w = _thd.GetCallbackWnd();
- if (w == NULL) {
+ if (w == nullptr) {
ResetObjectToPlace();
return ES_HANDLED;
}
@@ -3228,7 +3228,7 @@ void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowC
* this function might in some cases reset the newly set object to
* place or not properly reset the original selection. */
_thd.window_class = WC_INVALID;
- if (w != NULL) {
+ if (w != nullptr) {
w->OnPlaceObjectAbort();
HideMeasurementTooltips();
}
@@ -3305,7 +3305,7 @@ void InitializeSpriteSorter()
break;
}
}
- assert(_vp_sprite_sorter != NULL);
+ assert(_vp_sprite_sorter != nullptr);
}
/**
diff --git a/src/viewport_func.h b/src/viewport_func.h
index 319d4efd6..49ad4b2e8 100644
--- a/src/viewport_func.h
+++ b/src/viewport_func.h
@@ -49,10 +49,10 @@ static inline void MaxZoomInOut(ZoomStateChange how, Window *w)
void OffsetGroundSprite(int x, int y);
-void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0);
-void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = NULL, int extra_offs_x = 0, int extra_offs_y = 0);
-void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent = false, int bb_offset_x = 0, int bb_offset_y = 0, int bb_offset_z = 0, const SubSprite *sub = NULL);
-void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent = false, const SubSprite *sub = NULL, bool scale = true);
+void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub = nullptr, int extra_offs_x = 0, int extra_offs_y = 0);
+void DrawGroundSpriteAt(SpriteID image, PaletteID pal, int32 x, int32 y, int z, const SubSprite *sub = nullptr, int extra_offs_x = 0, int extra_offs_y = 0);
+void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent = false, int bb_offset_x = 0, int bb_offset_y = 0, int bb_offset_z = 0, const SubSprite *sub = nullptr);
+void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent = false, const SubSprite *sub = nullptr, bool scale = true);
void ViewportAddString(const DrawPixelInfo *dpi, ZoomLevel small_from, const ViewportSign *sign, StringID string_normal, StringID string_small, StringID string_small_shadow, uint64 params_1, uint64 params_2 = 0, Colours colour = INVALID_COLOUR);
diff --git a/src/viewport_gui.cpp b/src/viewport_gui.cpp
index 936990ac5..85b278b2a 100644
--- a/src/viewport_gui.cpp
+++ b/src/viewport_gui.cpp
@@ -122,7 +122,7 @@ public:
void OnResize() override
{
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_EV_VIEWPORT);
nvp->UpdateViewportCoordinates(this);
}
@@ -172,7 +172,7 @@ void ShowExtraViewPortWindow(TileIndex tile)
int i = 0;
/* find next free window number for extra viewport */
- while (FindWindowById(WC_EXTRA_VIEW_PORT, i) != NULL) i++;
+ while (FindWindowById(WC_EXTRA_VIEW_PORT, i) != nullptr) i++;
new ExtraViewportWindow(&_extra_view_port_desc, i, tile);
}
diff --git a/src/void_cmd.cpp b/src/void_cmd.cpp
index a2a45e722..9a0134f59 100644
--- a/src/void_cmd.cpp
+++ b/src/void_cmd.cpp
@@ -77,15 +77,15 @@ extern const TileTypeProcs _tile_type_void_procs = {
DrawTile_Void, // draw_tile_proc
GetSlopePixelZ_Void, // get_slope_z_proc
ClearTile_Void, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_Void, // get_tile_desc_proc
GetTileTrackStatus_Void, // get_tile_track_status_proc
- NULL, // click_tile_proc
- NULL, // animate_tile_proc
+ nullptr, // click_tile_proc
+ nullptr, // animate_tile_proc
TileLoop_Void, // tile_loop_proc
ChangeTileOwner_Void, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
- NULL, // vehicle_enter_tile_proc
+ nullptr, // add_produced_cargo_proc
+ nullptr, // vehicle_enter_tile_proc
GetFoundation_Void, // get_foundation_proc
TerraformTile_Void, // terraform_tile_proc
};
diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp
index 03b321e68..e3247ec66 100644
--- a/src/water_cmd.cpp
+++ b/src/water_cmd.cpp
@@ -168,7 +168,7 @@ void MakeWaterKeepingClass(TileIndex tile, Owner o)
if (wc == WATER_CLASS_CANAL) {
/* If we clear the canal, we have to remove it from the infrastructure count as well. */
Company *c = Company::GetIfValid(o);
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.water--;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -185,7 +185,7 @@ void MakeWaterKeepingClass(TileIndex tile, Owner o)
if (wc == WATER_CLASS_SEA && z > 0) {
/* Update company infrastructure count. */
Company *c = Company::GetIfValid(o);
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.water++;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -227,7 +227,7 @@ static CommandCost RemoveShipDepot(TileIndex tile, DoCommandFlag flags)
delete Depot::GetByTile(tile);
Company *c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.water -= 2 * LOCK_DEPOT_TILE_FACTOR;
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -293,7 +293,7 @@ static CommandCost DoBuildLock(TileIndex tile, DiagDirection dir, DoCommandFlag
if (flags & DC_EXEC) {
/* Update company infrastructure counts. */
Company *c = Company::GetIfValid(_current_company);
- if (c != NULL) {
+ if (c != nullptr) {
/* Counts for the water. */
if (!IsWaterTile(tile - delta)) c->infrastructure.water++;
if (!IsWaterTile(tile + delta)) c->infrastructure.water++;
@@ -338,7 +338,7 @@ static CommandCost RemoveLock(TileIndex tile, DoCommandFlag flags)
if (flags & DC_EXEC) {
/* Remove middle part from company infrastructure count. */
Company *c = Company::GetIfValid(GetTileOwner(tile));
- if (c != NULL) {
+ if (c != nullptr) {
c->infrastructure.water -= 3 * LOCK_DEPOT_TILE_FACTOR; // three parts of the lock.
DirtyCompanyInfrastructureWindows(c->index);
}
@@ -428,7 +428,7 @@ CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
MakeRiver(tile, Random());
if (_game_mode == GM_EDITOR) {
TileIndex tile2 = tile;
- CircularTileSearch(&tile2, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, NULL);
+ CircularTileSearch(&tile2, RIVER_OFFSET_DESERT_DISTANCE, RiverModifyDesertZone, nullptr);
}
break;
@@ -931,11 +931,11 @@ static void FloodVehicle(Vehicle *v)
* Flood a vehicle if we are allowed to flood it, i.e. when it is on the ground.
* @param v The vehicle to test for flooding.
* @param data The z of level to flood.
- * @return NULL as we always want to remove everything.
+ * @return nullptr as we always want to remove everything.
*/
static Vehicle *FloodVehicleProc(Vehicle *v, void *data)
{
- if ((v->vehstatus & VS_CRASHED) != 0) return NULL;
+ if ((v->vehstatus & VS_CRASHED) != 0) return nullptr;
switch (v->type) {
default: break;
@@ -963,7 +963,7 @@ static Vehicle *FloodVehicleProc(Vehicle *v, void *data)
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -1321,14 +1321,14 @@ extern const TileTypeProcs _tile_type_water_procs = {
DrawTile_Water, // draw_tile_proc
GetSlopePixelZ_Water, // get_slope_z_proc
ClearTile_Water, // clear_tile_proc
- NULL, // add_accepted_cargo_proc
+ nullptr, // add_accepted_cargo_proc
GetTileDesc_Water, // get_tile_desc_proc
GetTileTrackStatus_Water, // get_tile_track_status_proc
ClickTile_Water, // click_tile_proc
- NULL, // animate_tile_proc
+ nullptr, // animate_tile_proc
TileLoop_Water, // tile_loop_proc
ChangeTileOwner_Water, // change_tile_owner_proc
- NULL, // add_produced_cargo_proc
+ nullptr, // add_produced_cargo_proc
VehicleEnter_Water, // vehicle_enter_tile_proc
GetFoundation_Water, // get_foundation_proc
TerraformTile_Water, // terraform_tile_proc
diff --git a/src/waypoint_cmd.cpp b/src/waypoint_cmd.cpp
index 0fd5942c0..4c677a88a 100644
--- a/src/waypoint_cmd.cpp
+++ b/src/waypoint_cmd.cpp
@@ -56,7 +56,7 @@ void Waypoint::UpdateVirtCoord()
*/
static Waypoint *FindDeletedWaypointCloseTo(TileIndex tile, StringID str, CompanyID cid)
{
- Waypoint *wp, *best = NULL;
+ Waypoint *wp, *best = nullptr;
uint thres = 8;
FOR_ALL_WAYPOINTS(wp) {
@@ -108,7 +108,7 @@ static CommandCost IsValidTileForWaypoint(TileIndex tile, Axis axis, StationID *
/* if waypoint is set, then we have special handling to allow building on top of already existing waypoints.
* so waypoint points to INVALID_STATION if we can build on any waypoint.
* Or it points to a waypoint if we're only allowed to build on exactly that waypoint. */
- if (waypoint != NULL && IsTileType(tile, MP_STATION)) {
+ if (waypoint != nullptr && IsTileType(tile, MP_STATION)) {
if (!IsRailWaypoint(tile)) {
return ClearTile_Station(tile, DC_AUTO); // get error message
} else {
@@ -199,16 +199,16 @@ CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint
if (ret.Failed()) return ret;
}
- Waypoint *wp = NULL;
+ Waypoint *wp = nullptr;
TileArea new_location(TileArea(start_tile, width, height));
CommandCost ret = FindJoiningWaypoint(est, station_to_join, adjacent, new_location, &wp);
if (ret.Failed()) return ret;
/* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
TileIndex center_tile = start_tile + (count / 2) * offset;
- if (wp == NULL && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT, _current_company);
+ if (wp == nullptr && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT, _current_company);
- if (wp != NULL) {
+ if (wp != nullptr) {
/* Reuse an existing waypoint. */
if (wp->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_WAYPOINT);
@@ -227,7 +227,7 @@ CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint
if (flags & DC_EXEC) {
bool need_sign_update = false;
- if (wp == NULL) {
+ if (wp == nullptr) {
wp = new Waypoint(start_tile);
need_sign_update = true;
} else if (!wp->IsInUse()) {
@@ -246,14 +246,14 @@ CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint
wp->string_id = STR_SV_STNAME_WAYPOINT;
wp->train_station = new_location;
- if (wp->town == NULL) MakeDefaultName(wp);
+ if (wp->town == nullptr) MakeDefaultName(wp);
wp->UpdateVirtCoord();
if (need_sign_update) _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeWaypoint(wp->index));
const StationSpec *spec = StationClass::Get(spec_class)->GetSpec(spec_index);
byte *layout_ptr = AllocaM(byte, count);
- if (spec == NULL) {
+ if (spec == nullptr) {
/* The layout must be 0 for the 'normal' waypoints by design. */
memset(layout_ptr, 0, count);
} else {
@@ -302,7 +302,7 @@ CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
/* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
Waypoint *wp = FindDeletedWaypointCloseTo(tile, STR_SV_STNAME_BUOY, OWNER_NONE);
- if (wp == NULL && !Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
+ if (wp == nullptr && !Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_WAYPOINT_BUOY]);
if (!IsWaterTile(tile)) {
@@ -312,7 +312,7 @@ CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
}
if (flags & DC_EXEC) {
- if (wp == NULL) {
+ if (wp == nullptr) {
wp = new Waypoint(tile);
} else {
/* Move existing (recently deleted) buoy to the new location */
@@ -329,7 +329,7 @@ CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32
wp->build_date = _date;
- if (wp->town == NULL) MakeDefaultName(wp);
+ if (wp->town == nullptr) MakeDefaultName(wp);
MakeBuoy(tile, wp->index, GetWaterClass(tile));
MarkTileDirtyByTile(tile);
@@ -392,7 +392,7 @@ static bool IsUniqueWaypointName(const char *name)
const Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
- if (wp->name != NULL && strcmp(wp->name, name) == 0) return false;
+ if (wp->name != nullptr && strcmp(wp->name, name) == 0) return false;
}
return true;
@@ -410,7 +410,7 @@ static bool IsUniqueWaypointName(const char *name)
CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Waypoint *wp = Waypoint::GetIfValid(p1);
- if (wp == NULL) return CMD_ERROR;
+ if (wp == nullptr) return CMD_ERROR;
if (wp->owner != OWNER_NONE) {
CommandCost ret = CheckOwnership(wp->owner);
@@ -426,7 +426,7 @@ CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, ui
if (flags & DC_EXEC) {
free(wp->name);
- wp->name = reset ? NULL : stredup(text);
+ wp->name = reset ? nullptr : stredup(text);
wp->UpdateVirtCoord();
}
diff --git a/src/waypoint_gui.cpp b/src/waypoint_gui.cpp
index 5dd57c080..54578a4bb 100644
--- a/src/waypoint_gui.cpp
+++ b/src/waypoint_gui.cpp
@@ -126,7 +126,7 @@ public:
void OnResize() override
{
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_W_VIEWPORT);
nvp->UpdateViewportCoordinates(this);
this->wp->UpdateVirtCoord();
@@ -137,9 +137,9 @@ public:
void OnQueryTextFinished(char *str) override
{
- if (str == NULL) return;
+ if (str == nullptr) return;
- DoCommandP(0, this->window_number, 0, CMD_RENAME_WAYPOINT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_WAYPOINT_NAME), NULL, str);
+ DoCommandP(0, this->window_number, 0, CMD_RENAME_WAYPOINT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_WAYPOINT_NAME), nullptr, str);
}
};
diff --git a/src/widget.cpp b/src/widget.cpp
index 5ec539a49..dcdf75c17 100644
--- a/src/widget.cpp
+++ b/src/widget.cpp
@@ -147,7 +147,7 @@ void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y)
ma = nw->pos_y + nw->current_y;
}
NWidgetScrollbar *scrollbar = dynamic_cast<NWidgetScrollbar*>(nw);
- assert(scrollbar != NULL);
+ assert(scrollbar != nullptr);
ScrollbarClickPositioning(w, scrollbar, x, y, mi, ma);
}
@@ -162,7 +162,7 @@ void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y)
int GetWidgetFromPos(const Window *w, int x, int y)
{
NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
- return (nw != NULL) ? nw->index : -1;
+ return (nw != nullptr) ? nw->index : -1;
}
/**
@@ -613,7 +613,7 @@ void Window::DrawWidgets() const
extern bool _window_highlight_colour;
for (uint i = 0; i < this->nested_array_size; i++) {
const NWidgetBase *widget = this->GetWidget<NWidgetBase>(i);
- if (widget == NULL || !widget->IsHighlighted()) continue;
+ if (widget == nullptr || !widget->IsHighlighted()) continue;
int left = widget->pos_x;
int top = widget->pos_y;
@@ -639,7 +639,7 @@ void Window::DrawSortButtonState(int widget, SortButtonState state) const
{
if (state == SBS_OFF) return;
- assert(this->nested_array != NULL);
+ assert(this->nested_array != nullptr);
const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget);
/* Sort button uses the same sprites as vertical scrollbar */
@@ -784,17 +784,17 @@ void NWidgetBase::SetDirty(const Window *w) const
* Retrieve a widget by its position.
* @param x Horizontal position relative to the left edge of the window.
* @param y Vertical position relative to the top edge of the window.
- * @return Returns the deepest nested widget that covers the given position, or \c NULL if no widget can be found.
+ * @return Returns the deepest nested widget that covers the given position, or \c nullptr if no widget can be found.
*/
/**
* Retrieve a widget by its type.
* @param tp Widget type to search for.
- * @return Returns the first widget of the specified type, or \c NULL if no widget can be found.
+ * @return Returns the first widget of the specified type, or \c nullptr if no widget can be found.
*/
NWidgetBase *NWidgetBase::GetWidgetOfType(WidgetType tp)
{
- return (this->type == tp) ? this : NULL;
+ return (this->type == tp) ? this : nullptr;
}
/**
@@ -904,7 +904,7 @@ void NWidgetCore::FillNestedArray(NWidgetBase **array, uint length)
NWidgetCore *NWidgetCore::GetWidgetFromPos(int x, int y)
{
- return (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) ? this : NULL;
+ return (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) ? this : nullptr;
}
/**
@@ -913,28 +913,28 @@ NWidgetCore *NWidgetCore::GetWidgetFromPos(int x, int y)
*/
NWidgetContainer::NWidgetContainer(WidgetType tp) : NWidgetBase(tp)
{
- this->head = NULL;
- this->tail = NULL;
+ this->head = nullptr;
+ this->tail = nullptr;
}
NWidgetContainer::~NWidgetContainer()
{
- while (this->head != NULL) {
+ while (this->head != nullptr) {
NWidgetBase *wid = this->head->next;
delete this->head;
this->head = wid;
}
- this->tail = NULL;
+ this->tail = nullptr;
}
NWidgetBase *NWidgetContainer::GetWidgetOfType(WidgetType tp)
{
if (this->type == tp) return this;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
NWidgetBase *nwid = child_wid->GetWidgetOfType(tp);
- if (nwid != NULL) return nwid;
+ if (nwid != nullptr) return nwid;
}
- return NULL;
+ return nullptr;
}
/**
@@ -943,14 +943,14 @@ NWidgetBase *NWidgetContainer::GetWidgetOfType(WidgetType tp)
*/
void NWidgetContainer::Add(NWidgetBase *wid)
{
- assert(wid->next == NULL && wid->prev == NULL);
+ assert(wid->next == nullptr && wid->prev == nullptr);
- if (this->head == NULL) {
+ if (this->head == nullptr) {
this->head = wid;
this->tail = wid;
} else {
- assert(this->tail != NULL);
- assert(this->tail->next == NULL);
+ assert(this->tail != nullptr);
+ assert(this->tail->next == nullptr);
this->tail->next = wid;
wid->prev = this->tail;
@@ -960,7 +960,7 @@ void NWidgetContainer::Add(NWidgetBase *wid)
void NWidgetContainer::FillNestedArray(NWidgetBase **array, uint length)
{
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->FillNestedArray(array, length);
}
}
@@ -1006,11 +1006,11 @@ void NWidgetStacked::SetupSmallestSize(Window *w, bool init_array)
/* First sweep, recurse down and compute minimal size and filling. */
this->smallest_x = 0;
this->smallest_y = 0;
- this->fill_x = (this->head != NULL) ? 1 : 0;
- this->fill_y = (this->head != NULL) ? 1 : 0;
- this->resize_x = (this->head != NULL) ? 1 : 0;
- this->resize_y = (this->head != NULL) ? 1 : 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ this->fill_x = (this->head != nullptr) ? 1 : 0;
+ this->fill_y = (this->head != nullptr) ? 1 : 0;
+ this->resize_x = (this->head != nullptr) ? 1 : 0;
+ this->resize_y = (this->head != nullptr) ? 1 : 0;
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->SetupSmallestSize(w, init_array);
this->smallest_x = max(this->smallest_x, child_wid->smallest_x + child_wid->padding_left + child_wid->padding_right);
@@ -1029,7 +1029,7 @@ void NWidgetStacked::AssignSizePosition(SizingType sizing, uint x, uint y, uint
if (this->shown_plane >= SZSP_BEGIN) return;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint hor_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetHorizontalStepSize(sizing);
uint child_width = ComputeMaxSize(child_wid->smallest_x, given_width - child_wid->padding_left - child_wid->padding_right, hor_step);
uint child_pos_x = (rtl ? child_wid->padding_right : child_wid->padding_left);
@@ -1053,7 +1053,7 @@ void NWidgetStacked::Draw(const Window *w)
if (this->shown_plane >= SZSP_BEGIN) return;
int plane = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; plane++, child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; plane++, child_wid = child_wid->next) {
if (plane == this->shown_plane) {
child_wid->Draw(w);
return;
@@ -1065,16 +1065,16 @@ void NWidgetStacked::Draw(const Window *w)
NWidgetCore *NWidgetStacked::GetWidgetFromPos(int x, int y)
{
- if (this->shown_plane >= SZSP_BEGIN) return NULL;
+ if (this->shown_plane >= SZSP_BEGIN) return nullptr;
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
int plane = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; plane++, child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; plane++, child_wid = child_wid->next) {
if (plane == this->shown_plane) {
return child_wid->GetWidgetFromPos(x, y);
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -1109,20 +1109,20 @@ void NWidgetPIPContainer::SetPIP(uint8 pip_pre, uint8 pip_inter, uint8 pip_post)
void NWidgetPIPContainer::Draw(const Window *w)
{
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->Draw(w);
}
}
NWidgetCore *NWidgetPIPContainer::GetWidgetFromPos(int x, int y)
{
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
- if (nwid != NULL) return nwid;
+ if (nwid != nullptr) return nwid;
}
- return NULL;
+ return nullptr;
}
/** Horizontal container widget. */
@@ -1142,7 +1142,7 @@ void NWidgetHorizontal::SetupSmallestSize(Window *w, bool init_array)
/* 1a. Forward call, collect biggest nested array index, and longest/widest child length. */
uint longest = 0; // Longest child found.
uint max_vert_fill = 0; // Biggest vertical fill step.
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->SetupSmallestSize(w, init_array);
longest = max(longest, child_wid->smallest_x);
max_vert_fill = max(max_vert_fill, child_wid->GetVerticalStepSize(ST_SMALLEST));
@@ -1152,7 +1152,7 @@ void NWidgetHorizontal::SetupSmallestSize(Window *w, bool init_array)
uint max_smallest = this->smallest_y + 3 * max_vert_fill; // Upper limit to computing smallest height.
uint cur_height = this->smallest_y;
for (;;) {
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint step_size = child_wid->GetVerticalStepSize(ST_SMALLEST);
uint child_height = child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom;
if (step_size > 1 && child_height < cur_height) { // Small step sizes or already fitting children are not interesting.
@@ -1169,14 +1169,14 @@ void NWidgetHorizontal::SetupSmallestSize(Window *w, bool init_array)
}
/* 2. For containers that must maintain equal width, extend child minimal size. */
if (this->flags & NC_EQUALSIZE) {
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (child_wid->fill_x == 1) child_wid->smallest_x = longest;
}
}
/* 3. Move PIP space to the children, compute smallest, fill, and resize values of the container. */
- if (this->head != NULL) this->head->padding_left += this->pip_pre;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
- if (child_wid->next != NULL) {
+ if (this->head != nullptr) this->head->padding_left += this->pip_pre;
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
+ if (child_wid->next != nullptr) {
child_wid->padding_right += this->pip_inter;
} else {
child_wid->padding_right += this->pip_post;
@@ -1205,7 +1205,7 @@ void NWidgetHorizontal::AssignSizePosition(SizingType sizing, uint x, uint y, ui
uint additional_length = given_width;
if (sizing == ST_SMALLEST && (this->flags & NC_EQUALSIZE)) {
/* For EQUALSIZE containers this does not sum to smallest_x during initialisation */
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
additional_length -= child_wid->smallest_x + child_wid->padding_right + child_wid->padding_left;
}
} else {
@@ -1230,7 +1230,7 @@ void NWidgetHorizontal::AssignSizePosition(SizingType sizing, uint x, uint y, ui
*/
int num_changing_childs = 0; // Number of children that can change size.
uint biggest_stepsize = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint hor_step = child_wid->GetHorizontalStepSize(sizing);
if (hor_step > 0) {
num_changing_childs++;
@@ -1246,7 +1246,7 @@ void NWidgetHorizontal::AssignSizePosition(SizingType sizing, uint x, uint y, ui
/* Second loop: Allocate the additional horizontal space over the resizing children, starting with the biggest resize steps. */
while (biggest_stepsize > 0) {
uint next_biggest_stepsize = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint hor_step = child_wid->GetHorizontalStepSize(sizing);
if (hor_step > biggest_stepsize) continue; // Already done
if (hor_step == biggest_stepsize) {
@@ -1266,7 +1266,7 @@ void NWidgetHorizontal::AssignSizePosition(SizingType sizing, uint x, uint y, ui
/* Third loop: Compute position and call the child. */
uint position = rtl ? this->current_x : 0; // Place to put next child relative to origin of the container.
NWidgetBase *child_wid = this->head;
- while (child_wid != NULL) {
+ while (child_wid != nullptr) {
uint child_width = child_wid->current_x;
uint child_x = x + (rtl ? position - child_width - child_wid->padding_left : position + child_wid->padding_left);
uint child_y = y + child_wid->padding_top;
@@ -1307,7 +1307,7 @@ void NWidgetVertical::SetupSmallestSize(Window *w, bool init_array)
/* 1a. Forward call, collect biggest nested array index, and longest/widest child length. */
uint highest = 0; // Highest child found.
uint max_hor_fill = 0; // Biggest horizontal fill step.
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->SetupSmallestSize(w, init_array);
highest = max(highest, child_wid->smallest_y);
max_hor_fill = max(max_hor_fill, child_wid->GetHorizontalStepSize(ST_SMALLEST));
@@ -1317,7 +1317,7 @@ void NWidgetVertical::SetupSmallestSize(Window *w, bool init_array)
uint max_smallest = this->smallest_x + 3 * max_hor_fill; // Upper limit to computing smallest height.
uint cur_width = this->smallest_x;
for (;;) {
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint step_size = child_wid->GetHorizontalStepSize(ST_SMALLEST);
uint child_width = child_wid->smallest_x + child_wid->padding_left + child_wid->padding_right;
if (step_size > 1 && child_width < cur_width) { // Small step sizes or already fitting children are not interesting.
@@ -1334,14 +1334,14 @@ void NWidgetVertical::SetupSmallestSize(Window *w, bool init_array)
}
/* 2. For containers that must maintain equal width, extend children minimal size. */
if (this->flags & NC_EQUALSIZE) {
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (child_wid->fill_y == 1) child_wid->smallest_y = highest;
}
}
/* 3. Move PIP space to the child, compute smallest, fill, and resize values of the container. */
- if (this->head != NULL) this->head->padding_top += this->pip_pre;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
- if (child_wid->next != NULL) {
+ if (this->head != nullptr) this->head->padding_top += this->pip_pre;
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
+ if (child_wid->next != nullptr) {
child_wid->padding_bottom += this->pip_inter;
} else {
child_wid->padding_bottom += this->pip_post;
@@ -1370,7 +1370,7 @@ void NWidgetVertical::AssignSizePosition(SizingType sizing, uint x, uint y, uint
uint additional_length = given_height;
if (sizing == ST_SMALLEST && (this->flags & NC_EQUALSIZE)) {
/* For EQUALSIZE containers this does not sum to smallest_y during initialisation */
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
additional_length -= child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom;
}
} else {
@@ -1386,7 +1386,7 @@ void NWidgetVertical::AssignSizePosition(SizingType sizing, uint x, uint y, uint
/* First loop: Find biggest stepsize, find number of children that want a piece of the pie, handle horizontal size for all children, handle vertical size for non-resizing child. */
int num_changing_childs = 0; // Number of children that can change size.
uint biggest_stepsize = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint vert_step = child_wid->GetVerticalStepSize(sizing);
if (vert_step > 0) {
num_changing_childs++;
@@ -1402,7 +1402,7 @@ void NWidgetVertical::AssignSizePosition(SizingType sizing, uint x, uint y, uint
/* Second loop: Allocate the additional vertical space over the resizing children, starting with the biggest resize steps. */
while (biggest_stepsize > 0) {
uint next_biggest_stepsize = 0;
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint vert_step = child_wid->GetVerticalStepSize(sizing);
if (vert_step > biggest_stepsize) continue; // Already done
if (vert_step == biggest_stepsize) {
@@ -1421,7 +1421,7 @@ void NWidgetVertical::AssignSizePosition(SizingType sizing, uint x, uint y, uint
/* Third loop: Compute position and call the child. */
uint position = 0; // Place to put next child relative to origin of the container.
- for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
+ for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
uint child_x = x + (rtl ? child_wid->padding_right : child_wid->padding_left);
uint child_height = child_wid->current_y;
@@ -1463,7 +1463,7 @@ void NWidgetSpacer::SetDirty(const Window *w) const
NWidgetCore *NWidgetSpacer::GetWidgetFromPos(int x, int y)
{
- return NULL;
+ return nullptr;
}
NWidgetMatrix::NWidgetMatrix() : NWidgetPIPContainer(NWID_MATRIX, NC_EQUALSIZE), index(-1), clicked(-1), count(-1)
@@ -1487,7 +1487,7 @@ void NWidgetMatrix::SetColour(Colours colour)
void NWidgetMatrix::SetClicked(int clicked)
{
this->clicked = clicked;
- if (this->clicked >= 0 && this->sb != NULL && this->widgets_x != 0) {
+ if (this->clicked >= 0 && this->sb != nullptr && this->widgets_x != 0) {
int vpos = (this->clicked / this->widgets_x) * this->widget_h; // Vertical position of the top.
/* Need to scroll down -> Scroll to the bottom.
* However, last entry has no 'this->pip_inter' underneath, and we must stay below this->sb->GetCount() */
@@ -1505,7 +1505,7 @@ void NWidgetMatrix::SetCount(int count)
{
this->count = count;
- if (this->sb == NULL || this->widgets_x == 0) return;
+ if (this->sb == nullptr || this->widgets_x == 0) return;
/* We need to get the number of pixels the matrix is high/wide.
* So, determine the number of rows/columns based on the number of
@@ -1532,8 +1532,8 @@ void NWidgetMatrix::SetScrollbar(Scrollbar *sb)
void NWidgetMatrix::SetupSmallestSize(Window *w, bool init_array)
{
- assert(this->head != NULL);
- assert(this->head->next == NULL);
+ assert(this->head != nullptr);
+ assert(this->head->next == nullptr);
if (this->index >= 0 && init_array) { // Fill w->nested_array[]
assert(w->nested_array_size > (uint)this->index);
@@ -1542,7 +1542,7 @@ void NWidgetMatrix::SetupSmallestSize(Window *w, bool init_array)
/* Reset the widget number. */
NWidgetCore *nw = dynamic_cast<NWidgetCore *>(this->head);
- assert(nw != NULL);
+ assert(nw != nullptr);
SB(nw->index, 16, 16, 0);
this->head->SetupSmallestSize(w, init_array);
@@ -1594,7 +1594,7 @@ void NWidgetMatrix::FillNestedArray(NWidgetBase **array, uint length)
NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y)
{
/* Falls outside of the matrix widget. */
- if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
+ if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
int start_x, start_y, base_offs_x, base_offs_y;
this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
@@ -1609,10 +1609,10 @@ NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y)
int widget_row = (y - base_offs_y - (int)this->pip_pre - (int)this->pos_y) / this->widget_h;
int sub_wid = (widget_row + start_y) * this->widgets_x + start_x + widget_col;
- if (sub_wid >= this->count) return NULL;
+ if (sub_wid >= this->count) return nullptr;
NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->head);
- assert(child != NULL);
+ assert(child != nullptr);
child->AssignSizePosition(ST_RESIZE,
this->pos_x + (rtl ? this->pip_post - widget_col * this->widget_w : this->pip_pre + widget_col * this->widget_w) + base_offs_x,
this->pos_y + this->pip_pre + widget_row * this->widget_h + base_offs_y,
@@ -1637,7 +1637,7 @@ NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y)
/* Get the appropriate offsets so we can draw the right widgets. */
NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->head);
- assert(child != NULL);
+ assert(child != nullptr);
int start_x, start_y, base_offs_x, base_offs_y;
this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
@@ -1684,7 +1684,7 @@ void NWidgetMatrix::GetScrollOffsets(int &start_x, int &start_y, int &base_offs_
base_offs_y = 0;
start_x = 0;
start_y = 0;
- if (this->sb != NULL) {
+ if (this->sb != nullptr) {
if (this->sb->IsVertical()) {
start_y = this->sb->GetPosition() / this->widget_h;
base_offs_y += -this->sb->GetPosition() + start_y * this->widget_h;
@@ -1718,7 +1718,7 @@ NWidgetBackground::NWidgetBackground(WidgetType tp, Colours colour, int index, N
NWidgetBackground::~NWidgetBackground()
{
- if (this->child != NULL) delete this->child;
+ if (this->child != nullptr) delete this->child;
}
/**
@@ -1730,7 +1730,7 @@ NWidgetBackground::~NWidgetBackground()
*/
void NWidgetBackground::Add(NWidgetBase *nwid)
{
- if (this->child == NULL) {
+ if (this->child == nullptr) {
this->child = new NWidgetVertical();
}
this->child->Add(nwid);
@@ -1748,7 +1748,7 @@ void NWidgetBackground::Add(NWidgetBase *nwid)
*/
void NWidgetBackground::SetPIP(uint8 pip_pre, uint8 pip_inter, uint8 pip_post)
{
- if (this->child == NULL) {
+ if (this->child == nullptr) {
this->child = new NWidgetVertical();
}
this->child->SetPIP(pip_pre, pip_inter, pip_post);
@@ -1760,7 +1760,7 @@ void NWidgetBackground::SetupSmallestSize(Window *w, bool init_array)
assert(w->nested_array_size > (uint)this->index);
w->nested_array[this->index] = this;
}
- if (this->child != NULL) {
+ if (this->child != nullptr) {
this->child->SetupSmallestSize(w, init_array);
this->smallest_x = this->child->smallest_x;
@@ -1771,7 +1771,7 @@ void NWidgetBackground::SetupSmallestSize(Window *w, bool init_array)
this->resize_y = this->child->resize_y;
/* Account for the size of the frame's text if that exists */
- if (w != NULL && this->type == WWT_FRAME) {
+ if (w != nullptr && this->type == WWT_FRAME) {
this->child->padding_left = WD_FRAMETEXT_LEFT;
this->child->padding_right = WD_FRAMETEXT_RIGHT;
this->child->padding_top = max((int)WD_FRAMETEXT_TOP, this->widget_data != STR_NULL ? FONT_HEIGHT_NORMAL + WD_FRAMETEXT_TOP / 2 : 0);
@@ -1787,7 +1787,7 @@ void NWidgetBackground::SetupSmallestSize(Window *w, bool init_array)
Dimension d = {this->min_x, this->min_y};
Dimension fill = {this->fill_x, this->fill_y};
Dimension resize = {this->resize_x, this->resize_y};
- if (w != NULL) { // A non-NULL window pointer acts as switch to turn dynamic widget size on.
+ if (w != nullptr) { // A non-nullptr window pointer acts as switch to turn dynamic widget size on.
if (this->type == WWT_FRAME || this->type == WWT_INSET) {
if (this->index >= 0) w->SetStringParameters(this->index);
Dimension background = GetStringBoundingBox(this->widget_data);
@@ -1812,7 +1812,7 @@ void NWidgetBackground::AssignSizePosition(SizingType sizing, uint x, uint y, ui
{
this->StoreSizePosition(sizing, x, y, given_width, given_height);
- if (this->child != NULL) {
+ if (this->child != nullptr) {
uint x_offset = (rtl ? this->child->padding_right : this->child->padding_left);
uint width = given_width - this->child->padding_right - this->child->padding_left;
uint height = given_height - this->child->padding_top - this->child->padding_bottom;
@@ -1823,7 +1823,7 @@ void NWidgetBackground::AssignSizePosition(SizingType sizing, uint x, uint y, ui
void NWidgetBackground::FillNestedArray(NWidgetBase **array, uint length)
{
if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
- if (this->child != NULL) this->child->FillNestedArray(array, length);
+ if (this->child != nullptr) this->child->FillNestedArray(array, length);
}
void NWidgetBackground::Draw(const Window *w)
@@ -1860,7 +1860,7 @@ void NWidgetBackground::Draw(const Window *w)
}
if (this->index >= 0) w->DrawWidget(r, this->index);
- if (this->child != NULL) this->child->Draw(w);
+ if (this->child != nullptr) this->child->Draw(w);
if (this->IsDisabled()) {
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
@@ -1869,19 +1869,19 @@ void NWidgetBackground::Draw(const Window *w)
NWidgetCore *NWidgetBackground::GetWidgetFromPos(int x, int y)
{
- NWidgetCore *nwid = NULL;
+ NWidgetCore *nwid = nullptr;
if (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) {
- if (this->child != NULL) nwid = this->child->GetWidgetFromPos(x, y);
- if (nwid == NULL) nwid = this;
+ if (this->child != nullptr) nwid = this->child->GetWidgetFromPos(x, y);
+ if (nwid == nullptr) nwid = this;
}
return nwid;
}
NWidgetBase *NWidgetBackground::GetWidgetOfType(WidgetType tp)
{
- NWidgetBase *nwid = NULL;
- if (this->child != NULL) nwid = this->child->GetWidgetOfType(tp);
- if (nwid == NULL && this->type == tp) nwid = this;
+ NWidgetBase *nwid = nullptr;
+ if (this->child != nullptr) nwid = this->child->GetWidgetOfType(tp);
+ if (nwid == nullptr && this->type == tp) nwid = this;
return nwid;
}
@@ -1936,7 +1936,7 @@ void NWidgetViewport::InitializeViewport(Window *w, uint32 follow_flags, ZoomLev
void NWidgetViewport::UpdateViewportCoordinates(Window *w)
{
ViewPort *vp = w->viewport;
- if (vp != NULL) {
+ if (vp != nullptr) {
vp->left = w->left + this->pos_x;
vp->top = w->top + this->pos_y;
vp->width = this->current_x;
@@ -2207,7 +2207,7 @@ void NWidgetLeaf::SetupSmallestSize(Window *w, bool init_array)
Dimension fill = {this->fill_x, this->fill_y};
Dimension resize = {this->resize_x, this->resize_y};
/* Get padding, and update size with the real content size if appropriate. */
- const Dimension *padding = NULL;
+ const Dimension *padding = nullptr;
switch (this->type) {
case WWT_EMPTY: {
static const Dimension extra = {0, 0};
@@ -2464,7 +2464,7 @@ void NWidgetLeaf::Draw(const Window *w)
case WWT_EDITBOX: {
const QueryString *query = w->GetQueryString(this->index);
- if (query != NULL) query->DrawEditBox(w, this->index);
+ if (query != nullptr) query->DrawEditBox(w, this->index);
break;
}
@@ -2557,30 +2557,30 @@ bool NWidgetLeaf::ButtonHit(const Point &pt)
* @param fill_dest Fill the composed widget with child widgets.
* @param biggest_index Pointer to biggest nested widget index in the tree encountered so far.
* @return Number of widget part elements used to compose the widget.
- * @pre \c biggest_index != NULL.
+ * @pre \c biggest_index != nullptr.
*/
static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest, bool *fill_dest, int *biggest_index)
{
int num_used = 0;
- *dest = NULL;
+ *dest = nullptr;
*fill_dest = false;
while (count > num_used) {
switch (parts->type) {
case NWID_SPACER:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetSpacer(0, 0);
break;
case NWID_HORIZONTAL:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetHorizontal(parts->u.cont_flags);
*fill_dest = true;
break;
case NWID_HORIZONTAL_LTR:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetHorizontalLTR(parts->u.cont_flags);
*fill_dest = true;
break;
@@ -2588,20 +2588,20 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
case WWT_PANEL:
case WWT_INSET:
case WWT_FRAME:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetBackground(parts->type, parts->u.widget.colour, parts->u.widget.index);
*biggest_index = max(*biggest_index, (int)parts->u.widget.index);
*fill_dest = true;
break;
case NWID_VERTICAL:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetVertical(parts->u.cont_flags);
*fill_dest = true;
break;
case NWID_MATRIX: {
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
NWidgetMatrix *nwm = new NWidgetMatrix();
*dest = nwm;
*fill_dest = true;
@@ -2612,7 +2612,7 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
}
case WPT_FUNCTION: {
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
/* Ensure proper functioning even when the called code simply writes its largest index. */
int biggest = -1;
*dest = parts->u.func_ptr(&biggest);
@@ -2623,7 +2623,7 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
case WPT_RESIZE: {
NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
- if (nwrb != NULL) {
+ if (nwrb != nullptr) {
assert(parts->u.xy.x >= 0 && parts->u.xy.y >= 0);
nwrb->SetResize(parts->u.xy.x, parts->u.xy.y);
}
@@ -2632,7 +2632,7 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
case WPT_MINSIZE: {
NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
- if (nwrb != NULL) {
+ if (nwrb != nullptr) {
assert(parts->u.xy.x >= 0 && parts->u.xy.y >= 0);
nwrb->SetMinimalSize(parts->u.xy.x, parts->u.xy.y);
}
@@ -2641,7 +2641,7 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
case WPT_MINTEXTLINES: {
NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
- if (nwrb != NULL) {
+ if (nwrb != nullptr) {
assert(parts->u.text_lines.size >= FS_BEGIN && parts->u.text_lines.size < FS_END);
nwrb->SetMinimalTextLines(parts->u.text_lines.lines, parts->u.text_lines.spacing, parts->u.text_lines.size);
}
@@ -2650,13 +2650,13 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
case WPT_FILL: {
NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
- if (nwrb != NULL) nwrb->SetFill(parts->u.xy.x, parts->u.xy.y);
+ if (nwrb != nullptr) nwrb->SetFill(parts->u.xy.x, parts->u.xy.y);
break;
}
case WPT_DATATIP: {
NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
- if (nwc != NULL) {
+ if (nwc != nullptr) {
nwc->widget_data = parts->u.data_tip.data;
nwc->tool_tip = parts->u.data_tip.tooltip;
}
@@ -2664,21 +2664,21 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
}
case WPT_PADDING:
- if (*dest != NULL) (*dest)->SetPadding(parts->u.padding.top, parts->u.padding.right, parts->u.padding.bottom, parts->u.padding.left);
+ if (*dest != nullptr) (*dest)->SetPadding(parts->u.padding.top, parts->u.padding.right, parts->u.padding.bottom, parts->u.padding.left);
break;
case WPT_PIPSPACE: {
NWidgetPIPContainer *nwc = dynamic_cast<NWidgetPIPContainer *>(*dest);
- if (nwc != NULL) nwc->SetPIP(parts->u.pip.pre, parts->u.pip.inter, parts->u.pip.post);
+ if (nwc != nullptr) nwc->SetPIP(parts->u.pip.pre, parts->u.pip.inter, parts->u.pip.post);
NWidgetBackground *nwb = dynamic_cast<NWidgetBackground *>(*dest);
- if (nwb != NULL) nwb->SetPIP(parts->u.pip.pre, parts->u.pip.inter, parts->u.pip.post);
+ if (nwb != nullptr) nwb->SetPIP(parts->u.pip.pre, parts->u.pip.inter, parts->u.pip.post);
break;
}
case WPT_SCROLLBAR: {
NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
- if (nwc != NULL) {
+ if (nwc != nullptr) {
nwc->scrollbar_index = parts->u.widget.index;
}
break;
@@ -2688,20 +2688,20 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
return num_used;
case NWID_VIEWPORT:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetViewport(parts->u.widget.index);
*biggest_index = max(*biggest_index, (int)parts->u.widget.index);
break;
case NWID_HSCROLLBAR:
case NWID_VSCROLLBAR:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
*dest = new NWidgetScrollbar(parts->type, parts->u.widget.colour, parts->u.widget.index);
*biggest_index = max(*biggest_index, (int)parts->u.widget.index);
break;
case NWID_SELECTION: {
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
NWidgetStacked *nws = new NWidgetStacked();
*dest = nws;
*fill_dest = true;
@@ -2711,7 +2711,7 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
}
default:
- if (*dest != NULL) return num_used;
+ if (*dest != nullptr) return num_used;
assert((parts->type & WWT_MASK) < WWT_LAST || (parts->type & WWT_MASK) == NWID_BUTTON_DROPDOWN);
*dest = new NWidgetLeaf(parts->type, parts->u.widget.colour, parts->u.widget.index, 0x0, STR_NULL);
*biggest_index = max(*biggest_index, (int)parts->u.widget.index);
@@ -2728,29 +2728,29 @@ static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest,
* Build a nested widget tree by recursively filling containers with nested widgets read from their parts.
* @param parts Array with parts of the nested widgets.
* @param count Length of the \a parts array.
- * @param parent Pointer or container to use for storing the child widgets (*parent == NULL or *parent == container or background widget).
+ * @param parent Pointer or container to use for storing the child widgets (*parent == nullptr or *parent == container or background widget).
* @param biggest_index Pointer to biggest nested widget index in the tree.
* @return Number of widget part elements used to fill the container.
* @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
*/
static int MakeWidgetTree(const NWidgetPart *parts, int count, NWidgetBase **parent, int *biggest_index)
{
- /* If *parent == NULL, only the first widget is read and returned. Otherwise, *parent must point to either
+ /* If *parent == nullptr, only the first widget is read and returned. Otherwise, *parent must point to either
* a #NWidgetContainer or a #NWidgetBackground object, and parts are added as much as possible. */
NWidgetContainer *nwid_cont = dynamic_cast<NWidgetContainer *>(*parent);
NWidgetBackground *nwid_parent = dynamic_cast<NWidgetBackground *>(*parent);
- assert(*parent == NULL || (nwid_cont != NULL && nwid_parent == NULL) || (nwid_cont == NULL && nwid_parent != NULL));
+ assert(*parent == nullptr || (nwid_cont != nullptr && nwid_parent == nullptr) || (nwid_cont == nullptr && nwid_parent != nullptr));
int total_used = 0;
for (;;) {
- NWidgetBase *sub_widget = NULL;
+ NWidgetBase *sub_widget = nullptr;
bool fill_sub = false;
int num_used = MakeNWidget(parts, count - total_used, &sub_widget, &fill_sub, biggest_index);
parts += num_used;
total_used += num_used;
/* Break out of loop when end reached */
- if (sub_widget == NULL) break;
+ if (sub_widget == nullptr) break;
/* If sub-widget is a container, recursively fill that container. */
WidgetType tp = sub_widget->type;
@@ -2763,9 +2763,9 @@ static int MakeWidgetTree(const NWidgetPart *parts, int count, NWidgetBase **par
}
/* Add sub_widget to parent container if available, otherwise return the widget to the caller. */
- if (nwid_cont != NULL) nwid_cont->Add(sub_widget);
- if (nwid_parent != NULL) nwid_parent->Add(sub_widget);
- if (nwid_cont == NULL && nwid_parent == NULL) {
+ if (nwid_cont != nullptr) nwid_cont->Add(sub_widget);
+ if (nwid_parent != nullptr) nwid_parent->Add(sub_widget);
+ if (nwid_cont == nullptr && nwid_parent == nullptr) {
*parent = sub_widget;
return total_used;
}
@@ -2783,16 +2783,16 @@ static int MakeWidgetTree(const NWidgetPart *parts, int count, NWidgetBase **par
* @param parts Array with parts of the widgets.
* @param count Length of the \a parts array.
* @param biggest_index Pointer to biggest nested widget index collected in the tree.
- * @param container Container to add the nested widgets to. In case it is NULL a vertical container is used.
+ * @param container Container to add the nested widgets to. In case it is nullptr a vertical container is used.
* @return Root of the nested widget tree, a vertical container containing the entire GUI.
* @ingroup NestedWidgetParts
- * @pre \c biggest_index != NULL
+ * @pre \c biggest_index != nullptr
* @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
*/
NWidgetContainer *MakeNWidgets(const NWidgetPart *parts, int count, int *biggest_index, NWidgetContainer *container)
{
*biggest_index = -1;
- if (container == NULL) container = new NWidgetVertical();
+ if (container == nullptr) container = new NWidgetVertical();
NWidgetBase *cont_ptr = container;
MakeWidgetTree(parts, count, &cont_ptr, biggest_index);
return container;
@@ -2805,10 +2805,10 @@ NWidgetContainer *MakeNWidgets(const NWidgetPart *parts, int count, int *biggest
* @param parts Array with parts of the widgets.
* @param count Length of the \a parts array.
* @param biggest_index Pointer to biggest nested widget index collected in the tree.
- * @param[out] shade_select Pointer to the inserted shade selection widget (\c NULL if not unserted).
+ * @param[out] shade_select Pointer to the inserted shade selection widget (\c nullptr if not unserted).
* @return Root of the nested widget tree, a vertical container containing the entire GUI.
* @ingroup NestedWidgetParts
- * @pre \c biggest_index != NULL
+ * @pre \c biggest_index != nullptr
* @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
*/
NWidgetContainer *MakeWindowNWidgetTree(const NWidgetPart *parts, int count, int *biggest_index, NWidgetStacked **shade_select)
@@ -2816,16 +2816,16 @@ NWidgetContainer *MakeWindowNWidgetTree(const NWidgetPart *parts, int count, int
*biggest_index = -1;
/* Read the first widget recursively from the array. */
- NWidgetBase *nwid = NULL;
+ NWidgetBase *nwid = nullptr;
int num_used = MakeWidgetTree(parts, count, &nwid, biggest_index);
- assert(nwid != NULL);
+ assert(nwid != nullptr);
parts += num_used;
count -= num_used;
NWidgetContainer *root = new NWidgetVertical;
root->Add(nwid);
if (count == 0) { // There is no body at all.
- *shade_select = NULL;
+ *shade_select = nullptr;
return root;
}
@@ -2833,13 +2833,13 @@ NWidgetContainer *MakeWindowNWidgetTree(const NWidgetPart *parts, int count, int
* If it has a shading box, silently add a shade selection widget in the tree. */
NWidgetHorizontal *hor_cont = dynamic_cast<NWidgetHorizontal *>(nwid);
NWidgetContainer *body;
- if (hor_cont != NULL && hor_cont->GetWidgetOfType(WWT_CAPTION) != NULL && hor_cont->GetWidgetOfType(WWT_SHADEBOX) != NULL) {
+ if (hor_cont != nullptr && hor_cont->GetWidgetOfType(WWT_CAPTION) != nullptr && hor_cont->GetWidgetOfType(WWT_SHADEBOX) != nullptr) {
*shade_select = new NWidgetStacked;
root->Add(*shade_select);
body = new NWidgetVertical;
(*shade_select)->Add(body);
} else {
- *shade_select = NULL;
+ *shade_select = nullptr;
body = root;
}
@@ -2864,8 +2864,8 @@ NWidgetContainer *MakeWindowNWidgetTree(const NWidgetPart *parts, int count, int
NWidgetBase *MakeCompanyButtonRows(int *biggest_index, int widget_first, int widget_last, int max_length, StringID button_tooltip)
{
assert(max_length >= 1);
- NWidgetVertical *vert = NULL; // Storage for all rows.
- NWidgetHorizontal *hor = NULL; // Storage for buttons in one row.
+ NWidgetVertical *vert = nullptr; // Storage for all rows.
+ NWidgetHorizontal *hor = nullptr; // Storage for buttons in one row.
int hor_length = 0;
Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
@@ -2875,12 +2875,12 @@ NWidgetBase *MakeCompanyButtonRows(int *biggest_index, int widget_first, int wid
for (int widnum = widget_first; widnum <= widget_last; widnum++) {
/* Ensure there is room in 'hor' for another button. */
if (hor_length == max_length) {
- if (vert == NULL) vert = new NWidgetVertical();
+ if (vert == nullptr) vert = new NWidgetVertical();
vert->Add(hor);
- hor = NULL;
+ hor = nullptr;
hor_length = 0;
}
- if (hor == NULL) {
+ if (hor == nullptr) {
hor = new NWidgetHorizontal();
hor_length = 0;
}
@@ -2894,7 +2894,7 @@ NWidgetBase *MakeCompanyButtonRows(int *biggest_index, int widget_first, int wid
hor_length++;
}
*biggest_index = widget_last;
- if (vert == NULL) return hor; // All buttons fit in a single row.
+ if (vert == nullptr) return hor; // All buttons fit in a single row.
if (hor_length > 0 && hor_length < max_length) {
/* Last row is partial, add a spacer at the end to force all buttons to the left. */
@@ -2903,6 +2903,6 @@ NWidgetBase *MakeCompanyButtonRows(int *biggest_index, int widget_first, int wid
spc->SetResize(1, 0);
hor->Add(spc);
}
- if (hor != NULL) vert->Add(hor);
+ if (hor != nullptr) vert->Add(hor);
return vert;
}
diff --git a/src/widget_type.h b/src/widget_type.h
index 0467630c9..9d1702488 100644
--- a/src/widget_type.h
+++ b/src/widget_type.h
@@ -374,7 +374,7 @@ public:
void FillNestedArray(NWidgetBase **array, uint length) override;
/** Return whether the container is empty. */
- inline bool IsEmpty() { return head == NULL; }
+ inline bool IsEmpty() { return head == nullptr; }
NWidgetBase *GetWidgetOfType(WidgetType tp) override;
@@ -544,7 +544,7 @@ public:
*/
class NWidgetBackground : public NWidgetCore {
public:
- NWidgetBackground(WidgetType tp, Colours colour, int index, NWidgetPIPContainer *child = NULL);
+ NWidgetBackground(WidgetType tp, Colours colour, int index, NWidgetPIPContainer *child = nullptr);
~NWidgetBackground();
void Add(NWidgetBase *nwid);
diff --git a/src/widgets/dropdown.cpp b/src/widgets/dropdown.cpp
index b123d7d94..844c6470e 100644
--- a/src/widgets/dropdown.cpp
+++ b/src/widgets/dropdown.cpp
@@ -115,7 +115,7 @@ static const NWidgetPart _nested_dropdown_menu_widgets[] = {
};
static WindowDesc _dropdown_desc(
- WDP_MANUAL, NULL, 0, 0,
+ WDP_MANUAL, nullptr, 0, 0,
WC_DROPDOWN_MENU, WC_NONE,
WDF_NO_FOCUS,
_nested_dropdown_menu_widgets, lengthof(_nested_dropdown_menu_widgets)
@@ -200,7 +200,7 @@ struct DropdownWindow : Window {
this->SetDirty();
Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num);
- if (w2 != NULL) {
+ if (w2 != nullptr) {
Point pt = _cursor.pos;
pt.x -= w2->left;
pt.y -= w2->top;
@@ -304,7 +304,7 @@ struct DropdownWindow : Window {
virtual void OnMouseLoop()
{
Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num);
- if (w2 == NULL) {
+ if (w2 == nullptr) {
delete this;
return;
}
@@ -518,7 +518,7 @@ int HideDropDownMenu(Window *pw)
if (w->window_class != WC_DROPDOWN_MENU) continue;
DropdownWindow *dw = dynamic_cast<DropdownWindow*>(w);
- assert(dw != NULL);
+ assert(dw != nullptr);
if (pw->window_class == dw->parent_wnd_class &&
pw->window_number == dw->parent_wnd_num) {
int parent_button = dw->parent_button;
diff --git a/src/window.cpp b/src/window.cpp
index 891eafb5e..d956b55f9 100644
--- a/src/window.cpp
+++ b/src/window.cpp
@@ -52,13 +52,13 @@ enum ViewportAutoscrolling {
};
static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
-static Window *_mouseover_last_w = NULL; ///< Window of the last OnMouseOver event.
-static Window *_last_scroll_window = NULL; ///< Window of the last scroll event.
+static Window *_mouseover_last_w = nullptr; ///< Window of the last OnMouseOver event.
+static Window *_last_scroll_window = nullptr; ///< Window of the last scroll event.
/** List of windows opened at the screen sorted from the front. */
-Window *_z_front_window = NULL;
+Window *_z_front_window = nullptr;
/** List of windows opened at the screen sorted from the back. */
-Window *_z_back_window = NULL;
+Window *_z_back_window = nullptr;
/** If false, highlight is white, otherwise the by the widget defined colour. */
bool _window_highlight_colour = false;
@@ -85,7 +85,7 @@ SpecialMouseMode _special_mouse_mode; ///< Mode of the mouse.
* List of all WindowDescs.
* This is a pointer to ensure initialisation order with the various static WindowDesc instances.
*/
-static std::vector<WindowDesc*> *_window_descs = NULL;
+static std::vector<WindowDesc*> *_window_descs = nullptr;
/** Config file to store WindowDesc */
char *_windows_file;
@@ -108,7 +108,7 @@ WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_wi
default_width_trad(def_width_trad),
default_height_trad(def_height_trad)
{
- if (_window_descs == NULL) _window_descs = new std::vector<WindowDesc*>();
+ if (_window_descs == nullptr) _window_descs = new std::vector<WindowDesc*>();
_window_descs->push_back(this);
}
@@ -145,7 +145,7 @@ void WindowDesc::LoadFromConfig()
IniFile *ini = new IniFile();
ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
for (WindowDesc *wd : *_window_descs) {
- if (wd->ini_key == NULL) continue;
+ if (wd->ini_key == nullptr) continue;
IniLoadWindowSettings(ini, wd->ini_key, wd);
}
delete ini;
@@ -156,8 +156,8 @@ void WindowDesc::LoadFromConfig()
*/
static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
{
- if ((*a)->ini_key != NULL && (*b)->ini_key != NULL) return strcmp((*a)->ini_key, (*b)->ini_key);
- return ((*b)->ini_key != NULL ? 1 : 0) - ((*a)->ini_key != NULL ? 1 : 0);
+ if ((*a)->ini_key != nullptr && (*b)->ini_key != nullptr) return strcmp((*a)->ini_key, (*b)->ini_key);
+ return ((*b)->ini_key != nullptr ? 1 : 0) - ((*a)->ini_key != nullptr ? 1 : 0);
}
/**
@@ -171,7 +171,7 @@ void WindowDesc::SaveToConfig()
IniFile *ini = new IniFile();
ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
for (WindowDesc *wd : *_window_descs) {
- if (wd->ini_key == NULL) continue;
+ if (wd->ini_key == nullptr) continue;
IniSaveWindowSettings(ini, wd->ini_key, wd);
}
ini->SaveToDisk(_windows_file);
@@ -183,7 +183,7 @@ void WindowDesc::SaveToConfig()
*/
void Window::ApplyDefaults()
{
- if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
+ if (this->nested_root != nullptr && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != nullptr) {
if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
} else {
/* There is no stickybox; clear the preference in case someone tried to be funny */
@@ -215,7 +215,7 @@ void Window::DisableAllWidgetHighlight()
{
for (uint i = 0; i < this->nested_array_size; i++) {
NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
- if (nwid == NULL) continue;
+ if (nwid == nullptr) continue;
if (nwid->IsHighlighted()) {
nwid->SetHighlighted(TC_INVALID);
@@ -236,7 +236,7 @@ void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour
assert(widget_index < this->nested_array_size);
NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
- if (nwid == NULL) return;
+ if (nwid == nullptr) return;
nwid->SetHighlighted(highlighted_colour);
this->SetWidgetDirty(widget_index);
@@ -249,7 +249,7 @@ void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour
bool valid = false;
for (uint i = 0; i < this->nested_array_size; i++) {
NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
- if (nwid == NULL) continue;
+ if (nwid == nullptr) continue;
if (!nwid->IsHighlighted()) continue;
valid = true;
@@ -269,7 +269,7 @@ bool Window::IsWidgetHighlighted(byte widget_index) const
assert(widget_index < this->nested_array_size);
const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
- if (nwid == NULL) return false;
+ if (nwid == nullptr) return false;
return nwid->IsHighlighted();
}
@@ -326,63 +326,63 @@ Scrollbar *Window::GetScrollbar(uint widnum)
/**
* Return the querystring associated to a editbox.
* @param widnum Editbox widget index
- * @return QueryString or NULL.
+ * @return QueryString or nullptr.
*/
const QueryString *Window::GetQueryString(uint widnum) const
{
auto query = this->querystrings.Find(widnum);
- return query != this->querystrings.end() ? query->second : NULL;
+ return query != this->querystrings.end() ? query->second : nullptr;
}
/**
* Return the querystring associated to a editbox.
* @param widnum Editbox widget index
- * @return QueryString or NULL.
+ * @return QueryString or nullptr.
*/
QueryString *Window::GetQueryString(uint widnum)
{
SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
- return query != this->querystrings.End() ? query->second : NULL;
+ return query != this->querystrings.End() ? query->second : nullptr;
}
/**
* Get the current input text if an edit box has the focus.
- * @return The currently focused input text or NULL if no input focused.
+ * @return The currently focused input text or nullptr if no input focused.
*/
/* virtual */ const char *Window::GetFocusedText() const
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
return this->GetQueryString(this->nested_focus->index)->GetText();
}
- return NULL;
+ return nullptr;
}
/**
* Get the string at the caret if an edit box has the focus.
- * @return The text at the caret or NULL if no edit box is focused.
+ * @return The text at the caret or nullptr if no edit box is focused.
*/
/* virtual */ const char *Window::GetCaret() const
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
return this->GetQueryString(this->nested_focus->index)->GetCaret();
}
- return NULL;
+ return nullptr;
}
/**
* Get the range of the currently marked input text.
* @param[out] length Length of the marked text.
- * @return Pointer to the start of the marked text or NULL if no text is marked.
+ * @return Pointer to the start of the marked text or nullptr if no text is marked.
*/
/* virtual */ const char *Window::GetMarkedText(size_t *length) const
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
}
- return NULL;
+ return nullptr;
}
/**
@@ -391,7 +391,7 @@ QueryString *Window::GetQueryString(uint widnum)
*/
/* virtual */ Point Window::GetCaretPosition() const
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
}
@@ -407,7 +407,7 @@ QueryString *Window::GetQueryString(uint widnum)
*/
/* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
}
@@ -418,15 +418,15 @@ QueryString *Window::GetQueryString(uint widnum)
/**
* Get the character that is rendered at a position by the focused edit box.
* @param pt The position to test.
- * @return Pointer to the character at the position or NULL if no character is at the position.
+ * @return Pointer to the character at the position or nullptr if no character is at the position.
*/
/* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
}
- return NULL;
+ return nullptr;
}
/**
@@ -438,8 +438,8 @@ void SetFocusedWindow(Window *w)
if (_focused_window == w) return;
/* Invalidate focused widget */
- if (_focused_window != NULL) {
- if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
+ if (_focused_window != nullptr) {
+ if (_focused_window->nested_focus != nullptr) _focused_window->nested_focus->SetDirty(_focused_window);
}
/* Remember which window was previously focused */
@@ -447,8 +447,8 @@ void SetFocusedWindow(Window *w)
_focused_window = w;
/* So we can inform it that it lost focus */
- if (old_focused != NULL) old_focused->OnFocusLost();
- if (_focused_window != NULL) _focused_window->OnFocus();
+ if (old_focused != nullptr) old_focused->OnFocusLost();
+ if (_focused_window != nullptr) _focused_window->OnFocus();
}
/**
@@ -458,12 +458,12 @@ void SetFocusedWindow(Window *w)
*/
bool EditBoxInGlobalFocus()
{
- if (_focused_window == NULL) return false;
+ if (_focused_window == nullptr) return false;
/* The console does not have an edit box so a special case is needed. */
if (_focused_window->window_class == WC_CONSOLE) return true;
- return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
+ return _focused_window->nested_focus != nullptr && _focused_window->nested_focus->type == WWT_EDITBOX;
}
/**
@@ -471,12 +471,12 @@ bool EditBoxInGlobalFocus()
*/
void Window::UnfocusFocusedWidget()
{
- if (this->nested_focus != NULL) {
+ if (this->nested_focus != nullptr) {
if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
/* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
this->nested_focus->SetDirty(this);
- this->nested_focus = NULL;
+ this->nested_focus = nullptr;
}
}
@@ -490,8 +490,8 @@ bool Window::SetFocusedWidget(int widget_index)
/* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
if ((uint)widget_index >= this->nested_array_size) return false;
- assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
- if (this->nested_focus != NULL) {
+ assert(this->nested_array[widget_index] != nullptr); // Setting focus to a non-existing widget is a bad idea.
+ if (this->nested_focus != nullptr) {
if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
/* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
@@ -507,7 +507,7 @@ bool Window::SetFocusedWidget(int widget_index)
*/
void Window::OnFocusLost()
{
- if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
+ if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
}
/**
@@ -557,7 +557,7 @@ void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
void Window::RaiseButtons(bool autoraise)
{
for (uint i = 0; i < this->nested_array_size; i++) {
- if (this->nested_array[i] == NULL) continue;
+ if (this->nested_array[i] == nullptr) continue;
WidgetType type = this->nested_array[i]->type;
if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
(!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
@@ -567,8 +567,8 @@ void Window::RaiseButtons(bool autoraise)
}
/* Special widgets without widget index */
- NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
- if (wid != NULL) {
+ NWidgetCore *wid = this->nested_root != nullptr ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : nullptr;
+ if (wid != nullptr) {
wid->SetLowered(false);
wid->SetDirty(this);
}
@@ -581,7 +581,7 @@ void Window::RaiseButtons(bool autoraise)
void Window::SetWidgetDirty(byte widget_index) const
{
/* Sometimes this function is called before the window is even fully initialized */
- if (this->nested_array == NULL) return;
+ if (this->nested_array == nullptr) return;
this->nested_array[widget_index]->SetDirty(this);
}
@@ -596,7 +596,7 @@ EventState Window::OnHotkey(int hotkey)
if (hotkey < 0) return ES_NOT_HANDLED;
NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
- if (nw == NULL || nw->IsDisabled()) return ES_NOT_HANDLED;
+ if (nw == nullptr || nw->IsDisabled()) return ES_NOT_HANDLED;
if (nw->type == WWT_EDITBOX) {
if (this->IsShaded()) return ES_NOT_HANDLED;
@@ -636,7 +636,7 @@ static void StartWindowSizing(Window *w, bool to_left);
static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
{
NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
- WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
+ WidgetType widget_type = (nw != nullptr) ? nw->type : WWT_EMPTY;
bool focused_widget_changed = false;
/* If clicked on a window that previously did dot have focus */
@@ -647,7 +647,7 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
SetFocusedWindow(w);
}
- if (nw == NULL) return; // exit if clicked outside of widgets
+ if (nw == nullptr) return; // exit if clicked outside of widgets
/* don't allow any interaction if the button has been disabled */
if (nw->IsDisabled()) return;
@@ -686,7 +686,7 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
case WWT_EDITBOX: {
QueryString *query = w->GetQueryString(widget_index);
- if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
+ if (query != nullptr) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
break;
}
@@ -768,7 +768,7 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
static void DispatchRightClickEvent(Window *w, int x, int y)
{
NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
- if (wid == NULL) return;
+ if (wid == nullptr) return;
Point pt = { x, y };
@@ -781,7 +781,7 @@ static void DispatchRightClickEvent(Window *w, int x, int y)
if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
delete w;
} else if (_settings_client.gui.hover_delay_ms == 0 && !w->OnTooltip(pt, wid->index, TCC_RIGHT_CLICK) && wid->tool_tip != 0) {
- GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
+ GuiShowTooltips(w, wid->tool_tip, 0, nullptr, TCC_RIGHT_CLICK);
}
}
@@ -796,7 +796,7 @@ static void DispatchHoverEvent(Window *w, int x, int y)
NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
/* No widget to handle */
- if (wid == NULL) return;
+ if (wid == nullptr) return;
Point pt = { x, y };
@@ -821,7 +821,7 @@ static void DispatchHoverEvent(Window *w, int x, int y)
*/
static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
{
- if (nwid == NULL) return;
+ if (nwid == nullptr) return;
/* Using wheel on caption/shade-box shades or unshades the window. */
if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
@@ -840,8 +840,8 @@ static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
}
/* Scroll the widget attached to the scrollbar. */
- Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
- if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
+ Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : nullptr);
+ if (sb != nullptr && sb->GetCount() > sb->GetCapacity()) {
sb->UpdatePosition(wheel);
w->SetDirty();
}
@@ -1014,12 +1014,12 @@ void Window::ReInit(int rx, int ry)
*/
void Window::SetShaded(bool make_shaded)
{
- if (this->shade_select == NULL) return;
+ if (this->shade_select == nullptr) return;
int desired = make_shaded ? SZSP_HORIZONTAL : 0;
if (this->shade_select->shown_plane != desired) {
if (make_shaded) {
- if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
+ if (this->nested_focus != nullptr) this->UnfocusFocusedWidget();
this->unshaded_size.width = this->width;
this->unshaded_size.height = this->height;
this->shade_select->SetDisplayedPlane(desired);
@@ -1037,7 +1037,7 @@ void Window::SetShaded(bool make_shaded)
* Find the Window whose parent pointer points to this window
* @param w parent Window to find child of
* @param wc Window class of the window to remove; #WC_INVALID if class does not matter
- * @return a Window pointer that is the child of \a w, or \c NULL otherwise
+ * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
*/
static Window *FindChildWindow(const Window *w, WindowClass wc)
{
@@ -1046,7 +1046,7 @@ static Window *FindChildWindow(const Window *w, WindowClass wc)
if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
}
- return NULL;
+ return nullptr;
}
/**
@@ -1056,7 +1056,7 @@ static Window *FindChildWindow(const Window *w, WindowClass wc)
void Window::DeleteChildWindows(WindowClass wc) const
{
Window *child = FindChildWindow(this, wc);
- while (child != NULL) {
+ while (child != nullptr) {
delete child;
child = FindChildWindow(this, wc);
}
@@ -1073,20 +1073,20 @@ Window::~Window()
}
/* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
- if (_mouseover_last_w == this) _mouseover_last_w = NULL;
+ if (_mouseover_last_w == this) _mouseover_last_w = nullptr;
/* We can't scroll the window when it's closed. */
- if (_last_scroll_window == this) _last_scroll_window = NULL;
+ if (_last_scroll_window == this) _last_scroll_window = nullptr;
/* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
if (_focused_window == this) {
this->OnFocusLost();
- _focused_window = NULL;
+ _focused_window = nullptr;
}
this->DeleteChildWindows();
- if (this->viewport != NULL) DeleteWindowViewport(this);
+ if (this->viewport != nullptr) DeleteWindowViewport(this);
this->SetDirty();
@@ -1109,7 +1109,7 @@ Window::~Window()
* Find a window by its class and window number
* @param cls Window class
* @param number Number of the window within the window class
- * @return Pointer to the found window, or \c NULL if not available
+ * @return Pointer to the found window, or \c nullptr if not available
*/
Window *FindWindowById(WindowClass cls, WindowNumber number)
{
@@ -1118,14 +1118,14 @@ Window *FindWindowById(WindowClass cls, WindowNumber number)
if (w->window_class == cls && w->window_number == number) return w;
}
- return NULL;
+ return nullptr;
}
/**
* Find any window by its class. Useful when searching for a window that uses
* the window number as a #WindowClass, like #WC_SEND_NETWORK_MSG.
* @param cls Window class
- * @return Pointer to the found window, or \c NULL if not available
+ * @return Pointer to the found window, or \c nullptr if not available
*/
Window *FindWindowByClass(WindowClass cls)
{
@@ -1134,7 +1134,7 @@ Window *FindWindowByClass(WindowClass cls)
if (w->window_class == cls) return w;
}
- return NULL;
+ return nullptr;
}
/**
@@ -1146,7 +1146,7 @@ Window *FindWindowByClass(WindowClass cls)
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
{
Window *w = FindWindowById(cls, number);
- if (force || w == NULL ||
+ if (force || w == nullptr ||
(w->flags & WF_STICKY) == 0) {
delete w;
}
@@ -1244,7 +1244,7 @@ Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
{
Window *w = FindWindowById(cls, number);
- if (w != NULL) {
+ if (w != nullptr) {
if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
w->SetWhiteBorder();
@@ -1357,17 +1357,17 @@ static uint GetWindowZPriority(WindowClass wc)
*/
static void AddWindowToZOrdering(Window *w)
{
- assert(w->z_front == NULL && w->z_back == NULL);
+ assert(w->z_front == nullptr && w->z_back == nullptr);
- if (_z_front_window == NULL) {
+ if (_z_front_window == nullptr) {
/* It's the only window. */
_z_front_window = _z_back_window = w;
- w->z_front = w->z_back = NULL;
+ w->z_front = w->z_back = nullptr;
} else {
/* Search down the z-ordering for its location. */
Window *v = _z_front_window;
uint last_z_priority = UINT_MAX;
- while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v->window_class) > GetWindowZPriority(w->window_class))) {
+ while (v != nullptr && (v->window_class == WC_INVALID || GetWindowZPriority(v->window_class) > GetWindowZPriority(w->window_class))) {
if (v->window_class != WC_INVALID) {
/* Sanity check z-ordering, while we're at it. */
assert(last_z_priority >= GetWindowZPriority(v->window_class));
@@ -1377,15 +1377,15 @@ static void AddWindowToZOrdering(Window *w)
v = v->z_back;
}
- if (v == NULL) {
+ if (v == nullptr) {
/* It's the new back window. */
w->z_front = _z_back_window;
- w->z_back = NULL;
+ w->z_back = nullptr;
_z_back_window->z_back = w;
_z_back_window = w;
} else if (v == _z_front_window) {
/* It's the new front window. */
- w->z_front = NULL;
+ w->z_front = nullptr;
w->z_back = _z_front_window;
_z_front_window->z_front = w;
_z_front_window = w;
@@ -1406,21 +1406,21 @@ static void AddWindowToZOrdering(Window *w)
*/
static void RemoveWindowFromZOrdering(Window *w)
{
- if (w->z_front == NULL) {
+ if (w->z_front == nullptr) {
assert(_z_front_window == w);
_z_front_window = w->z_back;
} else {
w->z_front->z_back = w->z_back;
}
- if (w->z_back == NULL) {
+ if (w->z_back == nullptr) {
assert(_z_back_window == w);
_z_back_window = w->z_front;
} else {
w->z_back->z_front = w->z_front;
}
- w->z_front = w->z_back = NULL;
+ w->z_front = w->z_back = nullptr;
}
/**
@@ -1440,8 +1440,8 @@ static void BringWindowToFront(Window *w)
* Initializes the data (except the position and initial size) of a new Window.
* @param window_number Number being assigned to the new window
* @return Window pointer of the newly created window
- * @pre If nested widgets are used (\a widget is \c NULL), #nested_root and #nested_array_size must be initialized.
- * In addition, #nested_array is either \c NULL, or already initialized.
+ * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
+ * In addition, #nested_array is either \c nullptr, or already initialized.
*/
void Window::InitializeData(WindowNumber window_number)
{
@@ -1450,12 +1450,12 @@ void Window::InitializeData(WindowNumber window_number)
this->SetWhiteBorder();
if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
this->owner = INVALID_OWNER;
- this->nested_focus = NULL;
+ this->nested_focus = nullptr;
this->window_number = window_number;
this->OnInit();
/* Initialize nested widget tree. */
- if (this->nested_array == NULL) {
+ if (this->nested_array == nullptr) {
this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
this->nested_root->SetupSmallestSize(this, true);
} else {
@@ -1472,7 +1472,7 @@ void Window::InitializeData(WindowNumber window_number)
/* Give focus to the opened window unless a text box
* of focused window has focus (so we don't interrupt typing). But if the new
* window has a text box, then take focus anyway. */
- if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL) SetFocusedWindow(this);
+ if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != nullptr) SetFocusedWindow(this);
/* Insert the window into the correct location in the z-ordering. */
AddWindowToZOrdering(this);
@@ -1516,9 +1516,9 @@ void Window::FindWindowPlacementAndResize(int def_width, int def_height)
/* Think about the overlapping toolbars when determining the minimum window size */
int free_height = _screen.height;
const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
- if (wt != NULL) free_height -= wt->height;
+ if (wt != nullptr) free_height -= wt->height;
wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
- if (wt != NULL) free_height -= wt->height;
+ if (wt != nullptr) free_height -= wt->height;
int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
@@ -1542,10 +1542,10 @@ void Window::FindWindowPlacementAndResize(int def_width, int def_height)
if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
- ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
+ ny = max(ny, (wt == nullptr || this == wt || this->top == 0) ? 0 : wt->height);
nx = max(nx, 0);
- if (this->viewport != NULL) {
+ if (this->viewport != nullptr) {
this->viewport->left += nx - this->left;
this->viewport->top += ny - this->top;
}
@@ -1652,7 +1652,7 @@ static Point GetAutoPlacePosition(int width, int height)
/* First attempt, try top-left of the screen */
const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
- const int toolbar_y = main_toolbar != NULL ? main_toolbar->height : 0;
+ const int toolbar_y = main_toolbar != nullptr ? main_toolbar->height : 0;
if (IsGoodAutoPlace1(rtl ? _screen.width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
/* Second attempt, try around all existing windows.
@@ -1716,7 +1716,7 @@ restart:
Point GetToolbarAlignedWindowPosition(int window_width)
{
const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
- assert(w != NULL);
+ assert(w != nullptr);
Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
return pt;
}
@@ -1746,7 +1746,7 @@ static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int
int16 default_width = max(desc->GetDefaultWidth(), sm_width);
int16 default_height = max(desc->GetDefaultHeight(), sm_height);
- if (desc->parent_cls != WC_NONE && (w = FindWindowById(desc->parent_cls, window_number)) != NULL) {
+ if (desc->parent_cls != WC_NONE && (w = FindWindowById(desc->parent_cls, window_number)) != nullptr) {
bool rtl = _current_text_dir == TD_RTL;
if (desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) {
pt.x = w->left + (rtl ? w->width - default_width : 0);
@@ -1857,7 +1857,7 @@ Window::Window(WindowDesc *desc) : window_desc(desc), mouse_capture_widget(-1)
* at the topmost window, obviously and work our way down to the bottom
* @param x position x to query
* @param y position y to query
- * @return a pointer to the found window if any, NULL otherwise
+ * @return a pointer to the found window if any, nullptr otherwise
*/
Window *FindWindowFromPt(int x, int y)
{
@@ -1868,7 +1868,7 @@ Window *FindWindowFromPt(int x, int y)
}
}
- return NULL;
+ return nullptr;
}
/**
@@ -1878,11 +1878,11 @@ void InitWindowSystem()
{
IConsoleClose();
- _z_back_window = NULL;
- _z_front_window = NULL;
- _focused_window = NULL;
- _mouseover_last_w = NULL;
- _last_scroll_window = NULL;
+ _z_back_window = nullptr;
+ _z_front_window = nullptr;
+ _focused_window = nullptr;
+ _mouseover_last_w = nullptr;
+ _last_scroll_window = nullptr;
_scrolling_viewport = false;
_mouse_hovering = false;
@@ -1902,14 +1902,14 @@ void UnInitWindowSystem()
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
- for (w = _z_front_window; w != NULL; /* nothing */) {
+ for (w = _z_front_window; w != nullptr; /* nothing */) {
Window *to_del = w;
w = w->z_back;
free(to_del);
}
- _z_front_window = NULL;
- _z_back_window = NULL;
+ _z_front_window = nullptr;
+ _z_back_window = nullptr;
}
/**
@@ -1932,7 +1932,7 @@ static void DecreaseWindowCounters()
/* Unclick scrollbar buttons if they are pressed. */
for (uint i = 0; i < w->nested_array_size; i++) {
NWidgetBase *nwid = w->nested_array[i];
- if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
+ if (nwid != nullptr && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
@@ -1966,7 +1966,7 @@ static void HandlePlacePresize()
if (_special_mouse_mode != WSM_PRESIZE) return;
Window *w = _thd.GetCallbackWnd();
- if (w == NULL) return;
+ if (w == nullptr) return;
Point pt = GetTileBelowCursor();
if (pt.x == -1) {
@@ -1988,7 +1988,7 @@ static EventState HandleMouseDragDrop()
if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
Window *w = _thd.GetCallbackWnd();
- if (w != NULL) {
+ if (w != nullptr) {
/* Send an event in client coordinates. */
Point pt;
pt.x = _cursor.pos.x - w->left;
@@ -2010,7 +2010,7 @@ static void HandleMouseOver()
Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
/* We changed window, put an OnMouseOver event to the last window */
- if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
+ if (_mouseover_last_w != nullptr && _mouseover_last_w != w) {
/* Reset mouse-over coordinates of previous window */
Point pt = { -1, -1 };
_mouseover_last_w->OnMouseOver(pt, 0);
@@ -2019,11 +2019,11 @@ static void HandleMouseOver()
/* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
_mouseover_last_w = w;
- if (w != NULL) {
+ if (w != nullptr) {
/* send an event in client coordinates. */
Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
- if (widget != NULL) w->OnMouseOver(pt, widget->index);
+ if (widget != nullptr) w->OnMouseOver(pt, widget->index);
}
}
@@ -2048,7 +2048,7 @@ enum PreventHideDirection {
*/
static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
{
- if (v == NULL) return;
+ if (v == nullptr) return;
int v_bottom = v->top + v->height;
int v_right = v->left + v->width;
@@ -2089,7 +2089,7 @@ static void EnsureVisibleCaption(Window *w, int nx, int ny)
/* Search for the title bar rectangle. */
Rect caption_rect;
const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
- if (caption != NULL) {
+ if (caption != nullptr) {
caption_rect.left = caption->pos_x;
caption_rect.right = caption->pos_x + caption->current_x;
caption_rect.top = caption->pos_y;
@@ -2104,7 +2104,7 @@ static void EnsureVisibleCaption(Window *w, int nx, int ny)
PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
}
- if (w->viewport != NULL) {
+ if (w->viewport != nullptr) {
w->viewport->left += nx - w->left;
w->viewport->top += ny - w->top;
}
@@ -2162,7 +2162,7 @@ void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
int GetMainViewTop()
{
Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
- return (w == NULL) ? 0 : w->top + w->height;
+ return (w == nullptr) ? 0 : w->top + w->height;
}
/**
@@ -2173,7 +2173,7 @@ int GetMainViewTop()
int GetMainViewBottom()
{
Window *w = FindWindowById(WC_STATUS_BAR, 0);
- return (w == NULL) ? _screen.height : w->top;
+ return (w == nullptr) ? _screen.height : w->top;
}
static bool _dragging_window; ///< A window is being dragged or resized.
@@ -2469,12 +2469,12 @@ static EventState HandleViewportScroll()
/* When we don't have a last scroll window we are starting to scroll.
* When the last scroll window and this are not the same we went
* outside of the window and should not left-mouse scroll anymore. */
- if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
+ if (_last_scroll_window == nullptr) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
- if (_last_scroll_window == NULL || !((_settings_client.gui.scroll_mode != VSM_MAP_LMB && _right_button_down) || scrollwheel_scrolling || (_settings_client.gui.scroll_mode == VSM_MAP_LMB && _left_button_down))) {
+ if (_last_scroll_window == nullptr || !((_settings_client.gui.scroll_mode != VSM_MAP_LMB && _right_button_down) || scrollwheel_scrolling || (_settings_client.gui.scroll_mode == VSM_MAP_LMB && _left_button_down))) {
_cursor.fix_at = false;
_scrolling_viewport = false;
- _last_scroll_window = NULL;
+ _last_scroll_window = nullptr;
return ES_NOT_HANDLED;
}
@@ -2581,7 +2581,7 @@ static bool MaybeBringWindowToFront(Window *w)
EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
{
QueryString *query = this->GetQueryString(wid);
- if (query == NULL) return ES_NOT_HANDLED;
+ if (query == nullptr) return ES_NOT_HANDLED;
int action = QueryString::ACTION_NOTHING;
@@ -2685,7 +2685,7 @@ void HandleKeypress(uint keycode, WChar key)
Window *w;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->window_class == WC_MAIN_TOOLBAR) continue;
- if (w->window_desc->hotkeys != NULL) {
+ if (w->window_desc->hotkeys != nullptr) {
int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
}
@@ -2694,8 +2694,8 @@ void HandleKeypress(uint keycode, WChar key)
w = FindWindowById(WC_MAIN_TOOLBAR, 0);
/* When there is no toolbar w is null, check for that */
- if (w != NULL) {
- if (w->window_desc->hotkeys != NULL) {
+ if (w != nullptr) {
+ if (w->window_desc->hotkeys != nullptr) {
int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
}
@@ -2725,7 +2725,7 @@ void HandleCtrlChanged()
/* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
{
QueryString *query = this->GetQueryString(wid);
- if (query == NULL) return;
+ if (query == nullptr) return;
if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
this->SetWidgetDirty(wid);
@@ -2767,11 +2767,11 @@ static void HandleAutoscroll()
int x = _cursor.pos.x;
int y = _cursor.pos.y;
Window *w = FindWindowFromPt(x, y);
- if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
+ if (w == nullptr || w->flags & WF_DISABLE_VP_SCROLL) return;
if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
ViewPort *vp = IsPtInWindowViewport(w, x, y);
- if (vp == NULL) return;
+ if (vp == nullptr) return;
x -= vp->left;
y -= vp->top;
@@ -2877,23 +2877,23 @@ static void MouseLoop(MouseClick click, int mousewheel)
int x = _cursor.pos.x;
int y = _cursor.pos.y;
Window *w = FindWindowFromPt(x, y);
- if (w == NULL) return;
+ if (w == nullptr) return;
if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
ViewPort *vp = IsPtInWindowViewport(w, x, y);
/* Don't allow any action in a viewport if either in menu or when having a modal progress window */
- if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
+ if (vp != nullptr && (_game_mode == GM_MENU || HasModalProgress())) return;
if (mousewheel != 0) {
/* Send mousewheel event to window, unless we're scrolling a viewport or the map */
- if (!scrollwheel_scrolling || (vp == NULL && w->window_class != WC_SMALLMAP)) w->OnMouseWheel(mousewheel);
+ if (!scrollwheel_scrolling || (vp == nullptr && w->window_class != WC_SMALLMAP)) w->OnMouseWheel(mousewheel);
/* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
- if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
+ if (vp == nullptr) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
}
- if (vp != NULL) {
+ if (vp != nullptr) {
if (scrollwheel_scrolling && !(w->flags & WF_DISABLE_VP_SCROLL)) {
_scrolling_viewport = true;
_cursor.fix_at = true;
@@ -2927,7 +2927,7 @@ static void MouseLoop(MouseClick click, int mousewheel)
}
}
- if (vp == NULL || (w->flags & WF_DISABLE_VP_SCROLL)) {
+ if (vp == nullptr || (w->flags & WF_DISABLE_VP_SCROLL)) {
switch (click) {
case MC_LEFT:
case MC_DOUBLE_LEFT:
@@ -2935,7 +2935,7 @@ static void MouseLoop(MouseClick click, int mousewheel)
return;
default:
- if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
+ if (!scrollwheel_scrolling || w == nullptr || w->window_class != WC_SMALLMAP) break;
/* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
* Simulate a right button click so we can get started. */
FALLTHROUGH;
@@ -3046,7 +3046,7 @@ static void CheckSoftLimit()
for (;;) {
uint deletable_count = 0;
- Window *w, *last_deletable = NULL;
+ Window *w, *last_deletable = nullptr;
FOR_ALL_WINDOWS_FROM_FRONT(w) {
if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
@@ -3057,7 +3057,7 @@ static void CheckSoftLimit()
/* We've not reached the soft limit yet. */
if (deletable_count <= _settings_client.gui.window_soft_limit) break;
- assert(last_deletable != NULL);
+ assert(last_deletable != nullptr);
delete last_deletable;
}
}
@@ -3074,7 +3074,7 @@ void InputLoop()
CheckSoftLimit();
/* Do the actual free of the deleted windows. */
- for (Window *v = _z_front_window; v != NULL; /* nothing */) {
+ for (Window *v = _z_front_window; v != nullptr; /* nothing */) {
Window *w = v;
v = v->z_back;
@@ -3184,7 +3184,7 @@ void UpdateWindows()
FOR_ALL_WINDOWS_FROM_BACK(w) {
/* Update viewport only if window is not shaded. */
- if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
+ if (w->viewport != nullptr && !w->IsShaded()) UpdateViewportPosition(w);
}
NetworkDrawChatMessage();
/* Redraw mouse cursor in case it was hidden */
@@ -3455,17 +3455,17 @@ void ReInitAllWindows()
/**
* (Re)position a window at the screen.
- * @param w Window structure of the window, may also be \c NULL.
+ * @param w Window structure of the window, may also be \c nullptr.
* @param clss The class of the window to position.
* @param setting The actual setting used for the window's position.
* @return X coordinate of left edge of the repositioned window.
*/
static int PositionWindow(Window *w, WindowClass clss, int setting)
{
- if (w == NULL || w->window_class != clss) {
+ if (w == nullptr || w->window_class != clss) {
w = FindWindowById(clss, 0);
}
- if (w == NULL) return 0;
+ if (w == nullptr) return 0;
int old_left = w->left;
switch (setting) {
@@ -3473,14 +3473,14 @@ static int PositionWindow(Window *w, WindowClass clss, int setting)
case 2: w->left = _screen.width - w->width; break;
default: w->left = 0; break;
}
- if (w->viewport != NULL) w->viewport->left += w->left - old_left;
+ if (w->viewport != nullptr) w->viewport->left += w->left - old_left;
SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
return w->left;
}
/**
* (Re)position main toolbar window at the screen.
- * @param w Window structure of the main toolbar window, may also be \c NULL.
+ * @param w Window structure of the main toolbar window, may also be \c nullptr.
* @return X coordinate of left edge of the repositioned toolbar window.
*/
int PositionMainToolbar(Window *w)
@@ -3491,7 +3491,7 @@ int PositionMainToolbar(Window *w)
/**
* (Re)position statusbar window at the screen.
- * @param w Window structure of the statusbar window, may also be \c NULL.
+ * @param w Window structure of the statusbar window, may also be \c nullptr.
* @return X coordinate of left edge of the repositioned statusbar.
*/
int PositionStatusbar(Window *w)
@@ -3502,7 +3502,7 @@ int PositionStatusbar(Window *w)
/**
* (Re)position news message window at the screen.
- * @param w Window structure of the news message window, may also be \c NULL.
+ * @param w Window structure of the news message window, may also be \c nullptr.
* @return X coordinate of left edge of the repositioned news message.
*/
int PositionNewsMessage(Window *w)
@@ -3513,7 +3513,7 @@ int PositionNewsMessage(Window *w)
/**
* (Re)position network chat window at the screen.
- * @param w Window structure of the network chat window, may also be \c NULL.
+ * @param w Window structure of the network chat window, may also be \c nullptr.
* @return X coordinate of left edge of the repositioned network chat window.
*/
int PositionNetworkChatWindow(Window *w)
@@ -3532,7 +3532,7 @@ void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
- if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
+ if (w->viewport != nullptr && w->viewport->follow_vehicle == from_index) {
w->viewport->follow_vehicle = to_index;
w->SetDirty();
}
diff --git a/src/window_gui.h b/src/window_gui.h
index 63793b0ef..db42cafcd 100644
--- a/src/window_gui.h
+++ b/src/window_gui.h
@@ -169,14 +169,14 @@ struct WindowDesc : ZeroedMemoryAllocator {
WindowDesc(WindowPosition default_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
WindowClass window_class, WindowClass parent_class, uint32 flags,
- const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys = NULL);
+ const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys = nullptr);
~WindowDesc();
WindowPosition default_pos; ///< Preferred position of the window. @see WindowPosition()
WindowClass cls; ///< Class of the window, @see WindowClass.
WindowClass parent_cls; ///< Class of the parent window. @see WindowClass
- const char *ini_key; ///< Key to store window defaults in openttd.cfg. \c NULL if nothing shall be stored.
+ const char *ini_key; ///< Key to store window defaults in openttd.cfg. \c nullptr if nothing shall be stored.
uint32 flags; ///< Flags. @see WindowDefaultFlag
const NWidgetPart *nwid_parts; ///< Nested widget parts describing the window.
int16 nwid_length; ///< Length of the #nwid_parts array.
@@ -326,12 +326,12 @@ public:
Owner owner; ///< The owner of the content shown in this window. Company colour is acquired from this variable.
ViewportData *viewport; ///< Pointer to viewport data, if present.
- const NWidgetCore *nested_focus; ///< Currently focused nested widget, or \c NULL if no nested widget has focus.
+ const NWidgetCore *nested_focus; ///< Currently focused nested widget, or \c nullptr if no nested widget has focus.
SmallMap<int, QueryString*> querystrings; ///< QueryString associated to WWT_EDITBOX widgets.
NWidgetBase *nested_root; ///< Root of the nested tree.
NWidgetBase **nested_array; ///< Array of pointers into the tree. Do not access directly, use #Window::GetWidget() instead.
uint nested_array_size; ///< Size of the nested array.
- NWidgetStacked *shade_select; ///< Selection widget (#NWID_SELECTION) to use for shading the window. If \c NULL, window cannot shade.
+ NWidgetStacked *shade_select; ///< Selection widget (#NWID_SELECTION) to use for shading the window. If \c nullptr, window cannot shade.
Dimension unshaded_size; ///< Last known unshaded size (only valid while shaded).
int mouse_capture_widget; ///< Widgetindex of current mouse capture widget (e.g. dragged scrollbar). -1 if no widget has mouse capture.
@@ -394,7 +394,7 @@ public:
inline void SetWidgetDisabledState(byte widget_index, bool disab_stat)
{
assert(widget_index < this->nested_array_size);
- if (this->nested_array[widget_index] != NULL) this->GetWidget<NWidgetCore>(widget_index)->SetDisabled(disab_stat);
+ if (this->nested_array[widget_index] != nullptr) this->GetWidget<NWidgetCore>(widget_index)->SetDisabled(disab_stat);
}
/**
@@ -433,7 +433,7 @@ public:
*/
inline bool IsWidgetFocused(byte widget_index) const
{
- return this->nested_focus != NULL && this->nested_focus->index == widget_index;
+ return this->nested_focus != nullptr && this->nested_focus->index == widget_index;
}
/**
@@ -525,7 +525,7 @@ public:
/** Is window shaded currently? */
inline bool IsShaded() const
{
- return this->shade_select != NULL && this->shade_select->shown_plane == SZSP_HORIZONTAL;
+ return this->shade_select != nullptr && this->shade_select->shown_plane == SZSP_HORIZONTAL;
}
void SetShaded(bool make_shaded);
@@ -734,7 +734,7 @@ public:
/**
* The query window opened from this window has closed.
- * @param str the new value of the string, NULL if the window
+ * @param str the new value of the string, nullptr if the window
* was cancelled or an empty string when the default
* button was pressed, i.e. StrEmpty(str).
*/
@@ -818,14 +818,14 @@ public:
* Get the nested widget with number \a widnum from the nested widget tree.
* @tparam NWID Type of the nested widget.
* @param widnum Widget number of the widget to retrieve.
- * @return The requested widget if it is instantiated, \c NULL otherwise.
+ * @return The requested widget if it is instantiated, \c nullptr otherwise.
*/
template <class NWID>
inline NWID *Window::GetWidget(uint widnum)
{
- if (widnum >= this->nested_array_size || this->nested_array[widnum] == NULL) return NULL;
+ if (widnum >= this->nested_array_size || this->nested_array[widnum] == nullptr) return nullptr;
NWID *nwid = dynamic_cast<NWID *>(this->nested_array[widnum]);
- assert(nwid != NULL);
+ assert(nwid != nullptr);
return nwid;
}
@@ -833,7 +833,7 @@ inline NWID *Window::GetWidget(uint widnum)
template <>
inline const NWidgetBase *Window::GetWidget<NWidgetBase>(uint widnum) const
{
- if (widnum >= this->nested_array_size) return NULL;
+ if (widnum >= this->nested_array_size) return nullptr;
return this->nested_array[widnum];
}
@@ -841,7 +841,7 @@ inline const NWidgetBase *Window::GetWidget<NWidgetBase>(uint widnum) const
* Get the nested widget with number \a widnum from the nested widget tree.
* @tparam NWID Type of the nested widget.
* @param widnum Widget number of the widget to retrieve.
- * @return The requested widget if it is instantiated, \c NULL otherwise.
+ * @return The requested widget if it is instantiated, \c nullptr otherwise.
*/
template <class NWID>
inline const NWID *Window::GetWidget(uint widnum) const
@@ -873,26 +873,26 @@ Window *FindWindowFromPt(int x, int y);
* @param desc The pointer to the WindowDesc to be created
* @param window_number the window number of the new window
* @param return_existing If set, also return the window if it already existed.
- * @return %Window pointer of the newly created window, or the existing one if \a return_existing is set, or \c NULL.
+ * @return %Window pointer of the newly created window, or the existing one if \a return_existing is set, or \c nullptr.
*/
template <typename Wcls>
Wcls *AllocateWindowDescFront(WindowDesc *desc, int window_number, bool return_existing = false)
{
Wcls *w = static_cast<Wcls *>(BringWindowToFrontById(desc->cls, window_number));
- if (w != NULL) return return_existing ? w : NULL;
+ if (w != nullptr) return return_existing ? w : nullptr;
return new Wcls(desc, window_number);
}
void RelocateAllWindows(int neww, int newh);
-void GuiShowTooltips(Window *parent, StringID str, uint paramcount = 0, const uint64 params[] = NULL, TooltipCloseCondition close_tooltip = TCC_HOVER);
+void GuiShowTooltips(Window *parent, StringID str, uint paramcount = 0, const uint64 params[] = nullptr, TooltipCloseCondition close_tooltip = TCC_HOVER);
/* widget.cpp */
int GetWidgetFromPos(const Window *w, int x, int y);
/** Iterate over all windows */
-#define FOR_ALL_WINDOWS_FROM_BACK_FROM(w, start) for (w = start; w != NULL; w = w->z_front) if (w->window_class != WC_INVALID)
-#define FOR_ALL_WINDOWS_FROM_FRONT_FROM(w, start) for (w = start; w != NULL; w = w->z_back) if (w->window_class != WC_INVALID)
+#define FOR_ALL_WINDOWS_FROM_BACK_FROM(w, start) for (w = start; w != nullptr; w = w->z_front) if (w->window_class != WC_INVALID)
+#define FOR_ALL_WINDOWS_FROM_FRONT_FROM(w, start) for (w = start; w != nullptr; w = w->z_back) if (w->window_class != WC_INVALID)
#define FOR_ALL_WINDOWS_FROM_BACK(w) FOR_ALL_WINDOWS_FROM_BACK_FROM(w, _z_back_window)
#define FOR_ALL_WINDOWS_FROM_FRONT(w) FOR_ALL_WINDOWS_FROM_FRONT_FROM(w, _z_front_window)