diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..4036514d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.5.1) + +project(RCSSServer VERSION 17.0.0) + +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "" FORCE) +endif() +set(CMAKE_CXX_FLAGS "-W -Wall") + +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON) + +find_package(ZLIB REQUIRED) +if(ZLIB_FOUND) + set(HAVE_LIBZ TRUE) +endif() +find_package(BISON REQUIRED) +find_package(FLEX REQUIRED) +find_package(Boost COMPONENTS system filesystem REQUIRED) + +include(GNUInstallDirs) +include(CheckIncludeFileCXX) + +check_include_file_cxx("sys/socket.h" HAVE_SYS_SOCKET_H) +check_include_file_cxx("sys/param.h" HAVE_SYS_PARAM_H) +check_include_file_cxx("sys/time.h" HAVE_SYS_TIME_H) +check_include_file_cxx("netinet/in.h" HAVE_NETINET_IN_H) +check_include_file_cxx("arpa/inet.h" HAVE_ARPA_INET_H) +check_include_file_cxx("netdb.h" HAVE_NETDB_H) +check_include_file_cxx("unistd.h" HAVE_UNISTD_H) +check_include_file_cxx("poll.h" HAVE_POLL_H) +check_include_file_cxx("pwd.h" HAVE_PWD_H) + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.cmake config.h) + +add_subdirectory(rcss) +add_subdirectory(src) diff --git a/ChangeLog b/ChangeLog index 04d0b644..3df2589d 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,12 @@ +2022-04-02 Hidehisa Akiyama + + * CMakeLists.txt: + * NEWS: + * configure.ac: + - update a major version number. Official release 17.0.0 + - improve the dash model and the catch model + - support a JSON-based monitor protocol. + 2021-07-20 Hidehisa Akiyama * NEWS: diff --git a/Makefile.am b/Makefile.am index c9d14d5d..b72bae7c 100644 --- a/Makefile.am +++ b/Makefile.am @@ -5,12 +5,14 @@ libtool: $(LIBTOOL_DEPS) $(SHELL) ./config.status --recheck SUBDIRS = \ - rcssbase \ + rcss \ src \ . EXTRA_DIST = \ - README.md + README.md \ + CMakeLists.txt \ + config.h.cmake CLEANFILES = \ *~ \ diff --git a/NEWS b/NEWS index 6e481d7c..ef2f6066 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,41 @@ +[17.0.0] + * New parameters: + - server::max_catch_angle (default value: 90.0) + - server::min_catch_angle (default value: -90.0) + + * Changed parameters: + - server::min_dash_power (-100.0 -> 0) + - server::back_dash_rate (0.6 -> 0.7) + + * Improvement of the catch model. The direction of goalie's catch + command has been restricted within [server::min_catch_angle, + server::max_catch_angle]. The default values are [-90.0, 90.0]. + This setting means goalies cannot catch the ball behind them. + + * Improvement of the dash model. server::min_dash_power is changed + from -100.0 to 0.0. This means players cannot use the negative + power in order for them to accelerate backward. If players would + like to accelerate backward, they need to use the omnidirectional + dash. In connection with the change of the dash power, + server::back_dash_rate has been changed. + + * Support a JSON-based monitor protocol. If the monitor tries to + connect to the server by the client version 5, the received + messages will be JSON. The format of the game log file (.rcg) has + also followed the monitor protocol. If the value of + server::game_log_version is 6, the content of the recorded game + log is a JSON array except for the header line. + + * The installation destination of the library header files has been + unified under PREFIX/include/rcss. The location of the clang + parser library has been moved to prefix/include/rcss/clang. + + * Support CMake. Thanks to gikari for providing his great + contribution on GitHub. + + * Support C++11/14. Some environment-dependent implementations have + been replaced by the C++ standard library. + [16.0.1] * Fix a bug of the length of half time caused by slow_down_factor. diff --git a/README.md b/README.md index 203a007e..bc82a8e5 100644 --- a/README.md +++ b/README.md @@ -7,47 +7,68 @@ The RoboCup Soccer Simulator Server (rcssserver) is a research and educational tool for multi-agent systems and artificial intelligence. It allows 11 simulated autonomous robotic players to play soccer (football). -## Quick Start +For further reading, please check [the user's manual](https://rcsoccersim.readthedocs.io/). +## :soccer: Quick Start + +rcssserver is implemented by C++14 and depends some libraries. Make sure you have the required dependencies installed on your system: -- g++ -- make -- boost -- bison +- g++ (which supports C++14) +- autoconf +- automake +- libtool - flex +- bison +- boost >= 1.44 + +In the case of Ubuntu 18.04 or 20.04, the following commands will resolve all dependencies: + +``` +sudo apt update +sudo apt install build-essential automake autoconf libtool flex bison libboost-all-dev +``` -Download the latest rcssserver release in the [releases section](https://github.com/rcsoccersim/rcssserver/releases). Extract it and from the rcssserver directory execute: +Then, download the latest rcssserver tarball from the [releases section](https://github.com/rcsoccersim/rcssserver/releases). +Extract it and from the rcssserver directory execute: ```bash +tar xzvfp rcssserver-x.x.x.tar.gz +cd rcssserver-x.x.x ./configure make ``` This will build the necessary binaries to get you up and running. +`rcssserver/src/rcssserver` is the binary for the simulator server. -`rcssserver/src/rcssserver` is the binary for the simulator server. The simulator -server manages the actual simulation and comunicates with client programs that -control the simulated robots. To be able to run, the binary needs to find shared -libraries which are created when you build rcssserver. This means you must either -install the server (make install) or run it from `rcssserver/src`. +The simulator server manages the actual simulation and comunicates with client programs that +control the simulated robots. +To be able to run, the binary needs to find shared libraries which are created when you build rcssserver. +This means you must either install the server (make install) or run it from `rcssserver/src`. A sample client can be found at `rcssserver/src/rcssclient`. To see what is actually happening in the simulator, you will need to start a -simulator monitor, which needs to be installed separately ([rcssmonitor](https://github.com/rcsoccersim/rcssmonitor), - rcssmonitor_classic, [soccerwindow2](https://osdn.net/projects/rctools/releases/p4886) - or any other third party monitor). +simulator monitor, which needs to be installed separately ([rcssmonitor](https://github.com/rcsoccersim/rcssmonitor), or any other third party monitor). -To playback games that that you have recorded or downloaded, you will need to -start the log player such as [rcsslogplayer](https://github.com/rcsoccersim/rcsslogplayer), -which must also be downloaded separately. +To playback games that you have recorded or downloaded, you will need to start the log player. +[rcssmonitor](https://github.com/rcsoccersim/rcssmonitor) can be used for this purpose. -## Configuring +The version 17.0.0 or later support [CMake](https://cmake.org/). +If CMake is prefered or problems with the above procedure, try the following commands at the top of the project directory: -Before you can build The RoboCup Soccer Simulator Server you will need to run -the `configure` script located in the root of the distribution directory. +```bash +cd rcssserver-x.x.x +mkdir build +cd build +cmake .. +make +``` + +## :gear: Configuring +Before building rcssserver, you will need to run the `configure` script located in the root of the distribution directory. The default configuration will set up to install the server components in the following location: @@ -56,6 +77,9 @@ following location: You may need administrator privileges to install the server into the default location. This locations can be modified by using configure's `--prefix=DIR` and related options. See `configure --help` for more details. +```bash +./configure --prefix=YOUR_INSTALLATION_DIR +``` The server has several features that can be enabled or disabled at configure time by using the `--enable-FEATURE[=ARG]` or `--disable-FEATURE` parameters to @@ -63,14 +87,11 @@ by using the `--enable-FEATURE[=ARG]` or `--disable-FEATURE` parameters to `--enable-FEATURE` is equivalent to `--enable-FEATURE=yes`. The only valid values for `ARG` are `yes` and `no`. -`--enable-fast_scanner=yes` will enable a fast building but (very) large -scanner for the coach language. You will need to have `lex` or `flex` installed -and you will need to manually remove the `coach_lang_tok.cc` file in the -`rcssserver/src` directory. This is disabled by default. I found the actual -speed of the parser show only minimal improvement when using this option on my -system, but this may not be true on your system. All I can suggest is to test it -on your system and decide for yourself if the speed increase justifies the -increase in size of the executable. +`--enable-fast_scanner=yes` will enable a fast building but (very) large scanner for the coach language. +You will need to have `flex` installed and you will need to manually remove the `coach_lang_tok.cpp` file in the `rcssserver/rcss/clang` directory. +This is disabled by default. +I found the actual speed of the parser show only minimal improvement when using this option on my system, but this may not be true on your system. +All I can suggest is to test it on your system and decide for yourself if the speed increase justifies the increase in size of the executable. `--enable-rcssclient=yes` will enable the building of rcssclient, a sample client program. This is enabled by default. @@ -78,52 +99,77 @@ client program. This is enabled by default. `--enable-debug=yes` will enable the building of the modules with debugging information. This is disabled by default. +Once you have successfully configured the monitor, simply run `make` to build the sources. -## Building +If CMake is chosen, `ccmake` command is available for the configuration: +```bash +cd build +ccmake .. +``` + +## :hammer_and_wrench: Building Once you have successfully configured the server, simply run `make` to build the sources. -## Installing +## :package: Installing When you have completed building the server, its components can be installed into their default locations or the locations specified during configuring by -running `make install`. Depending on where you are installing the -server, you may need special permissions. +running +```bash +make install +``` +Depending on where you are installing the server, you may need special permissions. -## Uninstalling +## :wastebasket: Uninstalling The server can also be easily removed by entering the distribution directory and -running `make uninstall`. This will remove all the files that where installed, +running +```bash +make uninstall +``` + +This will remove all the files that where installed, but not any directories that were created during the installation process. -## Using the Server +In the case of CMake, find `install_manifest.txt` under the build directory, then execute: +```bash +xargs rm < install_manifest.txt +``` -To start only the server either type `./rcssserver` from the directory -containing the executable or `rcssserver` if you installed the executables -in your PATH. rcssserver will look in your home directory for the configuration files: +## :arrow_forward: Using the Server +To start only the server either type `./rcssserver` from the directory +containing the executable or `rcssserver` if you installed the executables +in your PATH. ```bash -~/.rcssserver/server.conf -~/.rcssserver/player.conf -~/.rcssserver-landmark.xml # (optional) +rcssserver ``` +rcssserver will look in your home directory for the configuration files: + +- ~/.rcssserver/server.conf +- ~/.rcssserver/player.conf +- ~/.rcssserver/CSVSaver.conf +- ~/.rcssserver-landmark.xml (optional) If these files do not exist they will be created and populated with default values. -To start the sample client, type `./rcssclient` or `rcssclient` as above. Then type -`(init sample)`. This will connect the sample client to the server. You can then -type in client command to move the client around the field. You will also need a +To start the sample client, type `./rcssclient` or `rcssclient` as above. Then type +`(init sample)`. This will connect the sample client to the server. You can then +type in client command to move the client around the field. You will also need a monitor to be able to see whats happening on the field. If you installed the server and the monitor successfully, you can use the `rcsoccersim` script. To start the simulator (server and monitor) either type: -`rcsoccersim` - +```bash +rcsoccersim +``` -## Contributing +## :incoming_envelope: Contributing -For bug reports, feature requests and latest updates, please open an issue or a pull request. +For bug reports, feature requests and latest updates, please goto +https://github.com/rcsoccersim/rcssserver and open an issue or a pull request. > The RoboCup Soccer Server Maintainance Group diff --git a/config.h.cmake b/config.h.cmake new file mode 100644 index 00000000..e54b6233 --- /dev/null +++ b/config.h.cmake @@ -0,0 +1,18 @@ +#define VERSION "${PROJECT_VERSION}" +#define PACKAGE "rcssserver" + +#cmakedefine HAVE_LIBZ 1 +#cmakedefine HAVE_SYS_SOCKET_H 1 +#cmakedefine HAVE_NETINET_IN_H 1 +#cmakedefine HAVE_ARPA_INET_H 1 +#cmakedefine HAVE_POLL_H 1 +#cmakedefine HAVE_NETDB_H 1 +#cmakedefine HAVE_SYS_TIME_H 1 +#cmakedefine HAVE_PWD_H 1 +#cmakedefine HAVE_SYS_PARAM_H 1 +#cmakedefine HAVE_UNISTD_H 1 +#cmakedefine HAVE_SYS_TYPES_H 1 +#cmakedefine HAVE_STDINT_H 1 +#cmakedefine HAVE_STDDEF_H 1 + +#define HAVE_SOCKLEN_T 1 diff --git a/configure.ac b/configure.ac index b38d7c3b..78bdb0f6 100644 --- a/configure.ac +++ b/configure.ac @@ -3,7 +3,7 @@ AC_PREREQ(2.61) LT_PREREQ([2.2]) -AC_INIT([RCSSServer],[16.0.1],[sserver-admin@users.sf.net],[rcssserver]) +AC_INIT([RCSSServer],[17.0.0],[https://github.com/rcsoccersim/],[rcssserver]) #AM_INIT_AUTOMAKE([gnu 1.7.2 check-news dist-bzip2 dist-zip]) AM_INIT_AUTOMAKE([gnu 1.7.2 check-news foreign]) @@ -34,18 +34,13 @@ AC_PROG_MAKE_SET AC_CHECK_LIB([m], [cos]) dnl AC_CHECK_LIB(expat, XML_Parse) #AC_CHECK_LIB([z], [deflate]) -AC_SUBST(GZ_LIBS) -AC_CHECK_LIB([z], [deflate], - [AC_DEFINE([HAVE_LIBZ], [1], - [Define to 1 if you have the `z' library (-lz).]) - GZ_LIBS="-lz"]) - -AC_ARG_WITH(sstream, - AS_HELP_STRING(--with-sstream,use sstream instead of strstream (default=yes)), - use_sstream=$withval, use_sstream=yes) -if test "$use_sstream" = "yes"; then - AC_CXX_HAVE_SSTREAM -fi +#AC_SUBST(GZ_LIBS) +#AC_CHECK_LIB([z], [deflate], +# [AC_DEFINE([HAVE_LIBZ], [1], +# [Define to 1 if you have the `z' library (-lz).]) +# GZ_LIBS="-lz"]) +AX_CHECK_ZLIB([], + [AC_MSG_NOTICE(Zlib not found.)]) ################################################## # Checks for header files. @@ -250,10 +245,11 @@ fi ################################################## AC_CONFIG_FILES([Makefile - rcssbase/Makefile - rcssbase/net/Makefile - rcssbase/conf/Makefile - rcssbase/gzip/Makefile + rcss/Makefile + rcss/net/Makefile + rcss/conf/Makefile + rcss/gzip/Makefile + rcss/clang/Makefile src/Makefile src/rcsoccersim], [test -f src/rcsoccersim && chmod +x src/rcsoccersim]) diff --git a/m4/ac_cxx_have_sstream.m4 b/m4/ac_cxx_have_sstream.m4 deleted file mode 100644 index 15be8408..00000000 --- a/m4/ac_cxx_have_sstream.m4 +++ /dev/null @@ -1,20 +0,0 @@ -dnl Available from the GNU Autoconf Macro Archive at: -dnl http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_have_sstream.html -dnl -AC_DEFUN([AC_CXX_HAVE_SSTREAM], -[AC_CACHE_CHECK(whether the compiler has stringstream, -ac_cv_cxx_have_sstream, -[AC_REQUIRE([AC_CXX_NAMESPACES]) - AC_LANG_SAVE - AC_LANG_CPLUSPLUS - AC_TRY_COMPILE([#include -#ifdef HAVE_NAMESPACES -using namespace std; -#endif],[stringstream message; message << "Hello"; return 0;], - ac_cv_cxx_have_sstream=yes, ac_cv_cxx_have_sstream=no) - AC_LANG_RESTORE -]) -if test "$ac_cv_cxx_have_sstream" = yes; then - AC_DEFINE(HAVE_SSTREAM,,[define if the compiler has stringstream]) -fi -]) diff --git a/m4/ac_cxx_namespaces.m4 b/m4/ac_cxx_namespaces.m4 deleted file mode 100644 index 37510c06..00000000 --- a/m4/ac_cxx_namespaces.m4 +++ /dev/null @@ -1,17 +0,0 @@ -dnl Available from the GNU Autoconf Macro Archive at: -dnl http://www.gnu.org/software/ac-archive/htmldoc/ac_cxx_namespaces.html -dnl -AC_DEFUN([AC_CXX_NAMESPACES], -[AC_CACHE_CHECK(whether the compiler implements namespaces, -ac_cv_cxx_namespaces, -[AC_LANG_SAVE - AC_LANG_CPLUSPLUS - AC_TRY_COMPILE([namespace Outer { namespace Inner { int i = 0; }}], - [using namespace Outer::Inner; return i;], - ac_cv_cxx_namespaces=yes, ac_cv_cxx_namespaces=no) - AC_LANG_RESTORE -]) -if test "$ac_cv_cxx_namespaces" = yes; then - AC_DEFINE(HAVE_NAMESPACES,,[define if the compiler implements namespaces]) -fi -]) diff --git a/m4/ax_boost_base.m4 b/m4/ax_boost_base.m4 index 16fa69b4..519f1c9d 100644 --- a/m4/ax_boost_base.m4 +++ b/m4/ax_boost_base.m4 @@ -33,7 +33,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 47 +#serial 49 # example boost program (need to pass version) m4_define([_AX_BOOST_BASE_PROGRAM], @@ -114,7 +114,7 @@ AC_DEFUN([_AX_BOOST_BASE_RUNDETECT],[ AS_CASE([${host_cpu}], [x86_64],[libsubdirs="lib64 libx32 lib lib64"], [mips*64*],[libsubdirs="lib64 lib32 lib lib64"], - [ppc64|powerpc64|s390x|sparc64|aarch64|ppc64le|powerpc64le|riscv64],[libsubdirs="lib64 lib lib64"], + [ppc64|powerpc64|s390x|sparc64|aarch64|ppc64le|powerpc64le|riscv64|e2k],[libsubdirs="lib64 lib lib64"], [libsubdirs="lib"] ) @@ -123,6 +123,7 @@ AC_DEFUN([_AX_BOOST_BASE_RUNDETECT],[ dnl are almost assuredly the ones desired. AS_CASE([${host_cpu}], [i?86],[multiarch_libsubdir="lib/i386-${host_os}"], + [armv7l],[multiarch_libsubdir="lib/arm-${host_os}"], [multiarch_libsubdir="lib/${host_cpu}-${host_os}"] ) diff --git a/m4/ax_check_zlib.m4 b/m4/ax_check_zlib.m4 new file mode 100644 index 00000000..1a168430 --- /dev/null +++ b/m4/ax_check_zlib.m4 @@ -0,0 +1,141 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_check_zlib.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CHECK_ZLIB([action-if-found], [action-if-not-found]) +# +# DESCRIPTION +# +# This macro searches for an installed zlib library. If nothing was +# specified when calling configure, it searches first in /usr/local and +# then in /usr, /opt/local and /sw. If the --with-zlib=DIR is specified, +# it will try to find it in DIR/include/zlib.h and DIR/lib/libz.a. If +# --without-zlib is specified, the library is not searched at all. +# +# If either the header file (zlib.h) or the library (libz) is not found, +# shell commands 'action-if-not-found' is run. If 'action-if-not-found' is +# not specified, the configuration exits on error, asking for a valid zlib +# installation directory or --without-zlib. +# +# If both header file and library are found, shell commands +# 'action-if-found' is run. If 'action-if-found' is not specified, the +# default action appends '-I${ZLIB_HOME}/include' to CPFLAGS, appends +# '-L$ZLIB_HOME}/lib' to LDFLAGS, prepends '-lz' to LIBS, and calls +# AC_DEFINE(HAVE_LIBZ). You should use autoheader to include a definition +# for this symbol in a config.h file. Sample usage in a C/C++ source is as +# follows: +# +# #ifdef HAVE_LIBZ +# #include +# #endif /* HAVE_LIBZ */ +# +# LICENSE +# +# Copyright (c) 2008 Loic Dachary +# Copyright (c) 2010 Bastien Chevreux +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation; either version 2 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 16 + +AU_ALIAS([CHECK_ZLIB], [AX_CHECK_ZLIB]) +AC_DEFUN([AX_CHECK_ZLIB], +# +# Handle user hints +# +[AC_MSG_CHECKING(if zlib is wanted) +zlib_places="/usr/local /usr /opt/local /sw" +AC_ARG_WITH([zlib], +[ --with-zlib=DIR root directory path of zlib installation @<:@defaults to + /usr/local or /usr if not found in /usr/local@:>@ + --without-zlib to disable zlib usage completely], +[if test "$withval" != no ; then + AC_MSG_RESULT(yes) + if test -d "$withval" + then + zlib_places="$withval $zlib_places" + else + AC_MSG_WARN([Sorry, $withval does not exist, checking usual places]) + fi +else + zlib_places= + AC_MSG_RESULT(no) +fi], +[AC_MSG_RESULT(yes)]) + +# +# Locate zlib, if wanted +# +if test -n "${zlib_places}" +then + # check the user supplied or any other more or less 'standard' place: + # Most UNIX systems : /usr/local and /usr + # MacPorts / Fink on OSX : /opt/local respectively /sw + for ZLIB_HOME in ${zlib_places} ; do + if test -f "${ZLIB_HOME}/include/zlib.h"; then break; fi + ZLIB_HOME="" + done + + ZLIB_OLD_LDFLAGS=$LDFLAGS + ZLIB_OLD_CPPFLAGS=$CPPFLAGS + if test -n "${ZLIB_HOME}"; then + LDFLAGS="$LDFLAGS -L${ZLIB_HOME}/lib" + CPPFLAGS="$CPPFLAGS -I${ZLIB_HOME}/include" + fi + AC_LANG_PUSH([C]) + AC_CHECK_LIB([z], [inflateEnd], [zlib_cv_libz=yes], [zlib_cv_libz=no]) + AC_CHECK_HEADER([zlib.h], [zlib_cv_zlib_h=yes], [zlib_cv_zlib_h=no]) + AC_LANG_POP([C]) + if test "$zlib_cv_libz" = "yes" && test "$zlib_cv_zlib_h" = "yes" + then + # + # If both library and header were found, action-if-found + # + m4_ifblank([$1],[ + CPPFLAGS="$CPPFLAGS -I${ZLIB_HOME}/include" + LDFLAGS="$LDFLAGS -L${ZLIB_HOME}/lib" + LIBS="-lz $LIBS" + AC_DEFINE([HAVE_LIBZ], [1], + [Define to 1 if you have `z' library (-lz)]) + ],[ + # Restore variables + LDFLAGS="$ZLIB_OLD_LDFLAGS" + CPPFLAGS="$ZLIB_OLD_CPPFLAGS" + $1 + ]) + else + # + # If either header or library was not found, action-if-not-found + # + m4_default([$2],[ + AC_MSG_ERROR([either specify a valid zlib installation with --with-zlib=DIR or disable zlib usage with --without-zlib]) + ]) + fi +fi +]) diff --git a/m4/ax_cxx_compile_stdcxx.m4 b/m4/ax_cxx_compile_stdcxx.m4 index 43087b2e..51a35054 100644 --- a/m4/ax_cxx_compile_stdcxx.m4 +++ b/m4/ax_cxx_compile_stdcxx.m4 @@ -10,13 +10,13 @@ # # Check for baseline language coverage in the compiler for the specified # version of the C++ standard. If necessary, add switches to CXX and -# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) -# or '14' (for the C++14 standard). +# CXXCPP to enable support. VERSION may be '11', '14', '17', or '20' for +# the respective C++ standard version. # # The second argument, if specified, indicates whether you insist on an # extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. # -std=c++11). If neither is specified, you get whatever works, with -# preference for an extended mode. +# preference for no added switch, and then for an extended mode. # # The third argument, if specified 'mandatory' or if left unspecified, # indicates that baseline support for the specified C++ standard is @@ -35,13 +35,15 @@ # Copyright (c) 2015 Moritz Klammler # Copyright (c) 2016, 2018 Krzesimir Nowak # Copyright (c) 2019 Enji Cooper +# Copyright (c) 2020 Jason Merrill +# Copyright (c) 2021 Jörn Heusipp # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 11 +#serial 14 dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro dnl (serial version number 13). @@ -50,6 +52,7 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], [$1], [14], [ax_cxx_compile_alternatives="14 1y"], [$1], [17], [ax_cxx_compile_alternatives="17 1z"], + [$1], [20], [ax_cxx_compile_alternatives="20"], [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl m4_if([$2], [], [], [$2], [ext], [], @@ -62,6 +65,16 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl AC_LANG_PUSH([C++])dnl ac_success=no + m4_if([$2], [], [dnl + AC_CACHE_CHECK(whether $CXX supports C++$1 features by default, + ax_cv_cxx_compile_cxx$1, + [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [ax_cv_cxx_compile_cxx$1=yes], + [ax_cv_cxx_compile_cxx$1=no])]) + if test x$ax_cv_cxx_compile_cxx$1 = xyes; then + ac_success=yes + fi]) + m4_if([$2], [noext], [], [dnl if test x$ac_success = xno; then for alternative in ${ax_cxx_compile_alternatives}; do @@ -140,7 +153,6 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 ) - dnl Test body for checking C++14 support m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], @@ -148,12 +160,24 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 ) +dnl Test body for checking C++17 support + m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 ) +dnl Test body for checking C++20 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_20], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_20 +) + + dnl Tests for new features in C++11 m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ @@ -949,3 +973,33 @@ namespace cxx17 #endif // __cplusplus < 201703L ]]) + + +dnl Tests for new features in C++20 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_20], [[ + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 202002L + +#error "This is not a C++20 compiler" + +#else + +#include + +namespace cxx20 +{ + +// As C++20 supports feature test macros in the standard, there is no +// immediate need to actually test for feature availability on the +// Autoconf side. + +} // namespace cxx20 + +#endif // __cplusplus < 202002L + +]]) diff --git a/rcss/CMakeLists.txt b/rcss/CMakeLists.txt new file mode 100644 index 00000000..d6033a4b --- /dev/null +++ b/rcss/CMakeLists.txt @@ -0,0 +1,42 @@ +add_subdirectory(net) +add_subdirectory(conf) +add_subdirectory(gzip) +add_subdirectory(clang) + +add_library(RCSSBase INTERFACE) +add_library(RCSS::Base ALIAS RCSSBase) + +target_compile_definitions(RCSSBase + INTERFACE + HAVE_CONFIG_H +) + +target_include_directories(RCSSBase + INTERFACE + ${PROJECT_SOURCE_DIR} + ${PROJECT_BINARY_DIR} +) + +#set_property(TARGET RCSSBase PROPERTY +# PUBLIC_HEADER +# factory.hpp +# parser.h +#) + +target_link_libraries(RCSSBase + INTERFACE + Boost::boost + Boost::system + Boost::filesystem +) + +#install(TARGETS RCSSBase +# PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rcssbase +#) + +install(FILES + factory.hpp + parser.h + vector.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rcss +) diff --git a/rcss/Makefile.am b/rcss/Makefile.am new file mode 100644 index 00000000..860d22e9 --- /dev/null +++ b/rcss/Makefile.am @@ -0,0 +1,21 @@ + +SUBDIRS = net conf gzip clang + +rcssincludedir = $(includedir)/rcss + +rcssinclude_HEADERS = \ + factory.hpp \ + parser.h \ + vector.h + +AM_CPPFLAGS = -I$(top_srcdir) +AM_CFLAGS = -W -Wall +AM_CXXFLAGS = -W -Wall +AM_LDFLAGS = + +EXTRA_DIST = \ + CMakeLists.txt + +CLEANFILES = \ + *~ \ + core diff --git a/rcss/clang/CMakeLists.txt b/rcss/clang/CMakeLists.txt new file mode 100644 index 00000000..ada40c31 --- /dev/null +++ b/rcss/clang/CMakeLists.txt @@ -0,0 +1,107 @@ + +bison_target(coach_lang_parser + coach_lang_parser.ypp + ${CMAKE_CURRENT_BINARY_DIR}/coach_lang_parser.cpp + DEFINES_FILE ${CMAKE_CURRENT_BINARY_DIR}/coach_lang_parser.hpp +) +flex_target(coach_lang_tokenizer + coach_lang_tok.lpp + ${CMAKE_CURRENT_BINARY_DIR}/raw_coach_lang_tok.cpp +) +add_flex_bison_dependency(coach_lang_tokenizer coach_lang_parser) +add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/coach_lang_tok.cpp" + COMMAND ${CMAKE_COMMAND} + ARGS + "-DGENERATED_FILE_PATH=\"${CMAKE_CURRENT_BINARY_DIR}/raw_coach_lang_tok.cpp\"" + "-DCORRECT_HEADER_NAME=coach_lang_tok.h" + "-DOUTPUT_FILE_PATH=\"${CMAKE_CURRENT_BINARY_DIR}/coach_lang_tok.cpp\"" + "-P" "${CMAKE_CURRENT_SOURCE_DIR}/fix_lexer_file.cmake" + MAIN_DEPENDENCY "${CMAKE_CURRENT_BINARY_DIR}/raw_coach_lang_tok.cpp" +) + +add_library(RCSSCLangParser SHARED + clangbuilder.cpp + clangmsgbuilder.cpp + clangparser.cpp + clangmsg.cpp + clangmetamsg.cpp + clangfreeformmsg.cpp + clangunsuppmsg.cpp + clangrulemsg.cpp + clangdelmsg.cpp + clanginfomsg.cpp + clangadvicemsg.cpp + clangdefmsg.cpp + clangaction.cpp + clangutil.cpp + coach_lang_comp.cpp + arithop.cpp + cond.cpp + compop.cpp + region.cpp + rule.cpp + ${CMAKE_CURRENT_BINARY_DIR}/coach_lang_parser.cpp + ${CMAKE_CURRENT_BINARY_DIR}/coach_lang_tok.cpp + ) + +add_library(RCSS::CLangParser ALIAS RCSSCLangParser) + + +target_link_libraries(RCSSCLangParser + PUBLIC + Boost::boost + ) + +target_compile_definitions(RCSSCLangParser + PUBLIC + HAVE_CONFIG_H + ) + +target_include_directories(RCSSCLangParser + PUBLIC + ${PROJECT_SOURCE_DIR} + ${PROJECT_BINARY_DIR} + ) + +set_target_properties(RCSSCLangParser + PROPERTIES + SOVERSION 2 + VERSION 2.1.0 + LIBRARY_OUTPUT_NAME "rcssclangparser" + ) + + +set_property(TARGET RCSSCLangParser PROPERTY + PUBLIC_HEADER + clangparser.h + coach_lang_tok.h + clangbuilder.h + clangmsgbuilder.h + clangmsg.h + clangmetamsg.h + clangfreeformmsg.h + clangunsuppmsg.h + clangrulemsg.h + clangdelmsg.h + clanginfomsg.h + clangadvicemsg.h + clangdefmsg.h + clangaction.h + clangutil.h + coach_lang_comp.h + ${CMAKE_CURRENT_BINARY_DIR}/coach_lang_parser.hpp + arithop.h + compop.h + cond.h + region.h + rule.h + ) + +install(TARGETS RCSSCLangParser + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Libraries + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rcss/clang +) diff --git a/rcss/clang/Makefile.am b/rcss/clang/Makefile.am new file mode 100644 index 00000000..85dda2f4 --- /dev/null +++ b/rcss/clang/Makefile.am @@ -0,0 +1,122 @@ + +lib_LTLIBRARIES = \ + librcssclangparser.la + +librcssclangparser_la_SOURCES = \ + clangbuilder.cpp \ + clangmsgbuilder.cpp \ + clangparser.cpp \ + clangmsg.cpp \ + clangmetamsg.cpp \ + clangfreeformmsg.cpp \ + clangunsuppmsg.cpp \ + clangrulemsg.cpp \ + clangdelmsg.cpp \ + clanginfomsg.cpp \ + clangadvicemsg.cpp \ + clangdefmsg.cpp \ + clangaction.cpp \ + clangutil.cpp \ + coach_lang_comp.cpp \ + arithop.cpp \ + cond.cpp \ + compop.cpp \ + region.cpp \ + rule.cpp + +librcssclangparser_la_LDFLAGS = -version-info 3:0:1 +# Changed from 2.0.0 to 3.0.1 at 9.3.5 for addition of buildCondList +# +# 1. Start with version information of `0:0:0' for each libtool library. +# +# 2. Update the version information only immediately before a public +# release of your software. More frequent updates are unnecessary, +# and only guarantee that the current interface number gets larger +# faster. +# +# 3. If the library source code has changed at all since the last +# update, then increment REVISION (`C:R:A' becomes `C:r+1:A'). +# +# 4. If any interfaces have been added, removed, or changed since the +# last update, increment CURRENT, and set REVISION to 0. +# +# 5. If any interfaces have been added since the last public release, +# then increment AGE. +# +# 6. If any interfaces have been removed since the last public release, +# then set AGE to 0. + +librcssclangparserincludedir = $(includedir)/rcss/clang + +librcssclangparserinclude_HEADERS = \ + clangparser.h \ + coach_lang_tok.h \ + clangbuilder.h \ + clangmsgbuilder.h \ + clangmsg.h \ + clangmetamsg.h \ + clangfreeformmsg.h \ + clangunsuppmsg.h \ + clangrulemsg.h \ + clangdelmsg.h \ + clanginfomsg.h \ + clangadvicemsg.h \ + clangdefmsg.h \ + clangaction.h \ + clangutil.h \ + coach_lang_comp.h \ + coach_lang_parser.hpp \ + arithop.h \ + compop.h \ + cond.h \ + region.h \ + rule.h + +nodist_librcssclangparser_la_SOURCES = \ + coach_lang_parser.ypp \ + coach_lang_tok.cpp + +BUILT_SOURCES = \ + coach_lang_parser.hpp \ + coach_lang_tok.cpp + +AM_CPPFLAGS = -I$(top_srcdir) +AM_CFLAGS = -W -Wall +AM_CXXFLAGS = -W -Wall +AM_LD_FLAGS = + +AM_YFLAGS=-d + +FLEX=@FLEX@ +FLEXFLAGS=@FLEXFLAGS@ +AM_FLEXFLEX=@AM_FLEXFLAGS@ + +.lpp.cpp: $*.lpp Makefile.am + $(FLEX) $(FLEXFLAGS) $(AM_FLEXFLAGS) $< + $(AWK) '/#include / { print "#include \"$*.h\""; getline; } \ + /class istream;/ { print "#include "; print "using namespace std;"; getline; } \ + /#include / { print "#include "; getline; } \ + { gsub( "lex\.yy\.c", "$@" ); print; }' lex.yy.c > $@ + rm -f lex.yy.c + +.ll.cc: $*.ll Makefile.am + $(FLEX) $(FLEXFLAGS) $(AM_FLEXFLAGS) $< + $(AWK) '/#include / { print "#include \"$*.h\""; getline; } \ + /class istream;/ { print "#include "; print "using namespace std;"; getline; } \ + /#include / { print "#include "; getline; } \ + { gsub( "lex\.yy\.c", "$@" ); print; }' lex.yy.c > $@ + rm -f lex.yy.c + + +EXTRA_DIST = \ + CMakeLists.txt \ + coach_lang_parser.ypp \ + coach_lang_tok.lpp \ + fix_lexer_file.cmake + + +CLEANFILES = \ + coach_lang_parser.cpp \ + coach_lang_parser.hpp \ + coach_lang_tok.cpp \ + *~ diff --git a/src/arithop.cpp b/rcss/clang/arithop.cpp similarity index 100% rename from src/arithop.cpp rename to rcss/clang/arithop.cpp diff --git a/src/arithop.h b/rcss/clang/arithop.h similarity index 93% rename from src/arithop.h rename to rcss/clang/arithop.h index cf603ce6..e6372eb7 100644 --- a/src/arithop.h +++ b/rcss/clang/arithop.h @@ -19,8 +19,8 @@ * * ***************************************************************************/ -#ifndef ARITHOP_H -#define ARITHOP_H +#ifndef RCSS_CLANG_ARITHOP_H +#define RCSS_CLANG_ARITHOP_H #include @@ -46,10 +46,10 @@ class ArithOp { ArithOp( const arith_t & arith ); - ArithOp( const ArithOp & arith_op ); // not used + ArithOp( const ArithOp & arith_op ) = default; - ArithOp& operator=( const ArithOp& arith_op ); // not used + ArithOp& operator=( const ArithOp& arith_op ) = delete; // not used public: template< typename A, typename B > diff --git a/src/clangaction.cpp b/rcss/clang/clangaction.cpp similarity index 98% rename from src/clangaction.cpp rename to rcss/clang/clangaction.cpp index ee9090b3..e6286715 100644 --- a/src/clangaction.cpp +++ b/rcss/clang/clangaction.cpp @@ -219,7 +219,7 @@ std::ostream & ActPos::print( std::ostream & out ) const { out << "(pos "; - if ( m_reg.get() == NULL ) + if ( ! m_reg ) { out << "(null)"; } @@ -235,7 +235,7 @@ ActPos::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "position self at: " << std::endl; - if ( m_reg.get() == NULL ) + if ( ! m_reg ) { out << line_header << " (null)\n"; } @@ -297,7 +297,7 @@ std::ostream & ActHome::print( std::ostream & out ) const { out << "(home "; - if ( m_reg.get() == NULL ) + if ( ! m_reg ) { out << "(null)"; } @@ -313,7 +313,7 @@ ActHome::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "home position at: " << std::endl; - if ( m_reg.get() == NULL ) + if ( ! m_reg ) { out << line_header << " (null)\n"; } @@ -356,7 +356,7 @@ std::shared_ptr< Action > ActBallToReg::deepCopy() const { std::shared_ptr< Region > new_reg; - if ( m_reg.get() != NULL ) + if ( m_reg ) { new_reg = m_reg->deepCopy(); } @@ -377,7 +377,7 @@ std::ostream & ActBallToReg::print( std::ostream & out ) const { out << "(bto "; - if ( m_reg.get() == NULL ) + if ( ! m_reg ) { out << "(null)"; } @@ -394,7 +394,7 @@ ActBallToReg::printPretty( std::ostream & out, { out << line_header << "ball to: use " << m_bmtset << " to go to:" << std::endl; - if ( m_reg.get() == NULL ) + if ( ! m_reg ) { out << line_header << " (null)\n"; } @@ -693,7 +693,7 @@ std::ostream & ActMarkLineReg::print( std::ostream & out ) const { out << "(markl "; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << "(null)"; } @@ -709,7 +709,7 @@ ActMarkLineReg::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "mark line to region:" << std::endl; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << line_header << " (null)\n"; } @@ -973,7 +973,7 @@ std::ostream & ActPassReg::print( std::ostream & out ) const { out << "(pass "; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << "(null)"; } @@ -989,7 +989,7 @@ ActPassReg::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "pass to region:" << std::endl; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << line_header << " (null)\n"; } @@ -1118,7 +1118,7 @@ std::ostream & ActDribble::print( std::ostream & out ) const { out << "(dribble "; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << "(null)"; } @@ -1134,7 +1134,7 @@ ActDribble::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "dribble to region:" << std::endl; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << line_header << " (null)\n"; } @@ -1197,7 +1197,7 @@ std::ostream & ActClear::print( std::ostream & out ) const { out << "(clear "; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << "(null)"; } @@ -1213,7 +1213,7 @@ ActClear::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "clear to region:" << std::endl; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << line_header << " (null)\n"; } diff --git a/src/clangaction.h b/rcss/clang/clangaction.h similarity index 83% rename from src/clangaction.h rename to rcss/clang/clangaction.h index 829bd545..073dad17 100644 --- a/src/clangaction.h +++ b/rcss/clang/clangaction.h @@ -19,11 +19,12 @@ * * ***************************************************************************/ -#ifndef CLANGACTION_H -#define CLANGACTION_H +#ifndef RCSS_CLANGACTION_H +#define RCSS_CLANGACTION_H + +#include +#include -#include "region.h" -#include "clangutil.h" #include namespace rcss { @@ -312,17 +313,17 @@ class ActPos public: ActPos(); ActPos( std::shared_ptr< Region > r ); - ~ActPos(); + ~ActPos() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; @@ -336,17 +337,17 @@ class ActHome public: ActHome(); ActHome( std::shared_ptr< Region > r ); - ~ActHome(); + ~ActHome() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; @@ -362,17 +363,17 @@ class ActBallToReg ActBallToReg(); ActBallToReg( std::shared_ptr< Region > reg, const BallMove & bmtset ); - ~ActBallToReg(); + ~ActBallToReg() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; BallMove getBallMove() const; @@ -390,17 +391,17 @@ class ActBallToPlayer public: ActBallToPlayer(); ActBallToPlayer( const UNumSet & players ); - ~ActBallToPlayer(); + ~ActBallToPlayer() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; UNumSet & getPlayers(); const UNumSet & getPlayers() const; @@ -418,17 +419,17 @@ class ActMark public: ActMark(); ActMark( const UNumSet & players ); - ~ActMark(); + ~ActMark() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; UNumSet & getPlayers(); const UNumSet & getPlayers() const; @@ -446,16 +447,16 @@ class ActMarkLinePlayer public: ActMarkLinePlayer(); ActMarkLinePlayer( const UNumSet & players ); - ~ActMarkLinePlayer(); + ~ActMarkLinePlayer() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; UNumSet & getPlayers(); const UNumSet & getPlayers() const; @@ -474,17 +475,17 @@ class ActMarkLineReg ActMarkLineReg(); ActMarkLineReg( std::shared_ptr< Region > reg ); - ~ActMarkLineReg(); + ~ActMarkLineReg() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; std::shared_ptr< Region > detachRegion(); @@ -500,17 +501,17 @@ class ActOffsidesLine ActOffsidesLine(); ActOffsidesLine( std::shared_ptr< Region > r ); - ~ActOffsidesLine(); + ~ActOffsidesLine() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; std::shared_ptr< Region > detachRegion(); @@ -526,17 +527,17 @@ class ActHetType ActHetType(); ActHetType( const int & player_type ); - ~ActHetType(); + ~ActHetType() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; /* class specific stuff */ int getPlayerType() const; @@ -551,17 +552,17 @@ class ActNamed : public Action { public: ActNamed( const std::string & name = "" ); - ~ActNamed(); + ~ActNamed() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; /* class specific */ std::string & getName(); @@ -578,17 +579,17 @@ class ActPassReg public: ActPassReg(); ActPassReg( std::shared_ptr< Region > reg ); - ~ActPassReg(); + ~ActPassReg() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; std::shared_ptr< Region > detachRegion(); @@ -603,17 +604,17 @@ class ActPassUNum public: ActPassUNum(); ActPassUNum( const UNumSet & players ); - ~ActPassUNum(); + ~ActPassUNum() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; /* class specific stuff */ UNumSet & getPlayers(); @@ -631,17 +632,17 @@ class ActDribble public: ActDribble(); ActDribble( std::shared_ptr< Region > reg ); - ~ActDribble(); + ~ActDribble() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; std::shared_ptr< Region > detachRegion(); @@ -656,17 +657,17 @@ class ActClear public: ActClear(); ActClear( std::shared_ptr< Region > reg ); - ~ActClear(); + ~ActClear() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Region * getRegion() const; std::shared_ptr< Region > detachRegion(); @@ -680,17 +681,17 @@ class ActShoot : public Action { public: ActShoot(); - ~ActShoot(); + ~ActShoot() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; }; @@ -698,17 +699,17 @@ class ActHold : public Action { public: ActHold(); - ~ActHold(); + ~ActHold() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; }; @@ -716,17 +717,17 @@ class ActIntercept : public Action { public: ActIntercept(); - ~ActIntercept(); + ~ActIntercept() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; }; @@ -735,17 +736,17 @@ class ActTackle public: ActTackle(); ActTackle( const UNumSet & players ); - ~ActTackle(); + ~ActTackle() override; virtual - std::shared_ptr< Action > deepCopy() const; + std::shared_ptr< Action > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; /* class specific stuff */ UNumSet & getPlayers(); diff --git a/src/clangadvicemsg.cpp b/rcss/clang/clangadvicemsg.cpp similarity index 79% rename from src/clangadvicemsg.cpp rename to rcss/clang/clangadvicemsg.cpp index f1cd2c72..d8c57b53 100644 --- a/src/clangadvicemsg.cpp +++ b/rcss/clang/clangadvicemsg.cpp @@ -24,7 +24,6 @@ #endif #include "clangadvicemsg.h" -#include "types.h" namespace rcss { namespace clang { @@ -51,10 +50,9 @@ std::shared_ptr< Msg > AdviceMsg::deepCopy() const { Storage new_tokens; - for( Storage::const_iterator i = M_tokens.begin(); - i != M_tokens.end(); ++i ) + for( Storage::const_reference i : M_tokens ) { - new_tokens.push_back( (*i)->deepCopy() ); + new_tokens.push_back( i->deepCopy() ); } std::shared_ptr< Msg > rval( new AdviceMsg( new_tokens ) ); @@ -73,17 +71,15 @@ std::ostream & AdviceMsg::print( std::ostream & out ) const { out << "(advice"; - for ( Storage::const_iterator token_iter = getTokens().begin(); - token_iter != getTokens().end(); - ++token_iter ) + for ( Storage::const_reference token : getTokens() ) { - if ( *token_iter == NULL ) + if ( ! token ) { out << " (null)"; } else { - out << " " << **token_iter; + out << " " << *token; } } out << ")"; @@ -95,17 +91,15 @@ AdviceMsg::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Advice" << std::endl; - for ( Storage::const_iterator token_iter = getTokens().begin(); - token_iter != getTokens().end(); - ++token_iter ) + for ( Storage::const_reference token : getTokens() ) { - if ( *token_iter == NULL ) + if ( ! token ) { out << line_header << " - (null)\n"; } else { - (*token_iter)->printPretty( out, line_header + " - " ); + token->printPretty( out, line_header + " - " ); } } return out; diff --git a/src/clangadvicemsg.h b/rcss/clang/clangadvicemsg.h similarity index 85% rename from src/clangadvicemsg.h rename to rcss/clang/clangadvicemsg.h index 163d2dda..c1387534 100644 --- a/src/clangadvicemsg.h +++ b/rcss/clang/clangadvicemsg.h @@ -19,11 +19,11 @@ * * ***************************************************************************/ -#ifndef CLANGADVICEMSG_H -#define CLANGADVICEMSG_H +#ifndef RCSS_CLANGADVICEMSG_H +#define RCSS_CLANGADVICEMSG_H -#include "clangmsg.h" -#include "coach_lang_comp.h" +#include +#include namespace rcss { namespace clang { @@ -39,17 +39,17 @@ class AdviceMsg public: virtual - ~AdviceMsg(); + ~AdviceMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Storage & getTokens() const { diff --git a/src/clangbuilder.cpp b/rcss/clang/clangbuilder.cpp similarity index 87% rename from src/clangbuilder.cpp rename to rcss/clang/clangbuilder.cpp index a4a52eba..204ef1be 100644 --- a/src/clangbuilder.cpp +++ b/rcss/clang/clangbuilder.cpp @@ -23,11 +23,7 @@ #include #endif -#ifdef HAVE_SSTREAM #include -#else -#include -#endif #include "clangbuilder.h" @@ -38,16 +34,9 @@ BuilderErr::BuilderErr( const char * file, const int & line, const char * msg ) throw() { -#ifdef HAVE_SSTREAM std::ostringstream tmp; tmp << file << ": " << line << ": " << msg; M_msg = tmp.str(); -#else - std::ostrstream tmp; - tmp << file << ": " << line << ": " << msg << std::ends; - M_msg = tmp.str(); - tmp.freeze( false ); -#endif } } diff --git a/src/clangbuilder.h b/rcss/clang/clangbuilder.h similarity index 98% rename from src/clangbuilder.h rename to rcss/clang/clangbuilder.h index 900fbcb7..ba2d21ac 100644 --- a/src/clangbuilder.h +++ b/rcss/clang/clangbuilder.h @@ -19,15 +19,14 @@ * * ***************************************************************************/ -#ifndef RCSSSERVER_CLANGBUILDER_H -#define RCSSSERVER_CLANGBUILDER_H +#ifndef RCSS_CLANGBUILDER_H +#define RCSS_CLANGBUILDER_H +#include #include #include -#include "clangutil.h" - // The clang::Builder is called from within the parser to construct the // CLang message. It is not the job of the builder to make sure the diff --git a/src/clangdefmsg.cpp b/rcss/clang/clangdefmsg.cpp similarity index 77% rename from src/clangdefmsg.cpp rename to rcss/clang/clangdefmsg.cpp index ee1d0830..ee4c6bb5 100644 --- a/src/clangdefmsg.cpp +++ b/rcss/clang/clangdefmsg.cpp @@ -24,7 +24,6 @@ #endif #include "clangdefmsg.h" -#include "types.h" namespace rcss { namespace clang { @@ -51,11 +50,9 @@ std::shared_ptr< Msg > DefineMsg::deepCopy() const { Storage new_defs; - for ( Storage::const_iterator i = M_defs.begin(); - i != M_defs.end(); - ++i ) + for ( Storage::const_reference def : M_defs ) { - new_defs.push_back( (*i)->deepCopy() ); + new_defs.push_back( def->deepCopy() ); } std::shared_ptr< Msg > ptr( new DefineMsg( new_defs ) ); @@ -66,17 +63,15 @@ std::ostream & DefineMsg::print( std::ostream & out ) const { out << "(define"; - for ( Storage::const_iterator token_iter = getDefs().begin(); - token_iter != getDefs().end(); - ++token_iter ) + for ( Storage::const_reference def : getDefs() ) { - if ( *token_iter == NULL ) + if ( ! def ) { out << " (null)"; } else { - out << " " << **token_iter; + out << " " << *def; } } out << ")"; @@ -88,17 +83,15 @@ DefineMsg::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Define" << std::endl; - for ( Storage::const_iterator token_iter = getDefs().begin(); - token_iter != getDefs().end(); - ++token_iter ) + for ( Storage::const_reference def : getDefs() ) { - if ( *token_iter == NULL ) + if ( ! def ) { out << line_header << " - (null)\n"; } else { - (*token_iter)->printPretty( out, line_header + " - " ); + def->printPretty( out, line_header + " - " ); } } return out; diff --git a/src/clangdefmsg.h b/rcss/clang/clangdefmsg.h similarity index 86% rename from src/clangdefmsg.h rename to rcss/clang/clangdefmsg.h index 35b5759f..d46d975f 100644 --- a/src/clangdefmsg.h +++ b/rcss/clang/clangdefmsg.h @@ -19,11 +19,11 @@ * * ***************************************************************************/ -#ifndef CLANGDEFMSG_H -#define CLANGDEFMSG_H +#ifndef RCSS_CLANGDEFMSG_H +#define RCSS_CLANGDEFMSG_H -#include "clangmsg.h" -#include "coach_lang_comp.h" +#include +#include namespace rcss { namespace clang { @@ -39,17 +39,17 @@ class DefineMsg public: virtual - ~DefineMsg(); + ~DefineMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Storage & getDefs() const { diff --git a/src/clangdelmsg.cpp b/rcss/clang/clangdelmsg.cpp similarity index 99% rename from src/clangdelmsg.cpp rename to rcss/clang/clangdelmsg.cpp index a91c1fe0..38721635 100644 --- a/src/clangdelmsg.cpp +++ b/rcss/clang/clangdelmsg.cpp @@ -26,7 +26,6 @@ #include "clangdelmsg.h" #include "rule.h" -#include "types.h" namespace rcss { namespace clang { diff --git a/src/clangdelmsg.h b/rcss/clang/clangdelmsg.h similarity index 86% rename from src/clangdelmsg.h rename to rcss/clang/clangdelmsg.h index ed49bfe2..8c39d411 100644 --- a/src/clangdelmsg.h +++ b/rcss/clang/clangdelmsg.h @@ -19,11 +19,11 @@ * * ***************************************************************************/ -#ifndef CLANGDELMSG_H -#define CLANGDELMSG_H +#ifndef RCSS_CLANGDELMSG_H +#define RCSS_CLANGDELMSG_H -#include "clangmsg.h" -#include "rule.h" +#include +#include namespace rcss { namespace clang { @@ -38,17 +38,17 @@ class DelMsg public: virtual - ~DelMsg(); + ~DelMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const RuleIDList & getList() const { diff --git a/src/clangfreeformmsg.cpp b/rcss/clang/clangfreeformmsg.cpp similarity index 98% rename from src/clangfreeformmsg.cpp rename to rcss/clang/clangfreeformmsg.cpp index d8e4fc2b..ef1cc54e 100644 --- a/src/clangfreeformmsg.cpp +++ b/rcss/clang/clangfreeformmsg.cpp @@ -25,8 +25,6 @@ #include "clangfreeformmsg.h" -#include "types.h" - namespace rcss { namespace clang { diff --git a/src/clangfreeformmsg.h b/rcss/clang/clangfreeformmsg.h similarity index 86% rename from src/clangfreeformmsg.h rename to rcss/clang/clangfreeformmsg.h index d0491cec..f825a6de 100644 --- a/src/clangfreeformmsg.h +++ b/rcss/clang/clangfreeformmsg.h @@ -19,10 +19,11 @@ * * ***************************************************************************/ -#ifndef CLANGFREEFORMMSG_H -#define CLANGFREEFORMMSG_H +#ifndef RCSS_CLANGFREEFORMMSG_H +#define RCSS_CLANGFREEFORMMSG_H + +#include -#include "clangmsg.h" #include namespace rcss { @@ -38,17 +39,17 @@ class FreeformMsg FreeformMsg( const std::string & str ); virtual - ~FreeformMsg(); + ~FreeformMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual Types getType() const diff --git a/src/clanginfomsg.cpp b/rcss/clang/clanginfomsg.cpp similarity index 73% rename from src/clanginfomsg.cpp rename to rcss/clang/clanginfomsg.cpp index 4eb1601b..7df80ae2 100644 --- a/src/clanginfomsg.cpp +++ b/rcss/clang/clanginfomsg.cpp @@ -25,8 +25,6 @@ #include "clanginfomsg.h" -#include "types.h" - namespace rcss { namespace clang { @@ -45,12 +43,6 @@ InfoMsg::InfoMsg( const Storage & tokens ) InfoMsg::~InfoMsg() { - // for ( Storage::iterator i = M_tokens.begin(); - // i != M_tokens.end(); - // ++i ) - // { - // delete *i; - // } M_tokens.clear(); } @@ -58,11 +50,9 @@ std::shared_ptr< Msg > InfoMsg::deepCopy() const { Storage new_tokens; - for ( Storage::const_iterator i = M_tokens.begin(); - i != M_tokens.end(); - ++i ) + for ( Storage::const_reference token : M_tokens ) { - new_tokens.push_back( (*i)->deepCopy() ); + new_tokens.push_back( token->deepCopy() ); } std::shared_ptr< Msg > ptr( new InfoMsg( new_tokens ) ); @@ -73,17 +63,15 @@ std::ostream & InfoMsg::print( std::ostream & out ) const { out << "(info"; - for ( Storage::const_iterator token_iter = getTokens().begin(); - token_iter != getTokens().end(); - ++token_iter ) + for ( Storage::const_reference token : getTokens() ) { - if ( *token_iter == NULL ) + if ( ! token ) { out << " (null)"; } else { - out << " " << **token_iter; + out << " " << *token; } } out << ")"; @@ -95,17 +83,15 @@ InfoMsg::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Info" << std::endl; - for ( Storage::const_iterator token_iter = getTokens().begin(); - token_iter != getTokens().end(); - ++token_iter ) + for ( Storage::const_reference token : getTokens() ) { - if ( *token_iter == NULL ) + if ( ! token ) { out << line_header << " - (null)\n"; } else { - (*token_iter)->printPretty( out, line_header + " - " ); + token->printPretty( out, line_header + " - " ); } } return out; diff --git a/src/clanginfomsg.h b/rcss/clang/clanginfomsg.h similarity index 86% rename from src/clanginfomsg.h rename to rcss/clang/clanginfomsg.h index 011f0a9c..8f7197e8 100644 --- a/src/clanginfomsg.h +++ b/rcss/clang/clanginfomsg.h @@ -19,11 +19,11 @@ * * ***************************************************************************/ -#ifndef CLANGINFOMSG_H -#define CLANGINFOMSG_H +#ifndef RCSS_CLANGINFOMSG_H +#define RCSS_CLANGINFOMSG_H -#include "clangmsg.h" -#include "coach_lang_comp.h" +#include +#include namespace rcss { namespace clang { @@ -39,17 +39,17 @@ class InfoMsg public: virtual - ~InfoMsg(); + ~InfoMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Storage & getTokens() const { diff --git a/src/clangmetamsg.cpp b/rcss/clang/clangmetamsg.cpp similarity index 78% rename from src/clangmetamsg.cpp rename to rcss/clang/clangmetamsg.cpp index 98242268..4868e4a9 100644 --- a/src/clangmetamsg.cpp +++ b/rcss/clang/clangmetamsg.cpp @@ -25,8 +25,6 @@ #include "clangmetamsg.h" -#include "types.h" - #include #include @@ -93,12 +91,6 @@ MetaMsg::MetaMsg( const Storage & tokens ) MetaMsg::~MetaMsg() { - // for ( Storage::const_iterator i = M_tokens.begin(); - // i != M_tokens.end(); - // ++i ) - // { - // delete *i; - // } M_tokens.clear(); } @@ -106,11 +98,9 @@ std::shared_ptr< Msg > MetaMsg::deepCopy() const { Storage new_tokens; - for ( Storage::const_iterator i = M_tokens.begin(); - i != M_tokens.end(); - ++i ) + for ( Storage::const_reference token : M_tokens ) { - new_tokens.push_back( (*i)->deepCopy() ); + new_tokens.push_back( token->deepCopy() ); } std::shared_ptr< Msg > rval( new MetaMsg( new_tokens ) ); @@ -121,17 +111,15 @@ std::ostream & MetaMsg::print( std::ostream & out ) const { out << "(meta"; - for ( Storage::const_iterator token_iter = M_tokens.begin(); - token_iter != M_tokens.end(); - ++token_iter ) + for ( Storage::const_reference token : M_tokens ) { - if ( *token_iter == NULL ) + if ( ! token ) { out << " (null)"; } else { - out << " " << **token_iter; + out << " " << *token; } } out << ")"; @@ -144,17 +132,15 @@ MetaMsg::printPretty( std::ostream & out, { out << line_header << "Meta" << std::endl; - for ( Storage::const_iterator token_iter = M_tokens.begin(); - token_iter != M_tokens.end(); - ++token_iter ) + for ( Storage::const_reference token : M_tokens ) { - if ( *token_iter == NULL ) + if ( ! token ) { out << line_header << " - (null)\n"; } else { - (*token_iter)->printPretty( out, line_header + " - " ); + token->printPretty( out, line_header + " - " ); } } return out; diff --git a/src/clangmetamsg.h b/rcss/clang/clangmetamsg.h similarity index 86% rename from src/clangmetamsg.h rename to rcss/clang/clangmetamsg.h index 99ad8206..fc7d3fea 100644 --- a/src/clangmetamsg.h +++ b/rcss/clang/clangmetamsg.h @@ -19,11 +19,13 @@ * * ***************************************************************************/ -#ifndef CLANGMETAMSG_H -#define CLANGMETAMSG_H +#ifndef RCSS_CLANGMETAMSG_H +#define RCSS_CLANGMETAMSG_H + +#include -#include "clangmsg.h" #include +#include namespace rcss { namespace clang { @@ -57,17 +59,17 @@ class MetaTokenVer MetaTokenVer( const double& ver = 0.0 ); virtual - ~MetaTokenVer(); + ~MetaTokenVer() override; virtual - std::shared_ptr< MetaToken > deepCopy() const; + std::shared_ptr< MetaToken > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; // double getVer() const // { @@ -90,17 +92,17 @@ class MetaMsg MetaMsg( const Storage& tokens ); public: virtual - ~MetaMsg(); + ~MetaMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; Storage & getTokens() { diff --git a/src/clangmsg.cpp b/rcss/clang/clangmsg.cpp similarity index 100% rename from src/clangmsg.cpp rename to rcss/clang/clangmsg.cpp diff --git a/src/clangmsg.h b/rcss/clang/clangmsg.h similarity index 98% rename from src/clangmsg.h rename to rcss/clang/clangmsg.h index d69d9545..e773a24d 100644 --- a/src/clangmsg.h +++ b/rcss/clang/clangmsg.h @@ -19,8 +19,8 @@ * * ***************************************************************************/ -#ifndef CLANGMSG_H -#define CLANGMSG_H +#ifndef RCSS_CLANGMSG_H +#define RCSS_CLANGMSG_H #include #include diff --git a/src/clangmsgbuilder.cpp b/rcss/clang/clangmsgbuilder.cpp similarity index 100% rename from src/clangmsgbuilder.cpp rename to rcss/clang/clangmsgbuilder.cpp diff --git a/src/clangmsgbuilder.h b/rcss/clang/clangmsgbuilder.h similarity index 62% rename from src/clangmsgbuilder.h rename to rcss/clang/clangmsgbuilder.h index f4bedf19..6b874eb4 100644 --- a/src/clangmsgbuilder.h +++ b/rcss/clang/clangmsgbuilder.h @@ -19,10 +19,10 @@ * * ***************************************************************************/ -#ifndef CLANGMSGBUILDER_H -#define CLANGMSGBUILDER_H +#ifndef RCSS_CLANGMSGBUILDER_H +#define RCSS_CLANGMSGBUILDER_H -#include "clangbuilder.h" +#include #include @@ -177,282 +177,282 @@ class MsgBuilder MsgBuilder(); virtual - ~MsgBuilder(); + ~MsgBuilder() override; std::shared_ptr< Msg > getMsg(); void resetMsg(); virtual void setVer( const unsigned int & min, - const unsigned int & max ); + const unsigned int & max ) override; virtual - void setStrVarSize( const unsigned int len ) { M_str_var_size = len; } + void setStrVarSize( const unsigned int len ) override { M_str_var_size = len; } virtual - unsigned int strVarSize() const { return M_str_var_size; } + unsigned int strVarSize() const override { return M_str_var_size; } virtual - void setFreeformMsgSize( const unsigned int len ) { M_freeform_msg_size = len; } + void setFreeformMsgSize( const unsigned int len ) override { M_freeform_msg_size = len; } virtual - unsigned int freeformMsgSize() const { return M_freeform_msg_size; } + unsigned int freeformMsgSize() const override { return M_freeform_msg_size; } virtual - void setTime( const int & time ); + void setTime( const int & time ) override; virtual - void setSide( const int & side ); + void setSide( const int & side ) override; virtual - void setTimeRecv( const int & time ); + void setTimeRecv( const int & time ) override; virtual - void buildMetaMsg(); + void buildMetaMsg() override; virtual - void buildMetaTokenVer( const double & ver ); + void buildMetaTokenVer( const double & ver ) override; virtual - void buildDefineMsg(); + void buildDefineMsg() override; virtual - void buildDefineCond( const std::string & name ); + void buildDefineCond( const std::string & name ) override; virtual - void buildDefineDir( const std::string & name ); + void buildDefineDir( const std::string & name ) override; virtual - void buildDefineReg( const std::string & name ); + void buildDefineReg( const std::string & name ) override; virtual - void buildDefineAct( const std::string & name ); + void buildDefineAct( const std::string & name ) override; virtual - void buildFreeformMsg( const std::string & str ); + void buildFreeformMsg( const std::string & str ) override; virtual - void buildUnsuppMsg(); + void buildUnsuppMsg() override; virtual - void buildInfoMsg(); + void buildInfoMsg() override; virtual - void buildAdviceMsg(); + void buildAdviceMsg() override; virtual - void buildTokenRule( const int & ttl ); + void buildTokenRule( const int & ttl ) override; virtual - void buildTokenClear(); + void buildTokenClear() override; virtual - void buildActPos(); + void buildActPos() override; virtual - void buildActHome(); + void buildActHome() override; virtual - void buildActBallToReg(); + void buildActBallToReg() override; virtual - void buildActBallToPlayer(); + void buildActBallToPlayer() override; virtual - void buildActMark(); + void buildActMark() override; virtual - void buildActMarkLinePlayer(); + void buildActMarkLinePlayer() override; virtual - void buildActMarkLineReg(); + void buildActMarkLineReg() override; virtual - void buildActOffsideLine(); + void buildActOffsideLine() override; virtual - void buildActHetType( const int & type ); + void buildActHetType( const int & type ) override; virtual - void buildActNamed( const std::string & name ); + void buildActNamed( const std::string & name ) override; virtual - void buildActPassReg(); + void buildActPassReg() override; virtual - void buildActPassUNum(); + void buildActPassUNum() override; virtual - void buildActDribble(); + void buildActDribble() override; virtual - void buildActClear(); + void buildActClear() override; virtual - void buildActShoot(); + void buildActShoot() override; virtual - void buildActHold(); + void buildActHold() override; virtual - void buildActIntercept(); + void buildActIntercept() override; virtual - void buildActTackle(); + void buildActTackle() override; virtual void buildDirComm( const bool & do_dont, - const bool & our_side ); + const bool & our_side ) override; virtual - void buildDirNamed( const std::string& name ); + void buildDirNamed( const std::string& name ) override; virtual - void buildCondTrue(); + void buildCondTrue() override; virtual - void buildCondFalse(); + void buildCondFalse() override; virtual void buildCondPlayerPos( const bool & our_side, const int & min, - const int & max ); + const int & max ) override; virtual - void buildCondBallPos(); + void buildCondBallPos() override; virtual - void buildCondBallOwner( const bool & our_side ); + void buildCondBallOwner( const bool & our_side ) override; virtual - void buildCondPlayMode( const PlayMode & play_mode ); + void buildCondPlayMode( const PlayMode & play_mode ) override; virtual - void buildCondAnd(); + void buildCondAnd() override; virtual - void buildCondOr(); + void buildCondOr() override; virtual - void buildCondNot(); + void buildCondNot() override; virtual - void buildCondNamed( const std::string & name ); + void buildCondNamed( const std::string & name ) override; virtual void buildCondTime( const int & time, - const util::CompOp & comp ); + const util::CompOp & comp ) override; virtual void buildCondOppGoal( const int & goals, - const util::CompOp & comp ); + const util::CompOp & comp ) override; virtual void buildCondOurGoal( const int & goals, - const util::CompOp & comp ); + const util::CompOp & comp ) override; virtual void buildCondGoalDiff( const int & goals, - const util::CompOp & comp ); + const util::CompOp & comp ) override; virtual - void buildCondUNum( const rcss::clang::UNum & unum ); + void buildCondUNum( const rcss::clang::UNum & unum ) override; virtual - void buildAddToCondList(); + void buildAddToCondList() override; virtual - void buildCreateCondList(); + void buildCreateCondList() override; virtual - void buildRegNull(); + void buildRegNull() override; virtual - void buildRegQuad(); + void buildRegQuad() override; virtual void buildRegArc( const double & start_rad, const double & end_rad, const double & start_ang, - const double & span_ang ); + const double & span_ang ) override; virtual - void buildRegUnion(); + void buildRegUnion() override; virtual - void buildRegNamed( const std::string & name ); + void buildRegNamed( const std::string & name ) override; virtual - void buildRegPoint(); + void buildRegPoint() override; virtual - void buildRegTri(); + void buildRegTri() override; virtual - void buildRegRec(); + void buildRegRec() override; virtual void buildPointSimple( const double & x, - const double & y ); + const double & y ) override; virtual void buildPointRel( const double & x, - const double & y ); + const double & y ) override; virtual - void buildPointBall(); + void buildPointBall() override; virtual void buildPointPlayer( const bool & our_side, - const UNum & unum ); + const UNum & unum ) override; virtual - void buildPointArith( const rcss::util::ArithOp & arith_op ); + void buildPointArith( const rcss::util::ArithOp & arith_op ) override; virtual - void buildUNum( const UNum & unum ); + void buildUNum( const UNum & unum ) override; virtual - void buildUNumSet(); + void buildUNumSet() override; virtual - void buildBallMoveToken( const BallMoveToken & bmt ); + void buildBallMoveToken( const BallMoveToken & bmt ) override; virtual - void buildRuleMsg(); + void buildRuleMsg() override; virtual - void buildActivateAllRules( const bool & on ); + void buildActivateAllRules( const bool & on ) override; virtual - void buildActivateRules( const bool & on ); + void buildActivateRules( const bool & on ) override; virtual - void buildRuleID( const std::string & id ); + void buildRuleID( const std::string & id ) override; virtual - void buildRuleIDList(); + void buildRuleIDList() override; virtual - void buildRuleIDListALL(); + void buildRuleIDListALL() override; virtual - void buildDelMsg(); + void buildDelMsg() override; virtual - void buildDefineModelRule( const std::string & id ); + void buildDefineModelRule( const std::string & id ) override; virtual - void buildDefineDirectiveRule( const std::string & id ); + void buildDefineDirectiveRule( const std::string & id ) override; virtual - void buildSimpleRule(); + void buildSimpleRule() override; virtual - void buildNestedRule(); + void buildNestedRule() override; virtual - void buildIDRule(); + void buildIDRule() override; }; } diff --git a/src/clangparser.cpp b/rcss/clang/clangparser.cpp similarity index 92% rename from src/clangparser.cpp rename to rcss/clang/clangparser.cpp index 7835faf6..7176bfbe 100644 --- a/src/clangparser.cpp +++ b/rcss/clang/clangparser.cpp @@ -23,11 +23,7 @@ #include #endif -#ifdef HAVE_SSTREAM #include -#else -#include ; -#endif #include "clangparser.h" @@ -44,11 +40,7 @@ Parser::Parser( Builder & builder ) int Parser::parse( const char * msg ) { -#ifdef HAVE_SSTREAM std::istringstream strm( msg ); -#else - std::istrstream strm( msg ); -#endif return ( rcss::Parser::parse( strm ) ? 0 : 1 ); } diff --git a/src/clangparser.h b/rcss/clang/clangparser.h similarity index 93% rename from src/clangparser.h rename to rcss/clang/clangparser.h index dbcd45bc..34d3e7f6 100644 --- a/src/clangparser.h +++ b/rcss/clang/clangparser.h @@ -19,12 +19,13 @@ * * ***************************************************************************/ -#ifndef CLANGPARSER_H -#define CLANGPARSER_H +#ifndef RCSS_CLANGPARSER_H +#define RCSS_CLANGPARSER_H + +#include +#include #include -#include -#include "coach_lang_tok.h" namespace rcss { namespace clang { @@ -74,7 +75,7 @@ class Parser ParserFunc M_parser; virtual - bool doParse( std::istream & strm ) + bool doParse( std::istream & strm ) override { M_param.getLexer().switch_streams( &strm, &std::cerr ); return M_parser( M_param ) == 0; diff --git a/src/clangrulemsg.cpp b/rcss/clang/clangrulemsg.cpp similarity index 87% rename from src/clangrulemsg.cpp rename to rcss/clang/clangrulemsg.cpp index 985565e1..3af9994e 100644 --- a/src/clangrulemsg.cpp +++ b/rcss/clang/clangrulemsg.cpp @@ -26,7 +26,6 @@ #include "clangrulemsg.h" #include "rule.h" -#include "types.h" namespace rcss { namespace clang { @@ -60,11 +59,9 @@ std::ostream & RuleMsg::print( std::ostream & out ) const { out << "(rule "; - for ( Storage::const_iterator i = M_active.begin(); - i != M_active.end(); - ++i ) + for ( Storage::const_reference i : M_active ) { - out << *i; + out << i; } out << ")"; return out; @@ -76,9 +73,7 @@ RuleMsg::printPretty( std::ostream & out, { out << line_header << "Activation List:\n"; bool first = true; - for ( Storage::const_iterator i = M_active.begin(); - i != M_active.end(); - ++i ) + for ( Storage::const_reference i : M_active ) { if ( first ) { @@ -88,7 +83,7 @@ RuleMsg::printPretty( std::ostream & out, { out << line_header << " Then:\n"; } - i->printPretty( out, line_header + " -" ); + i.printPretty( out, line_header + " -" ); } return out; } diff --git a/src/clangrulemsg.h b/rcss/clang/clangrulemsg.h similarity index 87% rename from src/clangrulemsg.h rename to rcss/clang/clangrulemsg.h index f4991f43..8d18e0ed 100644 --- a/src/clangrulemsg.h +++ b/rcss/clang/clangrulemsg.h @@ -19,12 +19,12 @@ * * ***************************************************************************/ -#ifndef CLANGRULEMSG_H -#define CLANGRULEMSG_H +#ifndef RCSS_CLANGRULEMSG_H +#define RCSS_CLANGRULEMSG_H -#include "clangmsg.h" -#include +#include +#include namespace rcss { namespace clang { @@ -41,17 +41,17 @@ class RuleMsg RuleMsg( const Storage & list ); public: virtual - ~RuleMsg(); + ~RuleMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; const Storage & getList() const { diff --git a/src/clangunsuppmsg.cpp b/rcss/clang/clangunsuppmsg.cpp similarity index 100% rename from src/clangunsuppmsg.cpp rename to rcss/clang/clangunsuppmsg.cpp diff --git a/src/clangunsuppmsg.h b/rcss/clang/clangunsuppmsg.h similarity index 85% rename from src/clangunsuppmsg.h rename to rcss/clang/clangunsuppmsg.h index 9a78e17b..d764d3f8 100644 --- a/src/clangunsuppmsg.h +++ b/rcss/clang/clangunsuppmsg.h @@ -19,10 +19,10 @@ * * ***************************************************************************/ -#ifndef CLANGUNSUPPMSG_H -#define CLANGUNSUPPMSG_H +#ifndef RCSS_CLANGUNSUPPMSG_H +#define RCSS_CLANGUNSUPPMSG_H -#include "clangmsg.h" +#include namespace rcss { namespace clang { @@ -33,17 +33,17 @@ class UnsuppMsg UnsuppMsg(); virtual - ~UnsuppMsg(); + ~UnsuppMsg() override; virtual - std::shared_ptr< Msg > deepCopy() const; + std::shared_ptr< Msg > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual Types getType() const diff --git a/src/clangutil.cpp b/rcss/clang/clangutil.cpp similarity index 95% rename from src/clangutil.cpp rename to rcss/clang/clangutil.cpp index caee25ad..2e27ce2d 100644 --- a/src/clangutil.cpp +++ b/rcss/clang/clangutil.cpp @@ -115,11 +115,9 @@ UNumSet::contains( const UNum & unum ) const if ( unum.isValid() ) { // return std::find( M_entries.begin(), M_entries.end(), unum ) != M_entries.end(); - for ( container::const_iterator i = M_entries.begin(); - i != M_entries.end(); - ++i ) + for ( container::const_reference i : M_entries ) { - if ( unum == *i ) + if ( unum == i ) { return true; } diff --git a/src/clangutil.h b/rcss/clang/clangutil.h similarity index 99% rename from src/clangutil.h rename to rcss/clang/clangutil.h index 88b4acd6..9670cf1f 100644 --- a/src/clangutil.h +++ b/rcss/clang/clangutil.h @@ -19,8 +19,8 @@ * * ***************************************************************************/ -#ifndef CLANGUTIL_H -#define CLANGUTIL_H +#ifndef RCSS_CLANGUTIL_H +#define RCSS_CLANGUTIL_H #include #include diff --git a/src/coach_lang_comp.cpp b/rcss/clang/coach_lang_comp.cpp similarity index 85% rename from src/coach_lang_comp.cpp rename to rcss/clang/coach_lang_comp.cpp index dd607527..3a4438db 100644 --- a/src/coach_lang_comp.cpp +++ b/rcss/clang/coach_lang_comp.cpp @@ -56,11 +56,9 @@ DirComm::print( std::ostream & out ) const } else { - for ( Storage::const_iterator i = getActions().begin(); - i != getActions().end(); - ++i ) + for ( Storage::const_reference i : getActions() ) { - out << **i; + out << *i; } } return out << ")"; @@ -80,11 +78,9 @@ DirComm::printPretty( std::ostream & out, } else { - for ( Storage::const_iterator i = getActions().begin(); - i != getActions().end(); - ++i ) + for ( Storage::const_reference i : getActions() ) { - (*i)->printPretty( out, line_header + " " ); + i->printPretty( out, line_header + " " ); } } return out; @@ -94,12 +90,6 @@ DirComm::printPretty( std::ostream & out, void DirComm::clearActions() { - // for ( Storage::iterator i = M_actions.begin(); - // i != M_actions.end(); - // ++i ) - // { - // delete *i; - // } M_actions.clear(); } @@ -116,11 +106,9 @@ std::shared_ptr< Dir > DirComm::deepCopy() const { Storage new_actions; - for ( Storage::const_iterator i = getActions().begin(); - i != getActions().end(); - ++i ) + for ( Storage::const_reference i : getActions() ) { - new_actions.push_back( (*i)->deepCopy() ); + new_actions.push_back( i->deepCopy() ); } std::shared_ptr< Dir > rval( new DirComm( M_positive, @@ -176,17 +164,15 @@ TokRule::print( std::ostream & out ) const out << *M_cond; } - for ( Storage::const_iterator iter = getDirs().begin(); - iter != getDirs().end(); - ++iter ) + for ( Storage::const_reference dir : getDirs() ) { - if ( *iter == NULL ) + if ( ! dir ) { out << " (null)"; } else { - out << " " << **iter; + out << " " << *dir; } } return out << ")"; @@ -208,17 +194,15 @@ TokRule::printPretty( std::ostream & out, out << line_header << "then" << std::endl; - for ( Storage::const_iterator iter = getDirs().begin(); - iter != getDirs().end(); - ++iter ) + for ( Storage::const_reference dir : getDirs() ) { - if ( *iter == NULL ) + if ( ! dir ) { out << line_header << " *(null)\n"; } else { - (*iter)->printPretty( out, line_header + " *"); + dir->printPretty( out, line_header + " *"); } } return out; @@ -240,11 +224,9 @@ TokRule::deepCopy() const } Storage new_dirs; - for ( Storage::const_iterator i = M_dirs.begin(); - i != M_dirs.end(); - ++i ) + for ( Storage::const_reference dir : M_dirs ) { - new_dirs.push_back( (*i)->deepCopy() ); + new_dirs.push_back( dir->deepCopy() ); } std::shared_ptr< Token > rval( new TokRule( M_ttl, @@ -258,7 +240,7 @@ std::ostream & DefCond::print( std::ostream & out ) const { out << "(definec \"" << M_name << "\" "; - if ( M_cond.get() == NULL ) + if ( ! M_cond ) { out << " (null)"; } @@ -274,7 +256,7 @@ DefCond::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Cond \"" << M_name << "\"" << std::endl; - if ( M_cond.get() == NULL ) + if ( ! M_cond ) { out << line_header << " (null)\n"; } @@ -290,7 +272,7 @@ DefCond::printPretty( std::ostream & out, DefDir::print( std::ostream & out ) const { out << "(defined \"" << M_name << "\" "; - if ( M_dir.get() == NULL ) + if ( ! M_dir ) { out << "(null)"; } @@ -306,7 +288,7 @@ DefDir::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Dir \"" << M_name << "\"" << std::endl; - if ( M_dir.get() == NULL ) + if ( ! M_dir ) { out << line_header << " (null)\n"; } @@ -321,7 +303,7 @@ std::ostream & DefReg::print( std::ostream & out ) const { out << "(definer \"" << M_name << "\" "; - if ( M_reg.get() == NULL ) + if ( ! M_reg ) { out << "(null)"; } @@ -337,7 +319,7 @@ DefReg::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Region \"" << M_name << "\"" << std::endl; - if ( M_reg.get() == NULL ) + if ( ! M_reg ) { out << line_header << " (null)\n"; } diff --git a/src/coach_lang_comp.h b/rcss/clang/coach_lang_comp.h similarity index 88% rename from src/coach_lang_comp.h rename to rcss/clang/coach_lang_comp.h index 0e584e0e..5c421fd5 100644 --- a/src/coach_lang_comp.h +++ b/rcss/clang/coach_lang_comp.h @@ -32,17 +32,17 @@ /* This file contains miscellaneous components for the coach language */ -#ifndef COACH_LANG_COMP_H -#define COACH_LANG_COMP_H +#ifndef RCSS_COACH_LANG_COMP_H +#define RCSS_COACH_LANG_COMP_H + +#include +#include +#include #include #include #include -#include "region.h" -#include "clangutil.h" -#include "clangaction.h" - namespace rcss { namespace clang { @@ -51,10 +51,10 @@ class DirComm; class DirNamed; class Dir { -public: - Dir() - { } +protected: + Dir() = default; +public: virtual ~Dir() { } @@ -100,17 +100,17 @@ class DirComm M_actions( actions ) { } - ~DirComm() + ~DirComm() override { clearActions(); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; bool isPositive() const { @@ -181,7 +181,7 @@ class DirComm } virtual - std::shared_ptr< Dir > deepCopy() const; + std::shared_ptr< Dir > deepCopy() const override; private: @@ -199,7 +199,7 @@ class DirNamed M_name( name ) { } - ~DirNamed() + ~DirNamed() override { } virtual @@ -209,11 +209,11 @@ class DirNamed } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; /* class specific */ std::string & getName() @@ -285,15 +285,15 @@ class TokClear : Token() { } - ~TokClear() + ~TokClear() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual std::shared_ptr< Token > deepCopy() const @@ -323,20 +323,20 @@ class TokRule { } virtual - ~TokRule() + ~TokRule() override { clearDirs(); } virtual - std::shared_ptr< Token > deepCopy() const; + std::shared_ptr< Token > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; /* class specific stuff */ int getTTL() const @@ -375,14 +375,17 @@ class DefAct; class DefRule; class Def { -public: +protected: Def() { } + explicit Def( const std::string & name ) : M_name( name ) { } +public: + virtual ~Def() { } @@ -439,7 +442,7 @@ class DefCond M_cond( def.M_cond->deepCopy() ) { } - ~DefCond() + ~DefCond() override { } DefCond & operator=( const DefCond & def ) @@ -451,17 +454,17 @@ class DefCond } virtual - std::shared_ptr< Def > deepCopy() const + std::shared_ptr< Def > deepCopy() const override { return std::shared_ptr< Def >( new DefCond( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; private: std::shared_ptr< Cond > M_cond; @@ -487,7 +490,7 @@ class DefDir M_dir( def.M_dir->deepCopy() ) { } - ~DefDir() + ~DefDir() override { } DefDir & operator=( const DefDir & def ) @@ -499,17 +502,17 @@ class DefDir } virtual - std::shared_ptr< Def > deepCopy() const + std::shared_ptr< Def > deepCopy() const override { return std::shared_ptr< Def >( new DefDir( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; private: std::shared_ptr< Dir > M_dir; @@ -535,7 +538,7 @@ class DefReg M_reg( def.M_reg->deepCopy() ) { } - ~DefReg() + ~DefReg() override { } DefReg & operator=( const DefReg & def ) @@ -547,17 +550,17 @@ class DefReg } virtual - std::shared_ptr< Def > deepCopy() const + std::shared_ptr< Def > deepCopy() const override { return std::shared_ptr< Def >( new DefReg( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; private: std::shared_ptr< Region > M_reg; @@ -583,7 +586,7 @@ class DefAct M_act( def.M_act->deepCopy() ) { } - ~DefAct() + ~DefAct() override { } DefAct & operator=( const DefAct & def ) @@ -595,17 +598,17 @@ class DefAct } virtual - std::shared_ptr< Def > deepCopy() const + std::shared_ptr< Def > deepCopy() const override { return std::shared_ptr< Def >( new DefAct( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; private: std::shared_ptr< Action > M_act; @@ -640,14 +643,14 @@ class DefRule { } virtual - std::shared_ptr< Def > deepCopy() const; + std::shared_ptr< Def > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; private: std::shared_ptr< Rule > M_rule; diff --git a/src/coach_lang_parser.ypp b/rcss/clang/coach_lang_parser.ypp similarity index 100% rename from src/coach_lang_parser.ypp rename to rcss/clang/coach_lang_parser.ypp diff --git a/src/coach_lang_tok.h b/rcss/clang/coach_lang_tok.h similarity index 95% rename from src/coach_lang_tok.h rename to rcss/clang/coach_lang_tok.h index 26bf1704..d406f55d 100644 --- a/src/coach_lang_tok.h +++ b/rcss/clang/coach_lang_tok.h @@ -19,18 +19,18 @@ * * ***************************************************************************/ -#ifndef CLANGLEXER_H -#define CLANGLEXER_H +#ifndef RCSS_CLANGLEXER_H +#define RCSS_CLANGLEXER_H -#include "compop.h" -#include "arithop.h" -#include "clangutil.h" +#include +#include +#include #include #undef yyFlexLexer #define yyFlexLexer RCSSCLangFLexLexer -//#include +//#include #include #define CLANG_MAX_STR 8192 diff --git a/src/coach_lang_tok.lpp b/rcss/clang/coach_lang_tok.lpp similarity index 99% rename from src/coach_lang_tok.lpp rename to rcss/clang/coach_lang_tok.lpp index 23f064c0..c1336cae 100644 --- a/src/coach_lang_tok.lpp +++ b/rcss/clang/coach_lang_tok.lpp @@ -28,9 +28,10 @@ #include "coach_lang_tok.h" #include "clangparser.h" #include "coach_lang_parser.hpp" -#include "types.h" #include +#define LEFT 1 +#define RIGHT -1 %} /* Definitions */ diff --git a/src/compop.cpp b/rcss/clang/compop.cpp similarity index 100% rename from src/compop.cpp rename to rcss/clang/compop.cpp diff --git a/src/compop.h b/rcss/clang/compop.h similarity index 95% rename from src/compop.h rename to rcss/clang/compop.h index 51ab2aec..59b76633 100644 --- a/src/compop.h +++ b/rcss/clang/compop.h @@ -19,8 +19,8 @@ * * ***************************************************************************/ -#ifndef COMPOP_H -#define COMPOP_H +#ifndef RCSS_CLANG_COMPOP_H +#define RCSS_CLANG_COMPOP_H #include @@ -56,10 +56,10 @@ class CompOp { CompOp( const comp_t & comp ); - CompOp( const CompOp & comp_op ); // not used + CompOp( const CompOp & comp_op ) = default; - CompOp& operator=( const CompOp & comp_op ); // not used + CompOp& operator=( const CompOp & comp_op ) = delete; // not used public: template< typename A, typename B > bool compare( const A & a, diff --git a/src/cond.cpp b/rcss/clang/cond.cpp similarity index 84% rename from src/cond.cpp rename to rcss/clang/cond.cpp index f312b008..d5008a18 100644 --- a/src/cond.cpp +++ b/rcss/clang/cond.cpp @@ -25,6 +25,8 @@ #include "cond.h" +#include + namespace rcss { namespace clang { @@ -107,7 +109,7 @@ CondPlayerPos::print( std::ostream & out ) const << " " << M_min_match << " " << M_max_match << " "; - if ( M_reg.get() == NULL ) + if ( ! M_reg ) { out << "(null)"; } @@ -129,7 +131,7 @@ CondPlayerPos::printPretty( std::ostream & out, << (M_our_side ? "our team" : "opponent") << " " << M_players << " " << "in:" << std::endl; - if ( M_reg.get() == NULL ) + if ( ! M_reg ) { out << line_header << " (null)\n"; } @@ -145,7 +147,7 @@ std::ostream & CondBallPos::print( std::ostream & out ) const { out << "(bpos "; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << "(null)"; } @@ -161,7 +163,7 @@ CondBallPos::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "is ball position at: " << std::endl; - if ( getRegion() == NULL ) + if ( ! getRegion() ) { out << line_header << " (null)\n"; } @@ -235,11 +237,9 @@ std::shared_ptr< Cond > CondAnd::deepCopy() const { Storage new_conds; - for ( Storage::const_iterator i = M_conds.begin(); - i != M_conds.end(); - ++i ) + for ( Storage::const_reference c : M_conds ) { - new_conds.push_back( (*i)->deepCopy() ); + new_conds.push_back( c->deepCopy() ); } std::shared_ptr< Cond > rval( new CondAnd( new_conds ) ); @@ -250,13 +250,11 @@ std::ostream & CondAnd::print( std::ostream & out ) const { out << "(and"; - for ( Storage::const_iterator iter = getConds().begin(); - iter != getConds().end(); - ++iter ) + for ( Storage::const_reference c : getConds() ) { - if ( *iter ) + if ( c ) { - out << " " << **iter; + out << " " << *c; } else { @@ -271,13 +269,11 @@ CondAnd::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "and" << std::endl; - for ( Storage::const_iterator iter = getConds().begin(); - iter != getConds().end(); - ++iter ) + for ( Storage::const_reference c : getConds() ) { - if ( *iter ) + if ( c ) { - (*iter)->printPretty( out, line_header + " +" ); + c->printPretty( out, line_header + " +" ); } else { @@ -290,17 +286,16 @@ CondAnd::printPretty( std::ostream & out, bool CondAnd::eval( const Context & context ) const { - for ( Storage::const_iterator iter = getConds().begin(); - iter != getConds().end(); - ++iter ) + for ( Storage::const_reference c : getConds() ) { - if ( ! *iter ) + if ( ! c ) { - throw util::NullErr( __FILE__, __LINE__, - "Null condition in CondAnd\n" ); + // throw util::NullErr( __FILE__, __LINE__, + // "Null condition in CondAnd\n" ); + throw std::logic_error( "Null condition in CondAnd\n" ); } - if ( !(*iter)->eval( context ) ) + if ( ! c->eval( context ) ) { return false; } @@ -318,11 +313,9 @@ std::shared_ptr< Cond > CondOr::deepCopy() const { Storage new_conds; - for ( Storage::const_iterator i = M_conds.begin(); - i != M_conds.end(); - ++i ) + for ( Storage::const_reference c : M_conds ) { - new_conds.push_back( (*i)->deepCopy() ); + new_conds.push_back( c->deepCopy() ); } std::shared_ptr< Cond > ptr( new CondOr( new_conds ) ); @@ -333,12 +326,11 @@ std::ostream & CondOr::print( std::ostream & out ) const { out << "(or"; - for( Storage::const_iterator iter = getConds().begin(); - iter != getConds().end(); ++iter) + for( Storage::const_reference c : getConds() ) { - if ( *iter ) + if ( c ) { - out << " " << **iter; + out << " " << *c; } else { @@ -353,12 +345,11 @@ CondOr::printPretty( std::ostream& out, const std::string& line_header ) const { out << line_header << "or" << std::endl; - for( Storage::const_iterator iter = getConds().begin(); - iter != getConds().end(); ++iter ) + for( Storage::const_reference c : getConds() ) { - if ( *iter ) + if ( c ) { - (*iter)->printPretty( out, line_header + " +" ); + c->printPretty( out, line_header + " +" ); } else { @@ -372,17 +363,16 @@ CondOr::printPretty( std::ostream& out, bool CondOr::eval( const Context & context ) const { - for ( Storage::const_iterator iter = getConds().begin(); - iter != getConds().end(); - ++iter ) + for ( Storage::const_reference c : getConds() ) { - if ( ! *iter ) + if ( ! c ) { - throw util::NullErr( __FILE__, __LINE__, - "Null condition in CondOr\n" ); + // throw util::NullErr( __FILE__, __LINE__, + // "Null condition in CondOr\n" ); + throw std::logic_error( "Null condition in CondOr\n" ); } - if ( (*iter)->eval( context ) ) + if ( c->eval( context ) ) { return true; } @@ -444,8 +434,9 @@ CondNot::eval( const Context & context ) const { if ( ! M_cond ) { - throw util::NullErr( __FILE__, __LINE__, - "Null condition in CondNot\n" ); + // throw util::NullErr( __FILE__, __LINE__, + // "Null condition in CondNot\n" ); + throw std::logic_error( "Null condition in CondNot\n" ); } else { diff --git a/src/cond.h b/rcss/clang/cond.h similarity index 82% rename from src/cond.h rename to rcss/clang/cond.h index 7ef77941..d8121027 100644 --- a/src/cond.h +++ b/rcss/clang/cond.h @@ -19,13 +19,13 @@ * * ***************************************************************************/ -#ifndef CLANG_COND_H -#define CLANG_COND_H +#ifndef RCSS_CLANG_COND_H +#define RCSS_CLANG_COND_H -#include "clangutil.h" -#include "region.h" -#include "compop.h" -#include "rcssexceptions.h" +#include +#include +#include +//#include "rcssexceptions.h" #include #include @@ -91,9 +91,11 @@ class Cond { bool lookup( const CondUNum & cond ) const = 0; }; // end Context +protected: Cond() { } +public: virtual ~Cond() { } @@ -135,18 +137,18 @@ class CondBool M_state( state ) { } - ~CondBool() + ~CondBool() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & ) const + bool eval( const Context & ) const override { return M_state; } @@ -157,7 +159,7 @@ class CondBool } virtual - std::shared_ptr< Cond > deepCopy() const; + std::shared_ptr< Cond > deepCopy() const override; private: bool M_state; @@ -172,7 +174,7 @@ class CondPlayerPos M_our_side( false ), M_min_match( 1 ), M_max_match( 11 ) - {} + { } public: CondPlayerPos( const bool & our_side, const UNumSet & players, @@ -185,25 +187,25 @@ class CondPlayerPos M_max_match( max_match ), M_players( players ), M_reg( reg ) - {} + { } virtual - ~CondPlayerPos() + ~CondPlayerPos() override { } virtual - std::shared_ptr< Cond > deepCopy() const; + std::shared_ptr< Cond > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -216,7 +218,7 @@ class CondPlayerPos bool isTheirSide() const { - return !M_our_side; + return ! M_our_side; } int getMinMatch() const @@ -295,21 +297,21 @@ class CondBallPos M_reg( reg ) { } - ~CondBallPos() + ~CondBallPos() override { } virtual - std::shared_ptr< Cond > deepCopy() const; + std::shared_ptr< Cond > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -329,7 +331,7 @@ class CondBallOwner CondBallOwner() : Cond(), M_our_side( false ) - {} + { } public: CondBallOwner( const bool & our_side, @@ -337,26 +339,26 @@ class CondBallOwner : Cond(), M_our_side( our_side ), M_players( players ) - {} + { } - ~CondBallOwner() - {} + ~CondBallOwner() override + { } virtual - std::shared_ptr< Cond > deepCopy() const + std::shared_ptr< Cond > deepCopy() const override { return std::shared_ptr< Cond >( new CondBallOwner( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -426,24 +428,24 @@ class CondPlayMode M_pm( pm ) { } - ~CondPlayMode() + ~CondPlayMode() override { } virtual - std::shared_ptr< Cond > deepCopy() const + std::shared_ptr< Cond > deepCopy() const override { return std::shared_ptr< Cond >( new CondPlayMode( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -481,20 +483,20 @@ class CondAnd { } virtual - ~CondAnd(); + ~CondAnd() override; virtual - std::shared_ptr< Cond > deepCopy() const; + std::shared_ptr< Cond > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const; + bool eval( const Context & context ) const override; const Storage & getConds() const { @@ -524,20 +526,20 @@ class CondOr { } virtual - ~CondOr(); + ~CondOr() override; virtual - std::shared_ptr< Cond > deepCopy() const; + std::shared_ptr< Cond > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const; + bool eval( const Context & context ) const override; const Storage & getConds() const { @@ -563,21 +565,21 @@ class CondNot { } virtual - ~CondNot() + ~CondNot() override { } virtual - std::shared_ptr< Cond > deepCopy() const; + std::shared_ptr< Cond > deepCopy() const override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const; + bool eval( const Context & context ) const override; private: std::shared_ptr< Cond > M_cond; @@ -607,14 +609,14 @@ class CondNamed } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup ( *this ); } @@ -686,7 +688,7 @@ class CondTime : CondComp< int >( value, comp ) { } - ~CondTime() + ~CondTime() override { } virtual @@ -696,14 +698,14 @@ class CondTime } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -718,24 +720,24 @@ class CondOppGoal : CondComp< int >( value, comp ) { } - ~CondOppGoal() + ~CondOppGoal() override { } virtual - std::shared_ptr< Cond > deepCopy() const + std::shared_ptr< Cond > deepCopy() const override { return std::shared_ptr< Cond >( new CondOppGoal( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -749,24 +751,24 @@ class CondOurGoal : CondComp< int >( value, comp ) { } - ~CondOurGoal() + ~CondOurGoal() override { } virtual - std::shared_ptr< Cond > deepCopy() const + std::shared_ptr< Cond > deepCopy() const override { return std::shared_ptr< Cond >( new CondOurGoal( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -780,24 +782,24 @@ class CondGoalDiff : CondComp< int >( value, comp ) { } - ~CondGoalDiff() + ~CondGoalDiff() override { } virtual - std::shared_ptr< Cond > deepCopy() const + std::shared_ptr< Cond > deepCopy() const override { return std::shared_ptr< Cond >( new CondGoalDiff( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } @@ -827,24 +829,24 @@ class CondUNum M_set( players ) { } - ~CondUNum() + ~CondUNum() override { } virtual - std::shared_ptr< Cond > deepCopy() const + std::shared_ptr< Cond > deepCopy() const override { return std::shared_ptr< Cond >( new CondUNum( *this ) ); } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - bool eval( const Context & context ) const + bool eval( const Context & context ) const override { return context.lookup( *this ); } diff --git a/rcss/clang/fix_lexer_file.cmake b/rcss/clang/fix_lexer_file.cmake new file mode 100755 index 00000000..41b738f7 --- /dev/null +++ b/rcss/clang/fix_lexer_file.cmake @@ -0,0 +1,21 @@ +#!/usr/bin/cmake + +# This file contains the fix for the legacy code + +if(NOT DEFINED GENERATED_FILE_PATH) + message(FATAL_ERROR "Missing arguments for the fix_lexer_file script: GENERATED_FILE_PATH") +elseif(NOT DEFINED CORRECT_HEADER_NAME) + message(FATAL_ERROR "Missing arguments for the fix_lexer_file script: CORRECT_HEADER_NAME") +elseif(NOT DEFINED OUTPUT_FILE_PATH) + message(FATAL_ERROR "Missing arguments for the fix_lexer_file script: OUTPUT_FILE_PATH") +endif() + +# Replace #include in generated lexer files +file(READ ${GENERATED_FILE_PATH} FILE_CONTENTS) +string(REPLACE + "#include " # String to match + "#include \"${CORRECT_HEADER_NAME}\"" # With what to replace + FILE_CONTENTS # Where to put the result + "${FILE_CONTENTS}" # Input +) +file(WRITE ${OUTPUT_FILE_PATH} "${FILE_CONTENTS}") diff --git a/src/region.cpp b/rcss/clang/region.cpp similarity index 90% rename from src/region.cpp rename to rcss/clang/region.cpp index 3c967db0..acbbff13 100644 --- a/src/region.cpp +++ b/rcss/clang/region.cpp @@ -63,7 +63,7 @@ PointRel::print( std::ostream & out ) const { out << "(pt " << M_offset.getVec().getX() << " " << M_offset.getVec().getY() << " "; - if ( getOrigin() == NULL ) + if ( ! getOrigin() ) { out << "(null)"; } @@ -80,7 +80,7 @@ PointRel::printPretty( std::ostream & out, { out << line_header << "Point-Relative(" << M_offset.getVec().getX() << ", " << M_offset.getVec().getY() << " "; - if ( getOrigin() == NULL ) + if ( ! getOrigin() ) { out << "(null)"; } @@ -150,7 +150,7 @@ PointPlayer::printPretty( std::ostream & out, // PointArith::PointArith() // : Point(), -// M_arith_op( NULL ), +// M_arith_op(), // M_idx( 0 ) // { // } @@ -193,7 +193,7 @@ PointArith::print( std::ostream & out ) const { out << "("; - if ( M_points[ 0 ].get() == NULL ) + if ( ! M_points[ 0 ] ) { out << "(null)"; } @@ -204,9 +204,9 @@ PointArith::print( std::ostream & out ) const out << " "; - if ( M_arith_op == NULL ) + if ( ! M_arith_op ) { - out << "(null)"; + out << "(null)"; } else { @@ -215,9 +215,9 @@ PointArith::print( std::ostream & out ) const out << " "; - if ( M_points[ 1 ].get() == NULL ) + if ( ! M_points[ 1 ] ) { - out << "(null)"; + out << "(null)"; } else { @@ -233,7 +233,7 @@ PointArith::printPretty( std::ostream & out, { out << line_header << "Point-Arith" << std::endl; - if ( M_points[ 0 ].get() == NULL ) + if ( ! M_points[ 0 ] ) { out << line_header << " (null)\n"; } @@ -242,7 +242,7 @@ PointArith::printPretty( std::ostream & out, M_points[ 0 ]->printPretty( out, line_header + " " ); } - if ( M_points[ 1 ].get() == NULL ) + if ( ! M_points[ 1 ] ) { out << line_header << " (null)\n"; } @@ -251,7 +251,7 @@ PointArith::printPretty( std::ostream & out, M_points[ 1 ]->printPretty( out, line_header + " " ); } - if ( M_arith_op == NULL ) + if ( ! M_arith_op ) { out << line_header << " (null)\n"; } @@ -300,7 +300,7 @@ RegQuad::print( std::ostream & out ) const out << "(quad"; for ( unsigned int i = 0; i < 3; ++i ) { - if ( M_points[ i ].get() == NULL ) + if ( ! M_points[ i ] ) { out << " (null)"; } @@ -320,7 +320,7 @@ RegQuad::printPretty( std::ostream & out, << "Quadrangle: "; for ( unsigned int i = 0; i < 4; ++i ) { - if ( M_points[ i ].get() == NULL ) + if ( ! M_points[ i ] ) { out << "(null) "; } @@ -353,14 +353,14 @@ RegQuad::deepCopy() const /*** RegArc ***/ -RegArc::RegArc() - : M_start_rad( 0.0 ), - M_end_rad( 0.0 ), - M_start_ang( 0.0 ), - M_span_ang( 0.0 ) -{ +// RegArc::RegArc() +// : M_start_rad( 0.0 ), +// M_end_rad( 0.0 ), +// M_start_ang( 0.0 ), +// M_span_ang( 0.0 ) +// { -} +// } RegArc::RegArc( std::shared_ptr< Point > center, const double & start_rad, @@ -380,7 +380,7 @@ std::ostream & RegArc::print( std::ostream & out ) const { out << "(arc"; - if ( M_center.get() == NULL ) + if ( ! M_center ) { out << " (null)"; } @@ -403,7 +403,7 @@ RegArc::printPretty( std::ostream & out, out << line_header << "Arc: " << "center="; - if ( M_center.get() == NULL ) + if ( ! M_center ) { out << "(null)"; } @@ -447,17 +447,15 @@ std::ostream & RegUnion::print( std::ostream & out ) const { out << "(reg"; - for ( Storage::const_iterator iter = M_regs.begin(); - iter != M_regs.end(); - ++iter ) + for ( Storage::const_reference r : M_regs ) { - if ( ! *iter ) + if ( ! r ) { out << " (null)"; } else { - out << " " << **iter; + out << " " << *r; } } return out << ")"; @@ -468,17 +466,15 @@ RegUnion::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "Region Union:" << std::endl; - for ( Storage::const_iterator iter = M_regs.begin(); - iter != M_regs.end(); - ++iter ) + for ( Storage::const_reference r : M_regs ) { - if ( ! *iter ) + if ( ! r ) { out << line_header << "o (null)"; } else { - (*iter)->printPretty( out, line_header + "o " ); + r->printPretty( out, line_header + "o " ); } } return out; @@ -488,11 +484,9 @@ std::shared_ptr< Region > RegUnion::deepCopy() const { Storage regs; - for ( Storage::const_iterator i = M_regs.begin(); - i != M_regs.end(); - ++i ) + for ( Storage::const_reference r : M_regs ) { - regs.push_front( (*i)->deepCopy() ); + regs.push_front( r->deepCopy() ); } std::shared_ptr< Region > rval( new RegUnion( regs ) ); @@ -528,7 +522,7 @@ RegNamed::printPretty( std::ostream & out, // RegPoint::RegPoint() // : Region(), -// M_point( NULL ) +// M_point() // { // } @@ -563,7 +557,7 @@ RegPoint::~RegPoint() std::ostream & RegPoint::print( std::ostream & out ) const { - if ( M_point.get() == NULL ) + if ( ! M_point ) { return out << "(null)"; } @@ -578,7 +572,7 @@ RegPoint::printPretty( std::ostream & out, const std::string & line_header ) const { out << line_header << "region point\n"; - if ( M_point.get() == NULL ) + if ( ! M_point ) { return out << line_header << " (null)\n"; } @@ -605,7 +599,7 @@ RegTri::print( std::ostream & out ) const out << "(tri"; for ( unsigned int i = 0; i < 3; ++i ) { - if ( m_points[ i ].get() == NULL ) + if ( ! m_points[ i ] ) { out << " (null)"; } @@ -626,7 +620,7 @@ RegTri::printPretty( std::ostream & out, << "Triangle: "; for ( unsigned int i = 0; i < 3; ++i ) { - if ( m_points[ i ].get() == NULL ) + if ( ! m_points[ i ] ) { out << "(null) "; } @@ -670,7 +664,7 @@ RegRec::print( std::ostream & out ) const out << "(rec"; for ( unsigned int i = 0; i < 2; ++i ) { - if ( M_points[ i ].get() == NULL ) + if ( ! M_points[ i ] ) { out << " (null)"; } @@ -690,7 +684,7 @@ RegRec::printPretty( std::ostream & out, << "Rectangle: "; for ( unsigned int i = 0; i < 2; ++i ) { - if ( M_points[ i ].get() == NULL ) + if ( ! M_points[ i ] ) { out << "(null) "; } diff --git a/src/region.h b/rcss/clang/region.h similarity index 75% rename from src/region.h rename to rcss/clang/region.h index 8520f155..8ca78ba7 100644 --- a/src/region.h +++ b/rcss/clang/region.h @@ -27,12 +27,12 @@ /* This files defines a class region to specify regions for the coach messages */ -#ifndef CLANGREGION_H -#define CLANGREGION_H +#ifndef RCSS_CLANGREGION_H +#define RCSS_CLANGREGION_H -#include "vector.h" -#include "clangutil.h" -#include "arithop.h" +#include +#include +#include #include #include @@ -43,8 +43,8 @@ namespace clang { class Point { protected: - Point() - { } + Point() = default; + public: virtual ~Point() @@ -73,7 +73,7 @@ operator<<( std::ostream & os, class PointSimple : public Point { private: - PointSimple(); // not used + PointSimple() = delete; // not used public: PointSimple( const double & x, @@ -87,18 +87,18 @@ class PointSimple M_vec( vec ) { } - ~PointSimple() + ~PointSimple() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Point > deepCopy() const + std::shared_ptr< Point > deepCopy() const override { return std::shared_ptr< Point >( new PointSimple( *this ) ); } @@ -115,9 +115,9 @@ class PointSimple class PointRel : public Point { private: - PointRel(); // not used - PointRel( const PointRel & ); // not used - PointRel & operator=( const PointRel & ); // not used + PointRel() = delete; // not used + PointRel( const PointRel & ) = delete; // not used + PointRel & operator=( const PointRel & ) = delete; // not used public: PointRel( const double & x, @@ -135,18 +135,18 @@ class PointRel M_offset( offset ) { } - ~PointRel() + ~PointRel() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Point > deepCopy() const; + std::shared_ptr< Point > deepCopy() const override; PointSimple getOffset() const @@ -172,18 +172,18 @@ class PointBall : Point() { } - ~PointBall() + ~PointBall() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Point > deepCopy() const + std::shared_ptr< Point > deepCopy() const override { return std::shared_ptr< Point >( new PointBall( *this ) ); } @@ -202,18 +202,18 @@ class PointPlayer M_unum( unum ) { } - ~PointPlayer() + ~PointPlayer() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Point > deepCopy() const + std::shared_ptr< Point > deepCopy() const override { return std::shared_ptr< Point >( new PointPlayer( *this ) ); } @@ -228,27 +228,27 @@ class PointPlayer class PointArith : public Point { private: - PointArith(); // not used + PointArith() = delete; // not used public: PointArith( std::shared_ptr< Point > pt1, std::shared_ptr< Point > pt2, const util::ArithOp & arith_op ); PointArith( const PointArith & pt ); - ~PointArith() + ~PointArith() override { } PointArith & operator=( const PointArith & pt ); virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Point > deepCopy() const + std::shared_ptr< Point > deepCopy() const override { return std::shared_ptr< Point >( new PointArith( *this ) ); } @@ -261,8 +261,8 @@ class PointArith class Region { protected: - Region() - { } + Region() = default; + public: virtual ~Region() @@ -291,22 +291,20 @@ operator<<( std::ostream & os, class RegNull : public Region { public: - RegNull() - : Region() - { } + RegNull() = default; - ~RegNull() + ~RegNull() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const + std::shared_ptr< Region > deepCopy() const override { return std::shared_ptr< Region >( new RegNull( *this ) ); } @@ -315,26 +313,26 @@ class RegNull class RegQuad : public Region { private: - RegQuad(); // not used - RegQuad( const RegQuad & ); // not used - RegQuad & operator=( const RegQuad & ); // not used + RegQuad() = delete; // not used + RegQuad( const RegQuad & ) = delete; // not used + RegQuad & operator=( const RegQuad & ) = delete; // not used public: RegQuad( std::shared_ptr< Point > pt0, std::shared_ptr< Point > pt1, std::shared_ptr< Point > pt2, std::shared_ptr< Point > pt3 ); - ~RegQuad() + ~RegQuad() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const; + std::shared_ptr< Region > deepCopy() const override; private: std::shared_ptr< Point > M_points[ 4 ]; @@ -344,25 +342,25 @@ class RegQuad class RegArc : public Region { private: - RegArc(); // not used + RegArc() = delete; public: RegArc( std::shared_ptr< Point > center, const double & start_rad, const double & end_rad, const double & start_ang, const double & span_ang ); - ~RegArc() + ~RegArc() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const; + std::shared_ptr< Region > deepCopy() const override; private: /* start rad <= end_rad */ @@ -392,14 +390,14 @@ class RegUnion } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const; + std::shared_ptr< Region > deepCopy() const override; Storage & getRegions() { @@ -416,22 +414,22 @@ class RegUnion class RegNamed : public Region { private: - RegNamed(); // not used + RegNamed() = delete; // not used public: RegNamed( const std::string & name ) : Region(), M_name( name ) { } - ~RegNamed() + ~RegNamed() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual std::shared_ptr< Region > deepCopy() const @@ -447,23 +445,23 @@ class RegNamed class RegPoint : public Region { private: - RegPoint(); // not used - RegPoint( const RegPoint & point ) ; - RegPoint & operator=( const RegPoint & point ); // not used + RegPoint() = delete; // not used + RegPoint( const RegPoint & point ); + RegPoint & operator=( const RegPoint & point ) = delete; // not used public: RegPoint( std::shared_ptr< Point > point ); - ~RegPoint(); + ~RegPoint() override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const + std::shared_ptr< Region > deepCopy() const override { return std::shared_ptr< Region >( new RegPoint( *this ) ); } @@ -476,24 +474,24 @@ class RegPoint class RegTri : public Region { private: - RegTri(); // not used + RegTri() = delete; // not used public: RegTri( std::shared_ptr< Point > pt0, std::shared_ptr< Point > pt1, std::shared_ptr< Point > pt2 ); - ~RegTri() + ~RegTri() override { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const; + std::shared_ptr< Region > deepCopy() const override; private: std::shared_ptr< Point > m_points[ 3 ]; @@ -504,7 +502,7 @@ class RegTri class RegRec : public Region { private: - RegRec(); // not used + RegRec() = delete; // not used public: RegRec( std::shared_ptr< Point > pt0, @@ -514,14 +512,14 @@ class RegRec { } virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Region > deepCopy() const; + std::shared_ptr< Region > deepCopy() const override; private: std::shared_ptr< Point > M_points[ 2 ]; diff --git a/src/rule.cpp b/rcss/clang/rule.cpp similarity index 84% rename from src/rule.cpp rename to rcss/clang/rule.cpp index 21a56f95..4de63d05 100644 --- a/src/rule.cpp +++ b/rcss/clang/rule.cpp @@ -66,18 +66,15 @@ RuleIDList::print( std::ostream & o ) const else { bool space = false; - //for ( const_iterator i = begin(); i != end(); ++i ) - for ( std::list< RuleID >::const_iterator i = M_list.begin(); - i != M_list.end(); - ++i ) + for ( const RuleID & i : M_list ) { if ( space ) { - o << " " << *i; + o << " " << i; } else { - o << "(" << *i; + o << "(" << i; space = true; } } @@ -228,7 +225,7 @@ std::ostream & SimpleRule::print( std::ostream & out ) const { out << "("; - if ( getCond() == NULL ) + if ( ! getCond() ) { out << "(null)"; } @@ -237,11 +234,9 @@ SimpleRule::print( std::ostream & out ) const out << *getCond(); } - for ( Storage::const_iterator i = getDirs().begin(); - i != getDirs().end(); - ++i ) + for ( Storage::const_reference d : getDirs() ) { - out << " " << **i; + out << " " << *d; } return out << ")"; } @@ -251,7 +246,7 @@ SimpleRule::printPretty( std::ostream & out, const std::string & lineheader ) const { out << lineheader << "Simple Rule:\n"; - if ( getCond() == NULL ) + if ( ! getCond() ) { out << lineheader << " if:(null)\n"; } @@ -260,11 +255,9 @@ SimpleRule::printPretty( std::ostream & out, getCond()->printPretty( out, lineheader + " if: " ); } - for ( Storage::const_iterator i = getDirs().begin(); - i != getDirs().end(); - ++i ) + for ( Storage::const_reference dir : getDirs() ) { - (*i)->printPretty( out, lineheader + " -" ); + dir->printPretty( out, lineheader + " -" ); } return out; } @@ -273,11 +266,9 @@ std::shared_ptr< Rule > SimpleRule::deepCopy() const { Storage new_dirs; - for ( Storage::const_iterator i = getDirs().begin(); - i != getDirs().end(); - ++i ) + for ( Storage::const_reference dir : getDirs() ) { - new_dirs.push_back( (*i)->deepCopy() ); + new_dirs.push_back( dir->deepCopy() ); } std::shared_ptr< Rule > rval( new SimpleRule( getCond()->deepCopy(), new_dirs ) ); @@ -318,7 +309,7 @@ std::ostream & NestedRule::print( std::ostream & out ) const { out << "("; - if ( getCond() == NULL ) + if ( ! getCond() ) { out << "(null)"; } @@ -327,11 +318,9 @@ NestedRule::print( std::ostream & out ) const out << *getCond(); } - for ( Storage::const_iterator i = getRules().begin(); - i != getRules().end(); - ++i ) + for ( Storage::const_reference rule : getRules() ) { - out << " " << **i; + out << " " << *rule; } return out << ")"; } @@ -341,7 +330,7 @@ NestedRule::printPretty( std::ostream & out, const std::string & lineheader ) const { out << lineheader << "Nested Rule:\n"; - if ( getCond() == NULL ) + if ( ! getCond() ) { out << lineheader << " if:(null)\n"; } @@ -350,11 +339,9 @@ NestedRule::printPretty( std::ostream & out, getCond()->printPretty( out, lineheader + " if: " ); } - for ( Storage::const_iterator i = getRules().begin(); - i != getRules().end(); - ++i ) + for ( Storage::const_reference rule : getRules() ) { - (*i)->printPretty( out, lineheader + " -" ); + rule->printPretty( out, lineheader + " -" ); } return out; } @@ -363,11 +350,9 @@ std::shared_ptr< Rule > NestedRule::deepCopy() const { Storage new_rules; - for ( Storage::const_iterator i = getRules().begin(); - i != getRules().end(); - ++i ) + for ( Storage::const_reference rule : getRules() ) { - new_rules.push_back( (*i)->deepCopy() ); + new_rules.push_back( rule->deepCopy() ); } std::shared_ptr< Rule > rval( new NestedRule( getCond()->deepCopy(), new_rules ) ); diff --git a/src/rule.h b/rcss/clang/rule.h similarity index 91% rename from src/rule.h rename to rcss/clang/rule.h index 5ae61b58..027e4701 100644 --- a/src/rule.h +++ b/rcss/clang/rule.h @@ -105,7 +105,7 @@ class CondRule CondRule( std::shared_ptr< Cond > cond ); virtual - ~CondRule(); + ~CondRule() override; const std::shared_ptr< const Cond > & getCond() const { @@ -125,14 +125,14 @@ class SimpleRule SimpleRule( std::shared_ptr< Cond > cond ); SimpleRule( std::shared_ptr< Cond > cond, const Storage & dirs ); - ~SimpleRule(); + ~SimpleRule() override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual std::shared_ptr< Rule > deepCopy() const; @@ -155,17 +155,17 @@ class NestedRule const Storage & rules ); virtual - ~NestedRule(); + ~NestedRule() override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Rule > deepCopy() const; + std::shared_ptr< Rule > deepCopy() const override; const Storage & getRules() const; @@ -179,17 +179,17 @@ class IDListRule IDListRule(); IDListRule( const RuleIDList & rules ); - ~IDListRule(); + ~IDListRule() override; virtual - std::ostream & print( std::ostream & out ) const; + std::ostream & print( std::ostream & out ) const override; virtual std::ostream & printPretty( std::ostream & out, - const std::string & line_header ) const; + const std::string & line_header ) const override; virtual - std::shared_ptr< Rule > deepCopy() const; + std::shared_ptr< Rule > deepCopy() const override; const RuleIDList & getIDList() const; diff --git a/rcss/conf/CMakeLists.txt b/rcss/conf/CMakeLists.txt new file mode 100644 index 00000000..411c43f5 --- /dev/null +++ b/rcss/conf/CMakeLists.txt @@ -0,0 +1,49 @@ +add_library(RCSSConfParser SHARED + parser.cpp + builder.cpp + statushandler.cpp + streamstatushandler.cpp + paramgetter.hpp + paramsetter.hpp +) +add_library(RCSS::ConfParser ALIAS RCSSConfParser) + +target_link_libraries(RCSSConfParser + PUBLIC + Boost::boost +) + +target_compile_definitions(RCSSConfParser + PUBLIC + HAVE_CONFIG_H +) + +target_include_directories(RCSSConfParser + PUBLIC + ${PROJECT_SOURCE_DIR} + ${PROJECT_BINARY_DIR} +) + +set_target_properties(RCSSConfParser + PROPERTIES + SOVERSION 3 + VERSION 3.0.0 + LIBRARY_OUTPUT_NAME "rcssconfparser" +) + +set_property(TARGET RCSSConfParser PROPERTY + PUBLIC_HEADER + builder.hpp + parser.hpp + paramgetter.hpp + paramsetter.hpp + statushandler.hpp + streamstatushandler.hpp +) + +install(TARGETS RCSSConfParser + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Libraries + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rcss/conf +) diff --git a/rcssbase/conf/Makefile.am b/rcss/conf/Makefile.am similarity index 91% rename from rcssbase/conf/Makefile.am rename to rcss/conf/Makefile.am index 4ff15d21..453c15bd 100644 --- a/rcssbase/conf/Makefile.am +++ b/rcss/conf/Makefile.am @@ -29,9 +29,9 @@ librcssconfparser_la_LDFLAGS = -version-info 3:0:0 #librcssconfparser_la_LIBADD = $(BOOST_FILESYSTEM_LIB) -rcssbase_confdir = $(includedir)/rcssbase/conf +librcssconfparserincludedir = $(includedir)/rcss/conf -rcssbase_conf_HEADERS = \ +librcssconfparserinclude_HEADERS = \ builder.hpp \ parser.hpp \ paramgetter.hpp \ @@ -44,6 +44,9 @@ AM_CFLAGS = -W -Wall AM_CXXFLAGS = -W -Wall AM_LD_FLAGS = +EXTRA_DIST = \ + CMakeLists.txt + CLEANFILES = \ *~ \ core diff --git a/rcssbase/conf/builder.cpp b/rcss/conf/builder.cpp similarity index 79% rename from rcssbase/conf/builder.cpp rename to rcss/conf/builder.cpp index afc633e2..67283a43 100644 --- a/rcssbase/conf/builder.cpp +++ b/rcss/conf/builder.cpp @@ -27,12 +27,7 @@ #include "statushandler.hpp" -#ifdef HAVE_SSTREAM #include -#else -#include -#endif - #include #include @@ -46,7 +41,7 @@ Builder::Builder( const std::string & progname, : m_err( false ), m_progname( progname ), m_version( version ), - m_parent( NULL ), + m_parent( nullptr ), m_generic_help_requested( false ), m_detailed_help_requested( false ), m_module_name( module_name ) @@ -83,11 +78,9 @@ Builder::createConfFile( std::ostream & conf, } else { - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->createConfFile( conf, module_name ); + c->createConfFile( conf, module_name ); } } } @@ -133,18 +126,14 @@ Builder::parseError( const std::string & curr, requestGenericHelp(); m_err = true; - for ( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for ( StatusHandler * h : m_handlers ) { - (*i)->parseError( curr, err, name, lineno ); + h->parseError( curr, err, name, lineno ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->parseError( curr, err, name, lineno ); + c->parseError( curr, err, name, lineno ); } } @@ -158,18 +147,14 @@ Builder::buildError( const std::string & module, requestDetailedHelp(); m_err = true; - for ( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for ( StatusHandler * h : m_handlers ) { - (*i)->buildError( module, param, err, name, lineno ); + h->buildError( module, param, err, name, lineno ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->buildError( module, param, err, name, lineno ); + c->buildError( module, param, err, name, lineno ); } } @@ -180,54 +165,42 @@ Builder::buildWarning( const std::string & module, const std::string & name, int lineno ) { - for ( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for ( StatusHandler * h : m_handlers ) { - (*i)->buildWarning( module, param, warn, name, lineno ); + h->buildWarning( module, param, warn, name, lineno ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->buildWarning( module, param, warn, name, lineno ); + c->buildWarning( module, param, warn, name, lineno ); } } void Builder::creatingConfFile( const std::string & conf_name ) { - for ( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for ( StatusHandler * h : m_handlers ) { - (*i)->creatingConfFile( conf_name ); + h->creatingConfFile( conf_name ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->creatingConfFile( conf_name ); + c->creatingConfFile( conf_name ); } } void Builder::createdConfFile( const std::string & conf_name ) { - for ( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for ( StatusHandler * h : m_handlers ) { - (*i)->createdConfFile( conf_name ); + h->createdConfFile( conf_name ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->createdConfFile( conf_name ); + c->createdConfFile( conf_name ); } } @@ -235,18 +208,14 @@ void Builder::confCreationFailed( const std::string & conf_name, int error ) { - for( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for( StatusHandler * h : m_handlers ) { - (*i)->confCreationFailed( conf_name, error ); + h->confCreationFailed( conf_name, error ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->confCreationFailed( conf_name, error ); + c->confCreationFailed( conf_name, error ); } } @@ -258,18 +227,14 @@ Builder::includeFailed( const std::string & filename, { m_err = true; - for ( std::list< StatusHandler * >::iterator i = m_handlers.begin(); - i != m_handlers.end(); - ++i ) + for ( StatusHandler * h : m_handlers ) { - (*i)->includeFailed( filename, error, name, lineno ); + h->includeFailed( filename, error, name, lineno ); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->includeFailed( filename, error, name, lineno ); + c->includeFailed( filename, error, name, lineno ); } } @@ -333,11 +298,9 @@ Builder::requestGenericHelp() void Builder::requestDetailedHelp( const std::string & module_name ) { - for( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for( Builder * c : m_children ) { - (*i)->requestDetailedHelp( module_name ); + c->requestDetailedHelp( module_name ); } doRequestDetailedHelp( module_name ); } @@ -357,24 +320,20 @@ void Builder::addedToParser( Parser & p ) { m_parser = &p; - for( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for( Builder * c : m_children ) { - (*i)->addedToParser( p ); + c->addedToParser( p ); } } void Builder::removedFromParser() { - m_parser = NULL; - m_parent = NULL; - for( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + m_parser = nullptr; + m_parent = nullptr; + for( Builder * c : m_children ) { - (*i)->removedFromParser(); + c->removedFromParser(); } } @@ -396,18 +355,16 @@ Builder::displayHelp() { if ( genericHelpRequested() ) { - if ( m_parent == NULL ) + if ( m_parent == nullptr ) { displayUsage( m_progname ); } displayGenericHelp(); - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - (*i)->displayGenericHelp(); + c->displayGenericHelp(); } if ( detailedHelpRequested() ) @@ -415,13 +372,11 @@ Builder::displayHelp() displayDetailedHelp(); } - for ( std::list< Builder * >::iterator i = m_children.begin(); - i != m_children.end(); - ++i ) + for ( Builder * c : m_children ) { - if ( (*i)->detailedHelpRequested() ) + if ( c->detailedHelpRequested() ) { - (*i)->displayDetailedHelp(); + c->displayDetailedHelp(); } } } @@ -491,48 +446,40 @@ Builder::displayDetailedHelp() std::cout << m_module_name << " Options:\n"; std::ostream & conf = std::cout; - for ( IntMap::iterator iter = m_ints.begin(); - iter != m_ints.end(); - ++iter ) + for ( IntMap::const_reference i : m_ints ) { displayHelpEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } - for ( BoolMap::iterator iter = m_bools.begin(); - iter != m_bools.end(); - ++iter ) + for ( BoolMap::const_reference i : m_bools ) { displayHelpEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } - for ( DoubMap::iterator iter = m_doubs.begin(); - iter != m_doubs.end(); - ++iter ) + for ( DoubMap::const_reference i : m_doubs ) { displayHelpEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } - for ( StrMap::iterator iter = m_strs.begin(); - iter != m_strs.end(); - ++iter ) + for ( StrMap::const_reference i : m_strs ) { displayHelpEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } } @@ -768,48 +715,40 @@ Builder::doCreateConfFile( std::ostream& conf ) "" ); m_parsed_version = m_version; - for ( IntMap::iterator iter = m_ints.begin(); - iter != m_ints.end(); - ++iter ) + for ( IntMap::const_reference i : m_ints ) { createConfFileEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } - for ( BoolMap::iterator iter = m_bools.begin(); - iter != m_bools.end(); - ++iter ) + for ( BoolMap::const_reference i : m_bools ) { createConfFileEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } - for ( DoubMap::iterator iter = m_doubs.begin(); - iter != m_doubs.end(); - ++iter ) + for ( DoubMap::const_reference i : m_doubs ) { createConfFileEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } - for ( StrMap::iterator iter = m_strs.begin(); - iter != m_strs.end(); - ++iter ) + for ( StrMap::const_reference i : m_strs ) { createConfFileEntry( conf, m_module_name, - iter->first, - iter->second.get(), - iter->second.desc() ); + i.first, + i.second.get(), + i.second.desc() ); } } diff --git a/rcssbase/conf/builder.hpp b/rcss/conf/builder.hpp similarity index 100% rename from rcssbase/conf/builder.hpp rename to rcss/conf/builder.hpp diff --git a/rcssbase/conf/paramgetter.hpp b/rcss/conf/paramgetter.hpp similarity index 97% rename from rcssbase/conf/paramgetter.hpp rename to rcss/conf/paramgetter.hpp index 806b7ceb..fdf49b94 100644 --- a/rcssbase/conf/paramgetter.hpp +++ b/rcss/conf/paramgetter.hpp @@ -22,7 +22,7 @@ #ifndef PARAMGETTER_HPP #define PARAMGETTER_HPP -#include +#include namespace rcss { namespace conf { @@ -121,7 +121,7 @@ class Getter { } private: - boost::shared_ptr< rcss::conf::priv::GetterBase< RVal > > m_getter; + std::shared_ptr< rcss::conf::priv::GetterBase< RVal > > m_getter; }; template< typename RVal > diff --git a/rcssbase/conf/paramsetter.hpp b/rcss/conf/paramsetter.hpp similarity index 97% rename from rcssbase/conf/paramsetter.hpp rename to rcss/conf/paramsetter.hpp index e19df082..dd944da9 100644 --- a/rcssbase/conf/paramsetter.hpp +++ b/rcss/conf/paramsetter.hpp @@ -22,7 +22,7 @@ #ifndef PARAMSETTER_HPP #define PARAMSETTER_HPP -#include +#include namespace rcss { namespace conf { @@ -124,7 +124,7 @@ class Setter { } private: - boost::shared_ptr< rcss::conf::priv::SetterBase< Arg > > m_setter; + std::shared_ptr< rcss::conf::priv::SetterBase< Arg > > m_setter; }; template< typename Arg > diff --git a/rcssbase/conf/parser.cpp b/rcss/conf/parser.cpp similarity index 81% rename from rcssbase/conf/parser.cpp rename to rcss/conf/parser.cpp index 938e65cc..590dae8a 100644 --- a/rcssbase/conf/parser.cpp +++ b/rcss/conf/parser.cpp @@ -27,14 +27,9 @@ #include "builder.hpp" -#ifdef HAVE_SSTREAM +#include #include -#else -#include -#endif - #include - #include #include @@ -51,8 +46,6 @@ # include #endif -#include -#include namespace { @@ -186,11 +179,8 @@ bool Parser::parse( int argc, const char * const * argv ) { -#ifdef HAVE_SSTREAM std::stringstream strm; -#else - std::strstream strm; -#endif + if ( argc > 1 ) { std::string arg( argv[1] ); @@ -218,15 +208,10 @@ Parser::parse( int argc, strm << ' ' << arg; } } -#ifndef HAVE_SSTREAM - strm << std::ends; -#else + strm << std::flush; -#endif + bool res = rcss::Parser::parse( strm, "cmd line args" ); -#ifndef HAVE_SSTREAM - strm.freeze( false ); -#endif return res; } @@ -253,7 +238,7 @@ bool Parser::parseCreateConf( const boost::filesystem::path & conf_name, const std::string & module_name ) { - std::string native_path = conf_name.BOOST_FS_FILE_STRING(); + std::string native_path = conf_name.string(); boost::filesystem::ifstream conf( conf_name ); if ( ! conf.is_open() ) @@ -320,13 +305,7 @@ Parser::include( const char * begin, boost::filesystem::path path; try { - path = boost::filesystem::path( incname -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + path = boost::filesystem::path( incname ); } catch ( ... ) { @@ -356,20 +335,14 @@ Parser::include( const char * begin, || curr_path == "cmd line args" || curr_path == "anonymous stream" ) { - full_name = boost::filesystem::BOOST_FS_ABSOLUTE( path ); + full_name = boost::filesystem::absolute( path ); } else { try { - boost::filesystem::path branch( curr_path -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); - branch = branch.BOOST_FS_PARENT_PATH(); + boost::filesystem::path branch( curr_path ); + branch = branch.parent_path(); full_name = branch / path; } catch ( const std::exception & e ) @@ -388,7 +361,7 @@ Parser::include( const char * begin, i != m_stack.end(); ++i ) { - if ( full_name.BOOST_FS_FILE_STRING() == i->m_name ) + if ( full_name.string() == i->m_name ) { // file already included so ignore it return true; @@ -403,14 +376,14 @@ Parser::include( const char * begin, if ( strm.is_open() && strm.good() ) { bool rval = parse( strm, - full_name.BOOST_FS_FILE_STRING() ); + full_name.string() ); strm.close(); return rval; } else { - m_builder.includeFailed( full_name.BOOST_FS_FILE_STRING(), + m_builder.includeFailed( full_name.string(), "read failed", m_stack.front().m_name, m_stack.front().m_lineno ); @@ -419,7 +392,7 @@ Parser::include( const char * begin, } else { - m_builder.includeFailed( full_name.BOOST_FS_FILE_STRING(), + m_builder.includeFailed( full_name.string(), "cannot include a directory", m_stack.front().m_name, m_stack.front().m_lineno ); @@ -428,7 +401,7 @@ Parser::include( const char * begin, } else { - m_builder.includeFailed( full_name.BOOST_FS_FILE_STRING(), + m_builder.includeFailed( full_name.string(), "file not found", m_stack.front().m_name, m_stack.front().m_lineno ); @@ -545,6 +518,7 @@ bool Parser::boostParse() { using namespace rcss::conf; + using namespace std::placeholders; sc::assertion< Errors > expect_assign( ASSIGN_EXPECTED ); sc::assertion< Errors > expect_delim( DELIM_EXPECTED ); @@ -566,8 +540,8 @@ Parser::boostParse() sc::rule<> junk_p = ( ws_p - | comment_p[ boost::bind( &Parser::countNewLines, this, _1, _2 ) ] - | newline_p[ boost::bind( &Parser::countNewLines, this, _1, _2 ) ] + | comment_p[ std::bind( &Parser::countNewLines, this, _1, _2 ) ] + | newline_p[ std::bind( &Parser::countNewLines, this, _1, _2 ) ] ); sc::rule<> ignore_p = *junk_p; @@ -608,40 +582,28 @@ Parser::boostParse() >> ignore_p >> expect_assign( assign_p ) >> ignore_p - >> expect_string( string_p[ boost::bind( &Parser::include, - this, - _1, _2 ) ] ) + >> expect_string( string_p[ std::bind( &Parser::include, this, _1, _2 ) ] ) ); sc::rule<> delim_p = sc::str_p( "::" ); sc::rule<> param_name_p - = ( (simple_str_p - flag_p)[ boost::bind( &Parser::setParamName, - this, - _1, _2 ) ] + = ( (simple_str_p - flag_p)[ std::bind( &Parser::setParamName, this, _1, _2 ) ] >> ( expect_delim( delim_p ) >> ( simple_str_p - sc::as_lower_d[ "help" ] - )[ boost::bind( &Parser::appendParamName, - this, - _1, _2 ) ] + )[ std::bind( &Parser::appendParamName, this, _1, _2 ) ] ) >> *( delim_p >> ( simple_str_p - sc::as_lower_d[ "help" ] - )[ boost::bind( &Parser::appendParamName, - this, - _1, _2 ) ] + )[ std::bind( &Parser::appendParamName, this, _1, _2 ) ] ) ); sc::rule<> module_name_p - = ( ( simple_str_p - flag_p )[ boost::bind( &Parser::setParamName, - this, - _1, _2 ) ] + = ( ( simple_str_p - flag_p )[ std::bind( &Parser::setParamName, this, _1, _2 ) ] >> *( delim_p >> ( simple_str_p - sc::as_lower_d[ "help" ] - )[ boost::bind( &Parser::appendParamName, - this, - _1, _2 ) ] + )[ std::bind( &Parser::appendParamName, this, _1, _2 ) ] ) ); @@ -658,32 +620,20 @@ Parser::boostParse() >> ignore_p >> expect_assign( assign_p ) >> ignore_p - >> expect_value( true_p[ boost::bind( &Parser::buildBool, - this, - true ) ] - | false_p[ boost::bind( &Parser::buildBool, - this, - false ) ] - | sc::strict_real_p[ boost::bind( &Parser::buildReal, - this, - _1 ) ] - | sc::int_p[ boost::bind( &Parser::buildInt, - this, - _1 ) ] - | string_p[ boost::bind( &Parser::buildString, - this, - _1, _2 ) ] + >> expect_value( true_p[ std::bind( &Parser::buildBool, this, true ) ] + | false_p[ std::bind( &Parser::buildBool, this, false ) ] + | sc::strict_real_p[ std::bind( &Parser::buildReal, this, _1 ) ] + | sc::int_p[ std::bind( &Parser::buildInt, this, _1 ) ] + | string_p[ std::bind( &Parser::buildString, this, _1, _2 ) ] ) ); sc::rule<> data_p - = ( sc::as_lower_d[ "help" ][ boost::bind( &Parser::requestGenericHelp, - this ) ] + = ( sc::as_lower_d[ "help" ][ std::bind( &Parser::requestGenericHelp, this ) ] | ( module_name_p >> delim_p >> sc::as_lower_d[ "help" ] - )[ boost::bind( &Parser::requestDetailedHelp, - this ) ] + )[ std::bind( &Parser::requestDetailedHelp, this ) ] | param_p | includerule_p ); @@ -694,9 +644,7 @@ Parser::boostParse() >> data_p ) ); sc::rule<> input_p - = conf_guard( *item_p )[ boost::bind( &ParseErrorHandler::parseError, - this, - _1, _2 ) ]; + = conf_guard( *item_p )[ std::bind( &ParseErrorHandler::parseError, this, _1, _2 ) ]; // BOOST_SPIRIT_DEBUG_RULE(ws_p); // BOOST_SPIRIT_DEBUG_RULE(newline_p); diff --git a/rcssbase/conf/parser.hpp b/rcss/conf/parser.hpp similarity index 99% rename from rcssbase/conf/parser.hpp rename to rcss/conf/parser.hpp index d4ec00d9..8f443081 100644 --- a/rcssbase/conf/parser.hpp +++ b/rcss/conf/parser.hpp @@ -22,7 +22,7 @@ #ifndef PARSER_HPP #define PARSER_HPP -#include "rcssbase/parser.h" +#include #include diff --git a/rcssbase/conf/statushandler.cpp b/rcss/conf/statushandler.cpp similarity index 100% rename from rcssbase/conf/statushandler.cpp rename to rcss/conf/statushandler.cpp diff --git a/rcssbase/conf/statushandler.hpp b/rcss/conf/statushandler.hpp similarity index 100% rename from rcssbase/conf/statushandler.hpp rename to rcss/conf/statushandler.hpp diff --git a/rcssbase/conf/streamstatushandler.cpp b/rcss/conf/streamstatushandler.cpp similarity index 93% rename from rcssbase/conf/streamstatushandler.cpp rename to rcss/conf/streamstatushandler.cpp index 288231b4..0bb19871 100644 --- a/rcssbase/conf/streamstatushandler.cpp +++ b/rcss/conf/streamstatushandler.cpp @@ -144,17 +144,7 @@ StreamStatusHandler::loadFailed( const std::string & libname, for( std::vector< boost::filesystem::path >::const_iterator i = avail.begin(); i != avail.end(); ++i ) { - M_errstrm << "\t" -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION > 2 - << i->string() -#else -# ifdef BOOST_FILESYSTEM_NO_DEPRECATED - << i->file_string() -# else - << i->native_file_string() -# endif -#endif - << std::endl; + M_errstrm << "\t" << i->string() << std::endl; } } } diff --git a/rcssbase/conf/streamstatushandler.hpp b/rcss/conf/streamstatushandler.hpp similarity index 100% rename from rcssbase/conf/streamstatushandler.hpp rename to rcss/conf/streamstatushandler.hpp diff --git a/rcssbase/factory.hpp b/rcss/factory.hpp similarity index 100% rename from rcssbase/factory.hpp rename to rcss/factory.hpp diff --git a/rcss/gzip/CMakeLists.txt b/rcss/gzip/CMakeLists.txt new file mode 100644 index 00000000..b36d9d64 --- /dev/null +++ b/rcss/gzip/CMakeLists.txt @@ -0,0 +1,46 @@ +add_library(RCSSGZ SHARED + gzfstream.cpp + gzstream.cpp +) +add_library(RCSS::GZ ALIAS RCSSGZ) + +target_link_libraries(RCSSGZ + PUBLIC + Boost::boost +) + +target_compile_definitions(RCSSGZ + PUBLIC + HAVE_CONFIG_H +) + +target_include_directories(RCSSGZ + PUBLIC + ${PROJECT_SOURCE_DIR} + ${PROJECT_BINARY_DIR} +) + +set_target_properties(RCSSGZ + PROPERTIES + SOVERSION 1 + VERSION 1.0.0 + LIBRARY_OUTPUT_NAME "rcssgz" +) + +set_property(TARGET RCSSGZ PROPERTY + PUBLIC_HEADER + gzstream.hpp + gzfstream.hpp +) + +target_link_libraries(RCSSGZ + PRIVATE + ZLIB::ZLIB +) + +install(TARGETS RCSSGZ + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Libraries + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rcss/gzip +) diff --git a/rcssbase/gzip/Makefile.am b/rcss/gzip/Makefile.am similarity index 89% rename from rcssbase/gzip/Makefile.am rename to rcss/gzip/Makefile.am index 600a3500..5ad2f46e 100644 --- a/rcssbase/gzip/Makefile.am +++ b/rcss/gzip/Makefile.am @@ -27,11 +27,11 @@ librcssgz_la_LDFLAGS = -version-info 1:0:0 # 6. If any interfaces have been removed since the last public release, # then set AGE to 0. -librcssgz_la_LIBADD = @GZ_LIBS@ +librcssgz_la_LIBADD = -rcssbase_gzipdir = $(includedir)/rcssbase/gzip +librcssgzincludedir = $(includedir)/rcss/gzip -rcssbase_gzip_HEADERS = \ +librcssgzinclude_HEADERS = \ gzstream.hpp \ gzfstream.hpp @@ -40,6 +40,9 @@ AM_CFLAGS = -W -Wall AM_CXXFLAGS = -W -Wall AM_LDFLAGS = +EXTRA_DIST = \ + CMakeLists.txt + CLEANFILES = \ *~ \ core diff --git a/rcssbase/gzip/gzfstream.cpp b/rcss/gzip/gzfstream.cpp similarity index 96% rename from rcssbase/gzip/gzfstream.cpp rename to rcss/gzip/gzfstream.cpp index 5f15d994..a0e5e372 100644 --- a/rcssbase/gzip/gzfstream.cpp +++ b/rcss/gzip/gzfstream.cpp @@ -52,7 +52,7 @@ struct gzfilebuf_impl { gzfilebuf_impl() : open_mode_( static_cast< std::ios_base::openmode >( 0 ) ) #ifdef HAVE_LIBZ - , file_( NULL ) + , file_( nullptr ) #endif { } }; @@ -66,7 +66,7 @@ struct gzfilebuf_impl { gzfilebuf::gzfilebuf() : M_impl( new gzfilebuf_impl ) , M_buf_size( 8192 ) - , M_buf( NULL ) + , M_buf( nullptr ) , M_remained_size( 0 ) { @@ -98,7 +98,7 @@ gzfilebuf::is_open() { #ifdef HAVE_LIBZ if ( M_impl - && M_impl->file_ != NULL ) + && M_impl->file_ != nullptr ) { return true; } @@ -116,7 +116,7 @@ gzfilebuf::open( const char * path, int level, int strategy ) { - gzfilebuf * ret = NULL; + gzfilebuf * ret = nullptr; #ifdef HAVE_LIBZ if ( ! M_impl ) { @@ -143,7 +143,7 @@ gzfilebuf::open( const char * path, M_impl->file_ = gzopen( path, mode_str.c_str() ); - if ( M_impl->file_ == NULL ) + if ( M_impl->file_ == nullptr ) { return ret; } @@ -191,21 +191,21 @@ gzfilebuf::close() throw() if ( ! M_impl ) { - return NULL; + return nullptr; } - if ( M_impl->file_ == NULL ) + if ( M_impl->file_ == nullptr ) { - return NULL; + return nullptr; } // TODO: checking close status... gzclose( M_impl->file_ ); - M_impl->file_ = NULL; + M_impl->file_ = nullptr; M_impl->open_mode_ = static_cast< std::ios_base::openmode >( 0 ); } #endif - return NULL; + return nullptr; } /*-------------------------------------------------------------------*/ @@ -329,10 +329,10 @@ gzfilebuf::destroyInternalBuffer() throw() if ( M_buf ) { delete [] M_buf; - M_buf = NULL; + M_buf = nullptr; M_remained_size = 0; - this->setg( NULL, NULL, NULL ); - this->setp( NULL, NULL ); + this->setg( nullptr, nullptr, nullptr ); + this->setp( nullptr, nullptr ); } } diff --git a/rcssbase/gzip/gzfstream.hpp b/rcss/gzip/gzfstream.hpp similarity index 99% rename from rcssbase/gzip/gzfstream.hpp rename to rcss/gzip/gzfstream.hpp index 791f052d..bf62c4ae 100644 --- a/rcssbase/gzip/gzfstream.hpp +++ b/rcss/gzip/gzfstream.hpp @@ -25,8 +25,7 @@ #include #include - -#include +#include namespace rcss { @@ -83,7 +82,7 @@ class gzfilebuf private: //! Pimpl ideom. the instance of a file buffer. - boost::scoped_ptr< gzfilebuf_impl > M_impl; + std::unique_ptr< gzfilebuf_impl > M_impl; //! buffer size (default: 8192) std::size_t M_buf_size; @@ -105,7 +104,7 @@ class gzfilebuf /*! \brief default constructor. - Default constructor creates an internal file buffer using boost::scoped_ptr. + Default constructor creates an internal file buffer using std::unique_ptr. This buffer is deleted automatically. */ gzfilebuf(); diff --git a/rcssbase/gzip/gzstream.cpp b/rcss/gzip/gzstream.cpp similarity index 94% rename from rcssbase/gzip/gzstream.cpp rename to rcss/gzip/gzstream.cpp index 1af73e0e..7b870bcf 100644 --- a/rcssbase/gzip/gzstream.cpp +++ b/rcss/gzip/gzstream.cpp @@ -40,8 +40,8 @@ class gzstreambuf_impl { public: gzstreambuf_impl() #ifdef HAVE_LIBZ - : M_compression_stream( NULL ), - M_decompression_stream( NULL ) + : M_compression_stream( nullptr ), + M_decompression_stream( nullptr ) #endif { } @@ -55,13 +55,13 @@ gzstreambuf::gzstreambuf( std::streambuf & strm, unsigned int bufsize ) : std::streambuf(), M_strmbuf( strm ), - M_output_stream( NULL ), - M_input_stream( NULL ), + M_output_stream( nullptr ), + M_input_stream( nullptr ), M_buffer_size( bufsize ), - M_read_buffer( NULL ), - M_input_buffer( NULL ), - M_output_buffer( NULL ), - M_write_buffer( NULL ), + M_read_buffer( nullptr ), + M_input_buffer( nullptr ), + M_output_buffer( nullptr ), + M_write_buffer( nullptr ), M_remained( 0 ), m_streams( new gzstreambuf_impl ), M_level( @@ -146,7 +146,7 @@ gzstreambuf::writeData( int sync ) } - if ( M_output_stream == NULL ) + if ( M_output_stream == nullptr ) { M_output_stream = new std::ostream( &M_strmbuf ); } @@ -160,12 +160,12 @@ gzstreambuf::writeData( int sync ) } else { - if ( m_streams->M_compression_stream == NULL ) + if ( m_streams->M_compression_stream == nullptr ) { m_streams->M_compression_stream = new z_stream; m_streams->M_compression_stream->zalloc = Z_NULL; m_streams->M_compression_stream->zfree = Z_NULL; - m_streams->M_compression_stream->opaque = NULL; + m_streams->M_compression_stream->opaque = nullptr; m_streams->M_compression_stream->avail_in = 0; m_streams->M_compression_stream->next_in = 0; m_streams->M_compression_stream->next_out = 0; @@ -175,7 +175,7 @@ gzstreambuf::writeData( int sync ) // cerr << "error in init\n"; return false; } - if( M_write_buffer == NULL ) + if( M_write_buffer == nullptr ) M_write_buffer = new char[ M_buffer_size ]; m_streams->M_compression_stream->next_out = (Bytef*)M_write_buffer; m_streams->M_compression_stream->avail_out = M_buffer_size; @@ -223,7 +223,7 @@ int gzstreambuf::readData( char * dest, int & dest_size ) { - if ( M_input_stream == NULL ) + if ( M_input_stream == nullptr ) { M_input_stream = new std::istream( &M_strmbuf ); } @@ -273,7 +273,7 @@ gzstreambuf::overflow( int_type c ) // if the buffer was not already allocated nor set by user, // do it just now - if ( pptr() == NULL ) + if ( pptr() == nullptr ) { M_output_buffer = new char_type[ M_buffer_size ]; } @@ -296,7 +296,7 @@ gzstreambuf::overflow( int_type c ) int gzstreambuf::sync() { - if ( pptr() != NULL ) + if ( pptr() != nullptr ) { // just flush the put area if ( ! writeData( @@ -319,7 +319,7 @@ gzstreambuf::underflow() // if the buffer was not already allocated nor set by user, // do it just now - if ( gptr() == NULL ) + if ( gptr() == nullptr ) { M_input_buffer = new char_type[ M_buffer_size ]; } @@ -349,7 +349,7 @@ gzstreambuf::underflow() } else { - if ( M_read_buffer == NULL ) + if ( M_read_buffer == nullptr ) { M_read_buffer = new char_type[ M_buffer_size ]; } @@ -359,12 +359,12 @@ gzstreambuf::underflow() M_input_buffer[ 0 ] = M_remaining_char; } - if ( m_streams->M_decompression_stream == NULL ) + if ( m_streams->M_decompression_stream == nullptr ) { m_streams->M_decompression_stream = new z_stream; m_streams->M_decompression_stream->zalloc = Z_NULL; m_streams->M_decompression_stream->zfree = Z_NULL; - m_streams->M_decompression_stream->opaque = NULL; + m_streams->M_decompression_stream->opaque = nullptr; m_streams->M_decompression_stream->avail_in = 0; m_streams->M_decompression_stream->next_in = 0; m_streams->M_decompression_stream->avail_out = 0; diff --git a/rcssbase/gzip/gzstream.hpp b/rcss/gzip/gzstream.hpp similarity index 98% rename from rcssbase/gzip/gzstream.hpp rename to rcss/gzip/gzstream.hpp index 6ce59488..bf8dd933 100644 --- a/rcssbase/gzip/gzstream.hpp +++ b/rcss/gzip/gzstream.hpp @@ -23,8 +23,7 @@ #define GZSTREAM_H -#include - +#include #include namespace rcss { @@ -83,7 +82,7 @@ class gzstreambuf int M_remained; // number of bytes remaining in M_output_buffer char_type M_remaining_char; - boost::shared_ptr< gzstreambuf_impl > m_streams; + std::shared_ptr< gzstreambuf_impl > m_streams; int M_level; // current level of compression/decompression // a level of -1 indicates that data is read // and written without modification. diff --git a/rcss/net/CMakeLists.txt b/rcss/net/CMakeLists.txt new file mode 100644 index 00000000..7a378b7f --- /dev/null +++ b/rcss/net/CMakeLists.txt @@ -0,0 +1,53 @@ +add_library(RCSSNet SHARED + addr.cpp + socket.cpp + socketstreambuf.cpp + tcpsocket.cpp + udpsocket.cpp + isocketstream.hpp + osocketstream.hpp + iosocketstream.hpp +) +add_library(RCSS::Net ALIAS RCSSNet) + +target_link_libraries(RCSSNet + PUBLIC + Boost::boost +) + +target_compile_definitions(RCSSNet + PUBLIC + HAVE_CONFIG_H +) + +target_include_directories(RCSSNet + PUBLIC + ${PROJECT_SOURCE_DIR} + ${PROJECT_BINARY_DIR} +) + +set_target_properties(RCSSNet + PROPERTIES + SOVERSION 1 + VERSION 1.0.1 + LIBRARY_OUTPUT_NAME "rcssnet" +) + +set_property(TARGET RCSSNet PROPERTY + PUBLIC_HEADER + addr.hpp + socket.hpp + udpsocket.hpp + tcpsocket.hpp + socketstreambuf.hpp + isocketstream.hpp + osocketstream.hpp + iosocketstream.hpp +) + +install(TARGETS RCSSNet + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Libraries + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/rcss/net +) diff --git a/rcssbase/net/Makefile.am b/rcss/net/Makefile.am similarity index 92% rename from rcssbase/net/Makefile.am rename to rcss/net/Makefile.am index 480de460..6719b205 100644 --- a/rcssbase/net/Makefile.am +++ b/rcss/net/Makefile.am @@ -32,9 +32,9 @@ librcssnet_la_LDFLAGS = -version-info 1:1:0 #librcssnet_la_LIBADD = @NET_LIBS@ -lrcsserror librcssnet_la_LIBADD = -rcssbase_netdir = $(includedir)/rcssbase/net +librcssnetincludedir = $(includedir)/rcss/net -rcssbase_net_HEADERS = \ +librcssnetinclude_HEADERS = \ addr.hpp \ socket.hpp \ udpsocket.hpp \ @@ -49,6 +49,8 @@ AM_CFLAGS = -W -Wall AM_CXXFLAGS = -W -Wall AM_LDFLAGS = +EXTRA_DIST = \ + CMakeLists.txt CLEANFILES = \ *~ \ diff --git a/rcssbase/net/addr.cpp b/rcss/net/addr.cpp similarity index 92% rename from rcssbase/net/addr.cpp rename to rcss/net/addr.cpp index b7d07aa2..dd1e0c95 100644 --- a/rcssbase/net/addr.cpp +++ b/rcss/net/addr.cpp @@ -59,7 +59,7 @@ namespace net { const Addr::HostType Addr::BROADCAST = INADDR_BROADCAST; const Addr::HostType Addr::ANY = INADDR_ANY; -class AddrImpl { +class Addr::Impl { private: void setAddr( Addr::PortType port, Addr::HostType host ) @@ -83,12 +83,12 @@ class AddrImpl { return true; } public: - AddrImpl( const Addr::AddrType & addr ) + Impl( const Addr::AddrType & addr ) : m_addr( addr ) { } - AddrImpl( Addr::PortType port, - Addr::HostType host ) + Impl( Addr::PortType port, + Addr::HostType host ) { setAddr( htons( port ), htonl( host ) ); } @@ -115,9 +115,9 @@ class AddrImpl { struct servent * serv_ent = (struct servent*)getservbyname( port.c_str(), ( proto.empty() - ? NULL + ? nullptr : proto.c_str() ) ); - if ( serv_ent == NULL ) + if ( ! serv_ent ) { return false; } @@ -142,9 +142,10 @@ class AddrImpl { #endif return false; } - struct hostent * host_ent - = (struct hostent*)gethostbyname( host.c_str() ); - if ( host_ent == NULL ) + + struct hostent * host_ent = (struct hostent*)gethostbyname( host.c_str() ); + + if ( ! host_ent ) { #ifdef RCSS_WIN return false; @@ -188,9 +189,9 @@ class AddrImpl { { struct servent * serv_ent = getservbyport( m_addr.sin_port, ( proto.empty() - ? NULL + ? nullptr : proto.c_str() ) ); - if( serv_ent == NULL ) + if( ! serv_ent ) { return m_port_name; } @@ -207,15 +208,21 @@ class AddrImpl { int m_errno; }; + Addr::Addr( PortType port, HostType host ) - : M_impl( new AddrImpl( port, host ) ) + : M_impl( new Impl( port, host ) ) { } Addr::Addr( const AddrType & addr ) - : M_impl( new AddrImpl( addr ) ) + : M_impl( new Impl( addr ) ) +{ + +} + +Addr::~Addr() { } diff --git a/rcssbase/net/addr.hpp b/rcss/net/addr.hpp similarity index 91% rename from rcssbase/net/addr.hpp rename to rcss/net/addr.hpp index a3182780..8035f98c 100644 --- a/rcssbase/net/addr.hpp +++ b/rcss/net/addr.hpp @@ -21,9 +21,8 @@ #ifndef RCSS_NET_ADDR_HPP #define RCSS_NET_ADDR_HPP -#include -#include - +#include +#include #include struct sockaddr_in; @@ -31,12 +30,14 @@ struct sockaddr_in; namespace rcss { namespace net { -class AddrImpl; - class Addr { +private: + class Impl; + + std::shared_ptr< Impl > M_impl; public: - typedef boost::uint16_t PortType; - typedef boost::uint32_t HostType; + typedef std::uint16_t PortType; + typedef std::uint32_t HostType; typedef struct sockaddr_in AddrType; enum Error { S_ADDR_OK, S_SERV_NOT_FOUND, S_HOST_NOT_FOUND }; @@ -50,6 +51,8 @@ class Addr { Addr( const AddrType & addr ); + ~Addr(); + bool setPort( PortType port = 0 ); bool setPort( const std::string & port, @@ -70,8 +73,6 @@ class Addr { std::string getPortStr( const std::string & proto = "" ) const; -private: - boost::shared_ptr< AddrImpl > M_impl; }; diff --git a/rcssbase/net/handler.cpp b/rcss/net/handler.cpp similarity index 100% rename from rcssbase/net/handler.cpp rename to rcss/net/handler.cpp diff --git a/rcssbase/net/handler.hpp b/rcss/net/handler.hpp similarity index 100% rename from rcssbase/net/handler.hpp rename to rcss/net/handler.hpp diff --git a/rcssbase/net/iosocketstream.hpp b/rcss/net/iosocketstream.hpp similarity index 94% rename from rcssbase/net/iosocketstream.hpp rename to rcss/net/iosocketstream.hpp index d41472d8..070e28e2 100644 --- a/rcssbase/net/iosocketstream.hpp +++ b/rcss/net/iosocketstream.hpp @@ -21,9 +21,9 @@ #ifndef RCSS_NET_IOSOCKETSTREAM_HPP #define RCSS_NET_IOSOCKETSTREAM_HPP -#include -#include -#include +#include +#include +#include namespace rcss { namespace net { diff --git a/rcssbase/net/isocketstream.hpp b/rcss/net/isocketstream.hpp similarity index 97% rename from rcssbase/net/isocketstream.hpp rename to rcss/net/isocketstream.hpp index 1f3c0b22..c3142322 100644 --- a/rcssbase/net/isocketstream.hpp +++ b/rcss/net/isocketstream.hpp @@ -21,7 +21,7 @@ #ifndef RCSS_NET_ISOCKETSTREAM_HPP #define RCSS_NET_ISOCKETSTREAM_HPP -#include +#include namespace rcss { namespace net { diff --git a/rcssbase/net/osocketstream.hpp b/rcss/net/osocketstream.hpp similarity index 97% rename from rcssbase/net/osocketstream.hpp rename to rcss/net/osocketstream.hpp index e3434ef4..0443f406 100644 --- a/rcssbase/net/osocketstream.hpp +++ b/rcss/net/osocketstream.hpp @@ -21,7 +21,7 @@ #ifndef RCSS_NET_OSOCKETSTREAM_HPP #define RCSS_NET_OSOCKETSTREAM_HPP -#include +#include namespace rcss { namespace net { diff --git a/rcssbase/net/socket.cpp b/rcss/net/socket.cpp similarity index 97% rename from rcssbase/net/socket.cpp rename to rcss/net/socket.cpp index ce5f8c5a..4884a785 100644 --- a/rcssbase/net/socket.cpp +++ b/rcss/net/socket.cpp @@ -85,8 +85,8 @@ Socket::Socket() Socket::Socket( SocketDesc s ) { - M_handle = boost::shared_ptr< SocketDesc >( new SocketDesc( s ), - Socket::closeFD ); + M_handle = std::shared_ptr< SocketDesc >( new SocketDesc( s ), + Socket::closeFD ); } @@ -104,8 +104,8 @@ Socket::open() return false; } - M_handle = boost::shared_ptr< SocketDesc >( new SocketDesc( s ), - Socket::closeFD ); + M_handle = std::shared_ptr< SocketDesc >( new SocketDesc( s ), + Socket::closeFD ); #ifndef RCSS_WIN int err = setCloseOnExec(); if ( err < 0 ) @@ -344,7 +344,7 @@ Socket::getFD() const bool Socket::isOpen() const { - return M_handle.get() != NULL; + return M_handle.get() != nullptr; } bool diff --git a/rcssbase/net/socket.hpp b/rcss/net/socket.hpp similarity index 96% rename from rcssbase/net/socket.hpp rename to rcss/net/socket.hpp index 1ca567f2..d7b9782a 100644 --- a/rcssbase/net/socket.hpp +++ b/rcss/net/socket.hpp @@ -21,9 +21,9 @@ #ifndef RCSS_NET_SOCKET_HPP #define RCSS_NET_SOCKET_HPP -#include +#include -#include +#include namespace rcss { namespace net { @@ -124,7 +124,7 @@ class Socket { bool doOpen( SocketDesc& fd ) = 0; private: - boost::shared_ptr< SocketDesc > M_handle; + std::shared_ptr< SocketDesc > M_handle; }; } diff --git a/rcssbase/net/socketstreambuf.cpp b/rcss/net/socketstreambuf.cpp similarity index 97% rename from rcssbase/net/socketstreambuf.cpp rename to rcss/net/socketstreambuf.cpp index fd580956..8a09ab28 100644 --- a/rcssbase/net/socketstreambuf.cpp +++ b/rcss/net/socketstreambuf.cpp @@ -36,8 +36,8 @@ SocketStreamBuf::SocketStreamBuf( Socket & socket, : M_socket( socket ), M_end_point( dest ), M_bufsize( bufsize ), - M_inbuf( NULL ), - M_outbuf( NULL ), + M_inbuf( nullptr ), + M_outbuf( nullptr ), M_remained( 0 ), M_connect( conn ) { @@ -52,8 +52,8 @@ SocketStreamBuf::SocketStreamBuf( Socket & socket, std::streamsize bufsize ) : M_socket( socket ), M_bufsize( bufsize ), - M_inbuf( NULL ), - M_outbuf( NULL ), + M_inbuf( nullptr ), + M_outbuf( nullptr ), M_remained( 0 ), M_connect( conn ) { @@ -144,7 +144,7 @@ SocketStreamBuf::underflow() // if the buffer was not already allocated nor set by user, // do it just now - if ( gptr() == NULL ) + if ( gptr() == nullptr ) { M_inbuf = new char_type[M_bufsize]; } diff --git a/rcssbase/net/socketstreambuf.hpp b/rcss/net/socketstreambuf.hpp similarity index 98% rename from rcssbase/net/socketstreambuf.hpp rename to rcss/net/socketstreambuf.hpp index 6ae649a0..dcb3888d 100644 --- a/rcssbase/net/socketstreambuf.hpp +++ b/rcss/net/socketstreambuf.hpp @@ -22,7 +22,7 @@ #ifndef RCSS_NET_SOCKETSTREAMBUF_HPP #define RCSS_NET_SOCKETSTREAMBUF_HPP -#include +#include //g++ 2.95.6 doesn't have the streambuf header, so iostream is used instead //#include diff --git a/rcssbase/net/tcpsocket.cpp b/rcss/net/tcpsocket.cpp similarity index 97% rename from rcssbase/net/tcpsocket.cpp rename to rcss/net/tcpsocket.cpp index 2e4e3432..ca400842 100644 --- a/rcssbase/net/tcpsocket.cpp +++ b/rcss/net/tcpsocket.cpp @@ -70,7 +70,7 @@ TCPSocket::TCPSocket( const Addr & addr, bool TCPSocket::accept( TCPSocket & sock ) { - SocketDesc fd = ::accept( getFD(), NULL, 0 ); + SocketDesc fd = ::accept( getFD(), nullptr, 0 ); if ( fd == INVALIDSOCKET ) { return false; diff --git a/rcssbase/net/tcpsocket.hpp b/rcss/net/tcpsocket.hpp similarity index 97% rename from rcssbase/net/tcpsocket.hpp rename to rcss/net/tcpsocket.hpp index 137f32f5..14457712 100644 --- a/rcssbase/net/tcpsocket.hpp +++ b/rcss/net/tcpsocket.hpp @@ -23,7 +23,7 @@ #define RCSS_NET_TCPSOCKET_HPP -#include +#include namespace rcss { namespace net { diff --git a/rcssbase/net/udpsocket.cpp b/rcss/net/udpsocket.cpp similarity index 100% rename from rcssbase/net/udpsocket.cpp rename to rcss/net/udpsocket.cpp diff --git a/rcssbase/net/udpsocket.hpp b/rcss/net/udpsocket.hpp similarity index 97% rename from rcssbase/net/udpsocket.hpp rename to rcss/net/udpsocket.hpp index af902a6a..16e99ff3 100644 --- a/rcssbase/net/udpsocket.hpp +++ b/rcss/net/udpsocket.hpp @@ -22,7 +22,7 @@ #ifndef RCSS_NET_UDPSOCKET_HPP #define RCSS_NET_UDPSOCKET_HPP -#include +#include namespace rcss { namespace net { diff --git a/rcssbase/parser.h b/rcss/parser.h similarity index 82% rename from rcssbase/parser.h rename to rcss/parser.h index fc0bdd0c..e180d33e 100644 --- a/rcssbase/parser.h +++ b/rcss/parser.h @@ -29,29 +29,6 @@ #include #include -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION > 2 - -#define BOOST_FS_ABSOLUTE absolute -#define BOOST_FS_FILE_STRING string -#define BOOST_FS_DIRECTORY_STRING string -#define BOOST_FS_PARENT_PATH parent_path - -#else - -#define BOOST_FS_ABSOLUTE complete - -# ifdef BOOST_FILESYSTEM_NO_DEPRECATED -# define BOOST_FS_FILE_STRING file_string -# define BOOST_FS_DIRECTORY_STRING directory_string -# define BOOST_FS_PARENT_PATH parent_path -# else -# define BOOST_FS_FILE_STRING native_file_string -# define BOOST_FS_DIRECTORY_STRING native_directory_string -# define BOOST_FS_PARENT_PATH branch_path -# endif - -#endif - namespace rcss { class Parser { @@ -108,7 +85,7 @@ class Parser { return false; } - bool rval = parse( strm, file.BOOST_FS_FILE_STRING(), errstrm ); + bool rval = parse( strm, file.string(), errstrm ); strm.close(); diff --git a/src/vector.h b/rcss/vector.h similarity index 94% rename from src/vector.h rename to rcss/vector.h index bf9725fd..35d32a7c 100644 --- a/src/vector.h +++ b/rcss/vector.h @@ -20,14 +20,12 @@ -#ifndef VECTOR_H -#define VECTOR_H - -#include "utility.h" +#ifndef RCSS_CLANG_VECTOR_H +#define RCSS_CLANG_VECTOR_H #include #include - +#include namespace rcss { namespace geom { @@ -168,9 +166,9 @@ class Vector2D { value sum = 0.0; for ( size_type i = X; i < DIM; ++i ) { - sum += pow ( M_data[ i ], 2 ); + sum += std::pow( M_data[ i ], 2 ); } - return sqrt ( sum ); + return std::sqrt( sum ); } void setMag( const_reference mag ); @@ -327,7 +325,17 @@ Vector2D::value angle( const Vector2D & a, const Vector2D & b ) { - return normalize_angle( b.getHead() - a.getHead() ); + //return normalize_angle( b.getHead() - a.getHead() ); + double ang = b.getHead() - a.getHead(); + if ( std::fabs( ang ) > 2*M_PI ) + { + ang = std::fmod( ang, 2*M_PI ); + } + + if ( ang < -M_PI ) ang += 2*M_PI; + if ( ang > M_PI ) ang -= 2*M_PI; + + return ang; } inline diff --git a/rcssbase/Makefile.am b/rcssbase/Makefile.am deleted file mode 100644 index 04a1fc20..00000000 --- a/rcssbase/Makefile.am +++ /dev/null @@ -1,16 +0,0 @@ -SUBDIRS = net conf gzip - -rcssbasedir = $(includedir)/rcssbase - -rcssbase_HEADERS = \ - factory.hpp \ - parser.h - -AM_CPPFLAGS = -I$(top_srcdir) -AM_CFLAGS = -W -Wall -AM_CXXFLAGS = -W -Wall -AM_LDFLAGS = - -CLEANFILES = \ - *~ \ - core diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 00000000..d1d2a820 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,144 @@ + +bison_target(player_command_parser + player_command_parser.ypp + ${CMAKE_CURRENT_BINARY_DIR}/player_command_parser.cpp + DEFINES_FILE ${CMAKE_CURRENT_BINARY_DIR}/player_command_parser.hpp +) +flex_target(player_command_tokenizer + player_command_tok.lpp + ${CMAKE_CURRENT_BINARY_DIR}/raw_player_command_tok.cpp +) +add_flex_bison_dependency(player_command_tokenizer player_command_parser) + +add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/player_command_tok.cpp" + COMMAND ${CMAKE_COMMAND} + ARGS + "-DGENERATED_FILE_PATH=\"${CMAKE_CURRENT_BINARY_DIR}/raw_player_command_tok.cpp\"" + "-DCORRECT_HEADER_NAME=player_command_tok.h" + "-DOUTPUT_FILE_PATH=\"${CMAKE_CURRENT_BINARY_DIR}/player_command_tok.cpp\"" + "-P" "${CMAKE_CURRENT_SOURCE_DIR}/fix_lexer_file.cmake" + MAIN_DEPENDENCY "${CMAKE_CURRENT_BINARY_DIR}/raw_player_command_tok.cpp" +) + +add_executable(RCSSServer + audio.cpp + bodysender.cpp + coach.cpp + csvsaver.cpp + dispsender.cpp + field.cpp + fullstatesender.cpp + heteroplayer.cpp + initsender.cpp + initsendercoach.cpp + initsenderlogger.cpp + initsendermonitor.cpp + initsenderonlinecoach.cpp + initsenderplayer.cpp + landmarkreader.cpp + logger.cpp + main.cpp + monitor.cpp + pcombuilder.cpp + pcomparser.cpp + player.cpp + playerparam.cpp + object.cpp + referee.cpp + remoteclient.cpp + resultsaver.cpp + serializer.cpp + serializercoachstdv1.cpp + serializercoachstdv7.cpp + serializercoachstdv8.cpp + serializercoachstdv13.cpp + serializercoachstdv14.cpp + serializercommonstdv1.cpp + serializercommonstdv7.cpp + serializercommonstdv8.cpp + serializercommonjson.cpp + serializermonitor.cpp + serializeronlinecoachstdv1.cpp + serializeronlinecoachstdv6.cpp + serializeronlinecoachstdv7.cpp + serializeronlinecoachstdv8.cpp + serializeronlinecoachstdv13.cpp + serializeronlinecoachstdv14.cpp + serializerplayerstdv1.cpp + serializerplayerstdv7.cpp + serializerplayerstdv8.cpp + serializerplayerstdv13.cpp + serializerplayerstdv14.cpp + serverparam.cpp + stadium.cpp + stdoutsaver.cpp + stdtimer.cpp + synctimer.cpp + team.cpp + utility.cpp + visualsendercoach.cpp + visualsenderplayer.cpp + weather.cpp + xmlreader.cpp + xpmholder.cpp + ${CMAKE_CURRENT_BINARY_DIR}/player_command_parser.cpp + ${CMAKE_CURRENT_BINARY_DIR}/player_command_tok.cpp +) + +target_link_libraries(RCSSServer + PRIVATE + RCSS::CLangParser + RCSS::ConfParser + RCSS::Net + RCSS::GZ + Boost::boost + Boost::filesystem + Boost::system + ZLIB::ZLIB + ) + +target_compile_definitions(RCSSServer + PUBLIC + HAVE_CONFIG_H +) + + +set_target_properties(RCSSServer + PROPERTIES + RUNTIME_OUTPUT_NAME "rcssserver" +) + + +add_executable(RCSSClient + client.cpp +) + +target_link_libraries(RCSSClient + PRIVATE + RCSS::Net + RCSS::GZ + Boost::boost + Boost::filesystem + Boost::system + ZLIB::ZLIB +) + +set_target_properties(RCSSClient + PROPERTIES + RUNTIME_OUTPUT_NAME "rcssclient" +) + +set(prefix ${CMAKE_INSTALL_PREFIX}) +set(exec_prefix ${CMAKE_INSTALL_PREFIX}) +set(libdir ${CMAKE_INSTALL_FULL_LIBDIR}) +configure_file(rcsoccersim.in rcsoccersim @ONLY) + +install(TARGETS RCSSServer + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Libraries + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE + ) + +install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/rcsoccersim DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/src/Makefile.am b/src/Makefile.am index 02c77395..8d8662fd 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,85 +1,4 @@ -lib_LTLIBRARIES = \ - librcssclangparser.la - -librcssclangparser_la_SOURCES = \ - clangbuilder.cpp \ - clangmsgbuilder.cpp \ - clangparser.cpp \ - clangmsg.cpp \ - clangmetamsg.cpp \ - clangfreeformmsg.cpp \ - clangunsuppmsg.cpp \ - clangrulemsg.cpp \ - clangdelmsg.cpp \ - clanginfomsg.cpp \ - clangadvicemsg.cpp \ - clangdefmsg.cpp \ - clangaction.cpp \ - clangutil.cpp \ - coach_lang_comp.cpp \ - arithop.cpp \ - cond.cpp \ - compop.cpp \ - region.cpp \ - rule.cpp \ - rcssexceptions.cpp - -librcssclangparser_la_LDFLAGS = -version-info 3:0:1 -# Changed from 2.0.0 to 3.0.1 at 9.3.5 for addition of buildCondList -# -# 1. Start with version information of `0:0:0' for each libtool library. -# -# 2. Update the version information only immediately before a public -# release of your software. More frequent updates are unnecessary, -# and only guarantee that the current interface number gets larger -# faster. -# -# 3. If the library source code has changed at all since the last -# update, then increment REVISION (`C:R:A' becomes `C:r+1:A'). -# -# 4. If any interfaces have been added, removed, or changed since the -# last update, increment CURRENT, and set REVISION to 0. -# -# 5. If any interfaces have been added since the last public release, -# then increment AGE. -# -# 6. If any interfaces have been removed since the last public release, -# then set AGE to 0. - -pkginclude_HEADERS = \ - clangparser.h \ - coach_lang_tok.h \ - clangbuilder.h \ - clangmsgbuilder.h \ - clangmsg.h \ - clangmetamsg.h \ - clangfreeformmsg.h \ - clangunsuppmsg.h \ - clangrulemsg.h \ - clangdelmsg.h \ - clanginfomsg.h \ - clangadvicemsg.h \ - clangdefmsg.h \ - clangaction.h \ - clangutil.h \ - coach_lang_comp.h \ - coach_lang_parser.hpp \ - player_command_parser.hpp \ - arithop.h \ - compop.h \ - cond.h \ - region.h \ - rule.h \ - vector.h \ - rcssexceptions.h - -nodist_librcssclangparser_la_SOURCES = \ - coach_lang_parser.ypp \ - coach_lang_tok.cpp - - - bin_PROGRAMS = \ rcssserver @RCSSCLIENT@ @@ -121,6 +40,7 @@ rcssserver_SOURCES = \ serializercommonstdv1.cpp \ serializercommonstdv7.cpp \ serializercommonstdv8.cpp \ + serializercommonjson.cpp \ serializermonitor.cpp \ serializeronlinecoachstdv1.cpp \ serializeronlinecoachstdv6.cpp \ @@ -192,6 +112,7 @@ noinst_HEADERS = \ serializercommonstdv1.h \ serializercommonstdv7.h \ serializercommonstdv8.h \ + serializercommonjson.h \ serializeronlinecoachstdv1.h \ serializeronlinecoachstdv6.h \ serializeronlinecoachstdv7.h \ @@ -223,21 +144,20 @@ noinst_HEADERS = \ xpmholder.h rcssserver_LDFLAGS = \ - -L$(top_builddir)/rcssbase/conf \ - -L$(top_builddir)/rcssbase/net \ - -L$(top_builddir)/rcssbase/gzip + -L$(top_builddir)/rcss/clang \ + -L$(top_builddir)/rcss/conf \ + -L$(top_builddir)/rcss/net \ + -L$(top_builddir)/rcss/gzip rcssserver_LDADD = \ - librcssclangparser.la \ + -lrcssclangparser \ -lrcssconfparser \ -lrcssnet \ -lrcssgz \ - $(BOOST_FILESYSTEM_LIB) $(BOOST_SYSTEM_LIB) @GZ_LIBS@ + $(BOOST_FILESYSTEM_LIB) $(BOOST_SYSTEM_LIB) BUILT_SOURCES = \ - coach_lang_parser.hpp \ - coach_lang_tok.cpp \ player_command_parser.hpp \ player_command_tok.cpp @@ -270,13 +190,13 @@ rcssclient_SOURCES = \ client.cpp rcssclient_LDFLAGS = \ - -L$(top_builddir)/rcssbase/net \ - -L$(top_builddir)/rcssbase/gzip + -L$(top_builddir)/rcss/net \ + -L$(top_builddir)/rcss/gzip rcssclient_LDADD = @RCSSCLIENT_LIBS@ \ -lrcssnet \ -lrcssgz \ - $(BOOST_FILESYSTEM_LIB) $(BOOST_SYSTEM_LIB) @GZ_LIBS@ + $(BOOST_FILESYSTEM_LIB) $(BOOST_SYSTEM_LIB) AM_CPPFLAGS = -I$(top_srcdir) @@ -286,16 +206,13 @@ AM_CXXFLAGS = -W -Wall EXTRA_DIST = \ - coach_lang_parser.ypp \ - coach_lang_tok.lpp \ + CMakeLists.txt \ + fix_lexer_file.cmake \ player_command_parser.ypp \ player_command_tok.lpp \ rcsoccersim.in CLEANFILES = \ - coach_lang_parser.cpp \ - coach_lang_parser.hpp \ - coach_lang_tok.cpp \ player_command_parser.cpp \ player_command_parser.hpp \ player_command_tok.cpp \ diff --git a/src/arm.h b/src/arm.h index 87942d89..ee13c42e 100644 --- a/src/arm.h +++ b/src/arm.h @@ -22,7 +22,8 @@ #ifndef ARM_H #define ARM_H -#include "vector.h" +#include + #include "utility.h" class Arm { diff --git a/src/audio.cpp b/src/audio.cpp index 1e759d29..29f9cb85 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -27,15 +27,16 @@ #include "object.h" #include "serializer.h" -#include "clangmsg.h" -#include "clangunsuppmsg.h" #include "coach.h" #include "stadium.h" #include "player.h" #include "random.h" #include "utility.h" -#include +#include +#include + +#include namespace rcss { @@ -384,7 +385,7 @@ AudioSenderPlayerv8::~AudioSenderPlayerv8() ++i ) { free( i->second ); - i->second = NULL; + i->second = nullptr; } M_player_msgs.clear(); @@ -393,7 +394,7 @@ AudioSenderPlayerv8::~AudioSenderPlayerv8() ++i ) { free( *i ); - *i = NULL; + *i = nullptr; } M_self_msgs.clear(); @@ -402,7 +403,7 @@ AudioSenderPlayerv8::~AudioSenderPlayerv8() ++i ) { free( i->second ); - i->second = NULL; + i->second = nullptr; } M_coach_msgs.clear(); } @@ -437,7 +438,7 @@ AudioSenderPlayerv8::sendCoachAudio( const Coach & coach, const char * msg ) { char * msg_copy = strdup( msg ); - if ( msg_copy == NULL ) + if ( ! msg_copy ) { std::cerr << "Error: could not alocate memory to cache coach audio message\n"; } @@ -453,7 +454,7 @@ void AudioSenderPlayerv8::sendSelfAudio( const char * msg ) { char * msg_copy = strdup( msg ); - if ( msg_copy == NULL ) + if ( ! msg_copy ) { std::cerr << "Error: could not alocate memory to cache player's own audio message\n"; } @@ -490,7 +491,7 @@ AudioSenderPlayerv8::sendNonSelfPlayerAudio( const Player & player, } char * msg_copy = strdup( msg ); - if ( msg_copy == NULL ) + if ( ! msg_copy ) { std::cerr << "Error: could not alocate memory to cache player audio message\n"; } @@ -658,8 +659,10 @@ AudioSenderPlayerv8::Focused::getMsg( msg_cont_t & msgs ) } } #else - if ( M_key == NULL ) + if ( ! M_key ) + { return Unfocused::getMsg( msgs ); + } std::pair< msg_cont_t::iterator, msg_cont_t::iterator > iters = msgs.equal_range( M_key ); @@ -980,6 +983,7 @@ RegHolder vp13 = AudioSenderPlayer::factory().autoReg( &create< AudioSenderPlaye RegHolder vp14 = AudioSenderPlayer::factory().autoReg( &create< AudioSenderPlayerv8 >, 14 ); RegHolder vp15 = AudioSenderPlayer::factory().autoReg( &create< AudioSenderPlayerv8 >, 15 ); RegHolder vp16 = AudioSenderPlayer::factory().autoReg( &create< AudioSenderPlayerv8 >, 16 ); +RegHolder vp17 = AudioSenderPlayer::factory().autoReg( &create< AudioSenderPlayerv8 >, 17 ); template< typename Sender > AudioSender::Ptr @@ -1004,6 +1008,7 @@ RegHolder vc13 = AudioSenderCoach::factory().autoReg( &create< AudioSenderCoachv RegHolder vc14 = AudioSenderCoach::factory().autoReg( &create< AudioSenderCoachv7 >, 14 ); RegHolder vc15 = AudioSenderCoach::factory().autoReg( &create< AudioSenderCoachv7 >, 15 ); RegHolder vc16 = AudioSenderCoach::factory().autoReg( &create< AudioSenderCoachv7 >, 16 ); +RegHolder vc17 = AudioSenderCoach::factory().autoReg( &create< AudioSenderCoachv7 >, 17 ); template< typename Sender > AudioSender::Ptr @@ -1028,5 +1033,6 @@ RegHolder voc13 = AudioSenderOnlineCoach::factory().autoReg( &create< AudioSende RegHolder voc14 = AudioSenderOnlineCoach::factory().autoReg( &create< AudioSenderOnlineCoachv7 >, 14 ); RegHolder voc15 = AudioSenderOnlineCoach::factory().autoReg( &create< AudioSenderOnlineCoachv7 >, 15 ); RegHolder voc16 = AudioSenderOnlineCoach::factory().autoReg( &create< AudioSenderOnlineCoachv7 >, 16 ); +RegHolder voc17 = AudioSenderOnlineCoach::factory().autoReg( &create< AudioSenderOnlineCoachv7 >, 17 ); } } diff --git a/src/audio.h b/src/audio.h index bca7878e..4ce78bb2 100644 --- a/src/audio.h +++ b/src/audio.h @@ -28,7 +28,7 @@ #include "param.h" #include "types.h" -#include +#include #include #include @@ -71,13 +71,13 @@ class AudioSender protected: const Stadium& M_stadium; -public: AudioSender( const Stadium & stadium, std::ostream & transport ) : Sender( transport ) , M_stadium( stadium ) { } +public: virtual ~AudioSender() { } @@ -113,10 +113,9 @@ class AudioSender { } virtual - const - Player * getFocusTarget() const + const Player * getFocusTarget() const { - return NULL; + return nullptr; } virtual @@ -151,6 +150,7 @@ class Listener : BaseObserver< AudioSender >( sender ) { } + virtual ~Listener() { } @@ -195,13 +195,13 @@ class Listener void sendErrorNoTeamName( const std::string & team_name ); - class NewCycle { - public: - void operator()( Listener * listener ) - { - listener->newCycle(); - } - }; + // class NewCycle { + // public: + // void operator()( Listener * listener ) + // { + // listener->newCycle(); + // } + // }; }; @@ -308,31 +308,31 @@ class AudioSenderPlayerv1 { } virtual - ~AudioSenderPlayerv1() + ~AudioSenderPlayerv1() override { } virtual - void sendRefereeAudio( const char * msg ); + void sendRefereeAudio( const char * msg ) override; virtual void sendCoachAudio( const Coach & coach, - const char * msg ); + const char * msg ) override; virtual - void sendCoachStdAudio( const clang::Msg & msg ); + void sendCoachStdAudio( const clang::Msg & msg ) override; virtual - void sendSelfAudio( const char * msg ); + void sendSelfAudio( const char * msg ) override; virtual void sendNonSelfPlayerAudio( const Player & player, - const char * msg ); + const char * msg ) override; virtual - void sendOKClang(); + void sendOKClang() override; virtual - void sendErrorNoTeamName( const std::string & team_name ); + void sendErrorNoTeamName( const std::string & team_name ) override; }; @@ -347,16 +347,16 @@ class AudioSenderPlayerv7 { } virtual - ~AudioSenderPlayerv7() + ~AudioSenderPlayerv7() override { } virtual void sendCoachAudio( const Coach & coach, - const char * msg ); + const char * msg ) override; virtual void sendNonSelfPlayerAudio( const Player & player, - const char * msg ); + const char * msg ) override; }; @@ -399,10 +399,9 @@ class AudioSenderPlayerv8 key_value_t getMsg( msg_cont_t& msgs ) = 0; virtual - const - Player * getFocusTarget() const + const Player * getFocusTarget() const { - return NULL; + return nullptr; } }; @@ -426,7 +425,7 @@ class AudioSenderPlayerv8 player_key_t M_key; public: Focused() - : M_key( NULL ) + : M_key( nullptr ) { } virtual @@ -480,37 +479,36 @@ class AudioSenderPlayerv8 {} virtual - ~AudioSenderPlayerv8(); + ~AudioSenderPlayerv8() override; virtual void sendCoachAudio( const Coach & coach, - const char * msg ); + const char * msg ) override; virtual - void sendSelfAudio( const char * msg ); + void sendSelfAudio( const char * msg ) override; virtual void sendNonSelfPlayerAudio( const Player & player, - const char * msg ); + const char * msg ) override; virtual - void newCycle(); + void newCycle() override; virtual - void focusOn( const Player & player ); + void focusOn( const Player & player ) override; virtual - void focusOff(); + void focusOff() override; virtual - const - Player * getFocusTarget() const + const Player * getFocusTarget() const override { return M_state_p->getFocusTarget(); } virtual - unsigned int getFocusCount() const + unsigned int getFocusCount() const override { return M_focus_count; } @@ -519,7 +517,7 @@ class AudioSenderPlayerv8 void setEar( bool on, Side side, bool complete, - bool partial ); + bool partial ) override; protected: virtual @@ -577,9 +575,12 @@ class AudioSenderCoach FactoryHolder & factory(); +protected: AudioSenderCoach( const Params & params ); - ~AudioSenderCoach(); +public: + virtual + ~AudioSenderCoach() override; protected: @@ -609,22 +610,22 @@ class AudioSenderCoachv1 { } virtual - ~AudioSenderCoachv1() + ~AudioSenderCoachv1() override { } virtual - void sendRefereeAudio( const char * msg ); + void sendRefereeAudio( const char * msg ) override; virtual void sendCoachAudio( const Coach & coach, - const char * msg ); + const char * msg ) override; virtual - void sendCoachStdAudio( const clang::Msg & msg ); + void sendCoachStdAudio( const clang::Msg & msg ) override; virtual void sendPlayerAudio( const Player & player, - const char * msg ); + const char * msg ) override; }; @@ -638,12 +639,12 @@ class AudioSenderCoachv7 { } virtual - ~AudioSenderCoachv7() + ~AudioSenderCoachv7() override { } virtual void sendPlayerAudio( const Player & player, - const char * msg ); + const char * msg ) override; }; @@ -681,9 +682,12 @@ class AudioSenderOnlineCoach static FactoryHolder & factory(); +protected: AudioSenderOnlineCoach( const Params & params ); - ~AudioSenderOnlineCoach(); +public: + virtual + ~AudioSenderOnlineCoach() override; protected: diff --git a/src/bodysender.cpp b/src/bodysender.cpp index d8aaa69e..68d9a944 100644 --- a/src/bodysender.cpp +++ b/src/bodysender.cpp @@ -294,7 +294,7 @@ BodySenderPlayerV8::sendBodyData() state.dist(), (int)state.head(), state.count() ); - if ( self().getFocusTarget() == NULL ) + if ( ! self().getFocusTarget() ) { serializer().serializeFocus( transport(), "none", @@ -427,6 +427,7 @@ RegHolder vp13 = BodySenderPlayer::factory().autoReg( &create< BodySenderPlayerV RegHolder vp14 = BodySenderPlayer::factory().autoReg( &create< BodySenderPlayerV14 >, 14 ); RegHolder vp15 = BodySenderPlayer::factory().autoReg( &create< BodySenderPlayerV14 >, 15 ); RegHolder vp16 = BodySenderPlayer::factory().autoReg( &create< BodySenderPlayerV14 >, 16 ); +RegHolder vp17 = BodySenderPlayer::factory().autoReg( &create< BodySenderPlayerV14 >, 17 ); } } diff --git a/src/bodysender.h b/src/bodysender.h index 6efa0bec..953d7182 100644 --- a/src/bodysender.h +++ b/src/bodysender.h @@ -27,7 +27,7 @@ #include "observer.h" -#include +#include #include @@ -93,10 +93,12 @@ class BodySenderPlayer static FactoryHolder & factory(); +protected: BodySenderPlayer( const Params & params ); +public: virtual - ~BodySenderPlayer(); + ~BodySenderPlayer() override; protected: const @@ -177,10 +179,10 @@ class BodySenderPlayerV1 BodySenderPlayerV1( const Params & params ); virtual - ~BodySenderPlayerV1(); + ~BodySenderPlayerV1() override; virtual - void sendBody(); + void sendBody() override; protected: virtual @@ -217,14 +219,14 @@ class BodySenderPlayerV5 BodySenderPlayerV5( const Params & params ); virtual - ~BodySenderPlayerV5(); + ~BodySenderPlayerV5() override; protected: virtual - void sendNeck(); + void sendNeck() override; virtual - void sendCounts(); + void sendCounts() override; }; /*! @@ -245,11 +247,11 @@ class BodySenderPlayerV6 BodySenderPlayerV6( const Params & params ); virtual - ~BodySenderPlayerV6(); + ~BodySenderPlayerV6() override; protected: virtual - void sendVelocity(); + void sendVelocity() override; }; /*! @@ -269,11 +271,11 @@ class BodySenderPlayerV7 BodySenderPlayerV7( const Params & params ); virtual - ~BodySenderPlayerV7(); + ~BodySenderPlayerV7() override; protected: virtual - void sendCounts(); + void sendCounts() override; }; @@ -295,11 +297,11 @@ class BodySenderPlayerV8 BodySenderPlayerV8( const Params & params ); virtual - ~BodySenderPlayerV8(); + ~BodySenderPlayerV8() override; protected: virtual - void sendBodyData(); + void sendBodyData() override; }; @@ -320,11 +322,11 @@ class BodySenderPlayerV12 BodySenderPlayerV12( const Params & params ); virtual - ~BodySenderPlayerV12(); + ~BodySenderPlayerV12() override; protected: virtual - void sendBodyData(); + void sendBodyData() override; }; @@ -347,7 +349,7 @@ class BodySenderPlayerV13 BodySenderPlayerV13( const Params & params ); virtual - ~BodySenderPlayerV13(); + ~BodySenderPlayerV13() override; }; @@ -369,11 +371,11 @@ class BodySenderPlayerV14 BodySenderPlayerV14( const Params & params ); virtual - ~BodySenderPlayerV14(); + ~BodySenderPlayerV14() override; protected: virtual - void sendBodyData(); + void sendBodyData() override; }; diff --git a/src/client.cpp b/src/client.cpp index 700ddb0a..6eb8ee1f 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -25,15 +25,11 @@ #include "compress.h" -#include -#include -#include +#include +#include +#include -#ifdef HAVE_SSTREAM #include -#else -#include -#endif #include #include #include @@ -84,9 +80,9 @@ class Client { const int port ) : M_dest( port ), M_socket(), - M_socket_buf( NULL ), - M_gz_buf( NULL ), - M_transport( NULL ), + M_socket_buf( nullptr ), + M_gz_buf( nullptr ), + M_transport( nullptr ), M_comp_level( -1 ), M_clean_cycle( true ) { @@ -156,19 +152,19 @@ class Client { if ( M_transport ) { delete M_transport; - M_transport = NULL; + M_transport = nullptr; } if ( M_gz_buf ) { delete M_gz_buf; - M_gz_buf = NULL; + M_gz_buf = nullptr; } if ( M_socket_buf ) { delete M_socket_buf; - M_socket_buf = NULL; + M_socket_buf = nullptr; } } @@ -258,7 +254,7 @@ class Client { { read_fds = read_fds_back; - int ret = ::select( max_fd, &read_fds, NULL, NULL, NULL ); + int ret = ::select( max_fd, &read_fds, nullptr, nullptr, nullptr ); if ( ret < 0 ) { perror( "Error selecting input" ); @@ -269,7 +265,7 @@ class Client { // read from stdin if ( FD_ISSET( in, &read_fds ) ) { - if ( std::fgets( buf, sizeof( buf ), stdin ) != NULL ) + if ( std::fgets( buf, sizeof( buf ), stdin ) ) { size_t len = std::strlen( buf ); if ( buf[len-1] == '\n' ) diff --git a/src/coach.cpp b/src/coach.cpp index f5a95388..e0a91a90 100644 --- a/src/coach.cpp +++ b/src/coach.cpp @@ -26,9 +26,7 @@ #include "coach.h" #include "audio.h" -#include "clangparser.h" -#include "clangmsg.h" -#include "clangmsgbuilder.h" +#include "logger.h" #include "stadium.h" #include "object.h" #include "player.h" @@ -39,7 +37,9 @@ #include "initsenderonlinecoach.h" #include "visualsendercoach.h" -#include +#include +#include +#include #include #include @@ -218,7 +218,7 @@ Coach::send( const char * msg ) { if ( RemoteClient::send( msg, std::strlen( msg ) + 1 ) != -1 ) { - M_stadium.logger().writeCoachLog( msg, SEND ); + Logger::instance().writeCoachLog( M_stadium, msg, SEND ); } } @@ -235,7 +235,7 @@ Coach::parseMsg( char * msg, } str[ len ] = 0; } - M_stadium.logger().writeCoachLog( str, RECV ); + Logger::instance().writeCoachLog( M_stadium, str, RECV ); parse_command( str ); } @@ -410,7 +410,7 @@ Coach::sendExternalMsg() } std::string msg = "(include "; - msg += boost::lexical_cast< std::string >( buf.size() ); + msg += std::to_string( buf.size() ); msg += ' '; msg.append( buf.begin(), buf.end() ); msg += ')'; @@ -528,11 +528,11 @@ Coach::parse_move( const char * command ) ServerParam::instance().maxMoment() ) ); if ( n == 3 ) { - M_stadium.movePlayer( side, unum, pos, NULL, NULL ); + M_stadium.movePlayer( side, unum, pos, nullptr, nullptr ); } else if ( n == 4 ) { - M_stadium.movePlayer( side, unum, pos, &ang, NULL ); + M_stadium.movePlayer( side, unum, pos, &ang, nullptr ); } else if ( n == 6 ) { @@ -725,7 +725,7 @@ Coach::change_player_type( const std::string & team_name, int unum, int player_type ) { - const Team * team = NULL; + const Team * team = nullptr; if ( M_stadium.teamLeft().name() == team_name ) { team = &( M_stadium.teamLeft() ); @@ -736,7 +736,7 @@ Coach::change_player_type( const std::string & team_name, team = &( M_stadium.teamRight() ); } - if ( team == NULL ) + if ( ! team ) { send( "(warning no_team_found)" ); return; @@ -749,7 +749,7 @@ Coach::change_player_type( const std::string & team_name, return; } - const Player * player = NULL; + const Player * player = nullptr; for ( int i = 0; i < team->size(); ++i ) { const Player * p = team->player( i ); @@ -760,7 +760,7 @@ Coach::change_player_type( const std::string & team_name, } } - if ( player == NULL ) + if ( ! player ) { send( "(warning no_such_player)" ); return; @@ -779,7 +779,7 @@ void Coach::change_player_type_goalie( const std::string & team_name, int unum ) { - const Team * team = NULL; + const Team * team = nullptr; if ( M_stadium.teamLeft().name() == team_name ) { team = &( M_stadium.teamLeft() ); @@ -1084,7 +1084,7 @@ OnlineCoach::send( const char * msg ) { if ( RemoteClient::send( msg, std::strlen( msg ) + 1 ) != -1 ) { - M_stadium.logger().writeOnlineCoachLog( *this, msg, SEND ); + Logger::instance().writeOnlineCoachLog( M_stadium, *this, msg, SEND ); } else { @@ -1108,7 +1108,7 @@ OnlineCoach::parseMsg( char * msg, str[ len ] = 0; } - M_stadium.logger().writeOnlineCoachLog( *this, str, RECV ); + Logger::instance().writeOnlineCoachLog( M_stadium, *this, str, RECV ); parse_command( str ); } @@ -1672,7 +1672,7 @@ OnlineCoach::change_player_types( const char * command ) return; } - const Player * player = NULL; + const Player * player = nullptr; for ( int i = 0; i < M_team.size(); ++i ) { const Player * p = M_team.player( i ); diff --git a/src/coach.h b/src/coach.h index d3351010..bfa86c88 100644 --- a/src/coach.h +++ b/src/coach.h @@ -62,9 +62,9 @@ class Coach private: // not used - Coach(); - Coach( const Coach & ); - Coach & operator=( const Coach & ); + Coach() = delete; + Coach( const Coach & ) = delete; + Coach & operator=( const Coach & ) = delete; public: @@ -72,7 +72,7 @@ class Coach Coach( Stadium & stadim ); virtual - ~Coach(); + ~Coach() override; void disable(); @@ -87,7 +87,7 @@ class Coach virtual void parseMsg( char * msg, - const size_t & len ); + const size_t & len ) override; virtual void parse_command( const char * command ); @@ -190,36 +190,41 @@ class OnlineCoach std::string M_coach_name; // not used - OnlineCoach(); - OnlineCoach( const OnlineCoach & ); - OnlineCoach & operator=( const OnlineCoach & ); + OnlineCoach() = delete; + OnlineCoach( const OnlineCoach & ) = delete; + OnlineCoach & operator=( const OnlineCoach & ) = delete; public: OnlineCoach( Stadium & stadium, Team & team ); - ~OnlineCoach(); + ~OnlineCoach() override; void disable(); virtual - bool setSenders( const double & client_version ); + bool setSenders( const double & client_version ) override; virtual - void sendInit(); + void sendInit() override; virtual - void send( const char * msg ); + void send( const char * msg ) override; virtual void parseMsg( char * msg, - const size_t & len ); + const size_t & len ) override; virtual - void parse_command( const char * command ); + void parse_command( const char * command ) override; + + const Team & team() const + { + return M_team; + } virtual - Side side() const + Side side() const override { return M_side; } diff --git a/src/compress.h b/src/compress.h index b93e6d22..6f62fc6d 100644 --- a/src/compress.h +++ b/src/compress.h @@ -54,13 +54,13 @@ class Compressor public: Compressor( int level = Z_DEFAULT_COMPRESSION, int strategy = Z_DEFAULT_STRATEGY ) - : M_out_buffer( NULL ), + : M_out_buffer( nullptr ), M_out_size( 0 ), M_out_avail( 0 ) { M_stream.zalloc = Z_NULL; M_stream.zfree = Z_NULL; - M_stream.opaque = NULL; + M_stream.opaque = nullptr; deflateInit( &M_stream, level ); deflateParams( &M_stream, level, strategy ); @@ -86,12 +86,14 @@ class Compressor int compress( const char* in_buffer, int in_size, int z_flush = Z_NO_FLUSH ) { - if( M_out_buffer == NULL ) + if ( ! M_out_buffer ) { M_out_avail = (int)(in_size * 1.01 + 12); M_out_buffer = (char*)malloc( M_out_avail ); - if( M_out_buffer == NULL ) + if ( ! M_out_buffer ) + { return Z_MEM_ERROR; + } M_stream.next_out = (Bytef*)M_out_buffer; M_stream.avail_out = M_out_avail; @@ -109,7 +111,7 @@ class Compressor { int extra = (int)(M_out_avail * 0.5); M_out_buffer = (char*)realloc( M_out_buffer, M_out_avail + extra ); - if( M_out_buffer == NULL ) + if ( ! M_out_buffer ) { err = Z_MEM_ERROR; break; @@ -134,13 +136,15 @@ class Compressor out = M_out_buffer; size = M_out_size; - if( detach ) + if ( detach ) { out = (char*)realloc( out, size ); - if( out == NULL ) + if ( ! out ) + { return Z_MEM_ERROR; + } - M_out_buffer = NULL; + M_out_buffer = nullptr; M_out_avail = 0; } @@ -164,13 +168,13 @@ class Decompressor public: Decompressor() - : M_out_buffer( NULL ), + : M_out_buffer( nullptr ), M_out_size( 0 ), M_out_avail( 0 ) { M_stream.zalloc = Z_NULL; M_stream.zfree = Z_NULL; - M_stream.opaque = NULL; + M_stream.opaque = nullptr; inflateInit( &M_stream ); } @@ -185,12 +189,14 @@ class Decompressor int in_size, int z_flush = Z_NO_FLUSH ) { - if( M_out_buffer == NULL ) + if ( ! M_out_buffer ) { M_out_avail = in_size * 2; M_out_buffer = (char*)malloc( M_out_avail ); - if( M_out_buffer == NULL ) + if ( ! M_out_buffer ) + { return Z_MEM_ERROR; + } M_stream.next_out = (Bytef*)M_out_buffer; M_stream.avail_out = M_out_avail; @@ -202,14 +208,14 @@ class Decompressor int bytes_out = M_stream.total_out; int err; - for(;;) + for ( ; ; ) { - if( M_stream.avail_out == 0 ) + if ( M_stream.avail_out == 0 ) { int extra = (int)(M_out_avail * 0.5); M_out_buffer = (char*)realloc( M_out_buffer, M_out_avail + extra ); - if( M_out_buffer == NULL ) + if ( ! M_out_buffer ) { err = Z_MEM_ERROR; break; @@ -221,8 +227,10 @@ class Decompressor } err = inflate( &M_stream, z_flush ); - if( err != Z_OK ) + if ( err != Z_OK ) + { break; + } } M_out_size = M_stream.total_out - bytes_out; @@ -237,10 +245,12 @@ class Decompressor if( detach ) { out = (char*)realloc( out, size ); - if( out == NULL ) + if ( !out ) + { return Z_MEM_ERROR; + } - M_out_buffer = NULL; + M_out_buffer = nullptr; M_out_avail = 0; } diff --git a/src/csvsaver.cpp b/src/csvsaver.cpp index 4f544a11..d041df85 100644 --- a/src/csvsaver.cpp +++ b/src/csvsaver.cpp @@ -27,12 +27,12 @@ #include "utility.h" -#include -#include - #include #include +#include +#include + #include #include #include @@ -48,7 +48,7 @@ const std::string CSVSaver::NAME = "CSVSaver"; CSVSaverParam & CSVSaverParam::instance() { - return CSVSaverParam::instance( NULL ); + return CSVSaverParam::instance( nullptr ); } @@ -56,7 +56,7 @@ CSVSaverParam & CSVSaverParam::instance( rcss::conf::Builder * parent ) { static bool parent_set = false; - if ( parent != NULL || parent_set ) + if ( parent || parent_set ) { static CSVSaverParam rval( parent ); parent_set = true; @@ -64,7 +64,7 @@ CSVSaverParam::instance( rcss::conf::Builder * parent ) } // hack to allow link testing to call instance without crashing // do not used the return value in these situations - CSVSaverParam * rval = NULL; + CSVSaverParam * rval = nullptr; return *rval; } @@ -97,14 +97,7 @@ CSVSaverParam::init( rcss::conf::Builder * parent ) boost::filesystem::path conf_path; try { - conf_path = boost::filesystem::path( tildeExpand( conf_dir ) -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); - + conf_path = boost::filesystem::path( tildeExpand( conf_dir ) ); conf_path /= "CSVSaver.conf"; } catch ( std::exception & e ) @@ -120,7 +113,7 @@ CSVSaverParam::init( rcss::conf::Builder * parent ) "CSVSaver" ) ) { std::cerr << "could not create or parse configuration file '" - << conf_path.BOOST_FS_FILE_STRING() + << conf_path.string() << "'" << std::endl; return false; } @@ -128,7 +121,7 @@ CSVSaverParam::init( rcss::conf::Builder * parent ) if ( instance().M_builder->version() != instance().M_builder->parsedVersion() ) { std::cerr << "Version mismatched in the configuration file. " - << "Need to regenerate '" << conf_path.BOOST_FS_FILE_STRING() << "'" + << "Need to regenerate '" << conf_path.string() << "'" << " or set '" << instance().M_builder->version() << "' to the 'version' option." << std::endl; // std::cerr << "registered version = [" @@ -209,13 +202,7 @@ CSVSaver::openResultsFile() boost::filesystem::path file_path; try { - file_path = boost::filesystem::path( tildeExpand( CSVSaverParam::instance().filename() ) -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + file_path = boost::filesystem::path( tildeExpand( CSVSaverParam::instance().filename() ) ); new_file = ! boost::filesystem::exists( file_path ); } catch ( std::exception & e ) @@ -228,7 +215,7 @@ CSVSaver::openResultsFile() return; } - M_file.open( file_path.BOOST_FS_FILE_STRING().c_str(), + M_file.open( file_path.c_str(), std::ofstream::out | std::ostream::app ); if ( ! M_file.is_open() ) { @@ -262,7 +249,7 @@ CSVSaver::doSaveStart() } void -CSVSaver::doSaveTime( const tm & time ) +CSVSaver::doSaveTime( const std::time_t time ) { M_time = time; } @@ -328,7 +315,8 @@ CSVSaver::doSaveComplete() { M_file.seekp( std::ofstream::end ); char time_str[256]; - std::strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", &M_time ); + const struct tm * lt = std::localtime( &M_time ); + std::strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", lt ); M_file << time_str << ", "; if ( M_team_name[ TEAM_LEFT ].empty() ) diff --git a/src/csvsaver.h b/src/csvsaver.h index ab7587f2..0bae6ba3 100644 --- a/src/csvsaver.h +++ b/src/csvsaver.h @@ -21,7 +21,7 @@ #include "resultsaver.hpp" -#include +#include #include #include @@ -39,9 +39,9 @@ class Builder; class CSVSaverParam { private: - CSVSaverParam(); // not used - CSVSaverParam( const CSVSaverParam & ); // not used - CSVSaverParam & operator=( const CSVSaverParam & ); // not used + CSVSaverParam() = delete; // not used + CSVSaverParam( const CSVSaverParam & ) = delete; // not used + CSVSaverParam & operator=( const CSVSaverParam & ) = delete; // not used protected: @@ -101,7 +101,7 @@ class CSVSaver public: virtual - ~CSVSaver(); + ~CSVSaver() override; static ResultSaver::Ptr create(); @@ -111,44 +111,44 @@ class CSVSaver void openResultsFile(); virtual - bool doEnabled() const; + bool doEnabled() const override; virtual - void doSaveStart(); + void doSaveStart() override; virtual - void doSaveTime( const tm & time ); + void doSaveTime( const std::time_t time ) override; virtual void doSaveTeamName( team_id id, - const std::string & name ); + const std::string & name ) override; virtual void doSaveCoachName( team_id id, - const std::string & name ); + const std::string & name ) override; virtual void doSaveScore( team_id id, - unsigned int score ); + unsigned int score ) override; virtual void doSavePenTaken( team_id id, - unsigned int taken ); + unsigned int taken ) override; virtual void doSavePenScored( team_id id, - unsigned int scored ); + unsigned int scored ) override; virtual - void doSaveCoinTossWinner( team_id id ); + void doSaveCoinTossWinner( team_id id ) override; virtual - bool doSaveComplete(); + bool doSaveComplete() override; virtual - const char * doGetName() const; + const char * doGetName() const override; - tm M_time; + std::time_t M_time; std::string M_team_name[ 2 ]; std::string M_coach_name[ 2 ]; unsigned int M_score[ 2 ]; diff --git a/src/dispsender.cpp b/src/dispsender.cpp index a097a898..49c42583 100644 --- a/src/dispsender.cpp +++ b/src/dispsender.cpp @@ -460,7 +460,7 @@ DispSenderMonitorV3::sendShow() last_sent_time = stadium().time(); last_sent_stoppage_time = stadium().stoppageTime(); - message.erase(); + message.clear(); // // create new data @@ -469,7 +469,7 @@ DispSenderMonitorV3::sendShow() std::ostringstream ostr; serializer().serializeShowBegin( ostr, - stadium().time() ); + stadium().time(), stadium().stoppageTime() ); serializer().serializePlayModeId( ostr, stadium().playmode() ); serializer().serializeScore( ostr, @@ -479,20 +479,19 @@ DispSenderMonitorV3::sendShow() serializer().serializeBall( ostr, stadium().ball() ); - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) - { - serializer().serializePlayerBegin( ostr, **p ); - serializer().serializePlayerPos( ostr, **p ); - serializer().serializePlayerArm( ostr, **p ); - serializer().serializePlayerViewMode( ostr, **p ); - serializer().serializePlayerStamina( ostr, **p ); - serializer().serializePlayerFocus( ostr, **p ); - serializer().serializePlayerCounts( ostr, **p ); + serializer().serializePlayerArrayBegin( ostr ); + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) + { + serializer().serializePlayerBegin( ostr, *p ); + serializer().serializePlayerPos( ostr, *p ); + serializer().serializePlayerArm( ostr, *p ); + serializer().serializePlayerViewMode( ostr, *p ); + serializer().serializePlayerStamina( ostr, *p ); + serializer().serializePlayerFocus( ostr, *p ); + serializer().serializePlayerCounts( ostr, *p ); serializer().serializePlayerEnd( ostr ); } + serializer().serializePlayerArrayEnd( ostr ); serializer().serializeShowEnd( ostr ); @@ -516,37 +515,120 @@ DispSenderMonitorV3::sendMsg( const BoardType board, // /*! // //=================================================================== // // -// // CLASS: DispSenderMonitorV4 +// // CLASS: DispSenderMonitorJSON // // -// // DESC: version 4 of display protocol. +// // DESC: version 5 of display protocol. // // // //=================================================================== // */ -// DispSenderMonitorV4::DispSenderMonitorV4( const Params & params ) -// : DispSenderMonitorV3( params ) -// { +DispSenderMonitorJSON::DispSenderMonitorJSON( const Params & params ) + : DispSenderMonitor( params ) +{ -// } +} -// DispSenderMonitorV4::~DispSenderMonitorV4() -// { +DispSenderMonitorJSON::~DispSenderMonitorJSON() +{ -// } +} -// void -// DispSenderMonitorV4::sendShow() -// { +void +DispSenderMonitorJSON::sendShow() +{ + static std::string message; + static int last_sent_time = -1; + static int last_sent_stoppage_time = -1; -// } + // + // send cached data + // -// void -// DispSenderMonitorV4::sendMsg( const BoardType board, -// const char * msg ) -// { + if ( stadium().time() == last_sent_time + && stadium().stoppageTime() == last_sent_stoppage_time ) + { + transport() << message << std::ends << std::flush; + return; + } -// } + last_sent_time = stadium().time(); + last_sent_stoppage_time = stadium().stoppageTime(); + + message.clear(); + + // + // create new data + // + + std::ostringstream ostr; + + serializer().serializeShowBegin( ostr, + stadium().time(), stadium().stoppageTime() ); + ostr << ','; + serializer().serializePlayModeId( ostr, + stadium().playmode() ); + ostr << ','; + serializer().serializeScore( ostr, + stadium().teamLeft(), + stadium().teamRight() ); + ostr << ','; + serializer().serializeBall( ostr, + stadium().ball() ); + ostr << ','; + serializer().serializePlayerArrayBegin( ostr ); + bool first = true; + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) + { + if ( first ) first = false; else ostr << ','; + serializer().serializePlayerBegin( ostr, *p ); + serializer().serializePlayerPos( ostr, *p ); + serializer().serializePlayerArm( ostr, *p ); + serializer().serializePlayerViewMode( ostr, *p ); + serializer().serializePlayerStamina( ostr, *p ); + serializer().serializePlayerFocus( ostr, *p ); + //serializer().serializePlayerCounts( ostr, *p ); + serializer().serializePlayerEnd( ostr ); + } + serializer().serializePlayerArrayEnd( ostr ); + + serializer().serializeShowEnd( ostr ); + + message = ostr.str(); + transport() << message << std::ends << std::flush; +} + +void +DispSenderMonitorJSON::sendMsg( const BoardType board, + const char * msg ) +{ + serializer().serializeMsg( transport(), + stadium().time(), stadium().stoppageTime(), + board, + msg ); + transport() << std::ends << std::flush; +} + + +void +DispSenderMonitorJSON::sendTeamGraphic( const Side side, + const unsigned int x, + const unsigned int y ) +{ + const std::shared_ptr< const XPMHolder > xpm = ( side == LEFT + ? stadium().teamLeft().teamGraphic( x, y ) + : side == RIGHT + ? stadium().teamRight().teamGraphic( x, y ) + : std::shared_ptr< const XPMHolder >() ); + if ( ! xpm + || ! xpm->valid() ) + { + return; + } + + serializer().serializeTeamGraphic( transport(), side, x, y, *xpm ); + transport() << std::ends << std::flush; +} /*! //=================================================================== @@ -918,23 +1000,20 @@ void DispSenderLoggerV4::sendShow() { serializer().serializeShowBegin( transport(), - stadium().time() ); + stadium().time(), stadium().stoppageTime() ); serializer().serializeBall( transport(), stadium().ball() ); - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) - { - serializer().serializePlayerBegin( transport(), **p ); - serializer().serializePlayerPos( transport(), **p ); - serializer().serializePlayerArm( transport(), **p ); - serializer().serializePlayerViewMode( transport(), **p ); - serializer().serializePlayerStamina( transport(), **p ); - serializer().serializePlayerFocus( transport(), **p ); - serializer().serializePlayerCounts( transport(), **p ); + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) + { + serializer().serializePlayerBegin( transport(), *p ); + serializer().serializePlayerPos( transport(), *p ); + serializer().serializePlayerArm( transport(), *p ); + serializer().serializePlayerViewMode( transport(), *p ); + serializer().serializePlayerStamina( transport(), *p ); + serializer().serializePlayerFocus( transport(), *p ); + serializer().serializePlayerCounts( transport(), *p ); serializer().serializePlayerEnd( transport() ); } @@ -955,40 +1034,93 @@ DispSenderLoggerV4::sendMsg( const BoardType board, } -// /*! -// //=================================================================== -// // -// // CLASS: DispSenderLoggerV5 -// // -// // DESC: version 5 log format -// // -// //=================================================================== -// */ +/*! +//=================================================================== +// +// CLASS: DispSenderLoggerJSON +// +// DESC: version 6 log format +// +//=================================================================== +*/ -// DispSenderLoggerV5::DispSenderLoggerV5( const Params & params ) -// : DispSenderLoggerV4( params ) -// { +DispSenderLoggerJSON::DispSenderLoggerJSON( const Params & params ) + : DispSenderLogger( params ) +{ -// } +} -// DispSenderLoggerV5::~DispSenderLoggerV5() -// { +DispSenderLoggerJSON::~DispSenderLoggerJSON() +{ -// } +} -// void -// DispSenderLoggerV5::sendShow() -// { -// DispSenderLoggerV4::sendShow(); -// } +void +DispSenderLoggerJSON::sendShow() +{ + transport() << ",\n"; -// void -// DispSenderLoggerV4::sendMsg( const BoardType board, -// const char * msg ) -// { + serializer().serializeShowBegin( transport(), + stadium().time(), stadium().stoppageTime() ); + transport() << ','; + serializer().serializeBall( transport(), + stadium().ball() ); + + transport() << ','; + serializer().serializePlayerArrayBegin( transport() ); + bool first = true; + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) + { + if ( first ) first = false; else transport() << ','; + serializer().serializePlayerBegin( transport(), *p ); + serializer().serializePlayerPos( transport(), *p ); + serializer().serializePlayerArm( transport(), *p ); + serializer().serializePlayerViewMode( transport(), *p ); + serializer().serializePlayerStamina( transport(), *p ); + serializer().serializePlayerFocus( transport(), *p ); + serializer().serializePlayerCounts( transport(), *p ); + serializer().serializePlayerEnd( transport() ); + } + serializer().serializePlayerArrayEnd( transport() ); + + serializer().serializeShowEnd( transport() ); + + transport() << std::flush; +} + +void +DispSenderLoggerJSON::sendMsg( const BoardType board, + const char * msg ) +{ + transport() << ",\n"; + serializer().serializeMsg( transport(), + stadium().time(), stadium().stoppageTime(), + board, + msg ); + transport() << std::flush; +} -// } +void +DispSenderLoggerJSON::sendTeamGraphic( const Side side, + const unsigned int x, + const unsigned int y ) +{ + const std::shared_ptr< const XPMHolder > xpm = ( side == LEFT + ? stadium().teamLeft().teamGraphic( x, y ) + : side == RIGHT + ? stadium().teamRight().teamGraphic( x, y ) + : std::shared_ptr< const XPMHolder >() ); + if ( ! xpm + || ! xpm->valid() ) + { + return; + } + + transport() << ",\n"; + serializer().serializeTeamGraphic( transport(), side, x, y, *xpm ); + transport() << std::flush; +} namespace dispsender { @@ -1003,6 +1135,7 @@ RegHolder vm1 = DispSenderMonitor::factory().autoReg( &create< DispSenderMonitor RegHolder vm2 = DispSenderMonitor::factory().autoReg( &create< DispSenderMonitorV2 >, 2 ); RegHolder vm3 = DispSenderMonitor::factory().autoReg( &create< DispSenderMonitorV3 >, 3 ); RegHolder vm4 = DispSenderMonitor::factory().autoReg( &create< DispSenderMonitorV3 >, 4 ); +RegHolder vm5 = DispSenderMonitor::factory().autoReg( &create< DispSenderMonitorJSON >, 5 ); template< typename Sender > @@ -1017,6 +1150,7 @@ RegHolder vl2 = DispSenderLogger::factory().autoReg( &create< DispSenderLoggerV2 RegHolder vl3 = DispSenderLogger::factory().autoReg( &create< DispSenderLoggerV3 >, 3 ); RegHolder vl4 = DispSenderLogger::factory().autoReg( &create< DispSenderLoggerV4 >, 4 ); RegHolder vl5 = DispSenderLogger::factory().autoReg( &create< DispSenderLoggerV4 >, 5 ); +RegHolder vl6 = DispSenderLogger::factory().autoReg( &create< DispSenderLoggerJSON >, 6 ); } } diff --git a/src/dispsender.h b/src/dispsender.h index 9fb7aa1c..151d2b69 100644 --- a/src/dispsender.h +++ b/src/dispsender.h @@ -26,7 +26,7 @@ #include "observer.h" #include "types.h" -#include +#include #include @@ -44,12 +44,14 @@ class SerializerMonitor; */ class DispSender : protected Sender { -public: +protected: DispSender( std::ostream & transport ); +public: + virtual - ~DispSender(); + ~DispSender() override; virtual void sendShow() = 0; @@ -112,9 +114,12 @@ class DispSenderMonitor static FactoryHolder & factory(); +protected: DispSenderMonitor( const Params & params ); - ~DispSenderMonitor(); +public: + virtual + ~DispSenderMonitor() override; protected: @@ -192,19 +197,19 @@ class DispSenderMonitorV1 DispSenderMonitorV1( const Params & params ); virtual - ~DispSenderMonitorV1(); + ~DispSenderMonitorV1() override; virtual - void sendShow(); + void sendShow() override; virtual void sendMsg( const BoardType board, - const char * msg ); + const char * msg ) override; virtual void sendTeamGraphic( const Side side, const unsigned int x, - const unsigned int y ); + const unsigned int y ) override; }; @@ -219,14 +224,14 @@ class DispSenderMonitorV2 DispSenderMonitorV2( const Params & params ); virtual - ~DispSenderMonitorV2(); + ~DispSenderMonitorV2() override; virtual - void sendShow(); + void sendShow() override; virtual void sendMsg( const BoardType board, - const char * msg ); + const char * msg ) override; //virtual //void sendTeamGraphic( const Side side, @@ -245,14 +250,14 @@ class DispSenderMonitorV3 DispSenderMonitorV3( const Params & params ); virtual - ~DispSenderMonitorV3(); + ~DispSenderMonitorV3() override; virtual - void sendShow(); + void sendShow() override; virtual void sendMsg( const BoardType board, - const char * msg ); + const char * msg ) override; //virtual //void sendTeamGraphic( const Side side, @@ -287,6 +292,34 @@ class DispSenderMonitorV3 // const unsigned int y ); // }; +/*! + \class DispSenderMonitorJSON + \brief class for the version 5 monitor protocol. (JSON format) +*/ +class DispSenderMonitorJSON + : public DispSenderMonitor { +public: + + DispSenderMonitorJSON( const Params & params ); + + virtual + ~DispSenderMonitorJSON() override; + + virtual + void sendShow() override; + + virtual + void sendMsg( const BoardType board, + const char * msg ) override; + + virtual + void sendTeamGraphic( const Side side, + const unsigned int x, + const unsigned int y ) override; +}; + + + //=================================================================== //=================================================================== @@ -331,9 +364,11 @@ class DispSenderLogger static FactoryHolder & factory(); +protected: DispSenderLogger( const Params & params ); - ~DispSenderLogger(); +public: + ~DispSenderLogger() override; protected: @@ -411,19 +446,19 @@ class DispSenderLoggerV1 DispSenderLoggerV1( const Params & params ); virtual - ~DispSenderLoggerV1(); + ~DispSenderLoggerV1() override; virtual - void sendShow(); + void sendShow() override; virtual void sendMsg( const BoardType board, - const char * msg ); + const char * msg ) override; virtual void sendTeamGraphic( const Side side, const unsigned int x, - const unsigned int y ); + const unsigned int y ) override; }; @@ -439,14 +474,14 @@ class DispSenderLoggerV2 DispSenderLoggerV2( const Params & params ); virtual - ~DispSenderLoggerV2(); + ~DispSenderLoggerV2() override; virtual - void sendShow(); + void sendShow() override; virtual void sendMsg( const BoardType board, - const char * msg ); + const char * msg ) override; }; @@ -462,10 +497,10 @@ class DispSenderLoggerV3 DispSenderLoggerV3( const Params & params ); virtual - ~DispSenderLoggerV3(); + ~DispSenderLoggerV3() override; virtual - void sendShow(); + void sendShow() override; //virtual //void sendMsg( const BoardType board, @@ -484,38 +519,42 @@ class DispSenderLoggerV4 DispSenderLoggerV4( const Params & params ); virtual - ~DispSenderLoggerV4(); + ~DispSenderLoggerV4() override; virtual - void sendShow(); + void sendShow() override; virtual void sendMsg( const BoardType board, - const char * msg ); + const char * msg ) override; }; -// /*! -// \class DispSenderLoggerV5 -// \brief class for the log version 5 -// */ -// class DispSenderLoggerV5 -// : public DispSenderLoggerV4 { -// public: +/*! + \class DispSenderLoggerV6 + \brief class for the log version 6 (JSON format) + */ +class DispSenderLoggerJSON + : public DispSenderLogger { +public: -// DispSenderLoggerV5( const Params & params ); + DispSenderLoggerJSON( const Params & params ); -// virtual -// ~DispSenderLoggerV5(); + virtual + ~DispSenderLoggerJSON() override; -// virtual -// void sendShow(); + virtual + void sendShow() override; -// virtual -// void sendMsg( const BoardType board, -// const char * msg ); + virtual + void sendMsg( const BoardType board, + const char * msg ); -// }; + virtual + void sendTeamGraphic( const Side side, + const unsigned int x, + const unsigned int y ) override; +}; } diff --git a/src/field.h b/src/field.h index cc2c5dab..4c15d948 100644 --- a/src/field.h +++ b/src/field.h @@ -44,10 +44,9 @@ #include "object.h" #include "weather.h" -#include "logger.h" -#include -#include +#include +#include #include #include diff --git a/src/fix_lexer_file.cmake b/src/fix_lexer_file.cmake new file mode 100755 index 00000000..41b738f7 --- /dev/null +++ b/src/fix_lexer_file.cmake @@ -0,0 +1,21 @@ +#!/usr/bin/cmake + +# This file contains the fix for the legacy code + +if(NOT DEFINED GENERATED_FILE_PATH) + message(FATAL_ERROR "Missing arguments for the fix_lexer_file script: GENERATED_FILE_PATH") +elseif(NOT DEFINED CORRECT_HEADER_NAME) + message(FATAL_ERROR "Missing arguments for the fix_lexer_file script: CORRECT_HEADER_NAME") +elseif(NOT DEFINED OUTPUT_FILE_PATH) + message(FATAL_ERROR "Missing arguments for the fix_lexer_file script: OUTPUT_FILE_PATH") +endif() + +# Replace #include in generated lexer files +file(READ ${GENERATED_FILE_PATH} FILE_CONTENTS) +string(REPLACE + "#include " # String to match + "#include \"${CORRECT_HEADER_NAME}\"" # With what to replace + FILE_CONTENTS # Where to put the result + "${FILE_CONTENTS}" # Input +) +file(WRITE ${OUTPUT_FILE_PATH} "${FILE_CONTENTS}") diff --git a/src/fullstatesender.cpp b/src/fullstatesender.cpp index b2f018ca..d99c0c94 100644 --- a/src/fullstatesender.cpp +++ b/src/fullstatesender.cpp @@ -180,14 +180,11 @@ FullStateSenderPlayerV5::sendFullState() sendBall(); - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - sendPlayer( *(*p) ); + sendPlayer( *p ); } // send end of FS @@ -478,6 +475,7 @@ RegHolder vp13 = FullStateSenderPlayer::factory().autoReg( &create< FullStateSen RegHolder vp14 = FullStateSenderPlayer::factory().autoReg( &create< FullStateSenderPlayerV13 >, 14 ); RegHolder vp15 = FullStateSenderPlayer::factory().autoReg( &create< FullStateSenderPlayerV13 >, 15 ); RegHolder vp16 = FullStateSenderPlayer::factory().autoReg( &create< FullStateSenderPlayerV13 >, 16 ); +RegHolder vp17 = FullStateSenderPlayer::factory().autoReg( &create< FullStateSenderPlayerV13 >, 17 ); } } diff --git a/src/fullstatesender.h b/src/fullstatesender.h index 595e6bca..6223b047 100644 --- a/src/fullstatesender.h +++ b/src/fullstatesender.h @@ -26,7 +26,7 @@ #include "sender.h" #include "observer.h" -#include +#include #include @@ -49,12 +49,13 @@ class SerializerPlayer; class FullStateSender : protected Sender { -public: +protected: FullStateSender( std::ostream & transport ); +public: virtual - ~FullStateSender(); + ~FullStateSender() override; virtual void sendFullState() = 0; @@ -108,10 +109,12 @@ class FullStateSenderPlayer static FactoryHolder & factory(); +protected: FullStateSenderPlayer( const Params & params ); +public: virtual - ~FullStateSenderPlayer(); + ~FullStateSenderPlayer() override; protected: const @@ -188,10 +191,10 @@ class FullStateSenderPlayerV1 FullStateSenderPlayerV1( const Params & ); virtual - ~FullStateSenderPlayerV1(); + ~FullStateSenderPlayerV1() override; virtual - void sendFullState(); + void sendFullState() override; }; /*! @@ -212,10 +215,10 @@ class FullStateSenderPlayerV5 FullStateSenderPlayerV5( const Params & ); virtual - ~FullStateSenderPlayerV5(); + ~FullStateSenderPlayerV5() override; virtual - void sendFullState(); + void sendFullState() override; protected: virtual @@ -248,20 +251,20 @@ class FullStateSenderPlayerV8 FullStateSenderPlayerV8( const Params & ); virtual - ~FullStateSenderPlayerV8(); + ~FullStateSenderPlayerV8() override; protected: virtual - void sendSelf(); + void sendSelf() override; virtual - void sendScore(); + void sendScore() override; virtual - void sendBall(); + void sendBall() override; virtual - void sendPlayer( const Player & p ); + void sendPlayer( const Player & p ) override; }; @@ -283,12 +286,12 @@ class FullStateSenderPlayerV13 FullStateSenderPlayerV13( const Params & ); virtual - ~FullStateSenderPlayerV13(); + ~FullStateSenderPlayerV13() override; protected: virtual - void sendPlayer( const Player & p ); + void sendPlayer( const Player & p ) override; }; diff --git a/src/heteroplayer.cpp b/src/heteroplayer.cpp index c82d5a5c..8509c4e1 100644 --- a/src/heteroplayer.cpp +++ b/src/heteroplayer.cpp @@ -39,23 +39,16 @@ #include "playerparam.h" #include "utility.h" -#include +#include +#include -#ifdef HAVE_SYS_PARAM_H -#include /* needed for htonl, htons, ... */ +#ifdef HAVE_ARPA_INET_H +#include /* needed for htonl, htons, ... */ #endif #ifdef HAVE_WINSOCK2_H #include /* needed for htonl, htons, ... */ #endif -#ifdef HAVE_NETINET_IN_H -#include -#endif - -#ifdef HAVE_SYS_TIME_H -#include // gettimeofday -#endif - HeteroPlayer::HeteroPlayer() { const int MAX_TRIAL = 1000; @@ -168,7 +161,7 @@ HeteroPlayer::delta( const double & min, const double & max ) { static bool s_seeded = false; - static boost::mt19937 s_engine; + static std::mt19937 s_engine; if ( ! s_seeded ) { @@ -187,10 +180,9 @@ HeteroPlayer::delta( const double & min, } else { - timeval now; - gettimeofday ( &now, NULL ); + std::random_device seed_gen; + const int seed = seed_gen(); - int seed = static_cast< int >( now.tv_usec ); PlayerParam::instance().setRandomSeed( seed ); std::cout << "Hetero Player Seed: " << seed << std::endl; s_engine.seed( PlayerParam::instance().randomSeed() ); @@ -211,9 +203,8 @@ HeteroPlayer::delta( const double & min, std::swap( minv, maxv ); } - boost::uniform_real< double > rng( minv, maxv ); - boost::variate_generator< boost::mt19937&, boost::uniform_real<> > gen( s_engine, rng ); - return gen(); + std::uniform_real_distribution< double > rng( minv, maxv ); + return rng( s_engine ); } void @@ -297,39 +288,84 @@ namespace { template < typename T > void -serialize_param( std::ostream & o, - const std::string & name, - const T & value ) +to_sexp( std::ostream & o, + const std::string & name, + const T & value ) { o << '(' << name << ' ' << value << ')'; } +template < typename T > +void +to_json_member( std::ostream & os, + const std::string & name, + const T & value ) +{ + os << std::quoted( name ) << ':' << value; +} + } void -HeteroPlayer::serializeParams( std::ostream & o, - const unsigned int version, - const int id ) const +HeteroPlayer::printParamsSExp( std::ostream & o, + const unsigned int version ) const { - serialize_param( o, "id", id ); - serialize_param( o, "player_speed_max", playerSpeedMax() ); - serialize_param( o, "stamina_inc_max", staminaIncMax() ); - serialize_param( o, "player_decay", playerDecay() ); - serialize_param( o, "inertia_moment", inertiaMoment() ); - serialize_param( o, "dash_power_rate", dashPowerRate() ); - serialize_param( o, "player_size", playerSize() ); - serialize_param( o, "kickable_margin", kickableMargin() ); - serialize_param( o, "kick_rand", kickRand() ); - serialize_param( o, "extra_stamina", extraStamina() ); - serialize_param( o, "effort_max", effortMax() ); - serialize_param( o, "effort_min", effortMin() ); + //to_sexp( o, "id", id ); + to_sexp( o, "player_speed_max", playerSpeedMax() ); + to_sexp( o, "stamina_inc_max", staminaIncMax() ); + to_sexp( o, "player_decay", playerDecay() ); + to_sexp( o, "inertia_moment", inertiaMoment() ); + to_sexp( o, "dash_power_rate", dashPowerRate() ); + to_sexp( o, "player_size", playerSize() ); + to_sexp( o, "kickable_margin", kickableMargin() ); + to_sexp( o, "kick_rand", kickRand() ); + to_sexp( o, "extra_stamina", extraStamina() ); + to_sexp( o, "effort_max", effortMax() ); + to_sexp( o, "effort_min", effortMin() ); if ( version < 14 ) { return; } - serialize_param( o, "kick_power_rate", kickPowerRate() ); - serialize_param( o, "foul_detect_probability", foulDetectProbability() ); - serialize_param( o, "catchable_area_l_stretch", catchAreaLengthStretch() ); + to_sexp( o, "kick_power_rate", kickPowerRate() ); + to_sexp( o, "foul_detect_probability", foulDetectProbability() ); + to_sexp( o, "catchable_area_l_stretch", catchAreaLengthStretch() ); +} + + +void +HeteroPlayer::printParamsJSON( std::ostream & o, + const unsigned int version ) const +{ + to_json_member( o, "player_speed_max", playerSpeedMax() ); + o << ','; + to_json_member( o, "stamina_inc_max", staminaIncMax() ); + o << ','; + to_json_member( o, "player_decay", playerDecay() ); + o << ','; + to_json_member( o, "inertia_moment", inertiaMoment() ); + o << ','; + to_json_member( o, "dash_power_rate", dashPowerRate() ); + o << ','; + to_json_member( o, "player_size", playerSize() ); + o << ','; + to_json_member( o, "kickable_margin", kickableMargin() ); + o << ','; + to_json_member( o, "kick_rand", kickRand() ); + o << ','; + to_json_member( o, "extra_stamina", extraStamina() ); + o << ','; + to_json_member( o, "effort_max", effortMax() ); + o << ','; + to_json_member( o, "effort_min", effortMin() ); + if ( version >= 14 ) + { + o << ','; + to_json_member( o, "kick_power_rate", kickPowerRate() ); + o << ','; + to_json_member( o, "foul_detect_probability", foulDetectProbability() ); + o << ','; + to_json_member( o, "catchable_area_l_stretch", catchAreaLengthStretch() ); + } } diff --git a/src/heteroplayer.h b/src/heteroplayer.h index 1a7e5833..e9016937 100644 --- a/src/heteroplayer.h +++ b/src/heteroplayer.h @@ -62,9 +62,10 @@ class HeteroPlayer { player_type_t convertToStruct( int id ) const; - void serializeParams( std::ostream & o, - const unsigned int version, - const int id ) const; + void printParamsSExp( std::ostream & o, + const unsigned int version ) const; + void printParamsJSON( std::ostream & o, + const unsigned int version ) const; private: double delta( const double & min, diff --git a/src/initsender.cpp b/src/initsender.cpp index 1882a2fc..d873f4de 100644 --- a/src/initsender.cpp +++ b/src/initsender.cpp @@ -291,7 +291,7 @@ InitSenderCommonV7::sendServerParams() serializer().serializeParam( transport(), ServerParam::instance().dropTime() ); serializer().serializeServerParamEnd( transport() ); - if ( newLine() ) + if ( isGameLog() ) { transport() << std::endl; } @@ -349,7 +349,7 @@ InitSenderCommonV7::sendPlayerParams() serializer().serializeParam( transport(), PlayerParam::instance().effortMinDeltaFactor() ); serializer().serializePlayerParamEnd( transport() ); - if ( newLine() ) + if ( isGameLog() ) { transport() << std::endl; } @@ -365,14 +365,14 @@ InitSenderCommonV7::sendPlayerTypes() for ( int i = 0; i < PlayerParam::instance().playerTypes(); ++i ) { const HeteroPlayer * type = stadium().playerType( i ); - if ( type != NULL ) + if ( type ) { - serializer().serializePlayerTypeBegin( transport() ); + serializer().serializePlayerTypeBegin( transport(), i ); - serializePlayerType( i, *type ); + serializePlayerType( *type ); serializer().serializePlayerTypeEnd( transport() ); - if ( newLine() ) + if ( isGameLog() ) { transport() << std::endl; } @@ -385,11 +385,10 @@ InitSenderCommonV7::sendPlayerTypes() } void -InitSenderCommonV7::serializePlayerType( const int id, - const HeteroPlayer & type ) +InitSenderCommonV7::serializePlayerType( const HeteroPlayer & type ) { - serializer().serializeParam( transport(), - id ); + // serializer().serializeParam( transport(), + // id ); serializer().serializeParam( transport(), type.playerSpeedMax() ); serializer().serializeParam( transport(), @@ -420,12 +419,20 @@ void InitSenderCommonV8::sendServerParams() { serializer().serializeServerParamBegin( transport() ); - std::for_each( ServerParam::instance().verMap().begin(), - ServerParam::instance().verMap().end(), - std::bind1st( std::mem_fun( &rcss::InitSenderCommonV8::sendServerParam ), - this ) ); + for ( ServerParam::VerMap::const_reference param : ServerParam::instance().verMap() ) + { + sendServerParam( param ); + } + // std::for_each( ServerParam::instance().verMap().begin(), + // ServerParam::instance().verMap().end(), + // [this]( const ServerParam::VerMap::value_type & v ) + // { + // sendServerParam( v ); + // } ); + // // std::bind1st( std::mem_fun( &rcss::InitSenderCommonV8::sendServerParam ), + // // this ) ); serializer().serializeServerParamEnd( transport() ); - if ( newLine() ) + if ( isGameLog() ) { transport() << std::endl; } @@ -436,7 +443,7 @@ InitSenderCommonV8::sendServerParams() } void -InitSenderCommonV8::doSendServerParam( ServerParam::VerMap::value_type param ) +InitSenderCommonV8::sendServerParam( const ServerParam::VerMap::value_type & param ) { if ( param.second <= version() ) { @@ -483,12 +490,20 @@ void InitSenderCommonV8::sendPlayerParams() { serializer().serializePlayerParamBegin( transport() ); - std::for_each( PlayerParam::instance().verMap().begin(), - PlayerParam::instance().verMap().end(), - std::bind1st( std::mem_fun( &rcss::InitSenderCommonV8::sendPlayerParam ), - this ) ); + for ( PlayerParam::VerMap::const_reference param : PlayerParam::instance().verMap() ) + { + sendPlayerParam( param ); + } + // std::for_each( PlayerParam::instance().verMap().begin(), + // PlayerParam::instance().verMap().end(), + // [this]( const PlayerParam::VerMap::value_type & v ) + // { + // sendPlayerParam( v ); + // } ); + // // std::bind1st( std::mem_fun( &rcss::InitSenderCommonV8::sendPlayerParam ), + // // this ) ); serializer().serializePlayerParamEnd( transport() ); - if ( newLine() ) + if ( isGameLog() ) { transport() << std::endl; } @@ -500,7 +515,7 @@ InitSenderCommonV8::sendPlayerParams() void -InitSenderCommonV8::doSendPlayerParam( PlayerParam::VerMap::value_type param ) +InitSenderCommonV8::sendPlayerParam( const PlayerParam::VerMap::value_type & param ) { if ( param.second <= version() ) { @@ -548,14 +563,14 @@ InitSenderCommonV8::sendPlayerTypes() for ( int i = 0; i < PlayerParam::instance().playerTypes(); ++i ) { const HeteroPlayer * type = stadium().playerType( i ); - if ( type != NULL ) + if ( type ) { - serializer().serializePlayerTypeBegin( transport() ); + serializer().serializePlayerTypeBegin( transport(), i ); - serializePlayerType( i, *type ); + type->printParamsSExp( transport(), version() ); serializer().serializePlayerTypeEnd( transport() ); - if ( newLine() ) + if ( isGameLog() ) { transport() << std::endl; } @@ -567,13 +582,224 @@ InitSenderCommonV8::sendPlayerTypes() } } + +/*-------------------------------------------------------------------*/ +/*-------------------------------------------------------------------*/ +/*-------------------------------------------------------------------*/ + +void +InitSenderCommonJSON::sendServerParams() +{ + if ( isGameLog() ) + { + transport() << ",\n"; + } + + serializer().serializeServerParamBegin( transport() ); + bool first = true; + for ( ServerParam::VerMap::const_reference param : ServerParam::instance().verMap() ) + { + if ( param.second <= version() ) + { + if ( first ) + { + first = false; + } + else + { + transport() << ','; + } + + sendServerParam( param ); + } + } + // std::for_each( ServerParam::instance().verMap().begin(), + // ServerParam::instance().verMap().end(), + // [this,&]( const ServerParam::VerMap::value_type & v ) + // { + // if ( v.second <= version() ) + // { + // if ( ! first ) + // { + // transport() << ","; + // first = false; + // } + // sendServerParam( v ); + // } + // } ); + serializer().serializeServerParamEnd( transport() ); + + if ( isGameLog() ) + { + transport() << std::flush; + } + else + { + transport() << std::ends << std::flush; + } +} + +void +InitSenderCommonJSON::sendPlayerParams() +{ + if ( isGameLog() ) + { + transport() << ",\n"; + } + + serializer().serializePlayerParamBegin( transport() ); + bool first = true; + for ( PlayerParam::VerMap::const_reference param : PlayerParam::instance().verMap() ) + { + if ( param.second <= version() ) + { + if ( first ) first = false; else transport() << ','; + + sendPlayerParam( param ); + } + } + // std::for_each( PlayerParam::instance().verMap().begin(), + // PlayerParam::instance().verMap().end(), + // [this,&]( const PlayerParam::VerMap::value_type & v ) + // { + // if ( v.second <= version() ) + // { + // if ( ! first ) + // { + // transport() << ","; + // first = false; + // } + // sendPlayerParam( v ); + // } + // } ); + serializer().serializePlayerParamEnd( transport() ); + + if ( isGameLog() ) + { + transport() << std::flush; + } + else + { + transport() << std::ends << std::flush; + } +} + + +void +InitSenderCommonJSON::sendPlayerTypes() +{ + const int max_types = PlayerParam::instance().playerTypes(); + if ( max_types == 0 ) + { + return; + } + + for ( int i = 0; i < max_types; ++i ) + { + const HeteroPlayer * type = stadium().playerType( i ); + if ( type ) + { + if ( isGameLog() ) + { + transport() << ",\n"; + } + + serializer().serializePlayerTypeBegin( transport(), i ); + + type->printParamsJSON( transport(), version() ); + + serializer().serializePlayerTypeEnd( transport() ); + if ( isGameLog() ) + { + transport() << std::flush; + } + else + { + transport() << std::ends << std::flush; + } + } + } +} + void -InitSenderCommonV8::serializePlayerType( const int id, - const HeteroPlayer & type ) +InitSenderCommonJSON::sendServerParam( ServerParam::VerMap::value_type param ) { - type.serializeParams( transport(), - version(), - id ); + int ivalue; + if ( ServerParam::instance().getInt( param.first, ivalue ) ) + { + serializer().serializeParam( transport(), + param.first, + ivalue ); + return; + } + + bool bvalue; + if ( ServerParam::instance().getBool( param.first, bvalue ) ) + { + serializer().serializeParam( transport(), + param.first, + bvalue ); + return; + } + + double dvalue; + if ( ServerParam::instance().getDouble( param.first, dvalue ) ) + { + serializer().serializeParam( transport(), + param.first, + dvalue ); + return; + } + + std::string svalue; + if ( ServerParam::instance().getStr( param.first, svalue ) ) + { + serializer().serializeParam( transport(), + param.first, + svalue ); + return; + } +} + +void +InitSenderCommonJSON::sendPlayerParam( const PlayerParam::VerMap::value_type & param ) +{ + int ivalue; + if ( PlayerParam::instance().getInt( param.first, ivalue ) ) + { + serializer().serializeParam( transport(), + param.first, + ivalue ); + return; + } + + bool bvalue; + if ( PlayerParam::instance().getBool( param.first, bvalue ) ) + { + serializer().serializeParam( transport(), + param.first, + bvalue ); + return; + } + + double dvalue; + if ( PlayerParam::instance().getDouble( param.first, dvalue ) ) + { + serializer().serializeParam( transport(), + param.first, + dvalue ); + return; + } + + std::string svalue; + if ( PlayerParam::instance().getStr( param.first, svalue ) ) + { + serializer().serializeParam( transport(), + param.first, + svalue ); + return; + } } + } diff --git a/src/initsender.h b/src/initsender.h index 68a6e17c..b0580a22 100644 --- a/src/initsender.h +++ b/src/initsender.h @@ -53,19 +53,19 @@ class InitSenderCommon { const std::shared_ptr< Serializer > M_serializer; const Stadium & M_stadium; const unsigned int M_version; - const bool M_new_line; + const bool M_game_log; public: InitSenderCommon( std::ostream & transport, const std::shared_ptr< Serializer > serializer, const Stadium & stadium, unsigned int version, - const bool new_line = false ) + const bool game_log = false ) : M_transport( transport ), M_serializer( serializer ), M_stadium( stadium ), M_version( version ), - M_new_line( new_line ) + M_game_log( game_log ) { } virtual @@ -92,9 +92,9 @@ class InitSenderCommon { return M_version; } - bool newLine() const + bool isGameLog() const { - return M_new_line; + return M_game_log; } virtual @@ -129,7 +129,7 @@ class InitSender public: virtual - ~InitSender(); + ~InitSender() override; InitSenderCommon & commonSender() { @@ -192,19 +192,19 @@ class InitSenderCommonV1 { } virtual - ~InitSenderCommonV1() + ~InitSenderCommonV1() override { } virtual - void sendServerParams() + void sendServerParams() override { } virtual - void sendPlayerParams() + void sendPlayerParams() override { } virtual - void sendPlayerTypes() + void sendPlayerTypes() override { } }; @@ -235,22 +235,21 @@ class InitSenderCommonV7 { } virtual - ~InitSenderCommonV7() + ~InitSenderCommonV7() override { } virtual - void sendServerParams(); + void sendServerParams() override; virtual - void sendPlayerParams(); + void sendPlayerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerTypes() override; protected: virtual - void serializePlayerType( const int id, - const HeteroPlayer & type ); + void serializePlayerType( const HeteroPlayer & type ); }; @@ -280,41 +279,73 @@ class InitSenderCommonV8 { } virtual - ~InitSenderCommonV8() + ~InitSenderCommonV8() override { } virtual - void sendServerParams(); + void sendServerParams() override; - void sendServerParam( ServerParam::VerMap::value_type param ) - { - doSendServerParam( param ); - } - - void sendPlayerParam( PlayerParam::VerMap::value_type param ) - { - doSendPlayerParam( param ); - } + virtual + void sendPlayerParams() override; virtual - void sendPlayerParams(); + void sendPlayerTypes() override; + +private: + + void sendServerParam( const ServerParam::VerMap::value_type & param ); + + void sendPlayerParam( const PlayerParam::VerMap::value_type & param ); +}; + + +/*! +//=================================================================== +// +// CLASS: InitSenderCommonJSON +// +// DESC: JSON format of the init protocol for monitor/log. +// +//=================================================================== +*/ + +class InitSenderCommonJSON + : public InitSenderCommon { +public: + InitSenderCommonJSON( std::ostream & transport, + const std::shared_ptr< Serializer > serializer, + const Stadium & stad, + unsigned int version, + const bool new_line = false ) + : InitSenderCommon( transport, + serializer, + stad, + version, + new_line ) + { } virtual - void sendPlayerTypes(); + ~InitSenderCommonJSON() override + { } -protected: virtual - void doSendServerParam( ServerParam::VerMap::value_type param ); + void sendServerParams() override; virtual - void doSendPlayerParam( PlayerParam::VerMap::value_type param ); + void sendPlayerParams() override; virtual - void serializePlayerType( const int id, - const HeteroPlayer & type ); + void sendPlayerTypes() override; + + +protected: + + void sendServerParam( ServerParam::VerMap::value_type param ); + void sendPlayerParam( const PlayerParam::VerMap::value_type & param ); }; + } #endif diff --git a/src/initsendercoach.cpp b/src/initsendercoach.cpp index 414fd83c..dca0e40b 100644 --- a/src/initsendercoach.cpp +++ b/src/initsendercoach.cpp @@ -221,6 +221,7 @@ RegHolder vc13 = InitSenderOfflineCoach::factory().autoReg( &create< InitSenderO RegHolder vc14 = InitSenderOfflineCoach::factory().autoReg( &create< InitSenderOfflineCoachV8 >, 14 ); RegHolder vc15 = InitSenderOfflineCoach::factory().autoReg( &create< InitSenderOfflineCoachV8 >, 15 ); RegHolder vc16 = InitSenderOfflineCoach::factory().autoReg( &create< InitSenderOfflineCoachV8 >, 16 ); +RegHolder vc17 = InitSenderOfflineCoach::factory().autoReg( &create< InitSenderOfflineCoachV8 >, 17 ); } } diff --git a/src/initsendercoach.h b/src/initsendercoach.h index d73da513..df77969d 100644 --- a/src/initsendercoach.h +++ b/src/initsendercoach.h @@ -25,7 +25,7 @@ #include "initsender.h" -#include +#include #include @@ -74,7 +74,7 @@ class InitSenderOfflineCoach FactoryHolder & factory(); virtual - ~InitSenderOfflineCoach(); + ~InitSenderOfflineCoach() override; protected: InitSenderOfflineCoach( const Params & params, @@ -193,7 +193,7 @@ class InitSenderOfflineCoachV1 public: virtual - ~InitSenderOfflineCoachV1(); + ~InitSenderOfflineCoachV1() override; virtual void sendInit(); @@ -226,7 +226,7 @@ class InitSenderOfflineCoachV7 public: virtual - ~InitSenderOfflineCoachV7(); + ~InitSenderOfflineCoachV7() override; }; @@ -251,7 +251,7 @@ class InitSenderOfflineCoachV8 public: virtual - ~InitSenderOfflineCoachV8(); + ~InitSenderOfflineCoachV8() override; }; diff --git a/src/initsenderlogger.cpp b/src/initsenderlogger.cpp index b40b461d..8b62a16c 100644 --- a/src/initsenderlogger.cpp +++ b/src/initsenderlogger.cpp @@ -25,7 +25,6 @@ #include "initsenderlogger.h" -#include "logger.h" #include "serializermonitor.h" #include "types.h" @@ -35,6 +34,8 @@ #include "playerparam.h" #include "heteroplayer.h" +#include + #ifdef HAVE_NETINET_IN_H #include #endif @@ -112,6 +113,12 @@ InitSenderLoggerV1::sendHeader() } +void +InitSenderLoggerV1::sendTail() +{ + +} + void InitSenderLoggerV1::sendServerParams() { @@ -377,6 +384,15 @@ InitSenderLoggerV4::sendHeader() transport() << "ULG4" << std::endl; } + +void +InitSenderLoggerV4::sendTail() +{ + // write the game result + sendTeam(); +} + + void InitSenderLoggerV4::sendServerParams() { @@ -400,7 +416,7 @@ void InitSenderLoggerV4::sendPlayMode() { serializer().serializePlayMode( transport(), - stadium().time(), + stadium().time(), stadium().stoppageTime(), stadium().playmode() ); transport() << std::endl; } @@ -409,7 +425,7 @@ void InitSenderLoggerV4::sendTeam() { serializer().serializeTeam( transport(), - stadium().time(), + stadium().time(), stadium().stoppageTime(), stadium().teamLeft(), stadium().teamRight() ); transport() << std::endl; @@ -456,6 +472,91 @@ InitSenderLoggerV5::sendHeader() } +/* +//=================================================================== +// +// InitSenderLoggerJSON +// +//=================================================================== +*/ + +InitSenderLoggerJSON::InitSenderLoggerJSON( const Params & params ) + : InitSenderLogger( params, + std::shared_ptr< InitSenderCommon >( new InitSenderCommonJSON( params.M_transport, + params.M_serializer, + params.M_stadium, + 999, // accept all parameters + true ) ) ) // new line +{ + // The client version is set to "999" in order to send all parameters. +} + +InitSenderLoggerJSON::InitSenderLoggerJSON( const Params & params, + const std::shared_ptr< InitSenderCommon > common ) + : InitSenderLogger( params, common ) +{ + +} + +InitSenderLoggerJSON::~InitSenderLoggerJSON() +{ + +} + +void +InitSenderLoggerJSON::sendHeader() +{ + transport() << "ULG6\n"; + transport() << "[\n"; + + transport() << '{' + << std::quoted( "type" ) << ':' << std::quoted( "header" ); + + transport() << ',' + << std::quoted( "version" ) << ':' << std::quoted( VERSION ); + + const std::time_t t = stadium().getStartTime(); + transport() << ',' + << std::quoted( "timestamp" ) << ':' + << '"' << std::put_time( std::localtime( &t ), "%FT%T%z" ) << '"'; + + transport() << '}'; +} + + +void +InitSenderLoggerJSON::sendTail() +{ + // write the game result + sendTeam(); + + transport() << '\n' + << ']' << std::endl; +} + + +void +InitSenderLoggerJSON::sendPlayMode() +{ + transport() << ",\n"; + serializer().serializePlayMode( transport(), + stadium().time(), stadium().stoppageTime(), + stadium().playmode() ); + transport() << std::flush; +} + +void +InitSenderLoggerJSON::sendTeam() +{ + transport() << ",\n"; + serializer().serializeTeam( transport(), + stadium().time(), stadium().stoppageTime(), + stadium().teamLeft(), + stadium().teamRight() ); + transport() << std::flush; +} + + namespace initsender { template< typename Sender > @@ -470,6 +571,7 @@ RegHolder vl2 = InitSenderLogger::factory().autoReg( &create< InitSenderLoggerV2 RegHolder vl3 = InitSenderLogger::factory().autoReg( &create< InitSenderLoggerV3 >, 3 ); RegHolder vl4 = InitSenderLogger::factory().autoReg( &create< InitSenderLoggerV4 >, 4 ); RegHolder vl5 = InitSenderLogger::factory().autoReg( &create< InitSenderLoggerV5 >, 5 ); +RegHolder vl6 = InitSenderLogger::factory().autoReg( &create< InitSenderLoggerJSON >, 6 ); } } diff --git a/src/initsenderlogger.h b/src/initsenderlogger.h index 9e9a59ae..d88485b4 100644 --- a/src/initsenderlogger.h +++ b/src/initsenderlogger.h @@ -25,7 +25,7 @@ #include "initsender.h" -#include +#include #include @@ -74,7 +74,7 @@ class InitSenderLogger FactoryHolder & factory(); virtual - ~InitSenderLogger(); + ~InitSenderLogger() override; protected: @@ -111,6 +111,9 @@ class InitSenderLogger virtual void sendHeader() = 0; + virtual + void sendTail() = 0; + virtual void sendPlayMode() = 0; @@ -143,6 +146,11 @@ class InitObserverLogger BaseObserver< InitSenderLogger >::sender().sendHeader(); } + void sendTail() + { + BaseObserver< InitSenderLogger >::sender().sendTail(); + } + void sendServerParams() { BaseObserver< InitSenderLogger >::sender().sendServerParams(); @@ -182,26 +190,28 @@ class InitSenderLoggerV1 public: virtual - ~InitSenderLoggerV1(); + ~InitSenderLoggerV1() override; virtual - void sendHeader(); + void sendHeader() override; virtual - void sendServerParams(); + void sendTail() override; virtual - void sendPlayerParams(); + void sendServerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerParams() override; virtual - void sendPlayMode(); + void sendPlayerTypes() override; virtual - void sendTeam(); + void sendPlayMode() override; + virtual + void sendTeam() override; }; class InitSenderLoggerV2 @@ -215,25 +225,28 @@ class InitSenderLoggerV2 public: virtual - ~InitSenderLoggerV2(); + ~InitSenderLoggerV2() override; virtual - void sendHeader(); + void sendHeader() override; + + // virtual + // void sendTail() override; virtual - void sendServerParams(); + void sendServerParams() override; virtual - void sendPlayerParams(); + void sendPlayerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerTypes() override; virtual - void sendPlayMode(); + void sendPlayMode() override; virtual - void sendTeam(); + void sendTeam() override; }; @@ -248,25 +261,28 @@ class InitSenderLoggerV3 public: virtual - ~InitSenderLoggerV3(); + ~InitSenderLoggerV3() override; virtual - void sendHeader(); + void sendHeader() override; + + // virtual + // void sendTail() override; virtual - void sendServerParams(); + void sendServerParams() override; virtual - void sendPlayerParams(); + void sendPlayerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerTypes() override; virtual - void sendPlayMode(); + void sendPlayMode() override; virtual - void sendTeam(); + void sendTeam() override; }; @@ -282,25 +298,28 @@ class InitSenderLoggerV4 public: virtual - ~InitSenderLoggerV4(); + ~InitSenderLoggerV4() override; virtual - void sendHeader(); + void sendHeader() override; virtual - void sendServerParams(); + void sendTail() override; virtual - void sendPlayerParams(); + void sendServerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerParams() override; virtual - void sendPlayMode(); + void sendPlayerTypes() override; virtual - void sendTeam(); + void sendPlayMode() override; + + virtual + void sendTeam() override; }; @@ -316,13 +335,43 @@ class InitSenderLoggerV5 public: virtual - ~InitSenderLoggerV5(); + ~InitSenderLoggerV5() override; virtual - void sendHeader(); + void sendHeader() override; }; +/*! + \brief version 6 of the init sender for Logger (JSON format) +*/ +class InitSenderLoggerJSON + : public InitSenderLogger { +public: + InitSenderLoggerJSON( const Params & params ); + +protected: + InitSenderLoggerJSON( const Params & params, + const std::shared_ptr< InitSenderCommon > common ); + +public: + virtual + ~InitSenderLoggerJSON() override; + + virtual + void sendHeader() override; + + virtual + void sendTail() override; + + virtual + void sendPlayMode() override; + + virtual + void sendTeam() override; +}; + + } #endif diff --git a/src/initsendermonitor.cpp b/src/initsendermonitor.cpp index fe04a471..232b3797 100644 --- a/src/initsendermonitor.cpp +++ b/src/initsendermonitor.cpp @@ -275,7 +275,7 @@ void InitSenderMonitorV3::sendScore() { serializer().serializeTeam( transport(), - stadium().time(), + stadium().time(), stadium().stoppageTime(), stadium().teamLeft(), stadium().teamRight() ); transport() << std::ends << std::flush; @@ -285,11 +285,87 @@ void InitSenderMonitorV3::sendPlayMode() { serializer().serializePlayMode( transport(), - stadium().time(), + stadium().time(), stadium().stoppageTime(), stadium().playmode() ); transport() << std::ends << std::flush; } +/* +//=================================================================== +// +// InitSenderMonitorJSON +// +//=================================================================== +*/ + + +InitSenderMonitorJSON::InitSenderMonitorJSON( const Params & params ) + : InitSenderMonitor( params, + std::shared_ptr< InitSenderCommon >( new InitSenderCommonJSON( params.M_transport, + params.M_serializer, + params.M_stadium, + 999 ) ) ) +{ + // The client version must be "999" in order to send all parameters. +} + + +InitSenderMonitorJSON::~InitSenderMonitorJSON() +{ + +} + +void +InitSenderMonitorJSON::sendInit() +{ + +} + +void +InitSenderMonitorJSON::sendServerParams() +{ + commonSender().sendServerParams(); +} + +void +InitSenderMonitorJSON::sendPlayerParams() +{ + commonSender().sendPlayerParams(); +} + +void +InitSenderMonitorJSON::sendPlayerTypes() +{ + commonSender().sendPlayerTypes(); +} + +void +InitSenderMonitorJSON::sendChangedPlayers() +{ + +} + +void +InitSenderMonitorJSON::sendScore() +{ + serializer().serializeTeam( transport(), + stadium().time(), stadium().stoppageTime(), + stadium().teamLeft(), + stadium().teamRight() ); + transport() << std::ends << std::flush; +} + + +void +InitSenderMonitorJSON::sendPlayMode() +{ + serializer().serializePlayMode( transport(), + stadium().time(), stadium().stoppageTime(), + stadium().playmode() ); + transport() << std::ends << std::flush; +} + + namespace initsender { template< typename Sender > @@ -303,6 +379,7 @@ RegHolder v1 = InitSenderMonitor::factory().autoReg( &create< InitSenderMonitorV RegHolder v2 = InitSenderMonitor::factory().autoReg( &create< InitSenderMonitorV2 >, 2 ); RegHolder v3 = InitSenderMonitor::factory().autoReg( &create< InitSenderMonitorV3 >, 3 ); RegHolder v4 = InitSenderMonitor::factory().autoReg( &create< InitSenderMonitorV3 >, 4 ); +RegHolder v5 = InitSenderMonitor::factory().autoReg( &create< InitSenderMonitorJSON >, 5 ); } } diff --git a/src/initsendermonitor.h b/src/initsendermonitor.h index c62a3575..7d1af4b8 100644 --- a/src/initsendermonitor.h +++ b/src/initsendermonitor.h @@ -25,7 +25,7 @@ #include "initsender.h" -#include +#include #include @@ -78,7 +78,7 @@ class InitSenderMonitor FactoryHolder & factory(); virtual - ~InitSenderMonitor(); + ~InitSenderMonitor() override; protected: @@ -105,8 +105,8 @@ class InitSenderMonitor public: - void sendReconnect() - { } + // void sendReconnect() + // { } virtual void sendPlayMode() = 0; @@ -188,25 +188,25 @@ class InitSenderMonitorV1 ~InitSenderMonitorV1(); virtual - void sendInit(); + void sendInit() override; virtual - void sendServerParams(); + void sendServerParams() override; virtual - void sendPlayerParams(); + void sendPlayerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerTypes() override; virtual - void sendChangedPlayers(); + void sendChangedPlayers() override; virtual - void sendScore(); + void sendScore() override; virtual - void sendPlayMode(); + void sendPlayMode() override; }; @@ -225,16 +225,16 @@ class InitSenderMonitorV2 public: virtual - ~InitSenderMonitorV2(); + ~InitSenderMonitorV2() override; virtual - void sendServerParams(); + void sendServerParams() override; virtual - void sendPlayerParams(); + void sendPlayerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerTypes() override; }; @@ -255,24 +255,67 @@ class InitSenderMonitorV3 public: virtual - ~InitSenderMonitorV3(); + ~InitSenderMonitorV3() override; virtual - void sendServerParams(); + void sendServerParams() override; virtual - void sendPlayerParams(); + void sendPlayerParams() override; virtual - void sendPlayerTypes(); + void sendPlayerTypes() override; virtual - void sendScore(); + void sendScore() override; virtual - void sendPlayMode(); + void sendPlayMode() override; }; + +/*! + \class InitSenderMonitorJSON + \brief version 5 of the init protocol (JSON format). + + The version of the common sender is "-1". + */ +class InitSenderMonitorJSON + : public InitSenderMonitor { +public: + InitSenderMonitorJSON( const Params & params ); + +protected: + InitSenderMonitorJSON( const Params & params, + const std::shared_ptr< InitSenderCommon > common ); + +public: + virtual + ~InitSenderMonitorJSON() override; + + virtual + void sendInit() override; + + virtual + void sendServerParams() override; + + virtual + void sendPlayerParams() override; + + virtual + void sendPlayerTypes() override; + + virtual + void sendChangedPlayers() override; + + virtual + void sendScore() override; + + virtual + void sendPlayMode() override; +}; + + } #endif diff --git a/src/initsenderonlinecoach.cpp b/src/initsenderonlinecoach.cpp index 092eb393..5cc0100a 100644 --- a/src/initsenderonlinecoach.cpp +++ b/src/initsenderonlinecoach.cpp @@ -69,14 +69,12 @@ InitSenderOnlineCoach::~InitSenderOnlineCoach() void InitSenderOnlineCoach::sendPlayerClangVer() { - for ( Stadium::PlayerCont::const_iterator i = stadium().remotePlayers().begin(); - i != stadium().remotePlayers().end(); - ++i ) + for ( Stadium::PlayerCont::const_reference p : stadium().remotePlayers() ) { - if ( (*i)->clangMinVer() != 0 - || (*i)->clangMaxVer() != 0 ) + if ( p->clangMinVer() != 0 + || p->clangMaxVer() != 0 ) { - sendPlayerClangVer( **i ); + sendPlayerClangVer( *p ); } } } @@ -204,23 +202,20 @@ InitSenderOnlineCoachV7::~InitSenderOnlineCoachV7() void InitSenderOnlineCoachV7::sendChangedPlayers() { - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) { - if ( (*p)->playerTypeId() == 0 ) continue; + if ( p->playerTypeId() == 0 ) continue; - if ( self().side() == (*p)->side() ) + if ( self().side() == p->side() ) { serializer().serializeChangedPlayer( transport(), - (*p)->unum(), - (*p)->playerTypeId() ); + p->unum(), + p->playerTypeId() ); } else { serializer().serializeChangedPlayer( transport(), - (*p)->unum() ); + p->unum() ); } transport() << std::ends << std::flush; } @@ -305,6 +300,7 @@ RegHolder voc13 = InitSenderOnlineCoach::factory().autoReg( &create< InitSenderO RegHolder voc14 = InitSenderOnlineCoach::factory().autoReg( &create< InitSenderOnlineCoachV8 >, 14 ); RegHolder voc15 = InitSenderOnlineCoach::factory().autoReg( &create< InitSenderOnlineCoachV8 >, 15 ); RegHolder voc16 = InitSenderOnlineCoach::factory().autoReg( &create< InitSenderOnlineCoachV8 >, 16 ); +RegHolder voc17 = InitSenderOnlineCoach::factory().autoReg( &create< InitSenderOnlineCoachV8 >, 17 ); } } diff --git a/src/initsenderonlinecoach.h b/src/initsenderonlinecoach.h index c58b88c3..c525ce47 100644 --- a/src/initsenderonlinecoach.h +++ b/src/initsenderonlinecoach.h @@ -25,7 +25,7 @@ #include "initsender.h" -#include +#include #include @@ -77,7 +77,7 @@ class InitSenderOnlineCoach FactoryHolder & factory(); virtual - ~InitSenderOnlineCoach(); + ~InitSenderOnlineCoach() override; protected: InitSenderOnlineCoach( const Params & params, @@ -211,19 +211,19 @@ class InitSenderOnlineCoachV1 public: virtual - ~InitSenderOnlineCoachV1(); + ~InitSenderOnlineCoachV1() override; virtual - void sendInit(); + void sendInit() override; virtual - void sendScore(); + void sendScore() override; virtual - void sendChangedPlayers(); + void sendChangedPlayers() override; virtual - void sendPlayerClangVer( const Player & ) + void sendPlayerClangVer( const Player & ) override { } }; @@ -249,10 +249,10 @@ class InitSenderOnlineCoachV6 public: virtual - ~InitSenderOnlineCoachV6(); + ~InitSenderOnlineCoachV6() override; virtual - void sendInit(); + void sendInit() override; }; @@ -277,10 +277,10 @@ class InitSenderOnlineCoachV7 public: virtual - ~InitSenderOnlineCoachV7(); + ~InitSenderOnlineCoachV7() override; virtual - void sendChangedPlayers(); + void sendChangedPlayers() override; }; /*! @@ -304,10 +304,10 @@ class InitSenderOnlineCoachV8 public: virtual - ~InitSenderOnlineCoachV8(); + ~InitSenderOnlineCoachV8() override; virtual - void sendPlayerClangVer( const Player & player ); + void sendPlayerClangVer( const Player & player ) override; }; diff --git a/src/initsenderplayer.cpp b/src/initsenderplayer.cpp index 35617a87..d26a1d48 100644 --- a/src/initsenderplayer.cpp +++ b/src/initsenderplayer.cpp @@ -193,23 +193,20 @@ InitSenderPlayerV7::~InitSenderPlayerV7() void InitSenderPlayerV7::sendChangedPlayers() { - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) { - if ( (*p)->playerTypeId() == 0 ) continue; + if ( p->playerTypeId() == 0 ) continue; - if ( self().team() == (*p)->team() ) + if ( self().team() == p->team() ) { serializer().serializeChangePlayer( transport(), - (*p)->unum(), - (*p)->playerTypeId() ); + p->unum(), + p->playerTypeId() ); } else { serializer().serializeChangePlayer( transport(), - (*p)->unum() ); + p->unum() ); } transport() << std::ends << std::flush; } @@ -284,6 +281,7 @@ RegHolder vp13 = InitSenderPlayer::factory().autoReg( &create< InitSenderPlayerV RegHolder vp14 = InitSenderPlayer::factory().autoReg( &create< InitSenderPlayerV8 >, 14 ); RegHolder vp15 = InitSenderPlayer::factory().autoReg( &create< InitSenderPlayerV8 >, 15 ); RegHolder vp16 = InitSenderPlayer::factory().autoReg( &create< InitSenderPlayerV8 >, 16 ); +RegHolder vp17 = InitSenderPlayer::factory().autoReg( &create< InitSenderPlayerV8 >, 17 ); } } diff --git a/src/initsenderplayer.h b/src/initsenderplayer.h index e259e894..3db31524 100644 --- a/src/initsenderplayer.h +++ b/src/initsenderplayer.h @@ -25,7 +25,7 @@ #include "initsender.h" -#include +#include #include @@ -75,7 +75,7 @@ class InitSenderPlayer FactoryHolder & factory(); virtual - ~InitSenderPlayer(); + ~InitSenderPlayer() override; protected: InitSenderPlayer( const Params & params, @@ -202,19 +202,19 @@ class InitSenderPlayerV1 public: virtual - ~InitSenderPlayerV1(); + ~InitSenderPlayerV1() override; virtual - void sendInit(); + void sendInit() override; virtual - void sendReconnect(); + void sendReconnect() override; virtual - void sendScore(); + void sendScore() override; virtual - void sendChangedPlayers(); + void sendChangedPlayers() override; }; /*! @@ -238,10 +238,10 @@ class InitSenderPlayerV7 public: virtual - ~InitSenderPlayerV7(); + ~InitSenderPlayerV7() override; virtual - void sendChangedPlayers(); + void sendChangedPlayers() override; }; /*! @@ -265,7 +265,7 @@ class InitSenderPlayerV8 public: virtual - ~InitSenderPlayerV8(); + ~InitSenderPlayerV8() override; }; } diff --git a/src/logger.cpp b/src/logger.cpp index d45c8d51..24d7d049 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -26,7 +26,6 @@ #include "logger.h" #include "player.h" -#include "clangmsg.h" #include "coach.h" #include "stadium.h" #include "heteroplayer.h" @@ -42,90 +41,124 @@ #include "serializercommonstdv8.h" -#include #include #include +#include +#include + #include -#ifdef HAVE_SYS_TIME_H -#include -#endif -// #ifdef HAVE_NETINET_IN_H -// #include -// #endif -// #ifdef HAVE_WINSOCK2_H -// #include -// #endif +namespace { +const std::string DEF_TEXT_NAME = "incomplete"; +const std::string DEF_TEXT_SUFFIX = ".rcl"; +const std::string DEF_GAME_NAME = "incomplete"; +const std::string DEF_GAME_SUFFIX = ".rcg"; +const std::string DEF_KAWAY_NAME = "incomplete"; +const std::string DEF_KAWAY_SUFFIX = ".kwy"; +} +struct Logger::Impl { -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION > 2 + std::unique_ptr< rcss::InitObserverLogger > init_observer_; + std::unique_ptr< rcss::ObserverLogger > observer_; -#define BOOST_FS_ABSOLUTE absolute -#define BOOST_FS_FILE_STRING string -#define BOOST_FS_DIRECTORY_STRING string -#define BOOST_FS_PARENT_PATH parent_path + std::string game_log_filepath_; + std::string text_log_filepath_; + std::string kaway_log_filepath_; -#else + std::ostream * game_log_; + std::ostream * text_log_; + std::ofstream kaway_log_; //!< file for keepaway log -#define BOOST_FS_ABSOLUTE complete -# ifdef BOOST_FILESYSTEM_NO_DEPRECATED -# define BOOST_FS_FILE_STRING file_string -# define BOOST_FS_DIRECTORY_STRING directory_string -# define BOOST_FS_PARENT_PATH parent_path -# else -# define BOOST_FS_FILE_STRING native_file_string -# define BOOST_FS_DIRECTORY_STRING native_directory_string -# define BOOST_FS_PARENT_PATH branch_path -# endif + Impl() + : init_observer_( new rcss::InitObserverLogger ), + observer_( new rcss::ObserverLogger ), + game_log_( nullptr ), + text_log_( nullptr ) + { -#endif + } -const std::string Logger::DEF_TEXT_NAME = "incomplete"; -const std::string Logger::DEF_TEXT_SUFFIX = ".rcl"; -const std::string Logger::DEF_GAME_NAME = "incomplete"; -const std::string Logger::DEF_GAME_SUFFIX = ".rcg"; -const std::string Logger::DEF_KAWAY_NAME = "incomplete"; -const std::string Logger::DEF_KAWAY_SUFFIX = ".kwy"; - - -Logger::Logger( Stadium & stadium ) - : M_init_observer( new rcss::InitObserverLogger ) - , M_observer( new rcss::ObserverLogger ) - , M_stadium( stadium ) - , M_game_log( static_cast< std::ostream * >( 0 ) ) - , M_text_log( static_cast< std::ostream * >( 0 ) ) - , M_playmode( PM_Null ) - , M_team_l_score( 0 ) - , M_team_r_score( 0 ) - , M_team_l_pen_taken( 0 ) - , M_team_r_pen_taken( 0 ) -{ + void flush() + { + if ( game_log_ ) game_log_->flush(); + if ( text_log_ ) text_log_->flush(); + kaway_log_.flush(); + } -} + void closeGameLog() + { + if ( game_log_ ) + { + init_observer_->sendTail(); -Logger::~Logger() -{ - this->close(); + game_log_->flush(); + delete game_log_; + game_log_ = nullptr; + } + } + + void closeTextLog() + { + if ( text_log_ ) + { + text_log_->flush(); + delete text_log_; + text_log_ = nullptr; + } + } + + void closeKeepawayLog() + { + if ( kaway_log_.is_open() ) + { + kaway_log_.flush(); + kaway_log_.close(); + } + } + + bool isGameLogOpen() const + { + return ( game_log_ + && game_log_->good() ); + } - if ( M_init_observer ) + bool isTextLogOpen() const { - delete M_init_observer; - M_init_observer = static_cast< rcss::InitObserverLogger * >( 0 ); + return ( text_log_ + && text_log_->good() ); } - if ( M_observer ) + bool isKeepawayLogOpen() const { - delete M_observer; - M_observer = static_cast< rcss::ObserverLogger * >( 0 ); + return kaway_log_.is_open(); } +}; + +Logger & +Logger::instance() +{ + static Logger s_instance; + return s_instance; +} + +Logger::Logger() + : M_impl( new Impl() ) +{ + +} + +Logger::~Logger() +{ + } bool -Logger::setSenders() +Logger::setSenders( const Stadium & stadium ) { - if ( ! isGameLogOpen() ) + if ( ! M_impl->isGameLogOpen() ) { return true; } @@ -155,43 +188,43 @@ Logger::setSenders() // init sender // { - rcss::InitSenderLogger::Params init_params( *M_game_log, + rcss::InitSenderLogger::Params init_params( *M_impl->game_log_, *this, ser, - M_stadium ); + stadium ); rcss::InitSenderLogger::Creator init_cre; if ( ! rcss::InitSenderLogger::factory().getCreator( init_cre, log_version ) ) { std::cerr << "No InitSenderLogger::Creator v" << log_version << std::endl; return false; } - M_init_observer->setInitSender( init_cre( init_params ) ); + M_impl->init_observer_->setInitSender( init_cre( init_params ) ); } // disp sender { - rcss::DispSenderLogger::Params disp_params( *M_game_log, + rcss::DispSenderLogger::Params disp_params( *M_impl->game_log_, *this, ser, - M_stadium ); + stadium ); rcss::DispSenderLogger::Creator disp_cre; if ( ! rcss::DispSenderLogger::factory().getCreator( disp_cre, log_version ) ) { std::cerr << "No DispSenderLogger::Creator v" << log_version << std::endl; return false; } - M_observer->setDispSender( disp_cre( disp_params ) ); + M_impl->observer_->setDispSender( disp_cre( disp_params ) ); } return true; } bool -Logger::open() +Logger::open( const Stadium & stadium ) { if ( ServerParam::instance().gameLogging() ) { - if ( ! openGameLog() ) + if ( ! openGameLog( stadium ) ) { return false; } @@ -218,9 +251,9 @@ Logger::open() } void -Logger::close() +Logger::close( const Stadium & stadium ) { - renameLogs(); + renameLogs( stadium ); closeGameLog(); closeTextLog(); @@ -228,37 +261,30 @@ Logger::close() } bool -Logger::openGameLog() +Logger::openGameLog( const Stadium & stadium ) { // create the log directory & file path string try { - boost::filesystem::path game_log( ServerParam::instance().gameLogDir() -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + boost::filesystem::path game_log( ServerParam::instance().gameLogDir() ); if ( ! boost::filesystem::exists( game_log ) && ! boost::filesystem::create_directories( game_log ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't create game log directory '" - << game_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl; + << ": can't create game log directory " << game_log << std::endl; return false; } if ( ServerParam::instance().gameLogFixed() ) { - game_log /= ServerParam::instance().gameLogFixedName() + Logger::DEF_GAME_SUFFIX; + game_log /= ServerParam::instance().gameLogFixedName() + DEF_GAME_SUFFIX; } else { - game_log /= Logger::DEF_GAME_NAME + Logger::DEF_GAME_SUFFIX; + game_log /= DEF_GAME_NAME + DEF_GAME_SUFFIX; } - M_game_log_name = game_log.BOOST_FS_FILE_STRING(); + M_impl->game_log_filepath_ = game_log.string(); } catch ( std::exception & e ) { @@ -281,43 +307,43 @@ Logger::openGameLog() #ifdef HAVE_LIBZ if ( ServerParam::instance().gameLogCompression() > 0 ) { - M_game_log_name += ".gz"; + M_impl->game_log_filepath_ += ".gz"; rcss::gz::gzofstream * f - = new rcss::gz::gzofstream( M_game_log_name.c_str(), + = new rcss::gz::gzofstream( M_impl->game_log_filepath_.c_str(), ServerParam::instance().gameLogCompression() ); - M_game_log = f; + M_impl->game_log_ = f; } else #endif { std::ofstream * f - = new std::ofstream( M_game_log_name.c_str(), + = new std::ofstream( M_impl->game_log_filepath_.c_str(), ( std::ofstream::binary | std::ofstream::out | std::ofstream::trunc ) ); - M_game_log = f; + M_impl->game_log_ = f; } - if ( ! isGameLogOpen() ) + if ( ! M_impl->isGameLogOpen() ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't open the game log file " << M_game_log_name << std::endl; + << ": can't open the game log file " << M_impl->game_log_filepath_ << std::endl; return false; } // write header and configration parameters - if ( ! setSenders() ) + if ( ! setSenders( stadium ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't set senders " << M_game_log_name << std::endl; + << ": can't set senders " << M_impl->game_log_filepath_ << std::endl; return false; } - M_init_observer->sendHeader(); - M_init_observer->sendServerParams(); - M_init_observer->sendPlayerParams(); - M_init_observer->sendPlayerTypes(); - M_game_log->flush(); + M_impl->init_observer_->sendHeader(); + M_impl->init_observer_->sendServerParams(); + M_impl->init_observer_->sendPlayerParams(); + M_impl->init_observer_->sendPlayerTypes(); + M_impl->game_log_->flush(); return true; } @@ -328,32 +354,25 @@ Logger::openTextLog() // create the log directory & file path string try { - boost::filesystem::path text_log( ServerParam::instance().textLogDir() -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + boost::filesystem::path text_log( ServerParam::instance().textLogDir() ); if ( ! boost::filesystem::exists( text_log ) && ! boost::filesystem::create_directories( text_log ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't create text log directory '" - << text_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl; + << ": can't create text log directory " << text_log << std::endl; return false; } if ( ServerParam::instance().textLogFixed() ) { - text_log /= ServerParam::instance().textLogFixedName() + Logger::DEF_TEXT_SUFFIX; + text_log /= ServerParam::instance().textLogFixedName() + DEF_TEXT_SUFFIX; } else { - text_log /= Logger::DEF_TEXT_NAME + Logger::DEF_TEXT_SUFFIX; + text_log /= DEF_TEXT_NAME + DEF_TEXT_SUFFIX; } - M_text_log_name = text_log.BOOST_FS_FILE_STRING(); + M_impl->text_log_filepath_ = text_log.string(); } catch ( std::exception & e ) { @@ -376,23 +395,23 @@ Logger::openTextLog() #ifdef HAVE_LIBZ if ( ServerParam::instance().textLogCompression() > 0 ) { - M_text_log_name += std::string ( ".gz" ); + M_impl->text_log_filepath_ += std::string ( ".gz" ); rcss::gz::gzofstream * f - = new rcss::gz::gzofstream( M_text_log_name.c_str(), + = new rcss::gz::gzofstream( M_impl->text_log_filepath_.c_str(), ServerParam::instance().textLogCompression() ); - M_text_log = f; + M_impl->text_log_ = f; } else #endif { - std::ofstream * f = new std::ofstream( M_text_log_name.c_str() ); - M_text_log = f; + std::ofstream * f = new std::ofstream( M_impl->text_log_filepath_.c_str() ); + M_impl->text_log_ = f; } - if ( ! isTextLogOpen() ) + if ( ! M_impl->isTextLogOpen() ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't open the text log file '" << M_text_log_name + << ": can't open the text log file '" << M_impl->text_log_filepath_ << "'" << std::endl; return false; } @@ -407,32 +426,25 @@ Logger::openKawayLog() // create the log directory & file path string try { - boost::filesystem::path kaway_log( ServerParam::instance().kawayLogDir() -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + boost::filesystem::path kaway_log( ServerParam::instance().kawayLogDir() ); if ( ! boost::filesystem::exists( kaway_log ) && ! boost::filesystem::create_directories( kaway_log ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't create keepaway log directory '" - << kaway_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl; + << ": can't create keepaway log directory " << kaway_log << std::endl; return false; } if ( ServerParam::instance().kawayLogFixed() ) { - kaway_log /= ServerParam::instance().kawayLogFixedName() + Logger::DEF_KAWAY_SUFFIX; + kaway_log /= ServerParam::instance().kawayLogFixedName() + DEF_KAWAY_SUFFIX; } else { - kaway_log /= Logger::DEF_KAWAY_NAME + Logger::DEF_KAWAY_SUFFIX; + kaway_log /= DEF_KAWAY_NAME + DEF_KAWAY_SUFFIX; } - M_kaway_log_name = kaway_log.BOOST_FS_FILE_STRING(); + M_impl->kaway_log_filepath_ = kaway_log.string(); } catch ( std::exception & e ) { @@ -445,12 +457,12 @@ Logger::openKawayLog() } // open the output file stream - M_kaway_log.open( M_kaway_log_name.c_str() ); + M_impl->kaway_log_.open( M_impl->kaway_log_filepath_.c_str() ); - if ( ! M_kaway_log.is_open() ) + if ( ! M_impl->kaway_log_.is_open() ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": can't open keepaway_log_file " << M_kaway_log_name + << ": can't open keepaway_log_file " << M_impl->kaway_log_filepath_ << std::endl; return false; } @@ -462,72 +474,66 @@ Logger::openKawayLog() void Logger::closeGameLog() { - if ( M_game_log ) - { - M_game_log->flush(); - delete M_game_log; - M_game_log = static_cast< std::ostream * >( 0 ); - } + M_impl->closeGameLog(); } void Logger::closeTextLog() { - if ( M_text_log ) - { - M_text_log->flush(); - delete M_text_log; - M_text_log = static_cast< std::ostream * >( 0 ); - } + M_impl->closeTextLog(); } void Logger::closeKawayLog() { - if ( M_kaway_log.is_open() ) - { - M_kaway_log.flush(); - M_kaway_log.close(); - } + M_impl->closeKeepawayLog(); } void -Logger::renameLogs() +Logger::flush() { - if ( ! isGameLogOpen() - && ! isTextLogOpen() - && ! M_kaway_log.is_open() ) + M_impl->flush(); +} + +void +Logger::renameLogs( const Stadium & stadium ) +{ + if ( ! M_impl->isGameLogOpen() + && ! M_impl->isTextLogOpen() + && ! M_impl->isKeepawayLogOpen() ) { return; } // add penalty to logfile when penalties are score or was draw and one team won - bool bAddPenaltyScore = ( M_stadium.teamRight().point() == M_stadium.teamLeft().point() - && M_stadium.teamLeft().penaltyTaken() > 0 - && M_stadium.teamRight().penaltyTaken() > 0 ); + bool bAddPenaltyScore = ( stadium.teamRight().point() == stadium.teamLeft().point() + && stadium.teamLeft().penaltyTaken() > 0 + && stadium.teamRight().penaltyTaken() > 0 ); char time_str[32]; + const std::time_t time = stadium.getStartTime(); + const std::tm * lt = std::localtime( &time ); std::strftime( time_str, 32, ServerParam::instance().logDateFormat().c_str(), - &( M_stadium.realTime() ) ); + lt ); std::string team_name_score( "" ); - if ( M_stadium.teamLeft().enabled() ) + if ( stadium.teamLeft().enabled() ) { - team_name_score += M_stadium.teamLeft().name(); + team_name_score += stadium.teamLeft().name(); team_name_score += "_"; - if ( ! M_stadium.teamLeft().olcoach()->name().empty() ) + if ( ! stadium.teamLeft().olcoach()->name().empty() ) { - team_name_score += M_stadium.teamLeft().olcoach()->name(); + team_name_score += stadium.teamLeft().olcoach()->name(); team_name_score += "_"; } - team_name_score += boost::lexical_cast< std::string >( M_stadium.teamLeft().point() ); + team_name_score += std::to_string( stadium.teamLeft().point() ); if ( bAddPenaltyScore ) { team_name_score += "_"; - team_name_score += boost::lexical_cast< std::string >( M_stadium.teamLeft().penaltyPoint() ); - team_name_score += ( M_stadium.teamLeft().penaltyWon() ? "w" : "" ); + team_name_score += std::to_string( stadium.teamLeft().penaltyPoint() ); + team_name_score += ( stadium.teamLeft().penaltyWon() ? "w" : "" ); } } else @@ -536,21 +542,21 @@ Logger::renameLogs() } team_name_score += "-vs-"; - if ( M_stadium.teamRight().enabled() ) + if ( stadium.teamRight().enabled() ) { - team_name_score += M_stadium.teamRight().name(); + team_name_score += stadium.teamRight().name(); team_name_score += "_"; - if ( ! M_stadium.teamRight().olcoach()->name().empty() ) + if ( ! stadium.teamRight().olcoach()->name().empty() ) { - team_name_score += M_stadium.teamRight().olcoach()->name(); + team_name_score += stadium.teamRight().olcoach()->name(); team_name_score += "_"; } - team_name_score += boost::lexical_cast< std::string >( M_stadium.teamRight().point() ); + team_name_score += std::to_string( stadium.teamRight().point() ); if ( bAddPenaltyScore ) { team_name_score += "_"; - team_name_score += boost::lexical_cast< std::string >( M_stadium.teamRight().penaltyPoint() ); - team_name_score += ( M_stadium.teamRight().penaltyWon() ? "w" : "" ); + team_name_score += std::to_string( stadium.teamRight().penaltyPoint() ); + team_name_score += ( stadium.teamRight().penaltyWon() ? "w" : "" ); } } else @@ -559,14 +565,16 @@ Logger::renameLogs() } // - // write result + // write the result to the game log // - if ( isGameLogOpen() ) + if ( M_impl->isGameLogOpen() ) { char time_stamp[32]; + const std::time_t time = stadium.getStartTime(); + const struct tm * lt = std::localtime( &time ); std::strftime( time_stamp, 32, "%Y%m%d%H%M", - &( M_stadium.realTime() ) ); + lt ); char msg[256]; snprintf( msg, 256, "(result %s %s)", time_stamp, team_name_score.c_str() ); writeMsgToGameLog( MSG_BOARD, msg, true ); @@ -575,7 +583,7 @@ Logger::renameLogs() // // rename text log // - if ( isTextLogOpen() + if ( M_impl->isTextLogOpen() && ! ServerParam::instance().textLogFixed() ) { std::string newname = ServerParam::instance().textLogDir(); @@ -588,7 +596,7 @@ Logger::renameLogs() newname += time_str; } newname += team_name_score; - newname += Logger::DEF_TEXT_SUFFIX; + newname += DEF_TEXT_SUFFIX; if ( ServerParam::instance().textLogCompression() > 0 ) { newname += ".gz"; @@ -596,19 +604,19 @@ Logger::renameLogs() closeTextLog(); - if ( std::rename( M_text_log_name.c_str(), + if ( std::rename( M_impl->text_log_filepath_.c_str(), newname.c_str() ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": error renaming " << M_text_log_name << std::endl; + << ": error renaming " << M_impl->text_log_filepath_ << std::endl; } - M_text_log_name = newname; + M_impl->text_log_filepath_ = newname; } // // rename game log // - if ( isGameLogOpen() + if ( M_impl->isGameLogOpen() && ! ServerParam::instance().gameLogFixed() ) { std::string newname = ServerParam::instance().gameLogDir(); @@ -621,7 +629,7 @@ Logger::renameLogs() newname += time_str; } newname += team_name_score; - newname += Logger::DEF_GAME_SUFFIX; + newname += DEF_GAME_SUFFIX; if ( ServerParam::instance().gameLogCompression() > 0 ) { newname += ".gz"; @@ -629,19 +637,19 @@ Logger::renameLogs() closeGameLog(); - if ( std::rename( M_game_log_name.c_str(), + if ( std::rename( M_impl->game_log_filepath_.c_str(), newname.c_str() ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": error renaming " << M_game_log_name << std::endl; + << ": error renaming " << M_impl->game_log_filepath_ << std::endl; } - M_game_log_name = newname; + M_impl->game_log_filepath_ = newname; } // // rename keepaway log // - if ( M_kaway_log.is_open() + if ( M_impl->kaway_log_.is_open() && ! ServerParam::instance().kawayLogFixed() ) { std::string newname = ServerParam::instance().kawayLogDir(); @@ -654,36 +662,36 @@ Logger::renameLogs() newname += time_str; } newname += team_name_score; - newname += Logger::DEF_KAWAY_SUFFIX; + newname += DEF_KAWAY_SUFFIX; closeKawayLog(); - if( std::rename( M_kaway_log_name.c_str(), + if( std::rename( M_impl->kaway_log_filepath_.c_str(), newname.c_str() ) ) { std::cerr << __FILE__ << ": " << __LINE__ - << ": error renaming " << M_kaway_log_name << std::endl; + << ": error renaming " << M_impl->kaway_log_filepath_ << std::endl; } } } -void -Logger::writeToGameLog( const char * str, - const std::streamsize n ) -{ - if ( M_game_log ) - { - M_game_log->write( str, n ); - } -} +// void +// Logger::writeToGameLog( const char * str, +// const std::streamsize n ) +// { +// if ( M_impl->game_log_ ) +// { +// M_impl->game_log_->write( str, n ); +// } +// } void Logger::writeMsgToGameLog( const BoardType board_type, const char * msg, const bool force ) { - if ( ! isGameLogOpen() ) + if ( ! M_impl->isGameLogOpen() ) { return; } @@ -692,7 +700,7 @@ Logger::writeMsgToGameLog( const BoardType board_type, || ServerParam::instance().recordMessages() || ServerParam::instance().gameLogVersion() == REC_OLD_VERSION ) { - M_observer->sendMsg( board_type, msg ); + M_impl->observer_->sendMsg( board_type, msg ); } // if ( ServerParam::instance().gameLogVersion() >= REC_VERSION_4 ) @@ -703,7 +711,7 @@ Logger::writeMsgToGameLog( const BoardType board_type, // std::string str( msg ); // std::replace( str.begin(), str.end(), '\n', ' ' ); -// *M_game_log << "(msg " << M_stadium.time() +// *M_game_log << "(msg " << stadium.time() // << ' ' << board_type << " \"" << str << "\")\n"; // } // } @@ -749,21 +757,21 @@ Logger::writeMsgToGameLog( const BoardType board_type, } void -Logger::writeGameLog() +Logger::writeGameLog( const Stadium & stadium ) { /* TH - 2-NOV-2000 */ static bool wrote_final_cycle = false; - if ( ! isGameLogOpen() ) + if ( ! M_impl->isGameLogOpen() ) { return; } - if ( M_stadium.playmode() != PM_BeforeKickOff - && M_stadium.playmode() != PM_TimeOver ) + if ( stadium.playmode() != PM_BeforeKickOff + && stadium.playmode() != PM_TimeOver ) { - writeGameLogImpl(); + writeGameLogImpl( stadium ); // switch ( ServerParam::instance().gameLogVersion() ) { // case REC_VERSION_4: // writeGameLogV4(); @@ -781,10 +789,10 @@ Logger::writeGameLog() // break; // } } - else if ( M_stadium.playmode() == PM_TimeOver + else if ( stadium.playmode() == PM_TimeOver && ! wrote_final_cycle ) { - writeGameLogImpl(); + writeGameLogImpl( stadium ); // switch ( ServerParam::instance().gameLogVersion() ) { // case REC_VERSION_4: // writeGameLogV4(); @@ -806,7 +814,7 @@ Logger::writeGameLog() } void -Logger::writeGameLogImpl() +Logger::writeGameLogImpl( const Stadium & stadium ) { static PlayMode pm = PM_Null; static std::string team_l_name, team_r_name; @@ -814,33 +822,33 @@ Logger::writeGameLogImpl() static int team_l_pen_taken = 0, team_r_pen_taken = 0; // if playmode has changed wirte playmode - if ( pm != M_stadium.playmode() ) + if ( pm != stadium.playmode() ) { - pm = M_stadium.playmode(); - M_init_observer->sendPlayMode(); + pm = stadium.playmode(); + M_impl->init_observer_->sendPlayMode(); } // if teams or score has changed, write teams and score - if ( team_l_score != M_stadium.teamLeft().point() - || team_r_score != M_stadium.teamRight().point() - || team_l_pen_taken != M_stadium.teamLeft().penaltyTaken() - || team_r_pen_taken != M_stadium.teamRight().penaltyTaken() - || M_stadium.teamLeft().name() != team_l_name - || M_stadium.teamRight().name() != team_r_name + if ( team_l_score != stadium.teamLeft().point() + || team_r_score != stadium.teamRight().point() + || team_l_pen_taken != stadium.teamLeft().penaltyTaken() + || team_r_pen_taken != stadium.teamRight().penaltyTaken() + || stadium.teamLeft().name() != team_l_name + || stadium.teamRight().name() != team_r_name ) { - team_l_name = M_stadium.teamLeft().name(); - team_r_name = M_stadium.teamRight().name(); - team_l_score = M_stadium.teamLeft().point(); - team_r_score = M_stadium.teamRight().point(); - team_l_pen_taken = M_stadium.teamLeft().penaltyTaken(); - team_r_pen_taken = M_stadium.teamRight().penaltyTaken(); + team_l_name = stadium.teamLeft().name(); + team_r_name = stadium.teamRight().name(); + team_l_score = stadium.teamLeft().point(); + team_r_score = stadium.teamRight().point(); + team_l_pen_taken = stadium.teamLeft().penaltyTaken(); + team_r_pen_taken = stadium.teamRight().penaltyTaken(); - M_init_observer->sendTeam(); + M_impl->init_observer_->sendTeam(); } - M_observer->sendShow(); + M_impl->observer_->sendShow(); } #if 0 @@ -852,14 +860,14 @@ Logger::writeGameLogV1() disp.mode = htons( SHOW_MODE ); - disp.body.show.time = htons( M_stadium.time() ); + disp.body.show.time = htons( stadium.time() ); - disp.body.show.pmode = static_cast< char >( M_stadium.playmode() ); + disp.body.show.pmode = static_cast< char >( stadium.playmode() ); - disp.body.show.pos[0].x = htons( (Int16)rint( ( M_stadium.ball().pos().x * SHOWINFO_SCALE ) ) ); - disp.body.show.pos[0].y = htons( (Int16)rint( ( M_stadium.ball().pos().y * SHOWINFO_SCALE ) ) ); + disp.body.show.pos[0].x = htons( (Int16)rint( ( stadium.ball().pos().x * SHOWINFO_SCALE ) ) ); + disp.body.show.pos[0].y = htons( (Int16)rint( ( stadium.ball().pos().y * SHOWINFO_SCALE ) ) ); - const Stadium::PlayerCont & players = M_stadium.players(); + const Stadium::PlayerCont & players = stadium.players(); for ( int i = 0; i < MAX_PLAYER * 2; ++i ) { disp.body.show.pos[i+1].enable = htons( players[i]->state() ); @@ -870,12 +878,12 @@ Logger::writeGameLogV1() disp.body.show.pos[i+1].unum = htons( players[i]->unum() ); } - if ( ! M_stadium.teamLeft().name().empty() ) + if ( ! stadium.teamLeft().name().empty() ) { std::strncpy( disp.body.show.team[0].name, - M_stadium.teamLeft().name().c_str(), - std::min( M_stadium.teamLeft().name().length() + 1, size_t( 16 ) ) ); - disp.body.show.team[0].score = htons( M_stadium.teamLeft().point() ); + stadium.teamLeft().name().c_str(), + std::min( stadium.teamLeft().name().length() + 1, size_t( 16 ) ) ); + disp.body.show.team[0].score = htons( stadium.teamLeft().point() ); } else { @@ -884,12 +892,12 @@ Logger::writeGameLogV1() sizeof( disp.body.show.team[0].name ) ); } - if ( ! M_stadium.teamRight().name().empty() ) + if ( ! stadium.teamRight().name().empty() ) { std::strncpy( disp.body.show.team[1].name, - M_stadium.teamRight().name().c_str(), - std::min( M_stadium.teamRight().name().length() + 1, size_t( 16 ) ) ); - disp.body.show.team[1].score = htons( M_stadium.teamRight().point() ); + stadium.teamRight().name().c_str(), + std::min( stadium.teamRight().name().length() + 1, size_t( 16 ) ) ); + disp.body.show.team[1].score = htons( stadium.teamRight().point() ); } else { @@ -910,14 +918,14 @@ Logger::writeGameLogV2() showinfo_t show; - show.time = htons( M_stadium.time() ); + show.time = htons( stadium.time() ); - show.pmode = static_cast< char >( M_stadium.playmode() ); + show.pmode = static_cast< char >( stadium.playmode() ); - show.pos[0].x = htons( (Int16)rint( ( M_stadium.ball().pos().x * SHOWINFO_SCALE ) ) ); - show.pos[0].y = htons( (Int16)rint( ( M_stadium.ball().pos().y * SHOWINFO_SCALE ) ) ); + show.pos[0].x = htons( (Int16)rint( ( stadium.ball().pos().x * SHOWINFO_SCALE ) ) ); + show.pos[0].y = htons( (Int16)rint( ( stadium.ball().pos().y * SHOWINFO_SCALE ) ) ); - const Stadium::PlayerCont & players = M_stadium.players(); + const Stadium::PlayerCont & players = stadium.players(); for ( int i = 0; i < MAX_PLAYER * 2; ++i ) { show.pos[i+1].enable = htons( players[i]->state() ); @@ -928,12 +936,12 @@ Logger::writeGameLogV2() show.pos[i+1].unum = htons( players[i]->unum() ); } - if ( ! M_stadium.teamLeft().name().empty() ) + if ( ! stadium.teamLeft().name().empty() ) { std::strncpy( show.team[0].name, - M_stadium.teamLeft().name().c_str(), - std::min( M_stadium.teamLeft().name().length() + 1, size_t( 16 ) ) ); - show.team[0].score = htons( M_stadium.teamLeft().point() ); + stadium.teamLeft().name().c_str(), + std::min( stadium.teamLeft().name().length() + 1, size_t( 16 ) ) ); + show.team[0].score = htons( stadium.teamLeft().point() ); } else { @@ -943,12 +951,12 @@ Logger::writeGameLogV2() show.team[0].score = htons( 0 ); } - if ( ! M_stadium.teamRight().name().empty() ) + if ( ! stadium.teamRight().name().empty() ) { std::strncpy( show.team[1].name, - M_stadium.teamRight().name().c_str(), - std::min( M_stadium.teamRight().name().length() + 1, size_t( 16 ) ) ); - show.team[1].score = htons( M_stadium.teamRight().point() ); + stadium.teamRight().name().c_str(), + std::min( stadium.teamRight().name().length() + 1, size_t( 16 ) ) ); + show.team[1].score = htons( stadium.teamRight().point() ); } else { @@ -978,9 +986,9 @@ Logger::writeGameLogV3() Int16 mode; // if playmode has changed wirte playmode - if ( pmode != M_stadium.playmode() ) + if ( pmode != stadium.playmode() ) { - pmode = M_stadium.playmode(); + pmode = stadium.playmode(); char pm = static_cast< char >( pmode ); @@ -992,22 +1000,22 @@ Logger::writeGameLogV3() } // if teams or score has changed, write teams and score - if ( M_stadium.teamLeft().point() != score_l - || M_stadium.teamRight().point() != score_r - || M_stadium.teamLeft().name() != teams[ 0 ].name - || M_stadium.teamRight().name() != teams[ 1 ].name ) + if ( stadium.teamLeft().point() != score_l + || stadium.teamRight().point() != score_r + || stadium.teamLeft().name() != teams[ 0 ].name + || stadium.teamRight().name() != teams[ 1 ].name ) { - score_l = M_stadium.teamLeft().point(); - score_r = M_stadium.teamLeft().point(); + score_l = stadium.teamLeft().point(); + score_r = stadium.teamLeft().point(); std::strncpy( teams[ 0 ].name, - M_stadium.teamLeft().name().c_str(), - std::min( M_stadium.teamLeft().name().length() + 1, size_t( 16 ) ) ); + stadium.teamLeft().name().c_str(), + std::min( stadium.teamLeft().name().length() + 1, size_t( 16 ) ) ); teams[ 0 ].score = htons( score_l ); std::strncpy( teams[ 1 ].name, - M_stadium.teamRight().name().c_str(), - std::min( M_stadium.teamRight().name().length() + 1, size_t( 16 ) ) ); + stadium.teamRight().name().c_str(), + std::min( stadium.teamRight().name().length() + 1, size_t( 16 ) ) ); teams[ 1 ].score = htons( score_r ); mode = htons( TEAM_MODE ); @@ -1021,14 +1029,14 @@ Logger::writeGameLogV3() // write positional data short_showinfo_t2 show; - show.time = htons( M_stadium.time() ); + show.time = htons( stadium.time() ); - show.ball.x = htonl( (Int32)rint( ( M_stadium.ball().pos().x * SHOWINFO_SCALE2 ) ) ); - show.ball.y = htonl( (Int32)rint( ( M_stadium.ball().pos().y * SHOWINFO_SCALE2 ) ) ); - show.ball.deltax = htonl( (Int32)rint( ( M_stadium.ball().vel().x * SHOWINFO_SCALE2 ) ) ); - show.ball.deltay = htonl( (Int32)rint( ( M_stadium.ball().vel().y * SHOWINFO_SCALE2) ) ); + show.ball.x = htonl( (Int32)rint( ( stadium.ball().pos().x * SHOWINFO_SCALE2 ) ) ); + show.ball.y = htonl( (Int32)rint( ( stadium.ball().pos().y * SHOWINFO_SCALE2 ) ) ); + show.ball.deltax = htonl( (Int32)rint( ( stadium.ball().vel().x * SHOWINFO_SCALE2 ) ) ); + show.ball.deltay = htonl( (Int32)rint( ( stadium.ball().vel().y * SHOWINFO_SCALE2) ) ); - const Stadium::PlayerCont & players = M_stadium.players(); + const Stadium::PlayerCont & players = stadium.players(); for ( int i = 0; i < MAX_PLAYER * 2; ++i ) { show.pos[i].mode = htons( players[i]->state() ); @@ -1081,80 +1089,77 @@ Logger::writeGameLogV4() std::ostream & os = *M_game_log; // if playmode has changed wirte playmode - if ( pm != M_stadium.playmode() ) + if ( pm != stadium.playmode() ) { - pm = M_stadium.playmode(); + pm = stadium.playmode(); - os << "(playmode " << M_stadium.time() + os << "(playmode " << stadium.time() << ' ' << playmode_strings[pm] << ")\n"; } // if teams or score has changed, write teams and score - if ( team_l_score != M_stadium.teamLeft().point() - || team_r_score != M_stadium.teamRight().point() - || team_l_pen_taken != M_stadium.teamLeft().penaltyTaken() - || team_r_pen_taken != M_stadium.teamRight().penaltyTaken() - || M_stadium.teamLeft().name() != team_l_name - || M_stadium.teamRight().name() != team_r_name + if ( team_l_score != stadium.teamLeft().point() + || team_r_score != stadium.teamRight().point() + || team_l_pen_taken != stadium.teamLeft().penaltyTaken() + || team_r_pen_taken != stadium.teamRight().penaltyTaken() + || stadium.teamLeft().name() != team_l_name + || stadium.teamRight().name() != team_r_name ) { - team_l_name = M_stadium.teamLeft().name(); - team_r_name = M_stadium.teamRight().name(); - team_l_score = M_stadium.teamLeft().point(); - team_r_score = M_stadium.teamRight().point(); - team_l_pen_taken = M_stadium.teamLeft().penaltyTaken(); - team_r_pen_taken = M_stadium.teamRight().penaltyTaken(); + team_l_name = stadium.teamLeft().name(); + team_r_name = stadium.teamRight().name(); + team_l_score = stadium.teamLeft().point(); + team_r_score = stadium.teamRight().point(); + team_l_pen_taken = stadium.teamLeft().penaltyTaken(); + team_r_pen_taken = stadium.teamRight().penaltyTaken(); - os << "(team " << M_stadium.time() + os << "(team " << stadium.time() << ' ' << ( team_l_name.empty() ? "null" : team_l_name.c_str() ) << ' ' << ( team_r_name.empty() ? "null" : team_r_name.c_str() ) << ' ' << team_l_score << ' ' << team_r_score; if ( team_l_pen_taken > 0 || team_r_pen_taken > 0 ) { - os << ' ' << M_stadium.teamLeft().penaltyPoint() - << ' ' << team_l_pen_taken - M_stadium.teamLeft().penaltyPoint() - << ' ' << M_stadium.teamRight().penaltyPoint() - << ' ' << team_r_pen_taken - M_stadium.teamRight().penaltyPoint(); + os << ' ' << stadium.teamLeft().penaltyPoint() + << ' ' << team_l_pen_taken - stadium.teamLeft().penaltyPoint() + << ' ' << stadium.teamRight().penaltyPoint() + << ' ' << team_r_pen_taken - stadium.teamRight().penaltyPoint(); } os << ")\n"; } - os << "(show " << M_stadium.time(); + os << "(show " << stadium.time(); os << " (" << BALL_NAME_SHORT - << ' ' << Quantize( M_stadium.ball().pos().x, prec ) - << ' ' << Quantize( M_stadium.ball().pos().y, prec ) - << ' ' << Quantize( M_stadium.ball().vel().x, prec ) - << ' ' << Quantize( M_stadium.ball().vel().y, prec ) + << ' ' << Quantize( stadium.ball().pos().x, prec ) + << ' ' << Quantize( stadium.ball().pos().y, prec ) + << ' ' << Quantize( stadium.ball().vel().x, prec ) + << ' ' << Quantize( stadium.ball().vel().y, prec ) << ')'; - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium.players() ) { os << " ("; - os << "(" << SideStr( (*p)->side() ) - << ' ' << (*p)->unum() + os << "(" << SideStr( p->side() ) + << ' ' << p->unum() << ')'; - os << ' ' << (*p)->playerTypeId() + os << ' ' << p->playerTypeId() << ' ' << std::hex << std::showbase - << (*p)->state() // include goalie flag + << p->state() // include goalie flag << std::dec << std::noshowbase; - os << ' ' << Quantize( (*p)->pos().x, prec ) - << ' ' << Quantize( (*p)->pos().y, prec ) - << ' ' << Quantize( (*p)->vel().x, prec ) - << ' ' << Quantize( (*p)->vel().y, prec ) - << ' ' << Quantize( Rad2Deg( (*p)->angleBodyCommitted() ), dprec ) - << ' ' << Quantize( Rad2Deg( (*p)->angleNeckCommitted() ), dprec ); - if ( (*p)->arm().isPointing() ) + os << ' ' << Quantize( p->pos().x, prec ) + << ' ' << Quantize( p->pos().y, prec ) + << ' ' << Quantize( p->vel().x, prec ) + << ' ' << Quantize( p->vel().y, prec ) + << ' ' << Quantize( Rad2Deg( p->angleBodyCommitted() ), dprec ) + << ' ' << Quantize( Rad2Deg( p->angleNeckCommitted() ), dprec ); + if ( p->arm().isPointing() ) { - os << ' ' << Quantize( (*p)->arm().dest().getX(), prec ) - << ' ' << Quantize( (*p)->arm().dest().getY(), prec ); + os << ' ' << Quantize( p->arm().dest().getX(), prec ) + << ' ' << Quantize( p->arm().dest().getY(), prec ); // rcss::geom::Vector2D arm_dest; -// if ( (*p)->arm().getRelDest( rcss::geom::Vector2D( (*p)->pos().x, -// (*p)->pos().y ), +// if ( p->arm().getRelDest( rcss::geom::Vector2D( p->pos().x, +// p->pos().y ), // 0.0, // arm_dest ) ) // { @@ -1164,32 +1169,32 @@ Logger::writeGameLogV4() } os << " (v " - << ( (*p)->highquality() ? "h " : "l " ) - << Quantize( Rad2Deg( (*p)->visibleAngle() ), dprec ) + << ( p->highquality() ? "h " : "l " ) + << Quantize( Rad2Deg( p->visibleAngle() ), dprec ) << ')'; os << " (s " - << (*p)->stamina() << ' ' - << (*p)->effort() << ' ' - << (*p)->recovery() << ')'; - if ( (*p)->isEnabled() - && (*p)->getFocusTarget() != NULL ) + << p->stamina() << ' ' + << p->effort() << ' ' + << p->recovery() << ')'; + if ( p->isEnabled() + && p->getFocusTarget() ) { - os << " (f " << SideStr( (*p)->getFocusTarget()->side() ) - << ' ' << (*p)->getFocusTarget()->unum() + os << " (f " << SideStr( p->getFocusTarget()->side() ) + << ' ' << p->getFocusTarget()->unum() << ')'; } os << " (c " - << (*p)->kickCount() - << ' ' << (*p)->dashCount() - << ' ' << (*p)->turnCount() - << ' ' << (*p)->catchCount() - << ' ' << (*p)->moveCount() - << ' ' << (*p)->turnNeckCount() - << ' ' << (*p)->changeViewCount() - << ' ' << (*p)->sayCount() - << ' ' << (*p)->tackleCount() - << ' ' << (*p)->arm().getCounter() - << ' ' << (*p)->attentiontoCount() + << p->kickCount() + << ' ' << p->dashCount() + << ' ' << p->turnCount() + << ' ' << p->catchCount() + << ' ' << p->moveCount() + << ' ' << p->turnNeckCount() + << ' ' << p->changeViewCount() + << ' ' << p->sayCount() + << ' ' << p->tackleCount() + << ' ' << p->arm().getCounter() + << ' ' << p->attentiontoCount() << ')'; os << ')'; // end of player } @@ -1203,65 +1208,54 @@ Logger::writeTeamGraphic( const Side side, const unsigned int x, const unsigned int y ) { - if ( ! isGameLogOpen() ) + if ( ! M_impl->isGameLogOpen() ) { return; } - M_observer->sendTeamGraphic( side, x, y ); + M_impl->observer_->sendTeamGraphic( side, x, y ); // const XPMHolder * xpm = ( side == LEFT -// ? M_stadium.teamLeft().teamGraphic( x, y ) +// ? stadium.teamLeft().teamGraphic( x, y ) // : side == RIGHT -// ? M_stadium.teamRight().teamGraphic( x, y ) +// ? stadium.teamRight().teamGraphic( x, y ) // : static_cast< const XPMHolder * >( 0 ) ); // if ( ! xpm ) // { // return; // } -// #ifdef HAVE_SSTREAM // std::ostringstream data; -// #else -// std::ostrstream data; -// #endif // data << "(team_graphic_" // << ( side == LEFT ? "l" : "r" ) // << " (" << x << " " << y << " " // << *xpm << ")"; -// #ifndef HAVE_SSTREAM -// data << std::ends; -// #endif - // std::string msg = data.str(); -// #ifndef HAVE_SSTREAM -// data.freeze( false ); -// #endif - // writeMsgToGameLog( MSG_BOARD, msg.c_str(), true ); } void -Logger::writeTextLog( const char * message, +Logger::writeTextLog( const Stadium & stadium, + const char * message, const TextLogFlag flag ) { if ( flag == RECV || flag == LOG_TEXT ) { - if ( isTextLogOpen() ) + if ( M_impl->isTextLogOpen() ) { - *M_text_log << M_stadium.time() - << ',' << M_stadium.stoppageTime() - << "\t" << message << '\n'; + *M_impl->text_log_ << stadium.time() + << ',' << stadium.stoppageTime() + << "\t" << message << '\n'; } } if ( ( flag == RECV || flag == SUBS ) - && isGameLogOpen() + && M_impl->isGameLogOpen() && ServerParam::instance().recordMessages() - && M_stadium.playmode() != PM_TimeOver ) + && stadium.playmode() != PM_TimeOver ) { char buf[max_message_length_for_display]; std::strncpy( buf, message, std::min( max_message_length_for_display, @@ -1277,8 +1271,8 @@ Logger::writeTextLog( const char * message, // std::strncpy( buf, message, std::min( max_message_length_for_display, // (int)std::strlen( message ) ) ); -// for ( Stadium::MonitorCont::iterator i = M_stadium.monitors().begin(); -// i != M_stadium.monitors().end(); +// for ( Stadium::MonitorCont::iterator i = stadium.monitors().begin(); +// i != stadium.monitors().end(); // ++i ) // { // (*i)->sendMsg( LOG_BOARD, buf ); @@ -1288,12 +1282,13 @@ Logger::writeTextLog( const char * message, } void -Logger::writePlayerLog( const Player & player, +Logger::writePlayerLog( const Stadium & stadium, + const Player & player, const char * message, const TextLogFlag flag ) { - if ( isTextLogOpen() - || ( flag == RECV && isGameLogOpen() ) + if ( M_impl->isTextLogOpen() + || ( flag == RECV && M_impl->isGameLogOpen() ) || ( flag == RECV && ServerParam::instance().sendComms() ) ) { char tmp[MaxMesg]; @@ -1303,16 +1298,17 @@ Logger::writePlayerLog( const Player & player, player.team()->name().c_str(), player.unum(), message ); - writeTextLog( tmp, flag ); + writeTextLog( stadium, tmp, flag ); } } void -Logger::writeCoachLog( const char * message, +Logger::writeCoachLog( const Stadium & stadium, + const char * message, const TextLogFlag flag ) { - if ( isTextLogOpen() - || ( flag == RECV && isGameLogOpen() ) + if ( M_impl->isTextLogOpen() + || ( flag == RECV && M_impl->isGameLogOpen() ) || ( flag == RECV && ServerParam::instance().sendComms() ) ) { char tmp[MaxMesg]; @@ -1320,38 +1316,38 @@ Logger::writeCoachLog( const char * message, "%s Coach: %s", ( flag == SEND ? "Send" : "Recv" ), message ) ; - writeTextLog( tmp, flag ); + writeTextLog( stadium, tmp, flag ); } } void -Logger::writeOnlineCoachLog( const OnlineCoach & coach, +Logger::writeOnlineCoachLog( const Stadium & stadium, + const OnlineCoach & coach, const char * message, const TextLogFlag flag ) { - if ( isTextLogOpen() - || ( flag == RECV && isGameLogOpen() ) + if ( M_impl->isTextLogOpen() + || ( flag == RECV && M_impl->isGameLogOpen() ) || ( flag == RECV && ServerParam::instance().sendComms() ) ) { char tmp[MaxMesg]; snprintf( tmp, MaxMesg, "%s %s_Coach: %s", ( flag == SEND ? "Send" : "Recv" ), - ( coach.side() == LEFT - ? M_stadium.teamLeft().name().c_str() - : M_stadium.teamRight().name().c_str() ), + coach.team().name().c_str(), message ); - writeTextLog( tmp, flag ); + writeTextLog( stadium, tmp, flag ); } } void -Logger::writeRefereeAudio( const char * msg ) +Logger::writeRefereeAudio( const Stadium & stadium, + const char * msg ) { - if ( isTextLogOpen() - || ( isGameLogOpen() - && M_stadium.playmode() != PM_BeforeKickOff - && M_stadium.playmode() != PM_TimeOver ) ) + if ( M_impl->isTextLogOpen() + || ( M_impl->isGameLogOpen() + && stadium.playmode() != PM_BeforeKickOff + && stadium.playmode() != PM_TimeOver ) ) { char buf[max_message_length_for_display]; snprintf( buf, @@ -1359,12 +1355,12 @@ Logger::writeRefereeAudio( const char * msg ) "(%s %s)", REFEREE_NAME, msg ); - if ( isTextLogOpen() ) + if ( M_impl->isTextLogOpen() ) { - writeTextLog( buf, LOG_TEXT ); + writeTextLog( stadium, buf, LOG_TEXT ); } - if ( isGameLogOpen() ) + if ( M_impl->isGameLogOpen() ) { writeMsgToGameLog( MSG_BOARD, buf ); } @@ -1372,14 +1368,15 @@ Logger::writeRefereeAudio( const char * msg ) } void -Logger::writePlayerAudio( const Player & player, +Logger::writePlayerAudio( const Stadium & stadium, + const Player & player, const char * msg ) { - if ( isGameLogOpen() + if ( M_impl->isGameLogOpen() && ServerParam::instance().recordMessages() - && M_stadium.playmode() != PM_BeforeKickOff - && M_stadium.playmode() != PM_TimeOver ) + && stadium.playmode() != PM_BeforeKickOff + && stadium.playmode() != PM_TimeOver ) { char buf[max_message_length_for_display]; snprintf( buf, @@ -1392,13 +1389,14 @@ Logger::writePlayerAudio( const Player & player, } void -Logger::writeCoachAudio( const Coach & coach, +Logger::writeCoachAudio( const Stadium & stadium, + const Coach & coach, const char * msg ) { - if ( isGameLogOpen() + if ( M_impl->isGameLogOpen() && ServerParam::instance().recordMessages() - && M_stadium.playmode() != PM_BeforeKickOff - && M_stadium.playmode() != PM_TimeOver ) + && stadium.playmode() != PM_BeforeKickOff + && stadium.playmode() != PM_TimeOver ) { char buf[max_message_length_for_display]; char format[40]; @@ -1419,13 +1417,14 @@ Logger::writeCoachAudio( const Coach & coach, } void -Logger::writeCoachStdAudio( const OnlineCoach & coach, +Logger::writeCoachStdAudio( const Stadium & stadium, + const OnlineCoach & coach, const rcss::clang::Msg & msg ) { - if ( isGameLogOpen() + if ( M_impl->isGameLogOpen() && ServerParam::instance().recordMessages() - && M_stadium.playmode() != PM_BeforeKickOff - && M_stadium.playmode() != PM_TimeOver ) + && stadium.playmode() != PM_BeforeKickOff + && stadium.playmode() != PM_TimeOver ) { std::ostringstream coach_mess; @@ -1448,34 +1447,76 @@ Logger::writeCoachStdAudio( const OnlineCoach & coach, void -Logger::writeTimes( const timeval & old_time, - const timeval & new_time ) +Logger::writeKeepawayHeader( const int keepers, + const int takers ) +{ + if ( M_impl->kaway_log_ ) + { + M_impl->kaway_log_ << "# Keepers: " << keepers << '\n' + << "# Takers: " << takers << '\n' + << "# Region: " << ServerParam::instance().keepAwayLength() + << " x " << ServerParam::instance().keepAwayWidth() + << '\n' + << "#\n" + << "# Description of Fields:\n" + << "# 1) Episode number\n" + << "# 2) Start time in simulator steps (100ms)\n" + << "# 3) End time in simulator steps (100ms)\n" + << "# 4) Duration in simulator steps (100ms)\n" + << "# 5) (o)ut of bounds / (t)aken away\n" + << "#\n" + << std::flush; + } +} + +void +Logger::writeKeepawayLog( const Stadium & stadium, + const int episode, + const int time, + const char * end_cond ) +{ + if ( M_impl->kaway_log_ ) + { + M_impl->kaway_log_ << episode << "\t" + << time << "\t" + << stadium.time() << "\t" + << stadium.time() - time << "\t" + << end_cond + << std::endl; + } +} + +void +Logger::writeTimes( const Stadium & stadium, + const std::chrono::system_clock::time_point & old_time, + const std::chrono::system_clock::time_point & new_time ) { - if ( isTextLogOpen() + if ( M_impl->isTextLogOpen() && ServerParam::instance().logTimes() ) { - double diff = (new_time.tv_sec - old_time.tv_sec) * 1000 - + (double)(new_time.tv_usec - old_time.tv_usec) / 1000; + const std::chrono::nanoseconds nano_diff = std::chrono::duration_cast< std::chrono::nanoseconds >( new_time - old_time ); + const double diff = nano_diff.count() * 0.001 * 0.001; - *M_text_log << M_stadium.time() - << ',' << M_stadium.stoppageTime() - << "\tCYCLE_TIMES: " << diff << '\n'; + *M_impl->text_log_ << stadium.time() + << ',' << stadium.stoppageTime() + << "\tCYCLE_TIMES: " << diff << '\n'; } } void -Logger::writeProfile( const timeval & start_time, - const timeval & end_time, - const char * str ) +Logger::writeProfile( const Stadium & stadium, + const std::chrono::system_clock::time_point & start_time, + const std::chrono::system_clock::time_point & end_time, + const std::string & str ) { - if ( isTextLogOpen() + if ( M_impl->isTextLogOpen() && ServerParam::instance().profile() ) { - double diff = (end_time.tv_sec - start_time.tv_sec) * 1000 - + (double)(end_time.tv_usec - start_time.tv_usec) / 1000; + const std::chrono::nanoseconds nano_diff = std::chrono::duration_cast< std::chrono::nanoseconds >( end_time - start_time ); + const double diff = nano_diff.count() * 0.001 * 0.001; - *M_text_log << M_stadium.time() - << ',' << M_stadium.stoppageTime() - << "\t" << str << ": " << diff << '\n'; + *M_impl->text_log_ << stadium.time() + << ',' << stadium.stoppageTime() + << "\t" << str << ": " << diff << '\n'; } } diff --git a/src/logger.h b/src/logger.h index 0039c514..107e3764 100644 --- a/src/logger.h +++ b/src/logger.h @@ -25,23 +25,16 @@ #include "types.h" -#include - -#include -#include #include - +#include +#include class Player; class Coach; class OnlineCoach; class Stadium; -class XPMHolder; -struct timeval; namespace rcss { -class InitObserverLogger; -class ObserverLogger; namespace clang { class Msg; } @@ -50,82 +43,38 @@ class Msg; class Logger { private: - static const std::string DEF_TEXT_NAME; - static const std::string DEF_TEXT_SUFFIX; - static const std::string DEF_GAME_NAME; - static const std::string DEF_GAME_SUFFIX; - static const std::string DEF_KAWAY_NAME; - static const std::string DEF_KAWAY_SUFFIX; - - rcss::InitObserverLogger * M_init_observer; - rcss::ObserverLogger * M_observer; - - const Stadium & M_stadium; + struct Impl; + std::unique_ptr< Impl > M_impl; - std::string M_game_log_name; - std::string M_text_log_name; - std::string M_kaway_log_name; + Logger(); - std::ostream * M_game_log; - std::ostream * M_text_log; - std::ofstream M_kaway_log; //!< file for keepaway log + Logger( const Logger & ) = delete; + Logger & operator=( const Logger & ) = delete; +public: - PlayMode M_playmode; - std::string M_team_l_name; - std::string M_team_r_name; - int M_team_l_score; - int M_team_r_score; - int M_team_l_pen_taken; - int M_team_r_pen_taken; + static Logger & instance(); -public: - explicit - Logger( Stadium & stadium ); ~Logger(); - bool setSenders(); - - bool open(); - void close(); + bool open( const Stadium & stadium ); + void close( const Stadium & stadium ); private: - bool openGameLog(); + bool setSenders( const Stadium & stadium ); + + bool openGameLog( const Stadium & stadium ); bool openTextLog(); bool openKawayLog(); + void renameLogs( const Stadium & stadium ); void closeGameLog(); void closeTextLog(); void closeKawayLog(); - void renameLogs(); - public: - bool isGameLogOpen() const - { - return ( M_game_log && M_game_log->good() ); - } - - bool isTextLogOpen() const - { - return ( M_text_log && M_text_log->good() ); - } - - std::ostream & kawayLog() - { - return M_kaway_log; - } - - void flush() - { - if ( M_game_log ) M_game_log->flush(); - if ( M_text_log ) M_text_log->flush(); - M_kaway_log.flush(); - } - - void writeToGameLog( const char * str, - const std::streamsize n ); + void flush(); void writeMsgToGameLog( const BoardType board_type, const char * msg, @@ -134,9 +83,12 @@ class Logger { /*! \brief write current status */ - void writeGameLog(); + void writeGameLog( const Stadium & stadium ); private: - void writeGameLogImpl(); + void writeGameLogImpl( const Stadium & stadium ); + + // void writeToGameLog( const char * str, + // const std::streamsize n ); //void writeGameLogV1(); //void writeGameLogV2(); @@ -149,31 +101,49 @@ class Logger { const unsigned int x, const unsigned int y ); - void writeTextLog( const char * message, + void writeTextLog( const Stadium & stadium, + const char * message, const TextLogFlag flag ); - void writePlayerLog( const Player & player, + void writePlayerLog( const Stadium & stadium, + const Player & player, const char * message, const TextLogFlag flag ); - void writeCoachLog( const char * message, + void writeCoachLog( const Stadium & stadium, + const char * message, const TextLogFlag flag ); - void writeOnlineCoachLog( const OnlineCoach & coach, + void writeOnlineCoachLog( const Stadium & stadium, + const OnlineCoach & coach, const char * message, const TextLogFlag flag ); - void writeRefereeAudio( const char * msg ); - void writePlayerAudio( const Player & player, + void writeRefereeAudio( const Stadium & stadium, + const char * msg ); + void writePlayerAudio( const Stadium & stadium, + const Player & player, const char * msg ); - void writeCoachAudio( const Coach & coach, + void writeCoachAudio( const Stadium & stadium, + const Coach & coach, const char * msg ); - void writeCoachStdAudio( const OnlineCoach & coach, + void writeCoachStdAudio( const Stadium & stadium, + const OnlineCoach & coach, const rcss::clang::Msg & msg ); - void writeTimes( const timeval &, - const timeval & ); - void writeProfile( const timeval &, - const timeval &, - const char * ); + void writeKeepawayHeader( const int keepers, + const int takers ); + void writeKeepawayLog( const Stadium & stadium, + const int episode, + const int time, + const char * end_cond ); + + void writeTimes( const Stadium & stadium, + const std::chrono::system_clock::time_point & old_time, + const std::chrono::system_clock::time_point & new_time ); + void writeProfile( const Stadium & stadium, + const std::chrono::system_clock::time_point & start_time, + const std::chrono::system_clock::time_point & end_time, + const std::string & str ); + }; diff --git a/src/main.cpp b/src/main.cpp index d15635d5..05993841 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -68,9 +68,9 @@ main( int argc, char *argv[] ) struct sigaction sig_action; sig_action.sa_handler = &sigHandle; sig_action.sa_flags = 0; - if ( sigaction( SIGINT, &sig_action , NULL ) != 0 - || sigaction( SIGTERM, &sig_action , NULL ) != 0 - || sigaction( SIGHUP, &sig_action , NULL ) != 0 ) + if ( sigaction( SIGINT, &sig_action, nullptr ) != 0 + || sigaction( SIGTERM, &sig_action, nullptr ) != 0 + || sigaction( SIGHUP, &sig_action, nullptr ) != 0 ) { std::cerr << __FILE__ << ": " << __LINE__ << ": could not set signal handler: " diff --git a/src/monitor.cpp b/src/monitor.cpp index 104ca6e6..22b67157 100644 --- a/src/monitor.cpp +++ b/src/monitor.cpp @@ -36,11 +36,7 @@ #include "types.h" #include "xpmholder.h" -#ifdef HAVE_SSTREAM #include -#else -#include -#endif // #ifdef HAVE_NETINET_IN_H // #include @@ -238,9 +234,8 @@ Monitor::sendTeamGraphics() if ( M_left_sent_graphics.size() < M_stadium.teamLeft().teamGraphics().size() ) { - const Team::GraphCont::const_reverse_iterator end = M_stadium.teamLeft().teamGraphics().rend(); - for ( Team::GraphCont::const_reverse_iterator it = M_stadium.teamLeft().teamGraphics().rbegin(); - it != end; + for ( Team::GraphCont::const_reverse_iterator it = M_stadium.teamLeft().teamGraphics().rbegin(), rend = M_stadium.teamLeft().teamGraphics().rend(); + it != rend; ++it ) { if ( send_count >= MAX_SEND ) break; @@ -264,9 +259,8 @@ Monitor::sendTeamGraphics() if ( M_right_sent_graphics.size() < M_stadium.teamRight().teamGraphics().size() ) { - const Team::GraphCont::const_reverse_iterator end = M_stadium.teamRight().teamGraphics().rend(); - for ( Team::GraphCont::const_reverse_iterator it = M_stadium.teamRight().teamGraphics().rbegin(); - it != end; + for ( Team::GraphCont::const_reverse_iterator it = M_stadium.teamRight().teamGraphics().rbegin(), rend = M_stadium.teamRight().teamGraphics().rend(); + it != rend; ++it ) { if ( send_count >= MAX_SEND ) break; @@ -538,16 +532,9 @@ Monitor::compression( const char * command ) return false; } -#ifdef HAVE_SSTREAM std::ostringstream reply; reply << "(ok compression " << level << ")"; sendMsg( MSG_BOARD, reply.str().c_str() ); -#else - std::ostrstream reply; - reply << "(ok compression " << level << ")" << std::ends; - sendMsg( MSG_BOARD, reply.str() ); - reply.freeze( false ); -#endif setCompressionLevel( level ); return true; #else @@ -652,11 +639,11 @@ Monitor::coach_move( const char * command ) ServerParam::instance().maxMoment() ) ); if ( n == 3 ) { - M_stadium.movePlayer( side, unum, pos, NULL, NULL ); + M_stadium.movePlayer( side, unum, pos, nullptr, nullptr ); } else if ( n == 4 ) { - M_stadium.movePlayer( side, unum, pos, &ang, NULL ); + M_stadium.movePlayer( side, unum, pos, &ang, nullptr ); } else if ( n == 6 ) { @@ -685,11 +672,7 @@ Monitor::coach_recover() bool Monitor::coach_check_ball() { -#ifdef HAVE_SSTREAM std::ostringstream ost; -#else - std::ostrstream ost; -#endif static const char * s_ball_pos_info_str[] = BALL_POS_INFO_STRINGS; BallPosInfo info = M_stadium.ballPosInfo(); @@ -700,13 +683,7 @@ Monitor::coach_check_ball() ost << std::ends; -#ifdef HAVE_SSTREAM sendMsg( MSG_BOARD, ost.str().c_str() ); -#else - ost << std::ends; - sendMsg( MSG_BOARD, ost.str() ); - ost.freeze( false ); -#endif return true; } @@ -724,7 +701,7 @@ Monitor::coach_change_player_type( const char * command ) return false; } - const Team * team = NULL; + const Team * team = nullptr; if ( M_stadium.teamLeft().name() == teamname ) { team = &( M_stadium.teamLeft() ); @@ -734,7 +711,7 @@ Monitor::coach_change_player_type( const char * command ) team = &( M_stadium.teamRight() ); } - if ( team == NULL ) + if ( ! team ) { sendMsg( MSG_BOARD, "(warning no_team_found)" ); return false; @@ -747,7 +724,7 @@ Monitor::coach_change_player_type( const char * command ) return false; } - const Player * player = NULL; + const Player * player = nullptr; for ( int i = 0; i < team->size(); ++i ) { const Player * p = team->player( i ); @@ -758,7 +735,7 @@ Monitor::coach_change_player_type( const char * command ) } } - if ( player == NULL ) + if ( ! player ) { sendMsg( MSG_BOARD, "(warning no_such_player)" ); return false; diff --git a/src/monitor.h b/src/monitor.h index 9b43314c..a22c6587 100644 --- a/src/monitor.h +++ b/src/monitor.h @@ -62,7 +62,7 @@ class Monitor public: Monitor( Stadium & stadium, const double & version ); - ~Monitor(); + ~Monitor() override; void disable() { @@ -70,7 +70,7 @@ class Monitor } void parseMsg( char * msg, - const size_t & len ); + const size_t & len ) override; bool parseCommand( const char * message ); bool setSenders(); diff --git a/src/mysqlsaver.cpp b/src/mysqlsaver.cpp index 7789bb92..6806c206 100644 --- a/src/mysqlsaver.cpp +++ b/src/mysqlsaver.cpp @@ -5,7 +5,7 @@ Class for saving results to a mysql database ------------------- begin : 09-MAY-2003 - copyright : (C) 2003 by The RoboCup Soccer Simulator + copyright : (C) 2003 by The RoboCup Soccer Simulator Maintenance Group. email : sserver-admin@lists.sourceforge.net ***************************************************************************/ @@ -34,12 +34,7 @@ #include "config.h" #endif -#ifdef HAVE_SSTREAM #include -#else -#include -#endif - #if defined(_WIN32) || defined(__WIN32__) || defined (WIN32) || defined (__CYGWIN__) # ifndef WIN32 @@ -53,7 +48,7 @@ class MySQLSaver public: MySQLSaver( int argc, const char** argv, const std::string& module_name ) : rcss::ResultSaver( argc, argv, module_name ), - m_mysql( NULL ), + m_mysql( nullptr ), m_left_coin( false ), m_right_coin( false ), m_save( false ), @@ -69,45 +64,35 @@ class MySQLSaver m_pen_taken[ i ] = 0; m_pen_scored[ i ] = 0; } - + addParams(); - + #ifdef WIN32 std::string user_dir = tildeExpand( "~\\.rcssserver\\" ); #else std::string user_dir = tildeExpand( "~/.rcssserver/" ); -#endif +#endif std::string user_conf_name = user_dir + getModuleName() + ".conf"; m_conf_parser.parseCreateConf( user_conf_name ); m_conf_parser.parse( argc, argv ); - + if( m_save ) { - m_mysql = mysql_init( NULL ); - if( m_mysql == 0 ) + m_mysql = mysql_init( nullptr ); + if ( m_mysql == 0 ) { std::cerr << "Error: could not initialise MySQL object\n"; } else { - if( mysql_real_connect( m_mysql, - ( m_host.empty() - ? NULL - : m_host.c_str() ), - ( m_user.empty() - ? NULL - : m_user.c_str() ), - m_pass.c_str(), - m_db.c_str(), - m_port, - ( m_unix_socket.empty() - ? NULL - : m_host.c_str() ), - ( ( m_compress - ? CLIENT_COMPRESS : 0 ) - | ( m_ssl - ? CLIENT_SSL : 0 ) ) ) - == NULL ) + if ( ! mysql_real_connect( m_mysql, + ( m_host.empty() ? nullptr : m_host.c_str() ), + ( m_user.empty() ? nullptr : m_user.c_str() ), + m_pass.c_str(), + m_db.c_str(), + m_port, + ( m_unix_socket.empty() ? nullptr : m_host.c_str() ), + ( ( m_compress ? CLIENT_COMPRESS : 0 ) | ( m_ssl ? CLIENT_SSL : 0 ) ) ) ) { std::cerr << "Error: could not connect to database: " << mysql_error( m_mysql ) << std::endl; @@ -118,12 +103,12 @@ class MySQLSaver { std::cout << "Connected to database\n"; createTables(); - determineRoundID(); + determineRoundID(); } } } } - + virtual ~MySQLSaver() { @@ -151,7 +136,7 @@ class MySQLSaver addParam( "event_id", m_event_id, "The ID of the event this game is part of. This vaule is used to try to distinguish between two rounds of the same names in different events if the round_id is less than zero (default: -1) and the round_name is specfied" ); addParam( "event_name", m_event_name, "The name of the event this game is part of. This value is used to try to distinguish between two rounds of the same name in different events is the round_id is less than zero, the round_name is specified and the event_id is zero(default)" ); } - + void createTables() { @@ -252,7 +237,7 @@ class MySQLSaver query += "`LEFT_FROM_TYPE` ENUM( 'WINNER', 'LOOSER' ) DEFAULT NULL ,"; query += "`RIGHT_FROM_TYPE` ENUM( 'WINNER', 'LOOSER' ) DEFAULT NULL ,"; query += "PRIMARY KEY ( `ID` ) ,"; - query += "INDEX ( `ROUND_ID` , `DATETIME` , `LEFT` , `RIGHT` )"; + query += "INDEX ( `ROUND_ID` , `DATETIME` , `LEFT` , `RIGHT` )"; query += ")"; if( mysql_query( m_mysql, query.c_str() ) != 0 ) { @@ -269,7 +254,7 @@ class MySQLSaver doCreateTables() { return createEvents() - && createRounds() + && createRounds() && createGames(); } @@ -277,117 +262,70 @@ class MySQLSaver addRound() { std::cout << "Adding round: " << m_round_name << std::endl; -#ifdef HAVE_SSTREAM std::ostringstream add_round; -#else - std::ostrstream add_round; -#endif + add_round << "INSERT INTO `ROUNDS` (`NAME`, `EVENT_ID`) VALUES ('" << m_event_name << "', "; if( m_event_id < 0 ) add_round << "null"; else add_round << m_event_id; add_round << " )"; -#ifndef HAVE_SSTREAM - add_round << std::ends; -#endif if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM add_round.str().c_str() -#else - add_round.str() -#endif ) != 0 ) { std::cerr << "Error: Could not add round to database: " << mysql_error( m_mysql ) << std::endl; -#ifndef HAVE_SSTREAM - add_round.freeze( false ); -#endif } else { -#ifndef HAVE_SSTREAM - add_round.freeze( false ); -#endif std::cout << "Round '" << m_round_name << "' added\n"; } } - + void addEvent() { std::cout << "Adding event: " << m_event_name << std::endl; -#ifdef HAVE_SSTREAM std::ostringstream add_event; -#else - std::ostrstream add_event; -#endif + add_event << "INSERT INTO `EVENTS` (`NAME`) VALUES ('" << m_event_name << "')"; -#ifndef HAVE_SSTREAM - add_event << std::ends; -#endif + if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM add_event.str().c_str() -#else - add_event.str() -#endif ) != 0 ) { std::cerr << "Error: Could not add event to database: " << mysql_error( m_mysql ) << std::endl; -#ifndef HAVE_SSTREAM - add_event.freeze( false ); -#endif } else { -#ifndef HAVE_SSTREAM - add_event.freeze( false ); -#endif std::cout << "Event '" << m_event_name << "' added\n"; } } - + void getRoundByName() { -#ifdef HAVE_SSTREAM std::ostringstream query; -#else - std::ostrstream query; -#endif + query << "SELECT `ID` FROM `ROUNDS` WHERE `NAME` = '" << m_round_name << "'"; if( m_event_id >= 0 ) query << " AND EVENT_ID = " << m_event_id; -#ifndef HAVE_SSTREAM - query << std::ends; -#endif if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM query.str().c_str() -#else - query.str() -#endif ) != 0 ) { std::cerr << "Error: Could not select round from database: " << mysql_error( m_mysql ) << std::endl; std::cerr << "Query was:\n" << query.str() << std::endl; -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif } else { -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif - MYSQL_RES* results = mysql_store_result( m_mysql ); - if( results == NULL ) + MYSQL_RES * results = mysql_store_result( m_mysql ); + if ( ! results ) { std::cerr << "Error: Could not get select round results from database: " << mysql_error( m_mysql ) << std::endl; @@ -395,11 +333,11 @@ class MySQLSaver else { my_ulonglong rows = mysql_num_rows( results ); - if( rows > 1 ) + if ( rows > 1 ) { std::cerr << "Error: Mutiple rounds returned for the name '" << m_round_name << "'\n"; } - else if( rows == 0 ) + else if ( rows == 0 ) { std::cout << "No round with the name '" << m_round_name << "' found.\n"; addRound(); @@ -408,19 +346,14 @@ class MySQLSaver else { MYSQL_ROW row = mysql_fetch_row( results ); - if( row == NULL ) + if ( ! row ) { std::cerr << "Error: could not get row from round query:" << mysql_error( m_mysql ) << std::endl; } else { -#ifdef HAVE_SSTREAM std::istringstream id( row[ 0 ] ); -#else - std::istrstream id( row[ 0 ] ); -#endif - id >> m_round_id; } } @@ -431,37 +364,21 @@ class MySQLSaver void getEventByName() { -#ifdef HAVE_SSTREAM std::ostringstream query; -#else - std::ostrstream query; -#endif query << "SELECT `ID` FROM `EVENTS` WHERE `NAME` = '" << m_event_name << "'"; -#ifndef HAVE_SSTREAM - query << std::ends; -#endif + if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM query.str().c_str() -#else - query.str() -#endif - ) != 0 ) + ) != 0 ) { std::cerr << "Error: Could not select event from database: " << mysql_error( m_mysql ) << std::endl; std::cerr << "Query was:\n" << query.str() << std::endl; -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif } else { -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif - MYSQL_RES* results = mysql_store_result( m_mysql ); - if( results == NULL ) + MYSQL_RES * results = mysql_store_result( m_mysql ); + if ( ! results ) { std::cerr << "Error: Could not get select event results from database: " << mysql_error( m_mysql ) << std::endl; @@ -482,18 +399,14 @@ class MySQLSaver else { MYSQL_ROW row = mysql_fetch_row( results ); - if( row == NULL ) + if ( ! row ) { std::cerr << "Error: could not get row from event query:" << mysql_error( m_mysql ) << std::endl; } else { -#ifdef HAVE_SSTREAM std::istringstream id( row[ 0 ] ); -#else - std::istrstream id( row[ 0 ] ); -#endif id >> m_event_id; } } @@ -504,38 +417,21 @@ class MySQLSaver void getRoundByID() { -#ifdef HAVE_SSTREAM std::ostringstream query; -#else - std::ostrstream query; -#endif query << "SELECT `NAME` FROM `ROUNDS` WHERE `ID` = " << m_round_id; -#ifndef HAVE_SSTREAM - query << std::ends; -#endif if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM query.str().c_str() -#else - query.str() -#endif - ) != 0 ) + ) != 0 ) { std::cerr << "Error: Could not select round from database: " << mysql_error( m_mysql ) << std::endl; std::cerr << "Query was:\n" << query.str() << std::endl; -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif } else { -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif - MYSQL_RES* results = mysql_store_result( m_mysql ); - if( results == NULL ) + MYSQL_RES * results = mysql_store_result( m_mysql ); + if ( ! results ) { std::cerr << "Error: Could not get select round results from database: " << mysql_error( m_mysql ) << std::endl; @@ -558,7 +454,7 @@ class MySQLSaver else { MYSQL_ROW row = mysql_fetch_row( results ); - if( row == NULL ) + if ( ! row ) { std::cerr << "Error: could not get row from round query:" << mysql_error( m_mysql ) << std::endl; @@ -575,37 +471,21 @@ class MySQLSaver void getEventByID() { -#ifdef HAVE_SSTREAM std::ostringstream query; -#else - std::ostrstream query; -#endif query << "SELECT `NAME` FROM `EVENTS` WHERE `ID` = " << m_event_id; -#ifndef HAVE_SSTREAM - query << std::ends; -#endif + if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM query.str().c_str() -#else - query.str() -#endif - ) != 0 ) + ) != 0 ) { std::cerr << "Error: Could not select event from database: " << mysql_error( m_mysql ) << std::endl; std::cerr << "Query was:\n" << query.str() << std::endl; -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif } else { -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif - MYSQL_RES* results = mysql_store_result( m_mysql ); - if( results == NULL ) + MYSQL_RES * results = mysql_store_result( m_mysql ); + if ( ! results ) { std::cerr << "Error: Could not get select event results from database: " << mysql_error( m_mysql ) << std::endl; @@ -613,11 +493,11 @@ class MySQLSaver else { my_ulonglong rows = mysql_num_rows( results ); - if( rows > 1 ) + if ( rows > 1 ) { std::cerr << "Error: Mutiple events returned for the ID '" << m_event_id << "'\n"; } - else if( rows == 0 ) + else if ( rows == 0 ) { std::cout << "No event with the id '" << m_event_id << "' found.\n"; std::cout << "Setting event id to -1\n"; @@ -627,7 +507,7 @@ class MySQLSaver else { MYSQL_ROW row = mysql_fetch_row( results ); - if( row == NULL ) + if ( ! row ) { std::cerr << "Error: could not get row from event query:" << mysql_error( m_mysql ) << std::endl; @@ -640,7 +520,7 @@ class MySQLSaver } } } - + virtual void doDetermineEventID() @@ -660,13 +540,13 @@ class MySQLSaver if( m_event_id >= 0 ) std::cout << "Event: " << m_event_id << ", '" << m_event_name << "'" << std::endl; } - + virtual void doDetermineRoundID() { determineEventID(); - + if( m_round_id < 0 ) { if( !m_round_name.empty() ) @@ -679,14 +559,14 @@ class MySQLSaver std::cout << "Using round id specifed\n"; getRoundByID(); } - + if( m_round_id > -1 ) std::cout << "Round: " << m_round_id << ", '" << m_round_name << "'" << std::endl; } - -private: - + +private: + virtual bool doEnabled() const @@ -696,49 +576,49 @@ class MySQLSaver void doSaveStart() {} - + virtual void - doSaveTime( const tm& time ) + doSaveTime( const std::time_t time ) { m_time = time; } - + virtual void doSaveTeamName( team_id id, const std::string& name ) { m_team_name[ id ] = name; } - + virtual void doSaveCoachName( team_id id, const std::string& name ) { m_coach_name[ id ] = name; } - + virtual void doSaveScore( team_id id, unsigned int score ) { m_score[ id ] = score; } - + virtual void doSavePenTaken( team_id id, unsigned int taken ) { m_pen_taken[ id ] = taken; } - + virtual void doSavePenScored( team_id id, unsigned int scored ) { m_pen_scored[ id ] = scored; } - + virtual void doSaveCoinTossWinner( team_id id ) @@ -759,7 +639,7 @@ class MySQLSaver break; } } - + virtual bool doSaveComplete() @@ -774,12 +654,11 @@ class MySQLSaver } char time_str[256]; - strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", &m_time ); -#ifdef HAVE_SSTREAM - std::ostringstream query; -#else - std::ostrstream query; -#endif + const std::time_t time = M_stadium.getStartTime(); + const struct tm * lt = std::localtime( &time ); + strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", lt ); + + std::ostringstream query;` query << "INSERT INTO `GAMES` ( `DATETIME` , `ROUND_ID` ,\n" << "`LEFT` , `RIGHT` , `COACH_L` , `COACH_R` , `SCORE_L` ,\n" << "`SCORE_R` , `PEN_TAKEN_L` , `PEN_TAKEN_R` , `PEN_SCORED_L` ,\n" @@ -800,16 +679,16 @@ class MySQLSaver else query << "'" << m_coach_name[ TEAM_RIGHT ] << "', \n"; - - query << "'" << m_score[ TEAM_LEFT ] << "', '" + + query << "'" << m_score[ TEAM_LEFT ] << "', '" << m_score[ TEAM_RIGHT ] << "', \n"; if( m_pen_taken[ TEAM_LEFT ] || m_pen_taken[ TEAM_RIGHT ] ) { - query << "'" << m_pen_taken[ TEAM_LEFT ] + query << "'" << m_pen_taken[ TEAM_LEFT ] << "', '" << m_pen_taken[ TEAM_RIGHT ] << "', \n"; - query << "'" << m_pen_scored[ TEAM_LEFT ] << "', '" + query << "'" << m_pen_scored[ TEAM_LEFT ] << "', '" << m_pen_scored[ TEAM_RIGHT ] << "', \n"; } else @@ -817,7 +696,7 @@ class MySQLSaver query << "NULL, NULL, \n"; query << "NULL, NULL, \n"; } - + if( m_left_coin ) { query << "'LEFT'"; @@ -832,29 +711,15 @@ class MySQLSaver } query << ")\n"; -#ifndef HAVE_SSREAM - query << std::ends; -#endif - if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM query.str().c_str() -#else - query.str() -#endif - ) != 0 ) + ) != 0 ) { std::cerr << "Error: Could not save results to database: " << mysql_error( m_mysql ) << std::endl; std::cerr << "Query was:\n" << query.str() << std::endl; -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif return false; } -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif getGameID(); } else @@ -869,11 +734,8 @@ class MySQLSaver { char time_str[256]; strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", &m_time ); -#ifdef HAVE_SSTREAM + std::ostringstream query; -#else - std::ostrstream query; -#endif query << "SELECT `ID` FROM `GAMES` WHERE\n" << "`DATETIME` = '" << time_str << "'\n"; if( m_round_id > 0 ) @@ -883,32 +745,18 @@ class MySQLSaver query << "AND `SCORE_L` = " << m_score[ TEAM_LEFT ] << "\n"; query << "AND `SCORE_R` = " << m_score[ TEAM_RIGHT ] << "\n"; -#ifndef HAVE_SSREAM - query << std::ends; -#endif - if( mysql_query( m_mysql, -#ifdef HAVE_SSTREAM query.str().c_str() -#else - query.str() -#endif - ) != 0 ) + ) != 0 ) { std::cerr << "Error: Could not get game id from database: " << mysql_error( m_mysql ) << std::endl; std::cerr << "Query was:\n" << query.str() << std::endl; -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif return; } -#ifndef HAVE_SSTREAM - query.freeze( false ); -#endif - MYSQL_RES* results = mysql_store_result( m_mysql ); - if( results == NULL ) + MYSQL_RES * results = mysql_store_result( m_mysql ); + if ( ! results ) { std::cerr << "Error: Could not get select game results from database: " << mysql_error( m_mysql ) << std::endl; @@ -916,17 +764,17 @@ class MySQLSaver else { my_ulonglong rows = mysql_num_rows( results ); - if( rows > 1 ) + if ( rows > 1 ) { std::cerr << "Error: Mutiple rounds returned for the game\n"; } - else if( rows == 0 ) + else if ( rows == 0 ) { std::cerr << "Could not find game that was just inserted\n"; } else { MYSQL_ROW row = mysql_fetch_row( results ); - if( row == NULL ) + if ( ! row ) { std::cerr << "Error: could not get row from game query:" << mysql_error( m_mysql ) << std::endl; @@ -949,7 +797,7 @@ class MySQLSaver MYSQL* m_mysql; - tm m_time; + std::time_t m_time; std::string m_team_name[ 2 ]; std::string m_coach_name[ 2 ]; unsigned int m_score[ 2 ]; @@ -958,7 +806,7 @@ class MySQLSaver bool m_left_coin; bool m_right_coin; - + bool m_save; std::string m_host; std::string m_user; @@ -988,13 +836,13 @@ class MySQLSaver argv, module_name ), &destroy, - rcss::lib::Loader::loadFromCache( "libmysqlsaver" ) ); + rcss::lib::Loader::loadFromCache( "libmysqlsaver" ) ); } }; RCSSLIB_INIT( libmysqlsaver ) -{ +{ MySQLSaver::factory().reg( &MySQLSaver::create, "MySQLSaver" ); return true; } @@ -1002,6 +850,4 @@ RCSSLIB_INIT( libmysqlsaver ) RCSSLIB_FIN( libmysqlsaver ) { MySQLSaver::factory().dereg( "MySQLSaver" ); -} - - +} diff --git a/src/object.h b/src/object.h index ac94e1b1..ba5f4b19 100644 --- a/src/object.h +++ b/src/object.h @@ -49,11 +49,8 @@ #include "types.h" #include "utility.h" -#include #include -#include #include -#include #include #include @@ -249,7 +246,7 @@ class RArea { double M_bottom; // not used - RArea(); + RArea() = delete; public: RArea( const double & l, const double & r, @@ -308,7 +305,7 @@ class CArea { double M_radius; // not used - CArea(); + CArea() = delete; public: CArea( const PVector & center, const double & radius ) @@ -393,8 +390,8 @@ class PObject { private: // not used - PObject(); - const PObject & operator=( const PObject & ); + PObject() = delete; + const PObject & operator=( const PObject & ) = delete; public: @@ -505,8 +502,8 @@ class MPObject private: // not used - MPObject(); - const MPObject & operator=( const MPObject & ); + MPObject() = delete; + const MPObject & operator=( const MPObject & ) = delete; public: @@ -633,25 +630,25 @@ class Ball Ball( Stadium & stadium ); virtual - void turnImpl() + void turnImpl() override { } virtual - void updateAngle() + void updateAngle() override { } virtual - void collidedWithPost() + void collidedWithPost() override { } virtual - double maxAccel() const + double maxAccel() const override { return M_max_accel; } virtual - double maxSpeed() const + double maxSpeed() const override { return M_max_speed; } diff --git a/src/observer.h b/src/observer.h index 4296b7e8..c5952d77 100644 --- a/src/observer.h +++ b/src/observer.h @@ -23,7 +23,7 @@ #ifndef RCSSOBSERVER_H #define RCSSOBSERVER_H -#include "rcssexceptions.h" +//#include "rcssexceptions.h" #include namespace rcss { @@ -53,7 +53,7 @@ class BaseObserver { : M_sender( sender ) { } - + virtual ~BaseObserver() { } @@ -66,8 +66,9 @@ class BaseObserver { { if ( ! M_sender ) { - throw util::NullErr( __FILE__, __LINE__, - "Sender is null" ); + // throw util::NullErr( __FILE__, __LINE__, + // "Sender is null" ); + throw std::logic_error( "Sender is null" ); } return *M_sender; } @@ -76,16 +77,17 @@ class BaseObserver { { if ( ! M_sender ) { - throw util::NullErr( __FILE__, __LINE__, - "Sender is null" ); + // throw util::NullErr( __FILE__, __LINE__, + // "Sender is null" ); + throw std::logic_error( "Sender is null" ); } return *M_sender; } private: - BaseObserver( const BaseObserver & ); // not used; - BaseObserver & operator=( const BaseObserver & ); // not used; + BaseObserver( const BaseObserver & ) = delete; // not used; + BaseObserver & operator=( const BaseObserver & ) = delete; // not used; }; } diff --git a/src/pcombuilder.cpp b/src/pcombuilder.cpp index c38e0668..bba90efa 100644 --- a/src/pcombuilder.cpp +++ b/src/pcombuilder.cpp @@ -23,11 +23,7 @@ #include #endif -#ifdef HAVE_SSTREAM #include -#else -#include -#endif #include "pcombuilder.h" @@ -38,16 +34,9 @@ BuilderErr::BuilderErr( const char * file, const int & line, const char * msg ) throw() { -#ifdef HAVE_SSTREAM std::ostringstream tmp; tmp << file << ": " << line << ": " << msg; M_msg = tmp.str(); -#else - std::ostrstream tmp; - tmp << file << ": " << line << ": " << msg << std::ends; - M_msg = tmp.str(); - tmp.freeze( false ); -#endif } } diff --git a/src/pcomparser.cpp b/src/pcomparser.cpp index 697530bd..813a5d63 100644 --- a/src/pcomparser.cpp +++ b/src/pcomparser.cpp @@ -23,11 +23,7 @@ #include #endif -#ifdef HAVE_SSTREAM #include -#else -#include ; -#endif #include "pcomparser.h" @@ -44,11 +40,8 @@ Parser::Parser( Builder & builder ) int Parser::parse( const char * msg ) { -#ifdef HAVE_SSTREAM std::istringstream strm( msg ); -#else - std::istrstream strm( msg ); -#endif + return ( rcss::Parser::parse( strm ) ? 0 : 1 ); } diff --git a/src/pcomparser.h b/src/pcomparser.h index c3353e16..0f372c44 100644 --- a/src/pcomparser.h +++ b/src/pcomparser.h @@ -22,10 +22,12 @@ #ifndef PCOMPARSER_H #define PCOMPARSER_H -#include -#include #include "player_command_tok.h" +#include + +#include + namespace rcss { namespace pcom { diff --git a/src/player.cpp b/src/player.cpp index 36cac161..ba291e86 100644 --- a/src/player.cpp +++ b/src/player.cpp @@ -25,6 +25,7 @@ #include "player.h" +#include "logger.h" #include "coach.h" #include "stadium.h" #include "team.h" @@ -45,12 +46,7 @@ #include #include #include - -#ifdef HAVE_SSTREAM #include -#else -#include -#endif namespace { @@ -81,6 +77,15 @@ NormalizeKickPower( const double & p ) ServerParam::instance().maxPower() ); } +inline +double +NormalizeCatchAngle( const double d ) +{ + return rcss::bound( ServerParam::instance().minCatchAngle(), + d, + ServerParam::instance().maxCatchAngle() ); +} + // For v11 or older version inline double @@ -150,7 +155,7 @@ Player::Player( Stadium & stadium, M_clang_min_ver( 0 ), M_clang_max_ver( 0 ), // - M_player_type( NULL ), + M_player_type( nullptr ), M_player_type_id( 0 ), M_substituted( false ), M_kick_rand( ServerParam::instance().kickRand() ), // pfr 8/14/00: for RC2000 evaluation @@ -489,7 +494,7 @@ Player::parseMsg( char * msg, } command[ len ] = 0; } - M_stadium.logger().writePlayerLog( *this, command, RECV ); + Logger::instance().writePlayerLog( M_stadium, *this, command, RECV ); /** Call the PlayerCommandParser */ if ( @@ -975,7 +980,7 @@ Player::send( const char * msg ) { if ( RemoteClient::send( msg, std::strlen( msg ) + 1 ) != -1 ) { - M_stadium.logger().writePlayerLog( *this, msg, SEND ); + Logger::instance().writePlayerLog( M_stadium, *this, msg, SEND ); } } @@ -1347,6 +1352,8 @@ Player::goalieCatch( double dir ) return; } + dir = NormalizeCatchAngle( dir ); + M_command_done = true; M_state |= CATCH; @@ -1452,11 +1459,8 @@ Player::goalieCatch( double dir ) if ( min_catchable.inArea( rotated_pos ) ) { //success = ( drand( 0, 1 ) <= SP.catchProb() ); - boost::bernoulli_distribution<> rng( SP.catchProbability() ); - boost::variate_generator< rcss::random::DefaultRNG &, - boost::bernoulli_distribution<> > - dst( rcss::random::DefaultRNG::instance(), rng ); - success = dst(); + std::bernoulli_distribution dst( SP.catchProbability() ); + success = dst( DefaultRNG::instance() ); //std::cerr << M_stadium.time() // << ": goalieCatch min_catchable ok" << std::endl; } @@ -1469,11 +1473,8 @@ Player::goalieCatch( double dir ) catch_prob = std::min( std::max( 0.0, catch_prob ), 1.0 ); //success = ( drand( 0, 1 ) <= catch_prob ); - boost::bernoulli_distribution<> rng( catch_prob ); - boost::variate_generator< rcss::random::DefaultRNG &, - boost::bernoulli_distribution<> > - dst( rcss::random::DefaultRNG::instance(), rng ); - success = dst(); + std::bernoulli_distribution dst( catch_prob ); + success = dst( DefaultRNG::instance() ); //std::cerr << M_stadium.time() // << ": goalieCatch " // << " dir=" << Rad2Deg( normalize_angle( angleBodyCommitted() + NormalizeMoment( dir ) ) ) @@ -1564,6 +1565,13 @@ Player::move( double x, //|| M_stadium.playmode() == PM_PenaltySetup_Right ) { + if ( M_stadium.playmode() == PM_BeforeKickOff + && ServerParam::instance().kickOffOffside() + && x >= -size() ) + { + send( "(warning moving_to_opponent_field)" ); + } + M_pos.x = x * side(); M_pos.y = y * side(); M_stadium.collisions(); @@ -1740,16 +1748,9 @@ Player::compression( int level ) return; } -#ifdef HAVE_SSTREAM std::ostringstream reply; reply << "(ok compression " << level << ")"; send( reply.str().c_str() ); -#else - std::ostrstream reply; - reply << "(ok compression " << level << ")" << std::ends; - send( reply.str() ); - reply.freeze( false ); -#endif setCompressionLevel( level ); #else @@ -1799,7 +1800,7 @@ Player::attentionto( bool on, } else { - const Team * at_team = NULL; + const Team * at_team = nullptr; if ( team_side == rcss::pcom::OUR ) { @@ -1906,15 +1907,11 @@ Player::tackle( double power_or_angle, if ( foul ) { foul = false; - - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( (*p)->isEnabled() - && (*p)->side() != this->side() - && (*p)->ballKickable() ) + if ( p->isEnabled() + && p->side() != this->side() + && p->ballKickable() ) { foul = true; exponent = ServerParam::instance().foulExponent(); @@ -1931,12 +1928,9 @@ Player::tackle( double power_or_angle, if ( prob < 1.0 ) { - boost::bernoulli_distribution<> rng( 1 - prob ); - boost::variate_generator< rcss::random::DefaultRNG &, - boost::bernoulli_distribution<> > - dst( rcss::random::DefaultRNG::instance(), rng ); + std::bernoulli_distribution dst( 1 - prob ); - if ( dst() ) + if ( dst( DefaultRNG::instance() ) ) { M_state |= TACKLE; @@ -2091,9 +2085,9 @@ Player::clang( int min, int max ) sendOKClang(); - if( M_team != NULL - && team()->olcoach() != NULL - && team()->olcoach()->assigned() ) + if( M_team + && M_team->olcoach() + && M_team->olcoach()->assigned() ) { M_team->olcoach()->sendPlayerClangVer( *this ); } diff --git a/src/player.h b/src/player.h index cacbb81f..3b231e02 100644 --- a/src/player.h +++ b/src/player.h @@ -190,8 +190,8 @@ class Player private: // not used - Player(); - const Player & operator=( const Player & ); + Player() = delete; + const Player & operator=( const Player & ) = delete; public: Player( Stadium & stadium, @@ -213,7 +213,7 @@ class Player // receive message // void parseMsg( char * msg, - const size_t & len ); + const size_t & len ) override; // // send messages @@ -418,46 +418,46 @@ class Player protected: virtual - void turnImpl(); + void turnImpl() override; virtual - void updateAngle(); + void updateAngle() override; virtual - void collidedWithPost(); + void collidedWithPost() override; virtual - double maxAccel() const; + double maxAccel() const override; virtual - double maxSpeed() const; + double maxSpeed() const override; private: bool parseCommand( const char * command ); int parseEar( const char * command ); /** PlayerCommands */ - void dash( double power ); - void dash( double power, double dir ); - void turn( double moment ); - void turn_neck( double moment ); - void kick( double power, double dir ); - void long_kick( double power, double dir ); - void goalieCatch( double dir ); - void say( std::string message ); + void dash( double power ) override; + void dash( double power, double dir ) override; + void turn( double moment ) override; + void turn_neck( double moment ) override; + void kick( double power, double dir ) override; + void long_kick( double power, double dir ) override; + void goalieCatch( double dir ) override; + void say( std::string message ) override; /*! This function is called in the begin of each cycle and in case a player sends a sense_body command. */ - void sense_body(); - void score(); - void move( double x, double y ); - void change_view( rcss::pcom::VIEW_WIDTH viewWidth, rcss::pcom::VIEW_QUALITY viewQuality ); - void change_view( rcss::pcom::VIEW_WIDTH viewWidth ); - void compression( int level ); - void bye(); - void done(); - void pointto( bool on, double dist, double head ); - void attentionto( bool on, rcss::pcom::TEAM team_side, std::string team_name, int at_unum ); - void tackle( double power_or_angle ); - void tackle( double power_or_angle, bool foul ); - void clang( int min, int max); - void ear( bool on, rcss::pcom::TEAM team_side, std::string team_name, rcss::pcom::EAR_MODE mode ); - void synch_see(); + void sense_body() override; + void score() override; + void move( double x, double y ) override; + void change_view( rcss::pcom::VIEW_WIDTH viewWidth, rcss::pcom::VIEW_QUALITY viewQuality ) override; + void change_view( rcss::pcom::VIEW_WIDTH viewWidth ) override; + void compression( int level ) override; + void bye() override; + void done() override; + void pointto( bool on, double dist, double head ) override; + void attentionto( bool on, rcss::pcom::TEAM team_side, std::string team_name, int at_unum ) override; + void tackle( double power_or_angle ) override; + void tackle( double power_or_angle, bool foul ) override; + void clang( int min, int max) override; + void ear( bool on, rcss::pcom::TEAM team_side, std::string team_name, rcss::pcom::EAR_MODE mode ) override; + void synch_see() override; }; diff --git a/src/player_command_tok.h b/src/player_command_tok.h index 22e6d10b..54a8d275 100644 --- a/src/player_command_tok.h +++ b/src/player_command_tok.h @@ -27,7 +27,7 @@ #undef yyFlexLexer #define yyFlexLexer RCSSPComFlexLexer -//#include +//#include #include class RCSSPComLexer diff --git a/src/playerparam.cpp b/src/playerparam.cpp index 2ee77557..a5496bb7 100644 --- a/src/playerparam.cpp +++ b/src/playerparam.cpp @@ -37,8 +37,8 @@ #include "utility.h" -#include -#include +#include +#include #include @@ -141,7 +141,7 @@ PlayerParam & PlayerParam::instance( rcss::conf::Builder * parent ) { static bool parent_set = false; - if ( parent != NULL || parent_set ) + if ( parent || parent_set ) { static PlayerParam rval( parent ); parent_set = true; @@ -149,14 +149,14 @@ PlayerParam::instance( rcss::conf::Builder * parent ) } // hack to allow link testing to call instance without crashing // do not used the return value in these situations - PlayerParam * rval = NULL; + PlayerParam * rval = nullptr; return *rval; } PlayerParam & PlayerParam::instance() { - return PlayerParam::instance( NULL ); + return PlayerParam::instance( nullptr ); } bool @@ -184,13 +184,7 @@ PlayerParam::init( rcss::conf::Builder * parent ) try { - conf_path = boost::filesystem::path( tildeExpand( conf_dir ) -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + conf_path = boost::filesystem::path( tildeExpand( conf_dir ) ); conf_path /= PlayerParam::PLAYER_CONF; } catch ( std::exception & e ) @@ -203,20 +197,18 @@ PlayerParam::init( rcss::conf::Builder * parent ) return false; } - instance().convertOldConf( conf_path.BOOST_FS_FILE_STRING() ); + instance().convertOldConf( conf_path.string() ); if ( ! instance().M_builder->parser()->parseCreateConf( conf_path, "player" ) ) { - std::cerr << "could not parse configuration file '" - << conf_path.BOOST_FS_FILE_STRING() - << "'\n"; + std::cerr << "could not parse configuration file " << conf_path << std::endl;; return false; } if ( instance().M_builder->version() != instance().M_builder->parsedVersion() ) { std::cerr << "Version mismatched in the configuration file. " - << "Need to regenerate '" << conf_path.BOOST_FS_FILE_STRING() << "'" + << "Need to regenerate " << conf_path << " or set '" << instance().M_builder->version() << "' to the 'version' option." << std::endl; // std::cerr << "registered version = [" diff --git a/src/playerparam.h b/src/playerparam.h index 288a1ff4..adfd4e00 100644 --- a/src/playerparam.h +++ b/src/playerparam.h @@ -34,7 +34,7 @@ #include "types.h" -#include +#include #include #include @@ -46,9 +46,9 @@ class PlayerParam { private: - PlayerParam(); // not used - PlayerParam( const PlayerParam & ); // not used - PlayerParam & operator=( PlayerParam & ); // not used + PlayerParam() = delete; // not used + PlayerParam( const PlayerParam & ) = delete; // not used + PlayerParam & operator=( PlayerParam & ) = delete; // not used protected: diff --git a/src/random.h b/src/random.h index 169faa79..e89773fd 100644 --- a/src/random.h +++ b/src/random.h @@ -23,33 +23,32 @@ #ifndef RCSSSERVER_RANDOM_H #define RCSSSERVER_RANDOM_H -#include - +#include #include #include #include -namespace rcss { -namespace random { +class DefaultRNG { +public: + typedef std::mt19937 Engine; +private: + + Engine M_engine; + + DefaultRNG() = default; -class DefaultRNG - : public boost::mt19937 { public: static - DefaultRNG & instance() + //DefaultRNG & instance() + Engine & instance() { static DefaultRNG the_instance; - return the_instance; + return the_instance.M_engine; } static - DefaultRNG & -#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x520) - // Work around overload resolution problem (Gennadiy E. Rozental) - instance( const boost::mt19937::result_type & value ) -#else - instance( boost::mt19937::result_type value ) -#endif + //DefaultRNG & instance( const std::mt19937::result_type & value ) + Engine & seed( const Engine::result_type & value ) { instance().seed( value ); return instance(); @@ -58,37 +57,15 @@ class DefaultRNG // For GCC, moving this function out-of-line prevents inlining, which may // reduce overall object code size. However, MSVC does not grok // out-of-line definitions of member function templates. - template< class Generator > - static - DefaultRNG & instance( Generator & gen ) - { - instance().seed( gen ); - return instance(); - } -private: - DefaultRNG() - : boost::mt19937() - { } -}; - -// class UniformRNG -// : public boost::random_number_generator< rcss::random::DefaultRNG > -// { -// public: -// static -// UniformRNG& -// instance () -// { static UniformRNG the_instance; return the_instance; } -// -// private: -// UniformRNG() -// : boost::random_number_generator< rcss::random::DefaultRNG >( DefaultRNG::instance() ) -// {} -// }; - -} // namespace random -} // namespace rcss + // template< class Generator > + // static + // DefaultRNG & instance( Generator & gen ) + // { + // instance().engine().seed( gen() ); + // return instance(); + // } +}; // old random code //#define RANDOMBASE 1000 @@ -102,9 +79,9 @@ int irand( int x ) { if ( x <= 1 ) return 0; - //return boost::uniform_smallint<>( 0, x - 1 )( rcss::random::DefaultRNG::instance() ); - //return (int)((double)x * std::rand() / (RAND_MAX + 1.0)); - return rcss::random::DefaultRNG::instance()() % x; + + std::uniform_int_distribution<> dst( 0, x - 1 ); + return dst( DefaultRNG::instance() ); } inline @@ -113,11 +90,9 @@ drand( double low, double high ) { if ( low > high ) std::swap( low, high ); if ( high - low < 1.0e-10 ) return (low + high) * 0.5; - //return boost::uniform_real<>( low, high )( rcss::random::DefaultRNG::instance() ); - boost::uniform_real<> rng( low, high ); - boost::variate_generator< rcss::random::DefaultRNG &, boost::uniform_real<> > - gen( rcss::random::DefaultRNG::instance(), rng ); - return gen(); + + std::uniform_real_distribution<> rng( low, high ); + return rng( DefaultRNG::instance() ); } #endif diff --git a/src/rcsoccersim.in b/src/rcsoccersim.in index eaf247b9..ef90ffec 100755 --- a/src/rcsoccersim.in +++ b/src/rcsoccersim.in @@ -13,6 +13,19 @@ if [ x"$LIBPATH" != x ] ; then export LD_LIBRARY_PATH fi +#-------------------------------------------------- +# usage +# +usage() +{ + (echo "Usage: $0 [options]" + echo "Available options:" + echo " -help print this message" + echo " -rcssmonitor use rcssmonitor" + echo " -monitor MONITOR specify the monitor command" + ) 1>&2 +} + #-------------------------------------------------- # option # @@ -26,7 +39,8 @@ fi if test $# -eq 0; then if test "$RCSSMONITOR"; then - MON=`which "$RCSSMONITOR" 2> /dev/null` + MON="$RCSSMONITOR" + which ${MON%% *} > /dev/null 2>&1 if test $? -eq 1; then echo "Error: cannot find the monitor specified by RCSSMONITOR: $RCSSMONITOR" echo "" @@ -35,57 +49,49 @@ if test $# -eq 0; then else MON=`which rcssmonitor 2> /dev/null` if test $? -eq 1; then - MON=`which rcssmonitor_frameview 2> /dev/null` - if test $? -eq 1; then - MON=`which rcssmonitor_classic 2> /dev/null` - if test $? -eq 1; then - echo "Error: No monitors can be found in your PATH and the" - echo " RCSSMONITOR environment variable is not set. Please" - echo " add rcssmonitor or rcssmonitor_classic to you PATH," - echo " or set the RCSSMONITOR environment variable to the" - echo " executable you wish to use." - echo "" - exit 1 - fi - fi + echo "Error: No monitors can be found in your PATH and the" + echo " RCSSMONITOR environment variable is not set. Please" + echo " add rcssmonitor or a third party monitor to you PATH," + echo " or set the RCSSMONITOR environment variable to the" + echo " executable you wish to use." + echo "" + exit 1 fi fi else while [ $# -gt 0 ] do case $1 in + -help) + usage + exit 0 + ;; + -rcssmonitor) - MON=`which rcssmonitor 2> /dev/null` - if test $? -eq 1; then - echo "Error: rcssmonitor cannot be found in your PATH" - echo "" - exit 1 - fi - ;; - - -frameview) - MON=`which rcssmonitor_frameview 2> /dev/null` - if test $? -eq 1; then - echo "Error: rcssmonitor_frameview cannot be found in your PATH" - echo "" - exit 1 - fi - ;; - - -classic) - MON=`which rcssmonitor_classic 2> /dev/null` - if test $? -eq 1; then - echo "Error: rcssmonitor_classic cannot be found in your PATH" - echo "" - exit 1 - fi - ;; + MON=`which rcssmonitor 2> /dev/null` + if test $? -eq 1; then + echo "Error: rcssmonitor cannot be found in your PATH" + echo "" + exit 1 + fi + ;; + + -monitor) + MON="${2}" + which ${MON%% *} > /dev/null 2>&1 + if test $? -eq 1; then + echo "Error: ${MON%% *} cannot be found in your PATH" + echo "" + exit 1 + fi + shift 1 + ;; *) - echo "Error: unsupported option" - echo "Usage: $0 [(-frameview)|(-classic)]" - echo "" - ;; + echo "Error: unsupported option ${1}" + usage + exit 1 + ;; esac shift 1 diff --git a/src/rcssexceptions.cpp b/src/rcssexceptions.cpp index 98576db3..5fdbfb3f 100644 --- a/src/rcssexceptions.cpp +++ b/src/rcssexceptions.cpp @@ -25,11 +25,7 @@ #include "rcssexceptions.h" -#ifdef HAVE_SSTREAM #include -#else -#include -#endif namespace rcss { namespace util { @@ -38,16 +34,9 @@ NullErr::NullErr( const char * file, const int & line, const char * msg ) throw() { -#ifdef HAVE_SSTREAM std::ostringstream tmp; tmp << file << ": " << line << ": " << msg; M_msg = tmp.str(); -#else - std::ostrstream tmp; - tmp << file << ": " << line << ": " << msg << std::ends; - M_msg = tmp.str(); - tmp.freeze( false ); -#endif } } diff --git a/src/referee.cpp b/src/referee.cpp index b4f4922c..cdbb524c 100644 --- a/src/referee.cpp +++ b/src/referee.cpp @@ -25,6 +25,7 @@ #include "referee.h" +#include "logger.h" #include "stadium.h" #include "player.h" #include "team.h" @@ -32,12 +33,7 @@ #include #include - -#ifdef HAVE_SSTREAM #include -#else -#include -#endif namespace { const int CLEAR_PLAYER_TIME = 5; @@ -618,37 +614,34 @@ Referee::placePlayersInTheirField() && ( M_stadium.playmode() == PM_KickOff_Left || M_stadium.playmode() == PM_KickOff_Right ) ); - const Stadium::PlayerCont::iterator end = M_stadium.remotePlayers().end(); - for ( Stadium::PlayerCont::iterator it = M_stadium.remotePlayers().begin(); - it != end; - ++it ) + for ( Stadium::PlayerCont::reference p : M_stadium.remotePlayers() ) { - if ( ! (*it)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - switch ( (*it)->side() ) { + switch ( p->side() ) { case LEFT: - if ( (*it)->pos().x > 0 ) + if ( p->pos().x > 0 ) { if ( kick_off_offside ) { - (*it)->moveTo( PVector( -(*it)->size(), (*it)->pos().y ) ); + p->moveTo( PVector( -p->size(), p->pos().y ) ); } else { - (*it)->moveTo( fld_l.randomize() ); + p->moveTo( fld_l.randomize() ); } } break; case RIGHT: - if ( (*it)->pos().x < 0 ) + if ( p->pos().x < 0 ) { if ( kick_off_offside ) { - (*it)->moveTo( PVector( (*it)->size(), (*it)->pos().y ) ); + p->moveTo( PVector( p->size(), p->pos().y ) ); } else { - (*it)->moveTo( fld_r.randomize() ); + p->moveTo( fld_r.randomize() ); } } break; @@ -657,14 +650,14 @@ Referee::placePlayersInTheirField() break; } - if ( (*it)->side() != M_stadium.kickOffSide() ) + if ( p->side() != M_stadium.kickOffSide() ) { CArea expand_c( PVector( 0.0, 0.0 ), - ServerParam::KICK_OFF_CLEAR_DISTANCE + (*it)->size() ); + ServerParam::KICK_OFF_CLEAR_DISTANCE + p->size() ); - if ( expand_c.inArea( (*it)->pos() ) ) + if ( expand_c.inArea( p->pos() ) ) { - (*it)->moveTo( expand_c.nearestEdge( (*it)->pos() ) ); + p->moveTo( expand_c.nearestEdge( p->pos() ) ); } } } @@ -710,33 +703,30 @@ Referee::clearPlayersFromBall( const Side side ) = ( std::fabs( M_stadium.ball().pos().x ) > max_x - clear_dist && std::fabs( M_stadium.ball().pos().y ) > max_y - clear_dist ); - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); for ( int loop = 0; loop < 10; ++loop ) { bool exist = false; - for ( Stadium::PlayerCont::iterator it = M_stadium.players().begin(); - it != end; - ++it ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*it)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; if ( side == NEUTRAL - || (*it)->side() == side ) + || p->side() == side ) { if ( indirect - && std::fabs( (*it)->pos().x ) >= ServerParam::PITCH_LENGTH*0.5 ) + && std::fabs( p->pos().x ) >= ServerParam::PITCH_LENGTH*0.5 ) { // defender is allowed to stand on the goal line. continue; } CArea clear_area( M_stadium.ball().pos(), - clear_dist + (*it)->size() ); - if ( clear_area.inArea( (*it)->pos() ) ) + clear_dist + p->size() ); + if ( clear_area.inArea( p->pos() ) ) { CArea expand_clear_area( M_stadium.ball().pos(), - clear_dist + (*it)->size() + 1.0e-5 ); - PVector new_pos = expand_clear_area.nearestEdge( (*it)->pos() ); + clear_dist + p->size() + 1.0e-5 ); + PVector new_pos = expand_clear_area.nearestEdge( p->pos() ); if ( ball_at_corner && std::fabs( new_pos.x ) > ServerParam::PITCH_LENGTH*0.5 @@ -761,7 +751,7 @@ Referee::clearPlayersFromBall( const Side side ) if ( std::fabs( new_pos.x ) > max_x ) { - double r = clear_dist + (*it)->size(); + double r = clear_dist + p->size(); double theta = std::acos( ( max_x - std::fabs( M_stadium.ball().pos().x ) ) / r ); double tmp_y = std::fabs( r * std::sin( theta ) ); new_pos.x = ( new_pos.x < 0.0 ? -max_x : +max_x ); @@ -773,7 +763,7 @@ Referee::clearPlayersFromBall( const Side side ) if ( std::fabs( new_pos.y ) > max_y ) { - double r = clear_dist + (*it)->size(); + double r = clear_dist + p->size(); double theta = std::acos( ( max_y - std::fabs( M_stadium.ball().pos().y ) ) / r ); double tmp_x = std::fabs( r * std::sin( theta ) ); new_pos.x = ( M_stadium.ball().pos().x @@ -791,7 +781,7 @@ Referee::clearPlayersFromBall( const Side side ) new_pos += M_stadium.ball().pos(); } - (*it)->place( new_pos ); + p->place( new_pos ); exist = true; } } @@ -819,15 +809,11 @@ Referee::checkFoul( const Player & tackler, bool yellow_card = false; bool red_card = false; - boost::bernoulli_distribution<> rng( tackler.foulDetectProbability() ); - boost::variate_generator< rcss::random::DefaultRNG &, boost::bernoulli_distribution<> > - dst( rcss::random::DefaultRNG::instance(), rng ); + std::bernoulli_distribution dst( tackler.foulDetectProbability() ); // 2011-05-14 akiyama // added red card probability - boost::bernoulli_distribution<> red_rng( ServerParam::instance().redCardProbability() ); - boost::variate_generator< rcss::random::DefaultRNG &, boost::bernoulli_distribution<> > - red_dst( rcss::random::DefaultRNG::instance(), red_rng ); + std::bernoulli_distribution red_dst( ServerParam::instance().redCardProbability() ); const double ball_dist2 = tackler.pos().distance2( M_stadium.ball().pos() ); const double ball_angle = ( M_stadium.ball().pos() - tackler.pos() ).th(); @@ -836,60 +822,57 @@ Referee::checkFoul( const Player & tackler, // << " (tackler " << SideStr( tackler.side() ) << ' ' << tackler.unum() << ")" // << std::endl; - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; - if ( (*p)->side() == tackler.side() ) continue; + if ( ! p->isEnabled() ) continue; + if ( p->side() == tackler.side() ) continue; - if ( ! (*p)->ballKickable() ) continue; // no kickable + if ( ! p->ballKickable() ) continue; // no kickable bool pre_check = false; if ( foul ) { - (*p)->setFoulCharged(); + p->setFoulCharged(); - //std::cerr << "---->" << (*p)->unum() << " intentional foul. prob=" << rng.p() << std::endl; - if ( dst() ) + //std::cerr << "---->" << p->unum() << " intentional foul. prob=" << rng.p() << std::endl; + if ( dst( DefaultRNG::instance() ) ) { - //std::cerr << "----> " << (*p)->unum() << " detected intentional foul." << std::endl; + //std::cerr << "----> " << p->unum() << " detected intentional foul." << std::endl; pre_check = true; foul_charge = true; } } - if ( ! (*p)->dashed() ) + if ( ! p->dashed() ) { - //std::cerr << "----> " << (*p)->unum() << " no dash." << std::endl; + //std::cerr << "----> " << p->unum() << " no dash." << std::endl; continue; // no dashing } - PVector player_rel = (*p)->pos() - tackler.pos(); + PVector player_rel = p->pos() - tackler.pos(); if ( player_rel.r2() > ball_dist2 ) { - //std::cerr << "----> " << (*p)->unum() << " ball near." << std::endl; + //std::cerr << "----> " << p->unum() << " ball near." << std::endl; continue; // further than ball } - //std::cerr << "--> (player " << SideStr( (*p)->side() ) << ' ' << (*p)->unum() << ")\n"; + //std::cerr << "--> (player " << SideStr( p->side() ) << ' ' << p->unum() << ")\n"; player_rel.rotate( -ball_angle ); if ( player_rel.x < 0.0 - || std::fabs( player_rel.y ) > (*p)->size() + tackler.size() ) + || std::fabs( player_rel.y ) > p->size() + tackler.size() ) { - //std::cerr << "----> " << (*p)->unum() << " behind or big y_diff. rel=" << player_rel + //std::cerr << "----> " << p->unum() << " behind or big y_diff. rel=" << player_rel // << std::endl; continue; } - double body_diff = std::fabs( normalize_angle( (*p)->angleBodyCommitted() - ball_angle ) ); + double body_diff = std::fabs( normalize_angle( p->angleBodyCommitted() - ball_angle ) ); if ( body_diff > M_PI*0.5 ) { - //std::cerr << "----> " << (*p)->unum() << " over body angle. angle=" << body_diff / M_PI * 180.0 + //std::cerr << "----> " << p->unum() << " over body angle. angle=" << body_diff / M_PI * 180.0 // << std::endl; continue; } @@ -898,9 +881,9 @@ Referee::checkFoul( const Player & tackler, { if ( pre_check ) { - //std::cerr << "----> " << (*p)->unum() << " detected yellow_card." << std::endl; + //std::cerr << "----> " << p->unum() << " detected yellow_card." << std::endl; yellow_card = true; - if ( red_dst() ) + if ( red_dst( DefaultRNG::instance() ) ) { yellow_card = false; red_card = true; @@ -909,11 +892,11 @@ Referee::checkFoul( const Player & tackler, } else { - if ( dst() ) + if ( dst( DefaultRNG::instance() ) ) { - //std::cerr << "----> " << (*p)->unum() << " detected foul. prob=" << rng.p() << std::endl; + //std::cerr << "----> " << p->unum() << " detected foul. prob=" << rng.p() << std::endl; foul_charge = true; - if ( red_dst() ) + if ( red_dst( DefaultRNG::instance() ) ) { yellow_card = true; } @@ -1014,16 +997,13 @@ OffsideRef::checkIntentionalAction( const Player & kicker ) return; } - for ( std::vector< Candidate >::iterator it = M_offside_candidates.begin(), - end = M_offside_candidates.end(); - it != end; - ++it ) + for ( const Candidate & c : M_offside_candidates ) { - if ( it->player_ == &kicker - && it->player_->pos().distance2( M_stadium.ball().pos() ) + if ( c.player_ == &kicker + && c.player_->pos().distance2( M_stadium.ball().pos() ) < std::pow( ServerParam::instance().offsideActiveArea(), 2 ) ) { - M_offside_pos = it->pos_; + M_offside_pos = c.pos_; callOffside(); } } @@ -1110,19 +1090,16 @@ OffsideRef::analyse() { double dist2 = std::pow( ServerParam::instance().offsideActiveArea(), 2 ); - for ( std::vector< Candidate >::const_iterator it = M_offside_candidates.begin(), - end = M_offside_candidates.end(); - it != end; - ++it ) + for ( const Candidate & c : M_offside_candidates ) { - if ( ! it->player_->isEnabled() ) continue; + if ( ! c.player_->isEnabled() ) continue; - double tmp = it->player_->pos().distance2( M_stadium.ball().pos() ); + double tmp = c.player_->pos().distance2( M_stadium.ball().pos() ); if ( tmp < dist2 ) { found = true; dist2 = tmp; - M_offside_pos = it->pos_; + M_offside_pos = c.pos_; } } } @@ -1174,14 +1151,11 @@ OffsideRef::setOffsideMark( const Player & kicker, M_last_kick_accel_r = accel_r; } - for ( std::vector< Candidate >::iterator it = M_offside_candidates.begin(), - end = M_offside_candidates.end(); - it != end; - ++it ) + for ( const Candidate & c : M_offside_candidates ) { - if ( it->player_ == &kicker ) + if ( c.player_ == &kicker ) { - M_offside_pos = it->pos_; + M_offside_pos = c.pos_; callOffside(); return; } @@ -1199,25 +1173,21 @@ OffsideRef::setOffsideMark( const Player & kicker, return; } - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - double first = 0.0; double second = 0.0; double offside_line = 0.0; switch ( kicker.side() ) { case LEFT: - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == RIGHT ) + if ( p->side() == RIGHT ) { - if ( (*p)->pos().x > second ) + if ( p->pos().x > second ) { - second = (*p)->pos().x; + second = p->pos().x; if ( second > first ) { std::swap( first, second ); @@ -1235,33 +1205,29 @@ OffsideRef::setOffsideMark( const Player & kicker, offside_line = M_stadium.ball().pos().x; } - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == LEFT - && (*p)->pos().x > offside_line - && (*p)->unum() != kicker.unum() ) + if ( p->side() == LEFT + && p->pos().x > offside_line + && p->unum() != kicker.unum() ) { - M_offside_candidates.push_back( Candidate( *p, offside_line, (*p)->pos().y ) ); + M_offside_candidates.push_back( Candidate( p, offside_line, p->pos().y ) ); } } break; case RIGHT: - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == LEFT ) + if ( p->side() == LEFT ) { - if ( (*p)->pos().x < second ) + if ( p->pos().x < second ) { - second = (*p)->pos().x; + second = p->pos().x; if ( second < first ) { std::swap( first, second ); @@ -1279,17 +1245,15 @@ OffsideRef::setOffsideMark( const Player & kicker, offside_line = M_stadium.ball().pos().x; } - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == RIGHT - && (*p)->pos().x < offside_line - && (*p)->unum() != kicker.unum() ) + if ( p->side() == RIGHT + && p->pos().x < offside_line + && p->unum() != kicker.unum() ) { - M_offside_candidates.push_back( Candidate( *p, offside_line, (*p)->pos().y ) ); + M_offside_candidates.push_back( Candidate( p, offside_line, p->pos().y ) ); } } break; @@ -1401,30 +1365,27 @@ OffsideRef::checkPlayerAfterOffside() const CArea c( M_offside_pos, 2.5 ); const RArea fld( center, size ); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(), - end = M_stadium.players().end(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; - if ( (*p)->side() != offsideside ) continue; + if ( ! p->isEnabled() ) continue; + if ( p->side() != offsideside ) continue; - if ( c.inArea( (*p)->pos() ) ) + if ( c.inArea( p->pos() ) ) { - (*p)->moveTo( c.nearestEdge( (*p)->pos() ) ); + p->moveTo( c.nearestEdge( p->pos() ) ); } - if ( ! fld.inArea( (*p)->pos() )) + if ( ! fld.inArea( p->pos() )) { if ( M_stadium.playmode() == PM_OffSide_Right ) { - (*p)->moveTo( fld.nearestVEdge( (*p)->pos() ) - + PVector( ServerParam::instance().offsideKickMargin(), 0 ) ); + p->moveTo( fld.nearestVEdge( p->pos() ) + + PVector( ServerParam::instance().offsideKickMargin(), 0 ) ); } else { - (*p)->moveTo( fld.nearestVEdge( (*p)->pos() ) - - PVector( ServerParam::instance().offsideKickMargin(), 0 ) ); + p->moveTo( fld.nearestVEdge( p->pos() ) + - PVector( ServerParam::instance().offsideKickMargin(), 0 ) ); } } } @@ -1522,29 +1483,27 @@ IllegalDefenseRef::analyse() const double right_x = +ServerParam::PITCH_LENGTH * 0.5 - ServerParam::instance().illegalDefenseDistX(); const double half_width = ServerParam::instance().illegalDefenseWidth() * 0.5; - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(), end = M_stadium.players().end(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == LEFT + if ( p->side() == LEFT && M_last_kicker_side == RIGHT && M_stadium.ball().pos().x < 0.0 - && (*p)->pos().x < left_x - && std::fabs( (*p)->pos().y ) < half_width ) + && p->pos().x < left_x + && std::fabs( p->pos().y ) < half_width ) { left_player_illegal += 1; - (*p)->addState( ILLEGAL_DEFENSE ); + p->addState( ILLEGAL_DEFENSE ); } - else if ( (*p)->side() == RIGHT + else if ( p->side() == RIGHT && M_last_kicker_side == LEFT && M_stadium.ball().pos().x > 0.0 - && (*p)->pos().x > right_x - && std::fabs( (*p)->pos().y ) < half_width ) + && p->pos().x > right_x + && std::fabs( p->pos().y ) < half_width ) { right_player_illegal += 1; - (*p)->addState( ILLEGAL_DEFENSE ); + p->addState( ILLEGAL_DEFENSE ); } } @@ -1556,11 +1515,9 @@ IllegalDefenseRef::analyse() { M_left_illegal_counter = 0; - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(), end = M_stadium.players().end(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( (*p)->side() == LEFT ) (*p)->removeState( ILLEGAL_DEFENSE ); + if ( p->side() == LEFT ) p->removeState( ILLEGAL_DEFENSE ); } } @@ -1572,11 +1529,9 @@ IllegalDefenseRef::analyse() { M_right_illegal_counter = 0; - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(), end = M_stadium.players().end(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( (*p)->side() == RIGHT ) (*p)->removeState( ILLEGAL_DEFENSE ); + if ( p->side() == RIGHT ) p->removeState( ILLEGAL_DEFENSE ); } } @@ -2091,24 +2046,21 @@ FreeKickRef::placePlayersForGoalkick() p_area = &p_r; } - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == oppside ) + if ( p->side() == oppside ) { - const double size = (*p)->size(); + const double size = p->size(); RArea expand_area( p_area->left() - size, p_area->right() + size, p_area->top() - size, p_area->bottom() + size ); - if ( expand_area.inArea( (*p)->pos() ) ) + if ( expand_area.inArea( p->pos() ) ) { - PVector new_pos = expand_area.nearestEdge( (*p)->pos() ); + PVector new_pos = expand_area.nearestEdge( p->pos() ); if ( new_pos.x * oppside >= ServerParam::PITCH_LENGTH/2 ) { new_pos.x @@ -2118,7 +2070,7 @@ FreeKickRef::placePlayersForGoalkick() * oppside; } - (*p)->moveTo( new_pos ); + p->moveTo( new_pos ); } } } @@ -2182,7 +2134,7 @@ TouchRef::analyseImpl() { // check for goal kick or corner kick Side side = NEUTRAL; - if ( M_last_touched != NULL ) + if ( M_last_touched ) { side = M_last_touched->side(); } @@ -2195,7 +2147,7 @@ TouchRef::analyseImpl() { awardCornerKick( LEFT, M_stadium.ball().pos() ); } - else if ( M_stadium.ballCatcher() == NULL ) + else if ( ! M_stadium.ballCatcher() ) { awardGoalKick( RIGHT, M_stadium.ball().pos() ); } @@ -2215,7 +2167,7 @@ TouchRef::analyseImpl() { awardCornerKick( RIGHT, M_stadium.ball().pos() ); } - else if ( M_stadium.ballCatcher() == NULL ) + else if ( ! M_stadium.ballCatcher() ) { awardGoalKick( LEFT, M_stadium.ball().pos() ); } @@ -2235,7 +2187,7 @@ TouchRef::analyseImpl() // check for kick in. Side side = NEUTRAL; - if ( M_last_touched != NULL ) + if ( M_last_touched ) { side = M_last_touched->side(); } @@ -2264,7 +2216,7 @@ TouchRef::kickTaken( const Player & kicker, && M_last_indirect_kicker && M_last_indirect_kicker != &kicker ) { - M_last_indirect_kicker = NULL; + M_last_indirect_kicker = nullptr; M_indirect_mode = false; } @@ -2307,7 +2259,7 @@ TouchRef::ballTouched( const Player & kicker ) && M_last_indirect_kicker && M_last_indirect_kicker != &kicker ) { - M_last_indirect_kicker = NULL; + M_last_indirect_kicker = nullptr; M_indirect_mode = false; } @@ -2337,17 +2289,17 @@ TouchRef::playModeChange( PlayMode pm ) { if ( pm != PM_PlayOn ) { - M_last_touched = NULL; + M_last_touched = nullptr; } if ( indirectFreeKick( pm ) ) { - M_last_indirect_kicker = NULL; + M_last_indirect_kicker = nullptr; M_indirect_mode = true; } else if ( pm != PM_PlayOn && pm != PM_Drop_Ball ) { - M_last_indirect_kicker = NULL; + M_last_indirect_kicker = nullptr; M_indirect_mode = false; } } @@ -2434,16 +2386,9 @@ TouchRef::checkGoal() void TouchRef::announceGoal( const Team & team ) { -#ifdef HAVE_SSTREAM std::ostringstream msg; msg << "goal_" << SideStr( team.side() ) << "_" << team.point(); M_stadium.sendRefereeAudio( msg.str().c_str() ); -#else - std::ostrstream msg; - msg << "goal_" << SideStr( team.side() ) << "_" << team.point() << std::ends; - M_stadium.say( msg.str() ); - msg.freeze( false ); -#endif } @@ -2481,8 +2426,8 @@ CatchRef::kickTaken( const Player & kicker, if ( M_team_l_touched && M_team_r_touched ) { - M_last_back_passer = NULL; - M_before_last_back_passer = NULL; + M_last_back_passer = nullptr; + M_before_last_back_passer = nullptr; return; } @@ -2524,8 +2469,8 @@ CatchRef::ballTouched( const Player & player ) if ( M_team_l_touched && M_team_r_touched ) { - M_before_last_back_passer = NULL; - M_last_back_passer = NULL; + M_before_last_back_passer = nullptr; + M_last_back_passer = nullptr; } } @@ -2552,17 +2497,17 @@ CatchRef::ballCaught( const Player & catcher ) && M_stadium.playmode() != PM_AfterGoal_Left && M_stadium.playmode() != PM_AfterGoal_Right && M_stadium.playmode() != PM_TimeOver - && M_last_back_passer != NULL + && M_last_back_passer && M_last_back_passer->team() == catcher.team() ) { if ( M_last_back_passer == &catcher - && M_before_last_back_passer != NULL + && M_before_last_back_passer && M_before_last_back_passer->team() != catcher.team() ) { // no backpass violation, if last kicker is goalie itself and before kicker is opponent } else if ( M_stadium.time() == M_last_back_passer_time - && ( M_before_last_back_passer == NULL + && ( ! M_before_last_back_passer || M_before_last_back_passer->team() != catcher.team() ) ) { // no backpass violation. kick and catch are taken simultaneously @@ -2578,8 +2523,8 @@ CatchRef::ballCaught( const Player & catcher ) } } - M_last_back_passer = NULL; - M_before_last_back_passer = NULL; + M_last_back_passer = nullptr; + M_before_last_back_passer = nullptr; awardFreeKick( catcher.side(), M_stadium.ball().pos() ); } @@ -2608,7 +2553,7 @@ CatchRef::ballPunched( const Player & catcher ) && M_stadium.playmode() != PM_AfterGoal_Right && M_stadium.playmode() != PM_TimeOver && M_stadium.time() != M_last_back_passer_time - && M_last_back_passer != NULL + && M_last_back_passer && M_last_back_passer->team() == catcher.team() && ServerParam::instance().backPasses() ) { @@ -2629,8 +2574,8 @@ CatchRef::ballPunched( const Player & catcher ) return; } - M_last_back_passer = NULL; - M_before_last_back_passer = NULL; + M_last_back_passer = nullptr; + M_before_last_back_passer = nullptr; } @@ -2738,8 +2683,8 @@ CatchRef::playModeChange( PlayMode pmode ) { if ( pmode != PM_PlayOn ) { - M_before_last_back_passer = NULL; - M_last_back_passer = NULL; + M_before_last_back_passer = nullptr; + M_last_back_passer = nullptr; } if ( pmode == PM_Back_Pass_Left @@ -2774,7 +2719,7 @@ CatchRef::callBackPass( const Side side ) M_stadium.placeBall( PM_Back_Pass_Right, LEFT, pos ); } - M_last_back_passer = NULL; + M_last_back_passer = nullptr; M_after_back_pass_time = 0; } @@ -2980,7 +2925,7 @@ KeepawayRef::analyse() return; } - static time_t s_start_time = std::time( NULL ); + static time_t s_start_time = std::time( nullptr ); if ( M_stadium.playmode() == PM_PlayOn ) { @@ -3000,23 +2945,20 @@ KeepawayRef::analyse() { bool keeper_poss = false; - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - PVector ppos = (*p)->pos(); + PVector ppos = p->pos(); if ( ppos.distance2( M_stadium.ball().pos() ) < std::pow( ServerParam::instance().kickableArea(), 2 ) ) { - if ( (*p)->side() == LEFT ) + if ( p->side() == LEFT ) { keeper_poss = true; } - else if ( (*p)->side() == RIGHT ) + else if ( p->side() == RIGHT ) { keeper_poss = false; ++M_take_time; @@ -3033,7 +2975,7 @@ KeepawayRef::analyse() } else if ( ServerParam::instance().kawayStart() >= 0 ) { - if ( difftime( std::time( NULL ), s_start_time ) > ServerParam::instance().kawayStart() ) + if ( difftime( std::time( nullptr ), s_start_time ) > ServerParam::instance().kawayStart() ) { M_stadium.changePlayMode( PM_PlayOn ); } @@ -3049,18 +2991,15 @@ KeepawayRef::playModeChange( PlayMode pm ) { M_episode = 1; - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == LEFT ) + if ( p->side() == LEFT ) { ++M_keepers; } - else if ( (*p)->side() == RIGHT ) + else if ( p->side() == RIGHT ) { ++M_takers; } @@ -3083,38 +3022,15 @@ KeepawayRef::ballInKeepawayArea() void KeepawayRef::logHeader() { - if ( M_stadium.logger().kawayLog() ) - { - M_stadium.logger().kawayLog() << "# Keepers: " << M_keepers << '\n' - << "# Takers: " << M_takers << '\n' - << "# Region: " << ServerParam::instance().keepAwayLength() - << " x " << ServerParam::instance().keepAwayWidth() - << '\n' - << "#\n" - << "# Description of Fields:\n" - << "# 1) Episode number\n" - << "# 2) Start time in simulator steps (100ms)\n" - << "# 3) End time in simulator steps (100ms)\n" - << "# 4) Duration in simulator steps (100ms)\n" - << "# 5) (o)ut of bounds / (t)aken away\n" - << "#\n" - << std::flush; - } + Logger::instance().writeKeepawayHeader( M_keepers, M_takers ); } void -KeepawayRef::logEpisode( const char * endCond ) +KeepawayRef::logEpisode( const char * end_cond ) { - if ( M_stadium.logger().kawayLog() ) - { - M_stadium.logger().kawayLog() << M_episode++ << "\t" - << M_time << "\t" - << M_stadium.time() << "\t" - << M_stadium.time() - M_time << "\t" - << endCond - << std::endl; - } + Logger::instance().writeKeepawayLog( M_stadium, M_episode, M_time, end_cond ); + ++M_episode; M_time = M_stadium.time(); } @@ -3124,15 +3040,12 @@ KeepawayRef::resetField() int keeper_pos = irand( M_keepers ); //int keeper_pos = boost::uniform_smallint<>( 0, M_keepers - 1 )( rcss::random::DefaultRNG::instance() ); - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; double x, y; - if ( (*p)->side() == LEFT ) + if ( p->side() == LEFT ) { switch( keeper_pos ) { case 0: @@ -3152,16 +3065,16 @@ KeepawayRef::resetField() break; } - (*p)->place( PVector( x, y ) ); + p->place( PVector( x, y ) ); keeper_pos = ( keeper_pos + 1 ) % M_keepers; } - else if ( (*p)->side() == RIGHT ) + else if ( p->side() == RIGHT ) { x = -ServerParam::instance().keepAwayLength() * 0.5 + drand( 0, 3 ); y = ServerParam::instance().keepAwayWidth() * 0.5 - drand( 0, 3 ); - (*p)->place( PVector( x, y ) ); + p->place( PVector( x, y ) ); } } @@ -3184,7 +3097,7 @@ PenaltyRef::PenaltyRef( Stadium& stadium ) M_pen_nr_taken( 0 ), M_bDebug( false ), M_cur_pen_taker( NEUTRAL ), - M_last_taker( NULL ), + M_last_taker( nullptr ), M_prev_ball_pos( 0.0, 0.0 ), M_timeover( false ) { @@ -3241,18 +3154,15 @@ PenaltyRef::startPenaltyShootout() // place the goalkeeper of the opposite field close to the penalty goal // otherwise it is hard to get there before pen_setup_wait cycles Side side = ( M_pen_side == LEFT ) ? RIGHT : LEFT; - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(); - p != end; - ++p ) - { - if ( (*p)->isEnabled() - && (*p)->side() == side - && (*p)->isGoalie() ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) + { + if ( p->isEnabled() + && p->side() == side + && p->isGoalie() ) { - (*p)->moveTo( PVector( -M_pen_side - * (ServerParam::PITCH_LENGTH/2-10), - 10 ) ); + p->moveTo( PVector( -M_pen_side + * (ServerParam::PITCH_LENGTH/2-10), + 10 ) ); } } @@ -3563,7 +3473,7 @@ PenaltyRef::kickTaken( const Player & kicker, return; } - if ( M_stadium.ballCatcher() != NULL ) + if ( M_stadium.ballCatcher() ) { std::cerr << "player kicked and goalie catched at the same time" << std::endl; } @@ -3705,12 +3615,12 @@ PenaltyRef::playModeChange( PlayMode pm ) if ( pm == PM_PenaltySetup_Left || pm == PM_PenaltySetup_Right ) { - M_last_taker = NULL; + M_last_taker = nullptr; M_timer = ServerParam::instance().penSetupWait(); } else if ( pm == PM_PenaltyReady_Left || pm == PM_PenaltyReady_Right ) { - M_last_taker = NULL; + M_last_taker = nullptr; M_timer = ServerParam::instance().penReadyWait(); } else if ( pm == PM_PenaltyTaken_Left || pm == PM_PenaltyTaken_Right ) @@ -3720,12 +3630,12 @@ PenaltyRef::playModeChange( PlayMode pm ) else if ( pm == PM_PenaltyMiss_Left || pm == PM_PenaltyMiss_Right || pm == PM_PenaltyScore_Left || pm == PM_PenaltyScore_Right ) { - M_last_taker = NULL; + M_last_taker = nullptr; M_timer = ServerParam::instance().penBeforeSetupWait(); } else { - M_last_taker = NULL; + M_last_taker = nullptr; } } @@ -3930,8 +3840,8 @@ PenaltyRef::penalty_check_players( const Side side ) bool bCheck = true; PVector posGoalie; //int iPlayerOutside = -1, iGoalieNr=-1; - const Player * outside_player = NULL; - const Player * goalie = NULL; + const Player * outside_player = nullptr; + const Player * goalie = nullptr; if ( pm == PM_PenaltyMiss_Left || pm == PM_PenaltyMiss_Right || pm == PM_PenaltyScore_Left || pm == PM_PenaltyScore_Right ) @@ -3941,29 +3851,26 @@ PenaltyRef::penalty_check_players( const Side side ) // for all players from side 'side' get the goalie pos and count how many // players are outside the center circle. - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == side ) + if ( p->side() == side ) { - if ( (*p)->isGoalie() ) + if ( p->isGoalie() ) { - goalie = *p; - posGoalie = (*p)->pos(); + goalie = p; + posGoalie = p->pos(); continue; } CArea c( PVector( 0.0, 0.0 ), ServerParam::KICK_OFF_CLEAR_DISTANCE - - (*p)->size() ); - if ( ! c.inArea( (*p)->pos() ) ) + - p->size() ); + if ( ! c.inArea( p->pos() ) ) { iOutsideCircle++; - outside_player = *p; + outside_player = p; } } } @@ -4097,16 +4004,13 @@ PenaltyRef::placeTakerTeamPlayers() const PVector goalie_wait_pos_t( -M_pen_side * ( ServerParam::PITCH_LENGTH / 2 + 2.0 ), -25.0 ); // then replace the players from the specified side - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() != M_cur_pen_taker ) continue; + if ( p->side() != M_cur_pen_taker ) continue; - if ( (*p) == taker ) + if ( p == taker ) { if ( ! bPenTaken && taker->pos().distance( M_stadium.ball().pos() ) > 2.0 ) @@ -4114,32 +4018,32 @@ PenaltyRef::placeTakerTeamPlayers() //PVector new_pos( -M_pen_side * ( ServerParam::PITCH_LENGTH/2 - ServerParam::instance().pen_dist_x - 2.0 ), //0.0 ); CArea c( M_stadium.ball().pos(), 2.0 ); - //(*p)->moveTo( new_pos ); - (*p)->moveTo( c.nearestEdge( taker->pos() ) ); + //p->moveTo( new_pos ); + p->moveTo( c.nearestEdge( taker->pos() ) ); } } else { - if ( (*p)->isGoalie() ) + if ( p->isGoalie() ) { - CArea c( ( (*p)->pos().y > 0.0 ? goalie_wait_pos_b : goalie_wait_pos_t ), + CArea c( ( p->pos().y > 0.0 ? goalie_wait_pos_b : goalie_wait_pos_t ), 2.0 ); - if ( ! c.inArea( (*p)->pos() ) ) + if ( ! c.inArea( p->pos() ) ) { - (*p)->moveTo( c.nearestEdge( (*p)->pos() ) ); + p->moveTo( c.nearestEdge( p->pos() ) ); } } else // not goalie { CArea center( PVector( 0.0, 0.0 ), ServerParam::KICK_OFF_CLEAR_DISTANCE - - (*p)->size() + - p->size() //- ServerParam::instance().pspeed_max ); - if ( ! center.inArea( (*p)->pos() ) ) + if ( ! center.inArea( p->pos() ) ) { - //(*p)->moveTo( PVector::fromPolar( 6.5, Deg2Rad( i*15 ) ) ); - (*p)->moveTo( center.nearestEdge( (*p)->pos() ) ); + //p->moveTo( PVector::fromPolar( 6.5, Deg2Rad( i*15 ) ) ); + p->moveTo( center.nearestEdge( p->pos() ) ); } } } @@ -4156,32 +4060,29 @@ PenaltyRef::placeOtherTeamPlayers() ? - ServerParam::PITCH_LENGTH/2.0 + ServerParam::instance().penMaxGoalieDistX() : + ServerParam::PITCH_LENGTH/2.0 - ServerParam::instance().penMaxGoalieDistX() ); - const Stadium::PlayerCont::iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() == M_cur_pen_taker ) continue; + if ( p->side() == M_cur_pen_taker ) continue; // only move goalie in case the penalty has not been started yet. - if ( (*p)->isGoalie() ) + if ( p->isGoalie() ) { if ( ! bPenTaken ) { if ( M_pen_side == LEFT ) { - if ( (*p)->pos().x - goalie_line > 0.0 ) + if ( p->pos().x - goalie_line > 0.0 ) { - (*p)->moveTo( PVector( goalie_line - 1.5, 0.0 ) ); + p->moveTo( PVector( goalie_line - 1.5, 0.0 ) ); } } else { - if ( (*p)->pos().x - goalie_line < 0.0 ) + if ( p->pos().x - goalie_line < 0.0 ) { - (*p)->moveTo( PVector( goalie_line + 1.5, 0.0 ) ); + p->moveTo( PVector( goalie_line + 1.5, 0.0 ) ); } } } @@ -4190,14 +4091,14 @@ PenaltyRef::placeOtherTeamPlayers() { CArea center( PVector( 0.0, 0.0 ), ServerParam::KICK_OFF_CLEAR_DISTANCE - - (*p)->size() + - p->size() //- ServerParam::instance().pspeed_max ); - if ( ! center.inArea( (*p)->pos() ) ) + if ( ! center.inArea( p->pos() ) ) { // place other players in circle in penalty area - //(*p)->moveTo( PVector::fromPolar( 6.5, Deg2Rad( i*15 ) ) ); - (*p)->moveTo( center.nearestEdge( (*p)->pos() ) ); + //p->moveTo( PVector::fromPolar( 6.5, Deg2Rad( i*15 ) ) ); + p->moveTo( center.nearestEdge( p->pos() ) ); } } } @@ -4210,21 +4111,18 @@ PenaltyRef::getCandidateTaker() ? M_sLeftPenTaken : M_sRightPenTaken ); - const Player * candidate = NULL; - const Player * goalie = NULL; + const Player * candidate = nullptr; + const Player * goalie = nullptr; double min_dist2 = std::numeric_limits< double >::max(); // first find the closest player to the ball - const Stadium::PlayerCont::const_iterator end = M_stadium.players().end(); - for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : M_stadium.players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - if ( (*p)->side() != M_cur_pen_taker ) continue; + if ( p->side() != M_cur_pen_taker ) continue; - if ( sPenTaken.find( (*p)->unum() ) + if ( sPenTaken.find( p->unum() ) != sPenTaken.end() ) { // players that have already taken a kick cannot be @@ -4232,21 +4130,21 @@ PenaltyRef::getCandidateTaker() continue; } - if ( (*p)->isGoalie() ) + if ( p->isGoalie() ) { - goalie = (*p); + goalie = p; continue; } - double d2 = (*p)->pos().distance2( M_stadium.ball().pos() ); + double d2 = p->pos().distance2( M_stadium.ball().pos() ); if( d2 < min_dist2 ) { min_dist2 = d2; - candidate = (*p); + candidate = p; } } - if ( candidate == NULL ) + if ( ! candidate ) { return goalie; } diff --git a/src/referee.h b/src/referee.h index 68468f69..cd65bb4d 100644 --- a/src/referee.h +++ b/src/referee.h @@ -39,17 +39,17 @@ class Team; class Referee { private: // not used - Referee(); - const Referee & operator=( const Referee & ); + Referee() = delete; + const Referee & operator=( const Referee & ) = delete; protected: Stadium & M_stadium; -public: explicit Referee( Stadium & stadium ) : M_stadium( stadium ) { } +public: virtual ~Referee() @@ -90,139 +90,139 @@ class Referee { // // - static - void doAnalyse( Referee * ref ) - { - ref->analyse(); - } + // static + // void doAnalyse( Referee * ref ) + // { + // ref->analyse(); + // } // // // - class doKickTaken { - private: - const Player & M_kicker; - const double M_accel_r; - public: - doKickTaken( const Player & kicker, - const double accel_r ) - : M_kicker( kicker ), - M_accel_r( accel_r ) - { } - - void operator()( Referee * ref ) - { - ref->kickTaken( M_kicker, M_accel_r ); - } - }; - - class doFailedKickTaken { - private: - const Player & M_kicker; - public: - doFailedKickTaken( const Player & kicker ) - : M_kicker( kicker ) - { } - - void operator()( Referee * ref ) - { - ref->failedKickTaken( M_kicker ); - } - }; - - class doTackleTaken { - private: - const Player & M_tackler; - const double M_accel_r; - const bool M_foul; - public: - doTackleTaken( const Player & tackler, - const double accel_r, - const bool foul ) - : M_tackler( tackler ), - M_accel_r( accel_r ), - M_foul( foul ) - { } - - void operator()( Referee * ref ) - { - ref->tackleTaken( M_tackler, M_accel_r, M_foul ); - } - }; - - class doFailedTackleTaken { - private: - const Player & M_tackler; - const bool M_foul; - public: - doFailedTackleTaken( const Player & tackler, - const bool foul ) - : M_tackler( tackler ), - M_foul( foul ) - { } - - void operator()( Referee * ref ) - { - ref->failedTackleTaken( M_tackler, M_foul ); - } - }; - - class doCaughtBall { - private: - const Player & M_catcher; - public: - doCaughtBall( const Player & catcher ) - : M_catcher( catcher ) - { } - - void operator()( Referee * ref ) - { - ref->ballCaught( M_catcher ); - } - }; - - class doPunchedBall { - private: - const Player & M_goalie; - public: - doPunchedBall( const Player & goalie ) - : M_goalie( goalie ) - { } - - void operator()( Referee * ref ) - { - ref->ballPunched( M_goalie ); - } - }; - - class doPlayModeChange { - private: - PlayMode M_pm; - public: - doPlayModeChange( PlayMode pm ) - : M_pm( pm ) - { } - - void operator()( Referee * ref ) - { - ref->playModeChange( M_pm ); - } - }; - - class doBallTouched { - private: - const Player & M_player; - public: - doBallTouched( const Player & player ) - : M_player( player ) - { } - - void operator()( Referee * ref ) - { - ref->ballTouched( M_player ); - } - }; + // class doKickTaken { + // private: + // const Player & M_kicker; + // const double M_accel_r; + // public: + // doKickTaken( const Player & kicker, + // const double accel_r ) + // : M_kicker( kicker ), + // M_accel_r( accel_r ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->kickTaken( M_kicker, M_accel_r ); + // } + // }; + + // class doFailedKickTaken { + // private: + // const Player & M_kicker; + // public: + // doFailedKickTaken( const Player & kicker ) + // : M_kicker( kicker ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->failedKickTaken( M_kicker ); + // } + // }; + + // class doTackleTaken { + // private: + // const Player & M_tackler; + // const double M_accel_r; + // const bool M_foul; + // public: + // doTackleTaken( const Player & tackler, + // const double accel_r, + // const bool foul ) + // : M_tackler( tackler ), + // M_accel_r( accel_r ), + // M_foul( foul ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->tackleTaken( M_tackler, M_accel_r, M_foul ); + // } + // }; + + // class doFailedTackleTaken { + // private: + // const Player & M_tackler; + // const bool M_foul; + // public: + // doFailedTackleTaken( const Player & tackler, + // const bool foul ) + // : M_tackler( tackler ), + // M_foul( foul ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->failedTackleTaken( M_tackler, M_foul ); + // } + // }; + + // class doCaughtBall { + // private: + // const Player & M_catcher; + // public: + // doCaughtBall( const Player & catcher ) + // : M_catcher( catcher ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->ballCaught( M_catcher ); + // } + // }; + + // class doPunchedBall { + // private: + // const Player & M_goalie; + // public: + // doPunchedBall( const Player & goalie ) + // : M_goalie( goalie ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->ballPunched( M_goalie ); + // } + // }; + + // class doPlayModeChange { + // private: + // PlayMode M_pm; + // public: + // doPlayModeChange( PlayMode pm ) + // : M_pm( pm ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->playModeChange( M_pm ); + // } + // }; + + // class doBallTouched { + // private: + // const Player & M_player; + // public: + // doBallTouched( const Player & player ) + // : M_player( player ) + // { } + + // void operator()( Referee * ref ) + // { + // ref->ballTouched( M_player ); + // } + // }; protected: @@ -341,33 +341,33 @@ class BallStuckRef { } void kickTaken( const Player &, - const double ) + const double ) override { } - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player &, const double, - const bool ) + const bool ) override { } void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & ) + void ballTouched( const Player & ) override { } - void analyse(); + void analyse() override; - void playModeChange( PlayMode ) + void playModeChange( PlayMode ) override { } }; @@ -416,28 +416,28 @@ class OffsideRef { } void kickTaken( const Player & kicker, - const double accel_r ); + const double accel_r ) override; - void failedKickTaken( const Player & kicker ); + void failedKickTaken( const Player & kicker ) override; void tackleTaken( const Player & tackler, const double accel_r, - const bool foul ); + const bool foul ) override; void failedTackleTaken( const Player & kicker, - const bool ); + const bool ) override; - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & player ); + void ballTouched( const Player & player ) override; - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: @@ -474,31 +474,31 @@ class IllegalDefenseRef { } void kickTaken( const Player & kicker, - const double accel_r); + const double accel_r) override; - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player & tackler, const double accel_r, - const bool foul); + const bool foul) override; void failedTackleTaken( const Player & , - const bool ) + const bool ) override { } - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & ) + void ballTouched( const Player & ) override { } - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: @@ -534,34 +534,34 @@ class FreeKickRef {} virtual - ~FreeKickRef() + ~FreeKickRef() override { } void kickTaken( const Player & kicker, - const double accel_r ); + const double accel_r ) override; - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player & kicker, const double accel_r, - const bool foul ); + const bool foul ) override; void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & player ); + void ballTouched( const Player & player ) override; - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: @@ -602,10 +602,10 @@ class TouchRef public: TouchRef( Stadium& stadium ) : Referee( stadium ), - M_last_touched( NULL ), + M_last_touched( nullptr ), M_last_touched_time( 0 ), M_last_touched_accel_r( 0.0 ), - M_last_indirect_kicker( NULL ), + M_last_indirect_kicker( nullptr ), M_indirect_mode( false ), M_after_goal_time( 0 ), M_prev_ball_pos( 0.0, 0.0 ) @@ -616,30 +616,30 @@ class TouchRef {} void kickTaken( const Player & kicker, - const double accel_r ); + const double accel_r ) override; - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player & kicker, const double accel_r, - const bool foul ); + const bool foul ) override; void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & player ); + void ballTouched( const Player & player ) override; - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: @@ -691,8 +691,8 @@ class CatchRef : Referee( stadium ), M_last_back_passer_time( 0 ), M_last_back_passer_accel_r( 0.0 ), - M_last_back_passer( NULL ), - M_before_last_back_passer( NULL ), + M_last_back_passer( nullptr ), + M_before_last_back_passer( nullptr ), M_team_l_touched( false ), M_team_r_touched( false ), M_after_back_pass_time( 0 ), @@ -704,28 +704,28 @@ class CatchRef { } void kickTaken( const Player & kicker, - const double accel_r ); + const double accel_r ) override; - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player & kicker, const double accel_r, - const bool foul ); + const bool foul ) override; void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & catcher ); + void ballCaught( const Player & catcher ) override; - void ballPunched( const Player & catcher ); + void ballPunched( const Player & catcher ) override; - void ballTouched( const Player & player ); + void ballTouched( const Player & player ) override; - void analyse(); + void analyse() override; - void playModeChange( PlayMode pmode ); + void playModeChange( PlayMode pmode ) override; private: @@ -754,36 +754,36 @@ class FoulRef { } virtual - ~FoulRef() + ~FoulRef() override { } void kickTaken( const Player &, - const double ) + const double ) override { } - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player & tackler, const double accel_r, - const bool foul ); + const bool foul ) override; void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & ) + void ballTouched( const Player & ) override { } - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: @@ -808,37 +808,37 @@ class KeepawayRef KeepawayRef( Stadium & stadium ); virtual - ~KeepawayRef() + ~KeepawayRef() override { } void kickTaken( const Player &, - const double ) + const double ) override { } - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player &, const double, - const bool ) + const bool ) override { } void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & ) + void ballCaught( const Player & ) override { } - void ballPunched( const Player & ) + void ballPunched( const Player & ) override { } - void ballTouched( const Player & ) + void ballTouched( const Player & ) override { } - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: bool ballInKeepawayArea(); @@ -872,33 +872,33 @@ class PenaltyRef PenaltyRef( Stadium& stadium ); virtual - ~PenaltyRef() + ~PenaltyRef() override { } void kickTaken( const Player & kicker, - const double accel_r ); + const double accel_r ) override; - void failedKickTaken( const Player & ) + void failedKickTaken( const Player & ) override { } void tackleTaken( const Player & tackler, const double accel_r, - const bool foul ); + const bool foul ) override; void failedTackleTaken( const Player &, - const bool ) + const bool ) override { } - void ballCaught( const Player & catcher ); + void ballCaught( const Player & catcher ) override; - void ballPunched( const Player & catcher ); + void ballPunched( const Player & catcher ) override; - void ballTouched( const Player & ) + void ballTouched( const Player & ) override { } - void analyse(); + void analyse() override; - void playModeChange( PlayMode pm ); + void playModeChange( PlayMode pm ) override; private: diff --git a/src/remoteclient.cpp b/src/remoteclient.cpp index 29d2d940..b3e69c16 100644 --- a/src/remoteclient.cpp +++ b/src/remoteclient.cpp @@ -26,10 +26,10 @@ #include "remoteclient.h" #include "param.h" -#include "rcssexceptions.h" +//#include "rcssexceptions.h" -#include -#include +#include +#include #include #include @@ -37,9 +37,9 @@ RemoteClient::RemoteClient() : M_socket() - , M_socket_buf( NULL ) - , M_gz_buf( NULL ) - , M_transport( NULL ) + , M_socket_buf( nullptr ) + , M_gz_buf( nullptr ) + , M_transport( nullptr ) , M_comp_level( -1 ) , M_enforce_dedicated_port( false ) { @@ -61,7 +61,8 @@ RemoteClient::getTransport() } else { - throw rcss::util::NullErr( __FILE__, __LINE__, "Transport is NULL" ); + //throw rcss::util::NullErr( __FILE__, __LINE__, "Transport is NULL" ); + throw std::logic_error( "Transport is NULL" ); } } @@ -73,19 +74,19 @@ RemoteClient::close() if ( M_transport ) { delete M_transport; - M_transport = NULL; + M_transport = nullptr; } if ( M_gz_buf ) { delete M_gz_buf; - M_gz_buf = NULL; + M_gz_buf = nullptr; } if ( M_socket_buf ) { delete M_socket_buf; - M_socket_buf = NULL; + M_socket_buf = nullptr; } setEnforceDedicatedPort( false ); diff --git a/src/remoteclient.h b/src/remoteclient.h index 11dc46b7..a2606965 100644 --- a/src/remoteclient.h +++ b/src/remoteclient.h @@ -24,7 +24,7 @@ #include "compress.h" -#include +#include namespace rcss { namespace net { diff --git a/src/resultsaver.hpp b/src/resultsaver.hpp index 75fcedb8..ee66443e 100644 --- a/src/resultsaver.hpp +++ b/src/resultsaver.hpp @@ -22,12 +22,11 @@ #ifndef RCSSRESULTSAVER_HPP #define RCSSRESULTSAVER_HPP -#include +#include #include #include - -struct tm; +#include class ResultSaver { public: @@ -62,7 +61,7 @@ class ResultSaver { doSaveStart(); } - void saveTime( const tm & time ) + void saveTime( const std::time_t time ) { doSaveTime( time ); } @@ -125,7 +124,7 @@ class ResultSaver { { } virtual - void doSaveTime( const tm & ) + void doSaveTime( const std::time_t ) { } virtual diff --git a/src/serializer.h b/src/serializer.h index 027ea573..d54d5220 100644 --- a/src/serializer.h +++ b/src/serializer.h @@ -24,7 +24,7 @@ #include "types.h" -#include +#include #include #include @@ -32,6 +32,7 @@ class Ball; class PVector; class Player; +class HeteroPlayer; class Team; class XPMHolder; @@ -53,8 +54,8 @@ class SerializerCommon { private: - SerializerCommon( const SerializerCommon & ); // not used - SerializerCommon & operator=( const SerializerCommon & ); // not used + SerializerCommon( const SerializerCommon & ) = delete; // not used + SerializerCommon & operator=( const SerializerCommon & ) = delete; // not used protected: SerializerCommon(); @@ -81,9 +82,9 @@ class SerializerCommon { { } virtual - void serializePlayerTypeBegin( std::ostream & ) const + void serializePlayerTypeBegin( std::ostream &, + const int ) const { } - virtual void serializePlayerTypeEnd( std::ostream & ) const { } @@ -145,9 +146,9 @@ class Serializer { const SerializerCommon::Ptr M_common; - Serializer(); // not used - Serializer( const Serializer & ); // not used - Serializer & operator=( const Serializer & ); // not used + Serializer() = delete; // not used + Serializer( const Serializer & ) = delete; // not used + Serializer & operator=( const Serializer & ) = delete; // not used protected: explicit @@ -188,9 +189,10 @@ class Serializer { commonSerializer().serializePlayerParamEnd( strm ); } - void serializePlayerTypeBegin( std::ostream & strm ) const + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const { - commonSerializer().serializePlayerTypeBegin( strm ); + commonSerializer().serializePlayerTypeBegin( strm, id ); } void serializePlayerTypeEnd( std::ostream & strm ) const @@ -272,9 +274,9 @@ class SerializerPlayer explicit SerializerPlayer( const SerializerCommon::Ptr common ); - virtual - ~SerializerPlayer(); public: + virtual + ~SerializerPlayer() override; virtual void serializeRefereeAudio( std::ostream & strm, @@ -890,11 +892,10 @@ class SerializerOnlineCoach SerializerOnlineCoach( const SerializerCommon::Ptr common, const SerializerCoach::Ptr cosch ); +public: virtual ~SerializerOnlineCoach(); - -public: const SerializerCoach::Ptr coachSerializerPtr() const { @@ -1085,20 +1086,20 @@ class SerializerMonitor virtual void serializeTeam( std::ostream &, - const int, + const int, const int, const Team &, const Team & ) const { } virtual void serializePlayMode( std::ostream &, - const int, + const int, const int, const PlayMode ) const { } virtual void serializeShowBegin( std::ostream &, - const int ) const + const int, const int ) const { } virtual void serializeShowEnd( std::ostream & ) const @@ -1117,6 +1118,14 @@ class SerializerMonitor const Ball & ) const { } + virtual + void serializePlayerArrayBegin( std::ostream & ) const + { } + + virtual + void serializePlayerArrayEnd( std::ostream & ) const + { } + virtual void serializePlayerBegin( std::ostream &, const Player & ) const @@ -1156,6 +1165,13 @@ class SerializerMonitor const unsigned int, const XPMHolder & ) const { } + + virtual + void serializeMsg( std::ostream &, + const int, const int, + const int, + const char * ) const + { } }; diff --git a/src/serializercoachstdv1.cpp b/src/serializercoachstdv1.cpp index 19af127f..219e570a 100644 --- a/src/serializercoachstdv1.cpp +++ b/src/serializercoachstdv1.cpp @@ -24,10 +24,11 @@ #endif #include "serializercoachstdv1.h" -#include "clangmsg.h" #include "param.h" #include "object.h" +#include + namespace rcss { SerializerCoachStdv1::SerializerCoachStdv1( const SerializerCommon::Ptr common ) diff --git a/src/serializercoachstdv1.h b/src/serializercoachstdv1.h index c7c8449f..7cb8c97d 100644 --- a/src/serializercoachstdv1.h +++ b/src/serializercoachstdv1.h @@ -34,7 +34,7 @@ class SerializerCoachStdv1 public: virtual - ~SerializerCoachStdv1(); + ~SerializerCoachStdv1() override; static const @@ -43,53 +43,53 @@ class SerializerCoachStdv1 virtual void serializeRefereeAudio( std::ostream & strm, const int time, - const char * msg ) const; + const char * msg ) const override; virtual void serializeCoachAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializeCoachStdAudio( std::ostream & strm, const int time, const std::string & name, - const rcss::clang::Msg & msg ) const; + const rcss::clang::Msg & msg ) const override; virtual void serializePlayerAudio( std::ostream & strm, const int time, const std::string& name, - const char* msg ) const; + const char* msg ) const override; virtual - void serializeInit( std::ostream & ) const; + void serializeInit( std::ostream & ) const override; virtual void serializeVisualBegin( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual - void serializeVisualEnd( std::ostream & strm ) const; + void serializeVisualEnd( std::ostream & strm ) const override; virtual void serializeLookBegin( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual - void serializeLookEnd( std::ostream & strm ) const; + void serializeLookEnd( std::ostream & strm ) const override; virtual void serializeVisualObject( std::ostream & strm , const std::string & name, - const PVector & pos ) const; + const PVector & pos ) const override; virtual void serializeVisualObject( std::ostream & strm, const std::string & name, const PVector & pos, - const PVector & vel ) const; + const PVector & vel ) const override; virtual void serializeVisualObject( std::ostream & strm, @@ -97,7 +97,7 @@ class SerializerCoachStdv1 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -106,7 +106,7 @@ class SerializerCoachStdv1 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -116,12 +116,12 @@ class SerializerCoachStdv1 const PVector & vel, const int body, const int neck, - const int point_dir ) const; + const int point_dir ) const override; virtual void serializeOKEye( std::ostream & strm, - const bool on ) const; + const bool on ) const override; }; } diff --git a/src/serializercoachstdv13.h b/src/serializercoachstdv13.h index d74dc236..7774dd4d 100644 --- a/src/serializercoachstdv13.h +++ b/src/serializercoachstdv13.h @@ -34,7 +34,7 @@ class SerializerCoachStdv13 public: virtual - ~SerializerCoachStdv13(); + ~SerializerCoachStdv13() override; static const @@ -47,7 +47,7 @@ class SerializerCoachStdv13 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -57,7 +57,7 @@ class SerializerCoachStdv13 const PVector & vel, const int body, const int neck, - const int point_dir ) const; + const int point_dir ) const override; }; } diff --git a/src/serializercoachstdv14.cpp b/src/serializercoachstdv14.cpp index ffc5e504..3614920b 100644 --- a/src/serializercoachstdv14.cpp +++ b/src/serializercoachstdv14.cpp @@ -137,6 +137,7 @@ namespace { RegHolder v14 = SerializerCoach::factory().autoReg( &SerializerCoachStdv14::create, 14 ); RegHolder v15 = SerializerCoach::factory().autoReg( &SerializerCoachStdv14::create, 15 ); RegHolder v16 = SerializerCoach::factory().autoReg( &SerializerCoachStdv14::create, 16 ); +RegHolder v17 = SerializerCoach::factory().autoReg( &SerializerCoachStdv14::create, 17 ); } } diff --git a/src/serializercoachstdv14.h b/src/serializercoachstdv14.h index e5c3aee0..0366340c 100644 --- a/src/serializercoachstdv14.h +++ b/src/serializercoachstdv14.h @@ -33,7 +33,7 @@ class SerializerCoachStdv14 public: virtual - ~SerializerCoachStdv14(); + ~SerializerCoachStdv14() override; static const @@ -46,7 +46,7 @@ class SerializerCoachStdv14 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -56,7 +56,7 @@ class SerializerCoachStdv14 const PVector & vel, const int body, const int neck, - const int point_dir ) const; + const int point_dir ) const override; }; } diff --git a/src/serializercoachstdv7.cpp b/src/serializercoachstdv7.cpp index 4226e119..0190eab3 100644 --- a/src/serializercoachstdv7.cpp +++ b/src/serializercoachstdv7.cpp @@ -25,9 +25,10 @@ #include "serializercoachstdv7.h" -#include "clangmsg.h" #include "object.h" +#include + namespace rcss { SerializerCoachStdv7::SerializerCoachStdv7( const SerializerCommon::Ptr common ) diff --git a/src/serializercoachstdv7.h b/src/serializercoachstdv7.h index eeacacc2..ee62b93f 100644 --- a/src/serializercoachstdv7.h +++ b/src/serializercoachstdv7.h @@ -34,7 +34,7 @@ class SerializerCoachStdv7 public: virtual - ~SerializerCoachStdv7(); + ~SerializerCoachStdv7() override; static const @@ -44,23 +44,23 @@ class SerializerCoachStdv7 void serializeCoachAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializeCoachStdAudio( std::ostream & strm, const int time, const std::string & name, - const rcss::clang::Msg & msg ) const; + const rcss::clang::Msg & msg ) const override; virtual void serializePlayerAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializeVisualBegin( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual void serializeVisualObject( std::ostream & strm, @@ -68,7 +68,7 @@ class SerializerCoachStdv7 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual @@ -78,7 +78,7 @@ class SerializerCoachStdv7 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -88,7 +88,7 @@ class SerializerCoachStdv7 const PVector & vel, const int body, const int neck, - const int point_dir ) const; + const int point_dir ) const override; }; diff --git a/src/serializercoachstdv8.cpp b/src/serializercoachstdv8.cpp index a0344f06..d013cc07 100644 --- a/src/serializercoachstdv8.cpp +++ b/src/serializercoachstdv8.cpp @@ -25,10 +25,11 @@ #include "serializercoachstdv8.h" -#include "clangmsg.h" #include "object.h" #include "player.h" +#include + namespace rcss { SerializerCoachStdv8::SerializerCoachStdv8( const SerializerCommon::Ptr common ) diff --git a/src/serializercoachstdv8.h b/src/serializercoachstdv8.h index 1ac5aefd..4ab487bd 100644 --- a/src/serializercoachstdv8.h +++ b/src/serializercoachstdv8.h @@ -35,7 +35,7 @@ class SerializerCoachStdv8 public: virtual - ~SerializerCoachStdv8(); + ~SerializerCoachStdv8() override; static const @@ -48,7 +48,7 @@ class SerializerCoachStdv8 const PVector &, const int, const int, - const bool ) const; + const bool ) const override; virtual void serializeVisualObject( std::ostream &, @@ -58,7 +58,7 @@ class SerializerCoachStdv8 const int, const int, const int, - const bool ) const; + const bool ) const override; virtual @@ -68,7 +68,7 @@ class SerializerCoachStdv8 const PVector & pos, const PVector & vel, const int body, - const int neck ) const; + const int neck ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -78,7 +78,7 @@ class SerializerCoachStdv8 const PVector & vel, const int body, const int neck, - const int point_dir ) const; + const int point_dir ) const override; }; } diff --git a/src/serializercommonjson.cpp b/src/serializercommonjson.cpp new file mode 100644 index 00000000..0260bca0 --- /dev/null +++ b/src/serializercommonjson.cpp @@ -0,0 +1,151 @@ +// -*-c++-*- + +/*! + \file serializercommonjson.cpp + \brief Class for serializing data by JSON format + \author Hidehisa Akiyama +*/ + +/* + *Copyright: + + Copyright (C) The RoboCup Soccer Server Maintenance Committee. + Hidehisa AKIYAMA + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + *EndCopyright: + */ + +///////////////////////////////////////////////////////////////////// + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "serializercommonjson.h" + +#include + +namespace rcss { + +SerializerCommonJSON::SerializerCommonJSON() +{ + +} + +SerializerCommonJSON::~SerializerCommonJSON() +{ + +} + +void +SerializerCommonJSON::serializeServerParamBegin( std::ostream & strm ) const +{ + strm << "{" + << std::quoted( "type" ) << ':' << std::quoted( "server_param" ) << ',' + << std::quoted( "params" ) << ":{"; +} + + +void +SerializerCommonJSON::serializeServerParamEnd( std::ostream & strm ) const +{ + strm << "}}"; +} + + +void +SerializerCommonJSON::serializePlayerParamBegin( std::ostream & strm ) const +{ + strm << "{" + << std::quoted( "type" ) << ':' << std::quoted( "player_param" ) << ',' + << std::quoted( "params" ) << ":{"; +} + + +void +SerializerCommonJSON::serializePlayerParamEnd( std::ostream & strm ) const +{ + strm << "}}"; +} + + +void +SerializerCommonJSON::serializePlayerTypeBegin( std::ostream & strm, + const int id ) const +{ + strm << '{' + << std::quoted( "type" ) << ':' << std::quoted( "player_type" ) + << ',' + << std::quoted( "id" ) << ':' << id + << ',' + << std::quoted( "params" ) << ":{"; +} + +void +SerializerCommonJSON::serializePlayerTypeEnd( std::ostream & strm ) const +{ + strm << "}}"; +} + + +void +SerializerCommonJSON::serializeParam( std::ostream & strm, + const std::string & name, + const int param ) const +{ + strm << std::quoted( name ) << ':' << param; +} + +void +SerializerCommonJSON::serializeParam( std::ostream & strm, + const std::string & name, + const bool param ) const +{ + strm << std::quoted( name ) << ':' << std::boolalpha << param; +} + +void +SerializerCommonJSON::serializeParam( std::ostream & strm, + const std::string & name, + const double & param ) const +{ + strm << std::quoted( name ) << ':' << param; +} + +void +SerializerCommonJSON::serializeParam( std::ostream & strm, + const std::string & name, + const std::string & param ) const +{ + strm << std::quoted( name ) << ':' << std::quoted( param ); +} + + +const +SerializerCommon::Ptr +SerializerCommonJSON::create() +{ + Ptr ptr( new SerializerCommonJSON() ); + return ptr; +} + + +namespace { +RegHolder json = SerializerCommon::factory().autoReg( &SerializerCommonJSON::create, -1 ); +} + +} diff --git a/src/serializercommonjson.h b/src/serializercommonjson.h new file mode 100644 index 00000000..5ef68e90 --- /dev/null +++ b/src/serializercommonjson.h @@ -0,0 +1,95 @@ +// -*-c++-*- + +/*! + \file serializercommonjson.h + \brief Class for serializing data by JSON format + \author Hidehisa Akiyama +*/ + +/* + *Copyright: + + Copyright (C) The RoboCup Soccer Server Maintenance Committee. + Hidehisa AKIYAMA + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + *EndCopyright: + */ + +///////////////////////////////////////////////////////////////////// + +#ifndef SERIALIZER_COMMON_JSON_H +#define SERIALIZER_COMMON_JSON_H + +#include "serializer.h" + +namespace rcss { + +class SerializerCommonJSON + : public SerializerCommon { +protected: + SerializerCommonJSON(); + +public: + virtual + ~SerializerCommonJSON() override; + + static const Ptr create(); + + virtual + void serializeServerParamBegin( std::ostream & strm ) const override; + + virtual + void serializeServerParamEnd( std::ostream & strm ) const override; + + virtual + void serializePlayerParamBegin( std::ostream & strm ) const override; + + virtual + void serializePlayerParamEnd( std::ostream & strm ) const override; + + virtual + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const override; + virtual + void serializePlayerTypeEnd( std::ostream & strm ) const override; + + + virtual + void serializeParam( std::ostream & strm, + const std::string & name, + const int param ) const override; + + virtual + void serializeParam( std::ostream & strm, + const std::string & name, + const bool param ) const override; + + virtual + void serializeParam( std::ostream & strm, + const std::string & name, + const double & param ) const override; + + virtual + void serializeParam( std::ostream & strm, + const std::string & name, + const std::string & param ) const override; + +}; + +} + +#endif diff --git a/src/serializercommonstdv1.cpp b/src/serializercommonstdv1.cpp index d9feb351..a6ccb430 100644 --- a/src/serializercommonstdv1.cpp +++ b/src/serializercommonstdv1.cpp @@ -25,7 +25,7 @@ #include "serializercommonstdv1.h" -#include "clangmsg.h" +#include namespace rcss { @@ -64,7 +64,8 @@ SerializerCommonStdv1::serializePlayerParamEnd( std::ostream & ) const } void -SerializerCommonStdv1::serializePlayerTypeBegin( std::ostream & ) const +SerializerCommonStdv1::serializePlayerTypeBegin( std::ostream &, + const int ) const { } diff --git a/src/serializercommonstdv1.h b/src/serializercommonstdv1.h index 8af3ffc8..f00cfe5a 100644 --- a/src/serializercommonstdv1.h +++ b/src/serializercommonstdv1.h @@ -34,49 +34,50 @@ class SerializerCommonStdv1 public: virtual - ~SerializerCommonStdv1(); + ~SerializerCommonStdv1() override; static const Ptr create(); virtual - void serializeServerParamBegin( std::ostream & strm ) const; + void serializeServerParamBegin( std::ostream & strm ) const override; virtual - void serializeServerParamEnd( std::ostream & strm ) const; + void serializeServerParamEnd( std::ostream & strm ) const override; virtual - void serializePlayerParamBegin( std::ostream & strm ) const; + void serializePlayerParamBegin( std::ostream & strm ) const override; virtual - void serializePlayerParamEnd( std::ostream & strm ) const; + void serializePlayerParamEnd( std::ostream & strm ) const override; virtual - void serializePlayerTypeBegin( std::ostream & strm ) const; + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const override; virtual - void serializePlayerTypeEnd( std::ostream & strm ) const; + void serializePlayerTypeEnd( std::ostream & strm ) const override; virtual void serializeParam( std::ostream & strm, - const int param ) const; + const int param ) const override; virtual void serializeParam( std::ostream & strm, - const unsigned int param ) const; + const unsigned int param ) const override; virtual void serializeParam( std::ostream & strm, - const bool param ) const; + const bool param ) const override; virtual void serializeParam( std::ostream & strm, - const double & param ) const; + const double & param ) const override; virtual void serializeParam( std::ostream & strm, - const std::string & param ) const; + const std::string & param ) const override; }; } diff --git a/src/serializercommonstdv7.cpp b/src/serializercommonstdv7.cpp index e8bb7d34..f7a757c7 100644 --- a/src/serializercommonstdv7.cpp +++ b/src/serializercommonstdv7.cpp @@ -25,7 +25,7 @@ #include "serializercommonstdv7.h" -#include "clangmsg.h" +#include namespace rcss { @@ -64,9 +64,10 @@ SerializerCommonStdv7::serializePlayerParamEnd( std::ostream & strm ) const } void -SerializerCommonStdv7::serializePlayerTypeBegin( std::ostream & strm ) const +SerializerCommonStdv7::serializePlayerTypeBegin( std::ostream & strm, + const int id ) const { - strm << "(player_type"; + strm << "(player_type " << id; } void diff --git a/src/serializercommonstdv7.h b/src/serializercommonstdv7.h index 6b23c43c..9914c530 100644 --- a/src/serializercommonstdv7.h +++ b/src/serializercommonstdv7.h @@ -34,49 +34,50 @@ class SerializerCommonStdv7 public: virtual - ~SerializerCommonStdv7(); + ~SerializerCommonStdv7() override; static const Ptr create(); virtual - void serializeServerParamBegin( std::ostream & strm ) const; + void serializeServerParamBegin( std::ostream & strm ) const override; virtual - void serializeServerParamEnd( std::ostream & strm ) const; + void serializeServerParamEnd( std::ostream & strm ) const override; virtual - void serializePlayerParamBegin( std::ostream & strm ) const; + void serializePlayerParamBegin( std::ostream & strm ) const override; virtual - void serializePlayerParamEnd( std::ostream & strm ) const; + void serializePlayerParamEnd( std::ostream & strm ) const override; virtual - void serializePlayerTypeBegin( std::ostream & strm ) const; + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const override; virtual - void serializePlayerTypeEnd( std::ostream & strm ) const; + void serializePlayerTypeEnd( std::ostream & strm ) const override; virtual void serializeParam( std::ostream & strm, - const int param ) const; + const int param ) const override; virtual void serializeParam( std::ostream & strm, - const unsigned int param ) const; + const unsigned int param ) const override; virtual void serializeParam( std::ostream & strm, - const bool param ) const; + const bool param ) const override; virtual void serializeParam( std::ostream & strm, - const double & param ) const; + const double & param ) const override; virtual void serializeParam( std::ostream & strm, - const std::string & param ) const; + const std::string & param ) const override; }; } diff --git a/src/serializercommonstdv8.cpp b/src/serializercommonstdv8.cpp index 7d621adc..f6d6332e 100644 --- a/src/serializercommonstdv8.cpp +++ b/src/serializercommonstdv8.cpp @@ -25,7 +25,7 @@ #include "serializercommonstdv8.h" -#include "clangmsg.h" +//#include "clangmsg.h" namespace rcss { @@ -52,9 +52,11 @@ SerializerCommonStdv8::serializePlayerParamBegin( std::ostream & strm ) const } void -SerializerCommonStdv8::serializePlayerTypeBegin( std::ostream & strm ) const +SerializerCommonStdv8::serializePlayerTypeBegin( std::ostream & strm, + const int id ) const { - strm << "(player_type "; + strm << "(player_type " + << "(id " << id << ")"; } void @@ -107,6 +109,7 @@ RegHolder v13 = SerializerCommon::factory().autoReg( &SerializerCommonStdv8::cre RegHolder v14 = SerializerCommon::factory().autoReg( &SerializerCommonStdv8::create, 14 ); RegHolder v15 = SerializerCommon::factory().autoReg( &SerializerCommonStdv8::create, 15 ); RegHolder v16 = SerializerCommon::factory().autoReg( &SerializerCommonStdv8::create, 16 ); +RegHolder v17 = SerializerCommon::factory().autoReg( &SerializerCommonStdv8::create, 17 ); } } diff --git a/src/serializercommonstdv8.h b/src/serializercommonstdv8.h index 07fe1f8a..99e2c585 100644 --- a/src/serializercommonstdv8.h +++ b/src/serializercommonstdv8.h @@ -34,40 +34,41 @@ class SerializerCommonStdv8 public: virtual - ~SerializerCommonStdv8(); + ~SerializerCommonStdv8() override; static const Ptr create(); virtual - void serializeServerParamBegin( std::ostream & strm ) const; + void serializeServerParamBegin( std::ostream & strm ) const override; virtual - void serializePlayerParamBegin( std::ostream & strm ) const; + void serializePlayerParamBegin( std::ostream & strm ) const override; virtual - void serializePlayerTypeBegin( std::ostream & strm ) const; + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const override; virtual void serializeParam( std::ostream & strm, const std::string & name, - const int param ) const; + const int param ) const override; virtual void serializeParam( std::ostream & strm, const std::string & name, - const bool param ) const; + const bool param ) const override; virtual void serializeParam( std::ostream & strm, const std::string & name, - const double & param ) const; + const double & param ) const override; virtual void serializeParam( std::ostream & strm, const std::string & name, - const std::string & param ) const; + const std::string & param ) const override; }; diff --git a/src/serializermonitor.cpp b/src/serializermonitor.cpp index 92d972ef..444b7c47 100644 --- a/src/serializermonitor.cpp +++ b/src/serializermonitor.cpp @@ -32,6 +32,8 @@ #include "team.h" #include "xpmholder.h" +#include + namespace rcss { /* @@ -120,7 +122,7 @@ SerializerMonitorStdv3::create() void SerializerMonitorStdv3::serializeTeam( std::ostream & os, - const int time, + const int time, const int /*stime*/, const Team & team_l, const Team & team_r ) const { @@ -143,7 +145,7 @@ SerializerMonitorStdv3::serializeTeam( std::ostream & os, void SerializerMonitorStdv3::serializePlayMode( std::ostream & os, - const int time, + const int time, const int /*stime*/, const PlayMode pmode ) const { static const char * playmode_strings[] = PLAYMODE_STRINGS; @@ -156,7 +158,7 @@ SerializerMonitorStdv3::serializePlayMode( std::ostream & os, void SerializerMonitorStdv3::serializeShowBegin( std::ostream & os, - const int time ) const + const int time, const int /*stime*/ ) const { os << "(show " << time; } @@ -281,7 +283,7 @@ SerializerMonitorStdv3::serializePlayerFocus( std::ostream & os, const Player & player ) const { if ( player.isEnabled() - && player.getFocusTarget() != NULL ) + && player.getFocusTarget() ) { os << " (f " << SideStr( player.getFocusTarget()->side() ) << ' ' @@ -351,12 +353,518 @@ SerializerMonitorStdv4::serializePlayerStamina( std::ostream & os, << player.staminaCapacity() << ')'; } +/* +//=================================================================== +// +// SerializerMonitorJSON (JSON) +// +//=================================================================== +*/ + +#define USE_FLAT_STYLE + +SerializerMonitorJSON::SerializerMonitorJSON( const SerializerCommon::Ptr common ) + : SerializerMonitor( common ) +{ + +} + +SerializerMonitorJSON::~SerializerMonitorJSON() +{ + +} + +const +SerializerMonitor::Ptr +SerializerMonitorJSON::create() +{ + // The version of JSON-based common serializer is always -1 + SerializerCommon::Creator cre_common; + if ( ! SerializerCommon::factory().getCreator( cre_common, -1 ) ) // *** versin of common = -1 *** + { + return SerializerMonitor::Ptr(); + } + + SerializerMonitor::Ptr ptr( new SerializerMonitorJSON( cre_common() ) ); + return ptr; +} + +namespace { + +std::string +to_string( const Side side ) +{ + return ( side == LEFT + ? "l" + : side == RIGHT + ? "r" + : "n" ); +} + +void +time_to_json( std::ostream & os, + const int time, + const int stime ) +{ + os << std::quoted( "time" ) << ':' << time; + if ( stime > 0 ) + { + os << ','; + os << std::quoted( "stime" ) << ':' << stime; + } +} + +#ifdef USE_FLAT_STYLE + +void +team_to_json( std::ostream & os, + const Team & team ) +{ + const std::string side = to_string( team.side() ); + if ( side != "l" && side != "r" ) + { + return; + } + + os << '{' + << std::quoted( "side" ) << ':' << std::quoted( side ); + + os << ',' + << std::quoted( "name" ) << ':'; + if ( team.name().empty() ) os << "null"; else os << std::quoted( team.name() ); + + os << ',' + << std::quoted( "score" ) << ':' << team.point(); + if ( team.penaltyTaken() > 0 ) + { + os << ','; + os << std::quoted( "pen_score" ) << ':' << team.penaltyPoint() << ',' + << std::quoted( "pen_miss" ) << ':' << team.penaltyTaken() - team.penaltyPoint(); + } + + os << '}'; +} + +void +teams_to_json( std::ostream & os, + const Team & team_l, + const Team & team_r ) +{ + os << std::quoted( "teams" ) << ':'; + + os << '['; + team_to_json( os, team_l ); + + os << ','; + team_to_json( os, team_r ); + + os << ']'; +} + +} + +void +SerializerMonitorJSON::serializeTeam( std::ostream & os, + const int time, const int stime, + const Team & team_l, + const Team & team_r ) const +{ + os << '{'; + os << std::quoted( "type" ) << ':' << std::quoted( "team" ); + + os << ','; + time_to_json( os, time, stime ); + + os << ','; + teams_to_json( os, team_l, team_r ); + + os << '}'; +} + + +void +SerializerMonitorJSON::serializePlayMode( std::ostream & os, + const int time, const int stime, + const PlayMode pmode ) const +{ + os << '{'; + os << std::quoted( "type" ) << ':' << std::quoted( "playmode" ); + + os << ','; + time_to_json( os, time, stime ); + + os << ','; + serializePlayModeId( os, pmode ); + + os << '}'; +} + + +void +SerializerMonitorJSON::serializeShowBegin( std::ostream & os, + const int time, const int stime ) const +{ + os << '{'; + os << std::quoted( "type" ) << ':' << std::quoted( "show" ); + + os << ','; + time_to_json( os, time, stime ); +} + + +void +SerializerMonitorJSON::serializeShowEnd( std::ostream & os ) const +{ + os << '}'; +} + + +void +SerializerMonitorJSON::serializePlayModeId( std::ostream & os, + const PlayMode pmode ) const +{ + static const char * playmode_strings[] = PLAYMODE_STRINGS; + os << std::quoted( "mode" ) << ':' << std::quoted( playmode_strings[pmode] ); +} + + +void +SerializerMonitorJSON::serializeScore( std::ostream & os, + const Team & team_l, + const Team & team_r ) const +{ + teams_to_json( os, team_l, team_r ); +} + + +namespace { +constexpr double POS_PREC = 0.0001; +constexpr double DIR_PREC = 0.001; + +#else +void +vec_to_json( std::ostream & os, + const std::string & name, + const double x, + const double y ) +{ + os << std::quoted( name ) << ':' + << '{' + << std::quoted( "x" ) << ':' << Quantize( x, POS_PREC ) + << ',' + << std::quoted( "y" ) << ':' << Quantize( y, POS_PREC ) + << '}'; +} +#endif +} + +void +SerializerMonitorJSON::serializeBall( std::ostream & os, + const Ball & ball ) const +{ + os << std::quoted( "ball" ) << ':' + << '{'; +#ifdef USE_FLAT_STYLE + os << std::quoted( "x" ) << ':' << Quantize( ball.pos().x, POS_PREC ) + << ',' + << std::quoted( "y" ) << ':' << Quantize( ball.pos().y, POS_PREC ) + << ',' + << std::quoted( "vx" ) << ':' << Quantize( ball.vel().x, POS_PREC ) + << ',' + << std::quoted( "vy" ) << ':' << Quantize( ball.vel().y, POS_PREC ); +#else + vec_to_json( os, "pos", ball.pos().x, ball.pos().x ); + os << ','; + vec_to_json( os, "vel", ball.vel().x, ball.vel().x ); +#endif + os << '}'; + +} + +void +SerializerMonitorJSON::serializePlayerArrayBegin( std::ostream & os ) const +{ + os << std::quoted( "players" ) << ':' + << '['; +} + +void +SerializerMonitorJSON::serializePlayerArrayEnd( std::ostream & os ) const +{ + os << ']'; +} + +void +SerializerMonitorJSON::serializePlayerBegin( std::ostream & os, + const Player & player ) const +{ + os << '{' + << std::quoted( "side" ) << ':' << std::quoted( to_string( player.side() ) ) + << ',' + << std::quoted( "unum" ) << ':' << player.unum() + << ',' + << std::quoted( "type" ) << ':' << player.playerTypeId() + << ',' + << std::quoted( "state" ) << ':' << player.state(); +} + + +void +SerializerMonitorJSON::serializePlayerEnd( std::ostream & os ) const +{ + os << '}'; +} + + +void +SerializerMonitorJSON::serializePlayerPos( std::ostream & os, + const Player & player ) const +{ +#ifdef USE_FLAT_STYLE + os << ',' + << std::quoted( "x" ) << ':' << Quantize( player.pos().x, POS_PREC ) + << ',' + << std::quoted( "y" ) << ':' << Quantize( player.pos().y, POS_PREC ); + os << ',' + << std::quoted( "vx" ) << ':' << Quantize( player.vel().x, POS_PREC ) + << ',' + << std::quoted( "vy" ) << ':' << Quantize( player.vel().y, POS_PREC ); +#else + os << ','; + vec_to_json( os, "pos", player.pos().x, player.pos().y ); + os << ','; + vec_to_json( os, "vel", player.vel().x, player.vel().y ); +#endif + + os << ',' + << std::quoted( "body" ) << ':' << Quantize( Rad2Deg( player.angleBodyCommitted() ), DIR_PREC ); + os << ',' + << std::quoted( "neck" ) << ':' << Quantize( Rad2Deg( player.angleNeckCommitted() ), DIR_PREC ); +} + + +void +SerializerMonitorJSON::serializePlayerArm( std::ostream & os, + const Player & player ) const +{ + if ( player.arm().isPointing() ) + { +#ifdef USE_FLAT_STYLE + os << ',' + << std::quoted( "px" ) << ':' << Quantize( player.arm().dest().getX(), POS_PREC ) + << ',' + << std::quoted( "py" ) << ':' << Quantize( player.arm().dest().getY(), POS_PREC ); +#else + os << ','; + vec_to_json( os, "arm", player.arm().dest().getX(), player.arm().dest().getY() ); +#endif + } +} + + +void SerializerMonitorJSON::serializePlayerViewMode( std::ostream & os, + const Player & player ) const +{ + os << ','; +#ifdef USE_FLAT_STYLE + os << std::quoted( "vq" ) << ':' << std::quoted( player.highQuality() ? "h" : "l" ) + << ',' + << std::quoted( "vw" ) << ':' << Quantize( Rad2Deg( player.visibleAngle() ), DIR_PREC ); +#else + os << std::quoted( "view" ) << ':' + << '{' + << std::quoted( "q" ) << ':' << std::quoted( player.highQuality() ? "h" : "l" ) + << ',' + << std::quoted( "w" ) << ':' << Quantize( Rad2Deg( player.visibleAngle() ), DIR_PREC ) + << '}'; +#endif +} + + +void +SerializerMonitorJSON::serializePlayerStamina( std::ostream & os, + const Player & player ) const +{ + os << ','; +#ifdef USE_FLAT_STYLE + os << std::quoted( "stamina" ) << ':' << player.stamina() + << ',' + << std::quoted( "effort" ) << ':' << player.effort() + << ',' + << std::quoted( "recovery" ) << ':' << player.recovery() + << ',' + << std::quoted( "capacity" ) << ':' << player.staminaCapacity(); +#else + os << std::quoted( "stamina" ) << ':' + << '{'; + os << std::quoted( "v" ) << ':' << player.stamina() + << ',' + << std::quoted( "e" ) << ':' << player.effort() + << ',' + << std::quoted( "r" ) << ':' << player.recovery() + << ',' + << std::quoted( "c" ) << ':' << player.staminaCapacity(); + os << '}'; +#endif +} + + +void SerializerMonitorJSON::serializePlayerFocus( std::ostream & os, + const Player & player ) const +{ + if ( player.isEnabled() + && player.getFocusTarget() ) + { + os << ','; +#if 1 + os << std::quoted( "fside" ) << ':' << std::quoted( to_string( player.getFocusTarget()->side() ) ) + << ',' + << std::quoted( "fnum" ) << ':' << player.getFocusTarget()->unum(); +#else + os << std::quoted( "focus" ) << ':' + << '{' + << std::quoted( "s" ) << ':' << std::quoted( to_string( player.getFocusTarget()->side() ) ) + << ',' + << std::quoted( "n" ) << ':' << player.getFocusTarget()->unum() + << '}'; +#endif + } +} + + +void +SerializerMonitorJSON::serializePlayerCounts( std::ostream & os, + const Player & player ) const + +{ + os << ','; + os << std::quoted( "count" ) << ':' +#if 0 + << '[' << player.kickCount() + << ',' << player.dashCount() + << ',' << player.turnCount() + << ',' << player.catchCount() + << ',' << player.moveCount() + << ',' << player.turnNeckCount() + << ',' << player.changeViewCount() + << ',' << player.sayCount() + << ',' << player.tackleCount() + << ',' << player.arm().getCounter() + << ',' << player.attentiontoCount() + << ']'; +#else + << '{' + << std::quoted( "kick" ) << ':' << player.kickCount() + << ',' + << std::quoted( "dash" ) << ':' << player.dashCount() + << ',' + << std::quoted( "turn" ) << ':' << player.turnCount() + << ',' + << std::quoted( "catch" ) << ':' << player.catchCount() + << ',' + << std::quoted( "move" ) << ':' << player.moveCount() + << ',' + << std::quoted( "turn_neck" ) << ':' << player.turnNeckCount() + << ',' + << std::quoted( "change_view" ) << ':' << player.changeViewCount() + << ',' + << std::quoted( "say" ) << ':' << player.sayCount() + << ',' + << std::quoted( "tackle" ) << ':' << player.tackleCount() + << ',' + << std::quoted( "pointto" ) << ':' << player.arm().getCounter() + << ',' + << std::quoted( "attentionto" ) << ':' << player.attentiontoCount() + << '}'; +#endif +} + + +void +SerializerMonitorJSON::serializeTeamGraphic( std::ostream & os, + const Side side, + const unsigned int x, + const unsigned int y, + const XPMHolder & xpm ) const +{ + if ( ! xpm.valid() + || xpm.colors() >= static_cast< int >( xpm.data().size() ) ) + { + return; + } + + os << '{' + << std::quoted( "type" ) << ':' << std::quoted( "team_graphic" ); + + os << ','; + os << std::quoted( "side" ) << ':' << std::quoted( to_string( side ) ); + + os << ','; +#ifdef USE_FLAT_STYLE + os << std::quoted( "x" ) << ':' << x + << ',' + << std::quoted( "y" ) << ':' << y; +#else + os << std::quoted( "index" ) << ':' + << '{' + << std::quoted( "x" ) << ':' << x + << ',' + << std::quoted( "y" ) << ':' << y + << '}'; +#endif + + os << ','; + os << std::quoted( "xpm" ) << ':' + << '['; // begin xpm array + bool first = true; + for ( std::string str : xpm.data() ) + { + if ( first ) first = false; else os << ','; + + std::replace( str.begin(), str.end(), '\t', ' ' ); + os << std::quoted( str ); + } + os << ']'; // end xpm array + + os << '}'; +} + +void +SerializerMonitorJSON::serializeMsg( std::ostream & os, + const int time, const int stime, + const int board, + const char * msg ) const +{ + os << '{' + << std::quoted( "type" ) << ':' << std::quoted( "msg" ); + + os << ','; + time_to_json( os, time, stime ); + + os << ','; + os << std::quoted( "board" ) << ':' << board; + + os << ','; + os << std::quoted( "message" ) << ':' << std::quoted( msg ); + + os << '}'; + +} + +/* +//=================================================================== +// +// Factory registration +// +//=================================================================== +*/ namespace { RegHolder v1 = SerializerMonitor::factory().autoReg( &SerializerMonitorStdv1::create, 1 ); RegHolder v2 = SerializerMonitor::factory().autoReg( &SerializerMonitorStdv1::create, 2 ); RegHolder v3 = SerializerMonitor::factory().autoReg( &SerializerMonitorStdv3::create, 3 ); RegHolder v4 = SerializerMonitor::factory().autoReg( &SerializerMonitorStdv4::create, 4 ); +RegHolder v5 = SerializerMonitor::factory().autoReg( &SerializerMonitorJSON::create, 5 ); } } diff --git a/src/serializermonitor.h b/src/serializermonitor.h index 30850954..19291e95 100644 --- a/src/serializermonitor.h +++ b/src/serializermonitor.h @@ -2,7 +2,7 @@ /*************************************************************************** serializermonitor.h - Classes for serializing data to std v1 monitors + Classes for serializing data to monitors ------------------- begin : 2007-11-21 copyright : (C) 2007 by The RoboCup Soccer Simulator @@ -20,8 +20,8 @@ ***************************************************************************/ -#ifndef RCSS_SERIALIZER_MONITOR_STD_V1_H -#define RCSS_SERIALIZER_MONITOR_STD_V1_H +#ifndef RCSS_SERIALIZER_MONITOR_H +#define RCSS_SERIALIZER_MONITOR_H #include "serializer.h" @@ -46,7 +46,7 @@ class SerializerMonitorStdv1 public: virtual - ~SerializerMonitorStdv1(); + ~SerializerMonitorStdv1() override; static const @@ -58,7 +58,7 @@ class SerializerMonitorStdv1 const Side side, const unsigned int x, const unsigned int y, - const XPMHolder & xpm ) const; + const XPMHolder & xpm ) const override; }; @@ -79,67 +79,67 @@ class SerializerMonitorStdv3 public: virtual - ~SerializerMonitorStdv3(); + ~SerializerMonitorStdv3() override; static - const - Ptr create(); + const Ptr create(); virtual void serializeTeam( std::ostream & os, - const int time, + const int time, const int stime, const Team & team_l, - const Team & team_r ) const; + const Team & team_r ) const override; virtual void serializePlayMode( std::ostream & os, - const int time, - const PlayMode pmode ) const; + const int time, const int stime, + const PlayMode pmode ) const override; virtual void serializeShowBegin( std::ostream & os, - const int time ) const; + const int time, const int stime ) const override; virtual - void serializeShowEnd( std::ostream & ) const; + void serializeShowEnd( std::ostream & ) const override; + virtual void serializePlayModeId( std::ostream & os, - const PlayMode pmode ) const; + const PlayMode pmode ) const override; virtual void serializeScore( std::ostream & os, const Team & team_l, - const Team & team_r ) const; + const Team & team_r ) const override; virtual void serializeBall( std::ostream & os, - const Ball & ball ) const; + const Ball & ball ) const override; virtual void serializePlayerBegin( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; virtual - void serializePlayerEnd( std::ostream & os ) const; + void serializePlayerEnd( std::ostream & os ) const override; virtual void serializePlayerPos( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; virtual void serializePlayerArm( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; virtual void serializePlayerViewMode( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; virtual void serializePlayerStamina( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; void serializePlayerFocus( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; virtual void serializePlayerCounts( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; }; /*! \class SerializerMonitorStdv4 - \brief class of the version 4 serialization for monitors. + \brief class of the version 4 serialization for monitors. Add the stamina capacity information. */ class SerializerMonitorStdv4 : public SerializerMonitorStdv3 { @@ -151,7 +151,7 @@ class SerializerMonitorStdv4 public: virtual - ~SerializerMonitorStdv4(); + ~SerializerMonitorStdv4() override; static const @@ -159,9 +159,113 @@ class SerializerMonitorStdv4 virtual void serializePlayerStamina( std::ostream & os, - const Player & player ) const; + const Player & player ) const override; }; + +/*! + \class SerializerMonitorJSON + \brief class of the version 5 serialization for monitors. (JSON format) +*/ +class SerializerMonitorJSON + : public SerializerMonitor { +protected: + + explicit + SerializerMonitorJSON( const SerializerCommon::Ptr common ); + +public: + + virtual + ~SerializerMonitorJSON() override; + + static const Ptr create(); + + virtual + void serializeTeam( std::ostream & os, + const int time, const int stime, + const Team & team_l, + const Team & team_r ) const override; + + virtual + void serializePlayMode( std::ostream & os, + const int time, const int stime, + const PlayMode pmode ) const override; + + virtual + void serializeShowBegin( std::ostream & os, + const int time, const int stime ) const override; + + virtual + void serializeShowEnd( std::ostream & os ) const override; + + virtual + void serializePlayModeId( std::ostream & os, + const PlayMode pmode ) const override; + + virtual + void serializeScore( std::ostream & os, + const Team & team_l, + const Team & team_r ) const override; + + virtual + void serializeBall( std::ostream & os, + const Ball & ball ) const override; + + + virtual + void serializePlayerArrayBegin( std::ostream & ) const override; + + virtual + void serializePlayerArrayEnd( std::ostream & ) const; + + virtual + void serializePlayerBegin( std::ostream & os, + const Player & player ) const override; + + virtual + void serializePlayerEnd( std::ostream & os ) const override; + + virtual + void serializePlayerPos( std::ostream & os, + const Player & player ) const override; + + virtual + void serializePlayerArm( std::ostream & os, + const Player & player ) const override; + + virtual + void serializePlayerViewMode( std::ostream & os, + const Player & player ) const override; + + virtual + void serializePlayerStamina( std::ostream & os, + const Player & player ) const override; + + virtual + void serializePlayerFocus( std::ostream & os, + const Player & player ) const override; + + virtual + void serializePlayerCounts( std::ostream & os, + const Player & player ) const override; + + virtual + void serializeTeamGraphic( std::ostream & os, + const Side side, + const unsigned int x, + const unsigned int y, + const XPMHolder & xpm ) const override; + + virtual + void serializeMsg( std::ostream & os, + const int time, const int stime, + const int board, + const char * msg ) const override; + +}; + + } #endif diff --git a/src/serializeronlinecoachstdv1.h b/src/serializeronlinecoachstdv1.h index 1e762a26..e7366432 100644 --- a/src/serializeronlinecoachstdv1.h +++ b/src/serializeronlinecoachstdv1.h @@ -34,38 +34,37 @@ class SerializerOnlineCoachStdv1 public: virtual - ~SerializerOnlineCoachStdv1(); + ~SerializerOnlineCoachStdv1() override; static - const - Ptr create(); + const Ptr create(); virtual void serializeRefereeAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializePlayerAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializePlayerClangVer( std::ostream & strm, const std::string & name, const unsigned int min, - const unsigned int max ) const; + const unsigned int max ) const override; virtual void serializeInit( std::ostream &, - const int side = 0 ) const; + const int side = 0 ) const override; virtual void serializeChangedPlayer( std::ostream &, const int unum, - const int type = -1 ) const; + const int type = -1 ) const override; }; diff --git a/src/serializeronlinecoachstdv13.h b/src/serializeronlinecoachstdv13.h index 6289c90e..4a87de48 100644 --- a/src/serializeronlinecoachstdv13.h +++ b/src/serializeronlinecoachstdv13.h @@ -34,11 +34,10 @@ class SerializerOnlineCoachStdv13 public: virtual - ~SerializerOnlineCoachStdv13(); + ~SerializerOnlineCoachStdv13() override; static - const - SerializerOnlineCoach::Ptr create(); + const Ptr create(); }; diff --git a/src/serializeronlinecoachstdv14.cpp b/src/serializeronlinecoachstdv14.cpp index 841ab999..5c1abce3 100644 --- a/src/serializeronlinecoachstdv14.cpp +++ b/src/serializeronlinecoachstdv14.cpp @@ -63,6 +63,7 @@ namespace { RegHolder v14 = SerializerOnlineCoach::factory().autoReg( &SerializerOnlineCoachStdv14::create, 14 ); RegHolder v15 = SerializerOnlineCoach::factory().autoReg( &SerializerOnlineCoachStdv14::create, 15 ); RegHolder v16 = SerializerOnlineCoach::factory().autoReg( &SerializerOnlineCoachStdv14::create, 16 ); +RegHolder v17 = SerializerOnlineCoach::factory().autoReg( &SerializerOnlineCoachStdv14::create, 17 ); } } diff --git a/src/serializeronlinecoachstdv14.h b/src/serializeronlinecoachstdv14.h index 9d9796a2..29dd8a72 100644 --- a/src/serializeronlinecoachstdv14.h +++ b/src/serializeronlinecoachstdv14.h @@ -34,11 +34,10 @@ class SerializerOnlineCoachStdv14 public: virtual - ~SerializerOnlineCoachStdv14(); + ~SerializerOnlineCoachStdv14() override; static - const - SerializerOnlineCoach::Ptr create(); + const Ptr create(); }; diff --git a/src/serializeronlinecoachstdv6.h b/src/serializeronlinecoachstdv6.h index 3130887c..dc383e50 100644 --- a/src/serializeronlinecoachstdv6.h +++ b/src/serializeronlinecoachstdv6.h @@ -34,16 +34,14 @@ class SerializerOnlineCoachStdv6 public: virtual - ~SerializerOnlineCoachStdv6(); + ~SerializerOnlineCoachStdv6() override; static - const - Ptr create(); + const Ptr create(); virtual - void - serializeInit( std::ostream &, - const int side = 0 ) const; + void serializeInit( std::ostream &, + const int side = 0 ) const override; }; } diff --git a/src/serializeronlinecoachstdv7.h b/src/serializeronlinecoachstdv7.h index a1caf3e2..d11cb41f 100644 --- a/src/serializeronlinecoachstdv7.h +++ b/src/serializeronlinecoachstdv7.h @@ -34,7 +34,7 @@ class SerializerOnlineCoachStdv7 public: virtual - ~SerializerOnlineCoachStdv7(); + ~SerializerOnlineCoachStdv7() override; static const @@ -44,18 +44,18 @@ class SerializerOnlineCoachStdv7 void serializeRefereeAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializePlayerAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializeChangedPlayer( std::ostream &, const int unum, - const int type = -1 ) const; + const int type = -1 ) const override; }; } diff --git a/src/serializeronlinecoachstdv8.h b/src/serializeronlinecoachstdv8.h index b3c4f00c..2ad87f5b 100644 --- a/src/serializeronlinecoachstdv8.h +++ b/src/serializeronlinecoachstdv8.h @@ -34,17 +34,16 @@ class SerializerOnlineCoachStdv8 public: virtual - ~SerializerOnlineCoachStdv8(); + ~SerializerOnlineCoachStdv8() override; static - const - Ptr create(); + const Ptr create(); virtual void serializePlayerClangVer( std::ostream & strm, const std::string & name, const unsigned int min, - const unsigned int max ) const; + const unsigned int max ) const override; }; } diff --git a/src/serializerplayerstdv1.cpp b/src/serializerplayerstdv1.cpp index b1a56e2f..83cc100c 100644 --- a/src/serializerplayerstdv1.cpp +++ b/src/serializerplayerstdv1.cpp @@ -26,8 +26,8 @@ #include "serializerplayerstdv1.h" #include "param.h" -#include "clangmsg.h" +#include static const char * playmode_strings[] = PLAYMODE_STRINGS; diff --git a/src/serializerplayerstdv1.h b/src/serializerplayerstdv1.h index 091aa051..c598f115 100644 --- a/src/serializerplayerstdv1.h +++ b/src/serializerplayerstdv1.h @@ -34,7 +34,7 @@ class SerializerPlayerStdv1 public: virtual - ~SerializerPlayerStdv1(); + ~SerializerPlayerStdv1() override; static const @@ -43,86 +43,86 @@ class SerializerPlayerStdv1 virtual void serializeRefereeAudio( std::ostream & strm, const int time, - const char * msg ) const; + const char * msg ) const override; virtual void serializeCoachAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializeCoachStdAudio( std::ostream & strm, const int time, const std::string & name, - const rcss::clang::Msg & msg ) const; + const rcss::clang::Msg & msg ) const override; virtual void serializeSelfAudio( std::ostream & strm, const int time, - const char * msg ) const; + const char * msg ) const override; virtual void serializePlayerAudio( std::ostream & strm, const int time, const double & dir, - const char * msg ) const; + const char * msg ) const override; virtual void serializeVisualBegin( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual - void serializeVisualEnd( std::ostream & strm ) const; + void serializeVisualEnd( std::ostream & strm ) const override; virtual void serializeBodyBegin( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual - void serializeBodyEnd( std::ostream & strm ) const; + void serializeBodyEnd( std::ostream & strm ) const override; virtual void serializeBodyViewMode( std::ostream & strm, const char * qual, - const char * width ) const; + const char * width ) const override; virtual void serializeBodyStamina( std::ostream & strm, const double & stamina, const double & effort, - const double & stamina_capacity ) const; + const double & stamina_capacity ) const override; virtual void serializeBodyVelocity( std::ostream & strm, - const double & mag ) const; + const double & mag ) const override; virtual void serializeBodyVelocity( std::ostream & strm, const double & mag, - const int head ) const; + const int head ) const override; virtual void serializeBodyCounts( std::ostream & strm, const int count_kick, const int count_dash, const int count_turn, - const int count_say ) const; + const int count_say ) const override; virtual void serializeBodyCounts( std::ostream & strm, const int count_catch, const int count_move, - const int count_change_view ) const; + const int count_change_view ) const override; virtual void serializeNeckAngle( std::ostream & strm, - const int ang ) const; + const int ang ) const override; virtual void serializeNeckCount( std::ostream & strm, - const int count_turn_neck ) const; + const int count_turn_neck ) const override; virtual void serializeArm( std::ostream & strm, @@ -130,59 +130,59 @@ class SerializerPlayerStdv1 const int expires_cycles, const double & dist, const int head, - const int count ) const; + const int count ) const override; virtual void serializeFocus( std::ostream & strm, const char * name, - const int count ) const; + const int count ) const override; virtual void serializeFocus( std::ostream & strm, const char * team, const int unum, - const int count ) const; + const int count ) const override; virtual void serializeTackle( std::ostream & strm, const int cycles, - const int count ) const; + const int count ) const override; virtual void serializeCollision( std::ostream & strm, const bool ball_collide, const bool player_collide, - const bool post_collide ) const; + const bool post_collide ) const override; virtual void serializeFSBegin( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual - void serializeFSEnd( std::ostream & strm ) const; + void serializeFSEnd( std::ostream & strm ) const override; virtual void serializeFSPlayMode( std::ostream & strm, - const char * mode ) const; + const char * mode ) const override; virtual void serializeFSViewMode( std::ostream & strm, const char * qual, - const char * width ) const; + const char * width ) const override; virtual void serializeFSScore( std::ostream & strm, const int left, - const int right ) const; + const int right ) const override; virtual void serializeFSBall( std::ostream & strm, const double & x, const double & y, const double & vel_x, - const double & vel_y ) const; + const double & vel_y ) const override; virtual void serializeFSPlayerBegin( std::ostream & strm, @@ -195,43 +195,43 @@ class SerializerPlayerStdv1 const double & vel_x, const double & vel_y, const double & body_dir, - const double & neck_dir ) const; + const double & neck_dir ) const override; virtual void serializeFSPlayerStamina( std::ostream & strm, const double & stamina, const double & effort, const double & recovery, - const double & stamina_capacity ) const; + const double & stamina_capacity ) const override; virtual - void serializeFSPlayerEnd( std::ostream & strm ) const; + void serializeFSPlayerEnd( std::ostream & strm ) const override; virtual void serializeInit( std::ostream & strm, const char * side, const int unum, - const PlayMode & mode ) const; + const PlayMode & mode ) const override; virtual void serializeReconnect( std::ostream & strm, const char * side, - const PlayMode & mode ) const; + const PlayMode & mode ) const override; virtual void serializeOKClang( std::ostream & strm, const int min, - const int max ) const; + const int max ) const override; virtual void serializeErrorNoTeamName( std::ostream & strm, - const std::string & team_name ) const; + const std::string & team_name ) const override; virtual void serializeScore( std::ostream & strm, const int time, const int our, - const int opp ) const; + const int opp ) const override; }; } diff --git a/src/serializerplayerstdv13.h b/src/serializerplayerstdv13.h index 042522e1..40149764 100644 --- a/src/serializerplayerstdv13.h +++ b/src/serializerplayerstdv13.h @@ -33,7 +33,7 @@ class SerializerPlayerStdv13 public: virtual - ~SerializerPlayerStdv13(); + ~SerializerPlayerStdv13() override; static const @@ -45,7 +45,7 @@ class SerializerPlayerStdv13 const Player & player, const std::string & name, const double & dist, - const int dir ) const; + const int dir ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -53,7 +53,7 @@ class SerializerPlayerStdv13 const std::string & name, const double & dist, const int dir, - const int point_dir ) const; + const int point_dir ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -64,7 +64,7 @@ class SerializerPlayerStdv13 const double & dist_chg, const double & dir_chg, const int body_dir, - const int head_dir ) const; + const int head_dir ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -76,25 +76,25 @@ class SerializerPlayerStdv13 const double & dir_chg, const int body_dir, const int head_dir, - const int point_dir ) const; + const int point_dir ) const override; virtual void serializeBodyStamina( std::ostream & strm, const double & stamina, const double & effort, - const double & stamina_capacity ) const; + const double & stamina_capacity ) const override; virtual void serializeFSPlayerStamina( std::ostream & strm, const double & stamina, const double & effort, const double & recovery, - const double & stamina_capacity ) const; + const double & stamina_capacity ) const override; virtual void serializeFSPlayerState( std::ostream & strm, - const Player & player ) const; + const Player & player ) const override; }; } diff --git a/src/serializerplayerstdv14.cpp b/src/serializerplayerstdv14.cpp index d5e8175e..2ec4e19e 100644 --- a/src/serializerplayerstdv14.cpp +++ b/src/serializerplayerstdv14.cpp @@ -141,6 +141,7 @@ namespace { RegHolder v14 = SerializerPlayer::factory().autoReg( &SerializerPlayerStdv14::create, 14 ); RegHolder v15 = SerializerPlayer::factory().autoReg( &SerializerPlayerStdv14::create, 15 ); RegHolder v16 = SerializerPlayer::factory().autoReg( &SerializerPlayerStdv14::create, 16 ); +RegHolder v17 = SerializerPlayer::factory().autoReg( &SerializerPlayerStdv14::create, 17 ); } } diff --git a/src/serializerplayerstdv14.h b/src/serializerplayerstdv14.h index 9b9b7640..9b0aa7c4 100644 --- a/src/serializerplayerstdv14.h +++ b/src/serializerplayerstdv14.h @@ -33,7 +33,7 @@ class SerializerPlayerStdv14 public: virtual - ~SerializerPlayerStdv14(); + ~SerializerPlayerStdv14() override; static const @@ -42,7 +42,7 @@ class SerializerPlayerStdv14 virtual void serializeFoul( std::ostream &, - const Player & ) const; + const Player & ) const override; virtual void serializeFSPlayerBegin( std::ostream &, @@ -55,10 +55,10 @@ class SerializerPlayerStdv14 const double &, const double &, const double &, - const double & ) const; + const double & ) const override; virtual void serializeFSPlayerState( std::ostream &, - const Player & ) const; + const Player & ) const override; }; } diff --git a/src/serializerplayerstdv7.cpp b/src/serializerplayerstdv7.cpp index af048b33..97e723ed 100644 --- a/src/serializerplayerstdv7.cpp +++ b/src/serializerplayerstdv7.cpp @@ -25,7 +25,7 @@ #include "serializerplayerstdv7.h" -#include "clangmsg.h" +#include namespace rcss { @@ -104,7 +104,8 @@ SerializerPlayerStdv7::serializePlayerParamEnd( std::ostream & strm ) const } void -SerializerPlayerStdv7::serializePlayerTypeBegin( std::ostream & strm ) const +SerializerPlayerStdv7::serializePlayerTypeBegin( std::ostream & strm, + const int ) const { strm << "(player_type"; } diff --git a/src/serializerplayerstdv7.h b/src/serializerplayerstdv7.h index 670716d1..dff8d340 100644 --- a/src/serializerplayerstdv7.h +++ b/src/serializerplayerstdv7.h @@ -34,7 +34,7 @@ class SerializerPlayerStdv7 public: virtual - ~SerializerPlayerStdv7(); + ~SerializerPlayerStdv7() override; static const @@ -44,24 +44,24 @@ class SerializerPlayerStdv7 void serializeCoachAudio( std::ostream & strm, const int time, const std::string & name, - const char * msg ) const; + const char * msg ) const override; virtual void serializeCoachStdAudio( std::ostream & strm, const int time, const std::string & name, - const rcss::clang::Msg & msg ) const; + const rcss::clang::Msg & msg ) const override; virtual void serializeSelfAudio( std::ostream& strm, const int time, - const char * msg ) const; + const char * msg ) const override; virtual void serializePlayerAudio( std::ostream & strm, const int time, const double & dir, - const char * msg ) const; + const char * msg ) const override; virtual void serializeServerParamBegin( std::ostream & strm ) const; @@ -76,7 +76,8 @@ class SerializerPlayerStdv7 void serializePlayerParamEnd( std::ostream & strm ) const; virtual - void serializePlayerTypeBegin( std::ostream & strm ) const; + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const; virtual void serializePlayerTypeEnd( std::ostream & strm ) const; diff --git a/src/serializerplayerstdv8.cpp b/src/serializerplayerstdv8.cpp index 27b978fa..24b92057 100644 --- a/src/serializerplayerstdv8.cpp +++ b/src/serializerplayerstdv8.cpp @@ -252,7 +252,8 @@ SerializerPlayerStdv8::serializePlayerParamBegin( std::ostream & strm ) const } void -SerializerPlayerStdv8::serializePlayerTypeBegin( std::ostream & strm ) const +SerializerPlayerStdv8::serializePlayerTypeBegin( std::ostream & strm, + const int ) const { strm << "(player_type "; } diff --git a/src/serializerplayerstdv8.h b/src/serializerplayerstdv8.h index 5d914d8b..d12011b3 100644 --- a/src/serializerplayerstdv8.h +++ b/src/serializerplayerstdv8.h @@ -34,7 +34,7 @@ class SerializerPlayerStdv8 public: virtual - ~SerializerPlayerStdv8(); + ~SerializerPlayerStdv8() override; static const @@ -46,7 +46,7 @@ class SerializerPlayerStdv8 const Player & player, const std::string & name, const double & dist, - const int dir ) const; + const int dir ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -54,7 +54,7 @@ class SerializerPlayerStdv8 const std::string & name, const double & dist, const int dir, - const int point_dir ) const; + const int point_dir ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -65,7 +65,7 @@ class SerializerPlayerStdv8 const double & dist_chg, const double & dir_chg, const int body_dir, - const int head_dir ) const; + const int head_dir ) const override; virtual void serializeVisualPlayer( std::ostream & strm, @@ -77,36 +77,36 @@ class SerializerPlayerStdv8 const double & dir_chg, const int body_dir, const int head_dir, - const int point_dir ) const; + const int point_dir ) const override; virtual void serializeAllyAudioFull( std::ostream & strm, const int time, const double & dir, const int unum, - const char * msg ) const; + const char * msg ) const override; virtual void serializeOppAudioFull( std::ostream & strm, const int time, const double & dir, - const char * msg ) const; + const char * msg ) const override; virtual void serializeAllyAudioShort( std::ostream & strm, const int time, - const int unum ) const; + const int unum ) const override; virtual void serializeOppAudioShort( std::ostream & strm, - const int time ) const; + const int time ) const override; virtual void serializeFSBall( std::ostream & strm, const double & x, const double & y, const double & vel_x, - const double & vel_y ) const; + const double & vel_y ) const override; virtual void serializeFSPlayerBegin( std::ostream & strm, @@ -119,19 +119,19 @@ class SerializerPlayerStdv8 const double & vel_x, const double & vel_y, const double & body_dir, - const double & neck_dir ) const; + const double & neck_dir ) const override; virtual void serializeFSPlayerArm( std::ostream & strm, const double & mag, - const double & head ) const; + const double & head ) const override; virtual void serializeFSPlayerStamina( std::ostream & strm, const double & stamina, const double & effort, const double & recovery, - const double & stamina_capacity ) const; + const double & stamina_capacity ) const override; virtual void serializeFSCounts( std::ostream & strm, @@ -142,16 +142,17 @@ class SerializerPlayerStdv8 const int count_move, const int count_turn_neck, const int count_change_view, - const int count_say ) const; + const int count_say ) const override; virtual - void serializeServerParamBegin( std::ostream & strm ) const; + void serializeServerParamBegin( std::ostream & strm ) const override; virtual - void serializePlayerParamBegin( std::ostream & strm ) const; + void serializePlayerParamBegin( std::ostream & strm ) const override; virtual - void serializePlayerTypeBegin( std::ostream & strm ) const; + void serializePlayerTypeBegin( std::ostream & strm, + const int id ) const override; virtual void serializeParam( std::ostream & strm, diff --git a/src/serverparam.cpp b/src/serverparam.cpp index f4d358a5..7e99a5df 100644 --- a/src/serverparam.cpp +++ b/src/serverparam.cpp @@ -40,11 +40,11 @@ #include "utility.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include @@ -351,9 +351,9 @@ const double ServerParam::MAX_DASH_ANGLE = +180.0; const double ServerParam::MIN_DASH_ANGLE = -180.0; const double ServerParam::DASH_ANGLE_STEP = 1.0; // [15.6.0] 45.0 -> 1.0 [14.0.0] 90.0 -> 45.0 const double ServerParam::SIDE_DASH_RATE = 0.4; // [14.0.0] 0.25 -> 0.4 -const double ServerParam::BACK_DASH_RATE = 0.6; // [14.0.0] 0.5 -> 0.6 +const double ServerParam::BACK_DASH_RATE = 0.7; // [14.0.0] 0.5 -> 0.6 [17.0.0] 0.6 -> 0.7 const double ServerParam::MAX_DASH_POWER = +100.0; -const double ServerParam::MIN_DASH_POWER = -100.0; +const double ServerParam::MIN_DASH_POWER = 0.0; // 14.0.0 const double ServerParam::TACKLE_RAND_FACTOR = 2.0; @@ -371,6 +371,12 @@ const int ServerParam::ILLEGAL_DEFENSE_NUMBER = 0; const double ServerParam::ILLEGAL_DEFENSE_DIST_X = 16.5; const double ServerParam::ILLEGAL_DEFENSE_WIDTH = 40.32; +namespace { +// 17.0.0 +constexpr double MAX_CATCH_ANGLE = +90.0; +constexpr double MIN_CATCH_ANGLE = -90.0; +} + // XXX const double ServerParam::LONG_KICK_POWER_FACTOR = 2.0; const int ServerParam::LONG_KICK_DELAY = 2; @@ -399,7 +405,7 @@ ServerParam::init( const int & argc, } // DIR* config_dir = opendir( config_dir_name.c_str() ); -// if ( config_dir == NULL ) +// if ( ! config_dir ) // { // int err = mkdir( config_dir_name.c_str(), 0777 ); // if ( err != 0 ) @@ -414,19 +420,11 @@ ServerParam::init( const int & argc, boost::filesystem::path conf_path; try { - conf_path = boost::filesystem::path( tildeExpand( conf_dir ) -#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2 -# ifndef BOOST_FILESYSTEM_NO_DEPRECATED - , &boost::filesystem::native -# endif -#endif - ); + conf_path = boost::filesystem::path( tildeExpand( conf_dir ) ); if ( ! boost::filesystem::exists( conf_path ) && ! boost::filesystem::create_directories( conf_path ) ) { - std::cerr << "Could not read or create config directory '" - << conf_path.BOOST_FS_FILE_STRING() << "'" - << std::endl; + std::cerr << "Could not read or create config directory " << conf_path << std::endl; instance().clear(); return false; } @@ -444,13 +442,11 @@ ServerParam::init( const int & argc, return false; } - instance().convertOldConf( conf_path.BOOST_FS_FILE_STRING() ); + instance().convertOldConf( conf_path.string() ); if ( ! instance().M_conf_parser->parseCreateConf( conf_path, "server" ) ) { - std::cerr << "could not create or parse configuration file '" - << conf_path.BOOST_FS_FILE_STRING() << "'" - << std::endl; + std::cerr << "could not create or parse configuration file " << conf_path << std::endl; instance().M_builder->displayHelp(); instance().clear(); return false; @@ -459,7 +455,7 @@ ServerParam::init( const int & argc, if ( instance().M_builder->version() != instance().M_builder->parsedVersion() ) { std::cerr << "Version mismatched in the configuration file. " - << "You need to regenerate '" << conf_path.BOOST_FS_FILE_STRING() << "'" + << "You need to regenerate " << conf_path << " or set '" << instance().M_builder->version() << "' to the 'version' option." << std::endl; // std::cerr << "registered version = [" @@ -944,6 +940,10 @@ ServerParam::addParams() rcss::conf::makeGetter( M_fixed_teamname_r ), "", 16 ); + // v17 + addParam( "max_catch_angle", M_max_catch_angle, "", 17 ); + addParam( "min_catch_angle", M_min_catch_angle, "", 17 ); + // XXX // addParam( "random_seed", M_random_seed, "", 999 ); // addParam( "long_kick_power_factor", M_long_kick_power_factor, "", 999 ); @@ -1447,6 +1447,10 @@ ServerParam::setDefaults() M_fixed_teamname_l = ""; M_fixed_teamname_r = ""; + // 17.0.0 + M_max_catch_angle = MAX_CATCH_ANGLE; + M_min_catch_angle = MIN_CATCH_ANGLE; + // XXX M_long_kick_power_factor = LONG_KICK_POWER_FACTOR; M_long_kick_delay = LONG_KICK_DELAY; diff --git a/src/serverparam.h b/src/serverparam.h index cb51df3d..b7884454 100644 --- a/src/serverparam.h +++ b/src/serverparam.h @@ -35,7 +35,7 @@ #include "types.h" -#include +#include #include #include @@ -66,9 +66,9 @@ class ServerParam { private: - ServerParam(); // not used - ServerParam( const ServerParam & ); // not used - ServerParam & operator=( const ServerParam & ); // not used + ServerParam() = delete; // not used + ServerParam( const ServerParam & ) = delete; // not used + ServerParam & operator=( const ServerParam & ) = delete; // not used protected: @@ -336,15 +336,16 @@ class ServerParam { static const bool GOLDEN_GOAL; // 15.0.0 static const double RED_CARD_PROBABILITY; - // XXX - static const double LONG_KICK_POWER_FACTOR; - static const int LONG_KICK_DELAY; // 16.0.0 static const int ILLEGAL_DEFENSE_DURATION; static const int ILLEGAL_DEFENSE_NUMBER; static const double ILLEGAL_DEFENSE_DIST_X; static const double ILLEGAL_DEFENSE_WIDTH; + // XXX + static const double LONG_KICK_POWER_FACTOR; + static const int LONG_KICK_DELAY; + double M_goal_width; /* goal width */ double M_inertia_moment; /* intertia moment for turn */ double M_player_size; /* player size */ @@ -617,6 +618,10 @@ class ServerParam { std::string M_fixed_teamname_l; std::string M_fixed_teamname_r; + // 17.0.0 + double M_max_catch_angle; + double M_min_catch_angle; + // XXX double M_long_kick_power_factor; int M_long_kick_delay; @@ -971,6 +976,10 @@ class ServerParam { const std::string & fixedTeamNameLeft() const { return M_fixed_teamname_l; } const std::string & fixedTeamNameRight() const { return M_fixed_teamname_r; } + // v17 + double maxCatchAngle() const { return M_max_catch_angle; } + double minCatchAngle() const { return M_min_catch_angle; } + // XXX double longKickPowerFactor() const { return M_long_kick_power_factor; } int longKickDelay() const { return M_long_kick_delay; } diff --git a/src/stadium.cpp b/src/stadium.cpp index 2a88849f..b5168216 100644 --- a/src/stadium.cpp +++ b/src/stadium.cpp @@ -26,9 +26,9 @@ #include "stadium.h" #include "audio.h" -#include "clangmsg.h" #include "coach.h" #include "landmarkreader.h" +#include "logger.h" #include "monitor.h" #include "object.h" #include "param.h" @@ -44,16 +44,15 @@ #include "utility.h" #include "xpmholder.h" -#ifdef HAVE_SSTREAM -#include -#else -#include -#endif +#include +#include #include #include #include #include +#include +#include #include #include @@ -62,23 +61,15 @@ #include #include -#ifdef HAVE_SYS_TIME_H -#include // gettimeofday -#endif -#ifdef HAVE_UNI_STD_H -#include -#endif - Stadium::Stadium() : M_alive( true ), - M_logger( *this ), - M_ball( NULL ), + M_ball( nullptr ), M_players( MAX_PLAYER*2, static_cast< Player * >( 0 ) ), - M_coach( NULL ), + M_coach( nullptr ), M_olcoaches( 2, static_cast< OnlineCoach * >( 0 ) ), - M_team_l( NULL ), - M_team_r( NULL ), + M_team_l( nullptr ), + M_team_r( nullptr ), M_playmode( PM_BeforeKickOff ), M_time( 0 ), M_stoppage_time( 0 ), @@ -89,25 +80,6 @@ Stadium::Stadium() M_left_child( 0 ), M_right_child( 0 ) { -#if 0 - time_t tmp_time = std::time( NULL ); - tm * tmp_local_time = std::localtime( &tmp_time ); - if ( tmp_local_time == NULL ) - { - std::cerr << __FILE__ << ":" << __LINE__ - << ": Error getting time: " - << strerror( errno ) << std::endl; - //this->exit( EXIT_FAILURE ); - disable(); - return; - } - m_real_time = *tmp_local_time; - - srand( tmp_time ); - srandom( tmp_time ); - rcss::random::DefaultRNG::instance( static_cast< rcss::random::DefaultRNG::result_type >( tmp_time ) ); -#endif - // !!! registration order is very important !!! // TODO: fix dependencies among referees. M_referees.push_back( new TimeRef( *this ) ); @@ -181,18 +153,18 @@ Stadium::~Stadium() it != M_player_types.end(); ++it ) { - if ( *it != NULL ) + if ( *it ) { delete *it; } } M_player_types.clear(); - delete M_team_l; M_team_l = NULL; - delete M_team_r; M_team_r = NULL; + delete M_team_l; M_team_l = nullptr; + delete M_team_r; M_team_r = nullptr; - delete M_coach; M_coach = NULL; - delete M_ball; M_ball = NULL; + delete M_coach; M_coach = nullptr; + delete M_ball; M_ball = nullptr; } @@ -205,18 +177,7 @@ Stadium::~Stadium() bool Stadium::init() { - time_t tmp_time = std::time( NULL ); - tm * tmp_local_time = std::localtime( &tmp_time ); - if ( tmp_local_time == NULL ) - { - std::cerr << __FILE__ << ":" << __LINE__ - << ": Error getting time: " - << strerror( errno ) << std::endl; - //this->exit( EXIT_FAILURE ); - disable(); - return false; - } - m_real_time = *tmp_local_time; + M_start_time = std::time( 0 ); if ( ServerParam::instance().randomSeed() >= 0 ) { @@ -224,16 +185,16 @@ Stadium::init() std::cout << "Using given Simulator Random Seed: " << seed << std::endl; srand( seed ); srandom( seed ); - rcss::random::DefaultRNG::instance( static_cast< rcss::random::DefaultRNG::result_type >( seed ) ); + DefaultRNG::seed( seed ); } else { - int seed = static_cast< int >( tmp_time ); + int seed = static_cast< int >( M_start_time ); std::cout << "Simulator Random Seed: " << seed << std::endl; ServerParam::instance().setRandomSeed( seed ); srand( seed ); srandom( seed ); - rcss::random::DefaultRNG::instance( static_cast< rcss::random::DefaultRNG::result_type >( seed ) ); + DefaultRNG::seed( seed ); } //std::cout << "Simulator Random Seed: " << ServerParam::instance().randomSeed() << std::endl; @@ -244,12 +205,10 @@ Stadium::init() // errors creating them, it will be reported before // the game starts, not after it has finished. std::list< ResultSaver::FactoryHolder::Index > savers = ResultSaver::factory().list(); - for ( std::list< ResultSaver::FactoryHolder::Index >::iterator i = savers.begin(); - i != savers.end(); - ++i ) + for ( const auto & idx : savers ) { ResultSaver::Creator creator; - if ( ResultSaver::factory().getCreator( creator, *i ) ) + if ( ResultSaver::factory().getCreator( creator, idx ) ) { ResultSaver::Ptr saver = creator(); std::cout << saver->getName() << ": Ready\n"; @@ -257,11 +216,10 @@ Stadium::init() } else { - std::cerr << *i << ": error loading" << std::endl; + std::cerr << idx << ": error loading" << std::endl; } } - if ( ServerParam::instance().coachMode() && ! ServerParam::instance().coachWithRefereeMode() ) { @@ -337,7 +295,7 @@ Stadium::init() M_connect_wait = std::max( 0, ServerParam::instance().connectWait() ); - if ( ! M_logger.open() ) + if ( ! Logger::instance().open( *this ) ) { disable(); return false; @@ -478,7 +436,7 @@ Stadium::startTeam( const std::string & start ) if ( pid == 0 ) { - execlp( "/bin/sh", "sh", "-c", start.c_str(), (char *)NULL ); + execlp( "/bin/sh", "sh", "-c", start.c_str(), (char *)nullptr ); std::cerr << PACKAGE << "-" << VERSION << ": Error: Could not execute \"/bin/sh -c " << start.c_str() << "\": " @@ -548,7 +506,7 @@ Stadium::playerType( int id ) const std::cerr << __FILE__ << ':' << __LINE__ << " Exception caught! " << e.what() << std::endl; - return NULL; + return nullptr; } } @@ -732,13 +690,13 @@ Stadium::initCoach( const double & version, if ( M_coach->open() != 0 ) { sendToCoach( "(error socket_open_failed)", addr ); - return NULL; + return nullptr; } if ( ! M_coach->connect( addr ) ) { sendToCoach( "(error connection_failed)", addr ); - return NULL; + return nullptr; } if ( ! M_coach->setSenders( version ) ) @@ -746,7 +704,7 @@ Stadium::initCoach( const double & version, std::cerr << "Error: Could not find serializer or sender for version" << version << std::endl; sendToCoach( "(error illegal_client_version)", addr ); - return NULL; + return nullptr; } addOfflineCoach( M_coach ); @@ -830,17 +788,13 @@ Stadium::initOnlineCoach( const char * teamname, void Stadium::step() { - const PlayerCont::iterator end = M_players.end(); - // // reset command flags // - for ( PlayerCont::iterator p = M_players.begin(); - p != end; - ++p ) + for ( PlayerCont::reference p : M_players ) { - (*p)->resetCommandFlags(); - (*p)->incArmAge(); + p->resetCommandFlags(); + p->incArmAge(); } for ( int i = 0; i < 2; ++i ) @@ -859,7 +813,8 @@ Stadium::step() { turnMovableObjects(); ++M_stoppage_time; - for_each( M_referees.begin(), M_referees.end(), &Referee::doAnalyse ); + //for_each( M_referees.begin(), M_referees.end(), &Referee::doAnalyse ); + for_each( M_referees.begin(), M_referees.end(), []( Referee * ref ) { ref->analyse(); } ); } else if ( playmode() == PM_AfterGoal_Right || playmode() == PM_AfterGoal_Left @@ -882,7 +837,8 @@ Stadium::step() clearBallCatcher(); incMovableObjects(); ++M_stoppage_time; - for_each( M_referees.begin(), M_referees.end(), &Referee::doAnalyse ); + //for_each( M_referees.begin(), M_referees.end(), &Referee::doAnalyse ); + for_each( M_referees.begin(), M_referees.end(), []( Referee * ref ) { ref->analyse(); } ); if ( pm != playmode() ) { ++M_time; @@ -894,8 +850,9 @@ Stadium::step() incMovableObjects(); ++M_time; M_stoppage_time = 0; - for_each( M_referees.begin(), M_referees.end(), &Referee::doAnalyse ); + //for_each( M_referees.begin(), M_referees.end(), &Referee::doAnalyse ); //for_each( M_referees.begin(), M_referees.end(), std::mem_fun( &Referee::analyse ) ); + for_each( M_referees.begin(), M_referees.end(), []( Referee * ref ) { ref->analyse(); } ); } else if ( playmode() == PM_TimeOver ) { @@ -905,14 +862,12 @@ Stadium::step() // // update stamina etc // - for ( PlayerCont::iterator p = M_players.begin(); - p != end; - ++p ) + for ( PlayerCont::reference p : M_players ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - (*p)->updateStamina(); - (*p)->updateCapacity(); + p->updateStamina(); + p->updateCapacity(); } if ( stoppageTime() == 0 @@ -934,43 +889,33 @@ Stadium::step() // // reset player state // - for ( PlayerCont::iterator p = M_players.begin(); - p != end; - ++p ) + for ( PlayerCont::reference p : M_players ) { - (*p)->resetState(); + p->resetState(); } } void Stadium::turnMovableObjects() { - std::random_shuffle( M_movable_objects.begin(), - M_movable_objects.end(), - irand ); - const MPObjectCont::iterator end = M_movable_objects.end(); - for ( MPObjectCont::iterator it = M_movable_objects.begin(); - it != end; - ++it ) + std::shuffle( M_movable_objects.begin(), M_movable_objects.end(), + DefaultRNG::instance() ); + for ( MPObjectCont::reference o : M_movable_objects ) { - (*it)->_turn(); + o->_turn(); } } void Stadium::incMovableObjects() { - std::random_shuffle( M_movable_objects.begin(), - M_movable_objects.end(), - irand ); - const MPObjectCont::iterator end = M_movable_objects.end(); - for ( MPObjectCont::iterator it = M_movable_objects.begin(); - it != end; - ++it ) + std::shuffle( M_movable_objects.begin(), M_movable_objects.end(), + DefaultRNG::instance() ); + for ( MPObjectCont::reference o : M_movable_objects ) { - if ( (*it)->isEnabled() ) + if ( o->isEnabled() ) { - (*it)->_inc(); + o->_inc(); } } @@ -991,47 +936,31 @@ Stadium::incMovableObjects() void Stadium::sendDisp() { - timeval tv_start, tv_end; - - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); // send to displays - for ( MonitorCont::iterator i = M_monitors.begin(); - i != M_monitors.end(); - ++i ) + for ( MonitorCont::reference m : M_monitors ) { - (*i)->sendShow(); + m->sendShow(); } // record game log - M_logger.writeGameLog(); - M_logger.flush(); - - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "DISP" ); - } + Logger::instance().writeGameLog( *this ); + Logger::instance().flush(); + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "DISP" ); } void Stadium::recoveryPlayers() { - const PlayerCont::iterator end = M_players.end(); - for ( PlayerCont::iterator p = M_players.begin(); - p != end; - ++p ) + for ( PlayerCont::reference p : M_players ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - (*p)->recoverAll(); + p->recoverAll(); } } @@ -1203,14 +1132,11 @@ Stadium::callHalfTime( const Side kick_off_side, // recover only stamina capacity at the start of extra halves if ( half_time_count == ServerParam::instance().nrNormalHalfs() ) { - const PlayerCont::iterator end = M_players.end(); - for ( PlayerCont::iterator p = M_players.begin(); - p != end; - ++p ) + for ( PlayerCont::reference p : M_players ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - (*p)->recoverStaminaCapacity(); + p->recoverStaminaCapacity(); } } @@ -1504,7 +1430,11 @@ Stadium::changePlayMode( const PlayMode pm ) M_playmode = pm; for_each( M_referees.begin(), M_referees.end(), - Referee::doPlayModeChange( pm ) ); + //Referee::doPlayModeChange( pm ) ); + [&]( Referee * ref ) + { + ref->playModeChange( pm ); + } ); if ( pm == PM_KickOff_Left || pm == PM_KickIn_Left @@ -1640,13 +1570,12 @@ Stadium::broadcastSubstitution( const int side, "(change_player_type %s %d %d)", ( side == LEFT ? "l" : "r" ), unum, player_type ); - for ( MonitorCont::iterator i = M_monitors.begin(); - i != M_monitors.end(); ++i ) + for ( MonitorCont::reference m : M_monitors ) { - (*i)->sendMsg( MSG_BOARD, buffer ); + m->sendMsg( MSG_BOARD, buffer ); } - M_logger.writeTextLog( buffer, SUBS ); + Logger::instance().writeTextLog( *this, buffer, SUBS ); } @@ -1705,13 +1634,12 @@ Stadium::broadcastChangePlayerToGoalie( const Player * player ) // TODO: send to offline coach // monitors - for ( MonitorCont::iterator i = M_monitors.begin(); - i != M_monitors.end(); ++i ) + for ( MonitorCont::reference m : M_monitors ) { - (*i)->sendMsg( MSG_BOARD, msg ); + m->sendMsg( MSG_BOARD, msg ); } - M_logger.writeTextLog( msg, SUBS ); + Logger::instance().writeTextLog( *this, msg, SUBS ); } @@ -1722,34 +1650,32 @@ Stadium::collisions() int max_loop = 10; const std::size_t SIZE = M_players.size(); - const PlayerCont::iterator end = M_players.end(); do { col = false; M_ball->clearCollision(); - for ( PlayerCont::iterator it = M_players.begin(); - it != end; - ++it ) + for ( PlayerCont::reference p : M_players ) { - (*it)->clearCollision(); + p->clearCollision(); } // check ball to player - for ( PlayerCont::iterator it = M_players.begin(); - it != end; - ++it ) - { - if ( (*it)->isEnabled() - && (*it) != M_ball_catcher - && M_ball->pos().distance2( (*it)->pos() ) - < std::pow( M_ball->size() + (*it)->size(), 2 ) ) + for ( PlayerCont::reference p : M_players ) + { + if ( p->isEnabled() + && p != M_ball_catcher + && M_ball->pos().distance2( p->pos() ) < std::pow( M_ball->size() + p->size(), 2 ) ) { col = true; - (*it)->collidedWithBall(); + p->collidedWithBall(); for_each( M_referees.begin(), M_referees.end(), - Referee::doBallTouched( **it ) ); - calcBallCollisionPos( *it ); + //Referee::doBallTouched( *p ) ); + [&]( Referee * ref ) + { + ref->ballTouched( *p ); + } ); + calcBallCollisionPos( p ); } } @@ -1760,8 +1686,7 @@ Stadium::collisions() { if ( M_players[i]->isEnabled() && M_players[j]->isEnabled() - && M_players[i]->pos().distance2( M_players[j]->pos() ) - < std::pow( M_players[i]->size() + M_players[j]->size(), 2 ) ) + && M_players[i]->pos().distance2( M_players[j]->pos() ) < std::pow( M_players[i]->size() + M_players[j]->size(), 2 ) ) { col = true; M_players[i]->collidedWithPlayer(); @@ -1772,11 +1697,9 @@ Stadium::collisions() } M_ball->moveToCollisionPos(); - for ( PlayerCont::iterator it = M_players.begin(); - it != end; - ++it ) + for ( PlayerCont::reference p : M_players ) { - (*it)->moveToCollisionPos(); + p->moveToCollisionPos(); } --max_loop; @@ -1788,11 +1711,9 @@ Stadium::collisions() // << std::endl; M_ball->updateCollisionVel(); - for ( PlayerCont::iterator it = M_players.begin(); - it != end; - ++it ) + for ( PlayerCont::reference p : M_players ) { - (*it)->updateCollisionVel(); + p->updateCollisionVel(); } } @@ -1826,7 +1747,7 @@ void Stadium::calcCollisionPos( MPObject * a, MPObject * b ) { - if ( a == NULL || b == NULL ) + if ( ! a || ! b ) { return; } @@ -1943,15 +1864,24 @@ Stadium::kickTaken( const Player & kicker, M_ball->push( accel ); + const double accel_r = accel.r(); for_each( M_referees.begin(), M_referees.end(), - Referee::doKickTaken( kicker, accel.r() ) ); + //Referee::doKickTaken( kicker, accel.r() ) ); + [&]( Referee * ref ) + { + ref->kickTaken( kicker, accel_r ); + } ); } void Stadium::failedKickTaken( const Player & kicker ) { for_each( M_referees.begin(), M_referees.end(), - Referee::doFailedKickTaken( kicker ) ); + //Referee::doFailedKickTaken( kicker ) ); + [&]( Referee * ref ) + { + ref->failedKickTaken( kicker ); + } ); } void @@ -1963,8 +1893,13 @@ Stadium::tackleTaken( const Player & tackler, M_ball->push( accel ); + const double accel_r = accel.r(); for_each( M_referees.begin(), M_referees.end(), - Referee::doTackleTaken( tackler, accel.r(), foul ) ); + //Referee::doTackleTaken( tackler, accel.r(), foul ) ); + [&]( Referee * ref ) + { + ref->tackleTaken( tackler, accel_r, foul ); + } ); } void @@ -1972,7 +1907,11 @@ Stadium::failedTackleTaken( const Player & tackler, const bool foul ) { for_each( M_referees.begin(), M_referees.end(), - Referee::doFailedTackleTaken( tackler, foul ) ); + //Referee::doFailedTackleTaken( tackler, foul ) ); + [&]( Referee * ref ) + { + ref->failedTackleTaken( tackler, foul ); + } ); } @@ -1989,10 +1928,18 @@ Stadium::ballCaught( const Player & catcher ) collisions(); for_each( M_referees.begin(), M_referees.end(), - Referee::doBallTouched( catcher ) ); + //Referee::doBallTouched( catcher ) ); + [&]( Referee * ref ) + { + ref->ballTouched( catcher ); + } ); for_each( M_referees.begin(), M_referees.end(), - Referee::doCaughtBall( catcher ) ); + //Referee::doCaughtBall( catcher ) ); + [&]( Referee * ref ) + { + ref->ballCaught( catcher ); + } ); if ( playmode() == PM_FreeKick_Left || playmode() == PM_FreeKick_Right ) @@ -2008,10 +1955,18 @@ Stadium::ballPunched( const Player & catcher, M_ball->push( accel ); for_each( M_referees.begin(), M_referees.end(), - Referee::doBallTouched( catcher ) ); + //Referee::doBallTouched( catcher ) ); + [&]( Referee * ref ) + { + ref->ballTouched( catcher ); + } ); for_each( M_referees.begin(), M_referees.end(), - Referee::doPunchedBall( catcher ) ); + //Referee::doPunchedBall( catcher ) ); + [&]( Referee * ref ) + { + ref->ballPunched( catcher ); + } ); } void @@ -2019,7 +1974,7 @@ Stadium::sendTeamGraphic( const Side side, const unsigned int x, const unsigned int y ) { - M_logger.writeTeamGraphic( side, x, y ); + Logger::instance().writeTeamGraphic( side, x, y ); } @@ -2091,23 +2046,20 @@ Stadium::removeDisconnectedClients() void Stadium::sendRefereeAudio( const char * msg ) { - std::random_shuffle( M_listeners.begin(), M_listeners.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( M_listeners.begin(), M_listeners.end(), + DefaultRNG::instance() ); // the following should work, but I haven't tested it yet // std::for_each( M_listeners.begin(), M_listeners.end(), // std::bind2nd( std::mem_fun( &rcss::Listener::sendRefereeAudio ), // msg.c_str() ) ); - const ListenerCont::iterator end = M_listeners.end(); - for ( ListenerCont::iterator it = M_listeners.begin(); - it != end; - ++it ) + for ( ListenerCont::reference l : M_listeners ) { - (*it)->sendRefereeAudio( msg ); + l->sendRefereeAudio( msg ); } - M_logger.writeRefereeAudio( msg ); + Logger::instance().writeRefereeAudio( *this, msg ); if ( ServerParam::instance().sendComms() ) { @@ -2117,11 +2069,9 @@ Stadium::sendRefereeAudio( const char * msg ) "(%s %s)", REFEREE_NAME, msg ); - for ( MonitorCont::iterator i = M_monitors.begin(); - i != M_monitors.end(); - ++i ) + for ( MonitorCont::reference m : M_monitors ) { - (*i)->sendMsg( MSG_BOARD, buf ); + m->sendMsg( MSG_BOARD, buf ); } } } @@ -2131,18 +2081,15 @@ void Stadium::sendPlayerAudio( const Player & player, const char * msg ) { - std::random_shuffle( M_listeners.begin(), M_listeners.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( M_listeners.begin(), M_listeners.end(), + DefaultRNG::instance() ); - const ListenerCont::iterator end = M_listeners.end(); - for ( ListenerCont::iterator it = M_listeners.begin(); - it != end; - ++it ) + for ( ListenerCont::reference l : M_listeners ) { - (*it)->sendPlayerAudio( player, msg ); + l->sendPlayerAudio( player, msg ); } - M_logger.writePlayerAudio( player, msg ); + Logger::instance().writePlayerAudio( *this, player, msg ); if ( ServerParam::instance().sendComms() ) { @@ -2153,11 +2100,9 @@ Stadium::sendPlayerAudio( const Player & player, player.name().c_str(), msg ); // send to monitors - for ( Stadium::MonitorCont::iterator i = monitors().begin(); - i != monitors().end(); - ++i ) + for ( MonitorCont::reference m : monitors() ) { - (*i)->sendMsg( MSG_BOARD, buf ); + m->sendMsg( MSG_BOARD, buf ); } } } @@ -2167,18 +2112,15 @@ void Stadium::sendCoachAudio( const Coach & coach, const char * msg ) { - std::random_shuffle( M_listeners.begin(), M_listeners.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( M_listeners.begin(), M_listeners.end(), + DefaultRNG::instance() ); - const ListenerCont::iterator end = M_listeners.end(); - for ( ListenerCont::iterator it = M_listeners.begin(); - it != end; - ++it ) + for ( ListenerCont::reference l : M_listeners ) { - (*it)->sendCoachAudio( coach, msg ); + l->sendCoachAudio( coach, msg ); } - M_logger.writeCoachAudio( coach, msg ); + Logger::instance().writeCoachAudio( *this, coach, msg ); if ( ServerParam::instance().sendComms() ) { @@ -2195,11 +2137,9 @@ Stadium::sendCoachAudio( const Coach & coach, ? OLCOACH_NAME_L: REFEREE_NAME ), msg ); - for ( MonitorCont::iterator i = monitors().begin(); - i != monitors().end(); - ++i ) + for ( MonitorCont::reference m : monitors() ) { - (*i)->sendMsg( MSG_BOARD, buf ); + m->sendMsg( MSG_BOARD, buf ); } } } @@ -2208,18 +2148,15 @@ void Stadium::sendCoachStdAudio( const OnlineCoach & coach, const rcss::clang::Msg & msg ) { - std::random_shuffle( M_listeners.begin(), M_listeners.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( M_listeners.begin(), M_listeners.end(), + DefaultRNG::instance() ); - const ListenerCont::iterator end = M_listeners.end(); - for ( ListenerCont::iterator it = M_listeners.begin(); - it != end; - ++it ) + for ( ListenerCont::reference l : M_listeners ) { - (*it)->sendCoachStdAudio( msg ); + l->sendCoachStdAudio( msg ); } - M_logger.writeCoachStdAudio( coach, msg ); + Logger::instance().writeCoachStdAudio( *this, coach, msg ); if ( ServerParam::instance().sendComms() ) { @@ -2238,11 +2175,9 @@ Stadium::sendCoachStdAudio( const OnlineCoach & coach, (coach.side() == RIGHT) ? OLCOACH_NAME_R : OLCOACH_NAME_L, coach_mess.str().c_str() ); - for ( MonitorCont::iterator i = monitors().begin(); - i != monitors().end(); - ++i ) + for ( MonitorCont::reference m : monitors() ) { - (*i)->sendMsg( MSG_BOARD, buf ); + m->sendMsg( MSG_BOARD, buf ); } } @@ -2255,13 +2190,7 @@ Stadium::doRecvFromClients() static int s_time = 0; static int s_stoppage_time = 0; - timeval tv_start, tv_end; - - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); // // delayed effects @@ -2272,13 +2201,11 @@ Stadium::doRecvFromClients() s_time = M_time; s_stoppage_time = M_stoppage_time; - std::random_shuffle( M_shuffle_players.begin(), M_shuffle_players.end(), irand ); - for ( PlayerCont::iterator p = M_shuffle_players.begin(), - p_end = M_shuffle_players.end(); - p != p_end; - ++p ) + std::shuffle( M_shuffle_players.begin(), M_shuffle_players.end(), + DefaultRNG::instance() ); + for ( PlayerCont::reference p : M_shuffle_players ) { - (*p)->doLongKick(); + p->doLongKick(); } } @@ -2291,38 +2218,22 @@ Stadium::doRecvFromClients() removeDisconnectedClients(); - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "RECV" ); - } + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "RECV" ); } void Stadium::doNewSimulatorStep() { - static timeval tp_old; - timeval tp_new, tv_start, tv_end; + static std::chrono::system_clock::time_point prev_time = std::chrono::system_clock::now(); + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); // th 6.3.00 - if ( M_logger.isTextLogOpen() ) - { - if ( ServerParam::instance().logTimes() ) - { - // tp_old = tp_new; - // write_times displays nonsense at first call, since tp_old is never - // initialized. Don't want to handle special exception for first call. - gettimeofday( &tp_new, NULL ); - M_logger.writeTimes( tp_old, tp_new ); - gettimeofday( &tp_old, NULL ); - } - - if ( ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } - } + // tp_old = tp_new; + // write_times displays nonsense at first call, since tp_old is never + // initialized. Don't want to handle special exception for first call. + Logger::instance().writeTimes( *this, prev_time, start_time ); + prev_time = start_time; // // step @@ -2331,147 +2242,104 @@ Stadium::doNewSimulatorStep() startTeams(); checkAutoMode(); - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "SIM" ); - } + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "SIM" ); } void Stadium::doSendSenseBody() { - struct timeval tv_start, tv_end; - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); - std::random_shuffle( M_remote_players.begin(), M_remote_players.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( M_remote_players.begin(), M_remote_players.end(), + DefaultRNG::instance() ); // // send sense_body & fullstate // - const PlayerCont::iterator end = M_remote_players.end(); - for ( PlayerCont::iterator it = M_remote_players.begin(); - it != end; - ++it ) + for ( PlayerCont::reference p : M_remote_players ) { - if ( (*it)->isEnabled() - && (*it)->connected() ) + if ( p->isEnabled() + && p->connected() ) { - (*it)->sendBody(); + p->sendBody(); - if ( ( (*it)->side() == LEFT + if ( ( p->side() == LEFT && ServerParam::instance().fullstateLeft() ) - || ( (*it)->side() == RIGHT + || ( p->side() == RIGHT && ServerParam::instance().fullstateRight() ) ) { - (*it)->sendFullstate(); + p->sendFullstate(); } } // reset collision flags - (*it)->resetCollisionFlags(); + p->resetCollisionFlags(); } // // send audio message // std::for_each( M_listeners.begin(), M_listeners.end(), - rcss::Listener::NewCycle() ); //std::mem_fun( &rcss::Listener::newCycle ) ); + []( rcss::Listener * l ) + { + l->newCycle(); + } ); + //rcss::Listener::NewCycle() ); //std::mem_fun( &rcss::Listener::newCycle ) ); // // write profile // - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "SB" ); - } + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "SB" ); } void Stadium::doSendVisuals() { - struct timeval tv_start, tv_end; + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } + std::shuffle( M_remote_players.begin(), M_remote_players.end(), + DefaultRNG::instance() ); - std::random_shuffle( M_remote_players.begin(), M_remote_players.end(), - irand ); //rcss::random::UniformRNG::instance() ); - - const PlayerCont::iterator end = M_remote_players.end(); - for ( PlayerCont::iterator it = M_remote_players.begin(); - it != end; - ++it ) + for ( PlayerCont::reference p : M_remote_players ) { - if ( (*it)->isEnabled() - && (*it)->connected() ) + if ( p->isEnabled() + && p->connected() ) { - (*it)->sendVisual(); + p->sendVisual(); } } - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "VIS" ); - } + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "VIS" ); } void Stadium::doSendSynchVisuals() { - struct timeval tv_start, tv_end; - // std::cerr << "sendSynchVisuals time=" << time() << std::endl; - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); - std::random_shuffle( M_remote_players.begin(), M_remote_players.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( M_remote_players.begin(), M_remote_players.end(), + DefaultRNG::instance() ); - const PlayerCont::iterator end = M_remote_players.end(); - for ( PlayerCont::iterator it = M_remote_players.begin(); - it != end; - ++it ) + for ( PlayerCont::reference p : M_remote_players ) { - if ( (*it)->isEnabled() - && (*it)->connected() ) + if ( p->isEnabled() + && p->connected() ) { - (*it)->sendSynchVisual(); + p->sendSynchVisual(); } } - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "VIS_S" ); - } + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "VIS_S" ); } void Stadium::doSendCoachMessages() { - struct timeval tv_start, tv_end; - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_start, NULL ); - } + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); if ( M_coach->assigned() && M_coach->isEyeOn() ) @@ -2487,12 +2355,8 @@ Stadium::doSendCoachMessages() } } - if ( M_logger.isTextLogOpen() - && ServerParam::instance().profile() ) - { - gettimeofday( &tv_end, NULL ); - M_logger.writeProfile( tv_start, tv_end, "COACH" ); - } + const std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); + Logger::instance().writeProfile( *this, start_time, end_time, "COACH" ); #if 0 // At each cycle we flush to logs otherwise the buffers @@ -2518,7 +2382,7 @@ Stadium::doSendCoachMessages() // reason for introducting threads to the code that to improve // logging. Maybe later, when we already have a thread for each // client it will seem like less of a hurdle. - M_logger.flush(); + Logger::instance().flush(); #endif } @@ -2532,12 +2396,13 @@ Stadium::doSendThink() static int cycles_missed = 0; //number of cycles where someone missed bool shutdown = false; - timeval tv_start, tv_now; if ( time() <= 0 ) { //still waiting for players to connect, so let's run a little more slowly - usleep( 50 * 1000 ); + std::chrono::microseconds sleep_count( 50 * 1000 ); + std::this_thread::sleep_for( sleep_count ); + //usleep( 50 * 1000 ); } else if ( ! monitors().empty() ) { @@ -2545,7 +2410,9 @@ Stadium::doSendThink() if ( ++monitor_wait_count >= 32 ) { monitor_wait_count = 0; - usleep( 20 * 1000 ); + std::chrono::microseconds sleep_count( 20 * 1000 ); + std::this_thread::sleep_for( sleep_count ); + //usleep( 20 * 1000 ); } } @@ -2597,14 +2464,16 @@ Stadium::doSendThink() int num_sleeps = 0; - gettimeofday( &tv_start, NULL ); + const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); do { done = DS_TRUE; ++num_sleeps; - usleep( ServerParam::instance().synchMicroSleep() ); + std::chrono::microseconds sleep_count( ServerParam::instance().synchMicroSleep() ); + std::this_thread::sleep_for( sleep_count ); + //usleep( ServerParam::instance().synchMicroSleep() ); doRecvFromClients(); @@ -2641,13 +2510,8 @@ Stadium::doSendThink() // get time differnce with start of loop, first get time difference in // seconds, then multiply with 1000 to get msec. - gettimeofday( &tv_now, NULL ); - double time_diff - = ( static_cast< double >( tv_now.tv_sec ) - + static_cast< double >( tv_now.tv_usec ) / 1000000 ) - - ( static_cast< double >( tv_start.tv_sec ) - + static_cast< double >( tv_start.tv_usec ) / 1000000 ); - time_diff *= 1000; + const std::chrono::nanoseconds nano_diff = std::chrono::duration_cast< std::chrono::nanoseconds >( std::chrono::system_clock::now() - start_time ); + const double time_diff = nano_diff.count() * 0.001 * 0.001; if ( time_diff > max_msec_waited ) { @@ -2671,12 +2535,11 @@ Stadium::doSendThink() cycles_missed = 0; } - if ( M_logger.isTextLogOpen() - && ServerParam::instance().logTimes() ) + if ( ServerParam::instance().logTimes() ) { - char buf[32]; - snprintf( buf, 32, "Num sleeps called: %d", num_sleeps ); - M_logger.writeTextLog( buf, LOG_TEXT ); + char buf[128]; + snprintf( buf, 127, "Num sleeps called: %d", num_sleeps ); + Logger::instance().writeTextLog( *this, buf, LOG_TEXT ); } if ( shutdown ) @@ -2694,8 +2557,8 @@ template < class T > void recv_from_clients( std::vector< T > & clients ) { - std::random_shuffle( clients.begin(), clients.end(), - irand ); //rcss::random::UniformRNG::instance() ); + std::shuffle( clients.begin(), clients.end(), + DefaultRNG::instance() ); for ( typename std::vector< T >::iterator i = clients.begin(); i != clients.end(); ) @@ -2731,13 +2594,11 @@ Stadium::udp_recv_message() // std::cerr << std::endl; bool found = false; - for ( PlayerCont::iterator i = M_remote_players.begin(); - i != M_remote_players.end(); - ++i ) + for ( PlayerCont::reference p : M_remote_players ) { - if ( (*i)->getDest() == cli_addr ) + if ( p->getDest() == cli_addr ) { - (*i)->undedicatedRecv( message, len ); + p->undedicatedRecv( message, len ); found = true; break; } @@ -2745,13 +2606,11 @@ Stadium::udp_recv_message() if ( ! found ) { - for ( MonitorCont::iterator i = M_monitors.begin(); - i != M_monitors.end(); - ++i ) + for ( MonitorCont::reference m : M_monitors ) { - if ( (*i)->getDest() == cli_addr ) + if ( m->getDest() == cli_addr ) { - (*i)->undedicatedRecv( message, len ); + m->undedicatedRecv( message, len ); found = true; break; } @@ -2867,7 +2726,7 @@ Stadium::parsePlayerInit( const char * message, << "player (" << teamname << ' ' << p->unum() << ") connected." << std::endl; - M_logger.writePlayerLog( *p, message, RECV ); + Logger::instance().writePlayerLog( *this, *p, message, RECV ); } return; @@ -2899,7 +2758,7 @@ Stadium::parsePlayerInit( const char * message, { std::cout << "A player (" << teamname << ' ' << p->unum() << ") reconnected." << std::endl; - M_logger.writePlayerLog( *p, message, RECV ); + Logger::instance().writePlayerLog( *this, *p, message, RECV ); } return; @@ -2982,13 +2841,11 @@ Stadium::udp_recv_from_coach() } bool found = false; - for ( OfflineCoachCont::iterator i = M_remote_offline_coaches.begin(); - i != M_remote_offline_coaches.end(); - ++i ) + for ( OfflineCoachCont::reference c : M_remote_offline_coaches ) { - if ( (*i)->getDest() == cli_addr ) + if ( c->getDest() == cli_addr ) { - (*i)->undedicatedRecv( message, len ); + c->undedicatedRecv( message, len ); found = true; break; } @@ -3058,7 +2915,7 @@ Stadium::parseCoachInit( const char * message, { std::cout << "A new (v" << coach->version() << ") " << "offline coach connected" << std::endl; - M_logger.writeCoachLog( message, RECV ); + Logger::instance().writeCoachLog( *this, message, RECV ); } } else @@ -3066,7 +2923,7 @@ Stadium::parseCoachInit( const char * message, kickOff(); // need to remove this line if we // dont want the server to start when the coach connects M_coach->parse_command( message ); - M_logger.writeCoachLog( message, RECV ); + Logger::instance().writeCoachLog( *this, message, RECV ); } return true; @@ -3089,17 +2946,16 @@ Stadium::udp_recv_from_online_coach() if ( len > 0 ) { bool found = false; - for ( OnlineCoachCont::iterator i = M_remote_online_coaches.begin(); - i != M_remote_online_coaches.end(); - ++i ) + for ( OnlineCoachCont::reference c : M_remote_online_coaches ) { - if ( (*i)->getDest() == cli_addr ) + if ( c->getDest() == cli_addr ) { - (*i)->undedicatedRecv( message, len ); + c->undedicatedRecv( message, len ); found = true; break; } } + if ( ! found ) { // a new online coach @@ -3222,7 +3078,7 @@ Stadium::parseOnlineCoachInit( const char * message, << "online coach (" << teamname << ") connected." << std::endl;; - M_logger.writeOnlineCoachLog( *olc, message, RECV ); + Logger::instance().writeOnlineCoachLog( *this, *olc, message, RECV ); } } @@ -3277,7 +3133,7 @@ Stadium::finalize( const std::string & msg ) s_first = false; killTeams(); std::cout << '\n' << msg << '\n'; - M_logger.close(); + Logger::instance().close( *this ); saveResults(); disable(); } @@ -3332,41 +3188,39 @@ Stadium::saveResults() } std::cout << "\nSaving Results:" << std::endl; - for ( std::list< ResultSaver::Ptr >::iterator i = M_savers.begin(); - i != M_savers.end(); - ++i ) + for ( std::list< ResultSaver::Ptr >::reference s : M_savers ) { - std::cout << "\t" << (*i)->getName() << ": saving...\n"; - if ( (*i)->enabled() ) + std::cout << "\t" << s->getName() << ": saving...\n"; + if ( s->enabled() ) { - (*i)->saveStart(); - (*i)->saveTime( realTime() ); + s->saveStart(); + s->saveTime( getStartTime() ); if ( M_team_l ) { rcss::save_results( ResultSaver::TEAM_LEFT, *M_team_l, - **i ); + *s ); } if ( M_team_r ) { rcss::save_results( ResultSaver::TEAM_RIGHT, *M_team_r, - **i ); + *s ); } - if ( (*i)->saveComplete() ) + if ( s->saveComplete() ) { - std::cout << "\t" << (*i)->getName() << ": ...saved\n"; + std::cout << "\t" << s->getName() << ": ...saved\n"; } else { - std::cout << "\t" << (*i)->getName() << ": ...failed\n"; + std::cout << "\t" << s->getName() << ": ...failed\n"; } } else { - std::cout << "\t" << (*i)->getName() << ": ...disabled\n"; + std::cout << "\t" << s->getName() << ": ...disabled\n"; } } std::cout << '\n'; diff --git a/src/stadium.h b/src/stadium.h index fc9e0be4..e9f02ea2 100644 --- a/src/stadium.h +++ b/src/stadium.h @@ -28,14 +28,12 @@ #include "object.h" #include "field.h" #include "weather.h" -#include "logger.h" #include "resultsaver.hpp" -#include -#include +#include +#include #include -#include #include #include #include @@ -52,8 +50,6 @@ class Team; class Referee; -struct timeval; - namespace rcss { class Listener; namespace clang { @@ -79,14 +75,14 @@ class Stadium typedef std::vector< MPObject * > MPObjectCont; protected: // definitions of different timeable methods - void doRecvFromClients( ); - void doNewSimulatorStep(); - void doSendSenseBody(); - void doSendVisuals(); - void doSendSynchVisuals(); - void doSendCoachMessages(); - bool doSendThink(); - void doQuit(); + void doRecvFromClients( ) override; + void doNewSimulatorStep() override; + void doSendSenseBody() override; + void doSendVisuals() override; + void doSendSynchVisuals() override; + void doSendCoachMessages() override; + bool doSendThink() override; + void doQuit() override; protected: bool M_alive; @@ -98,8 +94,6 @@ class Stadium Field M_field; Weather M_weather; - Logger M_logger; - PlayerCont M_remote_players; //!< connected players OfflineCoachCont M_remote_offline_coaches; //!< connected trainers OnlineCoachCont M_remote_online_coaches; //!< connected coaches @@ -140,7 +134,7 @@ class Stadium int M_left_child; int M_right_child; - tm m_real_time; + std::time_t M_start_time; std::list< ResultSaver::Ptr > M_savers; @@ -149,23 +143,18 @@ class Stadium Stadium(); virtual - ~Stadium(); + ~Stadium() override; bool init(); void finalize( const std::string & msg ); virtual - bool isAlive() + bool isAlive() override { return M_alive; } - Logger & logger() - { - return M_logger; - } - PlayMode playmode() const { return M_playmode; @@ -181,10 +170,9 @@ class Stadium return M_stoppage_time; } - const - tm & realTime() const + std::time_t getStartTime() const { - return m_real_time; + return M_start_time; } const @@ -375,8 +363,8 @@ class Stadium bool movePlayer( const Side side, const int unum, const PVector & pos, - const double * ang = NULL, - const PVector * vel = NULL ); + const double * ang = nullptr, + const PVector * vel = nullptr ); void changePlayMode( const PlayMode pm ); diff --git a/src/stdoutsaver.cpp b/src/stdoutsaver.cpp index be5cc767..bdb8ed6c 100644 --- a/src/stdoutsaver.cpp +++ b/src/stdoutsaver.cpp @@ -61,7 +61,7 @@ STDOutSaver::doSaveStart() } void -STDOutSaver::doSaveTime( const tm & time ) +STDOutSaver::doSaveTime( const std::time_t time ) { M_time = time; } @@ -124,7 +124,8 @@ bool STDOutSaver::doSaveComplete() { char time_str[256]; - std::strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", &M_time ); + const struct tm * lt = std::localtime( &M_time ); + std::strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", lt ); std::cout << "\t" << time_str << "\n\t"; diff --git a/src/stdoutsaver.h b/src/stdoutsaver.h index 85dde078..ed588f22 100644 --- a/src/stdoutsaver.h +++ b/src/stdoutsaver.h @@ -37,52 +37,52 @@ class STDOutSaver public: virtual - ~STDOutSaver(); + ~STDOutSaver() override; static - ResultSaver::Ptr create(); + Ptr create(); private: virtual - bool doEnabled() const; + bool doEnabled() const override; virtual - void doSaveStart(); + void doSaveStart() override; virtual - void doSaveTime( const tm & time ); + void doSaveTime( const std::time_t time ) override; virtual void doSaveTeamName( team_id id, - const std::string & name ); + const std::string & name ) override; virtual void doSaveCoachName( team_id id, - const std::string & name ); + const std::string & name ) override; virtual void doSaveScore( team_id id, - unsigned int score ); + unsigned int score ) override; virtual void doSavePenTaken( team_id id, - unsigned int taken ); + unsigned int taken ) override; virtual void doSavePenScored( team_id id, - unsigned int scored ); + unsigned int scored ) override; virtual - void doSaveCoinTossWinner( team_id id ); + void doSaveCoinTossWinner( team_id id ) override; virtual - bool doSaveComplete(); + bool doSaveComplete() override; virtual - const char * doGetName() const; + const char * doGetName() const override; - tm M_time; + std::time_t M_time; std::string M_team_name[ 2 ]; std::string M_coach_name[ 2 ]; unsigned int M_score[ 2 ]; diff --git a/src/stdtimer.cpp b/src/stdtimer.cpp index 305d222b..c0d5b30a 100644 --- a/src/stdtimer.cpp +++ b/src/stdtimer.cpp @@ -29,153 +29,20 @@ #include "param.h" // needed for TIMEDELTA #include "serverparam.h" // needed for ServerParam -#include // needed for sigaction -#include // needed for NULL - -#ifdef HAVE_SYS_TIME_H -#include // needed for itimerval -#endif - -#ifdef __CYGWIN__ -// cygwin is not win32 -#elif defined(_WIN32) || defined(__WIN32__) || defined (WIN32) -#define RCSS_WIN -#endif - - -bool StandardTimer::gotsig = false; -int StandardTimer::timedelta = 0; -bool StandardTimer::lock_timedelta = false; +#include +#include StandardTimer::StandardTimer( Timeable & timeable ) : Timer( timeable ) { - gotsig = false; - timedelta = 0; - lock_timedelta = false; -} - -#ifdef RCSS_WIN -VOID -CALLBACK -StandardTimer::check( PVOID ptr, BOOL ) -{ - static int td_mult = 1; - if ( lock_timedelta ) - { - td_mult += 1; - } - else - { - timedelta += td_mult * TIMEDELTA; - td_mult = 1; - } - gotsig = true; - SetEvent((HANDLE)ptr); -} -#else -void -StandardTimer::check( void ) -{ - static int td_mult = 1; - if ( lock_timedelta ) - { - td_mult += 1; - } - else - { - timedelta += td_mult * TIMEDELTA; - td_mult = 1; - } - gotsig = true; } -#endif -#ifdef RCSS_WIN -static -void -initTimer( HANDLE gDoneEvent ) -{ - HANDLE hTimer = NULL; - HANDLE hTimerQueue = NULL; - int arg = 123; - // Use an event object to track the TimerRoutine execution - gDoneEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); - if ( ! gDoneEvent ) - { - printf( "CreateEvent failed (%d)\n", GetLastError() ); - // return 1; - } - - // Create the timer queue. - hTimerQueue = CreateTimerQueue(); - if ( ! hTimerQueue ) - { - printf( "CreateTimerQueue failed (%d)\n", GetLastError() ); - // return 2; - } - - // Set a timer to call the timer routine in 10 seconds. - if ( ! CreateTimerQueueTimer( &hTimer, hTimerQueue, - (WAITORTIMERCALLBACK)&StandardTimer::check, - &gDoneEvent , TIMEDELTA, TIMEDELTA, 0 ) ) - { - printf( "CreateTimerQueueTimer failed (%d)\n", GetLastError() ); - // return 3; - } - - // TODO: Do other useful work here - - printf( "Call timer routine in 10 seconds...\n" ); - - // // Wait for the timer-queue thread to complete using an event - // // object. The thread will signal the event at that time. - - // if (WaitForSingleObject(gDoneEvent, INFINITE) != WAIT_OBJECT_0) - // printf("WaitForSingleObject failed (%d)\n", GetLastError()); - - // // Delete all timers in the timer queue. - // if (!DeleteTimerQueue(hTimerQueue)) - // printf("DeleteTimerQueue failed (%d)\n", GetLastError()); -} -#else -static -void -initTimer( struct itimerval & itv_prev, - struct sigaction & alarm_prev ) -{ - struct itimerval itv; - struct sigaction alarm_action; - itv.it_interval.tv_sec = 0 ; - itv.it_interval.tv_usec = TIMEDELTA * 1000 ; - itv.it_value.tv_sec = 0 ; - itv.it_value.tv_usec = TIMEDELTA * 1000 ; - - alarm_action.sa_handler = (void (*)(int))StandardTimer::check ; - alarm_action.sa_flags = 0; // [2000/11/20.frehberg.cs.tu-berlin.de] - - sigaction( SIGALRM, &alarm_action, &alarm_prev ); - setitimer( ITIMER_REAL, &itv, &itv_prev ); -} -#endif - -#ifdef RCSS_WIN -#else -static -void -restoreTimer( struct itimerval & itv_prev, - struct sigaction & alarm_prev ) -{ - setitimer( ITIMER_REAL, &itv_prev, NULL ); // restore the old timer - sigaction( SIGALRM, &alarm_prev, NULL ); // restore the old alaram handler -} -#endif - -/** This method controls the standard timer. After the arrival of a signal it - checks which messages should be sent / received by the clients and handles - them appropriately. */ +/** This method controls the standard timer. + In the mainloop, the sleep is called for each trial. + The sleep time is determined by subtracting the consumued time from the default delta. + After finishing the sleep, checking which messages should be sent / received by the clients and handles them appropriately. */ void StandardTimer::run() { @@ -203,40 +70,20 @@ StandardTimer::run() int c_synch_see = 1; bool sent_synch_see = false; - // create a timer that will be called every TIMEDELTA msec. Each time - // this timer is called, lcmt is raised and it is checked which message - // should be processed according to the part of the sequence we are in + const std::chrono::milliseconds default_delta( TIMEDELTA ); + std::chrono::nanoseconds elapsed( 0 ); + std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now(); -#ifdef RCSS_WIN - HANDLE gDoneEvent = NULL; - initTimer(gDoneEvent); -#else - struct itimerval itv_prev; - struct sigaction alarm_prev; - initTimer( itv_prev, alarm_prev ); -#endif - //for (;;) while ( getTimeableRef().alive() ) { -#ifdef RCSS_WIN - if ( WaitForSingleObject(gDoneEvent, INFINITE) != WAIT_OBJECT_0 ) - printf( "WaitForSingleObject failed (%d)\n", GetLastError() ); -#else - if ( ! gotsig ) - { - //sigpause( SIGUSR1 ); - sigset_t mask; - sigemptyset( &mask ); - sigaddset( &mask, SIGUSR1 ); - sigsuspend( &mask ); - } -#endif - gotsig = false; + const std::chrono::nanoseconds elapsed = std::chrono::duration_cast< std::chrono::nanoseconds >( std::chrono::system_clock::now() - start_time ); + const std::chrono::nanoseconds sleep_count = default_delta - elapsed; + std::this_thread::sleep_for( sleep_count ); - lock_timedelta = true; - lcmt += timedelta; - timedelta = 0; - lock_timedelta = false; + start_time = std::chrono::system_clock::now(); + lcmt += ( sleep_count.count() < 0 + ? elapsed.count() * 0.001 * 0.001 + : ( sleep_count.count() + elapsed.count() ) * 0.001 * 0.001 ); if ( lcmt >= ServerParam::instance().simStep() * c_simt ) { @@ -319,9 +166,6 @@ StandardTimer::run() c_synch_see = 1; } } -#ifdef RCSS_WIN -#else - restoreTimer( itv_prev, alarm_prev ); -#endif + getTimeableRef().quit(); } diff --git a/src/stdtimer.h b/src/stdtimer.h index 27b28f13..01fe5f12 100644 --- a/src/stdtimer.h +++ b/src/stdtimer.h @@ -22,16 +22,7 @@ #ifndef STDTIMER_H #define STDTIMER_H -#ifdef __CYGWIN__ -// cygwin is not win32 -#elif defined(_WIN32) || defined(__WIN32__) || defined (WIN32) -#define _WIN32_WINNT 0x0500 -#include -#include -#endif - #include "timer.h" -#include "rcssexceptions.h" /** This is a subclass of the timer class. The run method specifes the standard timer. This timer is controlled by the different server @@ -46,31 +37,13 @@ class StandardTimer : public Timer { private: - static bool gotsig; // variables needed to keep track - static int timedelta; // of amount of arrived signals - static bool lock_timedelta; - - StandardTimer( const StandardTimer& t ); + StandardTimer( const StandardTimer& t ) = delete; public: + explicit StandardTimer( Timeable &timeable ); - void - run(); - -#ifdef __CYGWIN__ -// cygwin is not win32 - static - void check(); -#elif defined(_WIN32) || defined(__WIN32__) || defined (WIN32) - static - VOID - CALLBACK - check( PVOID lpParam, BOOL TimerOrWaitFired ); -#else - static - void check(); -#endif + void run() override; }; diff --git a/src/synctimer.h b/src/synctimer.h index 253d4121..427f7259 100644 --- a/src/synctimer.h +++ b/src/synctimer.h @@ -31,12 +31,12 @@ class SyncTimer : public Timer { public: + explicit SyncTimer( Timeable &timeable ) : Timer( timeable ) - {} + { } - void - run(); + void run() override; // static // void diff --git a/src/team.cpp b/src/team.cpp index 3306d20c..334367c1 100644 --- a/src/team.cpp +++ b/src/team.cpp @@ -99,7 +99,7 @@ Team::newPlayer( const double & version, { std::cerr << "Warning:Too many players." << std::endl; } - return NULL; + return nullptr; } if ( goalie_flag ) @@ -112,7 +112,7 @@ Team::newPlayer( const double & version, { std::cerr << "Warning:Too many goalies." << std::endl; } - return NULL; + return nullptr; } } } @@ -121,7 +121,7 @@ Team::newPlayer( const double & version, if ( ! p->init( version, goalie_flag ) ) { - return NULL; + return nullptr; } ++M_size; @@ -201,13 +201,8 @@ Team::assignPlayerTypes() } } - for ( std::list< Player * >::iterator it = players.begin(); - it != players.end(); - ++it ) + for ( Player * p : players ) { - //Player * p = M_players[i]; - Player * p = *it; - // 2009-10-29 akiyama // enabled heterogeneous goalie // if ( p->isGoalie() ) diff --git a/src/team.h b/src/team.h index 8150dfcc..e49bb796 100644 --- a/src/team.h +++ b/src/team.h @@ -74,8 +74,8 @@ class Team { // not used - Team(); - const Team & operator=( const Team & ); + Team() = delete; + const Team & operator=( const Team & ) = delete; public: @@ -119,7 +119,7 @@ class Team { const Player * player( const int i ) const { - if ( i < 0 || M_size <= i ) return NULL; + if ( i < 0 || M_size <= i ) return nullptr; return M_players[i]; } diff --git a/src/timer.h b/src/timer.h index 918c9298..33d81ca5 100644 --- a/src/timer.h +++ b/src/timer.h @@ -29,6 +29,11 @@ class Timeable; the 'run' method. In this 'run' method the timeable methods from the timeable instance are called. */ class Timer { +private: + Timer() = delete; + Timer( const Timer & ) = delete; + Timer & operator=( const Timer & ) = delete; + public: virtual @@ -40,6 +45,7 @@ class Timer { protected: + explicit Timer( Timeable & timeable ) : M_timeable ( timeable ) { } diff --git a/src/types.h b/src/types.h index 556a05a1..91d5c778 100644 --- a/src/types.h +++ b/src/types.h @@ -39,10 +39,10 @@ #include "param.h" -#include +#include -typedef boost::int16_t Int16; -typedef boost::int32_t Int32; +typedef std::int16_t Int16; +typedef std::int32_t Int32; enum PlayerState { DISABLE = 0x00000000, @@ -200,6 +200,8 @@ const int REC_VERSION_2 = 2; const int REC_VERSION_3 = 3; const int REC_VERSION_4 = 4; const int REC_VERSION_5 = 5; +const int REC_VERSION_6 = 6; +const int REC_VERSION_JSON = REC_VERSION_6; const int DEFAULT_REC_VERSION = REC_VERSION_5; enum DispInfoMode { diff --git a/src/utility.cpp b/src/utility.cpp index 59e5692e..dbb96a93 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -148,7 +148,7 @@ tildeExpand( const std::string & path_name ) || new_path[1] == '/' ) { char szpath[MAX_PATH]; - if ( SHGetSpecialFolderPath( NULL, szpath, CSIDL_PERSONAL, TRUE ) ) + if ( SHGetSpecialFolderPath( nullptr, szpath, CSIDL_PERSONAL, TRUE ) ) { std::string userdir = szpath; std::replace( userdir.begin(), userdir.end(), '\\', '/' ); @@ -172,7 +172,7 @@ tildeExpand( const std::string & path_name ) || path_name[1] == '\\' ) { char szpath[MAX_PATH]; - if ( SHGetSpecialFolderPath( NULL, szpath, CSIDL_PERSONAL, TRUE ) ) + if ( SHGetSpecialFolderPath( nullptr, szpath, CSIDL_PERSONAL, TRUE ) ) { return szpath + path_name.substr( 1 ); } @@ -198,11 +198,11 @@ tildeExpand( const std::string & path_name ) { // Get the current user. const char * err = std::getenv( "USER" ); - if ( err == NULL ) + if ( ! err ) { // On Windows USERNAME is used instead err = std::getenv( "USERNAME" ); - if ( err == NULL ) + if ( ! err ) { return path_name; } @@ -229,7 +229,7 @@ tildeExpand( const std::string & path_name ) // Get the passwd file entry for the user and place their home // directory path at the start of newPath. struct passwd * pwd_entry = getpwnam( username.c_str() ); - if ( pwd_entry == NULL ) + if ( ! pwd_entry ) { return path_name; } diff --git a/src/visual.h b/src/visual.h index 18d61ff4..2e42596e 100644 --- a/src/visual.h +++ b/src/visual.h @@ -45,7 +45,7 @@ class VisualSender public: virtual - ~VisualSender() + ~VisualSender() override { } virtual diff --git a/src/visualsendercoach.cpp b/src/visualsendercoach.cpp index db97b613..ef88fbab 100644 --- a/src/visualsendercoach.cpp +++ b/src/visualsendercoach.cpp @@ -92,14 +92,11 @@ VisualSenderCoachV1::sendVisual() sendGoals(); sendBall(); - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - serializePlayer( **p ); + serializePlayer( *p ); } serializer().serializeVisualEnd( transport() ); @@ -114,14 +111,11 @@ VisualSenderCoachV1::sendLook() sendGoals(); sendBall(); - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) { - if ( ! (*p)->isEnabled() ) continue; + if ( ! p->isEnabled() ) continue; - serializePlayerLook( **p ); + serializePlayerLook( *p ); } serializer().serializeLookEnd( transport() ); @@ -138,12 +132,9 @@ VisualSenderCoachV1::sendOKEye() void VisualSenderCoachV1::sendGoals() { - const std::vector< const PObject * >::const_iterator end = stadium().field().goals().end(); - for ( std::vector< const PObject * >::const_iterator it = stadium().field().goals().begin(); - it != end; - ++it ) + for ( const PObject * o : stadium().field().goals() ) { - sendGoal( **it ); + sendGoal( *o ); } } @@ -378,6 +369,7 @@ RegHolder vc13 = VisualSenderCoach::factory().autoReg( &create< VisualSenderCoac RegHolder vc14 = VisualSenderCoach::factory().autoReg( &create< VisualSenderCoachV13 >, 14 ); RegHolder vc15 = VisualSenderCoach::factory().autoReg( &create< VisualSenderCoachV13 >, 15 ); RegHolder vc16 = VisualSenderCoach::factory().autoReg( &create< VisualSenderCoachV13 >, 16 ); +RegHolder vc17 = VisualSenderCoach::factory().autoReg( &create< VisualSenderCoachV13 >, 17 ); } } diff --git a/src/visualsendercoach.h b/src/visualsendercoach.h index 54151352..5d68816a 100644 --- a/src/visualsendercoach.h +++ b/src/visualsendercoach.h @@ -28,7 +28,7 @@ #include "object.h" #include "utility.h" -#include +#include #include @@ -80,8 +80,11 @@ class VisualSenderCoach static FactoryHolder & factory(); +protected: VisualSenderCoach( const Params & params ); +public: + virtual ~VisualSenderCoach(); protected: @@ -183,14 +186,14 @@ class VisualSenderCoachV1 VisualSenderCoachV1( const Params & params ); virtual - ~VisualSenderCoachV1(); + ~VisualSenderCoachV1() override; void sendVisual(); - void sendLook(); + void sendLook() override; virtual - void sendOKEye(); + void sendOKEye() override; private: @@ -217,8 +220,7 @@ class VisualSenderCoachV1 } virtual - const - std::string & calcName( const PObject & obj ) const + const std::string & calcName( const PObject & obj ) const { return obj.name(); } @@ -249,20 +251,19 @@ class VisualSenderCoachV7 protected: virtual - int rad2Deg( const double & rad ) const + int rad2Deg( const double & rad ) const override { return Rad2IDegRound( rad ); } virtual - const - std::string & calcName( const PObject & obj ) const + const std::string & calcName( const PObject & obj ) const override { return obj.shortName(); } virtual - const std::string & calcPlayerName( const Player & obj ) const; + const std::string & calcPlayerName( const Player & obj ) const override; }; /*! @@ -290,10 +291,10 @@ class VisualSenderCoachV8 virtual - void serializePlayer( const Player & player ); + void serializePlayer( const Player & player ) override; virtual - void serializePlayerLook( const Player & player ); + void serializePlayerLook( const Player & player ) override; }; @@ -321,10 +322,10 @@ class VisualSenderCoachV13 protected: virtual - void serializePlayer( const Player & player ); + void serializePlayer( const Player & player ) override; virtual - void serializePlayerLook( const Player & player ); + void serializePlayerLook( const Player & player ) override; }; } diff --git a/src/visualsenderplayer.cpp b/src/visualsenderplayer.cpp index 680bde8b..2c84c073 100644 --- a/src/visualsenderplayer.cpp +++ b/src/visualsenderplayer.cpp @@ -132,14 +132,11 @@ VisualSenderPlayerV1::sendVisual() void VisualSenderPlayerV1::sendFlags() { - const std::vector< PObject * >::const_iterator end = stadium().field().landmarks().end(); - for ( std::vector< PObject * >::const_iterator it = stadium().field().landmarks().begin(); - it != end; - ++it ) + for ( const PObject * o : stadium().field().landmarks() ) { - if ( (*it)->objectVersion() <= self().version() ) + if ( o->objectVersion() <= self().version() ) { - sendFlag( **it ); + sendFlag( *o ); } } } @@ -156,16 +153,13 @@ VisualSenderPlayerV1::sendBalls() void VisualSenderPlayerV1::sendPlayers() { - const Stadium::PlayerCont::const_iterator end = stadium().players().end(); - for ( Stadium::PlayerCont::const_iterator p = stadium().players().begin(); - p != end; - ++p ) + for ( Stadium::PlayerCont::const_reference p : stadium().players() ) { - if ( *p != &self() - && (*p)->isEnabled() - && (*p)->objectVersion() <= self().version() ) + if ( p != &self() + && p->isEnabled() + && p->objectVersion() <= self().version() ) { - sendPlayer( **p ); + sendPlayer( *p ); } } } @@ -894,12 +888,8 @@ VisualSenderPlayerV8::calcPointDir( const Player & player ) //sigma is now in a range of 2.5 to 180 degrees, dependant on //the distance of the player. 95% of the returned random values //will be within +- 2*sigma of dir - boost::normal_distribution<> rng( dir, sigma ); - boost::variate_generator< rcss::random::DefaultRNG &, - boost::normal_distribution<> > - gen( rcss::random::DefaultRNG::instance(), rng ); - - return rad2Deg( normalize_angle( gen() ) ); + std::normal_distribution<> dst( dir, sigma ); + return rad2Deg( normalize_angle( dst( DefaultRNG::instance() ) ) ); } else { @@ -1078,6 +1068,7 @@ RegHolder vp13 = VisualSenderPlayer::factory().autoReg( &create< VisualSenderPla RegHolder vp14 = VisualSenderPlayer::factory().autoReg( &create< VisualSenderPlayerV13 >, 14 ); RegHolder vp15 = VisualSenderPlayer::factory().autoReg( &create< VisualSenderPlayerV13 >, 15 ); RegHolder vp16 = VisualSenderPlayer::factory().autoReg( &create< VisualSenderPlayerV13 >, 16 ); +RegHolder vp17 = VisualSenderPlayer::factory().autoReg( &create< VisualSenderPlayerV13 >, 17 ); } } diff --git a/src/visualsenderplayer.h b/src/visualsenderplayer.h index 88b94972..fe968410 100644 --- a/src/visualsenderplayer.h +++ b/src/visualsenderplayer.h @@ -28,7 +28,7 @@ #include "player.h" #include "random.h" -#include +#include #include @@ -90,8 +90,11 @@ class VisualSenderPlayer static FactoryHolder & factory(); +protected: VisualSenderPlayer( const Params & params ); +public: + virtual ~VisualSenderPlayer(); protected: @@ -193,11 +196,10 @@ class VisualSenderPlayerV1 VisualSenderPlayerV1( const Params & params ); virtual - ~VisualSenderPlayerV1(); + ~VisualSenderPlayerV1() override; virtual - void - sendVisual(); + void sendVisual() override; private: @@ -316,7 +318,7 @@ class VisualSenderPlayerV1 { if ( prob >= 1.0 ) return true; if ( prob <= 0.0 ) return false; - return boost::bernoulli_distribution<>( prob )( random::DefaultRNG::instance() ); + return std::bernoulli_distribution( prob )( DefaultRNG::instance() ); } protected: @@ -406,7 +408,7 @@ class VisualSenderPlayerV4 VisualSenderPlayerV4( const Params & params ); virtual - ~VisualSenderPlayerV4(); + ~VisualSenderPlayerV4() override; protected: virtual @@ -415,7 +417,7 @@ class VisualSenderPlayerV4 const double & dist, const int dir, const double & dist_chg, - const double & dir_chg ); + const double & dir_chg ) override; int calcBodyDir( const Player & player ) const @@ -444,7 +446,7 @@ class VisualSenderPlayerV5 VisualSenderPlayerV5( const Params & params ); virtual - ~VisualSenderPlayerV5(); + ~VisualSenderPlayerV5() override; protected: virtual @@ -453,7 +455,7 @@ class VisualSenderPlayerV5 const double & dist, const int dir, const double & dist_chg, - const double & dir_chg ); + const double & dir_chg ) override; int calcHeadDir( const Player & player ) const { @@ -484,24 +486,24 @@ class VisualSenderPlayerV6 VisualSenderPlayerV6( const Params & params ); virtual - ~VisualSenderPlayerV6(); + ~VisualSenderPlayerV6() override; virtual const - std::string & calcName( const PObject & obj ) const + std::string & calcName( const PObject & obj ) const override { return obj.shortName(); } virtual const - std::string & calcCloseName( const PObject & obj ) const + std::string & calcCloseName( const PObject & obj ) const override { return obj.shortCloseName(); } virtual - const std::string & calcPlayerName( const Player & obj ) const + const std::string & calcPlayerName( const Player & obj ) const override { return self().side() == obj.side() ? obj.shortName() @@ -510,7 +512,7 @@ class VisualSenderPlayerV6 virtual const - std::string & calcUFarName( const Player & obj ) const + std::string & calcUFarName( const Player & obj ) const override { return self().side() == obj.side() ? obj.shortNameFar() @@ -519,7 +521,7 @@ class VisualSenderPlayerV6 virtual const - std::string & calcTFarName( const Player & obj ) const + std::string & calcTFarName( const Player & obj ) const override { return obj.shortNameTooFar(); } @@ -551,7 +553,7 @@ class VisualSenderPlayerV7 protected: virtual - int rad2Deg( const double & rad ) const + int rad2Deg( const double & rad ) const override { return Rad2IDegRound( rad ); } @@ -588,13 +590,13 @@ class VisualSenderPlayerV8 const double & dist, const int dir, const double & dist_chg, - const double & dir_chg ); + const double & dir_chg ) override; virtual void serializePlayer( const Player & player, const std::string & name, const double & dist, - const int dir ); + const int dir ) override; }; diff --git a/src/xmlreader.cpp b/src/xmlreader.cpp index dd452bb3..08c5fd72 100644 --- a/src/xmlreader.cpp +++ b/src/xmlreader.cpp @@ -46,7 +46,7 @@ XmlReader::readXml( const string & path_name ) return false; } - parser = XML_ParserCreate( NULL ); + parser = XML_ParserCreate( nullptr ); if ( ! parser ) { std::cerr << __FILE__ << ": " << __LINE__ diff --git a/src/xpmholder.cpp b/src/xpmholder.cpp index 8ac7495a..5eb765aa 100644 --- a/src/xpmholder.cpp +++ b/src/xpmholder.cpp @@ -25,12 +25,9 @@ #include "xpmholder.h" -#ifdef HAVE_SSTREAM +#include +#include #include -#else -#include -#endif - #include #include #include @@ -136,6 +133,16 @@ XPMHolder::print( std::ostream & o ) const { if ( ! M_data.empty() ) { +#if 1 + bool first = true; + for ( std::string str : M_data ) + { + if ( first ) first = false; else o << ' '; + + std::replace( str.begin(), str.end(), '\t', ' ' ); + o << std::quoted( str ); + } +#else std::vector< std::string >::const_iterator it = M_data.begin(); o << '"' << *it << '"'; ++it; @@ -143,6 +150,26 @@ XPMHolder::print( std::ostream & o ) const { o << " \"" << *it << '"'; } +#endif + } + return o; +} + + +std::ostream & +XPMHolder::printEscaped( std::ostream & o ) const +{ + if ( ! M_data.empty() ) + { + bool first = true; + for ( std::string str : M_data ) + { + if ( first ) first = false; else o << ' '; + + std::replace( str.begin(), str.end(), '\t', ' ' ); + + o << std::quoted( str ); + } } return o; } diff --git a/src/xpmholder.h b/src/xpmholder.h index c0f32d48..7cb7138d 100644 --- a/src/xpmholder.h +++ b/src/xpmholder.h @@ -33,9 +33,9 @@ class XPMHolder { int M_height; int M_colors; - XPMHolder(); // not used - XPMHolder( const XPMHolder & ); // not used - const XPMHolder & operator=( const XPMHolder & ); // not used + XPMHolder() = delete; // not used + XPMHolder( const XPMHolder & ) = delete; // not used + const XPMHolder & operator=( const XPMHolder & ) = delete; // not used public: explicit @@ -68,8 +68,15 @@ class XPMHolder { return M_colors; } + const std::vector< std::string > & data() const + { + return M_data; + } + std::ostream & print( std::ostream & o ) const; + std::ostream & printEscaped( std::ostream & o ) const; + }; inline