diff --git a/.gitignore b/.gitignore
index 5aa496774..56d4feb22 100644
--- a/.gitignore
+++ b/.gitignore
@@ -93,10 +93,18 @@ $RECYCLE.BIN/
unsuccessfulbuild
/mk/windows/dependencies/openssl
/mk/windows/dependencies/src
+/mk/windows/bin
/data
#
-/mk/linux/zetaglest
-/mk/linux/zetaglest_editor
-/mk/linux/zetaglest_g3dviewer
source/masterserver
mk/linux/tools-for-standalone-client/installer/mojosetup
+
+# These are generated when 'cmake . && make' is run from the root directory
+CMakeFiles
+CMakeCache.txt
+Makefile
+cmake_install.cmake
+CPackConfig.cmake
+CPackSourceConfig.cmake
+/source/shared_lib/liblibmegaglest.a
+/source/shared_lib/sources/streflop/libstreflop.a
diff --git a/BUILD.md b/BUILD.md
index b9c93b5db..d7955be68 100644
--- a/BUILD.md
+++ b/BUILD.md
@@ -68,10 +68,23 @@ libwxgtk3.0-dev libxml2-dev
Follow the [instructions](https://github.com/ZetaGlest/zetaglest-source/blob/develop/mk/windows/README.md) listed in the `Windows` directory.
-### *BSD
+### OpenBSD
-(Need editing/updating)
-[Current Status](https://github.com/ZetaGlest/zetaglest-source/issues/56)
+Below is a list of most of dependencies you will need.
+
+cmake libvorbis lua sdl2 openal wxWidgets fribidi ftgl nghttp2 gnutls glew jpeg png
+miniupnpc curl freeealut
+
+A C++11 compiler is mandatory, so base (or package) clang++, or eg++ (from 4.9.3)
+
+You can install the dependencies using `pkg_add`:
+
+`pkg_add curl libvorbis openal sdl2 git miniupnpc cmake wxWidgets
+xerces-c lua icu4c freealut`
+
+#### Optional
+
+`pkg_add g++ (either 4.9.3 or 6.2.0)`
### Arch Linux
@@ -98,8 +111,10 @@ lua51 miniupnpc openal sdl2 wxgtk3 xerces-c cmake ftjam git mesa`
./build-zg.bat
-### BSD
+### OpenBSD
-(Need editing/updating)
+`cmake <-DCMAKE_CXX_COMPILER=eg++>`
+
+`make`
### Other (add sections)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e8caef397..b5eb12535 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,11 +1,11 @@
CMAKE_MINIMUM_REQUIRED( VERSION 2.8.2 )
-PROJECT( MegaGlest )
+PROJECT( ZetaGlest )
#SET(CMAKE_VERBOSE_MAKEFILE ON)
#
# *NOTE: For now we assume some variation of GCC Compiler (or MingW for Windows binaries)
-# VC++ users should not use CMake yet but rather the build-mg.bat file in mk/windows
+# VC++ users should not use CMake yet but rather the build-zg.bat file in mk/windows
#
# build type
@@ -30,11 +30,11 @@ IF ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
ADD_DEFINITIONS("-Wno-switch")
ENDIF()
-OPTION(BUILD_MEGAGLEST_MODEL_IMPORT_EXPORT_TOOLS "Build model import/export tools" ON)
-OPTION(BUILD_MEGAGLEST_MODEL_VIEWER "Build model viewer" ON)
-OPTION(BUILD_MEGAGLEST_MAP_EDITOR "Build map editor" ON)
-OPTION(BUILD_MEGAGLEST "Build MegaGlest" ON)
-OPTION(BUILD_MEGAGLEST_TESTS "Build MegaGlest Unit Tests" OFF)
+OPTION(BUILD_ZETAGLEST_MODEL_IMPORT_EXPORT_TOOLS "Build model import/export tools" ON)
+OPTION(BUILD_ZETAGLEST_MODEL_VIEWER "Build model viewer" ON)
+OPTION(BUILD_ZETAGLEST_MAP_EDITOR "Build map editor" ON)
+OPTION(BUILD_ZETAGLEST "Build ZetaGlest" ON)
+OPTION(BUILD_ZETAGLEST_TESTS "Build ZetaGlest Unit Tests" OFF)
OPTION(WANT_SINGLE_INSTALL_DIRECTORY "Use single install directory for everything. It is useful for example for MacOS cpack bundles." OFF)
OPTION(WANT_STATIC_LIBS "Builds as many static libs as possible." OFF)
OPTION(WANT_USE_VLC "Use libVLC to play videos." ON)
@@ -58,37 +58,37 @@ include(${CMAKE_SOURCE_DIR}/mk/cmake/Modules/SpecialMacros.cmake)
include(${CMAKE_SOURCE_DIR}/mk/cmake/Modules/ReqVersAndStaticConf.cmake)
MESSAGE(STATUS "=====================================================================")
-SET(PKG_NAME "megaglest")
+SET(PKG_NAME "zetaglest")
# read version
-FILE(READ ${PROJECT_SOURCE_DIR}/source/glest_game/facilities/game_util.cpp MG_VERSION_H_CONTENTS)
+FILE(READ ${PROJECT_SOURCE_DIR}/source/glest_game/facilities/game_util.cpp ZG_VERSION_H_CONTENTS)
MESSAGE(STATUS "Determining version number system type to use:")
SET(Begin_otv_string "string glestVersionString")
-STRING(REGEX MATCH "${Begin_otv_string}[ \t]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\\.]*)(\\.)([^\\.]*)(\\.)([^\"\\.;]*)\";" _threePartMatch "${MG_VERSION_H_CONTENTS}")
-STRING(REGEX MATCH "${Begin_otv_string}[ \t]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\\.]*)(\\.)([^\"\\.;]*)\";" _twoPartMatch "${MG_VERSION_H_CONTENTS}")
-STRING(REGEX MATCH "${Begin_otv_string}[ \t]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\"\\.;]*)\";" _onePartMatch "${MG_VERSION_H_CONTENTS}")
+STRING(REGEX MATCH "${Begin_otv_string}[ \t]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\\.]*)(\\.)([^\\.]*)(\\.)([^\"\\.;]*)\";" _threePartMatch "${ZG_VERSION_H_CONTENTS}")
+STRING(REGEX MATCH "${Begin_otv_string}[ \t]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\\.]*)(\\.)([^\"\\.;]*)\";" _twoPartMatch "${ZG_VERSION_H_CONTENTS}")
+STRING(REGEX MATCH "${Begin_otv_string}[ \t]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\"\\.;]*)\";" _onePartMatch "${ZG_VERSION_H_CONTENTS}")
IF(_threePartMatch)
MESSAGE(STATUS "** Trying 3 part versioning ")
STRING(REGEX REPLACE "[^=]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\\.]*)\\.[^\\.]*\\..*" "\\1" VER_MAJOR "${_threePartMatch}")
STRING(REGEX REPLACE "[^=]*=[ \t]*\"[ \t]*v[ \t]*[0-9][^\\.]*\\.([^\\.]*)\\..*" "\\1" VER_MINOR "${_threePartMatch}")
STRING(REGEX REPLACE "[^=]*=[ \t]*\"[ \t]*v[ \t]*[0-9][^\\.]*\\.[^\\.]*\\.([^\"\\.;]*).*" "\\1" VER_PATCH "${_threePartMatch}")
- SET(MEGAGLEST_VERSION "${VER_MAJOR}.${VER_MINOR}.${VER_PATCH}")
+ SET(ZETAGLEST_VERSION "${VER_MAJOR}.${VER_MINOR}.${VER_PATCH}")
ELSEIF(_twoPartMatch)
MESSAGE(STATUS "** Trying 2 part versioning ")
STRING(REGEX REPLACE "[^=]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\\.]*)\\..*" "\\1" VER_MAJOR "${_twoPartMatch}")
STRING(REGEX REPLACE "[^=]*=[ \t]*\"[ \t]*v[ \t]*[0-9][^\\.]*\\.([^\"\\.;]*).*" "\\1" VER_MINOR "${_twoPartMatch}")
SET(VER_PATCH "0")
- SET(MEGAGLEST_VERSION "${VER_MAJOR}.${VER_MINOR}")
+ SET(ZETAGLEST_VERSION "${VER_MAJOR}.${VER_MINOR}")
ELSEIF(_onePartMatch)
MESSAGE(STATUS "** Trying 1 part versioning ")
STRING(REGEX REPLACE "[^=]*=[ \t]*\"[ \t]*v[ \t]*([0-9][^\"\\.;]*).*" "\\1" VER_MAJOR "${_onePartMatch}")
SET(VER_MINOR "0")
SET(VER_PATCH "0")
- SET(MEGAGLEST_VERSION "${VER_MAJOR}")
+ SET(ZETAGLEST_VERSION "${VER_MAJOR}")
ENDIF()
-FOREACH(ver_var VER_MAJOR;VER_MINOR;VER_PATCH;MEGAGLEST_VERSION)
+FOREACH(ver_var VER_MAJOR;VER_MINOR;VER_PATCH;ZETAGLEST_VERSION)
STRING(REGEX REPLACE "[ \t]" "" "${ver_var}" "${${ver_var}}")
ENDFOREACH()
-MESSAGE(STATUS "Detected MegaGlest Version is [v${MEGAGLEST_VERSION}] ")
+MESSAGE(STATUS "Detected ZetaGlest Version is [v${ZETAGLEST_VERSION}] ")
SET(PIC_FLAG "${PIC_FLAG} -fPIC")
IF(WANT_STATIC_LIBS AND "${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
@@ -210,121 +210,79 @@ IF(CMAKE_COMPILER_IS_GNUCXX OR MINGW)
SET(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} -s") ## Strip binary
ENDIF()
- # see if this fixes compile issue for tomreyn: libpthread.so.0: error adding symbols: DSO missing from command line
- IF(UNIX)
- MESSAGE(STATUS "*NOTE: Apply fix for: libpthread.so.0: error adding symbols: DSO missing from command line")
- set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")
- set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} -pthread")
- SET(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} -pthread")
- SET(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} -pthread")
- ENDIF()
-
- # Get the git revision info for the binary
- SET(HAS_GIT "FALSE")
- SET(GIT_LIVE_REV_CMD "")
-
- OPTION(WANT_GIT_STAMP "use git revision stamp" ON)
- IF(WANT_GIT_STAMP)
- # The stuff below gets GIT Global Revision # but ONLY when calling cmake!
- # the FindGit.cmake module is part of the standard distribution
- include(FindGit)
-
- IF(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git/")
- SET(HAS_GIT "TRUE")
- MESSAGE(STATUS "Found GIT and using GIT version stamping...")
-
- # Get the current commit SHA1
- execute_process(
- COMMAND git log -1 --format=%h --abbrev=7
- WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
- OUTPUT_VARIABLE GIT_SHA1
- OUTPUT_STRIP_TRAILING_WHITESPACE
- )
-
- # Get the current version counter
- execute_process(
- COMMAND git rev-list HEAD --count
- WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
- OUTPUT_VARIABLE GIT_COMMIT_COUNT
- OUTPUT_STRIP_TRAILING_WHITESPACE
- )
-
- SET(GIT_LIVE_REV_CMD "`cd '${PROJECT_SOURCE_DIR}' && git rev-list HEAD --count`.`cd '${PROJECT_SOURCE_DIR}' && git log -1 --format=%h --abbrev=7`")
-
- MESSAGE(STATUS "Using GIT revision stamp: [${GIT_COMMIT_COUNT}.${GIT_SHA1}] CMD [${GIT_LIVE_REV_CMD}]")
-
- IF(CMAKE_GENERATOR STREQUAL Xcode)
- SET(GIT_VERSION_CMD "-DGITVERSION='\\\\'${GIT_COMMIT_COUNT}.${GIT_SHA1}\\\\''")
- ELSE()
- SET(GIT_VERSION_CMD "-DGITVERSION='\\\"${GIT_LIVE_REV_CMD}\\\"'")
- ENDIF()
- ENDIF()
+ # see if this fixes compile issue for tomreyn: libpthread.so.0: error adding symbols: DSO missing from command line
+ IF(UNIX)
+ MESSAGE(STATUS "*NOTE: Apply fix for: libpthread.so.0: error adding symbols: DSO missing from command line")
+ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")
+ set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} -pthread")
+ SET(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} -pthread")
+ SET(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} -pthread")
ENDIF()
SET(COMMON_INFO_ABOUT_PATH "(if the path is relative then is appended to the CMAKE_INSTALL_PREFIX)")
IF(CMAKE_INSTALL_PREFIX STREQUAL "")
MESSAGE(STATUS "*NOTE: NOT USING a Custom Data Install Path...")
ELSE()
- IF(WANT_SINGLE_INSTALL_DIRECTORY AND NOT MEGAGLEST_SINGLE_DIRECTORY_INSTALL_PATH)
- SET(MEGAGLEST_SINGLE_DIRECTORY_INSTALL_PATH "megaglest-game/" CACHE STRING "The single directory installation path for game ${COMMON_INFO_ABOUT_PATH}")
+ IF(WANT_SINGLE_INSTALL_DIRECTORY AND NOT ZETAGLEST_SINGLE_DIRECTORY_INSTALL_PATH)
+ SET(ZETAGLEST_SINGLE_DIRECTORY_INSTALL_PATH "zetaglest-game/" CACHE STRING "The single directory installation path for game ${COMMON_INFO_ABOUT_PATH}")
ENDIF()
- IF(NOT MEGAGLEST_BIN_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
- SET(MEGAGLEST_BIN_INSTALL_PATH "bin/" CACHE STRING "The installation path for binaries ${COMMON_INFO_ABOUT_PATH}")
+ IF(NOT ZETAGLEST_BIN_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
+ SET(ZETAGLEST_BIN_INSTALL_PATH "bin/" CACHE STRING "The installation path for binaries ${COMMON_INFO_ABOUT_PATH}")
ENDIF()
- IF(NOT MEGAGLEST_DATA_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
- SET(MEGAGLEST_DATA_INSTALL_PATH "share/megaglest/" CACHE STRING "The installation path for data files ${COMMON_INFO_ABOUT_PATH}")
+ IF(NOT ZETAGLEST_DATA_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
+ SET(ZETAGLEST_DATA_INSTALL_PATH "share/zetaglest/" CACHE STRING "The installation path for data files ${COMMON_INFO_ABOUT_PATH}")
ENDIF()
- SET(MEGAGLEST_INI_INSTALL_PATH "${MEGAGLEST_DATA_INSTALL_PATH}")
- IF(NOT MEGAGLEST_DESKTOP_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
- SET(MEGAGLEST_DESKTOP_INSTALL_PATH "share/applications/" CACHE STRING "The installation path for desktop files ${COMMON_INFO_ABOUT_PATH}")
+ SET(ZETAGLEST_INI_INSTALL_PATH "${ZETAGLEST_DATA_INSTALL_PATH}")
+ IF(NOT ZETAGLEST_DESKTOP_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
+ SET(ZETAGLEST_DESKTOP_INSTALL_PATH "share/applications/" CACHE STRING "The installation path for desktop files ${COMMON_INFO_ABOUT_PATH}")
ENDIF()
- IF(NOT MEGAGLEST_ICON_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
- SET(MEGAGLEST_ICON_INSTALL_PATH "share/pixmaps/" CACHE STRING "The installation path for icon files ${COMMON_INFO_ABOUT_PATH}")
+ IF(NOT ZETAGLEST_ICON_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
+ SET(ZETAGLEST_ICON_INSTALL_PATH "share/pixmaps/" CACHE STRING "The installation path for icon files ${COMMON_INFO_ABOUT_PATH}")
ENDIF()
- IF(NOT MEGAGLEST_MANPAGE_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
- SET(MEGAGLEST_MANPAGE_INSTALL_PATH "share/man/man6/" CACHE STRING "The installation path for manpage files ${COMMON_INFO_ABOUT_PATH}")
+ IF(NOT ZETAGLEST_MANPAGE_INSTALL_PATH AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
+ SET(ZETAGLEST_MANPAGE_INSTALL_PATH "share/man/man6/" CACHE STRING "The installation path for manpage files ${COMMON_INFO_ABOUT_PATH}")
ENDIF()
IF(WANT_SINGLE_INSTALL_DIRECTORY)
- FOREACH(MG_PATH BIN DATA INI DESKTOP ICON)
- IF(NOT MEGAGLEST_${MG_PATH}_INSTALL_PATH)
- SET(MEGAGLEST_${MG_PATH}_INSTALL_PATH "${MEGAGLEST_SINGLE_DIRECTORY_INSTALL_PATH}")
+ FOREACH(ZG_PATH BIN DATA INI DESKTOP ICON)
+ IF(NOT ZETAGLEST_${ZG_PATH}_INSTALL_PATH)
+ SET(ZETAGLEST_${ZG_PATH}_INSTALL_PATH "${ZETAGLEST_SINGLE_DIRECTORY_INSTALL_PATH}")
ENDIF()
ENDFOREACH()
ENDIF()
IF(NOT WANT_SINGLE_INSTALL_DIRECTORY)
- FOREACH(MG_PATH DATA INI)
- IF(IS_ABSOLUTE "${MEGAGLEST_${MG_PATH}_INSTALL_PATH}")
- SET(MEGAGLEST_FULL_${MG_PATH}_INSTALL_PATH "${MEGAGLEST_${MG_PATH}_INSTALL_PATH}/")
+ FOREACH(ZG_PATH DATA INI)
+ IF(IS_ABSOLUTE "${ZETAGLEST_${ZG_PATH}_INSTALL_PATH}")
+ SET(ZETAGLEST_FULL_${ZG_PATH}_INSTALL_PATH "${ZETAGLEST_${ZG_PATH}_INSTALL_PATH}/")
ELSE()
- SET(MEGAGLEST_FULL_${MG_PATH}_INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/${MEGAGLEST_${MG_PATH}_INSTALL_PATH}/")
+ SET(ZETAGLEST_FULL_${ZG_PATH}_INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/${ZETAGLEST_${ZG_PATH}_INSTALL_PATH}/")
ENDIF()
- STRING(REGEX REPLACE "//+" "/" MEGAGLEST_FULL_${MG_PATH}_INSTALL_PATH "${MEGAGLEST_FULL_${MG_PATH}_INSTALL_PATH}")
+ STRING(REGEX REPLACE "//+" "/" ZETAGLEST_FULL_${ZG_PATH}_INSTALL_PATH "${ZETAGLEST_FULL_${ZG_PATH}_INSTALL_PATH}")
ENDFOREACH()
IF(NOT CUSTOM_DATA_INSTALL_PATH)
- SET(CUSTOM_DATA_INSTALL_PATH "${MEGAGLEST_FULL_DATA_INSTALL_PATH}")
+ SET(CUSTOM_DATA_INSTALL_PATH "${ZETAGLEST_FULL_DATA_INSTALL_PATH}")
# ^ someday this intermediate step may be removed
ENDIF()
SET(CUSTOM_INSTALL_PATHS_VALUES "-DCUSTOM_DATA_INSTALL_PATH=${CUSTOM_DATA_INSTALL_PATH}")
ENDIF()
#SET(PKG_DATADIR ${CUSTOM_DATA_INSTALL_PATH_VALUE})
- #SET(PKG_BINDIR ${MEGAGLEST_BIN_INSTALL_PATH})
+ #SET(PKG_BINDIR ${ZETAGLEST_BIN_INSTALL_PATH})
# ^ hard to tell for what it is needed and most likely both were set to wrong values, so let's try to not use them
MESSAGE(STATUS "*NOTE: Custom Data Install Path is [${CUSTOM_DATA_INSTALL_PATH}]")
ENDIF()
- string(TOUPPER "${CMAKE_BUILD_TYPE}" MG_BUILD_TYPE)
+ string(TOUPPER "${CMAKE_BUILD_TYPE}" ZG_BUILD_TYPE)
IF(HAS_GIT STREQUAL "TRUE")
- SET(CMAKE_CXX_FLAGS_${MG_BUILD_TYPE} "${CMAKE_CXX_FLAGS_${MG_BUILD_TYPE}} ${GIT_VERSION_CMD}")
+ SET(CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE} "${CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE}} ${GIT_VERSION_CMD}")
ENDIF()
- SET(CMAKE_CXX_FLAGS_${MG_BUILD_TYPE} "${CMAKE_CXX_FLAGS_${MG_BUILD_TYPE}} ${CUSTOM_INSTALL_PATHS_VALUES}")
+ SET(CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE} "${CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE}} ${CUSTOM_INSTALL_PATHS_VALUES}")
# We do some funky character escaping to get the right stuff written out to
# the final Makefile so we get the GIT Global Revsion #
- string(REPLACE "'" "\"" CMAKE_CXX_FLAGS_${MG_BUILD_TYPE} "${CMAKE_CXX_FLAGS_${MG_BUILD_TYPE}}")
+ string(REPLACE "'" "\"" CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE} "${CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE}}")
- message(STATUS "CMAKE_CXX_FLAGS_${MG_BUILD_TYPE}: ${CMAKE_CXX_FLAGS_${MG_BUILD_TYPE}}")
+ message(STATUS "CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE}: ${CMAKE_CXX_FLAGS_${ZG_BUILD_TYPE}}")
# Win32 specific Compiler Flags
IF(WIN32)
@@ -348,10 +306,10 @@ IF(NOT WANT_DEPRECATION_WARNINGS)
ENDIF()
MARK_AS_ADVANCED(WANT_DEPRECATION_WARNINGS)
-IF(NOT MG_CMAKE_INSTALL_PREFIX AND NOT CMAKE_INSTALL_PREFIX STREQUAL "")
- SET(MG_CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
+IF(NOT ZG_CMAKE_INSTALL_PREFIX AND NOT CMAKE_INSTALL_PREFIX STREQUAL "")
+ SET(ZG_CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
ENDIF()
-MESSAGE(STATUS "**NOTE: MG_CMAKE_INSTALL_PREFIX is [${MG_CMAKE_INSTALL_PREFIX}]")
+MESSAGE(STATUS "**NOTE: ZG_CMAKE_INSTALL_PREFIX is [${ZG_CMAKE_INSTALL_PREFIX}]")
SET(SDL_WINDOWS_DIR_DINC "SDL-2.0.x")
SET(SDL_VERSION_NAME "SDL2")
@@ -359,13 +317,13 @@ SET(SDL_VERSION_SNAME "sdl")
OPTION(WANT_DEV_OUTPATH "Use developer friendly output paths." OFF)
IF(UNIX AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
- SET(MEGAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/mk/linux/")
+ SET(ZETAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/mk/linux/")
ELSEIF(UNIX AND APPLE)
- SET(MEGAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/mk/macos/")
+ SET(ZETAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/mk/macos/")
ELSEIF(UNIX AND NOT APPLE)
- SET(MEGAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/mk/other_unix/")
+ SET(ZETAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/mk/other_unix/")
ELSE()
- SET(MEGAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/data/glest_game/")
+ SET(ZETAGLEST_FRIENDLY_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/data/glest_game/")
ENDIF()
IF(WIN32)
@@ -431,33 +389,33 @@ IF(NOT DEFINED CPACK_GENERATOR)
ENDIF()
# CPack configuration shared accross platforms
SET(CPACK_PACKAGE_NAME ${PKG_NAME})
-IF(EXISTS "${PROJECT_SOURCE_DIR}/data/glest_game/others/megaglest-long-description.txt.in")
- FILE(READ "${PROJECT_SOURCE_DIR}/data/glest_game/others/megaglest-long-description.txt.in" MEGAGLEST_LONG_DESCRIPTION)
- SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${MEGAGLEST_LONG_DESCRIPTION}")
+IF(EXISTS "${PROJECT_SOURCE_DIR}/../zetaglest-data/others/zetaglest-long-description.txt.in")
+ FILE(READ "${PROJECT_SOURCE_DIR}/../zetaglest-data/others/zetaglest-long-description.txt.in" ZETAGLEST_LONG_DESCRIPTION)
+ SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${ZETAGLEST_LONG_DESCRIPTION}")
ELSE()
- SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "MegaGlest")
+ SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "ZetaGlest")
ENDIF()
-SET(CPACK_PACKAGE_VENDOR "megaglest.org")
+SET(CPACK_PACKAGE_VENDOR "zetaglest.github.io")
#SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README")
#SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING")
-SET(CPACK_PACKAGE_INSTALL_DIRECTORY "megaglest")
+SET(CPACK_PACKAGE_INSTALL_DIRECTORY "zetaglest")
SET(CPACK_PACKAGING_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
-SET(CPACK_PACKAGE_VERSION "${MEGAGLEST_VERSION}")
+SET(CPACK_PACKAGE_VERSION "${ZETAGLEST_VERSION}")
SET(CPACK_PACKAGE_VERSION_MAJOR "${VER_MAJOR}")
SET(CPACK_PACKAGE_VERSION_MINOR "${VER_MINOR}")
SET(CPACK_PACKAGE_VERSION_PATCH "${VER_PATCH}")
IF("${CPACK_GENERATOR}" STREQUAL "DEB")
- SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Mark Vejvoda") #required
+ SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "ZetaGlest Team") #required
SET(CPACK_DEBIAN_PACKAGE_SECTION "games")
SET(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
SET(CPACK_DEBIAN_PACKAGE_SUGGESTS "p7zip-full")
ENDIF()
IF("${CPACK_GENERATOR}" STREQUAL "NSIS")
- SET(CPACK_NSIS_DISPLAY_NAME "MegaGlest")
+ SET(CPACK_NSIS_DISPLAY_NAME "ZetaGlest")
SET(CPACK_NSIS_MUI_ICON "${PROJECT_SOURCE_DIR}/mk/windows/zetaglest.ico")
SET(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/mk/windows/zetaglest.ico")
- SET(CPACK_NSIS_URL_INFO_ABOUT "http://megaglest.org")
+ SET(CPACK_NSIS_URL_INFO_ABOUT "https://zetaglest.github.io")
ENDIF()
INCLUDE(CPack)
diff --git a/ChangeLog.md b/ChangeLog.md
index e1d432c2c..a9614bdb2 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -5,6 +5,29 @@ This documents notable or significant changes to
information about the game from which it was forked, please see the
[MegaGlest home page](https://megaglest.org/).
+## 2018-05-08
+
+OpenBSD build instructions added
+
+## 2018-05-06
+
+[[d1acd87](https://github.com/ZetaGlest/zetaglest-source/commit/d1acd8742395bca8b37656e9e8065022902586fe)]Lua
+can now be used in scripts tag in faction tag within XML
+
+## 2018-03-31
+
+[[bugfix:835c6ef](https://github.com/ZetaGlest/zetaglest-source/commit/835c6efd924ed7e62ccd43e064bc6b7f5cdecbfc)]Fixed
+"x" key getting stuck on Windows
+
+## 2018-03-20
+
+[[045b0b8](https://github.com/ZetaGlest/zetaglest-source/commit/045b0b88e051f7163fbef42fa0adc63a326ca186)]Removed "MG_" and "xxx" (3 digit extension) on nicknames in lobby player list
+
+## 2018-03-14
+
+[Windows](https://github.com/ZetaGlest/zetaglest-source/commits/develop/mk/windows) build
+system, dependencies, and documentation updated
+
## 2018-02-22
* Some sound effects can now be customized by players. See
diff --git a/README.md b/README.md
index bd1a2004d..df70de339 100644
--- a/README.md
+++ b/README.md
@@ -21,9 +21,19 @@ Open games and [Server list and player stats](https://zetaglest.dreamhosters.com
[Detailed information about units in the game](https://zetaglest.github.io/)
+## Stay Informed (Updates)
+
+* [ChangeLog.md](https://github.com/ZetaGlest/zetaglest-source/blob/develop/ChangeLog.md)
+* [](https://github.com/ZetaGlest/zetaglest-source/commits/develop.atom)
+[Recent Commits to zetaglest-source:develop](https://github.com/ZetaGlest/zetaglest-source/commits/develop.atom)
+* [](https://github.com/ZetaGlest/zetaglest-data/commits/develop.atom)
+[Recent Commits to zetaglest-data:develop](https://github.com/ZetaGlest/zetaglest-data/commits/develop.atom)
+* [](https://github.com/ZetaGlest/zetaglest.github.io/commits/master.atom)
+[Recent Commits to the web site](https://github.com/ZetaGlest/zetaglest.github.io/commits/master.atom)
+
## Why this fork? (Project Goals)
-ZetaGlest forked from MegaGlest at v3.13.0-dev
+ZetaGlest forked from MegaGlest at v3.13.0-dev ([12998eb](https://github.com/ZetaGlest/zetaglest-source/commit/12998eb10f6447ac89a45d1e6d76f17946647b7a))
I noticed that there were some good feature requests in the MegaGlest
forum, as well as some mods, but it seemed that implementing and
@@ -99,4 +109,5 @@ for extended, important instructions and guidelines for contributing.
## Contact
* [Discord](https://discord.gg/WaAaXS7)
+* [Message Board](https://groups.google.com/forum/#!forum/zetaglest)
* email: andy400-dev@yahoo.com
diff --git a/docs/AUTHORS.source_code.txt b/deprecated_megaglest_docs/AUTHORS.source_code.txt
similarity index 100%
rename from docs/AUTHORS.source_code.txt
rename to deprecated_megaglest_docs/AUTHORS.source_code.txt
diff --git a/docs/CHANGELOG.txt b/deprecated_megaglest_docs/CHANGELOG.txt
similarity index 100%
rename from docs/CHANGELOG.txt
rename to deprecated_megaglest_docs/CHANGELOG.txt
diff --git a/docs/COPYRIGHT.source_code.txt b/deprecated_megaglest_docs/COPYRIGHT.source_code.txt
similarity index 100%
rename from docs/COPYRIGHT.source_code.txt
rename to deprecated_megaglest_docs/COPYRIGHT.source_code.txt
diff --git a/docs/README.release-management.txt b/deprecated_megaglest_docs/README.release-management.txt
similarity index 100%
rename from docs/README.release-management.txt
rename to deprecated_megaglest_docs/README.release-management.txt
diff --git a/docs/README.txt b/deprecated_megaglest_docs/README.txt
similarity index 98%
rename from docs/README.txt
rename to deprecated_megaglest_docs/README.txt
index 73cba973d..014f4c828 100644
--- a/docs/README.txt
+++ b/deprecated_megaglest_docs/README.txt
@@ -1,3 +1,7 @@
+The documents in this directory are here for historical purposes and pertain
+to MegaGlest, not ZetaGlest. To view active documentation for ZetaGlest, see
+https://github.com/ZetaGlest/zetaglest-source and https://zetaglest.github.io/docs/
+
MEGAGLEST
diff --git a/docs/gnu_gpl_3.0.txt b/deprecated_megaglest_docs/gnu_gpl_3.0.txt
similarity index 100%
rename from docs/gnu_gpl_3.0.txt
rename to deprecated_megaglest_docs/gnu_gpl_3.0.txt
diff --git a/docs/README.compiling-linux.txt b/docs/README.compiling-linux.txt
deleted file mode 100644
index a323a4b00..000000000
--- a/docs/README.compiling-linux.txt
+++ /dev/null
@@ -1,174 +0,0 @@
-
- MEGAGLEST
-
- by Titus Tscharntke and Mark Vejvoda
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Build instructions for Linux
-~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. Architecture ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Developed on Linux with glibc, little endian CPU. While MacIntel builds exist
-(for some versions of the game), MegaGlest does not currently work on big
-endian CPUs like PPC (though some unfinished patches for vanilla Glest float
-around on the forums, e.g. http://forum.megaglest.org/?topic=1426#).
-
-~~~~~~~~~~~~~~~~~~~~~~ 2. Building and Installation ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
---- 2.1 Prerequesites ---
-
-Compiling MegaGlest requires the following dependencies to be installed:
-
-* Standard GNU compiler and additional tools (g++ version 4.6.3 or later is
- required at the moment)
-
-* Kitware CMake 2.8.2 or later (used as build tool)
-
-* X11 libraries + headers
- http://x.org/
-
-* SDL 2.0.0 or later
- http://libsdl.org/
-
-* OpenGL
- http://dri.freedesktop.org/wiki/libGL
-
-* libvlc
- http://www.videolan.org/vlc/libvlc.html
-
-* libcurl
- http://curl.haxx.se/libcurl/
-
-* wxWidgets
- http://wxwidgets.org/
-
-* OpenAL
- http://openal.org/
-
-* Ogg
- http://xiph.org/ogg/
-
-* Vorbis
- http://xiph.org/vorbis/
-
-* Xerces-C
- http://xerces.apache.org/xerces-c/
-
-* Lua 5.1 or later
- http://www.lua.org/
-
-* JPEG
- http://www.ijg.org/
-
-* PNG
- http://www.libpng.org/
-
-* Zlib
- http://zlib.net/
-
-* GnuTLS
- http://www.gnu.org/software/gnutls/
-
-* ICU
- http://site.icu-project.org/
-
-* libdl
-
-NOTE: A script which tries to install build dependencies on many Linux distros
-is located in mk/linux/setupBuildDeps.sh
-
---- 2.2 Building ---
-
-To build the game simply invoke the build script:
-
-../mk/linux/build-mg.sh
-
-This script manually calls cmake with some optional parameters. Feel free to
-examine it and build manually using cmake.
-
---- 2.3 Installation --
-
-We provide MojoSetup based installers for Linux and NSIS based installers for
-Windows. By default, the Linux installers install to your home directory. The
-Windows installers install to %ProgramFiles% (global system scope).
-
-There are also community maintained packages available for several Linux and
-BSD distributions. Please see the website, forums and wiki for details.
-
-
-~~~~~~~~~~~~~~~~~~~~~~ 3. Troubleshooting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
---- General ---
-* Make sure both the hardware and software of your system match the requirements
-* If you cannot find what you are looking for on here please check the FAQs
- (https://docs.megaglest.org/MG/FAQ) before contacting the developers.
-
---- Compiling ---
-* If CMake reports that it cannot find some of the libraries, make sure that
- the relevant ...-dev(el) packages are also installed (distro-dependent).
-
---- Sound/Audio ---
-* If the game doesn't start because of audio/sound errors:
- Make sure no other application is using your soundcard. Typical problems are
- the Gnome/KDE sound dameons esd and artsd. You can kill these daemons with
- the following commands:
- # killall esd ; killall artsd
-
-* If this doesn't solve the sound problems, get an updated OpenAL from
- http://openal.org or a newer repository provided by your distribution.
-
-* Sound is played through OpenAL - double-check the OpenAL system
- configuration: http://supertux.lethargik.org/wiki/OpenAL_Configuration
-
---- OpenGL ---
-* If the game produces error messages regarding OpenGL or OpenGL extensions
- being unavailable, look at glxinfo and make sure the system is using the
- drivers you want to use. If you have a NVIDIA or AMD/ATI graphics card then
- consider using the proprietary drivers, which may provide better
- performance than the open source drivers most distributions use by default.
- Most Intel graphics chips use an open source driver on Linux, based on Mesa
- ("glxinfo | grep -i mesa"). This hardware is much slower than any dedicated
- graphics cards produced during the past few years. The same holds true for
- AMD APUs (the graphics chips embedded into AMD processors).
-
---- Crashing ---
-* Check the forums at http://forums.megaglest.org/
-* Please report any crashes and freezes that are not yet described on the forums,
- preferably with a gdb backtrace from a debugging enabled build
- (cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo)
-
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~ 4. More information ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-* Website
- http://megaglest.org/
-
-* Wiki
- https://docs.megaglest.org/Main_Page
-
-* Forums
- http://forums.megaglest.org/
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5. Contact + Credits ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-* MegaGlest is developed by:
- Titus Tscharntke (info@titusgames.de)
- Mark Vejvoda (www.soft-haus.com - mark_vejvoda@hotmail.com)
-
-* General contact:
- contact@megaglest.org
-
-* MegaGlest is a fork of Glest:
- http://glest.org/
-
-* Linux port by:
- Matthias Braun
-
-
- with help from
-
- Karl Robillard
-
-
-*** Please also refer to the copyright file. ***
-
-On Debian GNU/Linux systems please find license information in:
-/usr/share/common-licenses
diff --git a/docs/README.compiling-windows.txt b/docs/README.compiling-windows.txt
deleted file mode 100644
index 292c19375..000000000
--- a/docs/README.compiling-windows.txt
+++ /dev/null
@@ -1,152 +0,0 @@
-
- MEGAGLEST
-
- by Titus Tscharntke and Mark Vejvoda
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Build Instructions for Windows
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. Architecture ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Developed on Windows with Microsoft Visual Studio Community 2015,
-little endian CPU. Compiling using the mingw32 toolset is experimental, which
-also allows for cross compiling.
-
-On Debian GNU/Linux systems please find license information in:
-/usr/share/common-licenses
-Also see Build Instructions for Linux
-
-~~~~~~~~~~~~~~~~~~~~~~~~ 2. Building and Installation ~~~~~~~~~~~~~~~~~~~~~~~~
-
---- 2.1 Prerequesites ---
-
-To build the game, the following tools and libraries must be present:
-
-- Pick 1:
-* Microsoft Visual Studio Community 2015
- https://www.microsoft.com/en-us/download/details.aspx?id=48146
- (Experimental Microsoft Visual C++ Express 2012 projects also exist in the vc2012
- folder)
-* mingw32
- http://mingw.org/
-
-- Pick 1:
-* MegaGlest dependencies for building with VC++, which which will be downloaded
- automatically in 'Option A' (see below)
-* MegaGlest Windows 32 bit dependencies for building with mingw:
- https://github.com/MegaGlest/megaglest-source/releases/download/3.2.3/win32_deps_mingw.7z
-
-- These include:
-* Xerces-C
- http://xerces.apache.org/xerces-c/
-* wxWidgets
- http://wxwidgets.org/
-* And many more. For a more verbose list, please inspect the archive contents and refer to the
- Linux build instructions.
-
-
---- 2.2 Building ---
-
-To build and install the game proceed as follows:
-
-*** Option A ~ (recommended) Automated build on the command line:
-
-1. Open a command prompt and navigate to the root folder where you have acquired the source code.
-
-2. cd mk\windows
-
-3. build-mg-2015.bat (or build-mg32bit-2015.bat for 32 bit build)
-
-4. megaglest.exe --version
-
-5. megaglest.exe
-
-*** Option B ~ Using VC++ IDE:
-
-1. Download the dependencies archive (which one and from where you can find
- out in the "code" of build-...bat script from 'Option A' approach, some line
- with "wget.exe") and decompress its contents into the 'source' directory. This
- should create a subdirectory called "windows_deps..." with many files and
- subdirectories in it.
-
-2. Start the Visual C++ 2015 IDE and open the solution file:
- \mk\windows\Glest_vc2015.sln
-
-3. Right Click on the top level 'Glest' node in Solution Explorer and select
- 'Rebuild All' (choose release mode or release with debug info).
-
-Note: If you had no errors all binaries will be created.
- Before running MegaGlest you must run CopyWindowsRuntimeDlls_2015.bat.
- You should now be able to just run megaglest.exe.
-
-
---- 2.3 Installation ---
-
-We provide NSIS based installation packages. By default, these will create a
-system-wide installation below %ProgramFiles% and setup Desktop icons for
-simplified access. User specific configuration will be stored within the
-directory tree the %AppData% environment variable points to.
-
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3. Troubleshooting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
---- General ---
-* Make sure that the hardware and software of your system match the
- requirements
-
-* If you cannot find what you are looking for on here please check the FAQs
- (https://docs.megaglest.org/MG/FAQ) before contacting.
-
---- Compiling ---
-* If configure fails make sure you have read the Building section above
-
---- Sound/Audio errors when starting ---
-* If the game doesn't start because of audio/sound errors:
- Make sure no other application is using your soundcard.
-* If this doesn't solve your sound problems try to get an updated OpenAL from
- http://openal.org
-* Sound is played through OpenAL - you might need to take a look at your
- configuration: http://supertux.lethargik.org/wiki/OpenAL_Configuration
-
---- The game complains that OpenGL 1.3: is not available, is missing OpenGL
- extensions, or works very slowly ---
-* Try to get updated graphics drivers.
-
--- The game crashes ---
-* Check the forums at http://forums.megaglest.org/
-* Please report any other crashes and freezes that are not yet described on
- the forums, preferably with a backtrace from a debugging enabled build
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~ 4. More information ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-* Website
- http://megaglest.org/
-
-* Wiki
- https://docs.megaglest.org/Main_Page
-
-* Forums
- http://forums.megaglest.org/
-
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5. Contact + Credits ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-* MegaGlest is developed by:
- Titus Tscharntke (info@titusgames.de)
- Mark Vejvoda (www.soft-haus.com - mark_vejvoda@hotmail.com)
-
-* General contact:
- contact@megaglest.org
-
-* MegaGlest is a fork of Glest:
- http://glest.org/
-
-* Linux port by:
- Matthias Braun
-
-
- with help from
-
- Karl Robillard
-
-
-*** Please also refer to the copyright file. ***
diff --git a/mk/cmake/Modules/ReqVersAndStaticConf.cmake b/mk/cmake/Modules/ReqVersAndStaticConf.cmake
index c9bc8db79..61c02805a 100644
--- a/mk/cmake/Modules/ReqVersAndStaticConf.cmake
+++ b/mk/cmake/Modules/ReqVersAndStaticConf.cmake
@@ -8,7 +8,7 @@
#
IF(WANT_STATIC_LIBS)
- IF(BUILD_MEGAGLEST_MODEL_VIEWER OR BUILD_MEGAGLEST_MAP_EDITOR OR BUILD_MEGAGLEST)
+ IF(BUILD_ZETAGLEST_MODEL_VIEWER OR BUILD_ZETAGLEST_MAP_EDITOR OR BUILD_ZETAGLEST)
# shared lib
FOREACH(STATIC_LIB
OpenSSL
@@ -26,7 +26,7 @@ IF(WANT_STATIC_LIBS)
LIST(APPEND LIST_OF_STATIC_LIBS_MG "${STATIC_LIB}")
ENDFOREACH()
ENDIF()
- IF(BUILD_MEGAGLEST_MODEL_VIEWER OR BUILD_MEGAGLEST_MAP_EDITOR)
+ IF(BUILD_ZETAGLEST_MODEL_VIEWER OR BUILD_ZETAGLEST_MAP_EDITOR)
# wxWidgets for tools
FOREACH(STATIC_LIB
wxWidgets)
@@ -38,7 +38,7 @@ IF(WANT_STATIC_LIBS)
# wxWidgets by default are not available static
ENDIF()
ENDIF()
- IF(BUILD_MEGAGLEST)
+ IF(BUILD_ZETAGLEST)
# only libs not used by shared lib
FOREACH(STATIC_LIB
OGG)
diff --git a/mk/linux/.gitignore b/mk/linux/.gitignore
index 8ed774cfc..af011f75c 100644
--- a/mk/linux/.gitignore
+++ b/mk/linux/.gitignore
@@ -1,7 +1,9 @@
-/megaglest
-/megaglest.6
+/zetaglest
+/zetaglest.6
+/zetaglest_editor*
+/zetaglest_g3dviewer*
+/zetaglest_tests
-/megaglest_*
!/*.desktop
core
diff --git a/mk/linux/build-zg.sh b/mk/linux/build-zg.sh
index aa6be180b..a20e92f77 100755
--- a/mk/linux/build-zg.sh
+++ b/mk/linux/build-zg.sh
@@ -25,7 +25,7 @@ GCC_FORCED_VERSION=0
LUA_FORCED_VERSION=0
FORCE_32BIT_CROSS_COMPILE=0
COMPILATION_WITHOUT=0
-BUILD_MEGAGLEST_TESTS="ON"
+BUILD_ZETAGLEST_TESTS="ON"
while getopts "c:defg:hl:mnswx" option; do
case "${option}" in
@@ -189,14 +189,14 @@ case $distribution in
echo 'Turning ON dynamic FTGL, LUA, JPEG, PNG ... and forcing use the embedded IRCCLIENT'
EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DSTATIC_FTGL=OFF -DSTATIC_LUA=OFF -DSTATIC_JPEG=OFF -DSTATIC_PNG=OFF -DSTATIC_OGG=OFF -DFORCE_USE_EMBEDDED_Ircclient=ON"
fi
- if [ $CLANG_FORCED = 1 ]; then BUILD_MEGAGLEST_TESTS="OFF"; fi
+ if [ $CLANG_FORCED = 1 ]; then BUILD_ZETAGLEST_TESTS="OFF"; fi
;;
*)
if [ "$WANT_STATIC_LIBS" = "-DWANT_STATIC_LIBS=ON" ]; then
echo 'Turning ON dynamic OGG ... and forcing use the embedded IRCCLIENT'
EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DSTATIC_OGG=OFF -DFORCE_USE_EMBEDDED_Ircclient=ON"
fi
- if [ $CLANG_FORCED = 1 ]; then BUILD_MEGAGLEST_TESTS="OFF"; fi
+ if [ $CLANG_FORCED = 1 ]; then BUILD_ZETAGLEST_TESTS="OFF"; fi
# ^ may be removed ~ when default clang's version will be 3.9+
;;
esac
@@ -311,12 +311,12 @@ if [ $FORCE_32BIT_CROSS_COMPILE != 0 ]; then
fi
if [ "$COMPILATION_WITHOUT" != "0" ] && [ "$COMPILATION_WITHOUT" != "" ]; then
- EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DBUILD_MEGAGLEST_MAP_EDITOR=OFF -DBUILD_MEGAGLEST_MODEL_VIEWER=OFF"
+ EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DBUILD_ZETAGLEST_MAP_EDITOR=OFF -DBUILD_ZETAGLEST_MODEL_VIEWER=OFF"
fi
if [ $MAKE_ONLY = 0 ]; then
echo "Calling cmake with EXTRA_CMAKE_OPTIONS = ${EXTRA_CMAKE_OPTIONS} AND WANT_STATIC_LIBS = ${WANT_STATIC_LIBS}"
- cmake -DCMAKE_INSTALL_PREFIX='' -DWANT_DEV_OUTPATH=ON $WANT_STATIC_LIBS -DBUILD_MEGAGLEST_TESTS=$BUILD_MEGAGLEST_TESTS -DBREAKPAD_ROOT=$BREAKPAD_ROOT $EXTRA_CMAKE_OPTIONS ../../..
+ cmake -DCMAKE_INSTALL_PREFIX='' -DWANT_DEV_OUTPATH=ON $WANT_STATIC_LIBS -DBUILD_ZETAGLEST_TESTS=$BUILD_ZETAGLEST_TESTS -DBREAKPAD_ROOT=$BREAKPAD_ROOT $EXTRA_CMAKE_OPTIONS ../../..
if [ $? -ne 0 ]; then
echo 'ERROR: CMAKE failed.' >&2; exit 1
fi
diff --git a/mk/macos/CMakeLists.txt b/mk/macos/CMakeLists.txt
index a587c35c2..2a143a8c3 100644
--- a/mk/macos/CMakeLists.txt
+++ b/mk/macos/CMakeLists.txt
@@ -37,7 +37,7 @@ include (InstallRequiredSystemLibraries)
# Use bundle generator (OSX has 3 other options if you feel adventurous)
SET(CPACK_GENERATOR "Bundle")
SET(CPACK_BUNDLE_NAME "MegaGlest")
-SET(CPACK_PACKAGE_FILE_NAME "MegaGlest-game-macos-${MEGAGLEST_VERSION}")
+SET(CPACK_PACKAGE_FILE_NAME "MegaGlest-game-macos-${ZETAGLEST_VERSION}")
SET(CPACK_PACKAGE_ICON "${CMAKE_CURRENT_SOURCE_DIR}/mk/macos/bundle_resources/MegaGlest.icns")
SET(CPACK_BUNDLE_ICON "${CMAKE_CURRENT_SOURCE_DIR}/mk/macos/bundle_resources/MegaGlest.icns")
SET(CPACK_BUNDLE_STARTUP_COMMAND "${PROJECT_SOURCE_DIR}/mk/macos/bundle_resources/MegaGlest.sh")
diff --git a/mk/macos/build-zg.sh b/mk/macos/build-zg.sh
index 70e83c601..f8a4a4343 100755
--- a/mk/macos/build-zg.sh
+++ b/mk/macos/build-zg.sh
@@ -191,7 +191,7 @@ if [ "$FORCE_EMBEDDED_LIBS" != "0" ] && [ "$FORCE_EMBEDDED_LIBS" != "" ]; then
fi
if [ "$COMPILATION_WITHOUT" != "0" ] && [ "$COMPILATION_WITHOUT" != "" ]; then
- EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DBUILD_MEGAGLEST_MAP_EDITOR=OFF -DBUILD_MEGAGLEST_MODEL_VIEWER=OFF"
+ EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DBUILD_ZETAGLEST_MAP_EDITOR=OFF -DBUILD_ZETAGLEST_MODEL_VIEWER=OFF"
fi
if [ "$MAKE_ONLY" -eq "0" ]; then
@@ -200,7 +200,7 @@ if [ "$MAKE_ONLY" -eq "0" ]; then
EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DCMAKE_INSTALL_PREFIX=''"
if [ "$GCC_FORCED" -ne "1" ] || [ "$USE_XCODE" -eq "1" ]; then :
#^ Remove this condition when it V will start working on gcc
- #EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DBUILD_MEGAGLEST_TESTS=ON"
+ #EXTRA_CMAKE_OPTIONS="${EXTRA_CMAKE_OPTIONS} -DBUILD_ZETAGLEST_TESTS=ON"
#^ Uncomment when it will start working on clang
else
rm -f ../zetaglest_tests
diff --git a/mk/macos/bundle_resources/Info.plist.in b/mk/macos/bundle_resources/Info.plist.in
index b01daa05d..9e1835cf4 100644
--- a/mk/macos/bundle_resources/Info.plist.in
+++ b/mk/macos/bundle_resources/Info.plist.in
@@ -7,11 +7,11 @@
CFBundleExecutable
MegaGlest
CFBundleGetInfoString
- v${MEGAGLEST_VERSION}, © 2018 The ZetaGlest Team.
+ v${ZETAGLEST_VERSION}, © 2018 The ZetaGlest Team.
CFBundleIconFile
MegaGlest
CFBundleIdentifier
- org.megaglest.v${MEGAGLEST_VERSION}
+ org.megaglest.v${ZETAGLEST_VERSION}
CFBundleInfoDictionaryVersion
6.0
CFBundleName
diff --git a/mk/windows/LICENSE b/mk/windows/LICENSE
deleted file mode 100644
index 94a9ed024..000000000
--- a/mk/windows/LICENSE
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- 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 3 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 .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
diff --git a/mk/windows/README.md b/mk/windows/README.md
index d0ddc03d5..891ee7000 100644
--- a/mk/windows/README.md
+++ b/mk/windows/README.md
@@ -1,5 +1,4 @@
-# Windows
-ZetaGlest build system for Windows
+# Build ZetaGlest for Windows
**To build ZetaGlest for the first time:**
@@ -34,16 +33,20 @@ To be able to run ZetaGlest from within Visual Studio using the debugger, you ne
2. Right-click `glest_game` -> `Properties` -> `Debugging` and change `Working Directory` to `$(SolutionDir)$(TargetName)\`
Do this also for `g3d_viewer` and `map_editor`.
-Configuration in Visual Studio must be left as "Release", otherwise it won't compile, but one can still use debugging options by making the following changes in the project properties:
+Configuration in Visual Studio **must be left as `Release`**, and it must match the project architecture as otherwise it won't compile. The settings involved are the following:
-Debug:
+
+
+Although the configuration *must be set as `Release`*, one can still use debugging options by making the following changes in the project properties.
+
+To manually emulate `Debug`:
Inline Function Expansion: Disabled
Enable Intrinsic Functions: No
Favor Size Or Speed: Neither
Preprocessor: DEBUG instead of NDEBUG
-Release:
+To manually emulate `Release`:
Inline Function Expansion: Any Suitable
Enable Intrinsic Functions: Yes
diff --git a/mk/windows/build-zg.bat b/mk/windows/build-zg.bat
index 46a0800e1..27dd72fe5 100644
--- a/mk/windows/build-zg.bat
+++ b/mk/windows/build-zg.bat
@@ -162,5 +162,13 @@ Echo Building ZetaGlest...
cd .\%FOLDER_NAME%\
msbuild.exe /p:Configuration=%MSBUILD_CONFIG%;Platform=%PLATFORM%;PlatformToolset=%TOOLSET% ZetaGlest.sln
cd ..\
+ECHO.
+ECHO Copying binaries...
+ECHO.
+call .\group-binaries.bat
ECHO ... Done.
+ECHO.
+ECHO If build was successful, then output is in bin folder, otherwise scroll up a little to view error messages.
+ECHO Thanks for trying out ZetaGlest.
+ECHO.
pause
\ No newline at end of file
diff --git a/mk/windows/clean-all.bat b/mk/windows/clean-all.bat
index 866e5b371..3147a121b 100644
--- a/mk/windows/clean-all.bat
+++ b/mk/windows/clean-all.bat
@@ -39,6 +39,12 @@ IF EXIST .\vs2017-64 (
cd ..\
)
+IF EXIST .\bin (
+ cd .\bin
+ CALL :DELETE
+ cd ..\
+)
+
ROBOCOPY . . /S /MOVE
ROBOCOPY . . /S /MOVE
ROBOCOPY . . /S /MOVE
diff --git a/mk/windows/clean-zg.bat b/mk/windows/clean-zg.bat
index 1125120fd..f07705a42 100644
--- a/mk/windows/clean-zg.bat
+++ b/mk/windows/clean-zg.bat
@@ -33,6 +33,12 @@ IF EXIST .\vs2017-64 (
cd ..\
)
+IF EXIST .\bin (
+ cd .\bin
+ CALL :DELETE
+ cd ..\
+)
+
ROBOCOPY . . /S /MOVE
ROBOCOPY . . /S /MOVE
ROBOCOPY . . /S /MOVE
diff --git a/mk/windows/group-binaries.bat b/mk/windows/group-binaries.bat
new file mode 100644
index 000000000..31b6f97b9
--- /dev/null
+++ b/mk/windows/group-binaries.bat
@@ -0,0 +1,37 @@
+@echo off
+md bin
+md bin\vs2015
+md bin\vs2017
+
+copy /y 7z.dll bin\vs2015\7z.dll
+copy /y 7z.dll bin\vs2017\7z.dll
+
+copy /y 7z.exe bin\vs2015\7z.exe
+copy /y 7z.exe bin\vs2017\7z.exe
+
+copy /y glest.ini bin\vs2015\glest.ini
+copy /y glest.ini bin\vs2017\glest.ini
+
+copy /y ..\shared\glestkeys.ini bin\vs2015\glestkeys.ini
+copy /y ..\shared\glestkeys.ini bin\vs2017\glestkeys.ini
+
+copy /y ..\shared\servers.ini bin\vs2015\servers.ini
+copy /y ..\shared\servers.ini bin\vs2017\servers.ini
+
+copy /y vs2015-32\g3dviewerWin32\Release\g3dviewer.exe bin\vs2015\g3dviewer-32.exe
+copy /y vs2017-32\g3dviewerWin32\Release\g3dviewer.exe bin\vs2017\g3dviewer-32.exe
+
+copy /y vs2015-32\map_editorWin32\Release\map_editor.exe bin\vs2015\map_editor-32.exe
+copy /y vs2017-32\map_editorWin32\Release\map_editor.exe bin\vs2017\map_editor-32.exe
+
+copy /y vs2015-32\zetaglest\zetaglest.exe bin\vs2015\zetaglest-32.exe
+copy /y vs2017-32\zetaglest\zetaglest.exe bin\vs2017\zetaglest-32.exe
+
+copy /y vs2015-64\g3dviewerx64\Release\g3dviewer.exe bin\vs2015\g3dviewer-64.exe
+copy /y vs2017-64\g3dviewerx64\Release\g3dviewer.exe bin\vs2017\g3dviewer-64.exe
+
+copy /y vs2015-64\map_editorx64\Release\map_editor.exe bin\vs2015\map_editor-64.exe
+copy /y vs2017-64\map_editorx64\Release\map_editor.exe bin\vs2017\map_editor-64.exe
+
+copy /y vs2015-64\zetaglest\zetaglest.exe bin\vs2015\zetaglest-64.exe
+copy /y vs2017-64\zetaglest\zetaglest.exe bin\vs2017\zetaglest-64.exe
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/.gitignore b/mk/windows/vs2015-32/.gitignore
index 18bbedb1a..9db351467 100644
--- a/mk/windows/vs2015-32/.gitignore
+++ b/mk/windows/vs2015-32/.gitignore
@@ -17,4 +17,6 @@
*.ipch
*.pch
*.ini
-*.obj
\ No newline at end of file
+*.obj
+*.res
+*.user
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/ZetaGlest.sln b/mk/windows/vs2015-32/ZetaGlest.sln
index 69ee11b18..552cac21f 100644
--- a/mk/windows/vs2015-32/ZetaGlest.sln
+++ b/mk/windows/vs2015-32/ZetaGlest.sln
@@ -5,13 +5,13 @@ VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libglest", "libglest.vcxproj", "{8DAA0C24-95CD-4F66-B4C5-19ABDD771746}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glest_game", "glest_game.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zetaglest", "zetaglest.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libstreflop", "libstreflop.vcxproj", "{CDF4DDB9-945E-4D0D-9F0E-2BBEB5D22141}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "g2xml", "g2xml.vcxproj", "{407355A4-D12A-4E3B-A7EB-A835E573B376}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "g3d_viewer", "g3d_viewer.vcxproj", "{FE5C7C7C-F109-44F5-8329-25A4E24F162C}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "g3dviewer", "g3dviewer.vcxproj", "{FE5C7C7C-F109-44F5-8329-25A4E24F162C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "map_editor", "map_editor.vcxproj", "{5D09BE33-81EC-450B-8A7B-2E7B941ADC56}"
EndProject
diff --git a/mk/windows/vs2015-32/g2xml.vcxproj b/mk/windows/vs2015-32/g2xml.vcxproj
index 5a0740cb7..814bab31a 100644
--- a/mk/windows/vs2015-32/g2xml.vcxproj
+++ b/mk/windows/vs2015-32/g2xml.vcxproj
@@ -61,7 +61,7 @@
Full
true
- WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
MultiThreadedDLL
true
@@ -70,8 +70,8 @@
ProgramDatabase
true
StreamingSIMDExtensions2
- AnySuitable
- Speed
+ AnySuitable
+ Speed
true
diff --git a/mk/windows/vs2015-32/g2xml.vcxproj.user b/mk/windows/vs2015-32/g2xml.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-32/g2xml.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/g3d_viewer.vcxproj.user b/mk/windows/vs2015-32/g3d_viewer.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-32/g3d_viewer.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/g3d_viewerWin32_obj/Release/g3d_viewer.res b/mk/windows/vs2015-32/g3d_viewerWin32_obj/Release/g3d_viewer.res
deleted file mode 100644
index 2e34fdc1c..000000000
Binary files a/mk/windows/vs2015-32/g3d_viewerWin32_obj/Release/g3d_viewer.res and /dev/null differ
diff --git a/mk/windows/vs2015-32/g3d_viewer.vcxproj b/mk/windows/vs2015-32/g3dviewer.vcxproj
similarity index 98%
rename from mk/windows/vs2015-32/g3d_viewer.vcxproj
rename to mk/windows/vs2015-32/g3dviewer.vcxproj
index 47ee0d364..11d86e67d 100644
--- a/mk/windows/vs2015-32/g3d_viewer.vcxproj
+++ b/mk/windows/vs2015-32/g3dviewer.vcxproj
@@ -12,9 +12,9 @@
{FE5C7C7C-F109-44F5-8329-25A4E24F162C}
- g3d_viewer
+ g3dviewer
Win32Proj
- g3d_viewer
+ g3dviewer
8.1
@@ -161,7 +161,7 @@
/arch:SSE2 %(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;%(PreprocessorDefinitions)
+ _WINDOWS;WIN32;NDEBUG;_CRT_SECURE_NO_WARNINGS;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -261,9 +261,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/glest_game.vcxproj.user b/mk/windows/vs2015-32/glest_game.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-32/glest_game.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/libglest.vcxproj.user b/mk/windows/vs2015-32/libglest.vcxproj.user
deleted file mode 100644
index 620587b76..000000000
--- a/mk/windows/vs2015-32/libglest.vcxproj.user
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
- $(SolutionDir)\..\dependencies\src\wxwidgets
- lib
- true
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/libstreflop.vcxproj.user b/mk/windows/vs2015-32/libstreflop.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-32/libstreflop.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/map_editor.vcxproj b/mk/windows/vs2015-32/map_editor.vcxproj
index 3b5b545bd..93767f093 100644
--- a/mk/windows/vs2015-32/map_editor.vcxproj
+++ b/mk/windows/vs2015-32/map_editor.vcxproj
@@ -158,7 +158,7 @@
/arch:SSE2 %(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;%(PreprocessorDefinitions)
+ _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;_CRT_SECURE_NO_WARNINGS;UNICODE;_UNICODE;GLEW_STATIC;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -250,9 +250,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2015-32/map_editor.vcxproj.user b/mk/windows/vs2015-32/map_editor.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-32/map_editor.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-32/map_editorWin32_obj/Release/glest_editor.res b/mk/windows/vs2015-32/map_editorWin32_obj/Release/glest_editor.res
deleted file mode 100644
index 2f0f86c39..000000000
Binary files a/mk/windows/vs2015-32/map_editorWin32_obj/Release/glest_editor.res and /dev/null differ
diff --git a/mk/windows/vs2015-32/glest_game.vcxproj b/mk/windows/vs2015-32/zetaglest.vcxproj
similarity index 99%
rename from mk/windows/vs2015-32/glest_game.vcxproj
rename to mk/windows/vs2015-32/zetaglest.vcxproj
index 1c5fdaae5..66544fc0f 100644
--- a/mk/windows/vs2015-32/glest_game.vcxproj
+++ b/mk/windows/vs2015-32/zetaglest.vcxproj
@@ -12,8 +12,8 @@
{6B0C65F1-D031-46AF-AC0D-7C38892D2952}
- glest_game
- glest_game
+ zetaglest
+ zetaglest
8.1
diff --git a/mk/windows/vs2015-32/zetaglestWin32_obj/Release/glest.res b/mk/windows/vs2015-32/zetaglestWin32_obj/Release/glest.res
deleted file mode 100644
index 5082ca401..000000000
Binary files a/mk/windows/vs2015-32/zetaglestWin32_obj/Release/glest.res and /dev/null differ
diff --git a/mk/windows/vs2015-64/.gitignore b/mk/windows/vs2015-64/.gitignore
index 18bbedb1a..9db351467 100644
--- a/mk/windows/vs2015-64/.gitignore
+++ b/mk/windows/vs2015-64/.gitignore
@@ -17,4 +17,6 @@
*.ipch
*.pch
*.ini
-*.obj
\ No newline at end of file
+*.obj
+*.res
+*.user
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/ZetaGlest.sln b/mk/windows/vs2015-64/ZetaGlest.sln
index 967cf1029..bd9d397a4 100644
--- a/mk/windows/vs2015-64/ZetaGlest.sln
+++ b/mk/windows/vs2015-64/ZetaGlest.sln
@@ -5,7 +5,7 @@ VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libglest", "libglest.vcxproj", "{8DAA0C24-95CD-4F66-B4C5-19ABDD771746}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glest_game", "glest_game.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zetaglest", "zetaglest.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libstreflop", "libstreflop.vcxproj", "{CDF4DDB9-945E-4D0D-9F0E-2BBEB5D22141}"
EndProject
diff --git a/mk/windows/vs2015-64/g2xml.vcxproj b/mk/windows/vs2015-64/g2xml.vcxproj
index 333c0bbf4..96b911bea 100644
--- a/mk/windows/vs2015-64/g2xml.vcxproj
+++ b/mk/windows/vs2015-64/g2xml.vcxproj
@@ -83,7 +83,7 @@
Full
true
- WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
MultiThreadedDLL
true
diff --git a/mk/windows/vs2015-64/g2xml.vcxproj.user b/mk/windows/vs2015-64/g2xml.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-64/g2xml.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/g3d_viewer.vcxproj b/mk/windows/vs2015-64/g3d_viewer.vcxproj
index 16aa6582f..ceb2325d6 100644
--- a/mk/windows/vs2015-64/g3d_viewer.vcxproj
+++ b/mk/windows/vs2015-64/g3d_viewer.vcxproj
@@ -239,7 +239,7 @@
%(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- NDEBUG;_WINDOWS;WIN32;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;%(PreprocessorDefinitions)
+ NDEBUG;_WINDOWS;WIN32;_CRT_SECURE_NO_WARNINGS;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -331,9 +331,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2015-64/g3d_viewer.vcxproj.user b/mk/windows/vs2015-64/g3d_viewer.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-64/g3d_viewer.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/g3dviewerx64_obj/Release/g3d_viewer.res b/mk/windows/vs2015-64/g3dviewerx64_obj/Release/g3d_viewer.res
deleted file mode 100644
index 2e34fdc1c..000000000
Binary files a/mk/windows/vs2015-64/g3dviewerx64_obj/Release/g3d_viewer.res and /dev/null differ
diff --git a/mk/windows/vs2015-64/glest_game.vcxproj.user b/mk/windows/vs2015-64/glest_game.vcxproj.user
deleted file mode 100644
index b5b74823e..000000000
--- a/mk/windows/vs2015-64/glest_game.vcxproj.user
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
- $(SolutionDir)$(TargetName)\
- WindowsLocalDebugger
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/libglest.vcxproj.user b/mk/windows/vs2015-64/libglest.vcxproj.user
deleted file mode 100644
index 620587b76..000000000
--- a/mk/windows/vs2015-64/libglest.vcxproj.user
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
- $(SolutionDir)\..\dependencies\src\wxwidgets
- lib
- true
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/libstreflop.vcxproj.user b/mk/windows/vs2015-64/libstreflop.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-64/libstreflop.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/map_editor.vcxproj b/mk/windows/vs2015-64/map_editor.vcxproj
index 96606b543..d419423fd 100644
--- a/mk/windows/vs2015-64/map_editor.vcxproj
+++ b/mk/windows/vs2015-64/map_editor.vcxproj
@@ -234,7 +234,7 @@
%(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;%(PreprocessorDefinitions)
+ _WINDOWS;WIN32;NDEBUG;_CRT_SECURE_NO_WARNINGS;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -324,9 +324,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2015-64/map_editor.vcxproj.user b/mk/windows/vs2015-64/map_editor.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2015-64/map_editor.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2015-64/map_editorx64_obj/Release/glest_editor.res b/mk/windows/vs2015-64/map_editorx64_obj/Release/glest_editor.res
deleted file mode 100644
index 2f0f86c39..000000000
Binary files a/mk/windows/vs2015-64/map_editorx64_obj/Release/glest_editor.res and /dev/null differ
diff --git a/mk/windows/vs2015-64/glest_game.vcxproj b/mk/windows/vs2015-64/zetaglest.vcxproj
similarity index 99%
rename from mk/windows/vs2015-64/glest_game.vcxproj
rename to mk/windows/vs2015-64/zetaglest.vcxproj
index 640437a2a..ea0a216b1 100644
--- a/mk/windows/vs2015-64/glest_game.vcxproj
+++ b/mk/windows/vs2015-64/zetaglest.vcxproj
@@ -12,8 +12,8 @@
{6B0C65F1-D031-46AF-AC0D-7C38892D2952}
- glest_game
- glest_game
+ zetaglest
+ zetaglest
8.1
diff --git a/mk/windows/vs2015-64/zetaglestx64_obj/Release/glest.res b/mk/windows/vs2015-64/zetaglestx64_obj/Release/glest.res
deleted file mode 100644
index 5082ca401..000000000
Binary files a/mk/windows/vs2015-64/zetaglestx64_obj/Release/glest.res and /dev/null differ
diff --git a/mk/windows/vs2017-32/.gitignore b/mk/windows/vs2017-32/.gitignore
index 18bbedb1a..9db351467 100644
--- a/mk/windows/vs2017-32/.gitignore
+++ b/mk/windows/vs2017-32/.gitignore
@@ -17,4 +17,6 @@
*.ipch
*.pch
*.ini
-*.obj
\ No newline at end of file
+*.obj
+*.res
+*.user
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/ZetaGlest.sln b/mk/windows/vs2017-32/ZetaGlest.sln
index 3c6551019..8b216b401 100644
--- a/mk/windows/vs2017-32/ZetaGlest.sln
+++ b/mk/windows/vs2017-32/ZetaGlest.sln
@@ -5,13 +5,13 @@ VisualStudioVersion = 15.0.27130.2036
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libglest", "libglest.vcxproj", "{8DAA0C24-95CD-4F66-B4C5-19ABDD771746}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glest_game", "glest_game.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zetaglest", "zetaglest.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libstreflop", "libstreflop.vcxproj", "{CDF4DDB9-945E-4D0D-9F0E-2BBEB5D22141}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "g2xml", "g2xml.vcxproj", "{407355A4-D12A-4E3B-A7EB-A835E573B376}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "g3d_viewer", "g3d_viewer.vcxproj", "{FE5C7C7C-F109-44F5-8329-25A4E24F162C}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "g3dviewer", "g3dviewer.vcxproj", "{FE5C7C7C-F109-44F5-8329-25A4E24F162C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "map_editor", "map_editor.vcxproj", "{5D09BE33-81EC-450B-8A7B-2E7B941ADC56}"
EndProject
diff --git a/mk/windows/vs2017-32/g2xml.vcxproj b/mk/windows/vs2017-32/g2xml.vcxproj
index c6b2b7782..142052261 100644
--- a/mk/windows/vs2017-32/g2xml.vcxproj
+++ b/mk/windows/vs2017-32/g2xml.vcxproj
@@ -61,7 +61,7 @@
Full
true
- WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
MultiThreadedDLL
true
diff --git a/mk/windows/vs2017-32/g2xml.vcxproj.user b/mk/windows/vs2017-32/g2xml.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-32/g2xml.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/g3d_viewer.vcxproj.user b/mk/windows/vs2017-32/g3d_viewer.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-32/g3d_viewer.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/g3d_viewerWin32_obj/Release/g3d_viewer.res b/mk/windows/vs2017-32/g3d_viewerWin32_obj/Release/g3d_viewer.res
deleted file mode 100644
index 2e34fdc1c..000000000
Binary files a/mk/windows/vs2017-32/g3d_viewerWin32_obj/Release/g3d_viewer.res and /dev/null differ
diff --git a/mk/windows/vs2017-32/g3d_viewer.vcxproj b/mk/windows/vs2017-32/g3dviewer.vcxproj
similarity index 98%
rename from mk/windows/vs2017-32/g3d_viewer.vcxproj
rename to mk/windows/vs2017-32/g3dviewer.vcxproj
index 8b8f17488..eaea90ea8 100644
--- a/mk/windows/vs2017-32/g3d_viewer.vcxproj
+++ b/mk/windows/vs2017-32/g3dviewer.vcxproj
@@ -12,9 +12,9 @@
{FE5C7C7C-F109-44F5-8329-25A4E24F162C}
- g3d_viewer
+ g3dviewer
Win32Proj
- g3d_viewer
+ g3dviewer
8.1
@@ -161,7 +161,7 @@
/arch:SSE2 %(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;%(PreprocessorDefinitions)
+ _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -256,9 +256,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2017-32/glest_game.vcxproj.user b/mk/windows/vs2017-32/glest_game.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-32/glest_game.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/libglest.vcxproj.user b/mk/windows/vs2017-32/libglest.vcxproj.user
deleted file mode 100644
index 620587b76..000000000
--- a/mk/windows/vs2017-32/libglest.vcxproj.user
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
- $(SolutionDir)\..\dependencies\src\wxwidgets
- lib
- true
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/libstreflop.vcxproj.user b/mk/windows/vs2017-32/libstreflop.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-32/libstreflop.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/map_editor.vcxproj b/mk/windows/vs2017-32/map_editor.vcxproj
index d35ced090..baa298d14 100644
--- a/mk/windows/vs2017-32/map_editor.vcxproj
+++ b/mk/windows/vs2017-32/map_editor.vcxproj
@@ -158,7 +158,7 @@
/arch:SSE2 %(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;%(PreprocessorDefinitions)
+ _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -250,9 +250,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2017-32/map_editor.vcxproj.user b/mk/windows/vs2017-32/map_editor.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-32/map_editor.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-32/map_editorWin32_obj/Release/glest_editor.res b/mk/windows/vs2017-32/map_editorWin32_obj/Release/glest_editor.res
deleted file mode 100644
index 2f0f86c39..000000000
Binary files a/mk/windows/vs2017-32/map_editorWin32_obj/Release/glest_editor.res and /dev/null differ
diff --git a/mk/windows/vs2017-32/glest_game.vcxproj b/mk/windows/vs2017-32/zetaglest.vcxproj
similarity index 99%
rename from mk/windows/vs2017-32/glest_game.vcxproj
rename to mk/windows/vs2017-32/zetaglest.vcxproj
index a53a961fc..fcc027c6c 100644
--- a/mk/windows/vs2017-32/glest_game.vcxproj
+++ b/mk/windows/vs2017-32/zetaglest.vcxproj
@@ -12,8 +12,8 @@
{6B0C65F1-D031-46AF-AC0D-7C38892D2952}
- glest_game
- glest_game
+ zetaglest
+ zetaglest
8.1
diff --git a/mk/windows/vs2017-32/zetaglestWin32_obj/Release/glest.res b/mk/windows/vs2017-32/zetaglestWin32_obj/Release/glest.res
deleted file mode 100644
index 5082ca401..000000000
Binary files a/mk/windows/vs2017-32/zetaglestWin32_obj/Release/glest.res and /dev/null differ
diff --git a/mk/windows/vs2017-64/.gitignore b/mk/windows/vs2017-64/.gitignore
index 18bbedb1a..9db351467 100644
--- a/mk/windows/vs2017-64/.gitignore
+++ b/mk/windows/vs2017-64/.gitignore
@@ -17,4 +17,6 @@
*.ipch
*.pch
*.ini
-*.obj
\ No newline at end of file
+*.obj
+*.res
+*.user
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/ZetaGlest.sln b/mk/windows/vs2017-64/ZetaGlest.sln
index 0b4752b65..d48e560c2 100644
--- a/mk/windows/vs2017-64/ZetaGlest.sln
+++ b/mk/windows/vs2017-64/ZetaGlest.sln
@@ -5,7 +5,7 @@ VisualStudioVersion = 15.0.27130.2036
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libglest", "libglest.vcxproj", "{8DAA0C24-95CD-4F66-B4C5-19ABDD771746}"
EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glest_game", "glest_game.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zetaglest", "zetaglest.vcxproj", "{6B0C65F1-D031-46AF-AC0D-7C38892D2952}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libstreflop", "libstreflop.vcxproj", "{CDF4DDB9-945E-4D0D-9F0E-2BBEB5D22141}"
EndProject
diff --git a/mk/windows/vs2017-64/g2xml.vcxproj b/mk/windows/vs2017-64/g2xml.vcxproj
index ac32583a6..6bb7a5f1a 100644
--- a/mk/windows/vs2017-64/g2xml.vcxproj
+++ b/mk/windows/vs2017-64/g2xml.vcxproj
@@ -83,7 +83,7 @@
Full
true
- WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)
+ WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
MultiThreadedDLL
true
diff --git a/mk/windows/vs2017-64/g2xml.vcxproj.user b/mk/windows/vs2017-64/g2xml.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-64/g2xml.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/g3d_viewer.vcxproj b/mk/windows/vs2017-64/g3d_viewer.vcxproj
index a3d08020a..b57702cea 100644
--- a/mk/windows/vs2017-64/g3d_viewer.vcxproj
+++ b/mk/windows/vs2017-64/g3d_viewer.vcxproj
@@ -239,7 +239,7 @@
%(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- NDEBUG;_WINDOWS;WIN32;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;%(PreprocessorDefinitions)
+ NDEBUG;_WINDOWS;WIN32;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -331,9 +331,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2017-64/g3d_viewer.vcxproj.user b/mk/windows/vs2017-64/g3d_viewer.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-64/g3d_viewer.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/g3dviewerx64_obj/Release/g3d_viewer.res b/mk/windows/vs2017-64/g3dviewerx64_obj/Release/g3d_viewer.res
deleted file mode 100644
index 2e34fdc1c..000000000
Binary files a/mk/windows/vs2017-64/g3dviewerx64_obj/Release/g3d_viewer.res and /dev/null differ
diff --git a/mk/windows/vs2017-64/glest_game.vcxproj.user b/mk/windows/vs2017-64/glest_game.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-64/glest_game.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/libglest.vcxproj.user b/mk/windows/vs2017-64/libglest.vcxproj.user
deleted file mode 100644
index 620587b76..000000000
--- a/mk/windows/vs2017-64/libglest.vcxproj.user
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
- $(SolutionDir)\..\dependencies\src\wxwidgets
- lib
- true
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/libstreflop.vcxproj.user b/mk/windows/vs2017-64/libstreflop.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-64/libstreflop.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/map_editor.vcxproj b/mk/windows/vs2017-64/map_editor.vcxproj
index 7ee8abb21..f3b2271a8 100644
--- a/mk/windows/vs2017-64/map_editor.vcxproj
+++ b/mk/windows/vs2017-64/map_editor.vcxproj
@@ -234,7 +234,7 @@
%(AdditionalOptions)
..\dependencies\src\wxwidgets\include;..\..\..\source\shared_lib\include\util;..\..\..\source\shared_lib\include\graphics\gl;..\..\..\source\shared_lib\include\graphics;../dependencies/src/wxwidgets/include;..\..\..\source\shared_lib\include\platform\sdl;../../../source/shared_lib/include/platform/common;..\dependencies\src\sdl2\include;../dependencies/src/curl/include;..\..\..\source\glest_game\graphics;..\..\..\source\shared_lib\include\xml;../dependencies/src/xerces/src;..\..\..\source\glest_game\global;..\..\..\source\glest_game\sound;..\..\..\source\shared_lib\include\sound;..\..\..\source\glest_game\game;../../../source/shared_lib/include/map;../dependencies/src/png;..\..\..\source\glest_game\facilities;../dependencies/src/glew/include;..\..\..\source\shared_lib\include\xml\rapidxml;../../../source/shared_lib/include/platform/win32;..\dependencies\src\wxwidgets\lib\vc_lib\mswu;%(AdditionalIncludeDirectories)
- _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;%(PreprocessorDefinitions)
+ _WINDOWS;WIN32;NDEBUG;CURL_STATICLIB;UNICODE;_UNICODE;GLEW_STATIC;ZLIB_WINAPI;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
true
Async
MultiThreadedDLL
@@ -324,9 +324,9 @@
-
- PreserveNewest
-
+
+ PreserveNewest
+
diff --git a/mk/windows/vs2017-64/map_editor.vcxproj.user b/mk/windows/vs2017-64/map_editor.vcxproj.user
deleted file mode 100644
index abe8dd896..000000000
--- a/mk/windows/vs2017-64/map_editor.vcxproj.user
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/mk/windows/vs2017-64/map_editorx64_obj/Release/glest_editor.res b/mk/windows/vs2017-64/map_editorx64_obj/Release/glest_editor.res
deleted file mode 100644
index 2f0f86c39..000000000
Binary files a/mk/windows/vs2017-64/map_editorx64_obj/Release/glest_editor.res and /dev/null differ
diff --git a/mk/windows/vs2017-64/glest_game.vcxproj b/mk/windows/vs2017-64/zetaglest.vcxproj
similarity index 99%
rename from mk/windows/vs2017-64/glest_game.vcxproj
rename to mk/windows/vs2017-64/zetaglest.vcxproj
index 8724fe2fe..1e3e97557 100644
--- a/mk/windows/vs2017-64/glest_game.vcxproj
+++ b/mk/windows/vs2017-64/zetaglest.vcxproj
@@ -12,8 +12,8 @@
{6B0C65F1-D031-46AF-AC0D-7C38892D2952}
- glest_game
- glest_game
+ zetaglest
+ zetaglest
8.1
diff --git a/mk/windows/vs2017-64/zetaglestx64_obj/Release/glest.res b/mk/windows/vs2017-64/zetaglestx64_obj/Release/glest.res
deleted file mode 100644
index 5082ca401..000000000
Binary files a/mk/windows/vs2017-64/zetaglestx64_obj/Release/glest.res and /dev/null differ
diff --git a/rss_23x23.jpeg b/rss_23x23.jpeg
new file mode 100644
index 000000000..a496a9184
Binary files /dev/null and b/rss_23x23.jpeg differ
diff --git a/source/g3d_viewer/CMakeLists.txt b/source/g3d_viewer/CMakeLists.txt
index affc4be86..6126d20f0 100644
--- a/source/g3d_viewer/CMakeLists.txt
+++ b/source/g3d_viewer/CMakeLists.txt
@@ -4,7 +4,7 @@ SET(EXTERNAL_LIBS "")
SET(TARGET_NAME "zetaglest_g3dviewer")
SET(TARGET_NAME_MANPAGE "${TARGET_NAME}.6")
-IF(BUILD_MEGAGLEST_MODEL_VIEWER)
+IF(BUILD_ZETAGLEST_MODEL_VIEWER)
MESSAGE(STATUS "Will try to build ZetaGlest model viewer")
IF(UNIX AND "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
@@ -187,7 +187,7 @@ IF(BUILD_MEGAGLEST_MODEL_VIEWER)
ENDFOREACH(DIR)
IF(WANT_DEV_OUTPATH)
- SET(EXECUTABLE_OUTPUT_PATH "${MEGAGLEST_FRIENDLY_OUTPUT_PATH}")
+ SET(EXECUTABLE_OUTPUT_PATH "${ZETAGLEST_FRIENDLY_OUTPUT_PATH}")
ENDIF()
SET(HELP2MAN_OUT_PATH ${EXECUTABLE_OUTPUT_PATH})
@@ -234,20 +234,20 @@ IF(BUILD_MEGAGLEST_MODEL_VIEWER)
# Installation of the program
INSTALL(TARGETS
${TARGET_NAME}
- DESTINATION ${MEGAGLEST_BIN_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_BIN_INSTALL_PATH})
- IF(EXISTS ${HELP2MAN} AND NOT "${MEGAGLEST_MANPAGE_INSTALL_PATH}" STREQUAL "" AND NOT APPLE)
- MESSAGE(STATUS "**NOTE: Will Install manpage [${TARGET_NAME_MANPAGE}] to [${MEGAGLEST_MANPAGE_INSTALL_PATH}]")
+ IF(EXISTS ${HELP2MAN} AND NOT "${ZETAGLEST_MANPAGE_INSTALL_PATH}" STREQUAL "" AND NOT APPLE)
+ MESSAGE(STATUS "**NOTE: Will Install manpage [${TARGET_NAME_MANPAGE}] to [${ZETAGLEST_MANPAGE_INSTALL_PATH}]")
# Installation of the program manpage file
INSTALL(FILES
"${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE}"
- DESTINATION ${MEGAGLEST_MANPAGE_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_MANPAGE_INSTALL_PATH})
ENDIF()
# Installation of the program config and image files
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/shared/g3dviewer.ico"
- DESTINATION ${MEGAGLEST_INI_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_INI_INSTALL_PATH})
ENDIF()
ENDIF()
diff --git a/source/g3d_viewer/main.cpp b/source/g3d_viewer/main.cpp
index eccbfaabe..ebd52ce1b 100644
--- a/source/g3d_viewer/main.cpp
+++ b/source/g3d_viewer/main.cpp
@@ -43,15 +43,15 @@
#endif
#ifndef WIN32
- #define stricmp strcasecmp
- #define strnicmp strncasecmp
- #define _strnicmp strncasecmp
+#define stricmp strcasecmp
+#define strnicmp strncasecmp
+#define _strnicmp strncasecmp
#endif
#if wxCHECK_VERSION(2, 9, 1)
- #define WX2CHR(x) (x.mb_str())
+#define WX2CHR(x) (x.mb_str())
#else
- #define WX2CHR(x) (wxConvCurrent->cWX2MB(x))
+#define WX2CHR(x) (wxConvCurrent->cWX2MB(x))
#endif
using namespace Shared::Platform;
@@ -73,395 +73,398 @@ const char *folderDelimiter = "/";
//int GameConstants::updateFps= 40;
//int GameConstants::cameraFps= 100;
-const string g3dviewerVersionString= "v0.8.01";
+const string g3dviewerVersionString = "v0.8.01";
// Because g3d should always support alpha transparency
string fileFormat = "png";
-namespace Glest { namespace Game {
+namespace Glest {
+ namespace Game {
-string getGameReadWritePath(const string &lookupKey) {
- string path = "";
- if(path == "" && getenv("GLESTHOME") != NULL) {
- path = safeCharPtrCopy(getenv("GLESTHOME"),8096);
- if(path != "" && EndsWith(path, "/") == false && EndsWith(path, "\\") == false) {
- path += "/";
- }
+ string getGameReadWritePath(const string &lookupKey) {
+ string path = "";
+ if (path == "" && getenv("GLESTHOME") != NULL) {
+ path = safeCharPtrCopy(getenv("GLESTHOME"), 8096);
+ if (path != "" && EndsWith(path, "/") == false && EndsWith(path, "\\") == false) {
+ path += "/";
+ }
- //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path to be used for read/write files [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str());
- }
-
- return path;
-}
-}}
-
-namespace Shared{ namespace G3dViewer{
-
-// ===============================================
-// class Global functions
-// ===============================================
-
-wxString ToUnicode(const char* str) {
- return wxString(str, wxConvUTF8);
-}
-
-wxString ToUnicode(const string& str) {
- return wxString(str.c_str(), wxConvUTF8);
-}
-
-const wxChar *GAME_ARGS[] = {
- wxT("--help"),
- wxT("--auto-screenshot"),
- wxT("--load-unit"),
- wxT("--load-model"),
- wxT("--load-model-animation-value"),
- wxT("--load-particle"),
- wxT("--load-projectile-particle"),
- wxT("--load-splash-particle"),
- wxT("--load-particle-loop-value"),
- wxT("--zoom-value"),
- wxT("--rotate-x-value"),
- wxT("--rotate-y-value"),
- wxT("--screenshot-format"),
- wxT("--verbose"),
-};
-
-enum GAME_ARG_TYPE {
- GAME_ARG_HELP = 0,
- GAME_ARG_AUTO_SCREENSHOT,
- GAME_ARG_LOAD_UNIT,
- GAME_ARG_LOAD_MODEL,
- GAME_ARG_LOAD_MODEL_ANIMATION_VALUE,
- GAME_ARG_LOAD_PARTICLE,
- GAME_ARG_LOAD_PARTICLE_PROJECTILE,
- GAME_ARG_LOAD_PARTICLE_SPLASH,
- GAME_ARG_LOAD_PARTICLE_LOOP_VALUE,
- GAME_ARG_ZOOM_VALUE,
- GAME_ARG_ROTATE_X_VALUE,
- GAME_ARG_ROTATE_Y_VALUE,
- GAME_ARG_SCREENSHOT_FORMAT,
- GAME_ARG_VERBOSE,
-};
-
-bool hasCommandArgument(int argc, wxChar** argv,const string &argName,
- int *foundIndex=NULL, int startLookupIndex=1,
- bool useArgParamLen=false) {
- bool result = false;
-
- if(foundIndex != NULL) {
- *foundIndex = -1;
- }
- size_t compareLen = strlen(argName.c_str());
-
- for(int idx = startLookupIndex; idx < argc; idx++) {
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]);
- //printf("tmp_buf [%s]\n",(const char *)tmp_buf);
- if(useArgParamLen == true) {
- compareLen = strlen(tmp_buf);
- }
- if(_strnicmp(argName.c_str(),tmp_buf,compareLen) == 0) {
- result = true;
- if(foundIndex != NULL) {
- *foundIndex = idx;
+ //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] path to be used for read/write files [%s]\n",__FILE__,__FUNCTION__,__LINE__,path.c_str());
}
- break;
+ return path;
}
}
- return result;
}
-void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
- if(foundInvalidArgs == true) {
- printf("\n");
- }
+namespace Shared {
+ namespace G3dViewer {
- // "================================================================================"
- printf("\n%s %s, [Using %s]\n",extractFileFromDirectoryPath(argv0).c_str(),g3dviewerVersionString.c_str(),(const char *)wxConvCurrent->cWX2MB(wxVERSION_STRING));
+ // ===============================================
+ // class Global functions
+ // ===============================================
- printf("\nDisplays glest 3D-models and unit/projectile/splash particle systems.\n");
- printf("\nRotate with left mouse button. Zoom with right mouse button or mousewheel.");
- printf("\nUse ctrl to load more than one particle system.");
- printf("\nPress R to restart particles, this also reloads all files if they are changed.");
+ wxString ToUnicode(const char* str) {
+ return wxString(str, wxConvUTF8);
+ }
- //printf("\n\noptionally you may use any of the following:\n");
- printf("\n\n%s [G3D FILE], usage",extractFileFromDirectoryPath(argv0).c_str());
- printf("\n\nCommandline Parameter: Description:");
- printf("\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
- printf("\n\n%s \t\tDisplays this help text.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP]));
+ wxString ToUnicode(const string& str) {
+ return wxString(str.c_str(), wxConvUTF8);
+ }
- // "================================================================================"
- printf("\n\n%s=x \t\tAuto load the unit / skill information specified",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]));
- printf("\n\n \tin path/filename x.");
- printf("\n\n \tWhere x is a g3d filename to load separated with a");
- printf("\n\n \tcomma and one or more skill names to try loading.");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=techs/megapack/factions/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]));
- printf("\n\n \ttech/units/battle_machine,attack_skill,stop_skill");
+ const wxChar *GAME_ARGS[] = {
+ wxT("--help"),
+ wxT("--auto-screenshot"),
+ wxT("--load-unit"),
+ wxT("--load-model"),
+ wxT("--load-model-animation-value"),
+ wxT("--load-particle"),
+ wxT("--load-projectile-particle"),
+ wxT("--load-splash-particle"),
+ wxT("--load-particle-loop-value"),
+ wxT("--zoom-value"),
+ wxT("--rotate-x-value"),
+ wxT("--rotate-y-value"),
+ wxT("--screenshot-format"),
+ wxT("--verbose"),
+ };
- printf("\n\n%s=x \tAuto load the model specified in path/filename x.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]));
- printf("\n\n \tWhere x is a g3d filename to load.");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=techs/megapack/factions/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]));
- printf("\n\n \ttech/units/battle_machine/models/battle_machine_dying.g3d");
+ enum GAME_ARG_TYPE {
+ GAME_ARG_HELP = 0,
+ GAME_ARG_AUTO_SCREENSHOT,
+ GAME_ARG_LOAD_UNIT,
+ GAME_ARG_LOAD_MODEL,
+ GAME_ARG_LOAD_MODEL_ANIMATION_VALUE,
+ GAME_ARG_LOAD_PARTICLE,
+ GAME_ARG_LOAD_PARTICLE_PROJECTILE,
+ GAME_ARG_LOAD_PARTICLE_SPLASH,
+ GAME_ARG_LOAD_PARTICLE_LOOP_VALUE,
+ GAME_ARG_ZOOM_VALUE,
+ GAME_ARG_ROTATE_X_VALUE,
+ GAME_ARG_ROTATE_Y_VALUE,
+ GAME_ARG_SCREENSHOT_FORMAT,
+ GAME_ARG_VERBOSE,
+ };
- printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]));
- printf("\n\n \tAnimation value when loading a model.");
- printf("\n\n \tWhere x is a decimal value from -1.0 to 1.0");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=0.5",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]));
+ bool hasCommandArgument(int argc, wxChar** argv, const string &argName,
+ int *foundIndex = NULL, int startLookupIndex = 1,
+ bool useArgParamLen = false) {
+ bool result = false;
- // "================================================================================"
- printf("\n\n%s=x \tAutomatically takes a screenshot of the items you",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]));
- printf("\n\n \tare loading.");
- printf("\n\n \tWhere x is a comma-delimited list of one or more");
- printf("\n\n \t of the optional settings:");
- printf("\n\n \t transparent, enable_grid, enable_wireframe,");
- printf("\n\n \t enable_normals, disable_grid, disable_wireframe,");
- printf("\n\n \t disable_normals, saveas-, resize-wxh");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=transparent,",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]));
- printf("\n\n \tdisable_grid,saveas-test.png,resize-800x600");
- printf("\n\n \t%s=techs/megapack/factions/tech/units/",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]));
- printf("\n\n \tbattle_machine/models/battle_machine_dying.g3d");
+ if (foundIndex != NULL) {
+ *foundIndex = -1;
+ }
+ size_t compareLen = strlen(argName.c_str());
- // "================================================================================"
- printf("\n\n%s=x \tAuto load the particle specified in path/filename x.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]));
- printf("\n\n \tWhere x is a Particle XML filename to load.");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=techs/megapack/factions/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]));
- printf("\n\n \tpersian/units/genie/glow_particles.xml");
+ for (int idx = startLookupIndex; idx < argc; idx++) {
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]);
+ //printf("tmp_buf [%s]\n",(const char *)tmp_buf);
+ if (useArgParamLen == true) {
+ compareLen = strlen(tmp_buf);
+ }
+ if (_strnicmp(argName.c_str(), tmp_buf, compareLen) == 0) {
+ result = true;
+ if (foundIndex != NULL) {
+ *foundIndex = idx;
+ }
- printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]));
- printf("\n\n \tAuto load the projectile particle specified in");
- printf("\n\n \tpath/filename x.");
- printf("\n\n \tWhere x is a Projectile Particle Definition XML");
- printf("\n\n \t filename to load.");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=techs/megapack/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]));
- printf("\n\n \tfactions/persian/units/genie/particle_proj.xml");
+ break;
+ }
+ }
+ return result;
+ }
- printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]));
- printf("\n\n \tAuto load the splash particle specified in");
- printf("\n\n \tpath/filename x.");
- printf("\n\n \tWhere x is a Splash Particle Definition XML");
- printf("\n\n \t filename to load.");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=techs/megapack/",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]));
- printf("\n\n \tfactions/persian/units/genie/particle_splash.xml");
+ void printParameterHelp(const char *argv0, bool foundInvalidArgs) {
+ if (foundInvalidArgs == true) {
+ printf("\n");
+ }
- printf("\n\n%s=x ",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]));
- printf("\n\n \tParticle loop value when loading one or more");
- printf("\n\n \tparticles.");
- printf("\n\n \tWhere x is an integer value from 1 to particle count.");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=25",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]));
+ // "================================================================================"
+ printf("\n%s %s, [Using %s]\n", extractFileFromDirectoryPath(argv0).c_str(), g3dviewerVersionString.c_str(), (const char *) wxConvCurrent->cWX2MB(wxVERSION_STRING));
- printf("\n\n%s=x \tZoom value when loading a model.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]));
- printf("\n\n \tWhere x is a decimal value from 0.1 to 10.0");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=4.2",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]));
+ printf("\nDisplays glest 3D-models and unit/projectile/splash particle systems.\n");
+ printf("\nRotate with left mouse button. Zoom with right mouse button or mousewheel.");
+ printf("\nUse ctrl to load more than one particle system.");
+ printf("\nPress R to restart particles, this also reloads all files if they are changed.");
- printf("\n\n%s=x \tX Coordinate Rotation value when loading a model.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]));
- printf("\n\n \tWhere x is a decimal value from -10.0 to 10.0");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=2.2",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]));
+ //printf("\n\noptionally you may use any of the following:\n");
+ printf("\n\n%s [G3D FILE], usage", extractFileFromDirectoryPath(argv0).c_str());
+ printf("\n\nCommandline Parameter: Description:");
+ printf("\n\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
+ printf("\n\n%s \t\tDisplays this help text.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP]));
- printf("\n\n%s=x \tY Coordinate Rotation value when loading a model.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]));
- printf("\n\n \tWhere x is a decimal value from -10.0 to 10.0");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=2.2",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]));
+ // "================================================================================"
+ printf("\n\n%s=x \t\tAuto load the unit / skill information specified", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]));
+ printf("\n\n \tin path/filename x.");
+ printf("\n\n \tWhere x is a g3d filename to load separated with a");
+ printf("\n\n \tcomma and one or more skill names to try loading.");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=techs/megapack/factions/", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]));
+ printf("\n\n \ttech/units/battle_machine,attack_skill,stop_skill");
- printf("\n\n%s=x \tSpecify which image format to use for screenshots.",(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]));
- printf("\n\n \tWhere x is one of the following supported formats:");
- printf("\n\n \t png,jpg,tga,bmp");
- printf("\n\n \t*NOTE: png is the default (and supports transparency)");
- printf("\n\n \texample:");
- printf("\n\n \t%s %s=jpg",extractFileFromDirectoryPath(argv0).c_str(),(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]));
+ printf("\n\n%s=x \tAuto load the model specified in path/filename x.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]));
+ printf("\n\n \tWhere x is a g3d filename to load.");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=techs/megapack/factions/", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]));
+ printf("\n\n \ttech/units/battle_machine/models/battle_machine_dying.g3d");
- printf("\n\n");
-}
+ printf("\n\n%s=x ", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]));
+ printf("\n\n \tAnimation value when loading a model.");
+ printf("\n\n \tWhere x is a decimal value from -1.0 to 1.0");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=0.5", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]));
-bool autoScreenShotAndExit = false;
-vector autoScreenShotParams;
-std::pair overrideSize(0,0);
+ // "================================================================================"
+ printf("\n\n%s=x \tAutomatically takes a screenshot of the items you", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]));
+ printf("\n\n \tare loading.");
+ printf("\n\n \tWhere x is a comma-delimited list of one or more");
+ printf("\n\n \t of the optional settings:");
+ printf("\n\n \t transparent, enable_grid, enable_wireframe,");
+ printf("\n\n \t enable_normals, disable_grid, disable_wireframe,");
+ printf("\n\n \t disable_normals, saveas-, resize-wxh");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=transparent,", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]));
+ printf("\n\n \tdisable_grid,saveas-test.png,resize-800x600");
+ printf("\n\n \t%s=techs/megapack/factions/tech/units/", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]));
+ printf("\n\n \tbattle_machine/models/battle_machine_dying.g3d");
-// ===============================================
-// class MainWindow
-// ===============================================
+ // "================================================================================"
+ printf("\n\n%s=x \tAuto load the particle specified in path/filename x.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]));
+ printf("\n\n \tWhere x is a Particle XML filename to load.");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=techs/megapack/factions/", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]));
+ printf("\n\n \tpersian/units/genie/glow_particles.xml");
-const string MainWindow::winHeader= "G3D viewer " + g3dviewerVersionString;
+ printf("\n\n%s=x ", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]));
+ printf("\n\n \tAuto load the projectile particle specified in");
+ printf("\n\n \tpath/filename x.");
+ printf("\n\n \tWhere x is a Projectile Particle Definition XML");
+ printf("\n\n \t filename to load.");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=techs/megapack/", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]));
+ printf("\n\n \tfactions/persian/units/genie/particle_proj.xml");
-const float defaultspeed = 0.025f;
+ printf("\n\n%s=x ", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]));
+ printf("\n\n \tAuto load the splash particle specified in");
+ printf("\n\n \tpath/filename x.");
+ printf("\n\n \tWhere x is a Splash Particle Definition XML");
+ printf("\n\n \t filename to load.");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=techs/megapack/", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]));
+ printf("\n\n \tfactions/persian/units/genie/particle_splash.xml");
-MainWindow::MainWindow( std::pair > unitToLoad,
- const string modelPath,
- const string particlePath,
- const string projectileParticlePath,
- const string splashParticlePath,
- float defaultAnimation,
- int defaultParticleLoopStart,
- float defaultZoom,float defaultXRot, float defaultYRot,
- string appPath)
- : wxFrame(NULL, -1, ToUnicode(winHeader),
- wxPoint(Renderer::windowX, Renderer::windowY),
- wxSize(Renderer::windowW, Renderer::windowH)),
- glCanvas(NULL),
- renderer(NULL),
- timer(NULL),
- menu(NULL),
- fileDialog(NULL),
- colorPicker(NULL),
- model(NULL),
- initTextureManager(true),
- startupSettingsInited(false)
+ printf("\n\n%s=x ", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]));
+ printf("\n\n \tParticle loop value when loading one or more");
+ printf("\n\n \tparticles.");
+ printf("\n\n \tWhere x is an integer value from 1 to particle count.");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=25", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]));
-{
- this->appPath = appPath;
- Properties::setApplicationPath(executable_path(appPath));
+ printf("\n\n%s=x \tZoom value when loading a model.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]));
+ printf("\n\n \tWhere x is a decimal value from 0.1 to 10.0");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=4.2", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]));
- lastanim = 0;
- model= NULL;
+ printf("\n\n%s=x \tX Coordinate Rotation value when loading a model.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]));
+ printf("\n\n \tWhere x is a decimal value from -10.0 to 10.0");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=2.2", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]));
- Config &config = Config::getInstance();
+ printf("\n\n%s=x \tY Coordinate Rotation value when loading a model.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]));
+ printf("\n\n \tWhere x is a decimal value from -10.0 to 10.0");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=2.2", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]));
- isControlKeyPressed = false;
+ printf("\n\n%s=x \tSpecify which image format to use for screenshots.", (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]));
+ printf("\n\n \tWhere x is one of the following supported formats:");
+ printf("\n\n \t png,jpg,tga,bmp");
+ printf("\n\n \t*NOTE: png is the default (and supports transparency)");
+ printf("\n\n \texample:");
+ printf("\n\n \t%s %s=jpg", extractFileFromDirectoryPath(argv0).c_str(), (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]));
- initGlCanvas();
+ printf("\n\n");
+ }
+
+ bool autoScreenShotAndExit = false;
+ vector autoScreenShotParams;
+ std::pair overrideSize(0, 0);
+
+ // ===============================================
+ // class MainWindow
+ // ===============================================
+
+ const string MainWindow::winHeader = "G3D viewer " + g3dviewerVersionString;
+
+ const float defaultspeed = 0.025f;
+
+ MainWindow::MainWindow(std::pair > unitToLoad,
+ const string modelPath,
+ const string particlePath,
+ const string projectileParticlePath,
+ const string splashParticlePath,
+ float defaultAnimation,
+ int defaultParticleLoopStart,
+ float defaultZoom, float defaultXRot, float defaultYRot,
+ string appPath)
+ : wxFrame(NULL, -1, ToUnicode(winHeader),
+ wxPoint(Renderer::windowX, Renderer::windowY),
+ wxSize(Renderer::windowW, Renderer::windowH)),
+ glCanvas(NULL),
+ renderer(NULL),
+ timer(NULL),
+ menu(NULL),
+ fileDialog(NULL),
+ colorPicker(NULL),
+ model(NULL),
+ initTextureManager(true),
+ startupSettingsInited(false)
+
+ {
+ this->appPath = appPath;
+ Properties::setApplicationPath(executable_path(appPath));
+
+ lastanim = 0;
+ model = NULL;
+
+ Config &config = Config::getInstance();
+
+ isControlKeyPressed = false;
+
+ initGlCanvas();
#if wxCHECK_VERSION(2, 9, 1)
#else
- glCanvas->SetCurrent();
+ glCanvas->SetCurrent();
#endif
- unitPath = unitToLoad;
+ unitPath = unitToLoad;
- if(modelPath != "") {
- this->modelPathList.push_back(modelPath);
- printf("Startup Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n",modelPath.c_str(),this->modelPathList.size());
- }
- if(particlePath != "") {
- this->particlePathList.push_back(particlePath);
- }
- if(projectileParticlePath != "") {
- this->particleProjectilePathList.push_back(projectileParticlePath);
- }
- if(splashParticlePath != "") {
- this->particleSplashPathList.push_back(splashParticlePath);
- }
+ if (modelPath != "") {
+ this->modelPathList.push_back(modelPath);
+ printf("Startup Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n", modelPath.c_str(), this->modelPathList.size());
+ }
+ if (particlePath != "") {
+ this->particlePathList.push_back(particlePath);
+ }
+ if (projectileParticlePath != "") {
+ this->particleProjectilePathList.push_back(projectileParticlePath);
+ }
+ if (splashParticlePath != "") {
+ this->particleSplashPathList.push_back(splashParticlePath);
+ }
- resetAnimation = false;
- anim = defaultAnimation;
- particleLoopStart = defaultParticleLoopStart;
- resetAnim = anim;
- resetParticleLoopStart = particleLoopStart;
- rotX= defaultXRot;
- rotY= defaultYRot;
- zoom= defaultZoom;
- playerColor= Renderer::pcRed;
+ resetAnimation = false;
+ anim = defaultAnimation;
+ particleLoopStart = defaultParticleLoopStart;
+ resetAnim = anim;
+ resetParticleLoopStart = particleLoopStart;
+ rotX = defaultXRot;
+ rotY = defaultYRot;
+ zoom = defaultZoom;
+ playerColor = Renderer::pcRed;
- speed= defaultspeed;
+ speed = defaultspeed;
- //getGlPlatformExtensions();
- menu= new wxMenuBar();
+ //getGlPlatformExtensions();
+ menu = new wxMenuBar();
- //menu
- menuFile= new wxMenu();
- menuFile->Append(miFileLoad, wxT("&Load G3d model\tCtrl+L"), wxT("Load 3D model"));
- menuFile->Append(miFileLoadParticleXML, wxT("Load &Particle XML\tCtrl+P"), wxT("Press ctrl before menu for keeping current particles"));
- menuFile->Append(miFileLoadProjectileParticleXML, wxT("Load Pro&jectile Particle XML\tCtrl+J"), wxT("Press ctrl before menu for keeping current projectile particles"));
- menuFile->Append(miFileLoadSplashParticleXML, wxT("Load &Splash Particle XML\tCtrl+S"), wxT("Press ctrl before menu for keeping current splash particles"));
- menuFile->Append(miFileClearAll, wxT("&Clear All\tCtrl+C"));
- menuFile->AppendCheckItem(miFileToggleScreenshotTransparent, wxT("&Transparent Screenshots\tCtrl+T"));
- menuFile->Append(miFileSaveScreenshot, wxT("Sa&ve a Screenshot\tCtrl+V"));
- menuFile->AppendSeparator();
- menuFile->Append(wxID_EXIT);
- menu->Append(menuFile, wxT("&File"));
+ //menu
+ menuFile = new wxMenu();
+ menuFile->Append(miFileLoad, wxT("&Load G3d model\tCtrl+L"), wxT("Load 3D model"));
+ menuFile->Append(miFileLoadParticleXML, wxT("Load &Particle XML\tCtrl+P"), wxT("Press ctrl before menu for keeping current particles"));
+ menuFile->Append(miFileLoadProjectileParticleXML, wxT("Load Pro&jectile Particle XML\tCtrl+J"), wxT("Press ctrl before menu for keeping current projectile particles"));
+ menuFile->Append(miFileLoadSplashParticleXML, wxT("Load &Splash Particle XML\tCtrl+S"), wxT("Press ctrl before menu for keeping current splash particles"));
+ menuFile->Append(miFileClearAll, wxT("&Clear All\tCtrl+C"));
+ menuFile->AppendCheckItem(miFileToggleScreenshotTransparent, wxT("&Transparent Screenshots\tCtrl+T"));
+ menuFile->Append(miFileSaveScreenshot, wxT("Sa&ve a Screenshot\tCtrl+V"));
+ menuFile->AppendSeparator();
+ menuFile->Append(wxID_EXIT);
+ menu->Append(menuFile, wxT("&File"));
- //mode
- menuMode= new wxMenu();
- menuMode->AppendCheckItem(miModeNormals, wxT("&Normals"));
- menuMode->AppendCheckItem(miModeWireframe, wxT("&Wireframe"));
- menuMode->AppendCheckItem(miModeGrid, wxT("&Grid"));
- menu->Append(menuMode, wxT("&Mode"));
+ //mode
+ menuMode = new wxMenu();
+ menuMode->AppendCheckItem(miModeNormals, wxT("&Normals"));
+ menuMode->AppendCheckItem(miModeWireframe, wxT("&Wireframe"));
+ menuMode->AppendCheckItem(miModeGrid, wxT("&Grid"));
+ menu->Append(menuMode, wxT("&Mode"));
- //mode
- menuSpeed= new wxMenu();
- menuSpeed->Append(miSpeedSlower, wxT("&Slower\t-"));
- menuSpeed->Append(miSpeedFaster, wxT("&Faster\t+"));
- menuSpeed->AppendSeparator();
- menuSpeed->Append(miRestart, wxT("&Restart particles\tR"), wxT("Restart particle animations, this also reloads model and particle files if they are changed"));
- menu->Append(menuSpeed, wxT("&Speed"));
+ //mode
+ menuSpeed = new wxMenu();
+ menuSpeed->Append(miSpeedSlower, wxT("&Slower\t-"));
+ menuSpeed->Append(miSpeedFaster, wxT("&Faster\t+"));
+ menuSpeed->AppendSeparator();
+ menuSpeed->Append(miRestart, wxT("&Restart particles\tR"), wxT("Restart particle animations, this also reloads model and particle files if they are changed"));
+ menu->Append(menuSpeed, wxT("&Speed"));
- //custom color
- menuCustomColor= new wxMenu();
- menuCustomColor->Append(miChangeBackgroundColor, wxT("Change Background Color"));
- menuCustomColor->AppendCheckItem(miColorRed, wxT("&Red\t0"));
- menuCustomColor->AppendCheckItem(miColorBlue, wxT("&Blue\t1"));
- menuCustomColor->AppendCheckItem(miColorGreen, wxT("&Green\t2"));
- menuCustomColor->AppendCheckItem(miColorYellow, wxT("&Yellow\t3"));
- menuCustomColor->AppendCheckItem(miColorWhite, wxT("&White\t4"));
- menuCustomColor->AppendCheckItem(miColorCyan, wxT("&Cyan\t5"));
- menuCustomColor->AppendCheckItem(miColorOrange, wxT("&Orange\t6"));
- menuCustomColor->AppendCheckItem(miColorMagenta, wxT("&Pink\t7")); // it is called Pink everywhere else so...
- menu->Append(menuCustomColor, wxT("&Custom Color"));
+ //custom color
+ menuCustomColor = new wxMenu();
+ menuCustomColor->Append(miChangeBackgroundColor, wxT("Change Background Color"));
+ menuCustomColor->AppendCheckItem(miColorRed, wxT("&Red\t0"));
+ menuCustomColor->AppendCheckItem(miColorBlue, wxT("&Blue\t1"));
+ menuCustomColor->AppendCheckItem(miColorGreen, wxT("&Green\t2"));
+ menuCustomColor->AppendCheckItem(miColorYellow, wxT("&Yellow\t3"));
+ menuCustomColor->AppendCheckItem(miColorWhite, wxT("&White\t4"));
+ menuCustomColor->AppendCheckItem(miColorCyan, wxT("&Cyan\t5"));
+ menuCustomColor->AppendCheckItem(miColorOrange, wxT("&Orange\t6"));
+ menuCustomColor->AppendCheckItem(miColorMagenta, wxT("&Pink\t7")); // it is called Pink everywhere else so...
+ menu->Append(menuCustomColor, wxT("&Custom Color"));
- menuMode->Check(miModeGrid, true);
- menuCustomColor->Check(miColorRed, true);
+ menuMode->Check(miModeGrid, true);
+ menuCustomColor->Check(miColorRed, true);
- SetMenuBar(menu);
+ SetMenuBar(menu);
- //misc
- backBrightness= 0.3f;
- gridBrightness= 1.0f;
- lightBrightness= 0.3f;
- lastX= 0;
- lastY= 0;
+ //misc
+ backBrightness = 0.3f;
+ gridBrightness = 1.0f;
+ lightBrightness = 0.3f;
+ lastX = 0;
+ lastY = 0;
- statusbarText="";
- CreateStatusBar();
+ statusbarText = "";
+ CreateStatusBar();
- this->Layout();
+ this->Layout();
- wxInitAllImageHandlers();
+ wxInitAllImageHandlers();
#ifdef WIN32
#if defined(__MINGW32__)
- wxIcon icon(ToUnicode("IDI_ICON1"));
+ wxIcon icon(ToUnicode("IDI_ICON1"));
#else
- wxIcon icon(L"IDI_ICON1");
+ wxIcon icon(L"IDI_ICON1");
#endif
#else
- wxIcon icon;
- string iniFilePath = extractDirectoryPathFromFile(config.getFileName(false));
- string icon_file = iniFilePath + "g3dviewer.ico";
- std::ifstream testFile(icon_file.c_str());
- if(testFile.good()) {
- testFile.close();
- icon.LoadFile(ToUnicode(icon_file.c_str()),wxBITMAP_TYPE_ICO);
- }
+ wxIcon icon;
+ string iniFilePath = extractDirectoryPathFromFile(config.getFileName(false));
+ string icon_file = iniFilePath + "g3dviewer.ico";
+ std::ifstream testFile(icon_file.c_str());
+ if (testFile.good()) {
+ testFile.close();
+ icon.LoadFile(ToUnicode(icon_file.c_str()), wxBITMAP_TYPE_ICO);
+ }
#endif
- SetIcon(icon);
+ SetIcon(icon);
- fileDialog = new wxFileDialog(this);
- if(modelPath != "") {
- fileDialog->SetPath(ToUnicode(modelPath));
- }
- string userData = config.getString("UserData_Root","");
- if(userData != "") {
- endPathWithSlash(userData);
- }
- string defaultPath = userData + "techs/";
- fileDialog->SetDirectory(ToUnicode(defaultPath.c_str()));
+ fileDialog = new wxFileDialog(this);
+ if (modelPath != "") {
+ fileDialog->SetPath(ToUnicode(modelPath));
+ }
+ string userData = config.getString("UserData_Root", "");
+ if (userData != "") {
+ endPathWithSlash(userData);
+ }
+ string defaultPath = userData + "techs/";
+ fileDialog->SetDirectory(ToUnicode(defaultPath.c_str()));
- if(glCanvas != NULL) {
- glCanvas->SetFocus();
- }
+ if (glCanvas != NULL) {
+ glCanvas->SetFocus();
+ }
- // For windows register g3d file extension to launch this app
+ // For windows register g3d file extension to launch this app
#if defined(WIN32) && !defined(__MINGW32__)
// example from: http://stackoverflow.com/questions/1387769/create-registry-entry-to-associate-file-extension-with-application-in-c
//[HKEY_CURRENT_USER\Software\Classes\blergcorp.blergapp.v1\shell\open\command]
@@ -470,2160 +473,2096 @@ MainWindow::MainWindow( std::pair > unitToLoad,
//@="blergcorp.blergapp.v1"
//Open the registry key.
- wstring subKey = L"Software\\Classes\\zetaglest.g3d\\shell\\open\\command";
- HKEY keyHandle;
- DWORD dwDisposition;
- RegCreateKeyEx(HKEY_CURRENT_USER,subKey.c_str(),0, NULL, 0, KEY_ALL_ACCESS, NULL, &keyHandle, &dwDisposition);
- //Set the value.
- auto_ptr wstr(Ansi2WideString(appPath.c_str()));
+ wstring subKey = L"Software\\Classes\\zetaglest.g3d\\shell\\open\\command";
+ HKEY keyHandle;
+ DWORD dwDisposition;
+ RegCreateKeyEx(HKEY_CURRENT_USER, subKey.c_str(), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &keyHandle, &dwDisposition);
+ //Set the value.
+ auto_ptr wstr(Ansi2WideString(appPath.c_str()));
- wstring launchApp = wstring(wstr.get()) + L" \"%1\"";
- DWORD len = (launchApp.size() + 1) * sizeof(wchar_t);
- RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE)launchApp.c_str(), len);
- RegCloseKey(keyHandle);
+ wstring launchApp = wstring(wstr.get()) + L" \"%1\"";
+ DWORD len = (launchApp.size() + 1) * sizeof(wchar_t);
+ RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE) launchApp.c_str(), len);
+ RegCloseKey(keyHandle);
- subKey = L"Software\\Classes\\.g3d";
- RegCreateKeyEx(HKEY_CURRENT_USER,subKey.c_str(),0, NULL, 0, KEY_ALL_ACCESS, NULL, &keyHandle, &dwDisposition);
- //Set the value.
- launchApp = L"zetaglest.g3d";
- len = (launchApp.size() + 1) * sizeof(wchar_t);
- RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE)launchApp.c_str(), len);
- RegCloseKey(keyHandle);
+ subKey = L"Software\\Classes\\.g3d";
+ RegCreateKeyEx(HKEY_CURRENT_USER, subKey.c_str(), 0, NULL, 0, KEY_ALL_ACCESS, NULL, &keyHandle, &dwDisposition);
+ //Set the value.
+ launchApp = L"zetaglest.g3d";
+ len = (launchApp.size() + 1) * sizeof(wchar_t);
+ RegSetValueEx(keyHandle, NULL, 0, REG_SZ, (PBYTE) launchApp.c_str(), len);
+ RegCloseKey(keyHandle);
#endif
-}
+ }
-void MainWindow::setupTimer() {
- timer = new wxTimer(this);
- timer->Start(100);
-}
+ void MainWindow::setupTimer() {
+ timer = new wxTimer(this);
+ timer->Start(100);
+ }
-void MainWindow::setupStartupSettings() {
+ void MainWindow::setupStartupSettings() {
- //printf("In setupStartupSettings #1\n");
- if(glCanvas == NULL) {
- initGlCanvas();
+ //printf("In setupStartupSettings #1\n");
+ if (glCanvas == NULL) {
+ initGlCanvas();
#if wxCHECK_VERSION(2, 9, 1)
#else
- glCanvas->SetCurrent();
+ glCanvas->SetCurrent();
#endif
- }
- glCanvas->setCurrentGLContext();
- //printf("In setupStartupSettings #2\n");
+ }
+ glCanvas->setCurrentGLContext();
+ //printf("In setupStartupSettings #2\n");
- GLuint err = glewInit();
- if (GLEW_OK != err) {
- fprintf(stderr, "Error [main]: glewInit failed: %s\n", glewGetErrorString(err));
- //return 1;
- throw std::runtime_error((char *)glewGetErrorString(err));
- }
+ GLuint err = glewInit();
+ if (GLEW_OK != err) {
+ fprintf(stderr, "Error [main]: glewInit failed: %s\n", glewGetErrorString(err));
+ //return 1;
+ throw std::runtime_error((char *) glewGetErrorString(err));
+ }
- renderer= Renderer::getInstance();
+ renderer = Renderer::getInstance();
- for(unsigned int i = 0; i < autoScreenShotParams.size(); ++i) {
- if(autoScreenShotParams[i] == "transparent") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuFile->Check(miFileToggleScreenshotTransparent,true);
- float alpha = 0.0f;
- renderer->setAlphaColor(alpha);
+ for (unsigned int i = 0; i < autoScreenShotParams.size(); ++i) {
+ if (autoScreenShotParams[i] == "transparent") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuFile->Check(miFileToggleScreenshotTransparent, true);
+ float alpha = 0.0f;
+ renderer->setAlphaColor(alpha);
+ }
+ if (autoScreenShotParams[i] == "enable_grid") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuMode->Check(miModeGrid, true);
+ if (renderer->getGrid() == false) {
+ renderer->toggleGrid();
+ }
+ }
+ if (autoScreenShotParams[i] == "enable_wireframe") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuMode->Check(miModeWireframe, true);
+ if (renderer->getWireframe() == false) {
+ renderer->toggleWireframe();
+ }
+ }
+ if (autoScreenShotParams[i] == "enable_normals") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuMode->Check(miModeNormals, true);
+ if (renderer->getNormals() == false) {
+ renderer->toggleNormals();
+ }
+ }
+ if (autoScreenShotParams[i] == "disable_grid") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuMode->Check(miModeGrid, false);
+ if (renderer->getGrid() == true) {
+ renderer->toggleGrid();
+ }
+ }
+ if (autoScreenShotParams[i] == "enable_wireframe") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuMode->Check(miModeWireframe, false);
+ if (renderer->getWireframe() == true) {
+ renderer->toggleWireframe();
+ }
+ }
+ if (autoScreenShotParams[i] == "enable_normals") {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ menuMode->Check(miModeNormals, false);
+ if (renderer->getNormals() == true) {
+ renderer->toggleNormals();
+ }
+ }
+ }
+ renderer->init();
+
+ wxCommandEvent event;
+ onMenuRestart(event);
}
- if(autoScreenShotParams[i] == "enable_grid") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuMode->Check(miModeGrid,true);
- if(renderer->getGrid() == false) {
- renderer->toggleGrid();
+
+ MainWindow::~MainWindow() {
+ delete timer;
+ timer = NULL;
+
+ delete fileDialog;
+ fileDialog = NULL;
+
+ //delete model;
+ //model = NULL;
+ if (renderer) renderer->end();
+
+ delete renderer;
+ renderer = NULL;
+
+ if (glCanvas) {
+ glCanvas->Destroy();
+ }
+ glCanvas = NULL;
+
+ }
+
+ void MainWindow::initGlCanvas() {
+ if (glCanvas == NULL) {
+ int args[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_MIN_ALPHA, 8 }; // to prevent flicker
+ glCanvas = new GlCanvas(this, args);
}
}
- if(autoScreenShotParams[i] == "enable_wireframe") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuMode->Check(miModeWireframe,true);
- if(renderer->getWireframe() == false) {
- renderer->toggleWireframe();
- }
- }
- if(autoScreenShotParams[i] == "enable_normals") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuMode->Check(miModeNormals,true);
- if(renderer->getNormals() == false) {
- renderer->toggleNormals();
- }
- }
- if(autoScreenShotParams[i] == "disable_grid") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuMode->Check(miModeGrid,false);
- if(renderer->getGrid() == true) {
- renderer->toggleGrid();
- }
- }
- if(autoScreenShotParams[i] == "enable_wireframe") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuMode->Check(miModeWireframe,false);
- if(renderer->getWireframe() == true) {
- renderer->toggleWireframe();
- }
- }
- if(autoScreenShotParams[i] == "enable_normals") {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- menuMode->Check(miModeNormals,false);
- if(renderer->getNormals() == true) {
- renderer->toggleNormals();
- }
- }
- }
- renderer->init();
- wxCommandEvent event;
- onMenuRestart(event);
-}
-
-MainWindow::~MainWindow(){
- delete timer;
- timer = NULL;
-
- delete fileDialog;
- fileDialog = NULL;
-
- //delete model;
- //model = NULL;
- if(renderer) renderer->end();
-
- delete renderer;
- renderer = NULL;
-
- if(glCanvas) {
- glCanvas->Destroy();
- }
- glCanvas = NULL;
-
-}
-
-void MainWindow::initGlCanvas(){
- if(glCanvas == NULL) {
- int args[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_MIN_ALPHA, 8 }; // to prevent flicker
- glCanvas = new GlCanvas(this, args);
- }
-}
-
-void MainWindow::init() {
+ void MainWindow::init() {
#if wxCHECK_VERSION(2, 9, 3)
#elif wxCHECK_VERSION(2, 9, 1)
#else
- glCanvas->SetCurrent();
- //printf("setcurrent #2\n");
+ glCanvas->SetCurrent();
+ //printf("setcurrent #2\n");
#endif
-}
-
-void MainWindow::onPaint(wxPaintEvent &event) {
- if(!IsShown()) {
- event.Skip();
- return;
- }
-
- bool isFirstWindowShownEvent = !startupSettingsInited ;
- if(startupSettingsInited == false) {
- startupSettingsInited = true;
- setupStartupSettings();
- }
- glCanvas->setCurrentGLContext();
-
- static float autoScreenshotRender = -1;
- if(autoScreenShotAndExit == true && autoScreenshotRender >= 0) {
- anim = autoScreenshotRender;
- }
- // notice that we use GetSize() here and not GetClientSize() because
- // the latter doesn't return correct results for the minimized windows
- // (at least not under Windows)
- int viewportW = GetClientSize().x;
- int viewportH = GetClientSize().y;
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%d x %d\n",viewportW,viewportH);
-
- if(viewportW == 0 && viewportH == 0) {
- printf("#1 %d x %d\n",viewportW,viewportH);
-
- viewportW = GetSize().x;
- viewportH = GetSize().y;
-
- if(viewportH > 0) {
- //viewportH -= menu->GetSize().y;
- viewportH -= 22;
}
- printf("#2 %d x %d\n",viewportW,viewportH);
- }
+ void MainWindow::onPaint(wxPaintEvent &event) {
+ if (!IsShown()) {
+ event.Skip();
+ return;
+ }
+
+ bool isFirstWindowShownEvent = !startupSettingsInited;
+ if (startupSettingsInited == false) {
+ startupSettingsInited = true;
+ setupStartupSettings();
+ }
+ glCanvas->setCurrentGLContext();
+
+ static float autoScreenshotRender = -1;
+ if (autoScreenShotAndExit == true && autoScreenshotRender >= 0) {
+ anim = autoScreenshotRender;
+ }
+ // notice that we use GetSize() here and not GetClientSize() because
+ // the latter doesn't return correct results for the minimized windows
+ // (at least not under Windows)
+ int viewportW = GetClientSize().x;
+ int viewportH = GetClientSize().y;
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("%d x %d\n", viewportW, viewportH);
+
+ if (viewportW == 0 && viewportH == 0) {
+ printf("#1 %d x %d\n", viewportW, viewportH);
+
+ viewportW = GetSize().x;
+ viewportH = GetSize().y;
+
+ if (viewportH > 0) {
+ //viewportH -= menu->GetSize().y;
+ viewportH -= 22;
+ }
+
+ printf("#2 %d x %d\n", viewportW, viewportH);
+ }
#if defined(WIN32)
- renderer->reset(viewportW, viewportH, playerColor);
+ renderer->reset(viewportW, viewportH, playerColor);
#else
- renderer->reset(viewportW, viewportH, playerColor);
+ renderer->reset(viewportW, viewportH, playerColor);
#endif
- renderer->transform(rotX, rotY, zoom);
- renderer->renderGrid();
+ renderer->transform(rotX, rotY, zoom);
+ renderer->renderGrid();
- //printf("anim [%f] particleLoopStart [%d]\n",anim,particleLoopStart);
+ //printf("anim [%f] particleLoopStart [%d]\n",anim,particleLoopStart);
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
- renderer->renderTheModel(model, anim);
+ renderer->renderTheModel(model, anim);
- int updateLoops = particleLoopStart;
- particleLoopStart = 1;
+ int updateLoops = particleLoopStart;
+ particleLoopStart = 1;
- if(resetAnimation == true || ((anim - lastanim) >= defaultspeed*2)) {
- //printf("anim [%f] [%f] [%f]\n",anim,lastanim,speed);
+ if (resetAnimation == true || ((anim - lastanim) >= defaultspeed * 2)) {
+ //printf("anim [%f] [%f] [%f]\n",anim,lastanim,speed);
- for(int i=0; i< updateLoops; ++i) {
- renderer->updateParticleManager();
+ for (int i = 0; i < updateLoops; ++i) {
+ renderer->updateParticleManager();
+ }
+ }
+
+ renderer->renderParticleManager();
+
+ if (isFirstWindowShownEvent) {
+ this->Refresh();
+ glCanvas->Refresh();
+ glCanvas->SetFocus();
+ }
+
+ bool haveLoadedParticles = (particleProjectilePathList.empty() == false || particleSplashPathList.empty() == false);
+
+ if (autoScreenShotAndExit == true && viewportW > 0 && viewportH > 0) {
+ printf("Auto exiting app...\n");
+ fflush(stdout);
+
+ autoScreenShotAndExit = false;
+
+ saveScreenshot();
+ Close();
+ return;
+ }
+
+ glCanvas->SwapBuffers();
+
+ if (autoScreenShotAndExit == true && viewportW == 0 && viewportH == 0) {
+ autoScreenshotRender = anim;
+
+ printf("Auto exiting desired but waiting for w x h > 0...\n");
+
+ return;
+ }
+ if ((modelPathList.empty() == false) && resetAnimation && haveLoadedParticles) {
+ if (anim >= resetAnim && resetAnim > 0) {
+ printf("RESETTING EVERYTHING [%f][%f]...\n", anim, resetAnim);
+ fflush(stdout);
+
+ resetAnimation = false;
+ particleLoopStart = resetParticleLoopStart;
+
+ wxCommandEvent event;
+ if (unitPath.first != "") {
+ //onMenuFileClearAll(event);
+
+ modelPathList.clear();
+ particlePathList.clear();
+ particleProjectilePathList.clear();
+ particleSplashPathList.clear(); // as above
+
+ onMenuRestart(event);
+ } else {
+ onMenuRestart(event);
+ }
+ }
+ } else if (modelPathList.empty() == true && haveLoadedParticles) {
+ if (renderer->hasActiveParticleSystem(ParticleSystem::pst_ProjectileParticleSystem) == false &&
+ renderer->hasActiveParticleSystem(ParticleSystem::pst_SplashParticleSystem) == false) {
+
+ printf("RESETTING PARTICLES...\n");
+ fflush(stdout);
+
+ resetAnimation = false;
+ anim = 0.f;
+ particleLoopStart = resetParticleLoopStart;
+
+ wxCommandEvent event;
+ onMenuRestart(event);
+ }
+ }
+
+ lastanim = anim;
}
- }
- renderer->renderParticleManager();
+ void MainWindow::onClose(wxCloseEvent &event) {
+ // release memory first (from onMenuFileClearAll)
- if(isFirstWindowShownEvent) {
- this->Refresh();
- glCanvas->Refresh();
- glCanvas->SetFocus();
- }
+ //printf("OnClose START\n");
+ //fflush(stdout);
- bool haveLoadedParticles = (particleProjectilePathList.empty() == false || particleSplashPathList.empty() == false);
+ modelPathList.clear();
+ particlePathList.clear();
+ particleProjectilePathList.clear();
+ particleSplashPathList.clear(); // as above
- if(autoScreenShotAndExit == true && viewportW > 0 && viewportH > 0) {
- printf("Auto exiting app...\n");
- fflush(stdout);
+ if (timer) timer->Stop();
- autoScreenShotAndExit = false;
+ unitParticleSystems.clear();
+ unitParticleSystemTypes.clear();
- saveScreenshot();
- Close();
- return;
- }
+ projectileParticleSystems.clear();
+ projectileParticleSystemTypes.clear();
+ splashParticleSystems.clear(); // as above
+ splashParticleSystemTypes.clear();
- glCanvas->SwapBuffers();
+ //delete model;
+ //model = NULL;
+ if (renderer) renderer->end();
- if(autoScreenShotAndExit == true && viewportW == 0 && viewportH == 0) {
- autoScreenshotRender = anim;
+ //printf("OnClose about to END\n");
+ //fflush(stdout);
- printf("Auto exiting desired but waiting for w x h > 0...\n");
+ delete timer;
+ timer = NULL;
- return;
- }
- if((modelPathList.empty() == false) && resetAnimation && haveLoadedParticles) {
- if(anim >= resetAnim && resetAnim > 0) {
- printf("RESETTING EVERYTHING [%f][%f]...\n",anim,resetAnim);
- fflush(stdout);
+ //delete model;
+ //model = NULL;
- resetAnimation = false;
- particleLoopStart = resetParticleLoopStart;
+ delete renderer;
+ renderer = NULL;
- wxCommandEvent event;
- if(unitPath.first != "") {
- //onMenuFileClearAll(event);
+ //delete glCanvas;
+ if (glCanvas) {
+ glCanvas->Destroy();
+ }
+ glCanvas = NULL;
+
+ this->Destroy();
+ }
+
+ // for the mousewheel
+ void MainWindow::onMouseWheelDown(wxMouseEvent &event) {
+ try {
+ wxPaintEvent paintEvent;
+ zoom *= 1.1f;
+ zoom = clamp(zoom, 0.1f, 10.0f);
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+
+ onPaint(paintEvent);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMouseWheelUp(wxMouseEvent &event) {
+ try {
+ wxPaintEvent paintEvent;
+ zoom *= 0.90909f;
+ zoom = clamp(zoom, 0.1f, 10.0f);
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+
+ onPaint(paintEvent);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+
+ void MainWindow::onMouseMove(wxMouseEvent &event) {
+ try {
+ int x = event.GetX();
+ int y = event.GetY();
+ wxPaintEvent paintEvent;
+
+ if (event.LeftIsDown()) {
+ rotX += clamp(lastX - x, -10, 10);
+ rotY += clamp(lastY - y, -10, 10);
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+
+ onPaint(paintEvent);
+ } else if (event.RightIsDown()) {
+ zoom *= 1.0f + (lastX - x + lastY - y) / 100.0f;
+ zoom = clamp(zoom, 0.1f, 10.0f);
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+
+ onPaint(paintEvent);
+ }
+
+ lastX = x;
+ lastY = y;
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuFileLoad(wxCommandEvent &event) {
+ try {
+ //string fileName;
+ fileDialog->SetWildcard(wxT("G3D files (*.g3d)|*.g3d;*.G3D"));
+ fileDialog->SetMessage(wxT("Selecting Glest Model for current view."));
+
+ if (fileDialog->ShowModal() == wxID_OK) {
+ modelPathList.clear();
+ string file;
+#ifdef WIN32
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
+ file = tmp_buf;
+
+ auto_ptr wstr(Ansi2WideString(file.c_str()));
+ file = utf8_encode(wstr.get());
+#else
+ file = (const char*) wxFNCONV(fileDialog->GetPath().c_str());
+#endif
+
+ //loadModel((const char*)wxFNCONV(fileDialog->GetPath().c_str()));
+ loadModel(file);
+ }
+ isControlKeyPressed = false;
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuFileLoadParticleXML(wxCommandEvent &event) {
+ try {
+ //string fileName;
+ fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml"));
+
+ if (isControlKeyPressed == true) {
+ fileDialog->SetMessage(wxT("Adding ZetaGlest particle to current view."));
+ } else {
+ fileDialog->SetMessage(wxT("Selecting ZetaGlest particle for current view."));
+ }
+
+ if (fileDialog->ShowModal() == wxID_OK) {
+ //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
+ string file;
+#ifdef WIN32
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
+ file = tmp_buf;
+ auto_ptr wstr(Ansi2WideString(file.c_str()));
+ file = utf8_encode(wstr.get());
+#else
+ file = (const char*) wxFNCONV(fileDialog->GetPath().c_str());
+#endif
+
+ loadParticle(file);
+ }
+ isControlKeyPressed = false;
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuFileLoadProjectileParticleXML(wxCommandEvent &event) {
+ try {
+ //string fileName;
+ fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml"));
+
+ if (isControlKeyPressed == true) {
+ fileDialog->SetMessage(wxT("Adding ZetaGlest projectile particle to current view."));
+ } else {
+ fileDialog->SetMessage(wxT("Selecting ZetaGlest projectile particle for current view."));
+ }
+
+ if (fileDialog->ShowModal() == wxID_OK) {
+ //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
+ string file;
+#ifdef WIN32
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
+ file = tmp_buf;
+ auto_ptr wstr(Ansi2WideString(file.c_str()));
+ file = utf8_encode(wstr.get());
+#else
+ file = (const char*) wxFNCONV(fileDialog->GetPath().c_str());
+#endif
+
+ loadProjectileParticle(file);
+ }
+ isControlKeyPressed = false;
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuFileLoadSplashParticleXML(wxCommandEvent &event) {
+ try {
+ //string fileName;
+ fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml"));
+
+ if (isControlKeyPressed == true) {
+ fileDialog->SetMessage(wxT("Adding ZetaGlest splash particle to current view."));
+ } else {
+ fileDialog->SetMessage(wxT("Selecting ZetaGlest splash particle for current view."));
+ }
+
+ if (fileDialog->ShowModal() == wxID_OK) {
+ //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
+ string file;
+#ifdef WIN32
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
+ file = tmp_buf;
+
+ auto_ptr wstr(Ansi2WideString(file.c_str()));
+ file = utf8_encode(wstr.get());
+#else
+ file = (const char*) wxFNCONV(fileDialog->GetPath().c_str());
+#endif
+
+ loadSplashParticle(file);
+ }
+ isControlKeyPressed = false;
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ } // is it possible to join loadParticle(), loadProjectileParticle() and loadSplashParticle() to one method?
+
+
+ void MainWindow::OnChangeColor(wxCommandEvent &event) {
+ try {
+ //wxColour color = colorPicker->GetColour();
+ wxColourData data;
+ data.SetChooseFull(true);
+ for (int i = 0; i < 16; i++) {
+ wxColour colour(i * 16, i * 16, i * 16);
+ data.SetCustomColour(i, colour);
+ }
+
+ wxColourDialog dialog(this, &data);
+ if (dialog.ShowModal() == wxID_OK) {
+ wxColourData retData = dialog.GetColourData();
+ wxColour col = retData.GetColour();
+ renderer->setBackgroundColor(col.Red() / 255.0f, col.Green() / 255.0f, col.Blue() / 255.0f);
+ }
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenumFileToggleScreenshotTransparent(wxCommandEvent &event) {
+ try {
+ float alpha = (event.IsChecked() == true ? 0.0f : 1.0f);
+ renderer->setAlphaColor(alpha);
+ //printf("alpha = %f\n",alpha);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::saveScreenshot() {
+ try {
+ int autoSaveScreenshotIndex = -1;
+ for (unsigned int i = 0; i < autoScreenShotParams.size(); ++i) {
+ if (_strnicmp(autoScreenShotParams[i].c_str(), "saveas-", 7) == 0) {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
+ autoSaveScreenshotIndex = i;
+ break;
+ }
+ }
+ if (autoSaveScreenshotIndex >= 0) {
+ string saveAsFilename = autoScreenShotParams[autoSaveScreenshotIndex];
+ saveAsFilename.erase(0, 7);
+#ifdef WIN32
+ FILE*f = _wfopen(utf8_decode(saveAsFilename).c_str(), L"rb");
+#else
+ FILE *f = fopen(saveAsFilename.c_str(), "rb");
+#endif
+ if (f == NULL) {
+ renderer->saveScreen(saveAsFilename.c_str(), &overrideSize);
+ } else {
+ if (f) {
+ fclose(f);
+ }
+ }
+ } else {
+ //string screenShotsPath = extractDirectoryPathFromFile(appPath) + string("screens/");
+ string userData = Config::getInstance().getString("UserData_Root", "");
+ if (userData != "") {
+ endPathWithSlash(userData);
+ }
+ string screenShotsPath = userData + string("screens/");
+ printf("screenShotsPath [%s]\n", screenShotsPath.c_str());
+
+ if (isdir(screenShotsPath.c_str()) == false) {
+ createDirectoryPaths(screenShotsPath);
+ }
+
+ string path = screenShotsPath;
+ if (isdir(path.c_str()) == true) {
+ //Config &config= Config::getInstance();
+ //string fileFormat = config.getString("ScreenShotFileType","jpg");
+
+ for (int i = 0; i < 5000; ++i) {
+ path = screenShotsPath;
+ path += string("screen") + intToStr(i) + string(".") + fileFormat;
+#ifdef WIN32
+ FILE*f = _wfopen(utf8_decode(path).c_str(), L"rb");
+#else
+ FILE *f = fopen(path.c_str(), "rb");
+#endif
+ if (f == NULL) {
+ renderer->saveScreen(path, &overrideSize);
+ break;
+ } else {
+ if (f) {
+ fclose(f);
+ }
+ }
+ }
+ }
+ }
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuFileSaveScreenshot(wxCommandEvent &event) {
+ saveScreenshot();
+ }
+
+ void MainWindow::onMenuFileClearAll(wxCommandEvent &event) {
+ try {
+ //printf("Start onMenuFileClearAll\n");
+ //fflush(stdout);
modelPathList.clear();
particlePathList.clear();
particleProjectilePathList.clear();
particleSplashPathList.clear(); // as above
- onMenuRestart(event);
- }
- else {
- onMenuRestart(event);
+ if (timer) timer->Stop();
+ if (renderer) renderer->end();
+
+ unitParticleSystems.clear();
+ unitParticleSystemTypes.clear();
+
+ projectileParticleSystems.clear();
+ projectileParticleSystemTypes.clear();
+ splashParticleSystems.clear(); // as above
+ splashParticleSystemTypes.clear();
+
+ //delete model;
+ //model = NULL;
+ if (model != NULL && renderer != NULL) renderer->endModel(rsGlobal, model);
+ model = NULL;
+
+ loadUnit("", "");
+ loadModel("");
+ loadParticle("");
+ loadProjectileParticle("");
+ loadSplashParticle(""); // as above
+
+ GetStatusBar()->SetStatusText(ToUnicode(statusbarText.c_str()));
+ isControlKeyPressed = false;
+
+ //printf("END onMenuFileClearAll\n");
+ //fflush(stdout);
+
+ if (timer) timer->Start(100);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
}
}
- }
- else if(modelPathList.empty() == true && haveLoadedParticles) {
- if(renderer->hasActiveParticleSystem(ParticleSystem::pst_ProjectileParticleSystem) == false &&
- renderer->hasActiveParticleSystem(ParticleSystem::pst_SplashParticleSystem) == false) {
- printf("RESETTING PARTICLES...\n");
- fflush(stdout);
-
- resetAnimation = false;
- anim = 0.f;
- particleLoopStart = resetParticleLoopStart;
-
- wxCommandEvent event;
- onMenuRestart(event);
+ void MainWindow::onMenuFileExit(wxCommandEvent &event) {
+ Close();
}
- }
- lastanim = anim;
-}
+ void MainWindow::loadUnit(string path, string skillName) {
+ if (path != "" && fileExists(path) == true) {
+ // std::cout << "Clearing list..." << std::endl;
+ this->unitPath.first = path;
+ this->unitPath.second.push_back(skillName);
+ }
-void MainWindow::onClose(wxCloseEvent &event){
- // release memory first (from onMenuFileClearAll)
+ try {
+ if (this->unitPath.first != "") {
+ if (timer) timer->Stop();
+ if (renderer) renderer->end();
- //printf("OnClose START\n");
- //fflush(stdout);
+ string titlestring = winHeader;
- modelPathList.clear();
- particlePathList.clear();
- particleProjectilePathList.clear();
- particleSplashPathList.clear(); // as above
+ string unitPath = this->unitPath.first;
+ string dir = unitPath;
+ string name = lastDir(dir);
+ string path = dir + "/" + name + ".xml";
- if(timer) timer->Stop();
+ titlestring = unitPath + " - " + titlestring;
- unitParticleSystems.clear();
- unitParticleSystemTypes.clear();
+ std::string unitXML = path;
- projectileParticleSystems.clear();
- projectileParticleSystemTypes.clear();
- splashParticleSystems.clear(); // as above
- splashParticleSystemTypes.clear();
+ string skillModelFile = "";
+ string skillParticleFile = "";
+ string skillParticleProjectileFile = "";
+ string skillParticleSplashFile = "";
+ bool fileFound = fileExists(unitXML);
- //delete model;
- //model = NULL;
- if(renderer) renderer->end();
+ printf("Loading unit from file [%s] fileFound = %d\n", unitXML.c_str(), fileFound);
- //printf("OnClose about to END\n");
- //fflush(stdout);
+ if (fileFound == true) {
+ XmlTree xmlTree;
+ xmlTree.load(unitXML, Properties::getTagReplacementValues());
+ const XmlNode *unitNode = xmlTree.getRootNode();
- delete timer;
- timer = NULL;
+ bool foundSkillName = false;
+ for (unsigned int skillIdx = 0; foundSkillName == false && skillIdx < this->unitPath.second.size(); ++skillIdx) {
+ string lookipForSkillName = this->unitPath.second[skillIdx];
- //delete model;
- //model = NULL;
+ const XmlNode *skillsNode = unitNode->getChild("skills");
+ for (unsigned int i = 0; foundSkillName == false && i < skillsNode->getChildCount(); ++i) {
+ const XmlNode *sn = skillsNode->getChild("skill", i);
+ //const XmlNode *typeNode= sn->getChild("type");
+ const XmlNode *nameNode = sn->getChild("name");
+ string skillXmlName = nameNode->getAttribute("value")->getRestrictedValue();
+ if (skillXmlName == lookipForSkillName) {
+ printf("Found skill [%s]\n", lookipForSkillName.c_str());
+ foundSkillName = true;
- delete renderer;
- renderer = NULL;
+ if (sn->getChild("animation") != NULL) {
+ skillModelFile = sn->getChild("animation")->getAttribute("path")->getRestrictedValue(unitPath + '/');
+ printf("Found skill model [%s]\n", skillModelFile.c_str());
+ }
- //delete glCanvas;
- if(glCanvas) {
- glCanvas->Destroy();
- }
- glCanvas = NULL;
+ if (sn->hasChild("particles") == true) {
+ const XmlNode *particlesNode = sn->getChild("particles");
+ //for(int j = 0; particlesNode != NULL && particlesNode->getAttribute("value")->getRestrictedValue() == "true" &&
+ // j < particlesNode->getChildCount(); ++j) {
+ if (particlesNode != NULL && particlesNode->getAttribute("value")->getRestrictedValue() == "true" &&
+ particlesNode->hasChild("particle-file") == true) {
+ const XmlNode *pf = particlesNode->getChild("particle-file");
+ if (pf != NULL) {
+ skillParticleFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue();
+ printf("Found skill particle [%s]\n", skillParticleFile.c_str());
+ }
+ }
+ }
+ if (sn->hasChild("projectile") == true) {
+ const XmlNode *particlesProjectileNode = sn->getChild("projectile");
+ //for(int j = 0; particlesProjectileNode != NULL && particlesProjectileNode->getAttribute("value")->getRestrictedValue() == "true" &&
+ // j < particlesProjectileNode->getChildCount(); ++j) {
+ if (particlesProjectileNode != NULL && particlesProjectileNode->getAttribute("value")->getRestrictedValue() == "true" &&
+ particlesProjectileNode->hasChild("particle") == true) {
+ const XmlNode *pf = particlesProjectileNode->getChild("particle");
+ if (pf != NULL && pf->getAttribute("value")->getRestrictedValue() == "true") {
+ skillParticleProjectileFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue();
+ printf("Found skill skill projectile particle [%s]\n", skillParticleProjectileFile.c_str());
+ }
+ }
+ }
+ if (sn->hasChild("splash") == true) {
+ const XmlNode *particlesSplashNode = sn->getChild("splash");
+ //for(int j = 0; particlesSplashNode != NULL && particlesSplashNode->getAttribute("value")->getRestrictedValue() == "true" &&
+ // j < particlesSplashNode->getChildCount(); ++j) {
+ if (particlesSplashNode != NULL && particlesSplashNode->getAttribute("value")->getRestrictedValue() == "true" &&
+ particlesSplashNode->hasChild("particle") == true) {
+ const XmlNode *pf = particlesSplashNode->getChild("particle");
+ if (pf != NULL && pf->getAttribute("value")->getRestrictedValue() == "true") {
+ skillParticleSplashFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue();
+ printf("Found skill skill splash particle [%s]\n", skillParticleSplashFile.c_str());
+ }
+ }
+ }
+ }
+ }
+ }
- this->Destroy();
-}
-
-// for the mousewheel
-void MainWindow::onMouseWheelDown(wxMouseEvent &event) {
- try {
- wxPaintEvent paintEvent;
- zoom*= 1.1f;
- zoom= clamp(zoom, 0.1f, 10.0f);
-
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
-
- onPaint(paintEvent);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMouseWheelUp(wxMouseEvent &event) {
- try {
- wxPaintEvent paintEvent;
- zoom*= 0.90909f;
- zoom= clamp(zoom, 0.1f, 10.0f);
-
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
-
- onPaint(paintEvent);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-
-void MainWindow::onMouseMove(wxMouseEvent &event){
- try {
- int x= event.GetX();
- int y= event.GetY();
- wxPaintEvent paintEvent;
-
- if(event.LeftIsDown()){
- rotX+= clamp(lastX-x, -10, 10);
- rotY+= clamp(lastY-y, -10, 10);
-
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
-
- onPaint(paintEvent);
+ if (skillModelFile != "") {
+ this->modelPathList.push_back(skillModelFile);
+ printf("Added skill model [%s]\n", skillModelFile.c_str());
+ }
+ if (skillParticleFile != "") {
+ this->particlePathList.push_back(skillParticleFile);
+ printf("Added skill particle [%s]\n", skillParticleFile.c_str());
+ }
+ if (skillParticleProjectileFile != "") {
+ this->particleProjectilePathList.push_back(skillParticleProjectileFile);
+ printf("Added skill projectile particle [%s]\n", skillParticleProjectileFile.c_str());
+ }
+ if (skillParticleSplashFile != "") {
+ this->particleSplashPathList.push_back(skillParticleSplashFile);
+ printf("Added skill splash particle [%s]\n", skillParticleSplashFile.c_str());
+ }
+ }
+ SetTitle(ToUnicode(titlestring));
+ }
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a ZetaGlest particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
+ }
}
- else if(event.RightIsDown()){
- zoom*= 1.0f+(lastX-x+lastY-y)/100.0f;
- zoom= clamp(zoom, 0.1f, 10.0f);
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+ void MainWindow::loadModel(string path) {
+ try {
+ if (path != "" && fileExists(path) == true) {
+ this->modelPathList.push_back(path);
+ printf("Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n", path.c_str(), this->modelPathList.size());
+ }
+ string titlestring = winHeader;
+ for (unsigned int idx = 0; idx < this->modelPathList.size(); idx++) {
+ string modelPath = this->modelPathList[idx];
+
+ //printf("Loading model [%s] %u of " MG_SIZE_T_SPECIFIER "\n",modelPath.c_str(),idx, this->modelPathList.size());
+
+ if (timer) timer->Stop();
+ //delete model;
+ if (model != NULL && renderer != NULL) renderer->endModel(rsGlobal, model);
+ model = NULL;
+ model = renderer ? renderer->newModel(rsGlobal, modelPath) : NULL;
+
+ statusbarText = getModelInfo();
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+ if (timer) timer->Start(100);
+ titlestring = extractFileFromDirectoryPath(modelPath) + " - " + titlestring;
+ }
+ SetTitle(ToUnicode(titlestring));
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::loadParticle(string path) {
+ if (timer) timer->Stop();
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s]\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, path.c_str());
+ if (path != "" && fileExists(path) == true) {
+ renderer->end();
+ unitParticleSystems.clear();
+ unitParticleSystemTypes.clear();
+
+ if (isControlKeyPressed == true) {
+ // std::cout << "Adding to list..." << std::endl;
+ this->particlePathList.push_back(path);
+ } else {
+ // std::cout << "Clearing list..." << std::endl;
+ this->particlePathList.clear();
+ this->particlePathList.push_back(path);
+ }
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] added file [%s]\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, path.c_str());
+ }
+
+ try {
+ if (this->particlePathList.empty() == false) {
+ string titlestring = winHeader;
+ for (unsigned int idx = 0; idx < this->particlePathList.size(); idx++) {
+ string particlePath = this->particlePathList[idx];
+ string dir = extractDirectoryPathFromFile(particlePath);
+
+ size_t pos = dir.find_last_of(folderDelimiter);
+ if (pos == dir.length() - 1 && dir.length() > 0) {
+ dir.erase(dir.length() - 1);
+ }
+
+ particlePath = extractFileFromDirectoryPath(particlePath);
+ titlestring = particlePath + " - " + titlestring;
+
+ std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml";
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] looking for unit XML [%s]\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, unitXML.c_str());
+
+ //int size = -1;
+ //int height = -1;
+ int size = 0;
+ int height = 0;
+
+ if (fileExists(unitXML) == true) {
+ {
+ XmlTree xmlTree;
+ xmlTree.load(unitXML, Properties::getTagReplacementValues());
+ const XmlNode *unitNode = xmlTree.getRootNode();
+ const XmlNode *parametersNode = unitNode->getChild("parameters");
+ //size
+ size = parametersNode->getChild("size")->getAttribute("value")->getIntValue();
+ //height
+ height = parametersNode->getChild("height")->getAttribute("value")->getIntValue();
+ }
+
+ // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl;
+ } else {
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] unit XML NOT FOUND [%s] using default position values\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, unitXML.c_str());
+
+ size = 1;
+ height = 1;
+ }
+
+ std::map > > loadedFileList;
+ UnitParticleSystemType *unitParticleSystemType = new UnitParticleSystemType();
+ unitParticleSystemType->load(NULL, dir, dir + folderDelimiter + particlePath, //### if we knew which particle it was, we could be more accurate
+ renderer, loadedFileList, "g3dviewer", "");
+ unitParticleSystemTypes.push_back(unitParticleSystemType);
+
+ for (std::vector::const_iterator it = unitParticleSystemTypes.begin(); it != unitParticleSystemTypes.end(); ++it) {
+ UnitParticleSystem *ups = new UnitParticleSystem(200);
+
+ ups->setParticleType((*it));
+ (*it)->setValues(ups);
+ if (size > 0) {
+ //getCurrVectorFlat() + Vec3f(0.f, type->getHeight()/2.f, 0.f);
+ Vec3f vec = Vec3f(0.f, height / 2.f, 0.f);
+ ups->setPos(vec);
+ }
+ //ups->setFactionColor(getFaction()->getTexture()->getPixmap()->getPixel3f(0,0));
+ ups->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0, 0));
+ unitParticleSystems.push_back(ups);
+ renderer->manageParticleSystem(ups);
+
+ ups->setVisible(true);
+ }
+
+ if (path != "" && fileExists(path) == true) {
+ renderer->initModelManager();
+ if (initTextureManager) {
+ renderer->initTextureManager();
+ }
+ }
+
+ }
+ SetTitle(ToUnicode(titlestring));
+ }
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a Mega-Glest particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ if (timer) timer->Start(100);
+ }
+
+ void MainWindow::loadProjectileParticle(string path) {
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s] particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, path.c_str(), this->particleProjectilePathList.size());
+
+ if (timer) timer->Stop();
+ if (path != "" && fileExists(path) == true) {
+ renderer->end();
+ projectileParticleSystems.clear();
+ projectileParticleSystemTypes.clear();
+
+ if (isControlKeyPressed == true) {
+ // std::cout << "Adding to list..." << std::endl;
+ this->particleProjectilePathList.push_back(path);
+ } else {
+ // std::cout << "Clearing list..." << std::endl;
+ this->particleProjectilePathList.clear();
+ this->particleProjectilePathList.push_back(path);
+ }
+ }
+
+ try {
+ if (this->particleProjectilePathList.empty() == false) {
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("this->particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n", this->particleProjectilePathList.size());
+
+ string titlestring = winHeader;
+ for (unsigned int idx = 0; idx < this->particleProjectilePathList.size(); idx++) {
+ string particlePath = this->particleProjectilePathList[idx];
+ string dir = extractDirectoryPathFromFile(particlePath);
+
+ size_t pos = dir.find_last_of(folderDelimiter);
+ if (pos == dir.length() - 1) {
+ dir.erase(dir.length() - 1);
+ }
+
+ particlePath = extractFileFromDirectoryPath(particlePath);
+ titlestring = particlePath + " - " + titlestring;
+
+ std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml";
+
+ int size = 1;
+ int height = 1;
+
+ if (fileExists(unitXML) == true) {
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, unitXML.c_str(), idx);
+
+ XmlTree xmlTree;
+ xmlTree.load(unitXML, Properties::getTagReplacementValues());
+ const XmlNode *unitNode = xmlTree.getRootNode();
+ const XmlNode *parametersNode = unitNode->getChild("parameters");
+ //size
+ size = parametersNode->getChild("size")->getAttribute("value")->getIntValue();
+ //height
+ height = parametersNode->getChild("height")->getAttribute("value")->getIntValue();
+ }
+
+ // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl;
+
+ string particleFile = dir + folderDelimiter + particlePath;
+ {
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, particleFile.c_str(), idx);
+ XmlTree xmlTree;
+ xmlTree.load(particleFile, Properties::getTagReplacementValues());
+ //const XmlNode *particleSystemNode= xmlTree.getRootNode();
+
+ // std::cout << "Loaded successfully, loading values..." << std::endl;
+ }
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, particleFile.c_str(), idx);
+ std::map > > loadedFileList;
+ ParticleSystemTypeProjectile *projectileParticleSystemType = new ParticleSystemTypeProjectile();
+ projectileParticleSystemType->load(NULL, dir, //### we don't know if there are overrides in the unit XML
+ particleFile, renderer, loadedFileList,
+ "g3dviewer", "");
+
+ // std::cout << "Values loaded, about to read..." << std::endl;
+
+ projectileParticleSystemTypes.push_back(projectileParticleSystemType);
+
+ for (std::vector::const_iterator it = projectileParticleSystemTypes.begin();
+ it != projectileParticleSystemTypes.end(); ++it) {
+
+ ProjectileParticleSystem *ps = (*it)->create(NULL);
+
+ if (size > 0) {
+ Vec3f vec = Vec3f(0.f, height / 2.f, 0.f);
+ //ps->setPos(vec);
+
+ Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f);
+ ps->setPath(vec, vec2);
+ }
+ ps->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0, 0));
+
+ projectileParticleSystems.push_back(ps);
+
+ ps->setVisible(true);
+ renderer->manageParticleSystem(ps);
+ }
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loaded [%s] idx = %u\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, particleFile.c_str(), idx);
+ }
+ SetTitle(ToUnicode(titlestring));
+
+ if (path != "" && fileExists(path) == true) {
+ renderer->initModelManager();
+ if (initTextureManager) {
+ renderer->initTextureManager();
+ }
+ }
+ }
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a ZetaGlest projectile particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ if (timer) timer->Start(100);
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] after load [%s]\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, path.c_str());
+ }
+
+ void MainWindow::loadSplashParticle(string path) { // uses ParticleSystemTypeSplash::load (and own list...)
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s] particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, path.c_str(), this->particleSplashPathList.size());
+
+ if (timer) timer->Stop();
+ if (path != "" && fileExists(path) == true) {
+ renderer->end();
+ splashParticleSystems.clear();
+ splashParticleSystemTypes.clear();
+
+ if (isControlKeyPressed == true) {
+ // std::cout << "Adding to list..." << std::endl;
+ this->particleSplashPathList.push_back(path);
+ } else {
+ // std::cout << "Clearing list..." << std::endl;
+ this->particleSplashPathList.clear();
+ this->particleSplashPathList.push_back(path);
+ }
+ }
+
+ try {
+ if (this->particleSplashPathList.empty() == false) {
+ string titlestring = winHeader;
+ for (unsigned int idx = 0; idx < this->particleSplashPathList.size(); idx++) {
+ string particlePath = this->particleSplashPathList[idx];
+ string dir = extractDirectoryPathFromFile(particlePath);
+
+ size_t pos = dir.find_last_of(folderDelimiter);
+ if (pos == dir.length() - 1) {
+ dir.erase(dir.length() - 1);
+ }
+
+ particlePath = extractFileFromDirectoryPath(particlePath);
+ titlestring = particlePath + " - " + titlestring;
+
+ std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml";
+
+ int size = 1;
+ //int height = 1;
+
+ if (fileExists(unitXML) == true) {
+ XmlTree xmlTree;
+ xmlTree.load(unitXML, Properties::getTagReplacementValues());
+ const XmlNode *unitNode = xmlTree.getRootNode();
+ const XmlNode *parametersNode = unitNode->getChild("parameters");
+ //size
+ size = parametersNode->getChild("size")->getAttribute("value")->getIntValue();
+ //height
+ //height= parametersNode->getChild("height")->getAttribute("value")->getIntValue();
+ }
+
+ // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl;
+
+ {
+ XmlTree xmlTree;
+ xmlTree.load(dir + folderDelimiter + particlePath, Properties::getTagReplacementValues());
+ //const XmlNode *particleSystemNode= xmlTree.getRootNode();
+ // std::cout << "Loaded successfully, loading values..." << std::endl;
+ }
+
+ std::map > > loadedFileList;
+ ParticleSystemTypeSplash *splashParticleSystemType = new ParticleSystemTypeSplash();
+ splashParticleSystemType->load(NULL, dir, dir + folderDelimiter + particlePath, renderer, //### we don't know if there are overrides in the unit XML
+ loadedFileList, "g3dviewer", ""); // <---- only that must be splash...
+
+ // std::cout << "Values loaded, about to read..." << std::endl;
+
+ splashParticleSystemTypes.push_back(splashParticleSystemType);
+
+ //ParticleSystemTypeSplash
+ for (std::vector::const_iterator it = splashParticleSystemTypes.begin(); it != splashParticleSystemTypes.end(); ++it) {
+
+ SplashParticleSystem *ps = (*it)->create(NULL);
+
+ if (size > 0) {
+ //Vec3f vec = Vec3f(0.f, height / 2.f, 0.f);
+ //ps->setPos(vec);
+
+ //Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f); // <------- removed relative projectile
+ //ps->setPath(vec, vec2); // <------- removed relative projectile
+ }
+ ps->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0, 0));
+
+ splashParticleSystems.push_back(ps);
+
+ ps->setVisible(true);
+ renderer->manageParticleSystem(ps);
+ }
+ }
+ SetTitle(ToUnicode(titlestring));
+
+ if (path != "" && fileExists(path) == true) {
+ renderer->initModelManager();
+ if (initTextureManager) {
+ renderer->initTextureManager();
+ }
+ }
+ }
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a ZetaGlest projectile particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ if (timer) timer->Start(100);
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] after load [%s] particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__, path.c_str(), this->particleSplashPathList.size());
+ }
+
+ void MainWindow::onMenuModeNormals(wxCommandEvent &event) {
+ try {
+ renderer->toggleNormals();
+ menuMode->Check(miModeNormals, renderer->getNormals());
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuModeWireframe(wxCommandEvent &event) {
+ try {
+ renderer->toggleWireframe();
+ menuMode->Check(miModeWireframe, renderer->getWireframe());
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuModeGrid(wxCommandEvent &event) {
+ try {
+ renderer->toggleGrid();
+ menuMode->Check(miModeGrid, renderer->getGrid());
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuSpeedSlower(wxCommandEvent &event) {
+ try {
+ speed /= 1.5f;
+ if (speed < 0) {
+ speed = 0;
+ }
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuSpeedFaster(wxCommandEvent &event) {
+ try {
+ speed *= 1.5f;
+ if (speed > 1) {
+ speed = 1;
+ }
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ // set menu checkboxes to what player color is used
+ void MainWindow::onMenuColorRed(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcRed;
+ menuCustomColor->Check(miColorRed, true);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorBlue(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcBlue;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, true);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorGreen(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcGreen;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, true);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorYellow(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcYellow;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, true);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorWhite(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcWhite;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, true);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorCyan(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcCyan;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, true);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorOrange(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcOrange;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, true);
+ menuCustomColor->Check(miColorMagenta, false);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+ void MainWindow::onMenuColorMagenta(wxCommandEvent &event) {
+ try {
+ playerColor = Renderer::pcMagenta;
+ menuCustomColor->Check(miColorRed, false);
+ menuCustomColor->Check(miColorBlue, false);
+ menuCustomColor->Check(miColorGreen, false);
+ menuCustomColor->Check(miColorYellow, false);
+ menuCustomColor->Check(miColorWhite, false);
+ menuCustomColor->Check(miColorCyan, false);
+ menuCustomColor->Check(miColorOrange, false);
+ menuCustomColor->Check(miColorMagenta, true);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
+ }
+ }
+
+
+ void MainWindow::onTimer(wxTimerEvent &event) {
+ anim = anim + speed;
+ if (anim > 1.0f) {
+ anim -= 1.f;
+ resetAnimation = true;
+ }
+ wxPaintEvent paintEvent;
onPaint(paintEvent);
}
- lastX= x;
- lastY= y;
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
+ string MainWindow::getModelInfo() {
+ string str;
-void MainWindow::onMenuFileLoad(wxCommandEvent &event){
- try {
- //string fileName;
- fileDialog->SetWildcard(wxT("G3D files (*.g3d)|*.g3d;*.G3D"));
- fileDialog->SetMessage(wxT("Selecting Glest Model for current view."));
-
- if(fileDialog->ShowModal()==wxID_OK){
- modelPathList.clear();
- string file;
-#ifdef WIN32
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
- file = tmp_buf;
-
- auto_ptr wstr(Ansi2WideString(file.c_str()));
- file = utf8_encode(wstr.get());
-#else
- file = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
-#endif
-
- //loadModel((const char*)wxFNCONV(fileDialog->GetPath().c_str()));
- loadModel(file);
- }
- isControlKeyPressed = false;
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuFileLoadParticleXML(wxCommandEvent &event){
- try {
- //string fileName;
- fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml"));
-
- if(isControlKeyPressed == true) {
- fileDialog->SetMessage(wxT("Adding ZetaGlest particle to current view."));
- }
- else {
- fileDialog->SetMessage(wxT("Selecting ZetaGlest particle for current view."));
- }
-
- if(fileDialog->ShowModal()==wxID_OK){
- //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
- string file;
-#ifdef WIN32
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
- file = tmp_buf;
- auto_ptr wstr(Ansi2WideString(file.c_str()));
- file = utf8_encode(wstr.get());
-#else
- file = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
-#endif
-
- loadParticle(file);
- }
- isControlKeyPressed = false;
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuFileLoadProjectileParticleXML(wxCommandEvent &event){
- try {
- //string fileName;
- fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml"));
-
- if(isControlKeyPressed == true) {
- fileDialog->SetMessage(wxT("Adding ZetaGlest projectile particle to current view."));
- }
- else {
- fileDialog->SetMessage(wxT("Selecting ZetaGlest projectile particle for current view."));
- }
-
- if(fileDialog->ShowModal()==wxID_OK){
- //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
- string file;
-#ifdef WIN32
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
- file = tmp_buf;
- auto_ptr wstr(Ansi2WideString(file.c_str()));
- file = utf8_encode(wstr.get());
-#else
- file = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
-#endif
-
- loadProjectileParticle(file);
- }
- isControlKeyPressed = false;
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuFileLoadSplashParticleXML(wxCommandEvent &event){
- try {
- //string fileName;
- fileDialog->SetWildcard(wxT("XML files (*.xml)|*.xml"));
-
- if(isControlKeyPressed == true) {
- fileDialog->SetMessage(wxT("Adding ZetaGlest splash particle to current view."));
- }
- else {
- fileDialog->SetMessage(wxT("Selecting ZetaGlest splash particle for current view."));
- }
-
- if(fileDialog->ShowModal()==wxID_OK){
- //string path = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
- string file;
-#ifdef WIN32
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(fileDialog->GetPath());
- file = tmp_buf;
-
- auto_ptr wstr(Ansi2WideString(file.c_str()));
- file = utf8_encode(wstr.get());
-#else
- file = (const char*)wxFNCONV(fileDialog->GetPath().c_str());
-#endif
-
- loadSplashParticle(file);
- }
- isControlKeyPressed = false;
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-} // is it possible to join loadParticle(), loadProjectileParticle() and loadSplashParticle() to one method?
-
-
-void MainWindow::OnChangeColor(wxCommandEvent &event) {
- try {
- //wxColour color = colorPicker->GetColour();
- wxColourData data;
- data.SetChooseFull(true);
- for (int i = 0; i < 16; i++)
- {
- wxColour colour(i*16, i*16, i*16);
- data.SetCustomColour(i, colour);
- }
-
- wxColourDialog dialog(this, &data);
- if (dialog.ShowModal() == wxID_OK)
- {
- wxColourData retData = dialog.GetColourData();
- wxColour col = retData.GetColour();
- renderer->setBackgroundColor(col.Red()/255.0f, col.Green()/255.0f, col.Blue()/255.0f);
- }
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenumFileToggleScreenshotTransparent(wxCommandEvent &event) {
- try {
- float alpha = (event.IsChecked() == true ? 0.0f : 1.0f);
- renderer->setAlphaColor(alpha);
- //printf("alpha = %f\n",alpha);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::saveScreenshot() {
- try {
- int autoSaveScreenshotIndex = -1;
- for(unsigned int i = 0; i < autoScreenShotParams.size(); ++i) {
- if(_strnicmp(autoScreenShotParams[i].c_str(),"saveas-",7) == 0) {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
- autoSaveScreenshotIndex = i;
- break;
- }
- }
- if(autoSaveScreenshotIndex >= 0) {
- string saveAsFilename = autoScreenShotParams[autoSaveScreenshotIndex];
- saveAsFilename.erase(0,7);
-#ifdef WIN32
- FILE*f = _wfopen(utf8_decode(saveAsFilename).c_str(), L"rb");
-#else
- FILE *f= fopen(saveAsFilename.c_str(), "rb");
-#endif
- if(f == NULL) {
- renderer->saveScreen(saveAsFilename.c_str(),&overrideSize);
+ if (model != NULL) {
+ str += "Meshes: " + intToStr(model->getMeshCount());
+ str += ", Vertices: " + intToStr(model->getVertexCount());
+ str += ", Triangles: " + intToStr(model->getTriangleCount());
+ str += ", Version: " + intToStr(model->getFileVersion());
}
- else {
- if(f) {
- fclose(f);
+
+ return str;
+ }
+
+ void MainWindow::onKeyDown(wxKeyEvent &e) {
+
+ try {
+ // std::cout << "e.ControlDown() = " << e.ControlDown() << " e.GetKeyCode() = " << e.GetKeyCode() << " isCtrl = " << (e.GetKeyCode() == WXK_CONTROL) << std::endl;
+
+ // Note: This ctrl-key handling is buggy since it never resets when ctrl is released later, so I reset it at end of loadcommands for now.
+ if (e.ControlDown() == true || e.GetKeyCode() == WXK_CONTROL) {
+ isControlKeyPressed = true;
+ } else {
+ isControlKeyPressed = false;
}
- }
- }
- else {
- //string screenShotsPath = extractDirectoryPathFromFile(appPath) + string("screens/");
- string userData = Config::getInstance().getString("UserData_Root","");
- if(userData != "") {
- endPathWithSlash(userData);
- }
- string screenShotsPath = userData + string("screens/");
- printf("screenShotsPath [%s]\n",screenShotsPath.c_str());
- if(isdir(screenShotsPath.c_str()) == false) {
- createDirectoryPaths(screenShotsPath);
- }
+ // std::cout << "isControlKeyPressed = " << isControlKeyPressed << std::endl;
- string path = screenShotsPath;
- if(isdir(path.c_str()) == true) {
- //Config &config= Config::getInstance();
- //string fileFormat = config.getString("ScreenShotFileType","jpg");
- for(int i=0; i < 5000; ++i) {
- path = screenShotsPath;
- path += string("screen") + intToStr(i) + string(".") + fileFormat;
-#ifdef WIN32
- FILE*f= _wfopen(utf8_decode(path).c_str(), L"rb");
-#else
- FILE *f= fopen(path.c_str(), "rb");
-#endif
- if(f == NULL) {
- renderer->saveScreen(path,&overrideSize);
- break;
+ // here also because + and - hotkeys don't work for numpad automaticly
+ if (e.GetKeyCode() == 388) {
+ speed *= 1.5f; //numpad+
+ if (speed > 1.0) {
+ speed = 1.0;
}
- else {
- if(f) {
- fclose(f);
- }
+
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+
+ } else if (e.GetKeyCode() == 390) {
+ speed /= 1.5f; //numpad-
+ if (speed < 0) {
+ speed = 0;
}
- }
- }
- }
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
+ string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
+ GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
+ } else if (e.GetKeyCode() == 'W') {
+ glClearColor(0.6f, 0.6f, 0.6f, 1.0f); //w key //backgroundcolor constant 0.3 -> 0.6
-void MainWindow::onMenuFileSaveScreenshot(wxCommandEvent &event) {
- saveScreenshot();
-}
-
-void MainWindow::onMenuFileClearAll(wxCommandEvent &event) {
- try {
- //printf("Start onMenuFileClearAll\n");
- //fflush(stdout);
-
- modelPathList.clear();
- particlePathList.clear();
- particleProjectilePathList.clear();
- particleSplashPathList.clear(); // as above
-
- if(timer) timer->Stop();
- if(renderer) renderer->end();
-
- unitParticleSystems.clear();
- unitParticleSystemTypes.clear();
-
- projectileParticleSystems.clear();
- projectileParticleSystemTypes.clear();
- splashParticleSystems.clear(); // as above
- splashParticleSystemTypes.clear();
-
- //delete model;
- //model = NULL;
- if(model != NULL && renderer != NULL) renderer->endModel(rsGlobal, model);
- model = NULL;
-
- loadUnit("","");
- loadModel("");
- loadParticle("");
- loadProjectileParticle("");
- loadSplashParticle(""); // as above
-
- GetStatusBar()->SetStatusText(ToUnicode(statusbarText.c_str()));
- isControlKeyPressed = false;
-
- //printf("END onMenuFileClearAll\n");
- //fflush(stdout);
-
- if(timer) timer->Start(100);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuFileExit(wxCommandEvent &event) {
- Close();
-}
-
-void MainWindow::loadUnit(string path, string skillName) {
- if(path != "" && fileExists(path) == true) {
- // std::cout << "Clearing list..." << std::endl;
- this->unitPath.first = path;
- this->unitPath.second.push_back(skillName);
- }
-
- try{
- if(this->unitPath.first != "") {
- if(timer) timer->Stop();
- if(renderer) renderer->end();
-
- string titlestring = winHeader;
-
- string unitPath = this->unitPath.first;
- string dir = unitPath;
- string name= lastDir(dir);
- string path= dir + "/" + name + ".xml";
-
- titlestring = unitPath + " - "+ titlestring;
-
- std::string unitXML = path;
-
- string skillModelFile = "";
- string skillParticleFile = "";
- string skillParticleProjectileFile = "";
- string skillParticleSplashFile = "";
- bool fileFound = fileExists(unitXML);
-
- printf("Loading unit from file [%s] fileFound = %d\n",unitXML.c_str(),fileFound);
-
- if(fileFound == true) {
- XmlTree xmlTree;
- xmlTree.load(unitXML,Properties::getTagReplacementValues());
- const XmlNode *unitNode= xmlTree.getRootNode();
-
- bool foundSkillName = false;
- for(unsigned int skillIdx = 0; foundSkillName == false && skillIdx < this->unitPath.second.size(); ++skillIdx) {
- string lookipForSkillName = this->unitPath.second[skillIdx];
-
- const XmlNode *skillsNode= unitNode->getChild("skills");
- for(unsigned int i = 0; foundSkillName == false && i < skillsNode->getChildCount(); ++i) {
- const XmlNode *sn= skillsNode->getChild("skill", i);
- //const XmlNode *typeNode= sn->getChild("type");
- const XmlNode *nameNode= sn->getChild("name");
- string skillXmlName = nameNode->getAttribute("value")->getRestrictedValue();
- if(skillXmlName == lookipForSkillName) {
- printf("Found skill [%s]\n",lookipForSkillName.c_str());
- foundSkillName = true;
-
- if(sn->getChild("animation") != NULL) {
- skillModelFile = sn->getChild("animation")->getAttribute("path")->getRestrictedValue(unitPath + '/');
- printf("Found skill model [%s]\n",skillModelFile.c_str());
- }
-
- if(sn->hasChild("particles") == true) {
- const XmlNode *particlesNode= sn->getChild("particles");
- //for(int j = 0; particlesNode != NULL && particlesNode->getAttribute("value")->getRestrictedValue() == "true" &&
- // j < particlesNode->getChildCount(); ++j) {
- if(particlesNode != NULL && particlesNode->getAttribute("value")->getRestrictedValue() == "true" &&
- particlesNode->hasChild("particle-file") == true) {
- const XmlNode *pf= particlesNode->getChild("particle-file");
- if(pf != NULL) {
- skillParticleFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue();
- printf("Found skill particle [%s]\n",skillParticleFile.c_str());
- }
- }
- }
- if(sn->hasChild("projectile") == true) {
- const XmlNode *particlesProjectileNode= sn->getChild("projectile");
- //for(int j = 0; particlesProjectileNode != NULL && particlesProjectileNode->getAttribute("value")->getRestrictedValue() == "true" &&
- // j < particlesProjectileNode->getChildCount(); ++j) {
- if(particlesProjectileNode != NULL && particlesProjectileNode->getAttribute("value")->getRestrictedValue() == "true" &&
- particlesProjectileNode->hasChild("particle") == true) {
- const XmlNode *pf= particlesProjectileNode->getChild("particle");
- if(pf != NULL && pf->getAttribute("value")->getRestrictedValue() == "true") {
- skillParticleProjectileFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue();
- printf("Found skill skill projectile particle [%s]\n",skillParticleProjectileFile.c_str());
- }
- }
- }
- if(sn->hasChild("splash") == true) {
- const XmlNode *particlesSplashNode= sn->getChild("splash");
- //for(int j = 0; particlesSplashNode != NULL && particlesSplashNode->getAttribute("value")->getRestrictedValue() == "true" &&
- // j < particlesSplashNode->getChildCount(); ++j) {
- if(particlesSplashNode != NULL && particlesSplashNode->getAttribute("value")->getRestrictedValue() == "true" &&
- particlesSplashNode->hasChild("particle") == true) {
- const XmlNode *pf= particlesSplashNode->getChild("particle");
- if(pf != NULL && pf->getAttribute("value")->getRestrictedValue() == "true") {
- skillParticleSplashFile = unitPath + '/' + pf->getAttribute("path")->getRestrictedValue();
- printf("Found skill skill splash particle [%s]\n",skillParticleSplashFile.c_str());
- }
- }
- }
- }
- }
- }
-
- if(skillModelFile != "") {
- this->modelPathList.push_back(skillModelFile);
- printf("Added skill model [%s]\n",skillModelFile.c_str());
- }
- if(skillParticleFile != "") {
- this->particlePathList.push_back(skillParticleFile);
- printf("Added skill particle [%s]\n",skillParticleFile.c_str());
- }
- if(skillParticleProjectileFile != "") {
- this->particleProjectilePathList.push_back(skillParticleProjectileFile);
- printf("Added skill projectile particle [%s]\n",skillParticleProjectileFile.c_str());
- }
- if(skillParticleSplashFile != "") {
- this->particleSplashPathList.push_back(skillParticleSplashFile);
- printf("Added skill splash particle [%s]\n",skillParticleSplashFile.c_str());
- }
- }
- SetTitle(ToUnicode(titlestring));
- }
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a ZetaGlest particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::loadModel(string path) {
- try {
- if(path != "" && fileExists(path) == true) {
- this->modelPathList.push_back(path);
- printf("Adding model [%s] list size " MG_SIZE_T_SPECIFIER "\n",path.c_str(),this->modelPathList.size());
- }
-
- string titlestring=winHeader;
- for(unsigned int idx =0; idx < this->modelPathList.size(); idx++) {
- string modelPath = this->modelPathList[idx];
-
- //printf("Loading model [%s] %u of " MG_SIZE_T_SPECIFIER "\n",modelPath.c_str(),idx, this->modelPathList.size());
-
- if(timer) timer->Stop();
- //delete model;
- if(model != NULL && renderer != NULL) renderer->endModel(rsGlobal, model);
- model = NULL;
- model = renderer? renderer->newModel(rsGlobal, modelPath): NULL;
-
- statusbarText = getModelInfo();
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
- if(timer) timer->Start(100);
- titlestring = extractFileFromDirectoryPath(modelPath) + " - "+ titlestring;
- }
- SetTitle(ToUnicode(titlestring));
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::loadParticle(string path) {
- if(timer) timer->Stop();
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str());
- if(path != "" && fileExists(path) == true) {
- renderer->end();
- unitParticleSystems.clear();
- unitParticleSystemTypes.clear();
-
- if(isControlKeyPressed == true) {
- // std::cout << "Adding to list..." << std::endl;
- this->particlePathList.push_back(path);
- }
- else {
- // std::cout << "Clearing list..." << std::endl;
- this->particlePathList.clear();
- this->particlePathList.push_back(path);
- }
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] added file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str());
- }
-
- try {
- if(this->particlePathList.empty() == false) {
- string titlestring=winHeader;
- for(unsigned int idx = 0; idx < this->particlePathList.size(); idx++) {
- string particlePath = this->particlePathList[idx];
- string dir= extractDirectoryPathFromFile(particlePath);
-
- size_t pos = dir.find_last_of(folderDelimiter);
- if(pos == dir.length() - 1 && dir.length() > 0) {
- dir.erase(dir.length() -1);
- }
-
- particlePath= extractFileFromDirectoryPath(particlePath);
- titlestring = particlePath + " - "+ titlestring;
-
- std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml";
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] looking for unit XML [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitXML.c_str());
-
- //int size = -1;
- //int height = -1;
- int size = 0;
- int height= 0;
-
- if(fileExists(unitXML) == true) {
- {
- XmlTree xmlTree;
- xmlTree.load(unitXML,Properties::getTagReplacementValues());
- const XmlNode *unitNode= xmlTree.getRootNode();
- const XmlNode *parametersNode= unitNode->getChild("parameters");
- //size
- size= parametersNode->getChild("size")->getAttribute("value")->getIntValue();
- //height
- height= parametersNode->getChild("height")->getAttribute("value")->getIntValue();
}
- // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl;
- }
- else {
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] unit XML NOT FOUND [%s] using default position values\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitXML.c_str());
-
- size = 1;
- height= 1;
- }
-
- std::map > > loadedFileList;
- UnitParticleSystemType *unitParticleSystemType = new UnitParticleSystemType();
- unitParticleSystemType->load(NULL, dir, dir + folderDelimiter + particlePath, //### if we knew which particle it was, we could be more accurate
- renderer,loadedFileList,"g3dviewer","");
- unitParticleSystemTypes.push_back(unitParticleSystemType);
-
- for(std::vector::const_iterator it= unitParticleSystemTypes.begin(); it != unitParticleSystemTypes.end(); ++it) {
- UnitParticleSystem *ups= new UnitParticleSystem(200);
-
- ups->setParticleType((*it));
- (*it)->setValues(ups);
- if(size > 0) {
- //getCurrVectorFlat() + Vec3f(0.f, type->getHeight()/2.f, 0.f);
- Vec3f vec = Vec3f(0.f, height / 2.f, 0.f);
- ups->setPos(vec);
- }
- //ups->setFactionColor(getFaction()->getTexture()->getPixmap()->getPixel3f(0,0));
- ups->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0,0));
- unitParticleSystems.push_back(ups);
- renderer->manageParticleSystem(ups);
-
- ups->setVisible(true);
- }
-
- if(path != "" && fileExists(path) == true) {
- renderer->initModelManager();
- if(initTextureManager) {
- renderer->initTextureManager();
- }
- }
-
- }
- SetTitle(ToUnicode(titlestring));
- }
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a Mega-Glest particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
- }
- if(timer) timer->Start(100);
-}
-
-void MainWindow::loadProjectileParticle(string path) {
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s] particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),this->particleProjectilePathList.size());
-
- if(timer) timer->Stop();
- if(path != "" && fileExists(path) == true) {
- renderer->end();
- projectileParticleSystems.clear();
- projectileParticleSystemTypes.clear();
-
- if(isControlKeyPressed == true) {
- // std::cout << "Adding to list..." << std::endl;
- this->particleProjectilePathList.push_back(path);
- }
- else {
- // std::cout << "Clearing list..." << std::endl;
- this->particleProjectilePathList.clear();
- this->particleProjectilePathList.push_back(path);
- }
- }
-
- try {
- if(this->particleProjectilePathList.empty() == false) {
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("this->particleProjectilePathList.size() = " MG_SIZE_T_SPECIFIER "\n",this->particleProjectilePathList.size());
-
- string titlestring=winHeader;
- for(unsigned int idx = 0; idx < this->particleProjectilePathList.size(); idx++) {
- string particlePath = this->particleProjectilePathList[idx];
- string dir= extractDirectoryPathFromFile(particlePath);
-
- size_t pos = dir.find_last_of(folderDelimiter);
- if(pos == dir.length()-1) {
- dir.erase(dir.length() -1);
- }
-
- particlePath= extractFileFromDirectoryPath(particlePath);
- titlestring = particlePath + " - "+ titlestring;
-
- std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml";
-
- int size = 1;
- int height = 1;
-
- if(fileExists(unitXML) == true) {
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,unitXML.c_str(),idx);
-
- XmlTree xmlTree;
- xmlTree.load(unitXML,Properties::getTagReplacementValues());
- const XmlNode *unitNode= xmlTree.getRootNode();
- const XmlNode *parametersNode= unitNode->getChild("parameters");
- //size
- size= parametersNode->getChild("size")->getAttribute("value")->getIntValue();
- //height
- height= parametersNode->getChild("height")->getAttribute("value")->getIntValue();
- }
-
- // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl;
-
- string particleFile = dir + folderDelimiter + particlePath;
- {
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,particleFile.c_str(),idx);
- XmlTree xmlTree;
- xmlTree.load(particleFile,Properties::getTagReplacementValues());
- //const XmlNode *particleSystemNode= xmlTree.getRootNode();
-
- // std::cout << "Loaded successfully, loading values..." << std::endl;
- }
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loading [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,particleFile.c_str(),idx);
- std::map > > loadedFileList;
- ParticleSystemTypeProjectile *projectileParticleSystemType= new ParticleSystemTypeProjectile();
- projectileParticleSystemType->load(NULL, dir, //### we don't know if there are overrides in the unit XML
- particleFile,renderer, loadedFileList,
- "g3dviewer","");
-
- // std::cout << "Values loaded, about to read..." << std::endl;
-
- projectileParticleSystemTypes.push_back(projectileParticleSystemType);
-
- for(std::vector::const_iterator it= projectileParticleSystemTypes.begin();
- it != projectileParticleSystemTypes.end(); ++it) {
-
- ProjectileParticleSystem *ps = (*it)->create(NULL);
-
- if(size > 0) {
- Vec3f vec = Vec3f(0.f, height / 2.f, 0.f);
- //ps->setPos(vec);
-
- Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f);
- ps->setPath(vec, vec2);
+ // some posibility to adjust brightness:
+ /*
+ else if (e.GetKeyCode() == 322) { // Ins - Grid
+ gridBrightness += 0.1f; if (gridBrightness >1.0) gridBrightness =1.0;
}
- ps->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0,0));
-
- projectileParticleSystems.push_back(ps);
-
- ps->setVisible(true);
- renderer->manageParticleSystem(ps);
- }
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] loaded [%s] idx = %u\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,particleFile.c_str(),idx);
- }
- SetTitle(ToUnicode(titlestring));
-
- if(path != "" && fileExists(path) == true) {
- renderer->initModelManager();
- if(initTextureManager) {
- renderer->initTextureManager();
- }
- }
- }
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a ZetaGlest projectile particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
- }
- if(timer) timer->Start(100);
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] after load [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str());
-}
-
-void MainWindow::loadSplashParticle(string path) { // uses ParticleSystemTypeSplash::load (and own list...)
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] about to load [%s] particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),this->particleSplashPathList.size());
-
- if(timer) timer->Stop();
- if(path != "" && fileExists(path) == true) {
- renderer->end();
- splashParticleSystems.clear();
- splashParticleSystemTypes.clear();
-
- if(isControlKeyPressed == true) {
- // std::cout << "Adding to list..." << std::endl;
- this->particleSplashPathList.push_back(path);
- }
- else {
- // std::cout << "Clearing list..." << std::endl;
- this->particleSplashPathList.clear();
- this->particleSplashPathList.push_back(path);
- }
- }
-
- try {
- if(this->particleSplashPathList.empty() == false) {
- string titlestring=winHeader;
- for(unsigned int idx = 0; idx < this->particleSplashPathList.size(); idx++) {
- string particlePath = this->particleSplashPathList[idx];
- string dir= extractDirectoryPathFromFile(particlePath);
-
- size_t pos = dir.find_last_of(folderDelimiter);
- if(pos == dir.length()-1) {
- dir.erase(dir.length() -1);
- }
-
- particlePath= extractFileFromDirectoryPath(particlePath);
- titlestring = particlePath + " - "+ titlestring;
-
- std::string unitXML = dir + folderDelimiter + extractFileFromDirectoryPath(dir) + ".xml";
-
- int size = 1;
- //int height = 1;
-
- if(fileExists(unitXML) == true) {
- XmlTree xmlTree;
- xmlTree.load(unitXML,Properties::getTagReplacementValues());
- const XmlNode *unitNode= xmlTree.getRootNode();
- const XmlNode *parametersNode= unitNode->getChild("parameters");
- //size
- size= parametersNode->getChild("size")->getAttribute("value")->getIntValue();
- //height
- //height= parametersNode->getChild("height")->getAttribute("value")->getIntValue();
- }
-
- // std::cout << "About to load [" << particlePath << "] from [" << dir << "] unit [" << unitXML << "]" << std::endl;
-
- {
- XmlTree xmlTree;
- xmlTree.load(dir + folderDelimiter + particlePath,Properties::getTagReplacementValues());
- //const XmlNode *particleSystemNode= xmlTree.getRootNode();
- // std::cout << "Loaded successfully, loading values..." << std::endl;
- }
-
- std::map > > loadedFileList;
- ParticleSystemTypeSplash *splashParticleSystemType= new ParticleSystemTypeSplash();
- splashParticleSystemType->load(NULL, dir, dir + folderDelimiter + particlePath,renderer, //### we don't know if there are overrides in the unit XML
- loadedFileList,"g3dviewer",""); // <---- only that must be splash...
-
- // std::cout << "Values loaded, about to read..." << std::endl;
-
- splashParticleSystemTypes.push_back(splashParticleSystemType);
-
- //ParticleSystemTypeSplash
- for(std::vector::const_iterator it= splashParticleSystemTypes.begin(); it != splashParticleSystemTypes.end(); ++it) {
-
- SplashParticleSystem *ps = (*it)->create(NULL);
-
- if(size > 0) {
- //Vec3f vec = Vec3f(0.f, height / 2.f, 0.f);
- //ps->setPos(vec);
-
- //Vec3f vec2 = Vec3f(size * 2.f, height * 2.f, height * 2.f); // <------- removed relative projectile
- //ps->setPath(vec, vec2); // <------- removed relative projectile
+ else if (e.GetKeyCode() == 127) { // Del
+ gridBrightness -= 0.1f; if (gridBrightness <0) gridBrightness =0;
+ }
+ */
+ else if (e.GetKeyCode() == 313) { // Home - Background
+ backBrightness += 0.1f; if (backBrightness > 1.0) backBrightness = 1.0;
+ glClearColor(backBrightness, backBrightness, backBrightness, 1.0f);
+ } else if (e.GetKeyCode() == 312) { // End
+ backBrightness -= 0.1f; if (backBrightness < 0) backBrightness = 0;
+ glClearColor(backBrightness, backBrightness, backBrightness, 1.0f);
+ } else if (e.GetKeyCode() == 366) { // PgUp - Lightning of model
+ lightBrightness += 0.1f; if (lightBrightness > 1.0) lightBrightness = 1.0;
+ Vec4f ambientNEW = Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f);
+ glLightfv(GL_LIGHT0, GL_AMBIENT, ambientNEW.ptr());
+ } else if (e.GetKeyCode() == 367) { // pgDn
+ lightBrightness -= 0.1f; if (lightBrightness < 0) lightBrightness = 0;
+ Vec4f ambientNEW = Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f);
+ glLightfv(GL_LIGHT0, GL_AMBIENT, ambientNEW.ptr());
}
- ps->setFactionColor(renderer->getPlayerColorTexture(playerColor)->getPixmap()->getPixel3f(0,0));
- splashParticleSystems.push_back(ps);
-
- ps->setVisible(true);
- renderer->manageParticleSystem(ps);
+ std::cout << "pressed " << e.GetKeyCode() << std::endl;
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
}
}
- SetTitle(ToUnicode(titlestring));
- if(path != "" && fileExists(path) == true) {
- renderer->initModelManager();
- if(initTextureManager) {
- renderer->initTextureManager();
- }
- }
- }
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Not a ZetaGlest projectile particle XML file, or broken"), wxOK | wxICON_ERROR).ShowModal();
- }
- if(timer) timer->Start(100);
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] after load [%s] particleSplashPathList.size() = " MG_SIZE_T_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,path.c_str(),this->particleSplashPathList.size());
-}
+ void MainWindow::onMenuRestart(wxCommandEvent &event) {
+ try {
+ // std::cout << "pressed R (restart particle animation)" << std::endl;
+ if (timer) timer->Stop();
+ if (renderer) renderer->end();
-void MainWindow::onMenuModeNormals(wxCommandEvent &event){
- try {
- renderer->toggleNormals();
- menuMode->Check(miModeNormals, renderer->getNormals());
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
+ unitParticleSystems.clear();
+ unitParticleSystemTypes.clear();
+ projectileParticleSystems.clear();
+ projectileParticleSystemTypes.clear();
+ splashParticleSystems.clear(); // as above
+ splashParticleSystemTypes.clear();
-void MainWindow::onMenuModeWireframe(wxCommandEvent &event){
- try {
- renderer->toggleWireframe();
- menuMode->Check(miModeWireframe, renderer->getWireframe());
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
+ loadUnit("", "");
+ loadModel("");
+ loadParticle("");
+ loadProjectileParticle("");
+ loadSplashParticle(""); // as above
-void MainWindow::onMenuModeGrid(wxCommandEvent &event){
- try {
- renderer->toggleGrid();
- menuMode->Check(miModeGrid, renderer->getGrid());
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuSpeedSlower(wxCommandEvent &event){
- try {
- speed /= 1.5f;
- if(speed < 0) {
- speed = 0;
- }
-
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuSpeedFaster(wxCommandEvent &event){
- try {
- speed *= 1.5f;
- if(speed > 1) {
- speed = 1;
- }
-
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0 ) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-// set menu checkboxes to what player color is used
-void MainWindow::onMenuColorRed(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcRed;
- menuCustomColor->Check(miColorRed, true);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorBlue(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcBlue;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, true);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorGreen(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcGreen;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, true);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorYellow(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcYellow;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, true);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorWhite(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcWhite;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, true);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorCyan(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcCyan;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, true);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorOrange(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcOrange;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, true);
- menuCustomColor->Check(miColorMagenta, false);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-void MainWindow::onMenuColorMagenta(wxCommandEvent &event) {
- try {
- playerColor= Renderer::pcMagenta;
- menuCustomColor->Check(miColorRed, false);
- menuCustomColor->Check(miColorBlue, false);
- menuCustomColor->Check(miColorGreen, false);
- menuCustomColor->Check(miColorYellow, false);
- menuCustomColor->Check(miColorWhite, false);
- menuCustomColor->Check(miColorCyan, false);
- menuCustomColor->Check(miColorOrange, false);
- menuCustomColor->Check(miColorMagenta, true);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
-
-
-void MainWindow::onTimer(wxTimerEvent &event) {
- anim = anim + speed;
- if(anim > 1.0f){
- anim -= 1.f;
- resetAnimation = true;
- }
- wxPaintEvent paintEvent;
- onPaint(paintEvent);
-}
-
-string MainWindow::getModelInfo() {
- string str;
-
- if(model != NULL) {
- str+= "Meshes: "+intToStr(model->getMeshCount());
- str+= ", Vertices: "+intToStr(model->getVertexCount());
- str+= ", Triangles: "+intToStr(model->getTriangleCount());
- str+= ", Version: "+intToStr(model->getFileVersion());
- }
-
- return str;
-}
-
-void MainWindow::onKeyDown(wxKeyEvent &e) {
-
- try {
- // std::cout << "e.ControlDown() = " << e.ControlDown() << " e.GetKeyCode() = " << e.GetKeyCode() << " isCtrl = " << (e.GetKeyCode() == WXK_CONTROL) << std::endl;
-
- // Note: This ctrl-key handling is buggy since it never resets when ctrl is released later, so I reset it at end of loadcommands for now.
- if(e.ControlDown() == true || e.GetKeyCode() == WXK_CONTROL) {
- isControlKeyPressed = true;
- }
- else {
- isControlKeyPressed = false;
- }
-
- // std::cout << "isControlKeyPressed = " << isControlKeyPressed << std::endl;
-
-
- // here also because + and - hotkeys don't work for numpad automaticly
- if (e.GetKeyCode() == 388) {
- speed *= 1.5f; //numpad+
- if(speed > 1.0) {
- speed = 1.0;
+ renderer->initModelManager();
+ if (initTextureManager) {
+ renderer->initTextureManager();
+ }
+ if (timer) timer->Start(100);
+ } catch (std::runtime_error &e) {
+ std::cout << e.what() << std::endl;
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
}
-
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
-
- }
- else if (e.GetKeyCode() == 390) {
- speed /= 1.5f; //numpad-
- if(speed < 0) {
- speed = 0;
- }
- string statusTextValue = statusbarText + " animation speed: " + floatToStr(speed * 1000.0) + " anim value: " + floatToStr(anim) + " zoom: " + floatToStr(zoom) + " rotX: " + floatToStr(rotX) + " rotY: " + floatToStr(rotY);
- GetStatusBar()->SetStatusText(ToUnicode(statusTextValue.c_str()));
- }
- else if (e.GetKeyCode() == 'W') {
- glClearColor(0.6f, 0.6f, 0.6f, 1.0f); //w key //backgroundcolor constant 0.3 -> 0.6
-
}
- // some posibility to adjust brightness:
- /*
- else if (e.GetKeyCode() == 322) { // Ins - Grid
- gridBrightness += 0.1f; if (gridBrightness >1.0) gridBrightness =1.0;
- }
- else if (e.GetKeyCode() == 127) { // Del
- gridBrightness -= 0.1f; if (gridBrightness <0) gridBrightness =0;
- }
- */
- else if (e.GetKeyCode() == 313) { // Home - Background
- backBrightness += 0.1f; if (backBrightness >1.0) backBrightness=1.0;
- glClearColor(backBrightness, backBrightness, backBrightness, 1.0f);
- }
- else if (e.GetKeyCode() == 312) { // End
- backBrightness -= 0.1f; if (backBrightness<0) backBrightness=0;
- glClearColor(backBrightness, backBrightness, backBrightness, 1.0f);
- }
- else if (e.GetKeyCode() == 366) { // PgUp - Lightning of model
- lightBrightness += 0.1f; if (lightBrightness >1.0) lightBrightness =1.0;
- Vec4f ambientNEW= Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f);
- glLightfv(GL_LIGHT0,GL_AMBIENT, ambientNEW.ptr());
- }
- else if (e.GetKeyCode() == 367) { // pgDn
- lightBrightness -= 0.1f; if (lightBrightness <0) lightBrightness =0;
- Vec4f ambientNEW= Vec4f(lightBrightness, lightBrightness, lightBrightness, 1.0f);
- glLightfv(GL_LIGHT0,GL_AMBIENT, ambientNEW.ptr());
- }
+ BEGIN_EVENT_TABLE(MainWindow, wxFrame)
+ EVT_TIMER(-1, MainWindow::onTimer)
+ EVT_CLOSE(MainWindow::onClose)
+ EVT_MENU(miFileLoad, MainWindow::onMenuFileLoad)
+ EVT_MENU(miFileLoadParticleXML, MainWindow::onMenuFileLoadParticleXML)
+ EVT_MENU(miFileLoadProjectileParticleXML, MainWindow::onMenuFileLoadProjectileParticleXML)
+ EVT_MENU(miFileLoadSplashParticleXML, MainWindow::onMenuFileLoadSplashParticleXML)
+ EVT_MENU(miFileClearAll, MainWindow::onMenuFileClearAll)
+ EVT_MENU(miFileToggleScreenshotTransparent, MainWindow::onMenumFileToggleScreenshotTransparent)
+ EVT_MENU(miFileSaveScreenshot, MainWindow::onMenuFileSaveScreenshot)
+ EVT_MENU(wxID_EXIT, MainWindow::onMenuFileExit)
- std::cout << "pressed " << e.GetKeyCode() << std::endl;
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
+ EVT_MENU(miModeWireframe, MainWindow::onMenuModeWireframe)
+ EVT_MENU(miModeNormals, MainWindow::onMenuModeNormals)
+ EVT_MENU(miModeGrid, MainWindow::onMenuModeGrid)
-void MainWindow::onMenuRestart(wxCommandEvent &event) {
- try {
- // std::cout << "pressed R (restart particle animation)" << std::endl;
- if(timer) timer->Stop();
- if(renderer) renderer->end();
+ EVT_MENU(miSpeedFaster, MainWindow::onMenuSpeedFaster)
+ EVT_MENU(miSpeedSlower, MainWindow::onMenuSpeedSlower)
+ EVT_MENU(miRestart, MainWindow::onMenuRestart)
- unitParticleSystems.clear();
- unitParticleSystemTypes.clear();
- projectileParticleSystems.clear();
- projectileParticleSystemTypes.clear();
- splashParticleSystems.clear(); // as above
- splashParticleSystemTypes.clear();
+ EVT_MENU(miColorRed, MainWindow::onMenuColorRed)
+ EVT_MENU(miColorBlue, MainWindow::onMenuColorBlue)
+ EVT_MENU(miColorGreen, MainWindow::onMenuColorGreen)
+ EVT_MENU(miColorYellow, MainWindow::onMenuColorYellow)
+ EVT_MENU(miColorWhite, MainWindow::onMenuColorWhite)
+ EVT_MENU(miColorCyan, MainWindow::onMenuColorCyan)
+ EVT_MENU(miColorOrange, MainWindow::onMenuColorOrange)
+ EVT_MENU(miColorMagenta, MainWindow::onMenuColorMagenta)
- loadUnit("", "");
- loadModel("");
- loadParticle("");
- loadProjectileParticle("");
- loadSplashParticle(""); // as above
+ EVT_MENU(miChangeBackgroundColor, MainWindow::OnChangeColor)
+ END_EVENT_TABLE()
- renderer->initModelManager();
- if(initTextureManager) {
- renderer->initTextureManager();
- }
- if(timer) timer->Start(100);
- }
- catch(std::runtime_error &e) {
- std::cout << e.what() << std::endl;
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Error"), wxOK | wxICON_ERROR).ShowModal();
- }
-}
+ // =====================================================
+ // class GlCanvas
+ // =====================================================
-BEGIN_EVENT_TABLE(MainWindow, wxFrame)
- EVT_TIMER(-1, MainWindow::onTimer)
- EVT_CLOSE(MainWindow::onClose)
- EVT_MENU(miFileLoad, MainWindow::onMenuFileLoad)
- EVT_MENU(miFileLoadParticleXML, MainWindow::onMenuFileLoadParticleXML)
- EVT_MENU(miFileLoadProjectileParticleXML, MainWindow::onMenuFileLoadProjectileParticleXML)
- EVT_MENU(miFileLoadSplashParticleXML, MainWindow::onMenuFileLoadSplashParticleXML)
- EVT_MENU(miFileClearAll, MainWindow::onMenuFileClearAll)
- EVT_MENU(miFileToggleScreenshotTransparent, MainWindow::onMenumFileToggleScreenshotTransparent)
- EVT_MENU(miFileSaveScreenshot, MainWindow::onMenuFileSaveScreenshot)
- EVT_MENU(wxID_EXIT, MainWindow::onMenuFileExit)
-
- EVT_MENU(miModeWireframe, MainWindow::onMenuModeWireframe)
- EVT_MENU(miModeNormals, MainWindow::onMenuModeNormals)
- EVT_MENU(miModeGrid, MainWindow::onMenuModeGrid)
-
- EVT_MENU(miSpeedFaster, MainWindow::onMenuSpeedFaster)
- EVT_MENU(miSpeedSlower, MainWindow::onMenuSpeedSlower)
- EVT_MENU(miRestart, MainWindow::onMenuRestart)
-
- EVT_MENU(miColorRed, MainWindow::onMenuColorRed)
- EVT_MENU(miColorBlue, MainWindow::onMenuColorBlue)
- EVT_MENU(miColorGreen, MainWindow::onMenuColorGreen)
- EVT_MENU(miColorYellow, MainWindow::onMenuColorYellow)
- EVT_MENU(miColorWhite, MainWindow::onMenuColorWhite)
- EVT_MENU(miColorCyan, MainWindow::onMenuColorCyan)
- EVT_MENU(miColorOrange, MainWindow::onMenuColorOrange)
- EVT_MENU(miColorMagenta, MainWindow::onMenuColorMagenta)
-
- EVT_MENU(miChangeBackgroundColor, MainWindow::OnChangeColor)
-END_EVENT_TABLE()
-
-// =====================================================
-// class GlCanvas
-// =====================================================
-
-void translateCoords(wxWindow *wnd, int &x, int &y) {
+ void translateCoords(wxWindow *wnd, int &x, int &y) {
#ifdef WIN32
- int cx, cy;
- wnd->GetPosition(&cx, &cy);
- x += cx;
- y += cy;
+ int cx, cy;
+ wnd->GetPosition(&cx, &cy);
+ x += cx;
+ y += cy;
#endif
-}
+ }
-// to prevent flicker
-GlCanvas::GlCanvas(MainWindow * mainWindow, int *args)
+ // to prevent flicker
+ GlCanvas::GlCanvas(MainWindow * mainWindow, int *args)
#if wxCHECK_VERSION(2, 9, 1)
- : wxGLCanvas(mainWindow, wxID_ANY, args, wxDefaultPosition, mainWindow->GetClientSize(), wxFULL_REPAINT_ON_RESIZE, wxT("GLCanvas")) {
- this->context = new wxGLContext(this);
+ : wxGLCanvas(mainWindow, wxID_ANY, args, wxDefaultPosition, mainWindow->GetClientSize(), wxFULL_REPAINT_ON_RESIZE, wxT("GLCanvas")) {
+ this->context = new wxGLContext(this);
#else
- : wxGLCanvas(mainWindow, -1, wxDefaultPosition, wxDefaultSize, 0, wxT("GLCanvas"), args) {
- this->context = NULL;
+ : wxGLCanvas(mainWindow, -1, wxDefaultPosition, wxDefaultSize, 0, wxT("GLCanvas"), args) {
+ this->context = NULL;
#endif
- this->mainWindow = mainWindow;
-}
+ this->mainWindow = mainWindow;
+ }
-GlCanvas::~GlCanvas() {
- if(this->context) {
- delete this->context;
- }
- this->context = NULL;
-}
+ GlCanvas::~GlCanvas() {
+ if (this->context) {
+ delete this->context;
+ }
+ this->context = NULL;
+ }
-void GlCanvas::setCurrentGLContext() {
+ void GlCanvas::setCurrentGLContext() {
#ifndef __APPLE__
#if wxCHECK_VERSION(3, 0, 0)
- //printf("Setting glcontext 3x!\n");
+ //printf("Setting glcontext 3x!\n");
- //if(!IsShown()) {}
- if(this->context == NULL) {
- //printf("Make new ctx!\n");
- this->context = new wxGLContext(this);
- //printf("Set ctx [%p]\n",this->context);
- }
+ //if(!IsShown()) {}
+ if (this->context == NULL) {
+ //printf("Make new ctx!\n");
+ this->context = new wxGLContext(this);
+ //printf("Set ctx [%p]\n",this->context);
+ }
#elif wxCHECK_VERSION(2, 9, 1)
- //printf("Setting glcontext 29x!\n");
+ //printf("Setting glcontext 29x!\n");
- //if(!IsShown()) {}
- if(this->context == NULL) {
- this->context = new wxGLContext(this);
- //printf("Set ctx [%p]\n",this->context);
- }
+ //if(!IsShown()) {}
+ if (this->context == NULL) {
+ this->context = new wxGLContext(this);
+ //printf("Set ctx [%p]\n",this->context);
+ }
#endif
- //printf("Set ctx [%p]\n",this->context);
- if(this->context) {
- wxGLCanvas::SetCurrent(*this->context);
- //printf("Set ctx2 [%p]\n",this->context);
- }
+ //printf("Set ctx [%p]\n",this->context);
+ if (this->context) {
+ wxGLCanvas::SetCurrent(*this->context);
+ //printf("Set ctx2 [%p]\n",this->context);
+ }
#else
- this->SetCurrent();
+ this->SetCurrent();
#endif
-}
+ }
-// for the mousewheel
-void GlCanvas::onMouseWheel(wxMouseEvent &event) {
- if(event.GetWheelRotation()>0) mainWindow->onMouseWheelDown(event);
- else mainWindow->onMouseWheelUp(event);
-}
+ // for the mousewheel
+ void GlCanvas::onMouseWheel(wxMouseEvent &event) {
+ if (event.GetWheelRotation() > 0) mainWindow->onMouseWheelDown(event);
+ else mainWindow->onMouseWheelUp(event);
+ }
-void GlCanvas::onMouseMove(wxMouseEvent &event){
- mainWindow->onMouseMove(event);
-}
+ void GlCanvas::onMouseMove(wxMouseEvent &event) {
+ mainWindow->onMouseMove(event);
+ }
-void GlCanvas::onKeyDown(wxKeyEvent &event) {
- int x, y;
- event.GetPosition(&x, &y);
- translateCoords(this, x, y);
- mainWindow->onKeyDown(event);
-}
+ void GlCanvas::onKeyDown(wxKeyEvent &event) {
+ int x, y;
+ event.GetPosition(&x, &y);
+ translateCoords(this, x, y);
+ mainWindow->onKeyDown(event);
+ }
-void GlCanvas::OnSize(wxSizeEvent&event) {
+ void GlCanvas::OnSize(wxSizeEvent&event) {
- //printf("OnSize %dx%d\n",event.m_size.GetWidth(),event.m_size.GetHeight());
- Update();
-}
+ //printf("OnSize %dx%d\n",event.m_size.GetWidth(),event.m_size.GetHeight());
+ Update();
+ }
-// EVT_SPIN_DOWN(GlCanvas::onMouseDown)
-// EVT_SPIN_UP(GlCanvas::onMouseDown)
-// EVT_MIDDLE_DOWN(GlCanvas::onMouseWheel)
-// EVT_MIDDLE_UP(GlCanvas::onMouseWheel)
+ // EVT_SPIN_DOWN(GlCanvas::onMouseDown)
+ // EVT_SPIN_UP(GlCanvas::onMouseDown)
+ // EVT_MIDDLE_DOWN(GlCanvas::onMouseWheel)
+ // EVT_MIDDLE_UP(GlCanvas::onMouseWheel)
-BEGIN_EVENT_TABLE(GlCanvas, wxGLCanvas)
- EVT_MOUSEWHEEL(GlCanvas::onMouseWheel)
- EVT_MOTION(GlCanvas::onMouseMove)
- EVT_KEY_DOWN(GlCanvas::onKeyDown)
- EVT_SIZE(GlCanvas::OnSize)
-END_EVENT_TABLE()
+ BEGIN_EVENT_TABLE(GlCanvas, wxGLCanvas)
+ EVT_MOUSEWHEEL(GlCanvas::onMouseWheel)
+ EVT_MOTION(GlCanvas::onMouseMove)
+ EVT_KEY_DOWN(GlCanvas::onKeyDown)
+ EVT_SIZE(GlCanvas::OnSize)
+ END_EVENT_TABLE()
-// ===============================================
-// class App
-// ===============================================
+ // ===============================================
+ // class App
+ // ===============================================
-bool App::OnInit() {
- SystemFlags::VERBOSE_MODE_ENABLED = false;
+ bool App::OnInit() {
+ SystemFlags::VERBOSE_MODE_ENABLED = false;
#if defined(wxMAJOR_VERSION) && defined(wxMINOR_VERSION) && defined(wxRELEASE_NUMBER) && defined(wxSUBRELEASE_NUMBER)
- printf("Using wxWidgets version [%d.%d.%d.%d]\n",wxMAJOR_VERSION,wxMINOR_VERSION,wxRELEASE_NUMBER,wxSUBRELEASE_NUMBER);
+ printf("Using wxWidgets version [%d.%d.%d.%d]\n", wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, wxSUBRELEASE_NUMBER);
#endif
- string modelPath="";
- string particlePath="";
- string projectileParticlePath="";
- string splashParticlePath="";
+ string modelPath = "";
+ string particlePath = "";
+ string projectileParticlePath = "";
+ string splashParticlePath = "";
- bool foundInvalidArgs = false;
- const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]);
- for(int idx = 1; idx < argc; ++idx) {
+ bool foundInvalidArgs = false;
+ const int knownArgCount = sizeof(GAME_ARGS) / sizeof(GAME_ARGS[0]);
+ for (int idx = 1; idx < argc; ++idx) {
#if wxCHECK_VERSION(2, 9, 1)
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx].wc_str());
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx].wc_str());
#else
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]);
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(argv[idx]);
#endif
-if( hasCommandArgument(knownArgCount, (wxChar**)&GAME_ARGS[0], (const char *)tmp_buf, NULL, 0, true) == false &&
- argv[idx][0] == '-') {
- foundInvalidArgs = true;
+ if (hasCommandArgument(knownArgCount, (wxChar**) &GAME_ARGS[0], (const char *) tmp_buf, NULL, 0, true) == false &&
+ argv[idx][0] == '-') {
+ foundInvalidArgs = true;
- printf("\nInvalid argument: %s",(const char*)tmp_buf);
- }
- }
-
- if(foundInvalidArgs == true ||
- hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP])) == true) {
- printParameterHelp(static_cast(WX2CHR(argv[0])), foundInvalidArgs);
- return false;
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_VERBOSE])) == true) {
- SystemFlags::VERBOSE_MODE_ENABLED = true;
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])) == true) {
- autoScreenShotAndExit = true;
-
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]);
- //printf("param = [%s]\n",(const char*)param);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
-#if wxCHECK_VERSION(2, 9, 1)
- string options = argv[foundParamIndIndex].ToStdString();
-#else
- string options = (const char *)wxConvCurrent->cWX2MB(argv[foundParamIndIndex]);
-#endif
- vector paramPartTokens;
- Tokenize(options,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- string optionsValue = paramPartTokens[1];
-
- autoScreenShotParams.clear();
- Tokenize(optionsValue,autoScreenShotParams,",");
-
- for(unsigned int i = 0; i < autoScreenShotParams.size(); ++i) {
-
-#ifdef WIN32
- auto_ptr wstr(Ansi2WideString(autoScreenShotParams[i].c_str()));
- autoScreenShotParams[i] = utf8_encode(wstr.get());
-#endif
-
- if(_strnicmp(autoScreenShotParams[i].c_str(),"resize-",7) == 0) {
- printf("Screenshot option [%s]\n",autoScreenShotParams[i].c_str());
-
- string resize = autoScreenShotParams[i];
- resize = resize.erase(0,7);
- vector values;
- Tokenize(resize,values,"x");
- overrideSize.first = strToInt(values[0]);
- overrideSize.second = strToInt(values[1]);
-
- Renderer::windowX= 0;
- Renderer::windowY= 0;
- Renderer::windowW = overrideSize.first;
- Renderer::windowH = overrideSize.second + 25;
+ printf("\nInvalid argument: %s", (const char*) tmp_buf);
}
}
- }
- }
- std::pair > unitToLoad;
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]);
- //printf("param = [%s]\n",(const char*)param);
+ if (foundInvalidArgs == true ||
+ hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_HELP])) == true) {
+ printParameterHelp(static_cast(WX2CHR(argv[0])), foundInvalidArgs);
+ return false;
+ }
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string customPath = static_cast(WX2CHR(argv[foundParamIndIndex]));
- vector paramPartTokens;
- Tokenize(customPath,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- string customPathValue = paramPartTokens[1];
- std::vector delimitedList;
- Tokenize(customPathValue,delimitedList,",");
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_VERBOSE])) == true) {
+ SystemFlags::VERBOSE_MODE_ENABLED = true;
+ }
- if(delimitedList.size() >= 2) {
- unitToLoad.first = delimitedList[0];
- #ifdef WIN32
- auto_ptr wstr(Ansi2WideString(unitToLoad.first.c_str()));
- unitToLoad.first = utf8_encode(wstr.get());
- #endif
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT])) == true) {
+ autoScreenShotAndExit = true;
- for(unsigned int i = 1; i < delimitedList.size(); ++i) {
- string value = delimitedList[i];
- #ifdef WIN32
- auto_ptr wstr(Ansi2WideString(value.c_str()));
- value = utf8_encode(wstr.get());
- #endif
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_AUTO_SCREENSHOT]);
+ //printf("param = [%s]\n",(const char*)param);
- unitToLoad.second.push_back(value);
- }
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
-
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])) == true &&
- hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == false) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]);
- //printf("param = [%s]\n",(const char*)param);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(customPath,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- string customPathValue = paramPartTokens[1];
- modelPath = customPathValue;
- #ifdef WIN32
- auto_ptr wstr(Ansi2WideString(modelPath.c_str()));
- modelPath = utf8_encode(wstr.get());
- #endif
-
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n",(const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])) == true &&
- hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == false) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]);
- //printf("param = [%s]\n",(const char*)param);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(customPath,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- string customPathValue = paramPartTokens[1];
- particlePath = customPathValue;
- #ifdef WIN32
- auto_ptr wstr(Ansi2WideString(particlePath.c_str()));
- particlePath = utf8_encode(wstr.get());
- #endif
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]);
- //printf("param = [%s]\n",(const char*)param);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(customPath,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- string customPathValue = paramPartTokens[1];
- projectileParticlePath = customPathValue;
- #ifdef WIN32
- auto_ptr wstr(Ansi2WideString(projectileParticlePath.c_str()));
- projectileParticlePath = utf8_encode(wstr.get());
- #endif
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]);
- //printf("param = [%s]\n",(const char*)param);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string customPath = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(customPath,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- string customPathValue = paramPartTokens[1];
- splashParticlePath = customPathValue;
- #ifdef WIN32
- auto_ptr wstr(Ansi2WideString(splashParticlePath.c_str()));
- splashParticlePath = utf8_encode(wstr.get());
- #endif
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- float newAnimValue = 0.0f;
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string value = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(value,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- newAnimValue = strToFloat(paramPartTokens[1]);
- printf("newAnimValue = %f\n",newAnimValue);
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- int newParticleLoopValue = 1;
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string value = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(value,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- newParticleLoopValue = strToInt(paramPartTokens[1]);
- //printf("newParticleLoopValue = %d\n",newParticleLoopValue);
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- float newZoomValue = 1.0f;
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string value = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(value,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- newZoomValue = strToFloat(paramPartTokens[1]);
- //printf("newAnimValue = %f\n",newAnimValue);
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- float newXRotValue = 0.0f;
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string value = (const char*)WX2CHR(argv[foundParamIndIndex]);
- vector paramPartTokens;
- Tokenize(value,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- newXRotValue = strToFloat(paramPartTokens[1]);
- //printf("newAnimValue = %f\n",newAnimValue);
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*)WX2CHR(argv[foundParamIndIndex]),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- float newYRotValue = 0.0f;
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string value = static_cast(WX2CHR(argv[foundParamIndIndex]));
- vector paramPartTokens;
- Tokenize(value,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- newYRotValue = strToFloat(paramPartTokens[1]);
- //printf("newAnimValue = %f\n",newAnimValue);
- }
- else {
- printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])),(paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- if(hasCommandArgument(argc, argv,(const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])) == true) {
- const wxWX2MBbuf param = (const char *)wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]);
-
- int foundParamIndIndex = -1;
- hasCommandArgument(argc, argv,string((const char*)param) + string("="),&foundParamIndIndex);
- if(foundParamIndIndex < 0) {
- hasCommandArgument(argc, argv,(const char*)param,&foundParamIndIndex);
- }
- //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
- string value = static_cast(WX2CHR(argv[foundParamIndIndex]));
- vector paramPartTokens;
- Tokenize(value,paramPartTokens,"=");
- if(paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
- fileFormat = paramPartTokens[1];
- }
- else {
- printf("\nInvalid value specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
- printParameterHelp(WX2CHR(argv[0]),false);
- return false;
- }
- }
-
- if(argc == 2 && argv[1][0] != '-') {
-
-//#if defined(__MINGW32__)
-#ifdef WIN32
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(argv[1]));
- modelPath = tmp_buf;
- auto_ptr wstr(Ansi2WideString(modelPath.c_str()));
- modelPath = utf8_encode(wstr.get());
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+#if wxCHECK_VERSION(2, 9, 1)
+ string options = argv[foundParamIndIndex].ToStdString();
#else
- modelPath = static_cast(WX2CHR(argv[1]));
+ string options = (const char *) wxConvCurrent->cWX2MB(argv[foundParamIndIndex]);
+#endif
+ vector paramPartTokens;
+ Tokenize(options, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ string optionsValue = paramPartTokens[1];
+
+ autoScreenShotParams.clear();
+ Tokenize(optionsValue, autoScreenShotParams, ",");
+
+ for (unsigned int i = 0; i < autoScreenShotParams.size(); ++i) {
+
+#ifdef WIN32
+ auto_ptr wstr(Ansi2WideString(autoScreenShotParams[i].c_str()));
+ autoScreenShotParams[i] = utf8_encode(wstr.get());
#endif
-//#else
-// modelPath = wxFNCONV(argv[1]);
-//#endif
+ if (_strnicmp(autoScreenShotParams[i].c_str(), "resize-", 7) == 0) {
+ printf("Screenshot option [%s]\n", autoScreenShotParams[i].c_str());
- }
+ string resize = autoScreenShotParams[i];
+ resize = resize.erase(0, 7);
+ vector values;
+ Tokenize(resize, values, "x");
+ overrideSize.first = strToInt(values[0]);
+ overrideSize.second = strToInt(values[1]);
-//#if defined(__MINGW32__)
-// const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(argv[0]));
-// appPath = tmp_buf;
-//#else
-// appPath = wxFNCONV(argv[0]);
-//#endif
-// printf("appPath [%s]\n",argv[0]);
+ Renderer::windowX = 0;
+ Renderer::windowY = 0;
+ Renderer::windowW = overrideSize.first;
+ Renderer::windowH = overrideSize.second + 25;
+ }
+ }
+ }
+ }
- wxString exe_path = wxStandardPaths::Get().GetExecutablePath();
- //wxString path_separator = wxFileName::GetPathSeparator();
- //exe_path = exe_path.BeforeLast(path_separator[0]);
- //exe_path += path_separator;
+ std::pair > unitToLoad;
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_UNIT]);
+ //printf("param = [%s]\n",(const char*)param);
-//#if defined(__MINGW32__)
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string customPath = static_cast(WX2CHR(argv[foundParamIndIndex]));
+ vector paramPartTokens;
+ Tokenize(customPath, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ string customPathValue = paramPartTokens[1];
+ std::vector delimitedList;
+ Tokenize(customPathValue, delimitedList, ",");
+
+ if (delimitedList.size() >= 2) {
+ unitToLoad.first = delimitedList[0];
#ifdef WIN32
- const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(exe_path));
- string appPath = tmp_buf;
-
- auto_ptr wstr(Ansi2WideString(appPath.c_str()));
- appPath = utf8_encode(wstr.get());
-#else
- string appPath(static_cast(WX2CHR(exe_path)));
+ auto_ptr wstr(Ansi2WideString(unitToLoad.first.c_str()));
+ unitToLoad.first = utf8_encode(wstr.get());
#endif
-//#else
-// appPath = wxFNCONV(exe_path);
-//#endif
+ for (unsigned int i = 1; i < delimitedList.size(); ++i) {
+ string value = delimitedList[i];
+#ifdef WIN32
+ auto_ptr wstr(Ansi2WideString(value.c_str()));
+ value = utf8_encode(wstr.get());
+#endif
-// printf("#2 appPath [%s]\n",appPath.c_str());
+ unitToLoad.second.push_back(value);
+ }
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
- mainWindow= new MainWindow( unitToLoad,
- modelPath,
- particlePath,
- projectileParticlePath,
- splashParticlePath,
- newAnimValue,
- newParticleLoopValue,
- newZoomValue,
- newXRotValue,
- newYRotValue,
- appPath);
- if(autoScreenShotAndExit == true) {
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL])) == true &&
+ hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == false) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL]);
+ //printf("param = [%s]\n",(const char*)param);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string customPath = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(customPath, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ string customPathValue = paramPartTokens[1];
+ modelPath = customPathValue;
+#ifdef WIN32
+ auto_ptr wstr(Ansi2WideString(modelPath.c_str()));
+ modelPath = utf8_encode(wstr.get());
+#endif
+
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE])) == true &&
+ hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == false) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE]);
+ //printf("param = [%s]\n",(const char*)param);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string customPath = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(customPath, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ string customPathValue = paramPartTokens[1];
+ particlePath = customPathValue;
+#ifdef WIN32
+ auto_ptr wstr(Ansi2WideString(particlePath.c_str()));
+ particlePath = utf8_encode(wstr.get());
+#endif
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_PROJECTILE]);
+ //printf("param = [%s]\n",(const char*)param);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string customPath = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(customPath, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ string customPathValue = paramPartTokens[1];
+ projectileParticlePath = customPathValue;
+#ifdef WIN32
+ auto_ptr wstr(Ansi2WideString(projectileParticlePath.c_str()));
+ projectileParticlePath = utf8_encode(wstr.get());
+#endif
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_SPLASH]);
+ //printf("param = [%s]\n",(const char*)param);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string customPath = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(customPath, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ string customPathValue = paramPartTokens[1];
+ splashParticlePath = customPathValue;
+#ifdef WIN32
+ auto_ptr wstr(Ansi2WideString(splashParticlePath.c_str()));
+ splashParticlePath = utf8_encode(wstr.get());
+#endif
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ float newAnimValue = 0.0f;
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_MODEL_ANIMATION_VALUE]);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string value = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(value, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ newAnimValue = strToFloat(paramPartTokens[1]);
+ printf("newAnimValue = %f\n", newAnimValue);
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ int newParticleLoopValue = 1;
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_LOAD_PARTICLE_LOOP_VALUE]);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string value = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(value, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ newParticleLoopValue = strToInt(paramPartTokens[1]);
+ //printf("newParticleLoopValue = %d\n",newParticleLoopValue);
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ float newZoomValue = 1.0f;
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ZOOM_VALUE]);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string value = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(value, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ newZoomValue = strToFloat(paramPartTokens[1]);
+ //printf("newAnimValue = %f\n",newAnimValue);
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ float newXRotValue = 0.0f;
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_X_VALUE]);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string value = (const char*) WX2CHR(argv[foundParamIndIndex]);
+ vector paramPartTokens;
+ Tokenize(value, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ newXRotValue = strToFloat(paramPartTokens[1]);
+ //printf("newAnimValue = %f\n",newAnimValue);
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", (const char*) WX2CHR(argv[foundParamIndIndex]), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ float newYRotValue = 0.0f;
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_ROTATE_Y_VALUE]);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string value = static_cast(WX2CHR(argv[foundParamIndIndex]));
+ vector paramPartTokens;
+ Tokenize(value, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ newYRotValue = strToFloat(paramPartTokens[1]);
+ //printf("newAnimValue = %f\n",newAnimValue);
+ } else {
+ printf("\nInvalid path specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ if (hasCommandArgument(argc, argv, (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT])) == true) {
+ const wxWX2MBbuf param = (const char *) wxConvCurrent->cWX2MB(GAME_ARGS[GAME_ARG_SCREENSHOT_FORMAT]);
+
+ int foundParamIndIndex = -1;
+ hasCommandArgument(argc, argv, string((const char*) param) + string("="), &foundParamIndIndex);
+ if (foundParamIndIndex < 0) {
+ hasCommandArgument(argc, argv, (const char*) param, &foundParamIndIndex);
+ }
+ //printf("foundParamIndIndex = %d\n",foundParamIndIndex);
+ string value = static_cast(WX2CHR(argv[foundParamIndIndex]));
+ vector paramPartTokens;
+ Tokenize(value, paramPartTokens, "=");
+ if (paramPartTokens.size() >= 2 && paramPartTokens[1].length() > 0) {
+ fileFormat = paramPartTokens[1];
+ } else {
+ printf("\nInvalid value specified on commandline [%s] value [%s]\n\n", static_cast(WX2CHR(argv[foundParamIndIndex])), (paramPartTokens.size() >= 2 ? paramPartTokens[1].c_str() : NULL));
+ printParameterHelp(WX2CHR(argv[0]), false);
+ return false;
+ }
+ }
+
+ if (argc == 2 && argv[1][0] != '-') {
+
+ //#if defined(__MINGW32__)
+#ifdef WIN32
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(argv[1]));
+ modelPath = tmp_buf;
+ auto_ptr wstr(Ansi2WideString(modelPath.c_str()));
+ modelPath = utf8_encode(wstr.get());
+#else
+ modelPath = static_cast(WX2CHR(argv[1]));
+#endif
+
+ //#else
+ // modelPath = wxFNCONV(argv[1]);
+ //#endif
+
+ }
+
+ //#if defined(__MINGW32__)
+ // const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(argv[0]));
+ // appPath = tmp_buf;
+ //#else
+ // appPath = wxFNCONV(argv[0]);
+ //#endif
+ // printf("appPath [%s]\n",argv[0]);
+
+ wxString exe_path = wxStandardPaths::Get().GetExecutablePath();
+ //wxString path_separator = wxFileName::GetPathSeparator();
+ //exe_path = exe_path.BeforeLast(path_separator[0]);
+ //exe_path += path_separator;
+
+ //#if defined(__MINGW32__)
+#ifdef WIN32
+ const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(wxFNCONV(exe_path));
+ string appPath = tmp_buf;
+
+ auto_ptr wstr(Ansi2WideString(appPath.c_str()));
+ appPath = utf8_encode(wstr.get());
+#else
+ string appPath(static_cast(WX2CHR(exe_path)));
+#endif
+
+ //#else
+ // appPath = wxFNCONV(exe_path);
+ //#endif
+
+ // printf("#2 appPath [%s]\n",appPath.c_str());
+
+ mainWindow = new MainWindow(unitToLoad,
+ modelPath,
+ particlePath,
+ projectileParticlePath,
+ splashParticlePath,
+ newAnimValue,
+ newParticleLoopValue,
+ newZoomValue,
+ newXRotValue,
+ newYRotValue,
+ appPath);
+ if (autoScreenShotAndExit == true) {
#if !defined(WIN32)
- mainWindow->Iconize(true);
+ mainWindow->Iconize(true);
#endif
- }
- mainWindow->Show();
- mainWindow->init();
- mainWindow->Update();
- mainWindow->setupTimer();
+ }
+ mainWindow->Show();
+ mainWindow->init();
+ mainWindow->Update();
+ mainWindow->setupTimer();
- return true;
-}
+ return true;
+ }
-int App::MainLoop(){
- try{
- return wxApp::MainLoop();
- }
- catch(const exception &e){
- wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Exception"), wxOK | wxICON_ERROR).ShowModal();
- return 1;
- }
- return 0;
-}
+ int App::MainLoop() {
+ try {
+ return wxApp::MainLoop();
+ } catch (const exception &e) {
+ wxMessageDialog(NULL, ToUnicode(e.what()), ToUnicode("Exception"), wxOK | wxICON_ERROR).ShowModal();
+ return 1;
+ }
+ return 0;
+ }
-int App::OnExit(){
- SystemFlags::Close();
- SystemFlags::SHUTDOWN_PROGRAM_MODE=true;
+ int App::OnExit() {
+ SystemFlags::Close();
+ SystemFlags::SHUTDOWN_PROGRAM_MODE = true;
- return 0;
-}
+ return 0;
+ }
-}}//end namespace
+ }
+ }//end namespace
IMPLEMENT_APP_CONSOLE(Shared::G3dViewer::App)
diff --git a/source/g3d_viewer/main.h b/source/g3d_viewer/main.h
index d1af96318..02ab8e126 100644
--- a/source/g3d_viewer/main.h
+++ b/source/g3d_viewer/main.h
@@ -13,8 +13,8 @@
#define _SHADER_G3DVIEWER_MAIN_H_
#ifdef WIN32
- #include
- #include
+#include
+#include
#endif
#include
@@ -32,203 +32,208 @@
using std::string;
using namespace Glest::Game;
-namespace Shared{ namespace G3dViewer{
+namespace Shared {
+ namespace G3dViewer {
-class GlCanvas;
+ class GlCanvas;
-// ===============================
-// class MainWindow
-// ===============================
+ // ===============================
+ // class MainWindow
+ // ===============================
-class MainWindow: public wxFrame{
-private:
- DECLARE_EVENT_TABLE()
+ class MainWindow : public wxFrame {
+ private:
+ DECLARE_EVENT_TABLE()
-public:
- static const string versionString;
- static const string winHeader;
+ public:
+ static const string versionString;
+ static const string winHeader;
- enum MenuId{
- miFileLoad,
- miFileLoadParticleXML,
- miFileLoadProjectileParticleXML,
- miFileLoadSplashParticleXML,
- miFileClearAll,
- miFileToggleScreenshotTransparent,
- miFileSaveScreenshot,
- miModeWireframe,
- miModeNormals,
- miModeGrid,
- miSpeedSlower,
- miSpeedFaster,
- miRestart,
- miChangeBackgroundColor,
- miColorRed,
- miColorBlue,
- miColorGreen,
- miColorYellow,
- miColorWhite,
- miColorCyan,
- miColorOrange,
- miColorMagenta
- };
+ enum MenuId {
+ miFileLoad,
+ miFileLoadParticleXML,
+ miFileLoadProjectileParticleXML,
+ miFileLoadSplashParticleXML,
+ miFileClearAll,
+ miFileToggleScreenshotTransparent,
+ miFileSaveScreenshot,
+ miModeWireframe,
+ miModeNormals,
+ miModeGrid,
+ miSpeedSlower,
+ miSpeedFaster,
+ miRestart,
+ miChangeBackgroundColor,
+ miColorRed,
+ miColorBlue,
+ miColorGreen,
+ miColorYellow,
+ miColorWhite,
+ miColorCyan,
+ miColorOrange,
+ miColorMagenta
+ };
-private:
- GlCanvas *glCanvas;
- Renderer *renderer;
+ private:
+ GlCanvas *glCanvas;
+ Renderer *renderer;
- wxTimer *timer;
+ wxTimer *timer;
- wxMenuBar *menu;
- wxMenu *menuFile;
- wxMenu *menuMode;
- wxMenu *menuSpeed;
- wxMenu *menuCustomColor;
- wxFileDialog *fileDialog;
+ wxMenuBar *menu;
+ wxMenu *menuFile;
+ wxMenu *menuMode;
+ wxMenu *menuSpeed;
+ wxMenu *menuCustomColor;
+ wxFileDialog *fileDialog;
- wxColourDialog *colorPicker;
+ wxColourDialog *colorPicker;
- Model *model;
+ Model *model;
- std::pair > unitPath;
- std::vector modelPathList;
- std::vector particlePathList;
- std::vector particleProjectilePathList;
- std::vector particleSplashPathList; // as above
+ std::pair > unitPath;
+ std::vector modelPathList;
+ std::vector particlePathList;
+ std::vector particleProjectilePathList;
+ std::vector particleSplashPathList; // as above
- bool resetAnimation;
- float resetAnim;
- int resetParticleLoopStart;
+ bool resetAnimation;
+ float resetAnim;
+ int resetParticleLoopStart;
- float speed;
- float anim;
- float lastanim;
- int particleLoopStart;
- float rotX, rotY, zoom;
- float backBrightness, gridBrightness, lightBrightness;
- int lastX, lastY;
- Renderer::PlayerColor playerColor;
- bool initTextureManager;
+ float speed;
+ float anim;
+ float lastanim;
+ int particleLoopStart;
+ float rotX, rotY, zoom;
+ float backBrightness, gridBrightness, lightBrightness;
+ int lastX, lastY;
+ Renderer::PlayerColor playerColor;
+ bool initTextureManager;
- std::vector unitParticleSystemTypes;
- std::vector unitParticleSystems;
+ std::vector unitParticleSystemTypes;
+ std::vector unitParticleSystems;
- std::vector projectileParticleSystemTypes;
- std::vector projectileParticleSystems;
- std::vector splashParticleSystemTypes; // as above
- std::vector splashParticleSystems;
- string statusbarText;
+ std::vector projectileParticleSystemTypes;
+ std::vector projectileParticleSystems;
+ std::vector splashParticleSystemTypes; // as above
+ std::vector splashParticleSystems;
+ string statusbarText;
- bool isControlKeyPressed;
+ bool isControlKeyPressed;
- string appPath;
+ string appPath;
- bool startupSettingsInited;
+ bool startupSettingsInited;
- void initGlCanvas();
- void loadUnit(string path, string skillName);
- void loadModel(string path);
- void loadParticle(string path);
- void loadProjectileParticle(string path);
- void loadSplashParticle(string path);
+ void initGlCanvas();
+ void loadUnit(string path, string skillName);
+ void loadModel(string path);
+ void loadParticle(string path);
+ void loadProjectileParticle(string path);
+ void loadSplashParticle(string path);
- void saveScreenshot();
+ void saveScreenshot();
-public:
- MainWindow( std::pair > unitToLoad,
- const string modelPath,const string particlePath,
- const string projectileParticlePath,const string splashParticlePath,
- float defaultAnimation,int defaultParticleLoopStart,
- float defaultZoom,float defaultXRot, float defaultYRot,
+ public:
+ MainWindow(std::pair > unitToLoad,
+ const string modelPath, const string particlePath,
+ const string projectileParticlePath, const string splashParticlePath,
+ float defaultAnimation, int defaultParticleLoopStart,
+ float defaultZoom, float defaultXRot, float defaultYRot,
string appPath);
- ~MainWindow();
- void init();
+ ~MainWindow();
+ void init();
- void Notify();
+ void Notify();
- void onPaint(wxPaintEvent &event);
- void onClose(wxCloseEvent &event);
- void onMenuFileLoad(wxCommandEvent &event);
- void onMenuFileLoadParticleXML(wxCommandEvent &event);
- void onMenuFileLoadProjectileParticleXML(wxCommandEvent &event);
- void onMenuFileLoadSplashParticleXML(wxCommandEvent &event);
- void onMenuFileClearAll(wxCommandEvent &event);
- void onMenumFileToggleScreenshotTransparent(wxCommandEvent &event);
- void onMenuFileSaveScreenshot(wxCommandEvent &event);
- void onMenuFileExit(wxCommandEvent &event);
- void onMenuModeNormals(wxCommandEvent &event);
- void onMenuModeWireframe(wxCommandEvent &event);
- void onMenuModeGrid(wxCommandEvent &event);
- void onMenuSpeedSlower(wxCommandEvent &event);
- void onMenuSpeedFaster(wxCommandEvent &event);
- void onMenuRestart(wxCommandEvent &event);
- void OnChangeColor(wxCommandEvent &event);
- void onMenuColorRed(wxCommandEvent &event);
- void onMenuColorBlue(wxCommandEvent &event);
- void onMenuColorGreen(wxCommandEvent &event);
- void onMenuColorYellow(wxCommandEvent &event);
- void onMenuColorWhite(wxCommandEvent &event);
- void onMenuColorCyan(wxCommandEvent &event);
- void onMenuColorOrange(wxCommandEvent &event);
- void onMenuColorMagenta(wxCommandEvent &event);
- void onMouseWheelDown(wxMouseEvent &event);
- void onMouseWheelUp(wxMouseEvent &event);
- void onMouseMove(wxMouseEvent &event);
- void onTimer(wxTimerEvent &event);
+ void onPaint(wxPaintEvent &event);
+ void onClose(wxCloseEvent &event);
+ void onMenuFileLoad(wxCommandEvent &event);
+ void onMenuFileLoadParticleXML(wxCommandEvent &event);
+ void onMenuFileLoadProjectileParticleXML(wxCommandEvent &event);
+ void onMenuFileLoadSplashParticleXML(wxCommandEvent &event);
+ void onMenuFileClearAll(wxCommandEvent &event);
+ void onMenumFileToggleScreenshotTransparent(wxCommandEvent &event);
+ void onMenuFileSaveScreenshot(wxCommandEvent &event);
+ void onMenuFileExit(wxCommandEvent &event);
+ void onMenuModeNormals(wxCommandEvent &event);
+ void onMenuModeWireframe(wxCommandEvent &event);
+ void onMenuModeGrid(wxCommandEvent &event);
+ void onMenuSpeedSlower(wxCommandEvent &event);
+ void onMenuSpeedFaster(wxCommandEvent &event);
+ void onMenuRestart(wxCommandEvent &event);
+ void OnChangeColor(wxCommandEvent &event);
+ void onMenuColorRed(wxCommandEvent &event);
+ void onMenuColorBlue(wxCommandEvent &event);
+ void onMenuColorGreen(wxCommandEvent &event);
+ void onMenuColorYellow(wxCommandEvent &event);
+ void onMenuColorWhite(wxCommandEvent &event);
+ void onMenuColorCyan(wxCommandEvent &event);
+ void onMenuColorOrange(wxCommandEvent &event);
+ void onMenuColorMagenta(wxCommandEvent &event);
+ void onMouseWheelDown(wxMouseEvent &event);
+ void onMouseWheelUp(wxMouseEvent &event);
+ void onMouseMove(wxMouseEvent &event);
+ void onTimer(wxTimerEvent &event);
- void onKeyDown(wxKeyEvent &e);
+ void onKeyDown(wxKeyEvent &e);
- string getModelInfo();
+ string getModelInfo();
- void setupTimer();
- void setupStartupSettings();
-};
+ void setupTimer();
+ void setupStartupSettings();
+ };
-// =====================================================
-// class GlCanvas
-// =====================================================
+ // =====================================================
+ // class GlCanvas
+ // =====================================================
-class GlCanvas: public wxGLCanvas {
-private:
- DECLARE_EVENT_TABLE()
+ class GlCanvas : public wxGLCanvas {
+ private:
+ DECLARE_EVENT_TABLE()
-public:
- GlCanvas(MainWindow *mainWindow, int *args);
- ~GlCanvas();
+ public:
+ GlCanvas(MainWindow *mainWindow, int *args);
+ ~GlCanvas();
- void onMouseWheel(wxMouseEvent &event);
- void onMouseMove(wxMouseEvent &event);
- void onPaint(wxPaintEvent &event);
- void onKeyDown(wxKeyEvent &event);
- void OnSize(wxSizeEvent&);
- void setCurrentGLContext();
+ void onMouseWheel(wxMouseEvent &event);
+ void onMouseMove(wxMouseEvent &event);
+ void onPaint(wxPaintEvent &event);
+ void onKeyDown(wxKeyEvent &event);
+ void OnSize(wxSizeEvent&);
+ void setCurrentGLContext();
- wxGLContext * getCtx() { return context; }
-private:
- MainWindow *mainWindow;
- wxGLContext *context;
-};
+ wxGLContext * getCtx() {
+ return context;
+ }
+ private:
+ MainWindow *mainWindow;
+ wxGLContext *context;
+ };
-// ===============================
-// class App
-// ===============================
+ // ===============================
+ // class App
+ // ===============================
-class App: public wxApp{
-private:
- MainWindow *mainWindow;
+ class App : public wxApp {
+ private:
+ MainWindow *mainWindow;
+
+ public:
+ App() : wxApp() {
+ mainWindow = NULL;
+ }
+ virtual ~App() {
+ }
+ virtual bool OnInit();
+ virtual int MainLoop();
+ virtual int OnExit();
+ };
-public:
- App() : wxApp() {
- mainWindow = NULL;
}
- virtual ~App() {}
- virtual bool OnInit();
- virtual int MainLoop();
- virtual int OnExit();
-};
-
-}}//end namespace
+}//end namespace
DECLARE_APP(Shared::G3dViewer::App)
diff --git a/source/g3d_viewer/renderer.cpp b/source/g3d_viewer/renderer.cpp
index a8a09d44d..df1771e0f 100644
--- a/source/g3d_viewer/renderer.cpp
+++ b/source/g3d_viewer/renderer.cpp
@@ -22,534 +22,534 @@ using namespace Shared::Graphics::Gl;
using namespace Glest::Game;
using namespace Shared::Util;
-namespace Shared{ namespace G3dViewer{
+namespace Shared {
+ namespace G3dViewer {
-int Renderer::windowX= 100;
-int Renderer::windowY= 100;
-int Renderer::windowW= 640;
-int Renderer::windowH= 480;
+ int Renderer::windowX = 100;
+ int Renderer::windowY = 100;
+ int Renderer::windowW = 640;
+ int Renderer::windowH = 480;
-// ===============================================
-// class MeshCallbackTeamColor
-// ===============================================
+ // ===============================================
+ // class MeshCallbackTeamColor
+ // ===============================================
-void MeshCallbackTeamColor::execute(const Mesh *mesh){
+ void MeshCallbackTeamColor::execute(const Mesh *mesh) {
- //team color
- if(mesh->getCustomTexture() && teamTexture!=NULL){
- //texture 0
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
+ //team color
+ if (mesh->getCustomTexture() && teamTexture != NULL) {
+ //texture 0
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
- //set color to interpolation
- glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
+ //set color to interpolation
+ glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE1);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
- //set alpha to 1
- glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
+ //set alpha to 1
+ glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
- //texture 1
- glActiveTexture(GL_TEXTURE1);
- glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f);
- glEnable(GL_TEXTURE_2D);
+ //texture 1
+ glActiveTexture(GL_TEXTURE1);
+ glMultiTexCoord2f(GL_TEXTURE1, 0.f, 0.f);
+ glEnable(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D, static_cast(teamTexture)->getHandle());
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
+ glBindTexture(GL_TEXTURE_2D, static_cast(teamTexture)->getHandle());
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
- glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
+ glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR);
- //set alpha to 1
- glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
- glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR);
- glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
+ //set alpha to 1
+ glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
+ glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PRIMARY_COLOR);
+ glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA);
- glActiveTexture(GL_TEXTURE0);
- }
- else{
- glActiveTexture(GL_TEXTURE1);
- glDisable(GL_TEXTURE_2D);
- glActiveTexture(GL_TEXTURE0);
- glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
- }
-}
-
-// ===============================================
-// class Renderer
-// ===============================================
-
-Renderer::Renderer() {
- normals= false;
- wireframe= false;
- grid= true;
- modelRenderer = NULL;
- textureManager = NULL;
- particleRenderer = NULL;
- modelManager = NULL;
- width=0;
- height=0;
- red = 0.3f;
- green = 0.3f;
- blue = 0.3f;
- alpha = 1.0f;
-
- customTextureRed=NULL;
- customTextureBlue=NULL;
- customTextureGreen=NULL;
- customTextureYellow=NULL;
- customTextureWhite=NULL;
- customTextureCyan=NULL;
- customTextureOrange=NULL;
- customTextureMagenta=NULL;
- particleManager=NULL;
-}
-
-Renderer::~Renderer() {
- delete modelRenderer;
- delete textureManager;
- delete particleRenderer;
-
- //resources
- delete particleManager;
- delete modelManager;
-
- if(GraphicsInterface::getInstance().getFactory() != NULL) {
- delete GraphicsInterface::getInstance().getFactory();
- GraphicsInterface::getInstance().setFactory(NULL);
- }
-}
-
-Renderer * Renderer::getInstance() {
- static Renderer * renderer = new Renderer();
- return renderer;
-}
-
-void Renderer::transform(float rotX, float rotY, float zoom) {
- assertGl();
-
- glMatrixMode(GL_MODELVIEW);
- glRotatef(rotY, 1.0f, 0.0f, 0.0f);
- glRotatef(rotX, 0.0f, 1.0f, 0.0f);
- glScalef(zoom, zoom, zoom);
- Vec4f pos(-8.0f, 5.0f, 10.0f, 0.0f);
- glLightfv(GL_LIGHT0,GL_POSITION, pos.ptr());
-
- assertGl();
-}
-
-void Renderer::checkGlCaps() {
-
- if(glActiveTexture == NULL) {
- string message;
-
- message += "Your system supports OpenGL version \"";
- message += getGlVersion() + string("\"\n");
- message += "ZetaGlest needs a version that supports\n";
- message += "glActiveTexture (OpenGL 1.3) or the ARB_multitexture extension.";
-
- throw megaglest_runtime_error(message.c_str());
- }
-
- //opengl 1.3
- //if(!isGlVersionSupported(1, 3, 0)) {
- if(glewIsSupported("GL_VERSION_1_3") == false) {
- string message;
-
- message += "Your system supports OpenGL version \"";
- message += getGlVersion() + string("\"\n");
- message += "ZetaGlest needs at least version 1.3 to work\n";
- message += "You may solve this problem by installing your latest video card drivers";
-
- throw megaglest_runtime_error(message.c_str());
- }
-
- //opengl 1.4 or extension
- //if(isGlVersionSupported(1, 4, 0) == false) {
- if(glewIsSupported("GL_VERSION_1_4") == false) {
- checkExtension("GL_ARB_texture_env_crossbar", "ZetaGlest");
- }
-}
-
-void Renderer::checkExtension(const string &extension, const string &msg) {
- if(isGlExtensionSupported(extension.c_str()) == false) {
- string str= "OpenGL extension not supported: " + extension + ", required for " + msg;
- throw megaglest_runtime_error(str);
- }
-}
-
-Texture2D * Renderer::getNewTexture2D() {
- Texture2D *newTexture = textureManager->newTexture2D();
- return newTexture;
-}
-
-Model * Renderer::newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad,std::map > > *loadedFileList, string *sourceLoader) {
- return modelManager->newModel(path,deletePixMapAfterLoad,loadedFileList,sourceLoader);
-}
-
-void Renderer::endModel(ResourceScope rs,Model *model) {
- modelManager->endModel(model);
-}
-
-void Renderer::init() {
- assertGl();
-
- GraphicsFactory *gf= GraphicsInterface::getInstance().getFactory();
- if(gf == NULL) {
- gf= new GraphicsFactoryGl();
- GraphicsInterface::getInstance().setFactory(gf);
- }
-
- Config &config = Config::getInstance();
- if(config.getBool("CheckGlCaps")){
-
- if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
-
- checkGlCaps();
- }
-
- if(glActiveTexture == NULL) {
- char szBuf[8096]="";
- snprintf(szBuf,8096,"Error: glActiveTexture == NULL\nglActiveTexture is only supported if the GL version is 1.3 or greater,\nor if the ARB_multitexture extension is supported!");
- throw megaglest_runtime_error(szBuf);
- }
-
- modelRenderer= gf->newModelRenderer();
- textureManager= gf->newTextureManager();
- particleRenderer= gf->newParticleRenderer();
-
- //resources
- particleManager= gf->newParticleManager();
-
- modelManager = gf->newModelManager();
- modelManager->setTextureManager(textureManager);
-
- //red tex
- customTextureRed= textureManager->newTexture2D();
- customTextureRed->getPixmap()->init(1, 1, 3);
- customTextureRed->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.f, 0.f));
-
- //blue tex
- customTextureBlue= textureManager->newTexture2D();
- customTextureBlue->getPixmap()->init(1, 1, 3);
- customTextureBlue->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.f, 1.f));
-
- //green tex
- customTextureGreen= textureManager->newTexture2D();
- customTextureGreen->getPixmap()->init(1, 1, 3);
- customTextureGreen->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.5f, 0.f));
-
- //yellow tex
- customTextureYellow= textureManager->newTexture2D();
- customTextureYellow->getPixmap()->init(1, 1, 3);
- customTextureYellow->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 0.f));
-
- //white tex
- customTextureWhite= textureManager->newTexture2D();
- customTextureWhite->getPixmap()->init(1, 1, 3);
- customTextureWhite->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 1.f));
-
- //cyan tex
- customTextureCyan= textureManager->newTexture2D();
- customTextureCyan->getPixmap()->init(1, 1, 3);
- customTextureCyan->getPixmap()->setPixel(0, 0, Vec3f(0.f, 1.f, 0.8f));
-
- //orange tex
- customTextureOrange= textureManager->newTexture2D();
- customTextureOrange->getPixmap()->init(1, 1, 3);
- customTextureOrange->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 0.f));
-
- //magenta tex
- customTextureMagenta= textureManager->newTexture2D();
- customTextureMagenta->getPixmap()->init(1, 1, 3);
- customTextureMagenta->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 1.f));
-
- glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
- //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- /* once the GL context is valid : */
- //GLint alpha_bits;
- //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
- //printf("#1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
-
- glEnable(GL_TEXTURE_2D);
- glFrontFace(GL_CW);
- glEnable(GL_CULL_FACE);
- glEnable(GL_DEPTH_TEST);
- glEnable(GL_ALPHA_TEST);
- //glAlphaFunc(GL_GREATER, 0.5f);
- glAlphaFunc(GL_GREATER, 0.0f);
- glEnable(GL_LIGHTING);
- glEnable(GL_LIGHT0);
-
- Vec4f diffuse= Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
- Vec4f ambient= Vec4f(0.3f, 0.3f, 0.3f, 1.0f);
- Vec4f specular= Vec4f(0.1f, 0.1f, 0.1f, 1.0f);
-
- glLightfv(GL_LIGHT0,GL_AMBIENT, ambient.ptr());
- glLightfv(GL_LIGHT0,GL_DIFFUSE, diffuse.ptr());
- glLightfv(GL_LIGHT0,GL_SPECULAR, specular.ptr());
-
- glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
- glEnable(GL_COLOR_MATERIAL);
-
- assertGl();
-}
-
-void Renderer::reset(int w, int h, PlayerColor playerColor) {
- assertGl();
-
- width=w;
- height=h;
-
- //glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- /* once the GL context is valid : */
- //GLint alpha_bits;
- //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
- //printf("#2 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
-
- glViewport(0, 0, w, h);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluPerspective(60.0f, static_cast(w)/h, 1.0f, 200.0f);
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- glTranslatef(0, -1.5, -5);
-
- Texture2D *customTexture=NULL;
- switch(playerColor) {
- case pcRed:
- customTexture= customTextureRed;
- break;
- case pcBlue:
- customTexture= customTextureBlue;
- break;
- case pcGreen:
- customTexture= customTextureGreen;
- break;
- case pcYellow:
- customTexture= customTextureYellow;
- break;
- case pcWhite:
- customTexture= customTextureWhite;
- break;
- case pcCyan:
- customTexture= customTextureCyan;
- break;
- case pcOrange:
- customTexture= customTextureOrange;
- break;
- case pcMagenta:
- customTexture= customTextureMagenta;
- break;
- default:
- assert(false);
- break;
- }
- meshCallbackTeamColor.setTeamTexture(customTexture);
-
- if(wireframe) {
- glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
- glDisable(GL_TEXTURE_2D);
- glDisable(GL_LIGHTING);
- glDisable(GL_LIGHT0);
- }
- else {
- glEnable(GL_TEXTURE_2D);
- glEnable(GL_LIGHTING);
- glEnable(GL_LIGHT0);
- glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
- }
-
- assertGl();
-}
-
-void Renderer::renderGrid() {
- if(grid) {
- float i=0;
-
- assertGl();
-
- glPushAttrib(GL_ENABLE_BIT);
- glDisable(GL_TEXTURE_2D);
- glDisable(GL_LIGHTING);
-
- glBegin(GL_LINES);
- glColor3f(1.0f, 1.0f, 1.0f); // gridcolor constant
- for(i=-10.0f; i<=10.0f; i+=1.0f) {
- glVertex3f(i, 0.0f, 10.0f);
- glVertex3f(i, 0.0f, -10.0f);
+ glActiveTexture(GL_TEXTURE0);
+ } else {
+ glActiveTexture(GL_TEXTURE1);
+ glDisable(GL_TEXTURE_2D);
+ glActiveTexture(GL_TEXTURE0);
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+ }
}
- for(i=-10.0f; i<=10.0f; i+=1.0f) {
- glVertex3f(10.f, 0.0f, i);
- glVertex3f(-10.f, 0.0f, i);
+
+ // ===============================================
+ // class Renderer
+ // ===============================================
+
+ Renderer::Renderer() {
+ normals = false;
+ wireframe = false;
+ grid = true;
+ modelRenderer = NULL;
+ textureManager = NULL;
+ particleRenderer = NULL;
+ modelManager = NULL;
+ width = 0;
+ height = 0;
+ red = 0.3f;
+ green = 0.3f;
+ blue = 0.3f;
+ alpha = 1.0f;
+
+ customTextureRed = NULL;
+ customTextureBlue = NULL;
+ customTextureGreen = NULL;
+ customTextureYellow = NULL;
+ customTextureWhite = NULL;
+ customTextureCyan = NULL;
+ customTextureOrange = NULL;
+ customTextureMagenta = NULL;
+ particleManager = NULL;
}
- glEnd();
- glPopAttrib();
+ Renderer::~Renderer() {
+ delete modelRenderer;
+ delete textureManager;
+ delete particleRenderer;
- assertGl();
- }
-}
+ //resources
+ delete particleManager;
+ delete modelManager;
-void Renderer::toggleNormals() {
- normals= normals? false: true;
-}
+ if (GraphicsInterface::getInstance().getFactory() != NULL) {
+ delete GraphicsInterface::getInstance().getFactory();
+ GraphicsInterface::getInstance().setFactory(NULL);
+ }
+ }
-void Renderer::toggleWireframe() {
- wireframe= wireframe? false: true;
-}
+ Renderer * Renderer::getInstance() {
+ static Renderer * renderer = new Renderer();
+ return renderer;
+ }
-void Renderer::toggleGrid() {
- grid= grid? false: true;
-}
+ void Renderer::transform(float rotX, float rotY, float zoom) {
+ assertGl();
-void Renderer::renderTheModel(Model *model, float f) {
- if(model != NULL){
- modelRenderer->begin(true, true, !wireframe, false, &meshCallbackTeamColor);
- model->updateInterpolationData(f, true);
- modelRenderer->render(model);
+ glMatrixMode(GL_MODELVIEW);
+ glRotatef(rotY, 1.0f, 0.0f, 0.0f);
+ glRotatef(rotX, 0.0f, 1.0f, 0.0f);
+ glScalef(zoom, zoom, zoom);
+ Vec4f pos(-8.0f, 5.0f, 10.0f, 0.0f);
+ glLightfv(GL_LIGHT0, GL_POSITION, pos.ptr());
- if(normals) {
- glPushAttrib(GL_ENABLE_BIT);
- glDisable(GL_LIGHTING);
- glDisable(GL_TEXTURE_2D);
- glColor3f(1.0f, 1.0f, 1.0f); //normalscolor constant
- modelRenderer->renderNormalsOnly(model);
+ assertGl();
+ }
+
+ void Renderer::checkGlCaps() {
+
+ if (glActiveTexture == NULL) {
+ string message;
+
+ message += "Your system supports OpenGL version \"";
+ message += getGlVersion() + string("\"\n");
+ message += "ZetaGlest needs a version that supports\n";
+ message += "glActiveTexture (OpenGL 1.3) or the ARB_multitexture extension.";
+
+ throw megaglest_runtime_error(message.c_str());
+ }
+
+ //opengl 1.3
+ //if(!isGlVersionSupported(1, 3, 0)) {
+ if (glewIsSupported("GL_VERSION_1_3") == false) {
+ string message;
+
+ message += "Your system supports OpenGL version \"";
+ message += getGlVersion() + string("\"\n");
+ message += "ZetaGlest needs at least version 1.3 to work\n";
+ message += "You may solve this problem by installing your latest video card drivers";
+
+ throw megaglest_runtime_error(message.c_str());
+ }
+
+ //opengl 1.4 or extension
+ //if(isGlVersionSupported(1, 4, 0) == false) {
+ if (glewIsSupported("GL_VERSION_1_4") == false) {
+ checkExtension("GL_ARB_texture_env_crossbar", "ZetaGlest");
+ }
+ }
+
+ void Renderer::checkExtension(const string &extension, const string &msg) {
+ if (isGlExtensionSupported(extension.c_str()) == false) {
+ string str = "OpenGL extension not supported: " + extension + ", required for " + msg;
+ throw megaglest_runtime_error(str);
+ }
+ }
+
+ Texture2D * Renderer::getNewTexture2D() {
+ Texture2D *newTexture = textureManager->newTexture2D();
+ return newTexture;
+ }
+
+ Model * Renderer::newModel(ResourceScope rs, const string &path, bool deletePixMapAfterLoad, std::map > > *loadedFileList, string *sourceLoader) {
+ return modelManager->newModel(path, deletePixMapAfterLoad, loadedFileList, sourceLoader);
+ }
+
+ void Renderer::endModel(ResourceScope rs, Model *model) {
+ modelManager->endModel(model);
+ }
+
+ void Renderer::init() {
+ assertGl();
+
+ GraphicsFactory *gf = GraphicsInterface::getInstance().getFactory();
+ if (gf == NULL) {
+ gf = new GraphicsFactoryGl();
+ GraphicsInterface::getInstance().setFactory(gf);
+ }
+
+ Config &config = Config::getInstance();
+ if (config.getBool("CheckGlCaps")) {
+
+ if (SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s %d]\n", extractFileFromDirectoryPath(__FILE__).c_str(), __FUNCTION__, __LINE__);
+
+ checkGlCaps();
+ }
+
+ if (glActiveTexture == NULL) {
+ char szBuf[8096] = "";
+ snprintf(szBuf, 8096, "Error: glActiveTexture == NULL\nglActiveTexture is only supported if the GL version is 1.3 or greater,\nor if the ARB_multitexture extension is supported!");
+ throw megaglest_runtime_error(szBuf);
+ }
+
+ modelRenderer = gf->newModelRenderer();
+ textureManager = gf->newTextureManager();
+ particleRenderer = gf->newParticleRenderer();
+
+ //resources
+ particleManager = gf->newParticleManager();
+
+ modelManager = gf->newModelManager();
+ modelManager->setTextureManager(textureManager);
+
+ //red tex
+ customTextureRed = textureManager->newTexture2D();
+ customTextureRed->getPixmap()->init(1, 1, 3);
+ customTextureRed->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.f, 0.f));
+
+ //blue tex
+ customTextureBlue = textureManager->newTexture2D();
+ customTextureBlue->getPixmap()->init(1, 1, 3);
+ customTextureBlue->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.f, 1.f));
+
+ //green tex
+ customTextureGreen = textureManager->newTexture2D();
+ customTextureGreen->getPixmap()->init(1, 1, 3);
+ customTextureGreen->getPixmap()->setPixel(0, 0, Vec3f(0.f, 0.5f, 0.f));
+
+ //yellow tex
+ customTextureYellow = textureManager->newTexture2D();
+ customTextureYellow->getPixmap()->init(1, 1, 3);
+ customTextureYellow->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 0.f));
+
+ //white tex
+ customTextureWhite = textureManager->newTexture2D();
+ customTextureWhite->getPixmap()->init(1, 1, 3);
+ customTextureWhite->getPixmap()->setPixel(0, 0, Vec3f(1.f, 1.f, 1.f));
+
+ //cyan tex
+ customTextureCyan = textureManager->newTexture2D();
+ customTextureCyan->getPixmap()->init(1, 1, 3);
+ customTextureCyan->getPixmap()->setPixel(0, 0, Vec3f(0.f, 1.f, 0.8f));
+
+ //orange tex
+ customTextureOrange = textureManager->newTexture2D();
+ customTextureOrange->getPixmap()->init(1, 1, 3);
+ customTextureOrange->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 0.f));
+
+ //magenta tex
+ customTextureMagenta = textureManager->newTexture2D();
+ customTextureMagenta->getPixmap()->init(1, 1, 3);
+ customTextureMagenta->getPixmap()->setPixel(0, 0, Vec3f(1.f, 0.5f, 1.f));
+
+ glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
+ //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ /* once the GL context is valid : */
+ //GLint alpha_bits;
+ //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
+ //printf("#1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
+
+ glEnable(GL_TEXTURE_2D);
+ glFrontFace(GL_CW);
+ glEnable(GL_CULL_FACE);
+ glEnable(GL_DEPTH_TEST);
+ glEnable(GL_ALPHA_TEST);
+ //glAlphaFunc(GL_GREATER, 0.5f);
+ glAlphaFunc(GL_GREATER, 0.0f);
+ glEnable(GL_LIGHTING);
+ glEnable(GL_LIGHT0);
+
+ Vec4f diffuse = Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
+ Vec4f ambient = Vec4f(0.3f, 0.3f, 0.3f, 1.0f);
+ Vec4f specular = Vec4f(0.1f, 0.1f, 0.1f, 1.0f);
+
+ glLightfv(GL_LIGHT0, GL_AMBIENT, ambient.ptr());
+ glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse.ptr());
+ glLightfv(GL_LIGHT0, GL_SPECULAR, specular.ptr());
+
+ glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
+ glEnable(GL_COLOR_MATERIAL);
+
+ assertGl();
+ }
+
+ void Renderer::reset(int w, int h, PlayerColor playerColor) {
+ assertGl();
+
+ width = w;
+ height = h;
+
+ //glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ /* once the GL context is valid : */
+ //GLint alpha_bits;
+ //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
+ //printf("#2 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
+
+ glViewport(0, 0, w, h);
+ glMatrixMode(GL_PROJECTION);
+ glLoadIdentity();
+ gluPerspective(60.0f, static_cast(w) / h, 1.0f, 200.0f);
+ glMatrixMode(GL_MODELVIEW);
+ glLoadIdentity();
+ glTranslatef(0, -1.5, -5);
+
+ Texture2D *customTexture = NULL;
+ switch (playerColor) {
+ case pcRed:
+ customTexture = customTextureRed;
+ break;
+ case pcBlue:
+ customTexture = customTextureBlue;
+ break;
+ case pcGreen:
+ customTexture = customTextureGreen;
+ break;
+ case pcYellow:
+ customTexture = customTextureYellow;
+ break;
+ case pcWhite:
+ customTexture = customTextureWhite;
+ break;
+ case pcCyan:
+ customTexture = customTextureCyan;
+ break;
+ case pcOrange:
+ customTexture = customTextureOrange;
+ break;
+ case pcMagenta:
+ customTexture = customTextureMagenta;
+ break;
+ default:
+ assert(false);
+ break;
+ }
+ meshCallbackTeamColor.setTeamTexture(customTexture);
+
+ if (wireframe) {
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glDisable(GL_TEXTURE_2D);
+ glDisable(GL_LIGHTING);
+ glDisable(GL_LIGHT0);
+ } else {
+ glEnable(GL_TEXTURE_2D);
+ glEnable(GL_LIGHTING);
+ glEnable(GL_LIGHT0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ }
+
+ assertGl();
+ }
+
+ void Renderer::renderGrid() {
+ if (grid) {
+ float i = 0;
+
+ assertGl();
+
+ glPushAttrib(GL_ENABLE_BIT);
+ glDisable(GL_TEXTURE_2D);
+ glDisable(GL_LIGHTING);
+
+ glBegin(GL_LINES);
+ glColor3f(1.0f, 1.0f, 1.0f); // gridcolor constant
+ for (i = -10.0f; i <= 10.0f; i += 1.0f) {
+ glVertex3f(i, 0.0f, 10.0f);
+ glVertex3f(i, 0.0f, -10.0f);
+ }
+ for (i = -10.0f; i <= 10.0f; i += 1.0f) {
+ glVertex3f(10.f, 0.0f, i);
+ glVertex3f(-10.f, 0.0f, i);
+ }
+ glEnd();
+
+ glPopAttrib();
+
+ assertGl();
+ }
+ }
+
+ void Renderer::toggleNormals() {
+ normals = normals ? false : true;
+ }
+
+ void Renderer::toggleWireframe() {
+ wireframe = wireframe ? false : true;
+ }
+
+ void Renderer::toggleGrid() {
+ grid = grid ? false : true;
+ }
+
+ void Renderer::renderTheModel(Model *model, float f) {
+ if (model != NULL) {
+ modelRenderer->begin(true, true, !wireframe, false, &meshCallbackTeamColor);
+ model->updateInterpolationData(f, true);
+ modelRenderer->render(model);
+
+ if (normals) {
+ glPushAttrib(GL_ENABLE_BIT);
+ glDisable(GL_LIGHTING);
+ glDisable(GL_TEXTURE_2D);
+ glColor3f(1.0f, 1.0f, 1.0f); //normalscolor constant
+ modelRenderer->renderNormalsOnly(model);
+ glPopAttrib();
+ }
+
+ modelRenderer->end();
+ }
+ }
+
+ void Renderer::manageParticleSystem(ParticleSystem *particleSystem) {
+ particleManager->manage(particleSystem);
+ }
+
+ void Renderer::updateParticleManager() {
+ particleManager->update();
+ }
+
+ bool Renderer::hasActiveParticleSystem(ParticleSystem::ParticleSystemType type) const {
+ return particleManager->hasActiveParticleSystem(type);
+ }
+
+ void Renderer::renderParticleManager() {
+ glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+ glDepthFunc(GL_LESS);
+ particleRenderer->renderManager(particleManager, modelRenderer);
glPopAttrib();
}
- modelRenderer->end();
+ Texture2D * Renderer::getPlayerColorTexture(PlayerColor playerColor) {
+ Texture2D *customTexture = NULL;
+ switch (playerColor) {
+ case pcRed:
+ customTexture = customTextureRed;
+ break;
+ case pcBlue:
+ customTexture = customTextureBlue;
+ break;
+ case pcGreen:
+ customTexture = customTextureGreen;
+ break;
+ case pcYellow:
+ customTexture = customTextureYellow;
+ break;
+ case pcWhite:
+ customTexture = customTextureWhite;
+ break;
+ case pcCyan:
+ customTexture = customTextureCyan;
+ break;
+ case pcOrange:
+ customTexture = customTextureOrange;
+ break;
+ case pcMagenta:
+ customTexture = customTextureMagenta;
+ break;
+ default:
+ throw megaglest_runtime_error("Unknown playercolor: " + intToStr(playerColor));
+ break;
+ }
+
+ return customTexture;
+ }
+
+ void Renderer::initTextureManager() {
+ textureManager->init();
+ }
+
+ void Renderer::initModelManager() {
+ modelManager->init();
+ }
+
+ void Renderer::end() {
+ //delete resources
+ //textureManager->end();
+ particleManager->end();
+ modelManager->end();
+ }
+
+ void Renderer::setBackgroundColor(float red, float green, float blue) {
+ this->red = red;
+ this->green = green;
+ this->blue = blue;
+
+ glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
+ //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ /* once the GL context is valid : */
+ //GLint alpha_bits;
+ //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
+ //printf("#3 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
+ }
+
+ void Renderer::setAlphaColor(float alpha) {
+ this->alpha = alpha;
+
+ glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
+ //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ /* once the GL context is valid : */
+ //GLint alpha_bits;
+ //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
+ //printf("#3.1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
+ }
+
+ void Renderer::saveScreen(const string &path, std::pair *overrideSize) {
+ Pixmap2D *pixmapScreenShot = new Pixmap2D(width, height, 4);
+ //glFinish();
+
+ glPixelStorei(GL_PACK_ALIGNMENT, 1);
+
+ glReadPixels(0, 0, pixmapScreenShot->getW(), pixmapScreenShot->getH(),
+ GL_RGBA, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels());
+
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+ //if(overrideSize != NULL && overrideSize->first > 0 && overrideSize->second > 0) {
+ // pixmapScreenShot->Scale(GL_RGBA,overrideSize->first,overrideSize->second);
+ //}
+
+ pixmapScreenShot->save(path);
+ delete pixmapScreenShot;
+ }
+
}
-}
-
-void Renderer::manageParticleSystem(ParticleSystem *particleSystem) {
- particleManager->manage(particleSystem);
-}
-
-void Renderer::updateParticleManager() {
- particleManager->update();
-}
-
-bool Renderer::hasActiveParticleSystem(ParticleSystem::ParticleSystemType type) const {
- return particleManager->hasActiveParticleSystem(type);
-}
-
-void Renderer::renderParticleManager() {
- glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
- glDepthFunc(GL_LESS);
- particleRenderer->renderManager(particleManager, modelRenderer);
- glPopAttrib();
-}
-
-Texture2D * Renderer::getPlayerColorTexture(PlayerColor playerColor) {
- Texture2D *customTexture=NULL;
- switch(playerColor){
- case pcRed:
- customTexture= customTextureRed;
- break;
- case pcBlue:
- customTexture= customTextureBlue;
- break;
- case pcGreen:
- customTexture= customTextureGreen;
- break;
- case pcYellow:
- customTexture= customTextureYellow;
- break;
- case pcWhite:
- customTexture= customTextureWhite;
- break;
- case pcCyan:
- customTexture= customTextureCyan;
- break;
- case pcOrange:
- customTexture= customTextureOrange;
- break;
- case pcMagenta:
- customTexture= customTextureMagenta;
- break;
- default:
- throw megaglest_runtime_error("Unknown playercolor: " + intToStr(playerColor));
- break;
- }
-
- return customTexture;
-}
-
-void Renderer::initTextureManager() {
- textureManager->init();
-}
-
-void Renderer::initModelManager() {
- modelManager->init();
-}
-
-void Renderer::end() {
- //delete resources
- //textureManager->end();
- particleManager->end();
- modelManager->end();
-}
-
-void Renderer::setBackgroundColor(float red, float green, float blue) {
- this->red = red;
- this->green = green;
- this->blue = blue;
-
- glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
- //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- /* once the GL context is valid : */
- //GLint alpha_bits;
- //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
- //printf("#3 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
-}
-
-void Renderer::setAlphaColor(float alpha) {
- this->alpha= alpha;
-
- glClearColor(red, green, blue, alpha); //backgroundcolor constant 0.3
- //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
- /* once the GL context is valid : */
- //GLint alpha_bits;
- //glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
- //printf("#3.1 The framebuffer uses %d bit(s) per the alpha component\n", alpha_bits);
-}
-
-void Renderer::saveScreen(const string &path,std::pair *overrideSize) {
- Pixmap2D *pixmapScreenShot = new Pixmap2D(width, height, 4);
- //glFinish();
-
- glPixelStorei(GL_PACK_ALIGNMENT, 1);
-
- glReadPixels(0, 0, pixmapScreenShot->getW(), pixmapScreenShot->getH(),
- GL_RGBA, GL_UNSIGNED_BYTE, pixmapScreenShot->getPixels());
-
- glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
-
- //if(overrideSize != NULL && overrideSize->first > 0 && overrideSize->second > 0) {
- // pixmapScreenShot->Scale(GL_RGBA,overrideSize->first,overrideSize->second);
- //}
-
- pixmapScreenShot->save(path);
- delete pixmapScreenShot;
-}
-
-}}//end namespace
+}//end namespace
diff --git a/source/g3d_viewer/renderer.h b/source/g3d_viewer/renderer.h
index f9a881461..93a60d419 100644
--- a/source/g3d_viewer/renderer.h
+++ b/source/g3d_viewer/renderer.h
@@ -13,8 +13,8 @@
#define _SHADER_G3DVIEWER_RENDERER_H_
#ifdef WIN32
- #include
- #include
+#include
+#include
#endif
#include "model_renderer.h"
@@ -45,122 +45,134 @@ using Shared::Graphics::Texture;
using namespace Shared::Graphics;
-namespace Shared{ namespace G3dViewer{
+namespace Shared {
+ namespace G3dViewer {
-// ===============================================
-// class MeshCallbackTeamColor
-// ===============================================
+ // ===============================================
+ // class MeshCallbackTeamColor
+ // ===============================================
-class MeshCallbackTeamColor: public MeshCallback{
-private:
- const Texture *teamTexture;
+ class MeshCallbackTeamColor : public MeshCallback {
+ private:
+ const Texture *teamTexture;
+
+ public:
+ MeshCallbackTeamColor() : MeshCallback() {
+ teamTexture = NULL;
+ }
+ void setTeamTexture(const Texture *teamTexture) {
+ this->teamTexture = teamTexture;
+ }
+ virtual void execute(const Mesh *mesh);
+ };
+
+ // ===============================
+ // class Renderer
+ // ===============================
+
+ class Renderer : public RendererInterface {
+ public:
+ static int windowX;
+ static int windowY;
+ static int windowW;
+ static int windowH;
+
+ public:
+ enum PlayerColor {
+ pcRed,
+ pcBlue,
+ pcGreen,
+ pcYellow,
+ pcWhite,
+ pcCyan,
+ pcOrange,
+ pcMagenta
+ };
+
+ private:
+ bool wireframe;
+ bool normals;
+ bool grid;
+
+ int width;
+ int height;
+
+ ModelRenderer *modelRenderer;
+ TextureManager *textureManager;
+ ParticleRenderer *particleRenderer;
+
+ ParticleManager *particleManager;
+ ModelManager *modelManager;
+
+ Texture2D *customTextureRed;
+ Texture2D *customTextureBlue;
+ Texture2D *customTextureGreen;
+ Texture2D *customTextureYellow;
+ Texture2D *customTextureWhite;
+ Texture2D *customTextureCyan;
+ Texture2D *customTextureOrange;
+ Texture2D *customTextureMagenta;
+ MeshCallbackTeamColor meshCallbackTeamColor;
+
+ float red;
+ float green;
+ float blue;
+ float alpha;
+
+ Renderer();
+ void checkGlCaps();
+ void checkExtension(const string &extension, const string &msg);
+
+ public:
+ virtual ~Renderer();
+ static Renderer *getInstance();
+
+ void init();
+ void reset(int w, int h, PlayerColor playerColor);
+ void transform(float rotX, float rotY, float zoom);
+ void renderGrid();
+
+ bool getNormals() const {
+ return normals;
+ }
+ bool getWireframe() const {
+ return wireframe;
+ }
+ bool getGrid() const {
+ return grid;
+ }
+
+ void toggleNormals();
+ void toggleWireframe();
+ void toggleGrid();
+
+ void renderTheModel(Model *model, float f);
+
+ void manageParticleSystem(ParticleSystem *particleSystem);
+ void updateParticleManager();
+ void renderParticleManager();
+ Texture2D *getPlayerColorTexture(PlayerColor playerColor);
+
+ Texture2D * getNewTexture2D();
+
+ Model *newModel(ResourceScope rs, const string &path, bool deletePixMapAfterLoad = false, std::map > > *loadedFileList = NULL, string *sourceLoader = NULL);
+ void endModel(ResourceScope rs, Model *model);
+ Texture2D *newTexture2D(ResourceScope rs) {
+ return getNewTexture2D();
+ }
+
+ void initTextureManager();
+ void initModelManager();
+
+ void end();
+
+ void setBackgroundColor(float red, float green, float blue);
+ void setAlphaColor(float alpha);
+ void saveScreen(const string &path, std::pair *overrideSize);
+ bool hasActiveParticleSystem(ParticleSystem::ParticleSystemType typeName) const;
+ };
-public:
- MeshCallbackTeamColor() : MeshCallback() {
- teamTexture = NULL;
}
- void setTeamTexture(const Texture *teamTexture) {this->teamTexture= teamTexture;}
- virtual void execute(const Mesh *mesh);
-};
-
-// ===============================
-// class Renderer
-// ===============================
-
-class Renderer : public RendererInterface {
-public:
- static int windowX;
- static int windowY;
- static int windowW;
- static int windowH;
-
-public:
- enum PlayerColor{
- pcRed,
- pcBlue,
- pcGreen,
- pcYellow,
- pcWhite,
- pcCyan,
- pcOrange,
- pcMagenta
- };
-
-private:
- bool wireframe;
- bool normals;
- bool grid;
-
- int width;
- int height;
-
- ModelRenderer *modelRenderer;
- TextureManager *textureManager;
- ParticleRenderer *particleRenderer;
-
- ParticleManager *particleManager;
- ModelManager *modelManager;
-
- Texture2D *customTextureRed;
- Texture2D *customTextureBlue;
- Texture2D *customTextureGreen;
- Texture2D *customTextureYellow;
- Texture2D *customTextureWhite;
- Texture2D *customTextureCyan;
- Texture2D *customTextureOrange;
- Texture2D *customTextureMagenta;
- MeshCallbackTeamColor meshCallbackTeamColor;
-
- float red;
- float green;
- float blue;
- float alpha;
-
- Renderer();
- void checkGlCaps();
- void checkExtension(const string &extension, const string &msg);
-
-public:
- virtual ~Renderer();
- static Renderer *getInstance();
-
- void init();
- void reset(int w, int h, PlayerColor playerColor);
- void transform(float rotX, float rotY, float zoom);
- void renderGrid();
-
- bool getNormals() const {return normals;}
- bool getWireframe() const {return wireframe;}
- bool getGrid() const {return grid;}
-
- void toggleNormals();
- void toggleWireframe();
- void toggleGrid();
-
- void renderTheModel(Model *model, float f);
-
- void manageParticleSystem(ParticleSystem *particleSystem);
- void updateParticleManager();
- void renderParticleManager();
- Texture2D *getPlayerColorTexture(PlayerColor playerColor);
-
- Texture2D * getNewTexture2D();
-
- Model *newModel(ResourceScope rs,const string &path,bool deletePixMapAfterLoad=false,std::map > > *loadedFileList=NULL, string *sourceLoader=NULL);
- void endModel(ResourceScope rs,Model *model);
- Texture2D *newTexture2D(ResourceScope rs) { return getNewTexture2D(); }
-
- void initTextureManager();
- void initModelManager();
-
- void end();
-
- void setBackgroundColor(float red, float green, float blue);
- void setAlphaColor(float alpha);
- void saveScreen(const string &path,std::pair *overrideSize);
- bool hasActiveParticleSystem(ParticleSystem::ParticleSystemType typeName) const;
-};
-
-}}//end namespace
+}//end namespace
#endif
diff --git a/source/glest_game/CMakeLists.txt b/source/glest_game/CMakeLists.txt
index 3ef9f0a10..baa40b1d4 100644
--- a/source/glest_game/CMakeLists.txt
+++ b/source/glest_game/CMakeLists.txt
@@ -5,7 +5,7 @@ SET(EXTERNAL_LIBS "")
SET(TARGET_NAME "zetaglest")
SET(TARGET_NAME_MANPAGE "${TARGET_NAME}.6")
-IF(BUILD_MEGAGLEST)
+IF(BUILD_ZETAGLEST)
MESSAGE(STATUS "Will try to build ZetaGlest game")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
@@ -112,8 +112,8 @@ IF(BUILD_MEGAGLEST)
SET(EXTERNAL_LIBS ${EXTERNAL_LIBS} ${GLEW_LIBRARIES})
ENDIF()
- IF(VLC_MIN_VERSION_MG)
- SET(LIBVLC_MIN_VERSION "${VLC_MIN_VERSION_MG}")
+ IF(VLC_MIN_VERSION_ZG)
+ SET(LIBVLC_MIN_VERSION "${VLC_MIN_VERSION_ZG}")
ELSE()
SET(LIBVLC_MIN_VERSION "1.1.0")
ENDIF()
@@ -233,26 +233,26 @@ IF(BUILD_MEGAGLEST)
SET(GLEST_LIB_INCLUDE_DIRS ${GLEST_LIB_INCLUDE_DIRS} ${GLEST_LIB_INCLUDE_ROOT}platform/unix)
ENDIF()
- SET(MG_SOURCE_FILES "")
+ SET(ZG_SOURCE_FILES "")
FOREACH(DIR IN LISTS DIRS_WITH_SRC)
INCLUDE_DIRECTORIES( ${DIR} )
set(SRC_DIR_TO_GLOB ${DIR})
FILE(GLOB SRC_FILES_FROM_THIS_DIR ${SRC_DIR_TO_GLOB}/*.cpp)
- SET(MG_SOURCE_FILES ${MG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
+ SET(ZG_SOURCE_FILES ${ZG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
FILE(GLOB SRC_FILES_FROM_THIS_DIR ${SRC_DIR_TO_GLOB}/*.c)
- SET(MG_SOURCE_FILES ${MG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
+ SET(ZG_SOURCE_FILES ${ZG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
FILE(GLOB INCLUDE_FILES_FROM_THIS_DIR ${SRC_DIR_TO_GLOB}/*.h)
- SET(MG_INCLUDE_FILES ${MG_INCLUDE_FILES} ${INCLUDE_FILES_FROM_THIS_DIR})
+ SET(ZG_INCLUDE_FILES ${ZG_INCLUDE_FILES} ${INCLUDE_FILES_FROM_THIS_DIR})
IF(APPLE)
FILE(GLOB SRC_FILES_FROM_THIS_DIR ${SRC_DIR_TO_GLOB}/*.mm)
#MESSAGE(STATUS "SRC_FILES_FROM_THIS_DIR: ${SRC_FILES_FROM_THIS_DIR}")
- SET(MG_SOURCE_FILES ${MG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
+ SET(ZG_SOURCE_FILES ${ZG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
FILE(GLOB SRC_FILES_FROM_THIS_DIR ${SRC_DIR_TO_GLOB}/*.m)
#MESSAGE(STATUS "SRC_FILES_FROM_THIS_DIR: ${SRC_FILES_FROM_THIS_DIR}")
- SET(MG_SOURCE_FILES ${MG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
+ SET(ZG_SOURCE_FILES ${ZG_SOURCE_FILES} ${SRC_FILES_FROM_THIS_DIR})
ENDIF(APPLE)
ENDFOREACH(DIR)
@@ -261,18 +261,18 @@ IF(BUILD_MEGAGLEST)
ENDIF()
IF(WANT_DEV_OUTPATH)
- SET(EXECUTABLE_OUTPUT_PATH "${MEGAGLEST_FRIENDLY_OUTPUT_PATH}")
+ SET(EXECUTABLE_OUTPUT_PATH "${ZETAGLEST_FRIENDLY_OUTPUT_PATH}")
ENDIF()
MESSAGE(STATUS "***Note: The final output path for the ZetaGlest engine will be [${EXECUTABLE_OUTPUT_PATH}]")
- SET_SOURCE_FILES_PROPERTIES(${MG_INCLUDE_FILES} PROPERTIES HEADER_FILE_ONLY 1)
+ SET_SOURCE_FILES_PROPERTIES(${ZG_INCLUDE_FILES} PROPERTIES HEADER_FILE_ONLY 1)
- ADD_EXECUTABLE(${TARGET_NAME} ${MG_SOURCE_FILES} ${MG_INCLUDE_FILES})
+ ADD_EXECUTABLE(${TARGET_NAME} ${ZG_SOURCE_FILES} ${ZG_INCLUDE_FILES})
- SET(MG_STREFLOP "")
+ SET(ZG_STREFLOP "")
IF(WANT_USE_STREFLOP AND NOT STREFLOP_FOUND)
- SET(MG_STREFLOP "streflop")
+ SET(ZG_STREFLOP "streflop")
ENDIF()
if(WANT_USE_GoogleBreakpad)
@@ -289,12 +289,12 @@ IF(BUILD_MEGAGLEST)
endif()
IF(WIN32)
- TARGET_LINK_LIBRARIES(${TARGET_NAME} stdc++ gcc odbc32 wsock32 winspool winmm shell32 comctl32 ctl3d32 advapi32 wsock32 opengl32 glu32 ole32 oleaut32 uuid mingw32 ddraw dsound dxguid ws2_32 iphlpapi wsock32 libogg libvorbis libvorbisfile zlib jpeg libpng xerces-c2_8_0 OpenAL32 libcurl winmm gdi32 opengl32 glu32 ${SDL_VERSION_NAME} ${SDL_VERSION_NAME}main lua5.1 ${MG_STREFLOP} libmegaglest stdc++ moldname mingwex msvcrt user32 kernel32)
+ TARGET_LINK_LIBRARIES(${TARGET_NAME} stdc++ gcc odbc32 wsock32 winspool winmm shell32 comctl32 ctl3d32 advapi32 wsock32 opengl32 glu32 ole32 oleaut32 uuid mingw32 ddraw dsound dxguid ws2_32 iphlpapi wsock32 libogg libvorbis libvorbisfile zlib jpeg libpng xerces-c2_8_0 OpenAL32 libcurl winmm gdi32 opengl32 glu32 ${SDL_VERSION_NAME} ${SDL_VERSION_NAME}main lua5.1 ${ZG_STREFLOP} libmegaglest stdc++ moldname mingwex msvcrt user32 kernel32)
ENDIF()
IF(NOT WIN32)
IF(WANT_USE_STREFLOP AND NOT STREFLOP_FOUND)
- TARGET_LINK_LIBRARIES(${TARGET_NAME} ${MG_STREFLOP})
+ TARGET_LINK_LIBRARIES(${TARGET_NAME} ${ZG_STREFLOP})
ENDIF()
TARGET_LINK_LIBRARIES(${TARGET_NAME} libmegaglest)
ENDIF()
@@ -307,17 +307,17 @@ IF(BUILD_MEGAGLEST)
IF(EXISTS ${HELP2MAN})
MESSAGE(STATUS "***-- Found help2man: ${HELP2MAN} about to build manpage in [${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE}]")
- SET(MG_MANPAGE_DESCRIPTION "3D multi-player real time strategy game")
+ SET(ZG_MANPAGE_DESCRIPTION "3D multi-player real time strategy game")
IF(EXISTS ${XVFB_EXEC})
MESSAGE(STATUS "***-- Found xvfb-run: ${XVFB_EXEC} about to build manpage with it.")
add_custom_target(${TARGET_NAME_MANPAGE} ALL
- COMMAND ${XVFB_EXEC} --auto-servernum --server-num=770 ${HELP2MAN} --name="${MG_MANPAGE_DESCRIPTION}" --section=6 -N -o ${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE} ${HELP2MAN_OUT_PATH}${TARGET_NAME}
+ COMMAND ${XVFB_EXEC} --auto-servernum --server-num=770 ${HELP2MAN} --name="${ZG_MANPAGE_DESCRIPTION}" --section=6 -N -o ${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE} ${HELP2MAN_OUT_PATH}${TARGET_NAME}
DEPENDS ${TARGET_NAME})
ELSE()
add_custom_target(${TARGET_NAME_MANPAGE} ALL
- COMMAND ${HELP2MAN} --name="${MG_MANPAGE_DESCRIPTION}" --section=6 -N -o ${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE} ${HELP2MAN_OUT_PATH}${TARGET_NAME}
+ COMMAND ${HELP2MAN} --name="${ZG_MANPAGE_DESCRIPTION}" --section=6 -N -o ${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE} ${HELP2MAN_OUT_PATH}${TARGET_NAME}
DEPENDS ${TARGET_NAME})
ENDIF()
ENDIF()
@@ -329,57 +329,57 @@ IF(BUILD_MEGAGLEST)
# Installation of the program
INSTALL(TARGETS
${TARGET_NAME}
- DESTINATION ${MEGAGLEST_BIN_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_BIN_INSTALL_PATH})
- IF(EXISTS ${HELP2MAN} AND NOT "${MEGAGLEST_MANPAGE_INSTALL_PATH}" STREQUAL "")
- MESSAGE(STATUS "**NOTE: Will Install manpage [${TARGET_NAME_MANPAGE}] to [${MEGAGLEST_MANPAGE_INSTALL_PATH}]")
+ IF(EXISTS ${HELP2MAN} AND NOT "${ZETAGLEST_MANPAGE_INSTALL_PATH}" STREQUAL "")
+ MESSAGE(STATUS "**NOTE: Will Install manpage [${TARGET_NAME_MANPAGE}] to [${ZETAGLEST_MANPAGE_INSTALL_PATH}]")
# Installation of the program manpage file
INSTALL(FILES
"${HELP2MAN_OUT_PATH}${TARGET_NAME_MANPAGE}"
- DESTINATION ${MEGAGLEST_MANPAGE_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_MANPAGE_INSTALL_PATH})
ENDIF()
IF(UNIX)
INSTALL(PROGRAMS
"${PROJECT_SOURCE_DIR}/mk/linux/start_zetaglest_gameserver"
- DESTINATION ${MEGAGLEST_INI_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_INI_INSTALL_PATH})
ENDIF()
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/shared/glestkeys.ini"
"${PROJECT_SOURCE_DIR}/mk/shared/servers.ini"
- DESTINATION ${MEGAGLEST_DATA_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_DATA_INSTALL_PATH})
IF(WIN32)
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/windows/glest.ini"
- DESTINATION ${MEGAGLEST_INI_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_INI_INSTALL_PATH})
ELSEIF(UNIX AND NOT APPLE)
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/linux/glest.ini"
- DESTINATION ${MEGAGLEST_INI_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_INI_INSTALL_PATH})
ELSEIF(UNIX AND APPLE)
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/macos/glest.ini"
- DESTINATION ${MEGAGLEST_INI_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_INI_INSTALL_PATH})
IF(WANT_SINGLE_INSTALL_DIRECTORY AND EXISTS "${PROJECT_SOURCE_DIR}/mk/macos/p7zip/")
INSTALL(DIRECTORY
"${PROJECT_SOURCE_DIR}/mk/macos/p7zip"
- DESTINATION ${MEGAGLEST_DATA_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_DATA_INSTALL_PATH})
ENDIF()
IF(WANT_SINGLE_INSTALL_DIRECTORY AND EXISTS "${PROJECT_SOURCE_DIR}/mk/macos/lib/")
INSTALL(DIRECTORY
"${PROJECT_SOURCE_DIR}/mk/macos/lib/"
- DESTINATION "${MEGAGLEST_DATA_INSTALL_PATH}/../../Frameworks/")
+ DESTINATION "${ZETAGLEST_DATA_INSTALL_PATH}/../../Frameworks/")
ENDIF()
ENDIF()
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/shared/zetaglest.ico"
- DESTINATION ${MEGAGLEST_INI_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_INI_INSTALL_PATH})
IF(UNIX AND APPLE AND NOT WANT_SINGLE_INSTALL_DIRECTORY)
INSTALL(FILES
"${PROJECT_SOURCE_DIR}/mk/macos/bundle_resources/MegaGlest.icns"
- DESTINATION ${MEGAGLEST_ICON_INSTALL_PATH})
+ DESTINATION ${ZETAGLEST_ICON_INSTALL_PATH})
ENDIF()
ENDIF()
ENDIF()
diff --git a/source/glest_game/ai/ai.cpp b/source/glest_game/ai/ai.cpp
index 207dd37f3..bcacc82a3 100644
--- a/source/glest_game/ai/ai.cpp
+++ b/source/glest_game/ai/ai.cpp
@@ -19,2148 +19,1896 @@
#include "leak_dumper.h"
using namespace
- Shared::Graphics;
+Shared::Graphics;
using namespace
- Shared::Util;
+Shared::Util;
namespace
- Glest
-{
- namespace
- Game
- {
-
- Task::Task ()
- {
- taskClass = tcProduce;
- }
-
-//void Task::saveGame(XmlNode *rootNode) const {
-// std::map mapTagReplacements;
-// XmlNode *taskNode = rootNode->addChild("Task");
-//}
-
-// =====================================================
-// class ProduceTask
-// =====================================================
- ProduceTask::ProduceTask ():
- Task ()
- {
- taskClass = tcProduce;
- unitType = NULL;
- resourceType = NULL;
- unitClass = ucWarrior;
- }
-
- ProduceTask::ProduceTask (UnitClass unitClass):
- Task ()
- {
- taskClass = tcProduce;
- this->unitClass = unitClass;
- unitType = NULL;
- resourceType = NULL;
- }
-
- ProduceTask::ProduceTask (const UnitType * unitType):
- Task ()
- {
- taskClass = tcProduce;
- this->unitType = unitType;
- resourceType = NULL;
- unitClass = ucWarrior;
- }
-
- ProduceTask::ProduceTask (const ResourceType * resourceType):
- Task ()
- {
- taskClass = tcProduce;
- unitType = NULL;
- unitClass = ucWarrior;
- this->resourceType = resourceType;
- }
-
- string
- ProduceTask::toString () const
- {
- string
- str = "Produce ";
- if (unitType != NULL)
- {
- str += unitType->getName (false);
- }
- return
- str;
- }
-
- void
- ProduceTask::saveGame (XmlNode * rootNode) const
- {
- std::map <
- string,
- string >
- mapTagReplacements;
- XmlNode *
- taskNode = rootNode->addChild ("Task");
- taskNode->
- addAttribute ("taskClass", intToStr (taskClass), mapTagReplacements);
- XmlNode *
- produceTaskNode = taskNode->addChild ("ProduceTask");
-
-// UnitClass unitClass;
- produceTaskNode->
- addAttribute ("unitClass", intToStr (unitClass), mapTagReplacements);
-// const UnitType *unitType;
- if (unitType != NULL)
- {
- produceTaskNode->addAttribute ("unitType",
- unitType->getName (false),
- mapTagReplacements);
- }
-// const ResourceType *resourceType;
- if (resourceType != NULL)
- {
- produceTaskNode->addAttribute ("resourceType",
- resourceType->getName (false),
- mapTagReplacements);
- }
- }
-
- ProduceTask *
- ProduceTask::loadGame (const XmlNode * rootNode, Faction * faction)
- {
- const XmlNode *
- produceTaskNode = rootNode->getChild ("ProduceTask");
-
- ProduceTask *
- newTask = new ProduceTask ();
- // UnitClass unitClass;
- newTask->unitClass =
- static_cast < UnitClass >
- (produceTaskNode->getAttribute ("unitClass")->getIntValue ());
- // const UnitType *unitType;
- if (produceTaskNode->hasAttribute ("unitType"))
- {
- string
- unitTypeName =
- produceTaskNode->getAttribute ("unitType")->getValue ();
- newTask->unitType = faction->getType ()->getUnitType (unitTypeName);
- }
- // const ResourceType *resourceType;
- if (produceTaskNode->hasAttribute ("resourceType"))
- {
- string
- resourceTypeName =
- produceTaskNode->getAttribute ("resourceType")->getValue ();
- newTask->resourceType =
- faction->getTechTree ()->getResourceType (resourceTypeName);
- }
-
- return newTask;
- }
-
-// =====================================================
-// class BuildTask
-// =====================================================
- BuildTask::BuildTask ()
- {
- taskClass = tcBuild;
- this->unitType = NULL;
- resourceType = NULL;
- forcePos = false;
- }
-
- BuildTask::BuildTask (const UnitType * unitType)
- {
- taskClass = tcBuild;
- this->unitType = unitType;
- resourceType = NULL;
- forcePos = false;
- }
-
- BuildTask::BuildTask (const ResourceType * resourceType)
- {
- taskClass = tcBuild;
- unitType = NULL;
- this->resourceType = resourceType;
- forcePos = false;
- }
-
- BuildTask::BuildTask (const UnitType * unitType, const Vec2i & pos)
- {
- taskClass = tcBuild;
- this->unitType = unitType;
- resourceType = NULL;
- forcePos = true;
- this->pos = pos;
- }
-
- string
- BuildTask::toString () const
- {
- string
- str = "Build ";
- if (unitType != NULL)
- {
- str += unitType->getName (false);
- }
- return
- str;
- }
-
- void
- BuildTask::saveGame (XmlNode * rootNode) const
- {
- std::map <
- string,
- string >
- mapTagReplacements;
- XmlNode *
- taskNode = rootNode->addChild ("Task");
- taskNode->
- addAttribute ("taskClass", intToStr (taskClass), mapTagReplacements);
- XmlNode *
- buildTaskNode = taskNode->addChild ("BuildTask");
-
-// const UnitType *unitType;
- if (unitType != NULL)
- {
- buildTaskNode->addAttribute ("unitType", unitType->getName (false),
- mapTagReplacements);
- }
-// const ResourceType *resourceType;
- if (resourceType != NULL)
- {
- buildTaskNode->addAttribute ("resourceType",
- resourceType->getName (),
- mapTagReplacements);
- }
-// bool forcePos;
- buildTaskNode->addAttribute ("forcePos", intToStr (forcePos),
- mapTagReplacements);
-// Vec2i pos;
- buildTaskNode->addAttribute ("pos", pos.getString (),
- mapTagReplacements);
- }
-
- BuildTask *
- BuildTask::loadGame (const XmlNode * rootNode, Faction * faction)
- {
- const XmlNode *
- buildTaskNode = rootNode->getChild ("BuildTask");
-
- BuildTask *
- newTask = new BuildTask ();
- if (buildTaskNode->hasAttribute ("unitType"))
- {
- string
- unitTypeName =
- buildTaskNode->getAttribute ("unitType")->getValue ();
- newTask->unitType = faction->getType ()->getUnitType (unitTypeName);
- }
- if (buildTaskNode->hasAttribute ("resourceType"))
- {
- string
- resourceTypeName =
- buildTaskNode->getAttribute ("resourceType")->getValue ();
- newTask->resourceType =
- faction->getTechTree ()->getResourceType (resourceTypeName);
- }
-
- newTask->forcePos =
- buildTaskNode->getAttribute ("forcePos")->getIntValue () != 0;
- newTask->pos =
- Vec2i::strToVec2 (buildTaskNode->getAttribute ("pos")->getValue ());
-
- return newTask;
- }
-
-// =====================================================
-// class UpgradeTask
-// =====================================================
- UpgradeTask::UpgradeTask ()
- {
- taskClass = tcUpgrade;
- this->upgradeType = NULL;
- }
-
- UpgradeTask::UpgradeTask (const UpgradeType * upgradeType)
- {
- taskClass = tcUpgrade;
- this->upgradeType = upgradeType;
- }
-
- string
- UpgradeTask::toString () const
- {
- string
- str = "Build ";
- if (upgradeType != NULL)
- {
- str += upgradeType->getName ();
- }
- return
- str;
- }
-
- void
- UpgradeTask::saveGame (XmlNode * rootNode) const
- {
- std::map <
- string,
- string >
- mapTagReplacements;
- XmlNode *
- taskNode = rootNode->addChild ("Task");
- taskNode->
- addAttribute ("taskClass", intToStr (taskClass), mapTagReplacements);
- XmlNode *
- upgradeTaskNode = taskNode->addChild ("UpgradeTask");
-
- if (upgradeType != NULL)
- {
- //upgradeType->saveGame(upgradeTaskNode);
- upgradeTaskNode->addAttribute ("upgradeType",
- upgradeType->getName (),
- mapTagReplacements);
- }
- }
-
- UpgradeTask *
- UpgradeTask::loadGame (const XmlNode * rootNode, Faction * faction)
- {
- const XmlNode *
- upgradeTaskNode = rootNode->getChild ("UpgradeTask");
-
- UpgradeTask *
- newTask = new UpgradeTask ();
- if (upgradeTaskNode->hasAttribute ("upgradeType"))
- {
- string
- upgradeTypeName =
- upgradeTaskNode->getAttribute ("upgradeType")->getValue ();
- newTask->upgradeType =
- faction->getType ()->getUpgradeType (upgradeTypeName);
- }
- return newTask;
- }
-
-// =====================================================
-// class Ai
-// =====================================================
-
- void
- Ai::init (AiInterface * aiInterface, int useStartLocation)
- {
- this->aiInterface = aiInterface;
-
- Faction *
- faction = this->aiInterface->getMyFaction ();
- if (faction->getAIBehaviorStaticOverideValue (aibsvcMaxBuildRadius) !=
- INT_MAX)
- {
- maxBuildRadius =
- faction->getAIBehaviorStaticOverideValue (aibsvcMaxBuildRadius);
- //printf("Discovered overriden static value for AI, maxBuildRadius = %d\n",maxBuildRadius);
- }
- if (faction->getAIBehaviorStaticOverideValue (aibsvcMinMinWarriors) !=
- INT_MAX)
- {
- minMinWarriors =
- faction->getAIBehaviorStaticOverideValue (aibsvcMinMinWarriors);
- //printf("Discovered overriden static value for AI, minMinWarriors = %d\n",minMinWarriors);
- }
- if (faction->
- getAIBehaviorStaticOverideValue (aibsvcMinMinWarriorsExpandCpuEasy)
- != INT_MAX)
- {
- minMinWarriorsExpandCpuEasy =
- faction->
- getAIBehaviorStaticOverideValue
- (aibsvcMinMinWarriorsExpandCpuEasy);
- //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuEasy = %d\n",minMinWarriorsExpandCpuEasy);
- }
- if (faction->
- getAIBehaviorStaticOverideValue (aibsvcMinMinWarriorsExpandCpuZeta)
- != INT_MAX)
- {
- minMinWarriorsExpandCpuZeta =
- faction->
- getAIBehaviorStaticOverideValue
- (aibsvcMinMinWarriorsExpandCpuZeta);
- //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuZeta = %d\n",minMinWarriorsExpandCpuZeta);
- }
- if (faction->
- getAIBehaviorStaticOverideValue (aibsvcMinMinWarriorsExpandCpuUltra)
- != INT_MAX)
- {
- minMinWarriorsExpandCpuUltra =
- faction->
- getAIBehaviorStaticOverideValue
- (aibsvcMinMinWarriorsExpandCpuUltra);
- //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuUltra = %d\n",minMinWarriorsExpandCpuUltra);
- }
- if (faction->
- getAIBehaviorStaticOverideValue
- (aibsvcMinMinWarriorsExpandCpuNormal) != INT_MAX)
- {
- minMinWarriorsExpandCpuNormal =
- faction->
- getAIBehaviorStaticOverideValue
- (aibsvcMinMinWarriorsExpandCpuNormal);
- //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuNormal = %d\n",minMinWarriorsExpandCpuNormal);
- }
- if (faction->getAIBehaviorStaticOverideValue (aibsvcMaxMinWarriors) !=
- INT_MAX)
- {
- maxMinWarriors =
- faction->getAIBehaviorStaticOverideValue (aibsvcMaxMinWarriors);
- //printf("Discovered overriden static value for AI, maxMinWarriors = %d\n",maxMinWarriors);
- }
- if (faction->getAIBehaviorStaticOverideValue (aibsvcMaxExpansions) !=
- INT_MAX)
- {
- maxExpansions =
- faction->getAIBehaviorStaticOverideValue (aibsvcMaxExpansions);
- //printf("Discovered overriden static value for AI, maxExpansions = %d\n",maxExpansions);
- }
- if (faction->getAIBehaviorStaticOverideValue (aibsvcVillageRadius) !=
- INT_MAX)
- {
- villageRadius =
- faction->getAIBehaviorStaticOverideValue (aibsvcVillageRadius);
- //printf("Discovered overriden static value for AI, villageRadius = %d\n",villageRadius);
- }
- if (faction->
- getAIBehaviorStaticOverideValue (aibsvcScoutResourceRange) !=
- INT_MAX)
- {
- scoutResourceRange =
- faction->
- getAIBehaviorStaticOverideValue (aibsvcScoutResourceRange);
- //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange);
- }
- if (faction->
- getAIBehaviorStaticOverideValue (aibsvcMinWorkerAttackersHarvesting)
- != INT_MAX)
- {
- minWorkerAttackersHarvesting =
- faction->
- getAIBehaviorStaticOverideValue
- (aibsvcMinWorkerAttackersHarvesting);
- //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange);
- }
- if (faction->getAIBehaviorStaticOverideValue (aibsvcMinBuildSpacing) !=
- INT_MAX)
- {
- minBuildSpacing =
- faction->getAIBehaviorStaticOverideValue (aibsvcMinBuildSpacing);
- //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange);
- }
-
- if (useStartLocation == -1)
- {
- startLoc =
- random.randRange (0, aiInterface->getMapMaxPlayers () - 1);
- }
- else
- {
- startLoc = useStartLocation;
- }
- minWarriors = minMinWarriors;
- randomMinWarriorsReached = false;
- //add ai rules
- aiRules.clear ();
- aiRules.push_back (new AiRuleWorkerHarvest (this));
- aiRules.push_back (new AiRuleRefreshHarvester (this));
- aiRules.push_back (new AiRuleScoutPatrol (this));
- aiRules.push_back (new AiRuleUnBlock (this));
- aiRules.push_back (new AiRuleReturnBase (this));
- aiRules.push_back (new AiRuleMassiveAttack (this));
- aiRules.push_back (new AiRuleAddTasks (this));
- aiRules.push_back (new AiRuleProduceResourceProducer (this));
- aiRules.push_back (new AiRuleBuildOneFarm (this));
- aiRules.push_back (new AiRuleProduce (this));
- aiRules.push_back (new AiRuleBuild (this));
- aiRules.push_back (new AiRuleUpgrade (this));
- aiRules.push_back (new AiRuleExpand (this));
- aiRules.push_back (new AiRuleRepair (this));
- aiRules.push_back (new AiRuleRepair (this));
- }
-
- Ai::~Ai ()
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",
- __FILE__, __FUNCTION__, __LINE__,
- aiInterface);
- deleteValues (tasks.begin (), tasks.end ());
- tasks.clear ();
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",
- __FILE__, __FUNCTION__, __LINE__,
- aiInterface);
-
- deleteValues (aiRules.begin (), aiRules.end ());
- aiRules.clear ();
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",
- __FILE__, __FUNCTION__, __LINE__,
- aiInterface);
-
- aiInterface = NULL;
- }
-
- RandomGen *
- Ai::getRandom ()
- {
-// if(Thread::isCurrentThreadMainThread() == false) {
-// throw megaglest_runtime_error("Invalid access to AI random from outside main thread current id = " +
-// intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId()));
-// }
- return &random;
- }
-
- void
- Ai::update ()
- {
-
- Chrono
- chrono;
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled)
- chrono.start ();
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- if (aiInterface->getMyFaction ()->getFirstSwitchTeamVote () != NULL)
- {
- const SwitchTeamVote *
- vote = aiInterface->getMyFaction ()->getFirstSwitchTeamVote ();
- aiInterface->getMyFaction ()->
- setCurrentSwitchTeamVoteFactionIndex (vote->factionIndex);
-
- factionSwitchTeamRequestCount[vote->factionIndex]++;
- int
- factionSwitchTeamRequestCountCurrent =
- factionSwitchTeamRequestCount[vote->factionIndex];
-
- //int allowJoinTeam = random.randRange(0, 100);
- //srand(time(NULL) + aiInterface->getMyFaction()->getIndex());
- Chrono
- seed (true);
- srand ((unsigned int) seed.getCurTicks () +
- aiInterface->getMyFaction ()->getIndex ());
-
- int
- allowJoinTeam = rand () % 100;
-
- SwitchTeamVote *
- voteResult =
- aiInterface->getMyFaction ()->getSwitchTeamVote (vote->
- factionIndex);
- voteResult->voted = true;
- voteResult->allowSwitchTeam = false;
-
- const GameSettings *
- settings = aiInterface->getWorld ()->getGameSettings ();
-
- // If AI player already lost game they cannot vote
- if (aiInterface->getWorld ()->
- factionLostGame (aiInterface->getFactionIndex ()) == true)
- {
- voteResult->allowSwitchTeam = true;
- }
- else
- {
- // Can only ask the AI player 2 times max per game
- if (factionSwitchTeamRequestCountCurrent <= 2)
- {
- // x% chance the AI will answer yes
- if (settings->getAiAcceptSwitchTeamPercentChance () >= 100)
- {
- voteResult->allowSwitchTeam = true;
- }
- else if (settings->getAiAcceptSwitchTeamPercentChance () <=
- 0)
- {
- voteResult->allowSwitchTeam = false;
- }
- else
- {
- voteResult->allowSwitchTeam =
- (allowJoinTeam >=
- (100 -
- settings->getAiAcceptSwitchTeamPercentChance ()));
- }
- }
- }
-
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "AI for faction# %d voted %s [%d] CountCurrent [%d] PercentChance [%d]",
- aiInterface->getMyFaction ()->getIndex (),
- (voteResult->allowSwitchTeam ? "Yes" : "No"),
- allowJoinTeam, factionSwitchTeamRequestCountCurrent,
- settings->getAiAcceptSwitchTeamPercentChance ());
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] %s\n", __FILE__,
- __FUNCTION__, __LINE__, szBuf);
-
- aiInterface->printLog (3, szBuf);
-
- aiInterface->giveCommandSwitchTeamVote (aiInterface->
- getMyFaction (),
- voteResult);
- }
-
- //process ai rules
- for (unsigned int ruleIdx = 0; ruleIdx < aiRules.size (); ++ruleIdx)
- {
- AiRule *
- rule = aiRules[ruleIdx];
- if (rule == NULL)
- {
- throw
- megaglest_runtime_error ("rule == NULL");
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).enabled
- && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis (), ruleIdx);
- // Determines wether to process AI rules. Whether a particular rule is processed, is weighted by getTestInterval().
- // Values returned by getTestInterval() are defined in ai_rule.h.
- if ((aiInterface->getTimer () %
- (rule->getTestInterval () * GameConstants::updateFps /
- 1000)) == 0)
- {
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).enabled
- && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before rule->test()]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis (), ruleIdx);
-
- //printf("Testing AI Faction # %d RULE Name[%s]\n",aiInterface->getFactionIndex(),rule->getName().c_str());
-
- // Test to see if AI can execute rule e.g. is there a worker available to for harvesting wood?
- if (rule->test ())
- {
- if (outputAIBehaviourToConsole ())
- printf
- ("\n\nYYYYY Executing AI Faction # %d RULE Name[%s]\n\n",
- aiInterface->getFactionIndex (),
- rule->getName ().c_str ());
-
- aiInterface->printLog (3,
- intToStr (1000 *
- aiInterface->getTimer () /
- GameConstants::updateFps) +
- ": Executing rule: " +
- rule->getName () + '\n');
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before rule->execute() [%s]]\n",
- __FILE__, __FUNCTION__,
- __LINE__, chrono.getMillis (),
- ruleIdx,
- rule->getName ().c_str ());
- // Execute the rule.
- rule->execute ();
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, after rule->execute() [%s]]\n",
- __FILE__, __FUNCTION__,
- __LINE__, chrono.getMillis (),
- ruleIdx,
- rule->getName ().c_str ());
- }
- }
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [END]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
- }
-
-
-// ==================== state requests ====================
-
- int
- Ai::getCountOfType (const UnitType * ut)
- {
- int
- count = 0;
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- if (ut == aiInterface->getMyUnit (i)->getType ())
- {
- count++;
- }
- }
- return count;
- }
-
- int
- Ai::getCountOfClass (UnitClass uc,
- UnitClass * additionalUnitClassToExcludeFromCount)
- {
- int
- count = 0;
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- if (aiInterface->getMyUnit (i)->getType ()->isOfClass (uc))
- {
- // Skip unit if it ALSO contains the exclusion unit class type
- if (additionalUnitClassToExcludeFromCount != NULL)
- {
- if (aiInterface->getMyUnit (i)->getType ()->
- isOfClass (*additionalUnitClassToExcludeFromCount))
- {
- continue;
- }
- }
- ++count;
- }
- }
- return count;
- }
-
- float
- Ai::getRatioOfClass (UnitClass uc,
- UnitClass * additionalUnitClassToExcludeFromCount)
- {
- if (aiInterface->getMyUnitCount () == 0)
- {
- return 0;
- }
- else
- {
- //return static_cast(getCountOfClass(uc,additionalUnitClassToExcludeFromCount)) / aiInterface->getMyUnitCount();
- return truncateDecimal < float >(static_cast <
- float
- >(getCountOfClass
- (uc,
- additionalUnitClassToExcludeFromCount))
- / aiInterface->getMyUnitCount (),
- 6);
- }
- }
-
- const ResourceType *
- Ai::getNeededResource (int unitIndex)
- {
- int
- amount = INT_MAX;
- const ResourceType *
- neededResource = NULL;
- const TechTree *
- tt = aiInterface->getTechTree ();
- const Unit *
- unit = aiInterface->getMyUnit (unitIndex);
-
- for (int i = 0; i < tt->getResourceTypeCount (); ++i)
- {
- const ResourceType *
- rt = tt->getResourceType (i);
- const Resource *
- r = aiInterface->getResource (rt);
-
- if (rt->getClass () != rcStatic && rt->getClass () != rcConsumable)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Examining resource [%s] amount [%d] (previous amount [%d]",
- rt->getName ().c_str (), r->getAmount (), amount);
- aiInterface->printLog (3, szBuf);
- }
-
- if (rt->getClass () != rcStatic && rt->getClass () != rcConsumable
- && r->getAmount () < amount)
- {
-
- // Only have up to x units going for this resource so we can focus
- // on other needed resources for other units
- const int
- maxUnitsToHarvestResource = 5;
-
- vector < int >
- unitsGettingResource = findUnitsHarvestingResourceType (rt);
- if ((int) unitsGettingResource.size () <=
- maxUnitsToHarvestResource)
- {
- // Now MAKE SURE the unit has a harvest command for this resource
- // AND that the resource is within eye-sight to avoid units
- // standing around doing nothing.
- const HarvestCommandType *
- hct =
- unit->getType ()->getFirstHarvestCommand (rt,
- unit->
- getFaction ());
- Vec2i
- resPos;
- if (hct != NULL
- && aiInterface->getNearestSightedResource (rt,
- aiInterface->
- getHomeLocation
- (), resPos,
- false))
- {
- amount = r->getAmount ();
- neededResource = rt;
- }
- }
- }
- }
-
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Unit [%d - %s] looking for resources (not static or consumable)",
- unit->getId (), unit->getType ()->getName (false).c_str ());
- aiInterface->printLog (3, szBuf);
- snprintf (szBuf, 8096, "[resource type count %d] Needed resource [%s].",
- tt->getResourceTypeCount (),
- (neededResource !=
- NULL ? neededResource->getName ().c_str () : ""));
- aiInterface->printLog (3, szBuf);
-
- return neededResource;
- }
-
- bool
- Ai::beingAttacked (Vec2i & pos, Field & field, int radius)
- {
- const Unit *
- enemy = aiInterface->getFirstOnSightEnemyUnit (pos, field, radius);
- return (enemy != NULL);
- }
-
- bool
- Ai::isStableBase ()
- {
- UnitClass
- ucWorkerType = ucWorker;
- if (getCountOfClass (ucWarrior, &ucWorkerType) > minWarriors)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Base is stable [minWarriors = %d found = %d]",
- minWarriors, ucWorkerType);
- aiInterface->printLog (4, szBuf);
-
- return true;
- }
- else
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Base is NOT stable [minWarriors = %d found = %d]",
- minWarriors, ucWorkerType);
- aiInterface->printLog (4, szBuf);
-
- return false;
- }
- }
-
- bool
- Ai::findAbleUnit (int *unitIndex, CommandClass ability, bool idleOnly)
- {
- vector < int >
- units;
-
- *unitIndex = -1;
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- const Unit *
- unit = aiInterface->getMyUnit (i);
- if (unit->getType ()->isCommandable ()
- && unit->getType ()->hasCommandClass (ability))
- {
- if (!idleOnly || !unit->anyCommand ()
- || unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccStop)
- {
- units.push_back (i);
- }
- }
- }
-
- if (units.empty ())
- {
- return false;
- }
- else
- {
- *unitIndex = units[random.randRange (0, (int) units.size () - 1)];
- return true;
- }
- }
-
- vector < int >
- Ai::findUnitsHarvestingResourceType (const ResourceType * rt)
- {
- vector < int >
- units;
-
- Map *
- map = aiInterface->getMap ();
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- const Unit *
- unit = aiInterface->getMyUnit (i);
- if (unit->getType ()->isCommandable ())
- {
- if (unit->getType ()->hasCommandClass (ccHarvest))
- {
- if (unit->anyCommand ()
- && unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccHarvest)
- {
- Command *
- command = unit->getCurrCommand ();
- const HarvestCommandType *
- hct = dynamic_cast < const
- HarvestCommandType * >(command->getCommandType ());
- if (hct != NULL)
- {
- const Vec2i
- unitTargetPos = unit->getTargetPos ();
- SurfaceCell *
- sc =
- map->
- getSurfaceCell (Map::
- toSurfCoords (unitTargetPos));
- Resource *
- r = sc->getResource ();
- if (r != NULL && r->getType () == rt)
- {
- units.push_back (i);
- }
- }
- }
- }
- else if (unit->getType ()->hasCommandClass (ccProduce))
- {
- if (unit->anyCommand ()
- && unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccProduce)
- {
- Command *
- command = unit->getCurrCommand ();
- const ProduceCommandType *
- pct = dynamic_cast < const
- ProduceCommandType * >(command->getCommandType ());
- if (pct != NULL)
- {
- const UnitType *
- ut = pct->getProducedUnit ();
- if (ut != NULL)
- {
- const Resource *
- r = ut->getCost (rt);
- if (r != NULL)
- {
- if (r != NULL && r->getAmount () < 0)
- {
- units.push_back (i);
- }
- }
- }
- }
- }
- }
- else if (unit->getType ()->hasCommandClass (ccBuild))
- {
- if (unit->anyCommand ()
- && unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccBuild)
- {
- Command *
- command = unit->getCurrCommand ();
- const BuildCommandType *
- bct = dynamic_cast < const
- BuildCommandType * >(command->getCommandType ());
- if (bct != NULL)
- {
- for (int j = 0; j < bct->getBuildingCount (); ++j)
- {
- const UnitType *
- ut = bct->getBuilding (j);
- if (ut != NULL)
- {
- const Resource *
- r = ut->getCost (rt);
- if (r != NULL)
- {
- if (r != NULL && r->getAmount () < 0)
- {
- units.push_back (i);
- break;
- }
- }
- }
- }
- }
- }
- }
- }
- }
-
- return units;
- }
-
-//vector Ai::findUnitsDoingCommand(CommandClass currentCommand) {
-// vector units;
-//
-// for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
-// const Unit *unit= aiInterface->getMyUnit(i);
-// if(unit->getType()->isCommandable() && unit->getType()->hasCommandClass(currentCommand)) {
-// if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() == currentCommand) {
-// units.push_back(i);
-// }
-// }
-// }
-//
-// return units;
-//}
-
- bool
- Ai::findAbleUnit (int *unitIndex, CommandClass ability,
- CommandClass currentCommand)
- {
- vector < int >
- units;
-
- *unitIndex = -1;
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- const Unit *
- unit = aiInterface->getMyUnit (i);
- if (unit->getType ()->isCommandable ()
- && unit->getType ()->hasCommandClass (ability))
- {
- if (unit->anyCommand ()
- && unit->getCurrCommand ()->getCommandType ()->
- getClass () == currentCommand)
- {
- units.push_back (i);
- }
- }
- }
-
- if (units.empty ())
- {
- return false;
- }
- else
- {
- *unitIndex = units[random.randRange (0, (int) units.size () - 1)];
- return true;
- }
- }
-
- bool
- Ai::findPosForBuilding (const UnitType * building,
- const Vec2i & searchPos, Vec2i & outPos)
- {
-
- for (int currRadius = 0; currRadius < maxBuildRadius; ++currRadius)
- {
- for (int i = searchPos.x - currRadius; i < searchPos.x + currRadius;
- ++i)
- {
- for (int j = searchPos.y - currRadius;
- j < searchPos.y + currRadius; ++j)
- {
- outPos = Vec2i (i, j);
- if (aiInterface->
- isFreeCells (outPos - Vec2i (minBuildSpacing),
- building->getAiBuildSize () +
- minBuildSpacing * 2, fLand))
- {
- int
- aiBuildSizeDiff =
- building->getAiBuildSize () - building->getSize ();
- if (aiBuildSizeDiff > 0)
- {
- int
- halfSize = aiBuildSizeDiff / 2;
- outPos.x += halfSize;
- outPos.y += halfSize;
- }
- return true;
- }
- }
- }
- }
-
- return false;
-
- }
-
-
-// ==================== tasks ====================
-
- void
- Ai::addTask (const Task * task)
- {
- tasks.push_back (task);
- aiInterface->printLog (2, "Task added: " + task->toString ());
- }
-
- void
- Ai::addPriorityTask (const Task * task)
- {
- deleteValues (tasks.begin (), tasks.end ());
- tasks.clear ();
-
- tasks.push_back (task);
- aiInterface->printLog (2, "Priority Task added: " + task->toString ());
- }
-
- bool
- Ai::anyTask ()
- {
- return !tasks.empty ();
- }
-
- const Task *
- Ai::getTask () const
- {
- if (tasks.empty ())
- {
- return NULL;
- }
- else
- {
- return tasks.front ();
- }
- }
-
- void
- Ai::removeTask (const Task * task)
- {
- aiInterface->printLog (2, "Task removed: " + task->toString ());
- tasks.remove (task);
- delete
- task;
- }
-
- void
- Ai::retryTask (const Task * task)
- {
- tasks.remove (task);
- tasks.push_back (task);
- }
-// ==================== expansions ====================
-
- void
- Ai::addExpansion (const Vec2i & pos)
- {
-
- //check if there is a nearby expansion
- for (Positions::iterator it = expansionPositions.begin ();
- it != expansionPositions.end (); ++it)
- {
- if ((*it).dist (pos) < villageRadius)
- {
- return;
- }
- }
-
- //add expansion
- expansionPositions.push_front (pos);
-
- //remove expansion if queue is list is full
- if ((int) expansionPositions.size () > maxExpansions)
- {
- expansionPositions.pop_back ();
- }
- }
-
- Vec2i
- Ai::getRandomHomePosition ()
- {
-
- if (expansionPositions.empty () || random.randRange (0, 1) == 0)
- {
- return aiInterface->getHomeLocation ();
- }
-
- return expansionPositions[random.
- randRange (0,
- (int) expansionPositions.size () -
- 1)];
- }
-
-// ==================== actions ====================
-
- void
- Ai::sendScoutPatrol ()
- {
-
- Vec2i
- pos;
- int
- unit;
- bool
- possibleTargetFound = false;
-
- bool
- ultraResourceAttack = (aiInterface->getControlType () == ctCpuUltra
- || aiInterface->getControlType () ==
- ctNetworkCpuUltra)
- && random.randRange (0, 2) == 1;
- bool
- megaResourceAttack = (aiInterface->getControlType () == ctCpuZeta
- || aiInterface->getControlType () ==
- ctNetworkCpuZeta)
- && random.randRange (0, 1) == 1;
-
- if (megaResourceAttack || ultraResourceAttack)
- {
- Map *
- map = aiInterface->getMap ();
-
- const TechTree *
- tt = aiInterface->getTechTree ();
- const ResourceType *
- rt = tt->getResourceType (0);
- int
- tryCount = 0;
- int
- height = map->getH ();
- int
- width = map->getW ();
-
- for (int i = 0; i < tt->getResourceTypeCount (); ++i)
- {
- const ResourceType *
- rt_ = tt->getResourceType (i);
- //const Resource *r= aiInterface->getResource(rt);
-
- if (rt_->getClass () == rcTech)
- {
- rt = rt_;
- break;
- }
- }
- //printf("looking for resource %s\n",rt->getName().c_str());
- while (possibleTargetFound == false)
- {
- tryCount++;
- if (tryCount == 4)
- {
- //printf("no target found\n");
- break;
- }
- pos =
- Vec2i (random.randRange (2, width - 2),
- random.randRange (2, height - 2));
- if (map->isInside (pos)
- && map->isInsideSurface (map->toSurfCoords (pos)))
- {
- //printf("is inside map\n");
- // find first resource in this area
- Vec2i
- resPos;
- if (aiInterface->
- isResourceInRegion (pos, rt, resPos,
- scoutResourceRange))
- {
- // found a possible target.
- pos = resPos;
- //printf("lets try the new target\n");
- possibleTargetFound = true;
- break;
- }
- }
- //else printf("is outside map\n");
- }
- }
-
- std::vector < Vec2i > warningEnemyList =
- aiInterface->getEnemyWarningPositionList ();
- if ((possibleTargetFound == false)
- && (warningEnemyList.empty () == false))
- {
- //for(int i = (int)warningEnemyList.size() - 1; i <= 0; --i) {
- //Vec2i &checkPos = warningEnemyList[i];
- Vec2i & checkPos = warningEnemyList[0];
- if (random.randRange (0, 1) == 1)
- {
- pos = checkPos;
- possibleTargetFound = true;
- warningEnemyList.clear ();
- }
- else
- {
- aiInterface->removeEnemyWarningPositionFromList (checkPos);
- }
- //break;
- //}
- }
-
- if (possibleTargetFound == false)
- {
- startLoc = (startLoc + 1) % aiInterface->getMapMaxPlayers ();
- pos = aiInterface->getStartLocation (startLoc);
- //printf("normal target used\n");
- }
-
- if (aiInterface->getHomeLocation () != pos)
- {
- if (findAbleUnit (&unit, ccAttack, false))
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- aiInterface->giveCommand (unit, ccAttack, pos);
- aiInterface->printLog (2,
- "Scout patrol sent to: " +
- intToStr (pos.x) + "," +
- intToStr (pos.y) + "\n");
- }
- }
- }
-
- void
- Ai::massiveAttack (const Vec2i & pos, Field field, bool ultraAttack)
- {
- int
- producerWarriorCount = 0;
- int
- maxProducerWarriors = random.randRange (1, 11);
- int
- unitCount = aiInterface->getMyUnitCount ();
- int
- unitGroupCommandId = -1;
-
- int
- attackerWorkersHarvestingCount = 0;
- for (int i = 0; i < unitCount; ++i)
- {
- bool
- isWarrior = false;
- bool
- productionInProgress = false;
- const Unit *
- unit = aiInterface->getMyUnit (i);
- const AttackCommandType *
- act = unit->getType ()->getFirstAttackCommand (field);
-
- if (aiInterface->getControlType () == ctCpuZeta ||
- aiInterface->getControlType () == ctNetworkCpuZeta)
- {
- if (producerWarriorCount > maxProducerWarriors)
- {
- if (unit->getCommandSize () > 0 &&
- unit->getCurrCommand ()->getCommandType () != NULL
- && (unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccBuild
- || unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccMorph
- || unit->getCurrCommand ()->getCommandType ()->
- getClass () == ccProduce))
- {
- productionInProgress = true;
- isWarrior = false;
- producerWarriorCount++;
- }
- else
- {
- isWarrior =
- !unit->getType ()->hasCommandClass (ccHarvest);
- }
-
- }
- else
- {
- isWarrior = !unit->getType ()->hasCommandClass (ccHarvest)
- && !unit->getType ()->hasCommandClass (ccProduce);
- }
- }
- else
- {
- isWarrior = !unit->getType ()->hasCommandClass (ccHarvest)
- && !unit->getType ()->hasCommandClass (ccProduce);
- }
-
- bool
- alreadyAttacking =
- (unit->getCurrSkill ()->getClass () == scAttack);
-
- bool
- unitSignalledToAttack = false;
- if (alreadyAttacking == false
- && unit->getType ()->hasSkillClass (scAttack)
- && (aiInterface->getControlType () == ctCpuUltra
- || aiInterface->getControlType () == ctCpuZeta
- || aiInterface->getControlType () == ctNetworkCpuUltra
- || aiInterface->getControlType () == ctNetworkCpuZeta))
- {
- //printf("~~~~~~~~ Unit [%s - %d] checking if unit is being attacked\n",unit->getFullName().c_str(),unit->getId());
-
- std::pair < bool, Unit * >beingAttacked =
- aiInterface->getWorld ()->getUnitUpdater ()->
- unitBeingAttacked (unit);
- if (beingAttacked.first == true)
- {
- Unit *
- enemy = beingAttacked.second;
- const AttackCommandType *
- act_forenemy =
- unit->getType ()->getFirstAttackCommand (enemy->
- getCurrField ());
-
- //printf("~~~~~~~~ Unit [%s - %d] attacked by enemy [%s - %d] act_forenemy [%p] enemy->getCurrField() = %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),act_forenemy,enemy->getCurrField());
-
- if (act_forenemy != NULL)
- {
- bool
- shouldAttack = true;
- if (unit->getType ()->hasSkillClass (scHarvest))
- {
- shouldAttack =
- (attackerWorkersHarvestingCount >
- minWorkerAttackersHarvesting);
- if (shouldAttack == false)
- {
- attackerWorkersHarvestingCount++;
- }
- }
- if (shouldAttack)
- {
- if (unitGroupCommandId == -1)
- {
- unitGroupCommandId =
- aiInterface->getWorld ()->
- getNextCommandGroupId ();
- }
-
- aiInterface->giveCommand (i, act_forenemy,
- beingAttacked.second->
- getPos (),
- unitGroupCommandId);
- unitSignalledToAttack = true;
- }
- }
- else
- {
- const AttackStoppedCommandType *
- asct_forenemy =
- unit->getType ()->
- getFirstAttackStoppedCommand (enemy->getCurrField ());
- //printf("~~~~~~~~ Unit [%s - %d] found enemy [%s - %d] asct_forenemy [%p] enemy->getCurrField() = %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),asct_forenemy,enemy->getCurrField());
- if (asct_forenemy != NULL)
- {
- bool
- shouldAttack = true;
- if (unit->getType ()->hasSkillClass (scHarvest))
- {
- shouldAttack =
- (attackerWorkersHarvestingCount >
- minWorkerAttackersHarvesting);
- if (shouldAttack == false)
- {
- attackerWorkersHarvestingCount++;
- }
- }
- if (shouldAttack)
- {
-// printf("~~~~~~~~ Unit [%s - %d] WILL AttackStoppedCommand [%s - %d]\n", unit->getFullName().c_str(),
-// unit->getId(), enemy->getFullName().c_str(), enemy->getId());
-
- if (unitGroupCommandId == -1)
- {
- unitGroupCommandId =
- aiInterface->getWorld ()->
- getNextCommandGroupId ();
- }
-
- aiInterface->giveCommand (i, asct_forenemy,
- beingAttacked.second->
- getCenteredPos (),
- unitGroupCommandId);
- unitSignalledToAttack = true;
- }
- }
- }
- }
- }
- if (alreadyAttacking == false && act != NULL
- && (ultraAttack || isWarrior) && unitSignalledToAttack == false)
- {
- bool
- shouldAttack = true;
- if (unit->getType ()->hasSkillClass (scHarvest))
- {
- shouldAttack =
- (attackerWorkersHarvestingCount >
- minWorkerAttackersHarvesting);
- if (shouldAttack == false)
- {
- attackerWorkersHarvestingCount++;
- }
- }
-
- // Zeta CPU does not send ( far away ) units which are currently producing something
- if (aiInterface->getControlType () == ctCpuZeta
- || aiInterface->getControlType () == ctNetworkCpuZeta)
- {
- if (!isWarrior)
- {
- if (!productionInProgress)
- {
- shouldAttack = false;
- //printf("no attack \n ");
- }
- }
- }
- if (shouldAttack)
- {
- if (unitGroupCommandId == -1)
- {
- unitGroupCommandId =
- aiInterface->getWorld ()->getNextCommandGroupId ();
- }
-
- aiInterface->giveCommand (i, act, pos, unitGroupCommandId);
- }
- }
- }
-
- if (aiInterface->getControlType () == ctCpuEasy ||
- aiInterface->getControlType () == ctNetworkCpuEasy)
- {
- minWarriors += minMinWarriorsExpandCpuEasy;
- }
- else if (aiInterface->getControlType () == ctCpuZeta ||
- aiInterface->getControlType () == ctNetworkCpuZeta)
- {
- minWarriors += minMinWarriorsExpandCpuZeta;
- if (minWarriors > maxMinWarriors - 1 || randomMinWarriorsReached)
- {
- randomMinWarriorsReached = true;
- minWarriors =
- random.randRange (maxMinWarriors - 10, maxMinWarriors * 2);
- }
- }
- else if (minWarriors < maxMinWarriors)
- {
- if (aiInterface->getControlType () == ctCpuUltra ||
- aiInterface->getControlType () == ctNetworkCpuUltra)
- {
- minWarriors += minMinWarriorsExpandCpuUltra;
- }
- else
- {
- minWarriors += minMinWarriorsExpandCpuNormal;
- }
- }
- aiInterface->printLog (2,
- "Massive attack to pos: " + intToStr (pos.x) +
- ", " + intToStr (pos.y) + "\n");
- }
-
- void
- Ai::returnBase (int unitIndex)
- {
- Vec2i
- pos;
- //std::pair r(crFailUndefined,"");
- //aiInterface->getFactionIndex();
- pos = Vec2i (random.randRange (-villageRadius, villageRadius),
- random.randRange (-villageRadius, villageRadius)) +
- getRandomHomePosition ();
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- //r= aiInterface->giveCommand(unitIndex, ccMove, pos);
- aiInterface->giveCommand (unitIndex, ccMove, pos);
-
- //aiInterface->printLog(1, "Order return to base pos:" + intToStr(pos.x)+", "+intToStr(pos.y)+": "+rrToStr(r)+"\n");
- }
-
- void
- Ai::harvest (int unitIndex)
- {
- const ResourceType *
- rt = getNeededResource (unitIndex);
- if (rt != NULL)
- {
- const HarvestCommandType *
- hct =
- aiInterface->getMyUnit (unitIndex)->getType ()->
- getFirstHarvestCommand (rt,
- aiInterface->getMyUnit (unitIndex)->
- getFaction ());
-
- Vec2i
- resPos;
- if (hct != NULL
- && aiInterface->getNearestSightedResource (rt,
- aiInterface->
- getHomeLocation (),
- resPos, false))
- {
- resPos =
- resPos + Vec2i (random.randRange (-2, 2),
- random.randRange (-2, 2));
- aiInterface->giveCommand (unitIndex, hct, resPos, -1);
- //aiInterface->printLog(4, "Order harvest pos:" + intToStr(resPos.x)+", "+intToStr(resPos.y)+": "+rrToStr(r)+"\n");
- }
- }
- }
-
- bool
- Ai::haveBlockedUnits ()
- {
- Chrono
- chrono;
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled)
- chrono.start ();
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- int
- unitCount = aiInterface->getMyUnitCount ();
- Map *
- map = aiInterface->getMap ();
- //If there is no close store
- for (int j = 0; j < unitCount; ++j)
- {
- const Unit *
- u = aiInterface->getMyUnit (j);
- const UnitType *
- ut = u->getType ();
-
- // If this building is a store
- if (u->isAlive () && ut->isMobile () && u->getPath () != NULL
- && (u->getPath ()->isBlocked ()
- || u->getPath ()->getBlockCount ()))
- {
- Vec2i
- unitPos = u->getPosNotThreadSafe ();
-
- //printf("#1 AI found blocked unit [%d - %s]\n",u->getId(),u->getFullName().c_str());
-
- int
- failureCount = 0;
- int
- cellCount = 0;
-
- for (int i = -1; i <= 1; ++i)
- {
- for (int j = -1; j <= 1; ++j)
- {
- Vec2i
- pos = unitPos + Vec2i (i, j);
- if (map->isInside (pos)
- && map->isInsideSurface (map->toSurfCoords (pos)))
- {
- if (pos != unitPos)
- {
- bool
- canUnitMoveToCell =
- map->aproxCanMove (u, unitPos, pos);
- if (canUnitMoveToCell == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- }
- bool
- unitImmediatelyBlocked = (failureCount == cellCount);
- //printf("#1 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = %d\n",unitImmediatelyBlocked,failureCount,cellCount);
-
- if (unitImmediatelyBlocked)
- {
- //printf("#1 AI unit IS BLOCKED [%d - %s]\n",u->getId(),u->getFullName().c_str());
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__,
- __LINE__, chrono.getMillis ());
- return true;
- }
- }
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
- return false;
- }
-
- bool
- Ai::getAdjacentUnits (std::map < float, std::map < int,
- const Unit * > >&signalAdjacentUnits,
- const Unit * unit)
- {
- //printf("In getAdjacentUnits...\n");
-
- bool
- result = false;
- Map *
- map = aiInterface->getMap ();
- Vec2i
- unitPos = unit->getPosNotThreadSafe ();
- for (int i = -1; i <= 1; ++i)
- {
- for (int j = -1; j <= 1; ++j)
- {
- Vec2i
- pos = unitPos + Vec2i (i, j);
- if (map->isInside (pos)
- && map->isInsideSurface (map->toSurfCoords (pos)))
- {
- if (pos != unitPos)
- {
- Unit *
- adjacentUnit =
- map->getCell (pos)->getUnit (unit->getCurrField ());
- if (adjacentUnit != NULL
- && adjacentUnit->getFactionIndex () ==
- unit->getFactionIndex ())
- {
- if (adjacentUnit->getType ()->isMobile ()
- && adjacentUnit->getPath () != NULL)
- {
- //signalAdjacentUnits.push_back(adjacentUnit);
- float
- dist = unitPos.dist (adjacentUnit->getPos ());
-
- std::map < float,
- std::map < int, const Unit *> >::iterator
- iterFind1 = signalAdjacentUnits.find (dist);
- if (iterFind1 == signalAdjacentUnits.end ())
- {
- signalAdjacentUnits[dist][adjacentUnit->
- getId ()] =
- adjacentUnit;
-
- getAdjacentUnits (signalAdjacentUnits,
- adjacentUnit);
- result = true;
- }
- else
- {
- std::map < int, const Unit *>::iterator
- iterFind2 =
- iterFind1->second.find (adjacentUnit->
- getId ());
- if (iterFind2 == iterFind1->second.end ())
- {
- signalAdjacentUnits[dist][adjacentUnit->
- getId ()] =
- adjacentUnit;
- getAdjacentUnits (signalAdjacentUnits,
- adjacentUnit);
- result = true;
- }
- }
- }
- }
- }
- }
- }
- }
- return result;
- }
-
- void
- Ai::unblockUnits ()
- {
- Chrono
- chrono;
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled)
- chrono.start ();
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- int
- unitCount = aiInterface->getMyUnitCount ();
- Map *
- map = aiInterface->getMap ();
- // Find blocked units and move surrounding units out of the way
- std::map < float,
- std::map < int, const Unit *> >
- signalAdjacentUnits;
- for (int idx = 0; idx < unitCount; ++idx)
- {
- const Unit *
- u = aiInterface->getMyUnit (idx);
- const UnitType *
- ut = u->getType ();
-
- // If this building is a store
- if (u->isAlive () && ut->isMobile () && u->getPath () != NULL
- && (u->getPath ()->isBlocked ()
- || u->getPath ()->getBlockCount ()))
- {
- Vec2i
- unitPos = u->getPosNotThreadSafe ();
-
- //printf("#2 AI found blocked unit [%d - %s]\n",u->getId(),u->getFullName().c_str());
-
- //int failureCount = 0;
- //int cellCount = 0;
-
- for (int i = -1; i <= 1; ++i)
- {
- for (int j = -1; j <= 1; ++j)
- {
- Vec2i
- pos = unitPos + Vec2i (i, j);
- if (map->isInside (pos)
- && map->isInsideSurface (map->toSurfCoords (pos)))
- {
- if (pos != unitPos)
- {
- bool
- canUnitMoveToCell =
- map->aproxCanMove (u, unitPos, pos);
- if (canUnitMoveToCell == false)
- {
- //failureCount++;
- getAdjacentUnits (signalAdjacentUnits, u);
- }
- //cellCount++;
- }
- }
- }
- }
- //bool unitImmediatelyBlocked = (failureCount == cellCount);
- //printf("#2 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = %d, signalAdjacentUnits.size() = %d\n",unitImmediatelyBlocked,failureCount,cellCount,signalAdjacentUnits.size());
- }
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- if (signalAdjacentUnits.empty () == false)
- {
- //printf("#2 AI units ARE BLOCKED about to unblock\n");
-
- int
- unitGroupCommandId = -1;
-
- for (std::map < float, std::map < int,
- const Unit * > >::reverse_iterator iterMap =
- signalAdjacentUnits.rbegin ();
- iterMap != signalAdjacentUnits.rend (); ++iterMap)
- {
-
- for (std::map < int, const Unit * >::iterator iterMap2 =
- iterMap->second.begin ();
- iterMap2 != iterMap->second.end (); ++iterMap2)
- {
- //int idx = iterMap2->first;
- const Unit *
- adjacentUnit = iterMap2->second;
- if (adjacentUnit != NULL
- && adjacentUnit->getType ()->
- getFirstCtOfClass (ccMove) != NULL)
- {
- const CommandType *
- ct =
- adjacentUnit->getType ()->getFirstCtOfClass (ccMove);
-
- for (int moveAttempt = 1; moveAttempt <= villageRadius;
- ++moveAttempt)
- {
- Vec2i
- pos =
- Vec2i (random.
- randRange (-villageRadius * 2,
- villageRadius * 2),
- random.randRange (-villageRadius * 2,
- villageRadius * 2)) +
- adjacentUnit->getPosNotThreadSafe ();
-
- bool
- canUnitMoveToCell =
- map->aproxCanMove (adjacentUnit,
- adjacentUnit->
- getPosNotThreadSafe (), pos);
- if (canUnitMoveToCell == true)
- {
-
- if (ct != NULL)
- {
- if (unitGroupCommandId == -1)
- {
- unitGroupCommandId =
- aiInterface->getWorld ()->
- getNextCommandGroupId ();
- }
-
- //std::pair r = aiInterface->giveCommand(adjacentUnit,ct, pos, unitGroupCommandId);
- aiInterface->giveCommand (adjacentUnit, ct,
- pos,
- unitGroupCommandId);
- }
- }
- }
- }
- }
- }
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled && chrono.getMillis () > 0)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld [START]\n",
- __FILE__, __FUNCTION__, __LINE__,
- chrono.getMillis ());
- }
-
- bool
- Ai::outputAIBehaviourToConsole () const
- {
- return
- false;
- }
-
- void
- Ai::saveGame (XmlNode * rootNode) const
- {
- std::map <
- string,
- string >
- mapTagReplacements;
- XmlNode *
- aiNode = rootNode->addChild ("Ai");
-
-// AiInterface *aiInterface;
-// AiRules aiRules;
-// int startLoc;
- aiNode->
- addAttribute ("startLoc", intToStr (startLoc), mapTagReplacements);
-// bool randomMinWarriorsReached;
- aiNode->
- addAttribute ("randomMinWarriorsReached",
- intToStr (randomMinWarriorsReached), mapTagReplacements);
-// Tasks tasks;
- for (Tasks::const_iterator it = tasks.begin (); it != tasks.end ();
- ++it)
- {
- (*it)->saveGame (aiNode);
- }
-// Positions expansionPositions;
- for (Positions::const_iterator it = expansionPositions.begin ();
- it != expansionPositions.end (); ++it)
- {
- XmlNode *
- expansionPositionsNode = aiNode->addChild ("expansionPositions");
- expansionPositionsNode->addAttribute ("pos", (*it).getString (),
- mapTagReplacements);
- }
-
-// RandomGen random;
- aiNode->addAttribute ("random", intToStr (random.getLastNumber ()),
- mapTagReplacements);
-// std::map factionSwitchTeamRequestCount;
-
-// int maxBuildRadius;
- aiNode->addAttribute ("maxBuildRadius", intToStr (maxBuildRadius),
- mapTagReplacements);
-// int minMinWarriors;
- aiNode->addAttribute ("minMinWarriors", intToStr (minMinWarriors),
- mapTagReplacements);
-// int minMinWarriorsExpandCpuEasy;
- aiNode->addAttribute ("minMinWarriorsExpandCpuEasy",
- intToStr (minMinWarriorsExpandCpuEasy),
- mapTagReplacements);
-// int minMinWarriorsExpandCpuZeta;
- aiNode->addAttribute ("minMinWarriorsExpandCpuZeta",
- intToStr (minMinWarriorsExpandCpuZeta),
- mapTagReplacements);
-// int minMinWarriorsExpandCpuUltra;
- aiNode->addAttribute ("minMinWarriorsExpandCpuUltra",
- intToStr (minMinWarriorsExpandCpuUltra),
- mapTagReplacements);
-// int minMinWarriorsExpandCpuNormal;
- aiNode->addAttribute ("minMinWarriorsExpandCpuNormal",
- intToStr (minMinWarriorsExpandCpuNormal),
- mapTagReplacements);
-// int maxMinWarriors;
- aiNode->addAttribute ("maxMinWarriors", intToStr (maxMinWarriors),
- mapTagReplacements);
-// int maxExpansions;
- aiNode->addAttribute ("maxExpansions", intToStr (maxExpansions),
- mapTagReplacements);
-// int villageRadius;
- aiNode->addAttribute ("villageRadius", intToStr (villageRadius),
- mapTagReplacements);
-// int scoutResourceRange;
- aiNode->addAttribute ("scoutResourceRange",
- intToStr (scoutResourceRange),
- mapTagReplacements);
-// int minWorkerAttackersHarvesting;
- aiNode->addAttribute ("minWorkerAttackersHarvesting",
- intToStr (minWorkerAttackersHarvesting),
- mapTagReplacements);
- }
-
- void
- Ai::loadGame (const XmlNode * rootNode, Faction * faction)
- {
- const XmlNode *
- aiNode = rootNode->getChild ("Ai");
-
- startLoc = aiNode->getAttribute ("startLoc")->getIntValue ();
- randomMinWarriorsReached =
- aiNode->getAttribute ("randomMinWarriorsReached")->getIntValue () !=
- 0;
-
- vector < XmlNode * >taskNodeList = aiNode->getChildList ("Task");
- for (unsigned int i = 0; i < taskNodeList.size (); ++i)
- {
- XmlNode *
- taskNode = taskNodeList[i];
- TaskClass
- taskClass =
- static_cast < TaskClass >
- (taskNode->getAttribute ("taskClass")->getIntValue ());
- switch (taskClass)
- {
- case tcProduce:
- {
- ProduceTask *
- newTask = ProduceTask::loadGame (taskNode, faction);
- tasks.push_back (newTask);
- }
- break;
- case tcBuild:
- {
- BuildTask *
- newTask = BuildTask::loadGame (taskNode, faction);
- tasks.push_back (newTask);
- }
- break;
- case tcUpgrade:
- {
- UpgradeTask *
- newTask = UpgradeTask::loadGame (taskNode, faction);
- tasks.push_back (newTask);
- }
- break;
- }
- }
-
- vector < XmlNode * >expansionPositionsNodeList =
- aiNode->getChildList ("expansionPositions");
- for (unsigned int i = 0; i < expansionPositionsNodeList.size (); ++i)
- {
- XmlNode *
- expansionPositionsNode = expansionPositionsNodeList[i];
- Vec2i
- pos =
- Vec2i::strToVec2 (expansionPositionsNode->getAttribute ("pos")->
- getValue ());
- expansionPositions.push_back (pos);
- }
-
- // RandomGen random;
- random.setLastNumber (aiNode->getAttribute ("random")->getIntValue ());
- // std::map factionSwitchTeamRequestCount;
-
- // int maxBuildRadius;
- maxBuildRadius =
- aiNode->getAttribute ("maxBuildRadius")->getIntValue ();
- // int minMinWarriors;
- minMinWarriors =
- aiNode->getAttribute ("minMinWarriors")->getIntValue ();
- // int minMinWarriorsExpandCpuEasy;
- minMinWarriorsExpandCpuEasy =
- aiNode->getAttribute ("minMinWarriorsExpandCpuEasy")->getIntValue ();
- // int minMinWarriorsExpandCpZeta;
- minMinWarriorsExpandCpuZeta =
- aiNode->getAttribute ("minMinWarriorsExpandCpuZeta")->getIntValue ();
- // int minMinWarriorsExpandCpuUltra;
- minMinWarriorsExpandCpuUltra =
- aiNode->getAttribute ("minMinWarriorsExpandCpuUltra")->getIntValue ();
- // int minMinWarriorsExpandCpuNormal;
- minMinWarriorsExpandCpuNormal =
- aiNode->getAttribute ("minMinWarriorsExpandCpuNormal")->
- getIntValue ();
- // int maxMinWarriors;
- maxMinWarriors =
- aiNode->getAttribute ("maxMinWarriors")->getIntValue ();
- // int maxExpansions;
- maxExpansions = aiNode->getAttribute ("maxExpansions")->getIntValue ();
- // int villageRadius;
- villageRadius = aiNode->getAttribute ("villageRadius")->getIntValue ();
- // int scoutResourceRange;
- scoutResourceRange =
- aiNode->getAttribute ("scoutResourceRange")->getIntValue ();
- // int minWorkerAttackersHarvesting;
- minWorkerAttackersHarvesting =
- aiNode->getAttribute ("minWorkerAttackersHarvesting")->getIntValue ();
- }
-
-}} //end namespace
+ Glest {
+ namespace
+ Game {
+
+ Task::Task() {
+ taskClass = tcProduce;
+ }
+
+ //void Task::saveGame(XmlNode *rootNode) const {
+ // std::map mapTagReplacements;
+ // XmlNode *taskNode = rootNode->addChild("Task");
+ //}
+
+ // =====================================================
+ // class ProduceTask
+ // =====================================================
+ ProduceTask::ProduceTask() :
+ Task() {
+ taskClass = tcProduce;
+ unitType = NULL;
+ resourceType = NULL;
+ unitClass = ucWarrior;
+ }
+
+ ProduceTask::ProduceTask(UnitClass unitClass) :
+ Task() {
+ taskClass = tcProduce;
+ this->unitClass = unitClass;
+ unitType = NULL;
+ resourceType = NULL;
+ }
+
+ ProduceTask::ProduceTask(const UnitType * unitType) :
+ Task() {
+ taskClass = tcProduce;
+ this->unitType = unitType;
+ resourceType = NULL;
+ unitClass = ucWarrior;
+ }
+
+ ProduceTask::ProduceTask(const ResourceType * resourceType) :
+ Task() {
+ taskClass = tcProduce;
+ unitType = NULL;
+ unitClass = ucWarrior;
+ this->resourceType = resourceType;
+ }
+
+ string
+ ProduceTask::toString() const {
+ string
+ str = "Produce ";
+ if (unitType != NULL) {
+ str += unitType->getName(false);
+ }
+ return
+ str;
+ }
+
+ void
+ ProduceTask::saveGame(XmlNode * rootNode) const {
+ std::map <
+ string,
+ string >
+ mapTagReplacements;
+ XmlNode *
+ taskNode = rootNode->addChild("Task");
+ taskNode->
+ addAttribute("taskClass", intToStr(taskClass), mapTagReplacements);
+ XmlNode *
+ produceTaskNode = taskNode->addChild("ProduceTask");
+
+ // UnitClass unitClass;
+ produceTaskNode->
+ addAttribute("unitClass", intToStr(unitClass), mapTagReplacements);
+ // const UnitType *unitType;
+ if (unitType != NULL) {
+ produceTaskNode->addAttribute("unitType",
+ unitType->getName(false),
+ mapTagReplacements);
+ }
+ // const ResourceType *resourceType;
+ if (resourceType != NULL) {
+ produceTaskNode->addAttribute("resourceType",
+ resourceType->getName(false),
+ mapTagReplacements);
+ }
+ }
+
+ ProduceTask *
+ ProduceTask::loadGame(const XmlNode * rootNode, Faction * faction) {
+ const XmlNode *
+ produceTaskNode = rootNode->getChild("ProduceTask");
+
+ ProduceTask *
+ newTask = new ProduceTask();
+ // UnitClass unitClass;
+ newTask->unitClass =
+ static_cast
+ (produceTaskNode->getAttribute("unitClass")->getIntValue());
+ // const UnitType *unitType;
+ if (produceTaskNode->hasAttribute("unitType")) {
+ string
+ unitTypeName =
+ produceTaskNode->getAttribute("unitType")->getValue();
+ newTask->unitType = faction->getType()->getUnitType(unitTypeName);
+ }
+ // const ResourceType *resourceType;
+ if (produceTaskNode->hasAttribute("resourceType")) {
+ string
+ resourceTypeName =
+ produceTaskNode->getAttribute("resourceType")->getValue();
+ newTask->resourceType =
+ faction->getTechTree()->getResourceType(resourceTypeName);
+ }
+
+ return newTask;
+ }
+
+ // =====================================================
+ // class BuildTask
+ // =====================================================
+ BuildTask::BuildTask() {
+ taskClass = tcBuild;
+ this->unitType = NULL;
+ resourceType = NULL;
+ forcePos = false;
+ }
+
+ BuildTask::BuildTask(const UnitType * unitType) {
+ taskClass = tcBuild;
+ this->unitType = unitType;
+ resourceType = NULL;
+ forcePos = false;
+ }
+
+ BuildTask::BuildTask(const ResourceType * resourceType) {
+ taskClass = tcBuild;
+ unitType = NULL;
+ this->resourceType = resourceType;
+ forcePos = false;
+ }
+
+ BuildTask::BuildTask(const UnitType * unitType, const Vec2i & pos) {
+ taskClass = tcBuild;
+ this->unitType = unitType;
+ resourceType = NULL;
+ forcePos = true;
+ this->pos = pos;
+ }
+
+ string
+ BuildTask::toString() const {
+ string
+ str = "Build ";
+ if (unitType != NULL) {
+ str += unitType->getName(false);
+ }
+ return
+ str;
+ }
+
+ void
+ BuildTask::saveGame(XmlNode * rootNode) const {
+ std::map <
+ string,
+ string >
+ mapTagReplacements;
+ XmlNode *
+ taskNode = rootNode->addChild("Task");
+ taskNode->
+ addAttribute("taskClass", intToStr(taskClass), mapTagReplacements);
+ XmlNode *
+ buildTaskNode = taskNode->addChild("BuildTask");
+
+ // const UnitType *unitType;
+ if (unitType != NULL) {
+ buildTaskNode->addAttribute("unitType", unitType->getName(false),
+ mapTagReplacements);
+ }
+ // const ResourceType *resourceType;
+ if (resourceType != NULL) {
+ buildTaskNode->addAttribute("resourceType",
+ resourceType->getName(),
+ mapTagReplacements);
+ }
+ // bool forcePos;
+ buildTaskNode->addAttribute("forcePos", intToStr(forcePos),
+ mapTagReplacements);
+ // Vec2i pos;
+ buildTaskNode->addAttribute("pos", pos.getString(),
+ mapTagReplacements);
+ }
+
+ BuildTask *
+ BuildTask::loadGame(const XmlNode * rootNode, Faction * faction) {
+ const XmlNode *
+ buildTaskNode = rootNode->getChild("BuildTask");
+
+ BuildTask *
+ newTask = new BuildTask();
+ if (buildTaskNode->hasAttribute("unitType")) {
+ string
+ unitTypeName =
+ buildTaskNode->getAttribute("unitType")->getValue();
+ newTask->unitType = faction->getType()->getUnitType(unitTypeName);
+ }
+ if (buildTaskNode->hasAttribute("resourceType")) {
+ string
+ resourceTypeName =
+ buildTaskNode->getAttribute("resourceType")->getValue();
+ newTask->resourceType =
+ faction->getTechTree()->getResourceType(resourceTypeName);
+ }
+
+ newTask->forcePos =
+ buildTaskNode->getAttribute("forcePos")->getIntValue() != 0;
+ newTask->pos =
+ Vec2i::strToVec2(buildTaskNode->getAttribute("pos")->getValue());
+
+ return newTask;
+ }
+
+ // =====================================================
+ // class UpgradeTask
+ // =====================================================
+ UpgradeTask::UpgradeTask() {
+ taskClass = tcUpgrade;
+ this->upgradeType = NULL;
+ }
+
+ UpgradeTask::UpgradeTask(const UpgradeType * upgradeType) {
+ taskClass = tcUpgrade;
+ this->upgradeType = upgradeType;
+ }
+
+ string
+ UpgradeTask::toString() const {
+ string
+ str = "Build ";
+ if (upgradeType != NULL) {
+ str += upgradeType->getName();
+ }
+ return
+ str;
+ }
+
+ void
+ UpgradeTask::saveGame(XmlNode * rootNode) const {
+ std::map <
+ string,
+ string >
+ mapTagReplacements;
+ XmlNode *
+ taskNode = rootNode->addChild("Task");
+ taskNode->
+ addAttribute("taskClass", intToStr(taskClass), mapTagReplacements);
+ XmlNode *
+ upgradeTaskNode = taskNode->addChild("UpgradeTask");
+
+ if (upgradeType != NULL) {
+ //upgradeType->saveGame(upgradeTaskNode);
+ upgradeTaskNode->addAttribute("upgradeType",
+ upgradeType->getName(),
+ mapTagReplacements);
+ }
+ }
+
+ UpgradeTask *
+ UpgradeTask::loadGame(const XmlNode * rootNode, Faction * faction) {
+ const XmlNode *
+ upgradeTaskNode = rootNode->getChild("UpgradeTask");
+
+ UpgradeTask *
+ newTask = new UpgradeTask();
+ if (upgradeTaskNode->hasAttribute("upgradeType")) {
+ string
+ upgradeTypeName =
+ upgradeTaskNode->getAttribute("upgradeType")->getValue();
+ newTask->upgradeType =
+ faction->getType()->getUpgradeType(upgradeTypeName);
+ }
+ return newTask;
+ }
+
+ // =====================================================
+ // class Ai
+ // =====================================================
+
+ void
+ Ai::init(AiInterface * aiInterface, int useStartLocation) {
+ this->aiInterface = aiInterface;
+
+ Faction *
+ faction = this->aiInterface->getMyFaction();
+ if (faction->getAIBehaviorStaticOverideValue(aibsvcMaxBuildRadius) !=
+ INT_MAX) {
+ maxBuildRadius =
+ faction->getAIBehaviorStaticOverideValue(aibsvcMaxBuildRadius);
+ //printf("Discovered overriden static value for AI, maxBuildRadius = %d\n",maxBuildRadius);
+ }
+ if (faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriors) !=
+ INT_MAX) {
+ minMinWarriors =
+ faction->getAIBehaviorStaticOverideValue(aibsvcMinMinWarriors);
+ //printf("Discovered overriden static value for AI, minMinWarriors = %d\n",minMinWarriors);
+ }
+ if (faction->
+ getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuEasy)
+ != INT_MAX) {
+ minMinWarriorsExpandCpuEasy =
+ faction->
+ getAIBehaviorStaticOverideValue
+ (aibsvcMinMinWarriorsExpandCpuEasy);
+ //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuEasy = %d\n",minMinWarriorsExpandCpuEasy);
+ }
+ if (faction->
+ getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuZeta)
+ != INT_MAX) {
+ minMinWarriorsExpandCpuZeta =
+ faction->
+ getAIBehaviorStaticOverideValue
+ (aibsvcMinMinWarriorsExpandCpuZeta);
+ //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuZeta = %d\n",minMinWarriorsExpandCpuZeta);
+ }
+ if (faction->
+ getAIBehaviorStaticOverideValue(aibsvcMinMinWarriorsExpandCpuUltra)
+ != INT_MAX) {
+ minMinWarriorsExpandCpuUltra =
+ faction->
+ getAIBehaviorStaticOverideValue
+ (aibsvcMinMinWarriorsExpandCpuUltra);
+ //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuUltra = %d\n",minMinWarriorsExpandCpuUltra);
+ }
+ if (faction->
+ getAIBehaviorStaticOverideValue
+ (aibsvcMinMinWarriorsExpandCpuNormal) != INT_MAX) {
+ minMinWarriorsExpandCpuNormal =
+ faction->
+ getAIBehaviorStaticOverideValue
+ (aibsvcMinMinWarriorsExpandCpuNormal);
+ //printf("Discovered overriden static value for AI, minMinWarriorsExpandCpuNormal = %d\n",minMinWarriorsExpandCpuNormal);
+ }
+ if (faction->getAIBehaviorStaticOverideValue(aibsvcMaxMinWarriors) !=
+ INT_MAX) {
+ maxMinWarriors =
+ faction->getAIBehaviorStaticOverideValue(aibsvcMaxMinWarriors);
+ //printf("Discovered overriden static value for AI, maxMinWarriors = %d\n",maxMinWarriors);
+ }
+ if (faction->getAIBehaviorStaticOverideValue(aibsvcMaxExpansions) !=
+ INT_MAX) {
+ maxExpansions =
+ faction->getAIBehaviorStaticOverideValue(aibsvcMaxExpansions);
+ //printf("Discovered overriden static value for AI, maxExpansions = %d\n",maxExpansions);
+ }
+ if (faction->getAIBehaviorStaticOverideValue(aibsvcVillageRadius) !=
+ INT_MAX) {
+ villageRadius =
+ faction->getAIBehaviorStaticOverideValue(aibsvcVillageRadius);
+ //printf("Discovered overriden static value for AI, villageRadius = %d\n",villageRadius);
+ }
+ if (faction->
+ getAIBehaviorStaticOverideValue(aibsvcScoutResourceRange) !=
+ INT_MAX) {
+ scoutResourceRange =
+ faction->
+ getAIBehaviorStaticOverideValue(aibsvcScoutResourceRange);
+ //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange);
+ }
+ if (faction->
+ getAIBehaviorStaticOverideValue(aibsvcMinWorkerAttackersHarvesting)
+ != INT_MAX) {
+ minWorkerAttackersHarvesting =
+ faction->
+ getAIBehaviorStaticOverideValue
+ (aibsvcMinWorkerAttackersHarvesting);
+ //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange);
+ }
+ if (faction->getAIBehaviorStaticOverideValue(aibsvcMinBuildSpacing) !=
+ INT_MAX) {
+ minBuildSpacing =
+ faction->getAIBehaviorStaticOverideValue(aibsvcMinBuildSpacing);
+ //printf("Discovered overriden static value for AI, scoutResourceRange = %d\n",scoutResourceRange);
+ }
+
+ if (useStartLocation == -1) {
+ startLoc =
+ random.randRange(0, aiInterface->getMapMaxPlayers() - 1);
+ } else {
+ startLoc = useStartLocation;
+ }
+ minWarriors = minMinWarriors;
+ randomMinWarriorsReached = false;
+ //add ai rules
+ aiRules.clear();
+ aiRules.push_back(new AiRuleWorkerHarvest(this));
+ aiRules.push_back(new AiRuleRefreshHarvester(this));
+ aiRules.push_back(new AiRuleScoutPatrol(this));
+ aiRules.push_back(new AiRuleUnBlock(this));
+ aiRules.push_back(new AiRuleReturnBase(this));
+ aiRules.push_back(new AiRuleMassiveAttack(this));
+ aiRules.push_back(new AiRuleAddTasks(this));
+ aiRules.push_back(new AiRuleProduceResourceProducer(this));
+ aiRules.push_back(new AiRuleBuildOneFarm(this));
+ aiRules.push_back(new AiRuleProduce(this));
+ aiRules.push_back(new AiRuleBuild(this));
+ aiRules.push_back(new AiRuleUpgrade(this));
+ aiRules.push_back(new AiRuleExpand(this));
+ aiRules.push_back(new AiRuleRepair(this));
+ aiRules.push_back(new AiRuleRepair(this));
+ }
+
+ Ai::~Ai() {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ aiInterface);
+ deleteValues(tasks.begin(), tasks.end());
+ tasks.clear();
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ aiInterface);
+
+ deleteValues(aiRules.begin(), aiRules.end());
+ aiRules.clear();
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] deleting AI aiInterface [%p]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ aiInterface);
+
+ aiInterface = NULL;
+ }
+
+ RandomGen *
+ Ai::getRandom() {
+ // if(Thread::isCurrentThreadMainThread() == false) {
+ // throw megaglest_runtime_error("Invalid access to AI random from outside main thread current id = " +
+ // intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId()));
+ // }
+ return &random;
+ }
+
+ void
+ Ai::update() {
+
+ Chrono
+ chrono;
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled)
+ chrono.start();
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ if (aiInterface->getMyFaction()->getFirstSwitchTeamVote() != NULL) {
+ const SwitchTeamVote *
+ vote = aiInterface->getMyFaction()->getFirstSwitchTeamVote();
+ aiInterface->getMyFaction()->
+ setCurrentSwitchTeamVoteFactionIndex(vote->factionIndex);
+
+ factionSwitchTeamRequestCount[vote->factionIndex]++;
+ int
+ factionSwitchTeamRequestCountCurrent =
+ factionSwitchTeamRequestCount[vote->factionIndex];
+
+ //int allowJoinTeam = random.randRange(0, 100);
+ //srand(time(NULL) + aiInterface->getMyFaction()->getIndex());
+ Chrono
+ seed(true);
+ srand((unsigned int) seed.getCurTicks() +
+ aiInterface->getMyFaction()->getIndex());
+
+ int
+ allowJoinTeam = rand() % 100;
+
+ SwitchTeamVote *
+ voteResult =
+ aiInterface->getMyFaction()->getSwitchTeamVote(vote->
+ factionIndex);
+ voteResult->voted = true;
+ voteResult->allowSwitchTeam = false;
+
+ const GameSettings *
+ settings = aiInterface->getWorld()->getGameSettings();
+
+ // If AI player already lost game they cannot vote
+ if (aiInterface->getWorld()->
+ factionLostGame(aiInterface->getFactionIndex()) == true) {
+ voteResult->allowSwitchTeam = true;
+ } else {
+ // Can only ask the AI player 2 times max per game
+ if (factionSwitchTeamRequestCountCurrent <= 2) {
+ // x% chance the AI will answer yes
+ if (settings->getAiAcceptSwitchTeamPercentChance() >= 100) {
+ voteResult->allowSwitchTeam = true;
+ } else if (settings->getAiAcceptSwitchTeamPercentChance() <=
+ 0) {
+ voteResult->allowSwitchTeam = false;
+ } else {
+ voteResult->allowSwitchTeam =
+ (allowJoinTeam >=
+ (100 -
+ settings->getAiAcceptSwitchTeamPercentChance()));
+ }
+ }
+ }
+
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "AI for faction# %d voted %s [%d] CountCurrent [%d] PercentChance [%d]",
+ aiInterface->getMyFaction()->getIndex(),
+ (voteResult->allowSwitchTeam ? "Yes" : "No"),
+ allowJoinTeam, factionSwitchTeamRequestCountCurrent,
+ settings->getAiAcceptSwitchTeamPercentChance());
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] %s\n", __FILE__,
+ __FUNCTION__, __LINE__, szBuf);
+
+ aiInterface->printLog(3, szBuf);
+
+ aiInterface->giveCommandSwitchTeamVote(aiInterface->
+ getMyFaction(),
+ voteResult);
+ }
+
+ //process ai rules
+ for (unsigned int ruleIdx = 0; ruleIdx < aiRules.size(); ++ruleIdx) {
+ AiRule *
+ rule = aiRules[ruleIdx];
+ if (rule == NULL) {
+ throw
+ megaglest_runtime_error("rule == NULL");
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).enabled
+ && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis(), ruleIdx);
+ // Determines wether to process AI rules. Whether a particular rule is processed, is weighted by getTestInterval().
+ // Values returned by getTestInterval() are defined in ai_rule.h.
+ if ((aiInterface->getTimer() %
+ (rule->getTestInterval() * GameConstants::updateFps /
+ 1000)) == 0) {
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).enabled
+ && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before rule->test()]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis(), ruleIdx);
+
+ //printf("Testing AI Faction # %d RULE Name[%s]\n",aiInterface->getFactionIndex(),rule->getName().c_str());
+
+ // Test to see if AI can execute rule e.g. is there a worker available to for harvesting wood?
+ if (rule->test()) {
+ if (outputAIBehaviourToConsole())
+ printf
+ ("\n\nYYYYY Executing AI Faction # %d RULE Name[%s]\n\n",
+ aiInterface->getFactionIndex(),
+ rule->getName().c_str());
+
+ aiInterface->printLog(3,
+ intToStr(1000 *
+ aiInterface->getTimer() /
+ GameConstants::updateFps) +
+ ": Executing rule: " +
+ rule->getName() + '\n');
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, before rule->execute() [%s]]\n",
+ __FILE__, __FUNCTION__,
+ __LINE__, chrono.getMillis(),
+ ruleIdx,
+ rule->getName().c_str());
+ // Execute the rule.
+ rule->execute();
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [ruleIdx = %d, after rule->execute() [%s]]\n",
+ __FILE__, __FUNCTION__,
+ __LINE__, chrono.getMillis(),
+ ruleIdx,
+ rule->getName().c_str());
+ }
+ }
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [END]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+ }
+
+
+ // ==================== state requests ====================
+
+ int
+ Ai::getCountOfType(const UnitType * ut) {
+ int
+ count = 0;
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ if (ut == aiInterface->getMyUnit(i)->getType()) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ int
+ Ai::getCountOfClass(UnitClass uc,
+ UnitClass * additionalUnitClassToExcludeFromCount) {
+ int
+ count = 0;
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ if (aiInterface->getMyUnit(i)->getType()->isOfClass(uc)) {
+ // Skip unit if it ALSO contains the exclusion unit class type
+ if (additionalUnitClassToExcludeFromCount != NULL) {
+ if (aiInterface->getMyUnit(i)->getType()->
+ isOfClass(*additionalUnitClassToExcludeFromCount)) {
+ continue;
+ }
+ }
+ ++count;
+ }
+ }
+ return count;
+ }
+
+ float
+ Ai::getRatioOfClass(UnitClass uc,
+ UnitClass * additionalUnitClassToExcludeFromCount) {
+ if (aiInterface->getMyUnitCount() == 0) {
+ return 0;
+ } else {
+ //return static_cast(getCountOfClass(uc,additionalUnitClassToExcludeFromCount)) / aiInterface->getMyUnitCount();
+ return truncateDecimal < float >(static_cast <
+ float
+ >(getCountOfClass
+ (uc,
+ additionalUnitClassToExcludeFromCount))
+ / aiInterface->getMyUnitCount(),
+ 6);
+ }
+ }
+
+ const ResourceType *
+ Ai::getNeededResource(int unitIndex) {
+ int
+ amount = INT_MAX;
+ const ResourceType *
+ neededResource = NULL;
+ const TechTree *
+ tt = aiInterface->getTechTree();
+ const Unit *
+ unit = aiInterface->getMyUnit(unitIndex);
+
+ for (int i = 0; i < tt->getResourceTypeCount(); ++i) {
+ const ResourceType *
+ rt = tt->getResourceType(i);
+ const Resource *
+ r = aiInterface->getResource(rt);
+
+ if (rt->getClass() != rcStatic && rt->getClass() != rcConsumable) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Examining resource [%s] amount [%d] (previous amount [%d]",
+ rt->getName().c_str(), r->getAmount(), amount);
+ aiInterface->printLog(3, szBuf);
+ }
+
+ if (rt->getClass() != rcStatic && rt->getClass() != rcConsumable
+ && r->getAmount() < amount) {
+
+ // Only have up to x units going for this resource so we can focus
+ // on other needed resources for other units
+ const int
+ maxUnitsToHarvestResource = 5;
+
+ vector < int >
+ unitsGettingResource = findUnitsHarvestingResourceType(rt);
+ if ((int) unitsGettingResource.size() <=
+ maxUnitsToHarvestResource) {
+ // Now MAKE SURE the unit has a harvest command for this resource
+ // AND that the resource is within eye-sight to avoid units
+ // standing around doing nothing.
+ const HarvestCommandType *
+ hct =
+ unit->getType()->getFirstHarvestCommand(rt,
+ unit->
+ getFaction());
+ Vec2i
+ resPos;
+ if (hct != NULL
+ && aiInterface->getNearestSightedResource(rt,
+ aiInterface->
+ getHomeLocation
+ (), resPos,
+ false)) {
+ amount = r->getAmount();
+ neededResource = rt;
+ }
+ }
+ }
+ }
+
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Unit [%d - %s] looking for resources (not static or consumable)",
+ unit->getId(), unit->getType()->getName(false).c_str());
+ aiInterface->printLog(3, szBuf);
+ snprintf(szBuf, 8096, "[resource type count %d] Needed resource [%s].",
+ tt->getResourceTypeCount(),
+ (neededResource !=
+ NULL ? neededResource->getName().c_str() : ""));
+ aiInterface->printLog(3, szBuf);
+
+ return neededResource;
+ }
+
+ bool
+ Ai::beingAttacked(Vec2i & pos, Field & field, int radius) {
+ const Unit *
+ enemy = aiInterface->getFirstOnSightEnemyUnit(pos, field, radius);
+ return (enemy != NULL);
+ }
+
+ bool
+ Ai::isStableBase() {
+ UnitClass
+ ucWorkerType = ucWorker;
+ if (getCountOfClass(ucWarrior, &ucWorkerType) > minWarriors) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Base is stable [minWarriors = %d found = %d]",
+ minWarriors, ucWorkerType);
+ aiInterface->printLog(4, szBuf);
+
+ return true;
+ } else {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Base is NOT stable [minWarriors = %d found = %d]",
+ minWarriors, ucWorkerType);
+ aiInterface->printLog(4, szBuf);
+
+ return false;
+ }
+ }
+
+ bool
+ Ai::findAbleUnit(int *unitIndex, CommandClass ability, bool idleOnly) {
+ vector < int >
+ units;
+
+ *unitIndex = -1;
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ const Unit *
+ unit = aiInterface->getMyUnit(i);
+ if (unit->getType()->isCommandable()
+ && unit->getType()->hasCommandClass(ability)) {
+ if (!idleOnly || !unit->anyCommand()
+ || unit->getCurrCommand()->getCommandType()->
+ getClass() == ccStop) {
+ units.push_back(i);
+ }
+ }
+ }
+
+ if (units.empty()) {
+ return false;
+ } else {
+ *unitIndex = units[random.randRange(0, (int) units.size() - 1)];
+ return true;
+ }
+ }
+
+ vector < int >
+ Ai::findUnitsHarvestingResourceType(const ResourceType * rt) {
+ vector < int >
+ units;
+
+ Map *
+ map = aiInterface->getMap();
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ const Unit *
+ unit = aiInterface->getMyUnit(i);
+ if (unit->getType()->isCommandable()) {
+ if (unit->getType()->hasCommandClass(ccHarvest)) {
+ if (unit->anyCommand()
+ && unit->getCurrCommand()->getCommandType()->
+ getClass() == ccHarvest) {
+ Command *
+ command = unit->getCurrCommand();
+ const HarvestCommandType *
+ hct = dynamic_cast (command->getCommandType());
+ if (hct != NULL) {
+ const Vec2i
+ unitTargetPos = unit->getTargetPos();
+ SurfaceCell *
+ sc =
+ map->
+ getSurfaceCell(Map::
+ toSurfCoords(unitTargetPos));
+ Resource *
+ r = sc->getResource();
+ if (r != NULL && r->getType() == rt) {
+ units.push_back(i);
+ }
+ }
+ }
+ } else if (unit->getType()->hasCommandClass(ccProduce)) {
+ if (unit->anyCommand()
+ && unit->getCurrCommand()->getCommandType()->
+ getClass() == ccProduce) {
+ Command *
+ command = unit->getCurrCommand();
+ const ProduceCommandType *
+ pct = dynamic_cast (command->getCommandType());
+ if (pct != NULL) {
+ const UnitType *
+ ut = pct->getProducedUnit();
+ if (ut != NULL) {
+ const Resource *
+ r = ut->getCost(rt);
+ if (r != NULL) {
+ if (r != NULL && r->getAmount() < 0) {
+ units.push_back(i);
+ }
+ }
+ }
+ }
+ }
+ } else if (unit->getType()->hasCommandClass(ccBuild)) {
+ if (unit->anyCommand()
+ && unit->getCurrCommand()->getCommandType()->
+ getClass() == ccBuild) {
+ Command *
+ command = unit->getCurrCommand();
+ const BuildCommandType *
+ bct = dynamic_cast (command->getCommandType());
+ if (bct != NULL) {
+ for (int j = 0; j < bct->getBuildingCount(); ++j) {
+ const UnitType *
+ ut = bct->getBuilding(j);
+ if (ut != NULL) {
+ const Resource *
+ r = ut->getCost(rt);
+ if (r != NULL) {
+ if (r != NULL && r->getAmount() < 0) {
+ units.push_back(i);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return units;
+ }
+
+ //vector Ai::findUnitsDoingCommand(CommandClass currentCommand) {
+ // vector units;
+ //
+ // for(int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ // const Unit *unit= aiInterface->getMyUnit(i);
+ // if(unit->getType()->isCommandable() && unit->getType()->hasCommandClass(currentCommand)) {
+ // if(unit->anyCommand() && unit->getCurrCommand()->getCommandType()->getClass() == currentCommand) {
+ // units.push_back(i);
+ // }
+ // }
+ // }
+ //
+ // return units;
+ //}
+
+ bool
+ Ai::findAbleUnit(int *unitIndex, CommandClass ability,
+ CommandClass currentCommand) {
+ vector < int >
+ units;
+
+ *unitIndex = -1;
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ const Unit *
+ unit = aiInterface->getMyUnit(i);
+ if (unit->getType()->isCommandable()
+ && unit->getType()->hasCommandClass(ability)) {
+ if (unit->anyCommand()
+ && unit->getCurrCommand()->getCommandType()->
+ getClass() == currentCommand) {
+ units.push_back(i);
+ }
+ }
+ }
+
+ if (units.empty()) {
+ return false;
+ } else {
+ *unitIndex = units[random.randRange(0, (int) units.size() - 1)];
+ return true;
+ }
+ }
+
+ bool
+ Ai::findPosForBuilding(const UnitType * building,
+ const Vec2i & searchPos, Vec2i & outPos) {
+
+ for (int currRadius = 0; currRadius < maxBuildRadius; ++currRadius) {
+ for (int i = searchPos.x - currRadius; i < searchPos.x + currRadius;
+ ++i) {
+ for (int j = searchPos.y - currRadius;
+ j < searchPos.y + currRadius; ++j) {
+ outPos = Vec2i(i, j);
+ if (aiInterface->
+ isFreeCells(outPos - Vec2i(minBuildSpacing),
+ building->getAiBuildSize() +
+ minBuildSpacing * 2, fLand)) {
+ int
+ aiBuildSizeDiff =
+ building->getAiBuildSize() - building->getSize();
+ if (aiBuildSizeDiff > 0) {
+ int
+ halfSize = aiBuildSizeDiff / 2;
+ outPos.x += halfSize;
+ outPos.y += halfSize;
+ }
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+
+ }
+
+
+ // ==================== tasks ====================
+
+ void
+ Ai::addTask(const Task * task) {
+ tasks.push_back(task);
+ aiInterface->printLog(2, "Task added: " + task->toString());
+ }
+
+ void
+ Ai::addPriorityTask(const Task * task) {
+ deleteValues(tasks.begin(), tasks.end());
+ tasks.clear();
+
+ tasks.push_back(task);
+ aiInterface->printLog(2, "Priority Task added: " + task->toString());
+ }
+
+ bool
+ Ai::anyTask() {
+ return !tasks.empty();
+ }
+
+ const Task *
+ Ai::getTask() const {
+ if (tasks.empty()) {
+ return NULL;
+ } else {
+ return tasks.front();
+ }
+ }
+
+ void
+ Ai::removeTask(const Task * task) {
+ aiInterface->printLog(2, "Task removed: " + task->toString());
+ tasks.remove(task);
+ delete
+ task;
+ }
+
+ void
+ Ai::retryTask(const Task * task) {
+ tasks.remove(task);
+ tasks.push_back(task);
+ }
+ // ==================== expansions ====================
+
+ void
+ Ai::addExpansion(const Vec2i & pos) {
+
+ //check if there is a nearby expansion
+ for (Positions::iterator it = expansionPositions.begin();
+ it != expansionPositions.end(); ++it) {
+ if ((*it).dist(pos) < villageRadius) {
+ return;
+ }
+ }
+
+ //add expansion
+ expansionPositions.push_front(pos);
+
+ //remove expansion if queue is list is full
+ if ((int) expansionPositions.size() > maxExpansions) {
+ expansionPositions.pop_back();
+ }
+ }
+
+ Vec2i
+ Ai::getRandomHomePosition() {
+
+ if (expansionPositions.empty() || random.randRange(0, 1) == 0) {
+ return aiInterface->getHomeLocation();
+ }
+
+ return expansionPositions[random.
+ randRange(0,
+ (int) expansionPositions.size() -
+ 1)];
+ }
+
+ // ==================== actions ====================
+
+ void
+ Ai::sendScoutPatrol() {
+
+ Vec2i
+ pos;
+ int
+ unit;
+ bool
+ possibleTargetFound = false;
+
+ bool
+ ultraResourceAttack = (aiInterface->getControlType() == ctCpuUltra
+ || aiInterface->getControlType() ==
+ ctNetworkCpuUltra)
+ && random.randRange(0, 2) == 1;
+ bool
+ megaResourceAttack = (aiInterface->getControlType() == ctCpuZeta
+ || aiInterface->getControlType() ==
+ ctNetworkCpuZeta)
+ && random.randRange(0, 1) == 1;
+
+ if (megaResourceAttack || ultraResourceAttack) {
+ Map *
+ map = aiInterface->getMap();
+
+ const TechTree *
+ tt = aiInterface->getTechTree();
+ const ResourceType *
+ rt = tt->getResourceType(0);
+ int
+ tryCount = 0;
+ int
+ height = map->getH();
+ int
+ width = map->getW();
+
+ for (int i = 0; i < tt->getResourceTypeCount(); ++i) {
+ const ResourceType *
+ rt_ = tt->getResourceType(i);
+ //const Resource *r= aiInterface->getResource(rt);
+
+ if (rt_->getClass() == rcTech) {
+ rt = rt_;
+ break;
+ }
+ }
+ //printf("looking for resource %s\n",rt->getName().c_str());
+ while (possibleTargetFound == false) {
+ tryCount++;
+ if (tryCount == 4) {
+ //printf("no target found\n");
+ break;
+ }
+ pos =
+ Vec2i(random.randRange(2, width - 2),
+ random.randRange(2, height - 2));
+ if (map->isInside(pos)
+ && map->isInsideSurface(map->toSurfCoords(pos))) {
+ //printf("is inside map\n");
+ // find first resource in this area
+ Vec2i
+ resPos;
+ if (aiInterface->
+ isResourceInRegion(pos, rt, resPos,
+ scoutResourceRange)) {
+ // found a possible target.
+ pos = resPos;
+ //printf("lets try the new target\n");
+ possibleTargetFound = true;
+ break;
+ }
+ }
+ //else printf("is outside map\n");
+ }
+ }
+
+ std::vector < Vec2i > warningEnemyList =
+ aiInterface->getEnemyWarningPositionList();
+ if ((possibleTargetFound == false)
+ && (warningEnemyList.empty() == false)) {
+ //for(int i = (int)warningEnemyList.size() - 1; i <= 0; --i) {
+ //Vec2i &checkPos = warningEnemyList[i];
+ Vec2i & checkPos = warningEnemyList[0];
+ if (random.randRange(0, 1) == 1) {
+ pos = checkPos;
+ possibleTargetFound = true;
+ warningEnemyList.clear();
+ } else {
+ aiInterface->removeEnemyWarningPositionFromList(checkPos);
+ }
+ //break;
+ //}
+ }
+
+ if (possibleTargetFound == false) {
+ startLoc = (startLoc + 1) % aiInterface->getMapMaxPlayers();
+ pos = aiInterface->getStartLocation(startLoc);
+ //printf("normal target used\n");
+ }
+
+ if (aiInterface->getHomeLocation() != pos) {
+ if (findAbleUnit(&unit, ccAttack, false)) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ aiInterface->giveCommand(unit, ccAttack, pos);
+ aiInterface->printLog(2,
+ "Scout patrol sent to: " +
+ intToStr(pos.x) + "," +
+ intToStr(pos.y) + "\n");
+ }
+ }
+ }
+
+ void
+ Ai::massiveAttack(const Vec2i & pos, Field field, bool ultraAttack) {
+ int
+ producerWarriorCount = 0;
+ int
+ maxProducerWarriors = random.randRange(1, 11);
+ int
+ unitCount = aiInterface->getMyUnitCount();
+ int
+ unitGroupCommandId = -1;
+
+ int
+ attackerWorkersHarvestingCount = 0;
+ for (int i = 0; i < unitCount; ++i) {
+ bool
+ isWarrior = false;
+ bool
+ productionInProgress = false;
+ const Unit *
+ unit = aiInterface->getMyUnit(i);
+ const AttackCommandType *
+ act = unit->getType()->getFirstAttackCommand(field);
+
+ if (aiInterface->getControlType() == ctCpuZeta ||
+ aiInterface->getControlType() == ctNetworkCpuZeta) {
+ if (producerWarriorCount > maxProducerWarriors) {
+ if (unit->getCommandSize() > 0 &&
+ unit->getCurrCommand()->getCommandType() != NULL
+ && (unit->getCurrCommand()->getCommandType()->
+ getClass() == ccBuild
+ || unit->getCurrCommand()->getCommandType()->
+ getClass() == ccMorph
+ || unit->getCurrCommand()->getCommandType()->
+ getClass() == ccProduce)) {
+ productionInProgress = true;
+ isWarrior = false;
+ producerWarriorCount++;
+ } else {
+ isWarrior =
+ !unit->getType()->hasCommandClass(ccHarvest);
+ }
+
+ } else {
+ isWarrior = !unit->getType()->hasCommandClass(ccHarvest)
+ && !unit->getType()->hasCommandClass(ccProduce);
+ }
+ } else {
+ isWarrior = !unit->getType()->hasCommandClass(ccHarvest)
+ && !unit->getType()->hasCommandClass(ccProduce);
+ }
+
+ bool
+ alreadyAttacking =
+ (unit->getCurrSkill()->getClass() == scAttack);
+
+ bool
+ unitSignalledToAttack = false;
+ if (alreadyAttacking == false
+ && unit->getType()->hasSkillClass(scAttack)
+ && (aiInterface->getControlType() == ctCpuUltra
+ || aiInterface->getControlType() == ctCpuZeta
+ || aiInterface->getControlType() == ctNetworkCpuUltra
+ || aiInterface->getControlType() == ctNetworkCpuZeta)) {
+ //printf("~~~~~~~~ Unit [%s - %d] checking if unit is being attacked\n",unit->getFullName().c_str(),unit->getId());
+
+ std::pair < bool, Unit * >beingAttacked =
+ aiInterface->getWorld()->getUnitUpdater()->
+ unitBeingAttacked(unit);
+ if (beingAttacked.first == true) {
+ Unit *
+ enemy = beingAttacked.second;
+ const AttackCommandType *
+ act_forenemy =
+ unit->getType()->getFirstAttackCommand(enemy->
+ getCurrField());
+
+ //printf("~~~~~~~~ Unit [%s - %d] attacked by enemy [%s - %d] act_forenemy [%p] enemy->getCurrField() = %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),act_forenemy,enemy->getCurrField());
+
+ if (act_forenemy != NULL) {
+ bool
+ shouldAttack = true;
+ if (unit->getType()->hasSkillClass(scHarvest)) {
+ shouldAttack =
+ (attackerWorkersHarvestingCount >
+ minWorkerAttackersHarvesting);
+ if (shouldAttack == false) {
+ attackerWorkersHarvestingCount++;
+ }
+ }
+ if (shouldAttack) {
+ if (unitGroupCommandId == -1) {
+ unitGroupCommandId =
+ aiInterface->getWorld()->
+ getNextCommandGroupId();
+ }
+
+ aiInterface->giveCommand(i, act_forenemy,
+ beingAttacked.second->
+ getPos(),
+ unitGroupCommandId);
+ unitSignalledToAttack = true;
+ }
+ } else {
+ const AttackStoppedCommandType *
+ asct_forenemy =
+ unit->getType()->
+ getFirstAttackStoppedCommand(enemy->getCurrField());
+ //printf("~~~~~~~~ Unit [%s - %d] found enemy [%s - %d] asct_forenemy [%p] enemy->getCurrField() = %d\n",unit->getFullName().c_str(),unit->getId(),enemy->getFullName().c_str(),enemy->getId(),asct_forenemy,enemy->getCurrField());
+ if (asct_forenemy != NULL) {
+ bool
+ shouldAttack = true;
+ if (unit->getType()->hasSkillClass(scHarvest)) {
+ shouldAttack =
+ (attackerWorkersHarvestingCount >
+ minWorkerAttackersHarvesting);
+ if (shouldAttack == false) {
+ attackerWorkersHarvestingCount++;
+ }
+ }
+ if (shouldAttack) {
+ // printf("~~~~~~~~ Unit [%s - %d] WILL AttackStoppedCommand [%s - %d]\n", unit->getFullName().c_str(),
+ // unit->getId(), enemy->getFullName().c_str(), enemy->getId());
+
+ if (unitGroupCommandId == -1) {
+ unitGroupCommandId =
+ aiInterface->getWorld()->
+ getNextCommandGroupId();
+ }
+
+ aiInterface->giveCommand(i, asct_forenemy,
+ beingAttacked.second->
+ getCenteredPos(),
+ unitGroupCommandId);
+ unitSignalledToAttack = true;
+ }
+ }
+ }
+ }
+ }
+ if (alreadyAttacking == false && act != NULL
+ && (ultraAttack || isWarrior) && unitSignalledToAttack == false) {
+ bool
+ shouldAttack = true;
+ if (unit->getType()->hasSkillClass(scHarvest)) {
+ shouldAttack =
+ (attackerWorkersHarvestingCount >
+ minWorkerAttackersHarvesting);
+ if (shouldAttack == false) {
+ attackerWorkersHarvestingCount++;
+ }
+ }
+
+ // Zeta CPU does not send ( far away ) units which are currently producing something
+ if (aiInterface->getControlType() == ctCpuZeta
+ || aiInterface->getControlType() == ctNetworkCpuZeta) {
+ if (!isWarrior) {
+ if (!productionInProgress) {
+ shouldAttack = false;
+ //printf("no attack \n ");
+ }
+ }
+ }
+ if (shouldAttack) {
+ if (unitGroupCommandId == -1) {
+ unitGroupCommandId =
+ aiInterface->getWorld()->getNextCommandGroupId();
+ }
+
+ aiInterface->giveCommand(i, act, pos, unitGroupCommandId);
+ }
+ }
+ }
+
+ if (aiInterface->getControlType() == ctCpuEasy ||
+ aiInterface->getControlType() == ctNetworkCpuEasy) {
+ minWarriors += minMinWarriorsExpandCpuEasy;
+ } else if (aiInterface->getControlType() == ctCpuZeta ||
+ aiInterface->getControlType() == ctNetworkCpuZeta) {
+ minWarriors += minMinWarriorsExpandCpuZeta;
+ if (minWarriors > maxMinWarriors - 1 || randomMinWarriorsReached) {
+ randomMinWarriorsReached = true;
+ minWarriors =
+ random.randRange(maxMinWarriors - 10, maxMinWarriors * 2);
+ }
+ } else if (minWarriors < maxMinWarriors) {
+ if (aiInterface->getControlType() == ctCpuUltra ||
+ aiInterface->getControlType() == ctNetworkCpuUltra) {
+ minWarriors += minMinWarriorsExpandCpuUltra;
+ } else {
+ minWarriors += minMinWarriorsExpandCpuNormal;
+ }
+ }
+ aiInterface->printLog(2,
+ "Massive attack to pos: " + intToStr(pos.x) +
+ ", " + intToStr(pos.y) + "\n");
+ }
+
+ void
+ Ai::returnBase(int unitIndex) {
+ Vec2i
+ pos;
+ //std::pair r(crFailUndefined,"");
+ //aiInterface->getFactionIndex();
+ pos = Vec2i(random.randRange(-villageRadius, villageRadius),
+ random.randRange(-villageRadius, villageRadius)) +
+ getRandomHomePosition();
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ //r= aiInterface->giveCommand(unitIndex, ccMove, pos);
+ aiInterface->giveCommand(unitIndex, ccMove, pos);
+
+ //aiInterface->printLog(1, "Order return to base pos:" + intToStr(pos.x)+", "+intToStr(pos.y)+": "+rrToStr(r)+"\n");
+ }
+
+ void
+ Ai::harvest(int unitIndex) {
+ const ResourceType *
+ rt = getNeededResource(unitIndex);
+ if (rt != NULL) {
+ const HarvestCommandType *
+ hct =
+ aiInterface->getMyUnit(unitIndex)->getType()->
+ getFirstHarvestCommand(rt,
+ aiInterface->getMyUnit(unitIndex)->
+ getFaction());
+
+ Vec2i
+ resPos;
+ if (hct != NULL
+ && aiInterface->getNearestSightedResource(rt,
+ aiInterface->
+ getHomeLocation(),
+ resPos, false)) {
+ resPos =
+ resPos + Vec2i(random.randRange(-2, 2),
+ random.randRange(-2, 2));
+ aiInterface->giveCommand(unitIndex, hct, resPos, -1);
+ //aiInterface->printLog(4, "Order harvest pos:" + intToStr(resPos.x)+", "+intToStr(resPos.y)+": "+rrToStr(r)+"\n");
+ }
+ }
+ }
+
+ bool
+ Ai::haveBlockedUnits() {
+ Chrono
+ chrono;
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled)
+ chrono.start();
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ int
+ unitCount = aiInterface->getMyUnitCount();
+ Map *
+ map = aiInterface->getMap();
+ //If there is no close store
+ for (int j = 0; j < unitCount; ++j) {
+ const Unit *
+ u = aiInterface->getMyUnit(j);
+ const UnitType *
+ ut = u->getType();
+
+ // If this building is a store
+ if (u->isAlive() && ut->isMobile() && u->getPath() != NULL
+ && (u->getPath()->isBlocked()
+ || u->getPath()->getBlockCount())) {
+ Vec2i
+ unitPos = u->getPosNotThreadSafe();
+
+ //printf("#1 AI found blocked unit [%d - %s]\n",u->getId(),u->getFullName().c_str());
+
+ int
+ failureCount = 0;
+ int
+ cellCount = 0;
+
+ for (int i = -1; i <= 1; ++i) {
+ for (int j = -1; j <= 1; ++j) {
+ Vec2i
+ pos = unitPos + Vec2i(i, j);
+ if (map->isInside(pos)
+ && map->isInsideSurface(map->toSurfCoords(pos))) {
+ if (pos != unitPos) {
+ bool
+ canUnitMoveToCell =
+ map->aproxCanMove(u, unitPos, pos);
+ if (canUnitMoveToCell == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ }
+ }
+ bool
+ unitImmediatelyBlocked = (failureCount == cellCount);
+ //printf("#1 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = %d\n",unitImmediatelyBlocked,failureCount,cellCount);
+
+ if (unitImmediatelyBlocked) {
+ //printf("#1 AI unit IS BLOCKED [%d - %s]\n",u->getId(),u->getFullName().c_str());
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__,
+ __LINE__, chrono.getMillis());
+ return true;
+ }
+ }
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+ return false;
+ }
+
+ bool
+ Ai::getAdjacentUnits(std::map < float, std::map < int,
+ const Unit * > >&signalAdjacentUnits,
+ const Unit * unit) {
+ //printf("In getAdjacentUnits...\n");
+
+ bool
+ result = false;
+ Map *
+ map = aiInterface->getMap();
+ Vec2i
+ unitPos = unit->getPosNotThreadSafe();
+ for (int i = -1; i <= 1; ++i) {
+ for (int j = -1; j <= 1; ++j) {
+ Vec2i
+ pos = unitPos + Vec2i(i, j);
+ if (map->isInside(pos)
+ && map->isInsideSurface(map->toSurfCoords(pos))) {
+ if (pos != unitPos) {
+ Unit *
+ adjacentUnit =
+ map->getCell(pos)->getUnit(unit->getCurrField());
+ if (adjacentUnit != NULL
+ && adjacentUnit->getFactionIndex() ==
+ unit->getFactionIndex()) {
+ if (adjacentUnit->getType()->isMobile()
+ && adjacentUnit->getPath() != NULL) {
+ //signalAdjacentUnits.push_back(adjacentUnit);
+ float
+ dist = unitPos.dist(adjacentUnit->getPos());
+
+ std::map < float,
+ std::map < int, const Unit *> >::iterator
+ iterFind1 = signalAdjacentUnits.find(dist);
+ if (iterFind1 == signalAdjacentUnits.end()) {
+ signalAdjacentUnits[dist][adjacentUnit->
+ getId()] =
+ adjacentUnit;
+
+ getAdjacentUnits(signalAdjacentUnits,
+ adjacentUnit);
+ result = true;
+ } else {
+ std::map < int, const Unit *>::iterator
+ iterFind2 =
+ iterFind1->second.find(adjacentUnit->
+ getId());
+ if (iterFind2 == iterFind1->second.end()) {
+ signalAdjacentUnits[dist][adjacentUnit->
+ getId()] =
+ adjacentUnit;
+ getAdjacentUnits(signalAdjacentUnits,
+ adjacentUnit);
+ result = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ void
+ Ai::unblockUnits() {
+ Chrono
+ chrono;
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled)
+ chrono.start();
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ int
+ unitCount = aiInterface->getMyUnitCount();
+ Map *
+ map = aiInterface->getMap();
+ // Find blocked units and move surrounding units out of the way
+ std::map < float,
+ std::map < int, const Unit *> >
+ signalAdjacentUnits;
+ for (int idx = 0; idx < unitCount; ++idx) {
+ const Unit *
+ u = aiInterface->getMyUnit(idx);
+ const UnitType *
+ ut = u->getType();
+
+ // If this building is a store
+ if (u->isAlive() && ut->isMobile() && u->getPath() != NULL
+ && (u->getPath()->isBlocked()
+ || u->getPath()->getBlockCount())) {
+ Vec2i
+ unitPos = u->getPosNotThreadSafe();
+
+ //printf("#2 AI found blocked unit [%d - %s]\n",u->getId(),u->getFullName().c_str());
+
+ //int failureCount = 0;
+ //int cellCount = 0;
+
+ for (int i = -1; i <= 1; ++i) {
+ for (int j = -1; j <= 1; ++j) {
+ Vec2i
+ pos = unitPos + Vec2i(i, j);
+ if (map->isInside(pos)
+ && map->isInsideSurface(map->toSurfCoords(pos))) {
+ if (pos != unitPos) {
+ bool
+ canUnitMoveToCell =
+ map->aproxCanMove(u, unitPos, pos);
+ if (canUnitMoveToCell == false) {
+ //failureCount++;
+ getAdjacentUnits(signalAdjacentUnits, u);
+ }
+ //cellCount++;
+ }
+ }
+ }
+ }
+ //bool unitImmediatelyBlocked = (failureCount == cellCount);
+ //printf("#2 unitImmediatelyBlocked = %d, failureCount = %d, cellCount = %d, signalAdjacentUnits.size() = %d\n",unitImmediatelyBlocked,failureCount,cellCount,signalAdjacentUnits.size());
+ }
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ if (signalAdjacentUnits.empty() == false) {
+ //printf("#2 AI units ARE BLOCKED about to unblock\n");
+
+ int
+ unitGroupCommandId = -1;
+
+ for (std::map < float, std::map < int,
+ const Unit * > >::reverse_iterator iterMap =
+ signalAdjacentUnits.rbegin();
+ iterMap != signalAdjacentUnits.rend(); ++iterMap) {
+
+ for (std::map < int, const Unit * >::iterator iterMap2 =
+ iterMap->second.begin();
+ iterMap2 != iterMap->second.end(); ++iterMap2) {
+ //int idx = iterMap2->first;
+ const Unit *
+ adjacentUnit = iterMap2->second;
+ if (adjacentUnit != NULL
+ && adjacentUnit->getType()->
+ getFirstCtOfClass(ccMove) != NULL) {
+ const CommandType *
+ ct =
+ adjacentUnit->getType()->getFirstCtOfClass(ccMove);
+
+ for (int moveAttempt = 1; moveAttempt <= villageRadius;
+ ++moveAttempt) {
+ Vec2i
+ pos =
+ Vec2i(random.
+ randRange(-villageRadius * 2,
+ villageRadius * 2),
+ random.randRange(-villageRadius * 2,
+ villageRadius * 2)) +
+ adjacentUnit->getPosNotThreadSafe();
+
+ bool
+ canUnitMoveToCell =
+ map->aproxCanMove(adjacentUnit,
+ adjacentUnit->
+ getPosNotThreadSafe(), pos);
+ if (canUnitMoveToCell == true) {
+
+ if (ct != NULL) {
+ if (unitGroupCommandId == -1) {
+ unitGroupCommandId =
+ aiInterface->getWorld()->
+ getNextCommandGroupId();
+ }
+
+ //std::pair r = aiInterface->giveCommand(adjacentUnit,ct, pos, unitGroupCommandId);
+ aiInterface->giveCommand(adjacentUnit, ct,
+ pos,
+ unitGroupCommandId);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled && chrono.getMillis() > 0)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld [START]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ chrono.getMillis());
+ }
+
+ bool
+ Ai::outputAIBehaviourToConsole() const {
+ return
+ false;
+ }
+
+ void
+ Ai::saveGame(XmlNode * rootNode) const {
+ std::map <
+ string,
+ string >
+ mapTagReplacements;
+ XmlNode *
+ aiNode = rootNode->addChild("Ai");
+
+ // AiInterface *aiInterface;
+ // AiRules aiRules;
+ // int startLoc;
+ aiNode->
+ addAttribute("startLoc", intToStr(startLoc), mapTagReplacements);
+ // bool randomMinWarriorsReached;
+ aiNode->
+ addAttribute("randomMinWarriorsReached",
+ intToStr(randomMinWarriorsReached), mapTagReplacements);
+ // Tasks tasks;
+ for (Tasks::const_iterator it = tasks.begin(); it != tasks.end();
+ ++it) {
+ (*it)->saveGame(aiNode);
+ }
+ // Positions expansionPositions;
+ for (Positions::const_iterator it = expansionPositions.begin();
+ it != expansionPositions.end(); ++it) {
+ XmlNode *
+ expansionPositionsNode = aiNode->addChild("expansionPositions");
+ expansionPositionsNode->addAttribute("pos", (*it).getString(),
+ mapTagReplacements);
+ }
+
+ // RandomGen random;
+ aiNode->addAttribute("random", intToStr(random.getLastNumber()),
+ mapTagReplacements);
+ // std::map factionSwitchTeamRequestCount;
+
+ // int maxBuildRadius;
+ aiNode->addAttribute("maxBuildRadius", intToStr(maxBuildRadius),
+ mapTagReplacements);
+ // int minMinWarriors;
+ aiNode->addAttribute("minMinWarriors", intToStr(minMinWarriors),
+ mapTagReplacements);
+ // int minMinWarriorsExpandCpuEasy;
+ aiNode->addAttribute("minMinWarriorsExpandCpuEasy",
+ intToStr(minMinWarriorsExpandCpuEasy),
+ mapTagReplacements);
+ // int minMinWarriorsExpandCpuZeta;
+ aiNode->addAttribute("minMinWarriorsExpandCpuZeta",
+ intToStr(minMinWarriorsExpandCpuZeta),
+ mapTagReplacements);
+ // int minMinWarriorsExpandCpuUltra;
+ aiNode->addAttribute("minMinWarriorsExpandCpuUltra",
+ intToStr(minMinWarriorsExpandCpuUltra),
+ mapTagReplacements);
+ // int minMinWarriorsExpandCpuNormal;
+ aiNode->addAttribute("minMinWarriorsExpandCpuNormal",
+ intToStr(minMinWarriorsExpandCpuNormal),
+ mapTagReplacements);
+ // int maxMinWarriors;
+ aiNode->addAttribute("maxMinWarriors", intToStr(maxMinWarriors),
+ mapTagReplacements);
+ // int maxExpansions;
+ aiNode->addAttribute("maxExpansions", intToStr(maxExpansions),
+ mapTagReplacements);
+ // int villageRadius;
+ aiNode->addAttribute("villageRadius", intToStr(villageRadius),
+ mapTagReplacements);
+ // int scoutResourceRange;
+ aiNode->addAttribute("scoutResourceRange",
+ intToStr(scoutResourceRange),
+ mapTagReplacements);
+ // int minWorkerAttackersHarvesting;
+ aiNode->addAttribute("minWorkerAttackersHarvesting",
+ intToStr(minWorkerAttackersHarvesting),
+ mapTagReplacements);
+ }
+
+ void
+ Ai::loadGame(const XmlNode * rootNode, Faction * faction) {
+ const XmlNode *
+ aiNode = rootNode->getChild("Ai");
+
+ startLoc = aiNode->getAttribute("startLoc")->getIntValue();
+ randomMinWarriorsReached =
+ aiNode->getAttribute("randomMinWarriorsReached")->getIntValue() !=
+ 0;
+
+ vector < XmlNode * >taskNodeList = aiNode->getChildList("Task");
+ for (unsigned int i = 0; i < taskNodeList.size(); ++i) {
+ XmlNode *
+ taskNode = taskNodeList[i];
+ TaskClass
+ taskClass =
+ static_cast
+ (taskNode->getAttribute("taskClass")->getIntValue());
+ switch (taskClass) {
+ case tcProduce:
+ {
+ ProduceTask *
+ newTask = ProduceTask::loadGame(taskNode, faction);
+ tasks.push_back(newTask);
+ }
+ break;
+ case tcBuild:
+ {
+ BuildTask *
+ newTask = BuildTask::loadGame(taskNode, faction);
+ tasks.push_back(newTask);
+ }
+ break;
+ case tcUpgrade:
+ {
+ UpgradeTask *
+ newTask = UpgradeTask::loadGame(taskNode, faction);
+ tasks.push_back(newTask);
+ }
+ break;
+ }
+ }
+
+ vector < XmlNode * >expansionPositionsNodeList =
+ aiNode->getChildList("expansionPositions");
+ for (unsigned int i = 0; i < expansionPositionsNodeList.size(); ++i) {
+ XmlNode *
+ expansionPositionsNode = expansionPositionsNodeList[i];
+ Vec2i
+ pos =
+ Vec2i::strToVec2(expansionPositionsNode->getAttribute("pos")->
+ getValue());
+ expansionPositions.push_back(pos);
+ }
+
+ // RandomGen random;
+ random.setLastNumber(aiNode->getAttribute("random")->getIntValue());
+ // std::map factionSwitchTeamRequestCount;
+
+ // int maxBuildRadius;
+ maxBuildRadius =
+ aiNode->getAttribute("maxBuildRadius")->getIntValue();
+ // int minMinWarriors;
+ minMinWarriors =
+ aiNode->getAttribute("minMinWarriors")->getIntValue();
+ // int minMinWarriorsExpandCpuEasy;
+ minMinWarriorsExpandCpuEasy =
+ aiNode->getAttribute("minMinWarriorsExpandCpuEasy")->getIntValue();
+ // int minMinWarriorsExpandCpZeta;
+ minMinWarriorsExpandCpuZeta =
+ aiNode->getAttribute("minMinWarriorsExpandCpuZeta")->getIntValue();
+ // int minMinWarriorsExpandCpuUltra;
+ minMinWarriorsExpandCpuUltra =
+ aiNode->getAttribute("minMinWarriorsExpandCpuUltra")->getIntValue();
+ // int minMinWarriorsExpandCpuNormal;
+ minMinWarriorsExpandCpuNormal =
+ aiNode->getAttribute("minMinWarriorsExpandCpuNormal")->
+ getIntValue();
+ // int maxMinWarriors;
+ maxMinWarriors =
+ aiNode->getAttribute("maxMinWarriors")->getIntValue();
+ // int maxExpansions;
+ maxExpansions = aiNode->getAttribute("maxExpansions")->getIntValue();
+ // int villageRadius;
+ villageRadius = aiNode->getAttribute("villageRadius")->getIntValue();
+ // int scoutResourceRange;
+ scoutResourceRange =
+ aiNode->getAttribute("scoutResourceRange")->getIntValue();
+ // int minWorkerAttackersHarvesting;
+ minWorkerAttackersHarvesting =
+ aiNode->getAttribute("minWorkerAttackersHarvesting")->getIntValue();
+ }
+
+ }
+} //end namespace
diff --git a/source/glest_game/ai/ai.h b/source/glest_game/ai/ai.h
index 19b108c91..a0e891f81 100644
--- a/source/glest_game/ai/ai.h
+++ b/source/glest_game/ai/ai.h
@@ -22,410 +22,389 @@
# include "leak_dumper.h"
using
- std::deque;
+std::deque;
using
- std::vector;
+std::vector;
using
- std::list;
+std::list;
using
- Shared::Util::RandomGen;
+Shared::Util::RandomGen;
namespace
- Glest
-{
- namespace
- Game
- {
+ Glest {
+ namespace
+ Game {
- class
- AiInterface;
- class
- AiRule;
+ class
+ AiInterface;
+ class
+ AiRule;
-// =====================================================
-// class Task
-//
-/// An action that has to be performed by the IA
-// =====================================================
+ // =====================================================
+ // class Task
+ //
+ /// An action that has to be performed by the IA
+ // =====================================================
- enum TaskClass
- {
- tcProduce,
- tcBuild,
- tcUpgrade
- };
+ enum TaskClass {
+ tcProduce,
+ tcBuild,
+ tcUpgrade
+ };
- class
- Task
- {
- protected:
- TaskClass
- taskClass;
+ class
+ Task {
+ protected:
+ TaskClass
+ taskClass;
- public:
- Task ();
- virtual ~
- Task ()
- {
- }
- TaskClass
- getClass () const
- {
- return
- taskClass;
- }
- virtual string
- toString () const = 0;
+ public:
+ Task();
+ virtual ~
+ Task() {
+ }
+ TaskClass
+ getClass() const {
+ return
+ taskClass;
+ }
+ virtual string
+ toString() const = 0;
- virtual void
- saveGame (XmlNode * rootNode) const = 0;
- };
+ virtual void
+ saveGame(XmlNode * rootNode) const = 0;
+ };
-// ==================== ProduceTask ====================
+ // ==================== ProduceTask ====================
- class
- ProduceTask:
- public
- Task
- {
- private:
- UnitClass
- unitClass;
- const UnitType *
- unitType;
- const ResourceType *
- resourceType;
+ class
+ ProduceTask :
+ public
+ Task {
+ private:
+ UnitClass
+ unitClass;
+ const UnitType *
+ unitType;
+ const ResourceType *
+ resourceType;
- ProduceTask ();
- public:
- explicit
- ProduceTask (UnitClass unitClass);
- explicit
- ProduceTask (const UnitType * unitType);
- explicit
- ProduceTask (const ResourceType * resourceType);
+ ProduceTask();
+ public:
+ explicit
+ ProduceTask(UnitClass unitClass);
+ explicit
+ ProduceTask(const UnitType * unitType);
+ explicit
+ ProduceTask(const ResourceType * resourceType);
- UnitClass
- getUnitClass () const
- {
- return
- unitClass;
- }
- const UnitType *
- getUnitType () const
- {
- return
- unitType;
- }
- const ResourceType *
- getResourceType () const
- {
- return
- resourceType;
- }
- virtual string
- toString () const;
+ UnitClass
+ getUnitClass() const {
+ return
+ unitClass;
+ }
+ const UnitType *
+ getUnitType() const {
+ return
+ unitType;
+ }
+ const ResourceType *
+ getResourceType() const {
+ return
+ resourceType;
+ }
+ virtual string
+ toString() const;
- virtual void
- saveGame (XmlNode * rootNode) const;
- static ProduceTask *
- loadGame (const XmlNode * rootNode, Faction * faction);
- };
+ virtual void
+ saveGame(XmlNode * rootNode) const;
+ static ProduceTask *
+ loadGame(const XmlNode * rootNode, Faction * faction);
+ };
-// ==================== BuildTask ====================
+ // ==================== BuildTask ====================
- class
- BuildTask:
- public
- Task
- {
- private:
- const UnitType *
- unitType;
- const ResourceType *
- resourceType;
- bool
- forcePos;
- Vec2i
- pos;
+ class
+ BuildTask :
+ public
+ Task {
+ private:
+ const UnitType *
+ unitType;
+ const ResourceType *
+ resourceType;
+ bool
+ forcePos;
+ Vec2i
+ pos;
- BuildTask ();
+ BuildTask();
- public:
- explicit
- BuildTask (const UnitType * unitType);
- explicit
- BuildTask (const ResourceType * resourceType);
- BuildTask (const UnitType * unitType, const Vec2i & pos);
+ public:
+ explicit
+ BuildTask(const UnitType * unitType);
+ explicit
+ BuildTask(const ResourceType * resourceType);
+ BuildTask(const UnitType * unitType, const Vec2i & pos);
- const UnitType *
- getUnitType () const
- {
- return
- unitType;
- }
- const ResourceType *
- getResourceType () const
- {
- return
- resourceType;
- }
- bool
- getForcePos () const
- {
- return
- forcePos;
- }
- Vec2i
- getPos () const
- {
- return
- pos;
- }
- virtual string
- toString () const;
+ const UnitType *
+ getUnitType() const {
+ return
+ unitType;
+ }
+ const ResourceType *
+ getResourceType() const {
+ return
+ resourceType;
+ }
+ bool
+ getForcePos() const {
+ return
+ forcePos;
+ }
+ Vec2i
+ getPos() const {
+ return
+ pos;
+ }
+ virtual string
+ toString() const;
- virtual void
- saveGame (XmlNode * rootNode) const;
- static BuildTask *
- loadGame (const XmlNode * rootNode, Faction * faction);
- };
+ virtual void
+ saveGame(XmlNode * rootNode) const;
+ static BuildTask *
+ loadGame(const XmlNode * rootNode, Faction * faction);
+ };
-// ==================== UpgradeTask ====================
+ // ==================== UpgradeTask ====================
- class
- UpgradeTask:
- public
- Task
- {
- private:
- const UpgradeType *
- upgradeType;
+ class
+ UpgradeTask :
+ public
+ Task {
+ private:
+ const UpgradeType *
+ upgradeType;
- UpgradeTask ();
- public:
- explicit
- UpgradeTask (const UpgradeType * upgradeType);
- const UpgradeType *
- getUpgradeType () const
- {
- return
- upgradeType;
- }
- virtual string
- toString () const;
+ UpgradeTask();
+ public:
+ explicit
+ UpgradeTask(const UpgradeType * upgradeType);
+ const UpgradeType *
+ getUpgradeType() const {
+ return
+ upgradeType;
+ }
+ virtual string
+ toString() const;
- virtual void
- saveGame (XmlNode * rootNode) const;
- static UpgradeTask *
- loadGame (const XmlNode * rootNode, Faction * faction);
- };
+ virtual void
+ saveGame(XmlNode * rootNode) const;
+ static UpgradeTask *
+ loadGame(const XmlNode * rootNode, Faction * faction);
+ };
-// ===============================
-// class AI
-//
-/// Main AI class
-// ===============================
+ // ===============================
+ // class AI
+ //
+ /// Main AI class
+ // ===============================
- class
- Ai
- {
- private:
- int
- maxBuildRadius;
+ class
+ Ai {
+ private:
+ int
+ maxBuildRadius;
- int
- minMinWarriors;
- int
- minMinWarriorsExpandCpuEasy;
- int
- minMinWarriorsExpandCpuZeta;
- int
- minMinWarriorsExpandCpuUltra;
- int
- minMinWarriorsExpandCpuNormal;
- int
- maxMinWarriors;
+ int
+ minMinWarriors;
+ int
+ minMinWarriorsExpandCpuEasy;
+ int
+ minMinWarriorsExpandCpuZeta;
+ int
+ minMinWarriorsExpandCpuUltra;
+ int
+ minMinWarriorsExpandCpuNormal;
+ int
+ maxMinWarriors;
- int
- maxExpansions;
- int
- villageRadius;
- int
- scoutResourceRange;
- int
- minWorkerAttackersHarvesting;
- int
- minBuildSpacing;
+ int
+ maxExpansions;
+ int
+ villageRadius;
+ int
+ scoutResourceRange;
+ int
+ minWorkerAttackersHarvesting;
+ int
+ minBuildSpacing;
- public:
- enum ResourceUsage
- {
- ruHarvester,
- ruWarrior,
- ruBuilding,
- ruUpgrade
- };
+ public:
+ enum ResourceUsage {
+ ruHarvester,
+ ruWarrior,
+ ruBuilding,
+ ruUpgrade
+ };
- private:
- typedef
- vector <
- AiRule * >
- AiRules;
- typedef
- list < const Task *>
- Tasks;
- typedef
- deque <
- Vec2i >
- Positions;
+ private:
+ typedef
+ vector <
+ AiRule * >
+ AiRules;
+ typedef
+ list < const Task *>
+ Tasks;
+ typedef
+ deque <
+ Vec2i >
+ Positions;
- private:
- AiInterface *
- aiInterface;
- AiRules
- aiRules;
- int
- startLoc;
- bool
- randomMinWarriorsReached;
- Tasks
- tasks;
- Positions
- expansionPositions;
- RandomGen
- random;
- std::map < int, int >
- factionSwitchTeamRequestCount;
- int
- minWarriors;
+ private:
+ AiInterface *
+ aiInterface;
+ AiRules
+ aiRules;
+ int
+ startLoc;
+ bool
+ randomMinWarriorsReached;
+ Tasks
+ tasks;
+ Positions
+ expansionPositions;
+ RandomGen
+ random;
+ std::map < int, int >
+ factionSwitchTeamRequestCount;
+ int
+ minWarriors;
- bool
- getAdjacentUnits (std::map < float, std::map < int,
- const Unit * > >&signalAdjacentUnits,
- const Unit * unit);
+ bool
+ getAdjacentUnits(std::map < float, std::map < int,
+ const Unit * > >&signalAdjacentUnits,
+ const Unit * unit);
- public:
- Ai ()
- {
- // Defaults that used to be static which can now be overriden
- maxBuildRadius = 40;
- minMinWarriors = 7;
- minMinWarriorsExpandCpuEasy = 1;
- minMinWarriorsExpandCpuZeta = 3;
- minMinWarriorsExpandCpuUltra = 3;
- minMinWarriorsExpandCpuNormal = 3;
- maxMinWarriors = 20;
- maxExpansions = 20;
- villageRadius = 15;
- scoutResourceRange = 20;
- minWorkerAttackersHarvesting = 3;
- minBuildSpacing = 1;
+ public:
+ Ai() {
+ // Defaults that used to be static which can now be overriden
+ maxBuildRadius = 40;
+ minMinWarriors = 7;
+ minMinWarriorsExpandCpuEasy = 1;
+ minMinWarriorsExpandCpuZeta = 3;
+ minMinWarriorsExpandCpuUltra = 3;
+ minMinWarriorsExpandCpuNormal = 3;
+ maxMinWarriors = 20;
+ maxExpansions = 20;
+ villageRadius = 15;
+ scoutResourceRange = 20;
+ minWorkerAttackersHarvesting = 3;
+ minBuildSpacing = 1;
- aiInterface = NULL;
- startLoc = -1;
- randomMinWarriorsReached = false;
- minWarriors = 0;
- }
- ~
- Ai ();
+ aiInterface = NULL;
+ startLoc = -1;
+ randomMinWarriorsReached = false;
+ minWarriors = 0;
+ }
+ ~
+ Ai();
- void
- init (AiInterface * aiInterface, int useStartLocation = -1);
- void
- update ();
+ void
+ init(AiInterface * aiInterface, int useStartLocation = -1);
+ void
+ update();
- //state requests
- AiInterface *
- getAiInterface () const
- {
- return
- aiInterface;
- }
- RandomGen *
- getRandom ();
- int
- getCountOfType (const UnitType * ut);
+ //state requests
+ AiInterface *
+ getAiInterface() const {
+ return
+ aiInterface;
+ }
+ RandomGen *
+ getRandom();
+ int
+ getCountOfType(const UnitType * ut);
- int
- getMinWarriors () const
- {
- return
- minWarriors;
- }
+ int
+ getMinWarriors() const {
+ return
+ minWarriors;
+ }
- int
- getCountOfClass (UnitClass uc,
- UnitClass * additionalUnitClassToExcludeFromCount =
- NULL);
- float
- getRatioOfClass (UnitClass uc,
- UnitClass * additionalUnitClassToExcludeFromCount =
- NULL);
+ int
+ getCountOfClass(UnitClass uc,
+ UnitClass * additionalUnitClassToExcludeFromCount =
+ NULL);
+ float
+ getRatioOfClass(UnitClass uc,
+ UnitClass * additionalUnitClassToExcludeFromCount =
+ NULL);
- const ResourceType *
- getNeededResource (int unitIndex);
- bool
- isStableBase ();
- bool
- findPosForBuilding (const UnitType * building, const Vec2i & searchPos,
- Vec2i & pos);
- bool
- findAbleUnit (int *unitIndex, CommandClass ability, bool idleOnly);
- bool
- findAbleUnit (int *unitIndex, CommandClass ability,
- CommandClass currentCommand);
- //vector findUnitsDoingCommand(CommandClass currentCommand);
- vector < int >
- findUnitsHarvestingResourceType (const ResourceType * rt);
+ const ResourceType *
+ getNeededResource(int unitIndex);
+ bool
+ isStableBase();
+ bool
+ findPosForBuilding(const UnitType * building, const Vec2i & searchPos,
+ Vec2i & pos);
+ bool
+ findAbleUnit(int *unitIndex, CommandClass ability, bool idleOnly);
+ bool
+ findAbleUnit(int *unitIndex, CommandClass ability,
+ CommandClass currentCommand);
+ //vector findUnitsDoingCommand(CommandClass currentCommand);
+ vector < int >
+ findUnitsHarvestingResourceType(const ResourceType * rt);
- bool
- beingAttacked (Vec2i & pos, Field & field, int radius);
+ bool
+ beingAttacked(Vec2i & pos, Field & field, int radius);
- //tasks
- void
- addTask (const Task * task);
- void
- addPriorityTask (const Task * task);
- bool
- anyTask ();
- const Task *
- getTask () const;
- void
- removeTask (const Task * task);
- void
- retryTask (const Task * task);
+ //tasks
+ void
+ addTask(const Task * task);
+ void
+ addPriorityTask(const Task * task);
+ bool
+ anyTask();
+ const Task *
+ getTask() const;
+ void
+ removeTask(const Task * task);
+ void
+ retryTask(const Task * task);
- //expansions
- void
- addExpansion (const Vec2i & pos);
- Vec2i
- getRandomHomePosition ();
+ //expansions
+ void
+ addExpansion(const Vec2i & pos);
+ Vec2i
+ getRandomHomePosition();
- //actions
- void
- sendScoutPatrol ();
- void
- massiveAttack (const Vec2i & pos, Field field, bool ultraAttack =
- false);
- void
- returnBase (int unitIndex);
- void
- harvest (int unitIndex);
- bool
- haveBlockedUnits ();
- void
- unblockUnits ();
+ //actions
+ void
+ sendScoutPatrol();
+ void
+ massiveAttack(const Vec2i & pos, Field field, bool ultraAttack =
+ false);
+ void
+ returnBase(int unitIndex);
+ void
+ harvest(int unitIndex);
+ bool
+ haveBlockedUnits();
+ void
+ unblockUnits();
- bool
- outputAIBehaviourToConsole () const;
+ bool
+ outputAIBehaviourToConsole() const;
- void
- saveGame (XmlNode * rootNode) const;
- void
- loadGame (const XmlNode * rootNode, Faction * faction);
- };
+ void
+ saveGame(XmlNode * rootNode) const;
+ void
+ loadGame(const XmlNode * rootNode, Faction * faction);
+ };
-}} //end namespace
+ }
+} //end namespace
#endif
diff --git a/source/glest_game/ai/ai_interface.cpp b/source/glest_game/ai/ai_interface.cpp
index cea7b00d2..17c62eb4c 100644
--- a/source/glest_game/ai/ai_interface.cpp
+++ b/source/glest_game/ai/ai_interface.cpp
@@ -35,1616 +35,1451 @@
#include "leak_dumper.h"
using namespace
- Shared::Util;
+Shared::Util;
using namespace
- Shared::Graphics;
+Shared::Graphics;
// =====================================================
// class AiInterface
// =====================================================
namespace
- Glest
-{
- namespace
- Game
- {
+ Glest {
+ namespace
+ Game {
-// =====================================================
-// class FactionThread
-// =====================================================
+ // =====================================================
+ // class FactionThread
+ // =====================================================
- AiInterfaceThread::AiInterfaceThread (AiInterface * aiIntf):
- BaseThread ()
- {
- this->masterController = NULL;
- this->
- triggerIdMutex = new Mutex (CODE_AT_LINE);
- this->
- aiIntf = aiIntf;
- uniqueID = "AiInterfaceThread";
- }
+ AiInterfaceThread::AiInterfaceThread(AiInterface * aiIntf) :
+ BaseThread() {
+ this->masterController = NULL;
+ this->
+ triggerIdMutex = new Mutex(CODE_AT_LINE);
+ this->
+ aiIntf = aiIntf;
+ uniqueID = "AiInterfaceThread";
+ }
- AiInterfaceThread::~
- AiInterfaceThread ()
- {
- delete
- triggerIdMutex;
- triggerIdMutex = NULL;
- }
+ AiInterfaceThread::~
+ AiInterfaceThread() {
+ delete
+ triggerIdMutex;
+ triggerIdMutex = NULL;
+ }
- void
- AiInterfaceThread::setQuitStatus (bool value)
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s] Line: %d value = %d\n",
- __FILE__, __FUNCTION__, __LINE__, value);
+ void
+ AiInterfaceThread::setQuitStatus(bool value) {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s] Line: %d value = %d\n",
+ __FILE__, __FUNCTION__, __LINE__, value);
- BaseThread::setQuitStatus (value);
- if (value == true)
- {
- signal (-1);
- }
+ BaseThread::setQuitStatus(value);
+ if (value == true) {
+ signal(-1);
+ }
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s] Line: %d\n", __FILE__,
- __FUNCTION__, __LINE__);
- }
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s] Line: %d\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ }
- void
- AiInterfaceThread::signal (int frameIndex)
- {
- if (frameIndex >= 0)
- {
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- MutexSafeWrapper
- safeMutex (triggerIdMutex, mutexOwnerId);
- this->frameIndex.first = frameIndex;
- this->frameIndex.second = false;
+ void
+ AiInterfaceThread::signal(int frameIndex) {
+ if (frameIndex >= 0) {
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ MutexSafeWrapper
+ safeMutex(triggerIdMutex, mutexOwnerId);
+ this->frameIndex.first = frameIndex;
+ this->frameIndex.second = false;
- safeMutex.ReleaseLock ();
- }
- semTaskSignalled.signal ();
- }
+ safeMutex.ReleaseLock();
+ }
+ semTaskSignalled.signal();
+ }
- void
- AiInterfaceThread::setTaskCompleted (int frameIndex)
- {
- if (frameIndex >= 0)
- {
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- MutexSafeWrapper
- safeMutex (triggerIdMutex, mutexOwnerId);
- if (this->frameIndex.first == frameIndex)
- {
- this->frameIndex.second = true;
- }
- safeMutex.ReleaseLock ();
- }
- }
+ void
+ AiInterfaceThread::setTaskCompleted(int frameIndex) {
+ if (frameIndex >= 0) {
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ MutexSafeWrapper
+ safeMutex(triggerIdMutex, mutexOwnerId);
+ if (this->frameIndex.first == frameIndex) {
+ this->frameIndex.second = true;
+ }
+ safeMutex.ReleaseLock();
+ }
+ }
- bool
- AiInterfaceThread::canShutdown (bool deleteSelfIfShutdownDelayed)
- {
- bool
- ret = (getExecutingTask () == false);
- if (ret == false && deleteSelfIfShutdownDelayed == true)
- {
- setDeleteSelfOnExecutionDone (deleteSelfIfShutdownDelayed);
- deleteSelfIfRequired ();
- signalQuit ();
- }
+ bool
+ AiInterfaceThread::canShutdown(bool deleteSelfIfShutdownDelayed) {
+ bool
+ ret = (getExecutingTask() == false);
+ if (ret == false && deleteSelfIfShutdownDelayed == true) {
+ setDeleteSelfOnExecutionDone(deleteSelfIfShutdownDelayed);
+ deleteSelfIfRequired();
+ signalQuit();
+ }
- return ret;
- }
+ return ret;
+ }
- bool
- AiInterfaceThread::isSignalCompleted (int frameIndex)
- {
- if (getRunningStatus () == false)
- {
- return true;
- }
- static string
- mutexOwnerId = string (__FILE__) + string ("_") + intToStr (__LINE__);
- MutexSafeWrapper
- safeMutex (triggerIdMutex, mutexOwnerId);
- //bool result = (event != NULL ? event->eventCompleted : true);
- bool
- result = (this->frameIndex.first == frameIndex
- && this->frameIndex.second == true);
+ bool
+ AiInterfaceThread::isSignalCompleted(int frameIndex) {
+ if (getRunningStatus() == false) {
+ return true;
+ }
+ static string
+ mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__);
+ MutexSafeWrapper
+ safeMutex(triggerIdMutex, mutexOwnerId);
+ //bool result = (event != NULL ? event->eventCompleted : true);
+ bool
+ result = (this->frameIndex.first == frameIndex
+ && this->frameIndex.second == true);
- //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] worker thread this = %p, this->frameIndex.first = %d, this->frameIndex.second = %d\n",__FILE__,__FUNCTION__,__LINE__,this,this->frameIndex.first,this->frameIndex.second);
+ //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] worker thread this = %p, this->frameIndex.first = %d, this->frameIndex.second = %d\n",__FILE__,__FUNCTION__,__LINE__,this,this->frameIndex.first,this->frameIndex.second);
- safeMutex.ReleaseLock ();
- return result;
- }
+ safeMutex.ReleaseLock();
+ return result;
+ }
- void
- AiInterfaceThread::signalQuit ()
- {
- if (this->aiIntf != NULL)
- {
- MutexSafeWrapper
- safeMutex (this->aiIntf->getMutex (),
- string (__FILE__) + "_" + intToStr (__LINE__));
- this->aiIntf = NULL;
- }
+ void
+ AiInterfaceThread::signalQuit() {
+ if (this->aiIntf != NULL) {
+ MutexSafeWrapper
+ safeMutex(this->aiIntf->getMutex(),
+ string(__FILE__) + "_" + intToStr(__LINE__));
+ this->aiIntf = NULL;
+ }
- BaseThread::signalQuit ();
- }
- void
- AiInterfaceThread::execute ()
- {
- RunningStatusSafeWrapper
- runningStatus (this);
- try
- {
- //setRunningStatus(true);
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- if (SystemFlags::VERBOSE_MODE_ENABLED)
- printf
- ("In [%s::%s Line: %d] ****************** STARTING worker thread this = %p\n",
- __FILE__, __FUNCTION__, __LINE__, this);
+ BaseThread::signalQuit();
+ }
+ void
+ AiInterfaceThread::execute() {
+ RunningStatusSafeWrapper
+ runningStatus(this);
+ try {
+ //setRunningStatus(true);
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ if (SystemFlags::VERBOSE_MODE_ENABLED)
+ printf
+ ("In [%s::%s Line: %d] ****************** STARTING worker thread this = %p\n",
+ __FILE__, __FUNCTION__, __LINE__, this);
- //bool minorDebugPerformance = false;
- Chrono
- chrono;
+ //bool minorDebugPerformance = false;
+ Chrono
+ chrono;
- //unsigned int idx = 0;
- for (; this->aiIntf != NULL;)
- {
- if (getQuitStatus () == true)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__, __FUNCTION__, __LINE__);
- break;
- }
+ //unsigned int idx = 0;
+ for (; this->aiIntf != NULL;) {
+ if (getQuitStatus() == true) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__, __FUNCTION__, __LINE__);
+ break;
+ }
- semTaskSignalled.waitTillSignalled ();
+ semTaskSignalled.waitTillSignalled();
- static string
- masterSlaveOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- MasterSlaveThreadControllerSafeWrapper
- safeMasterController (masterController, 20000,
- masterSlaveOwnerId);
+ static string
+ masterSlaveOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ MasterSlaveThreadControllerSafeWrapper
+ safeMasterController(masterController, 20000,
+ masterSlaveOwnerId);
- if (getQuitStatus () == true)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__, __FUNCTION__, __LINE__);
- break;
- }
+ if (getQuitStatus() == true) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__, __FUNCTION__, __LINE__);
+ break;
+ }
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- MutexSafeWrapper
- safeMutex (triggerIdMutex, mutexOwnerId);
- bool
- executeTask = (frameIndex.first >= 0);
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ MutexSafeWrapper
+ safeMutex(triggerIdMutex, mutexOwnerId);
+ bool
+ executeTask = (frameIndex.first >= 0);
- //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] frameIndex = %d this = %p executeTask = %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, executeTask);
+ //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] frameIndex = %d this = %p executeTask = %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, executeTask);
- safeMutex.ReleaseLock ();
+ safeMutex.ReleaseLock();
- if (executeTask == true)
- {
- ExecutingTaskSafeWrapper
- safeExecutingTaskMutex (this);
+ if (executeTask == true) {
+ ExecutingTaskSafeWrapper
+ safeExecutingTaskMutex(this);
- MutexSafeWrapper
- safeMutex (this->aiIntf->getMutex (),
- string (__FILE__) + "_" + intToStr (__LINE__));
+ MutexSafeWrapper
+ safeMutex(this->aiIntf->getMutex(),
+ string(__FILE__) + "_" + intToStr(__LINE__));
- this->aiIntf->update ();
+ this->aiIntf->update();
- safeMutex.ReleaseLock ();
+ safeMutex.ReleaseLock();
- setTaskCompleted (frameIndex.first);
- }
+ setTaskCompleted(frameIndex.first);
+ }
- if (getQuitStatus () == true)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__, __FUNCTION__, __LINE__);
- break;
- }
- }
+ if (getQuitStatus() == true) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__, __FUNCTION__, __LINE__);
+ break;
+ }
+ }
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- if (SystemFlags::VERBOSE_MODE_ENABLED)
- printf
- ("In [%s::%s Line: %d] ****************** ENDING worker thread this = %p\n",
- __FILE__, __FUNCTION__, __LINE__, this);
- }
- catch (const exception & ex)
- {
- //setRunningStatus(false);
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ if (SystemFlags::VERBOSE_MODE_ENABLED)
+ printf
+ ("In [%s::%s Line: %d] ****************** ENDING worker thread this = %p\n",
+ __FILE__, __FUNCTION__, __LINE__, this);
+ } catch (const exception & ex) {
+ //setRunningStatus(false);
- SystemFlags::OutputDebug (SystemFlags::debugError,
- "In [%s::%s Line: %d] Error [%s]\n",
- __FILE__, __FUNCTION__, __LINE__,
- ex.what ());
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
+ SystemFlags::OutputDebug(SystemFlags::debugError,
+ "In [%s::%s Line: %d] Error [%s]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ ex.what());
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
- throw
- megaglest_runtime_error (ex.what ());
- }
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s] Line: %d\n", __FILE__,
- __FUNCTION__, __LINE__);
- }
+ throw
+ megaglest_runtime_error(ex.what());
+ }
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s] Line: %d\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ }
- AiInterface::AiInterface (Game & game, int factionIndex, int teamIndex,
- int useStartLocation):
- fp (NULL)
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
+ AiInterface::AiInterface(Game & game, int factionIndex, int teamIndex,
+ int useStartLocation) :
+ fp(NULL) {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
- this->aiMutex = new Mutex (CODE_AT_LINE);
- this->workerThread = NULL;
- this->world = game.getWorld ();
- this->commander = game.getCommander ();
- this->console = game.getConsole ();
- this->gameSettings = game.getGameSettings ();
+ this->aiMutex = new Mutex(CODE_AT_LINE);
+ this->workerThread = NULL;
+ this->world = game.getWorld();
+ this->commander = game.getCommander();
+ this->console = game.getConsole();
+ this->gameSettings = game.getGameSettings();
- this->factionIndex = factionIndex;
- this->teamIndex = teamIndex;
- timer = 0;
+ this->factionIndex = factionIndex;
+ this->teamIndex = teamIndex;
+ timer = 0;
- //init ai
- ai.init (this, useStartLocation);
+ //init ai
+ ai.init(this, useStartLocation);
- //config
- logLevel = Config::getInstance ().getInt ("AiLog");
- redir = Config::getInstance ().getBool ("AiRedir");
+ //config
+ logLevel = Config::getInstance().getInt("AiLog");
+ redir = Config::getInstance().getBool("AiRedir");
- aiLogFile = getLogFilename ();
- if (getGameReadWritePath (GameConstants::path_logs_CacheLookupKey) !=
- "")
- {
- aiLogFile =
- getGameReadWritePath (GameConstants::path_logs_CacheLookupKey) +
- aiLogFile;
- }
- else
- {
- string
- userData = Config::getInstance ().getString ("UserData_Root", "");
- if (userData != "")
- {
- endPathWithSlash (userData);
- }
- aiLogFile = userData + aiLogFile;
- }
+ aiLogFile = getLogFilename();
+ if (getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) !=
+ "") {
+ aiLogFile =
+ getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) +
+ aiLogFile;
+ } else {
+ string
+ userData = Config::getInstance().getString("UserData_Root", "");
+ if (userData != "") {
+ endPathWithSlash(userData);
+ }
+ aiLogFile = userData + aiLogFile;
+ }
- //clear log file
- if (logLevel > 0)
- {
+ //clear log file
+ if (logLevel > 0) {
#ifdef WIN32
- fp =
- _wfopen (::Shared::Platform::utf8_decode (aiLogFile).c_str (),
- L"wt");
+ fp =
+ _wfopen(::Shared::Platform::utf8_decode(aiLogFile).c_str(),
+ L"wt");
#else
- fp = fopen (aiLogFile.c_str (), "wt");
+ fp = fopen(aiLogFile.c_str(), "wt");
#endif
- if (fp == NULL)
- {
- throw
- megaglest_runtime_error ("Can't open file: [" + aiLogFile +
- "]");
- }
- fprintf (fp,
- "ZetaGlest AI log file for Tech [%s] Faction [%s] #%d\n\n",
- this->gameSettings->getTech ().c_str (),
- this->world->getFaction (this->factionIndex)->getType ()->
- getName ().c_str (), this->factionIndex);
- }
-
-
- if (Config::getInstance ().getBool ("EnableAIWorkerThreads", "true") ==
- true)
- {
- if (workerThread != NULL)
- {
- workerThread->signalQuit ();
- if (workerThread->shutdownAndWait () == true)
- {
- delete
- workerThread;
- }
- workerThread = NULL;
- }
- static string
- mutexOwnerId =
- string (extractFileFromDirectoryPath (__FILE__).c_str ()) +
- string ("_") + intToStr (__LINE__);
- this->workerThread = new AiInterfaceThread (this);
- this->workerThread->setUniqueID (mutexOwnerId);
- this->workerThread->start ();
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- }
-
- void
- AiInterface::init ()
- {
- world = NULL;;
- commander = NULL;;
- console = NULL;;
- gameSettings = NULL;;
- timer = 0;
- factionIndex = 0;
- teamIndex = 0;
- redir = false;
- logLevel = 0;
- fp = NULL;;
- aiMutex = NULL;
- workerThread = NULL;
- }
-
- AiInterface::~AiInterface ()
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] deleting AI factionIndex = %d, teamIndex = %d\n",
- __FILE__, __FUNCTION__, __LINE__,
- this->factionIndex, this->teamIndex);
- cacheUnitHarvestResourceLookup.clear ();
-
- if (workerThread != NULL)
- {
- workerThread->signalQuit ();
- sleep (0);
- if (workerThread->canShutdown (true) == true &&
- workerThread->shutdownAndWait () == true)
- {
- delete
- workerThread;
- }
- workerThread = NULL;
- }
-
- if (fp)
- {
- fclose (fp);
- fp = NULL;
- }
-
- delete
- aiMutex;
- aiMutex = NULL;
- }
-
- void
- AiInterface::signalWorkerThread (int frameIndex)
- {
- if (workerThread != NULL)
- {
- workerThread->signal (frameIndex);
- }
- else
- {
- this->update ();
- }
- }
-
- bool
- AiInterface::isWorkerThreadSignalCompleted (int frameIndex)
- {
- if (workerThread != NULL)
- {
- return workerThread->isSignalCompleted (frameIndex);
- }
- return true;
- }
-
-// ==================== main ====================
-
- void
- AiInterface::update ()
- {
- timer++;
- ai.update ();
- }
-
-// ==================== misc ====================
-
- bool
- AiInterface::isLogLevelEnabled (int level)
- {
- return (this->logLevel >= level);
- }
-
- void
- AiInterface::printLog (int logLevel, const string & s)
- {
- if (isLogLevelEnabled (logLevel) == true)
- {
- string
- logString = "(" + intToStr (factionIndex) + ") " + s;
-
- MutexSafeWrapper
- safeMutex (aiMutex, string (__FILE__) + "_" + intToStr (__LINE__));
- //print log to file
- if (fp != NULL)
- {
- fprintf (fp, "%s\n", logString.c_str ());
- }
-
- //redirect to console
- if (redir)
- {
- console->addLine (logString);
- }
- }
- }
-
-// ==================== interaction ====================
-
- Faction *
- AiInterface::getMyFaction ()
- {
- return world->getFaction (factionIndex);
- }
-
- bool
- AiInterface::executeCommandOverNetwork ()
- {
- bool
- enableServerControlledAI =
- gameSettings->getEnableServerControlledAI ();
- bool
- isNetworkGame = gameSettings->isNetworkGame ();
- NetworkRole
- role = NetworkManager::getInstance ().getNetworkRole ();
- Faction *
- faction = world->getFaction (factionIndex);
- return faction->getCpuControl (enableServerControlledAI, isNetworkGame,
- role);
- }
-
- std::pair < CommandResult,
- string >
- AiInterface::giveCommandSwitchTeamVote (const Faction * faction,
- SwitchTeamVote * vote)
- {
- assert (this->gameSettings != NULL);
-
- commander->trySwitchTeamVote (faction, vote);
- return std::pair < CommandResult, string > (crSuccess, "");
- }
-
- std::pair < CommandResult,
- string > AiInterface::giveCommand (int unitIndex,
- CommandClass commandClass,
- const Vec2i & pos)
- {
- assert (this->gameSettings != NULL);
-
- std::pair < CommandResult, string > result (crFailUndefined, "");
- if (executeCommandOverNetwork () == true)
- {
- const Unit *
- unit = getMyUnit (unitIndex);
- result =
- commander->tryGiveCommand (unit,
- unit->getType ()->
- getFirstCtOfClass (commandClass), pos,
- unit->getType (),
- CardinalDir (CardinalDir::NORTH));
- return result;
- }
- else
- {
- Command *
- c =
- new Command (world->getFaction (factionIndex)->
- getUnit (unitIndex)->getType ()->
- getFirstCtOfClass (commandClass), pos);
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- result =
- world->getFaction (factionIndex)->getUnit (unitIndex)->
- giveCommand (c);
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- return result;
- }
- }
-
- std::pair < CommandResult,
- string > AiInterface::giveCommand (const Unit * unit,
- const CommandType * commandType,
- const Vec2i & pos,
- int unitGroupCommandId)
- {
- assert (this->gameSettings != NULL);
-
- std::pair < CommandResult, string > result (crFailUndefined, "");
- if (unit == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unit in AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const UnitType *
- unitType = unit->getType ();
- if (unitType == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unittype with unit id: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unit->getId (),
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- if (commandType == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] commandType == NULL, unit id: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unit->getId (),
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const CommandType *
- ct = unit->getType ()->findCommandTypeById (commandType->getId ());
- if (ct == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unit->getId (),
- unit->getFullName (false).c_str (),
- unit->getDesc (false).c_str (),
- unit->getFaction ()->getIndex ());
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem, "%s\n",
- szBuf);
-
- std::string worldLog = world->DumpWorldToLog ();
- std::string sError =
- "worldLog = " + worldLog + " " + string (szBuf);
- throw
- megaglest_runtime_error (sError);
- }
-
- if (executeCommandOverNetwork () == true)
- {
- result = commander->tryGiveCommand (unit, commandType, pos,
- unit->getType (),
- CardinalDir (CardinalDir::
- NORTH), false,
- NULL, unitGroupCommandId);
- return result;
- }
- else
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- Faction *
- faction = world->getFaction (unit->getFactionIndex ());
- Unit *
- unitToCommand = faction->findUnit (unit->getId ());
- Command *
- cmd = new Command (commandType, pos);
- cmd->setUnitCommandGroupId (unitGroupCommandId);
- result = unitToCommand->giveCommand (cmd);
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- return result;
- }
- }
-
- std::pair < CommandResult,
- string > AiInterface::giveCommand (int unitIndex,
- const CommandType * commandType,
- const Vec2i & pos,
- int unitGroupCommandId)
- {
- assert (this->gameSettings != NULL);
-
- std::pair < CommandResult, string > result (crFailUndefined, "");
- const Unit *
- unit = getMyUnit (unitIndex);
- if (unit == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const UnitType *
- unitType = unit->getType ();
- if (unitType == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const CommandType *
- ct = unit->getType ()->findCommandTypeById (commandType->getId ());
- if (ct == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unit->getId (),
- unit->getFullName (false).c_str (),
- unit->getDesc (false).c_str (),
- unit->getFaction ()->getIndex ());
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem, "%s\n",
- szBuf);
-
- std::string worldLog = world->DumpWorldToLog ();
- std::string sError =
- "worldLog = " + worldLog + " " + string (szBuf);
- throw
- megaglest_runtime_error (sError);
- }
-
- if (executeCommandOverNetwork () == true)
- {
- const Unit *
- unit = getMyUnit (unitIndex);
- result =
- commander->tryGiveCommand (unit, commandType, pos,
- unit->getType (),
- CardinalDir (CardinalDir::NORTH));
- return result;
- }
- else
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- Command *
- cmd = new Command (commandType, pos);
- cmd->setUnitCommandGroupId (unitGroupCommandId);
- result =
- world->getFaction (factionIndex)->getUnit (unitIndex)->
- giveCommand (cmd);
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
- return result;
- }
- }
-
- std::pair < CommandResult,
- string > AiInterface::giveCommand (int unitIndex,
- const CommandType * commandType,
- const Vec2i & pos,
- const UnitType * ut)
- {
- assert (this->gameSettings != NULL);
-
- std::pair < CommandResult, string > result (crFailUndefined, "");
- const Unit *
- unit = getMyUnit (unitIndex);
- if (unit == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const UnitType *
- unitType = unit->getType ();
- if (unitType == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const CommandType *
- ct = unit->getType ()->findCommandTypeById (commandType->getId ());
- if (ct == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unit->getId (),
- unit->getFullName (false).c_str (),
- unit->getDesc (false).c_str (),
- unit->getFaction ()->getIndex ());
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem, "%s\n",
- szBuf);
-
- std::string worldLog = world->DumpWorldToLog ();
- std::string sError =
- "worldLog = " + worldLog + " " + string (szBuf);
- throw
- megaglest_runtime_error (sError);
- }
-
- if (executeCommandOverNetwork () == true)
- {
- const Unit *
- unit = getMyUnit (unitIndex);
- result =
- commander->tryGiveCommand (unit, commandType, pos, ut,
- CardinalDir (CardinalDir::NORTH));
- return result;
- }
- else
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- result =
- world->getFaction (factionIndex)->getUnit (unitIndex)->
- giveCommand (new
- Command (commandType, pos, ut,
- CardinalDir (CardinalDir::NORTH)));
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- return result;
- }
- }
-
- std::pair < CommandResult,
- string > AiInterface::giveCommand (int unitIndex,
- const CommandType * commandType,
- Unit * u)
- {
- assert (this->gameSettings != NULL);
- assert (this->commander != NULL);
-
- std::pair < CommandResult, string > result (crFailUndefined, "");
- const Unit *
- unit = getMyUnit (unitIndex);
- if (unit == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const UnitType *
- unitType = unit->getType ();
- if (unitType == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- factionIndex);
- throw
- megaglest_runtime_error (szBuf);
- }
- const CommandType *
- ct =
- (commandType !=
- NULL ? unit->getType ()->findCommandTypeById (commandType->
- getId ()) : NULL);
- if (ct == NULL)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
- __FILE__, __FUNCTION__, __LINE__, unit->getId (),
- unit->getFullName (false).c_str (),
- unit->getDesc (false).c_str (),
- unit->getFaction ()->getIndex ());
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem, "%s\n",
- szBuf);
-
- std::string worldLog = world->DumpWorldToLog ();
- std::string sError =
- "worldLog = " + worldLog + " " + string (szBuf);
- throw
- megaglest_runtime_error (sError);
- }
-
- if (executeCommandOverNetwork () == true)
- {
- Unit *
- targetUnit = u;
- const Unit *
- unit = getMyUnit (unitIndex);
-
- result =
- commander->tryGiveCommand (unit, commandType, Vec2i (0),
- unit->getType (),
- CardinalDir (CardinalDir::NORTH),
- false, targetUnit);
-
- return result;
- }
- else
- {
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- result =
- world->getFaction (factionIndex)->getUnit (unitIndex)->
- giveCommand (new Command (commandType, u));
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- return result;
- }
- }
-
-// ==================== get data ====================
-
- int
- AiInterface::getMapMaxPlayers ()
- {
- return world->getMaxPlayers ();
- }
-
- Vec2i
- AiInterface::getHomeLocation ()
- {
- return world->getMap ()->getStartLocation (world->
- getFaction (factionIndex)->
- getStartLocationIndex ());
- }
-
- Vec2i
- AiInterface::getStartLocation (int loactionIndex)
- {
- return world->getMap ()->getStartLocation (loactionIndex);
- }
-
- int
- AiInterface::getFactionCount ()
- {
- return world->getFactionCount ();
- }
-
- int
- AiInterface::getMyUnitCount () const
- {
- return
- world->
- getFaction (factionIndex)->
- getUnitCount ();
- }
-
- int
- AiInterface::getMyUpgradeCount () const
- {
- return
- world->
- getFaction (factionIndex)->
- getUpgradeManager ()->
- getUpgradeCount ();
- }
-
-//int AiInterface::onSightUnitCount() {
-// int count=0;
-// Map *map= world->getMap();
-// for(int i=0; igetFactionCount(); ++i) {
-// for(int j=0; jgetFaction(i)->getUnitCount(); ++j) {
-// Unit *unit = world->getFaction(i)->getUnit(j);
-// SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos()));
-// bool cannotSeeUnit = (unit->getType()->hasCellMap() == true &&
-// unit->getType()->getAllowEmptyCellMap() == true &&
-// unit->getType()->hasEmptyCellMap() == true);
-// if(sc->isVisible(teamIndex) && cannotSeeUnit == false) {
-// count++;
-// }
-// }
-// }
-// return count;
-//}
-
- const Resource *
- AiInterface::getResource (const ResourceType * rt)
- {
- return world->getFaction (factionIndex)->getResource (rt);
- }
-
- Unit *
- AiInterface::getMyUnitPtr (int unitIndex)
- {
- if (unitIndex < 0
- || unitIndex >= world->getFaction (factionIndex)->getUnitCount ())
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] unitIndex >= world->getFaction(factionIndex)->getUnitCount(), unitIndex = %d, world->getFaction(factionIndex)->getUnitCount() = %d",
- __FILE__, __FUNCTION__, __LINE__, unitIndex,
- world->getFaction (factionIndex)->getUnitCount ());
- throw
- megaglest_runtime_error (szBuf);
- }
-
- return world->getFaction (factionIndex)->getUnit (unitIndex);
- }
-
- const Unit *
- AiInterface::getMyUnit (int unitIndex)
- {
- return getMyUnitPtr (unitIndex);
- }
-
-//const Unit *AiInterface::getOnSightUnit(int unitIndex) {
-//
-// int count=0;
-// Map *map= world->getMap();
-//
-// for(int i=0; igetFactionCount(); ++i) {
-// for(int j=0; jgetFaction(i)->getUnitCount(); ++j) {
-// Unit * unit= world->getFaction(i)->getUnit(j);
-// SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos()));
-// bool cannotSeeUnit = (unit->getType()->hasCellMap() == true &&
-// unit->getType()->getAllowEmptyCellMap() == true &&
-// unit->getType()->hasEmptyCellMap() == true);
-//
-// if(sc->isVisible(teamIndex) && cannotSeeUnit == false) {
-// if(count==unitIndex) {
-// return unit;
-// }
-// else {
-// count ++;
-// }
-// }
-// }
-// }
-// return NULL;
-//}
-
- const FactionType *
- AiInterface::getMyFactionType ()
- {
- return world->getFaction (factionIndex)->getType ();
- }
-
- const ControlType
- AiInterface::getControlType ()
- {
- return world->getFaction (factionIndex)->getControlType ();
- }
-
- const TechTree *
- AiInterface::getTechTree ()
- {
- return world->getTechTree ();
- }
-
-
- bool
- AiInterface::isResourceInRegion (const Vec2i & pos,
- const ResourceType * rt,
- Vec2i & resourcePos, int range) const
- {
- const Map *
- map = world->getMap ();
-
- int
- xi = 1;
- int
- xj = 1;
-
- if (rand () % 2 == 1)
- {
- xi = -1;
- }
- if (rand () % 2 == 1)
- {
- xj = -1;
- }
- for (int i = -range; i <= range; ++i)
- {
- for (int j = -range; j <= range; ++j)
- {
- int
- ii = xi * i;
- int
- jj = xj * j;
- if (map->isInside (pos.x + ii, pos.y + jj))
- {
- Resource *
- r =
- map->getSurfaceCell (map->
- toSurfCoords (Vec2i
- (pos.x + ii,
- pos.y +
- jj)))->getResource ();
- if (r != NULL)
- {
- if (r->getType () == rt)
- {
- resourcePos = pos + Vec2i (ii, jj);
- return true;
- }
- }
- }
- }
- }
- return false;
- }
-
-
-
-//returns if there is a resource next to a unit, in "resourcePos" is stored the relative position of the resource
- bool
- AiInterface::isResourceNear (const Vec2i & pos, const ResourceType * rt,
- Vec2i & resourcePos, Faction * faction,
- bool fallbackToPeersHarvestingSameResource)
- const
- {
- const Map *
- map = world->getMap ();
- int
- size = 1;
- for (int i = -1; i <= size; ++i)
- {
- for (int j = -1; j <= size; ++j)
- {
- if (map->isInside (pos.x + i, pos.y + j))
- {
- Resource *
- r =
- map->getSurfaceCell (map->
- toSurfCoords (Vec2i
- (pos.x + i,
- pos.y +
- j)))->getResource ();
- if (r != NULL)
- {
- if (r->getType () == rt)
- {
- resourcePos = pos + Vec2i (i, j);
-
- return
- true;
- }
- }
- }
- }
- }
-
- if (fallbackToPeersHarvestingSameResource == true && faction != NULL)
- {
- // Look for another unit that is currently harvesting the same resource
- // type right now
-
- // Check the faction cache for a known position where we can harvest
- // this resource type
- Vec2i
- result = faction->getClosestResourceTypeTargetFromCache (pos, rt);
- if (result.x >= 0)
- {
- resourcePos = result;
-
- if (pos.dist (resourcePos) <= size)
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- bool
- AiInterface::getNearestSightedResource (const ResourceType * rt,
- const Vec2i & pos,
- Vec2i & resultPos,
- bool usableResourceTypeOnly)
- {
- Faction *
- faction = world->getFaction (factionIndex);
- //float tmpDist=0;
- float
- nearestDist = infinity;
- bool
- anyResource = false;
- resultPos.x = -1;
- resultPos.y = -1;
-
- bool
- canUseResourceType = (usableResourceTypeOnly == false);
- if (usableResourceTypeOnly == true)
- {
- // can any unit harvest this resource yet?
- std::map < const ResourceType *, int >::iterator
- iterFind = cacheUnitHarvestResourceLookup.find (rt);
-
- if (iterFind != cacheUnitHarvestResourceLookup.end () &&
- faction->findUnit (iterFind->second) != NULL)
- {
- canUseResourceType = true;
- }
- else
- {
- int
- unitCount = getMyUnitCount ();
- for (int i = 0; i < unitCount; ++i)
- {
- const Unit *
- unit = getMyUnit (i);
- const HarvestCommandType *
- hct =
- unit->getType ()->getFirstHarvestCommand (rt,
- unit->
- getFaction ());
- if (hct != NULL)
- {
- canUseResourceType = true;
- cacheUnitHarvestResourceLookup[rt] = unit->getId ();
- break;
- }
- }
- }
- }
-
- if (canUseResourceType == true)
- {
- bool
- isResourceClose =
- isResourceNear (pos, rt, resultPos, faction, true);
-
- // Found a resource
- if (isResourceClose == true || resultPos.x >= 0)
- {
- anyResource = true;
- }
- else
- {
- const Map *
- map = world->getMap ();
- for (int i = 0; i < map->getW (); ++i)
- {
- for (int j = 0; j < map->getH (); ++j)
- {
- Vec2i
- resPos = Vec2i (i, j);
- Vec2i
- surfPos = Map::toSurfCoords (resPos);
- SurfaceCell *
- sc = map->getSurfaceCell (surfPos);
-
- //if explored cell
- if (sc != NULL && sc->isExplored (teamIndex))
- {
- Resource *
- r = sc->getResource ();
-
- //if resource cell
- if (r != NULL)
- {
- if (r->getType () == rt)
- {
- float
- tmpDist = pos.dist (resPos);
- if (tmpDist < nearestDist)
- {
- anyResource = true;
- nearestDist = tmpDist;
- resultPos = resPos;
- }
- }
- }
- }
- }
- }
- }
- }
- return anyResource;
- }
-
- bool
- AiInterface::isAlly (const Unit * unit) const
- {
- return
- world->
- getFaction (factionIndex)->
- isAlly (unit->getFaction ());
- }
- bool
- AiInterface::reqsOk (const RequirableType * rt)
- {
- return world->getFaction (factionIndex)->reqsOk (rt);
- }
-
- bool
- AiInterface::reqsOk (const CommandType * ct)
- {
- return world->getFaction (factionIndex)->reqsOk (ct);
- }
-
- bool
- AiInterface::checkCosts (const ProducibleType * pt,
- const CommandType * ct)
- {
- return world->getFaction (factionIndex)->checkCosts (pt, ct);
- }
-
- bool
- AiInterface::isFreeCells (const Vec2i & pos, int size, Field field)
- {
- return world->getMap ()->isFreeCells (pos, size, field);
- }
-
- void
- AiInterface::removeEnemyWarningPositionFromList (Vec2i & checkPos)
- {
- for (int i = (int)enemyWarningPositionList.size () - 1; i >= 0; --i)
- {
- Vec2i & pos = enemyWarningPositionList[i];
-
- if (checkPos == pos)
- {
- enemyWarningPositionList.erase (enemyWarningPositionList.
- begin () + i);
- break;
- }
- }
- }
-
- const Unit *
- AiInterface::getFirstOnSightEnemyUnit (Vec2i & pos, Field & field,
- int radius)
- {
- Map *
- map = world->getMap ();
-
- const int
- CHECK_RADIUS = 12;
- const int
- WARNING_ENEMY_COUNT = 6;
-
- for (int i = 0; i < world->getFactionCount (); ++i)
- {
- for (int j = 0; j < world->getFaction (i)->getUnitCount (); ++j)
- {
- Unit *
- unit = world->getFaction (i)->getUnit (j);
- SurfaceCell *
- sc =
- map->getSurfaceCell (Map::toSurfCoords (unit->getPos ()));
- bool
- cannotSeeUnit = (unit->getType ()->hasCellMap () == true &&
- unit->getType ()->getAllowEmptyCellMap () ==
- true
- && unit->getType ()->hasEmptyCellMap () ==
- true);
-
- if (sc->isVisible (teamIndex) && cannotSeeUnit == false &&
- isAlly (unit) == false && unit->isAlive () == true)
- {
- pos = unit->getPos ();
- field = unit->getCurrField ();
- if (pos.dist (getHomeLocation ()) < radius)
- {
- printLog (2,
- "Being attacked at pos " + intToStr (pos.x) +
- "," + intToStr (pos.y) + "\n");
-
- // Now check if there are more than x enemies in sight and if
- // so make note of the position
- int
- foundEnemies = 0;
- std::map < int,
- bool >
- foundEnemyList;
- for (int aiX = pos.x - CHECK_RADIUS;
- aiX < pos.x + CHECK_RADIUS; ++aiX)
- {
- for (int aiY = pos.y - CHECK_RADIUS;
- aiY < pos.y + CHECK_RADIUS; ++aiY)
- {
- Vec2i
- checkPos (aiX, aiY);
- if (map->isInside (checkPos)
- && map->isInsideSurface (map->
- toSurfCoords
- (checkPos)))
- {
- Cell *
- cAI = map->getCell (checkPos);
- SurfaceCell *
- scAI =
- map->
- getSurfaceCell (Map::
- toSurfCoords (checkPos));
- if (scAI != NULL && cAI != NULL
- && cAI->getUnit (field) != NULL
- && sc->isVisible (teamIndex))
- {
- const Unit *
- checkUnit = cAI->getUnit (field);
- if (foundEnemyList.
- find (checkUnit->getId ()) ==
- foundEnemyList.end ())
- {
- bool
- cannotSeeUnitAI =
- (checkUnit->getType ()->
- hasCellMap () == true
- && checkUnit->getType ()->
- getAllowEmptyCellMap () == true
- && checkUnit->getType ()->
- hasEmptyCellMap () == true);
- if (cannotSeeUnitAI == false
- && isAlly (checkUnit) == false
- && checkUnit->isAlive () ==
- true)
- {
- foundEnemies++;
- foundEnemyList[checkUnit->
- getId ()] = true;
- }
- }
- }
- }
- }
- }
- if (foundEnemies >= WARNING_ENEMY_COUNT)
- {
- if (std::
- find (enemyWarningPositionList.begin (),
- enemyWarningPositionList.end (),
- pos) == enemyWarningPositionList.end ())
- {
- enemyWarningPositionList.push_back (pos);
- }
- }
- return unit;
- }
- }
- }
- }
- return NULL;
- }
-
- Map *
- AiInterface::getMap ()
- {
- Map *
- map = world->getMap ();
- return map;
- }
-
- bool
- AiInterface::factionUsesResourceType (const FactionType * factionType,
- const ResourceType * rt)
- {
- bool
- factionUsesResourceType = factionType->factionUsesResourceType (rt);
- return factionUsesResourceType;
- }
-
- void
- AiInterface::saveGame (XmlNode * rootNode) const
- {
- std::map <
- string,
- string >
- mapTagReplacements;
- XmlNode *
- aiInterfaceNode = rootNode->addChild ("AiInterface");
-
-// World *world;
-// Commander *commander;
-// Console *console;
-// GameSettings *gameSettings;
-//
-// Ai ai;
- ai.
- saveGame (aiInterfaceNode);
-// int timer;
- aiInterfaceNode->
- addAttribute ("timer", intToStr (timer), mapTagReplacements);
-// int factionIndex;
- aiInterfaceNode->
- addAttribute ("factionIndex", intToStr (factionIndex),
- mapTagReplacements);
-// int teamIndex;
- aiInterfaceNode->
- addAttribute ("teamIndex", intToStr (teamIndex), mapTagReplacements);
-// //config
-// bool redir;
- aiInterfaceNode->
- addAttribute ("redir", intToStr (redir), mapTagReplacements);
-// int logLevel;
- aiInterfaceNode->
- addAttribute ("logLevel", intToStr (logLevel), mapTagReplacements);
-// std::map cacheUnitHarvestResourceLookup;
- for (std::map < const ResourceType *, int >::const_iterator iterMap =
- cacheUnitHarvestResourceLookup.begin ();
- iterMap != cacheUnitHarvestResourceLookup.end (); ++iterMap)
- {
- XmlNode *
- cacheUnitHarvestResourceLookupNode =
- aiInterfaceNode->addChild ("cacheUnitHarvestResourceLookup");
-
- cacheUnitHarvestResourceLookupNode->
- addAttribute ("key", iterMap->first->getName (),
- mapTagReplacements);
- cacheUnitHarvestResourceLookupNode->
- addAttribute ("value", intToStr (iterMap->second),
- mapTagReplacements);
- }
- }
-
-// AiInterface::AiInterface(Game &game, int factionIndex, int teamIndex, int useStartLocation) {
- void
- AiInterface::loadGame (const XmlNode * rootNode, Faction * faction)
- {
- XmlNode *
- aiInterfaceNode = NULL;
- vector < XmlNode * >aiInterfaceNodeList =
- rootNode->getChildList ("AiInterface");
- for (unsigned int i = 0; i < aiInterfaceNodeList.size (); ++i)
- {
- XmlNode *
- node = aiInterfaceNodeList[i];
- if (node->getAttribute ("factionIndex")->getIntValue () ==
- faction->getIndex ())
- {
- aiInterfaceNode = node;
- break;
- }
- }
-
- if (aiInterfaceNode != NULL)
- {
- factionIndex =
- aiInterfaceNode->getAttribute ("factionIndex")->getIntValue ();
- teamIndex =
- aiInterfaceNode->getAttribute ("teamIndex")->getIntValue ();
-
- ai.loadGame (aiInterfaceNode, faction);
- //firstTime = timeflowNode->getAttribute("firstTime")->getFloatValue();
-
- timer = aiInterfaceNode->getAttribute ("timer")->getIntValue ();
- // int factionIndex;
- //factionIndex = aiInterfaceNode->getAttribute("factionIndex")->getIntValue();
- // int teamIndex;
- //teamIndex = aiInterfaceNode->getAttribute("teamIndex")->getIntValue();
- // //config
- // bool redir;
- redir =
- aiInterfaceNode->getAttribute ("redir")->getIntValue () != 0;
- // int logLevel;
- logLevel =
- aiInterfaceNode->getAttribute ("logLevel")->getIntValue ();
-
- // std::map cacheUnitHarvestResourceLookup;
- // for(std::map::const_iterator iterMap = cacheUnitHarvestResourceLookup.begin();
- // iterMap != cacheUnitHarvestResourceLookup.end(); ++iterMap) {
- // XmlNode *cacheUnitHarvestResourceLookupNode = aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup");
- //
- // cacheUnitHarvestResourceLookupNode->addAttribute("key",iterMap->first->getName(), mapTagReplacements);
- // cacheUnitHarvestResourceLookupNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements);
- // }
- }
- }
-
- }
+ if (fp == NULL) {
+ throw
+ megaglest_runtime_error("Can't open file: [" + aiLogFile +
+ "]");
+ }
+ fprintf(fp,
+ "ZetaGlest AI log file for Tech [%s] Faction [%s] #%d\n\n",
+ this->gameSettings->getTech().c_str(),
+ this->world->getFaction(this->factionIndex)->getType()->
+ getName().c_str(), this->factionIndex);
+ }
+
+
+ if (Config::getInstance().getBool("EnableAIWorkerThreads", "true") ==
+ true) {
+ if (workerThread != NULL) {
+ workerThread->signalQuit();
+ if (workerThread->shutdownAndWait() == true) {
+ delete
+ workerThread;
+ }
+ workerThread = NULL;
+ }
+ static string
+ mutexOwnerId =
+ string(extractFileFromDirectoryPath(__FILE__).c_str()) +
+ string("_") + intToStr(__LINE__);
+ this->workerThread = new AiInterfaceThread(this);
+ this->workerThread->setUniqueID(mutexOwnerId);
+ this->workerThread->start();
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ }
+
+ void
+ AiInterface::init() {
+ world = NULL;;
+ commander = NULL;;
+ console = NULL;;
+ gameSettings = NULL;;
+ timer = 0;
+ factionIndex = 0;
+ teamIndex = 0;
+ redir = false;
+ logLevel = 0;
+ fp = NULL;;
+ aiMutex = NULL;
+ workerThread = NULL;
+ }
+
+ AiInterface::~AiInterface() {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] deleting AI factionIndex = %d, teamIndex = %d\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ this->factionIndex, this->teamIndex);
+ cacheUnitHarvestResourceLookup.clear();
+
+ if (workerThread != NULL) {
+ workerThread->signalQuit();
+ sleep(0);
+ if (workerThread->canShutdown(true) == true &&
+ workerThread->shutdownAndWait() == true) {
+ delete
+ workerThread;
+ }
+ workerThread = NULL;
+ }
+
+ if (fp) {
+ fclose(fp);
+ fp = NULL;
+ }
+
+ delete
+ aiMutex;
+ aiMutex = NULL;
+ }
+
+ void
+ AiInterface::signalWorkerThread(int frameIndex) {
+ if (workerThread != NULL) {
+ workerThread->signal(frameIndex);
+ } else {
+ this->update();
+ }
+ }
+
+ bool
+ AiInterface::isWorkerThreadSignalCompleted(int frameIndex) {
+ if (workerThread != NULL) {
+ return workerThread->isSignalCompleted(frameIndex);
+ }
+ return true;
+ }
+
+ // ==================== main ====================
+
+ void
+ AiInterface::update() {
+ timer++;
+ ai.update();
+ }
+
+ // ==================== misc ====================
+
+ bool
+ AiInterface::isLogLevelEnabled(int level) {
+ return (this->logLevel >= level);
+ }
+
+ void
+ AiInterface::printLog(int logLevel, const string & s) {
+ if (isLogLevelEnabled(logLevel) == true) {
+ string
+ logString = "(" + intToStr(factionIndex) + ") " + s;
+
+ MutexSafeWrapper
+ safeMutex(aiMutex, string(__FILE__) + "_" + intToStr(__LINE__));
+ //print log to file
+ if (fp != NULL) {
+ fprintf(fp, "%s\n", logString.c_str());
+ }
+
+ //redirect to console
+ if (redir) {
+ console->addLine(logString);
+ }
+ }
+ }
+
+ // ==================== interaction ====================
+
+ Faction *
+ AiInterface::getMyFaction() {
+ return world->getFaction(factionIndex);
+ }
+
+ bool
+ AiInterface::executeCommandOverNetwork() {
+ bool
+ enableServerControlledAI =
+ gameSettings->getEnableServerControlledAI();
+ bool
+ isNetworkGame = gameSettings->isNetworkGame();
+ NetworkRole
+ role = NetworkManager::getInstance().getNetworkRole();
+ Faction *
+ faction = world->getFaction(factionIndex);
+ return faction->getCpuControl(enableServerControlledAI, isNetworkGame,
+ role);
+ }
+
+ std::pair < CommandResult,
+ string >
+ AiInterface::giveCommandSwitchTeamVote(const Faction * faction,
+ SwitchTeamVote * vote) {
+ assert(this->gameSettings != NULL);
+
+ commander->trySwitchTeamVote(faction, vote);
+ return std::pair < CommandResult, string >(crSuccess, "");
+ }
+
+ std::pair < CommandResult,
+ string > AiInterface::giveCommand(int unitIndex,
+ CommandClass commandClass,
+ const Vec2i & pos) {
+ assert(this->gameSettings != NULL);
+
+ std::pair < CommandResult, string > result(crFailUndefined, "");
+ if (executeCommandOverNetwork() == true) {
+ const Unit *
+ unit = getMyUnit(unitIndex);
+ result =
+ commander->tryGiveCommand(unit,
+ unit->getType()->
+ getFirstCtOfClass(commandClass), pos,
+ unit->getType(),
+ CardinalDir(CardinalDir::NORTH));
+ return result;
+ } else {
+ Command *
+ c =
+ new Command(world->getFaction(factionIndex)->
+ getUnit(unitIndex)->getType()->
+ getFirstCtOfClass(commandClass), pos);
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ result =
+ world->getFaction(factionIndex)->getUnit(unitIndex)->
+ giveCommand(c);
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ return result;
+ }
+ }
+
+ std::pair < CommandResult,
+ string > AiInterface::giveCommand(const Unit * unit,
+ const CommandType * commandType,
+ const Vec2i & pos,
+ int unitGroupCommandId) {
+ assert(this->gameSettings != NULL);
+
+ std::pair < CommandResult, string > result(crFailUndefined, "");
+ if (unit == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unit in AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const UnitType *
+ unitType = unit->getType();
+ if (unitType == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unittype with unit id: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unit->getId(),
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ if (commandType == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] commandType == NULL, unit id: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unit->getId(),
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const CommandType *
+ ct = unit->getType()->findCommandTypeById(commandType->getId());
+ if (ct == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unit->getId(),
+ unit->getFullName(false).c_str(),
+ unit->getDesc(false).c_str(),
+ unit->getFaction()->getIndex());
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n",
+ szBuf);
+
+ std::string worldLog = world->DumpWorldToLog();
+ std::string sError =
+ "worldLog = " + worldLog + " " + string(szBuf);
+ throw
+ megaglest_runtime_error(sError);
+ }
+
+ if (executeCommandOverNetwork() == true) {
+ result = commander->tryGiveCommand(unit, commandType, pos,
+ unit->getType(),
+ CardinalDir(CardinalDir::
+ NORTH), false,
+ NULL, unitGroupCommandId);
+ return result;
+ } else {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ Faction *
+ faction = world->getFaction(unit->getFactionIndex());
+ Unit *
+ unitToCommand = faction->findUnit(unit->getId());
+ Command *
+ cmd = new Command(commandType, pos);
+ cmd->setUnitCommandGroupId(unitGroupCommandId);
+ result = unitToCommand->giveCommand(cmd);
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ return result;
+ }
+ }
+
+ std::pair < CommandResult,
+ string > AiInterface::giveCommand(int unitIndex,
+ const CommandType * commandType,
+ const Vec2i & pos,
+ int unitGroupCommandId) {
+ assert(this->gameSettings != NULL);
+
+ std::pair < CommandResult, string > result(crFailUndefined, "");
+ const Unit *
+ unit = getMyUnit(unitIndex);
+ if (unit == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const UnitType *
+ unitType = unit->getType();
+ if (unitType == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const CommandType *
+ ct = unit->getType()->findCommandTypeById(commandType->getId());
+ if (ct == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unit->getId(),
+ unit->getFullName(false).c_str(),
+ unit->getDesc(false).c_str(),
+ unit->getFaction()->getIndex());
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n",
+ szBuf);
+
+ std::string worldLog = world->DumpWorldToLog();
+ std::string sError =
+ "worldLog = " + worldLog + " " + string(szBuf);
+ throw
+ megaglest_runtime_error(sError);
+ }
+
+ if (executeCommandOverNetwork() == true) {
+ const Unit *
+ unit = getMyUnit(unitIndex);
+ result =
+ commander->tryGiveCommand(unit, commandType, pos,
+ unit->getType(),
+ CardinalDir(CardinalDir::NORTH));
+ return result;
+ } else {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ Command *
+ cmd = new Command(commandType, pos);
+ cmd->setUnitCommandGroupId(unitGroupCommandId);
+ result =
+ world->getFaction(factionIndex)->getUnit(unitIndex)->
+ giveCommand(cmd);
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ return result;
+ }
+ }
+
+ std::pair < CommandResult,
+ string > AiInterface::giveCommand(int unitIndex,
+ const CommandType * commandType,
+ const Vec2i & pos,
+ const UnitType * ut) {
+ assert(this->gameSettings != NULL);
+
+ std::pair < CommandResult, string > result(crFailUndefined, "");
+ const Unit *
+ unit = getMyUnit(unitIndex);
+ if (unit == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const UnitType *
+ unitType = unit->getType();
+ if (unitType == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const CommandType *
+ ct = unit->getType()->findCommandTypeById(commandType->getId());
+ if (ct == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unit->getId(),
+ unit->getFullName(false).c_str(),
+ unit->getDesc(false).c_str(),
+ unit->getFaction()->getIndex());
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n",
+ szBuf);
+
+ std::string worldLog = world->DumpWorldToLog();
+ std::string sError =
+ "worldLog = " + worldLog + " " + string(szBuf);
+ throw
+ megaglest_runtime_error(sError);
+ }
+
+ if (executeCommandOverNetwork() == true) {
+ const Unit *
+ unit = getMyUnit(unitIndex);
+ result =
+ commander->tryGiveCommand(unit, commandType, pos, ut,
+ CardinalDir(CardinalDir::NORTH));
+ return result;
+ } else {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ result =
+ world->getFaction(factionIndex)->getUnit(unitIndex)->
+ giveCommand(new
+ Command(commandType, pos, ut,
+ CardinalDir(CardinalDir::NORTH)));
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ return result;
+ }
+ }
+
+ std::pair < CommandResult,
+ string > AiInterface::giveCommand(int unitIndex,
+ const CommandType * commandType,
+ Unit * u) {
+ assert(this->gameSettings != NULL);
+ assert(this->commander != NULL);
+
+ std::pair < CommandResult, string > result(crFailUndefined, "");
+ const Unit *
+ unit = getMyUnit(unitIndex);
+ if (unit == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unit with index: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const UnitType *
+ unitType = unit->getType();
+ if (unitType == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] Can not find AI unittype with unit index: %d, AI factionIndex = %d. Game out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ factionIndex);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ const CommandType *
+ ct =
+ (commandType !=
+ NULL ? unit->getType()->findCommandTypeById(commandType->
+ getId()) : NULL);
+ if (ct == NULL) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d]\nCan not find AI command type for:\nunit = %d\n[%s]\n[%s]\nactual local factionIndex = %d.\nGame out of synch.",
+ __FILE__, __FUNCTION__, __LINE__, unit->getId(),
+ unit->getFullName(false).c_str(),
+ unit->getDesc(false).c_str(),
+ unit->getFaction()->getIndex());
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem, "%s\n",
+ szBuf);
+
+ std::string worldLog = world->DumpWorldToLog();
+ std::string sError =
+ "worldLog = " + worldLog + " " + string(szBuf);
+ throw
+ megaglest_runtime_error(sError);
+ }
+
+ if (executeCommandOverNetwork() == true) {
+ Unit *
+ targetUnit = u;
+ const Unit *
+ unit = getMyUnit(unitIndex);
+
+ result =
+ commander->tryGiveCommand(unit, commandType, Vec2i(0),
+ unit->getType(),
+ CardinalDir(CardinalDir::NORTH),
+ false, targetUnit);
+
+ return result;
+ } else {
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ result =
+ world->getFaction(factionIndex)->getUnit(unitIndex)->
+ giveCommand(new Command(commandType, u));
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ return result;
+ }
+ }
+
+ // ==================== get data ====================
+
+ int
+ AiInterface::getMapMaxPlayers() {
+ return world->getMaxPlayers();
+ }
+
+ Vec2i
+ AiInterface::getHomeLocation() {
+ return world->getMap()->getStartLocation(world->
+ getFaction(factionIndex)->
+ getStartLocationIndex());
+ }
+
+ Vec2i
+ AiInterface::getStartLocation(int loactionIndex) {
+ return world->getMap()->getStartLocation(loactionIndex);
+ }
+
+ int
+ AiInterface::getFactionCount() {
+ return world->getFactionCount();
+ }
+
+ int
+ AiInterface::getMyUnitCount() const {
+ return
+ world->
+ getFaction(factionIndex)->
+ getUnitCount();
+ }
+
+ int
+ AiInterface::getMyUpgradeCount() const {
+ return
+ world->
+ getFaction(factionIndex)->
+ getUpgradeManager()->
+ getUpgradeCount();
+ }
+
+ //int AiInterface::onSightUnitCount() {
+ // int count=0;
+ // Map *map= world->getMap();
+ // for(int i=0; igetFactionCount(); ++i) {
+ // for(int j=0; jgetFaction(i)->getUnitCount(); ++j) {
+ // Unit *unit = world->getFaction(i)->getUnit(j);
+ // SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos()));
+ // bool cannotSeeUnit = (unit->getType()->hasCellMap() == true &&
+ // unit->getType()->getAllowEmptyCellMap() == true &&
+ // unit->getType()->hasEmptyCellMap() == true);
+ // if(sc->isVisible(teamIndex) && cannotSeeUnit == false) {
+ // count++;
+ // }
+ // }
+ // }
+ // return count;
+ //}
+
+ const Resource *
+ AiInterface::getResource(const ResourceType * rt) {
+ return world->getFaction(factionIndex)->getResource(rt);
+ }
+
+ Unit *
+ AiInterface::getMyUnitPtr(int unitIndex) {
+ if (unitIndex < 0
+ || unitIndex >= world->getFaction(factionIndex)->getUnitCount()) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] unitIndex >= world->getFaction(factionIndex)->getUnitCount(), unitIndex = %d, world->getFaction(factionIndex)->getUnitCount() = %d",
+ __FILE__, __FUNCTION__, __LINE__, unitIndex,
+ world->getFaction(factionIndex)->getUnitCount());
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ return world->getFaction(factionIndex)->getUnit(unitIndex);
+ }
+
+ const Unit *
+ AiInterface::getMyUnit(int unitIndex) {
+ return getMyUnitPtr(unitIndex);
+ }
+
+ //const Unit *AiInterface::getOnSightUnit(int unitIndex) {
+ //
+ // int count=0;
+ // Map *map= world->getMap();
+ //
+ // for(int i=0; igetFactionCount(); ++i) {
+ // for(int j=0; jgetFaction(i)->getUnitCount(); ++j) {
+ // Unit * unit= world->getFaction(i)->getUnit(j);
+ // SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getPos()));
+ // bool cannotSeeUnit = (unit->getType()->hasCellMap() == true &&
+ // unit->getType()->getAllowEmptyCellMap() == true &&
+ // unit->getType()->hasEmptyCellMap() == true);
+ //
+ // if(sc->isVisible(teamIndex) && cannotSeeUnit == false) {
+ // if(count==unitIndex) {
+ // return unit;
+ // }
+ // else {
+ // count ++;
+ // }
+ // }
+ // }
+ // }
+ // return NULL;
+ //}
+
+ const FactionType *
+ AiInterface::getMyFactionType() {
+ return world->getFaction(factionIndex)->getType();
+ }
+
+ const ControlType
+ AiInterface::getControlType() {
+ return world->getFaction(factionIndex)->getControlType();
+ }
+
+ const TechTree *
+ AiInterface::getTechTree() {
+ return world->getTechTree();
+ }
+
+
+ bool
+ AiInterface::isResourceInRegion(const Vec2i & pos,
+ const ResourceType * rt,
+ Vec2i & resourcePos, int range) const {
+ const Map *
+ map = world->getMap();
+
+ int
+ xi = 1;
+ int
+ xj = 1;
+
+ if (rand() % 2 == 1) {
+ xi = -1;
+ }
+ if (rand() % 2 == 1) {
+ xj = -1;
+ }
+ for (int i = -range; i <= range; ++i) {
+ for (int j = -range; j <= range; ++j) {
+ int
+ ii = xi * i;
+ int
+ jj = xj * j;
+ if (map->isInside(pos.x + ii, pos.y + jj)) {
+ Resource *
+ r =
+ map->getSurfaceCell(map->
+ toSurfCoords(Vec2i
+ (pos.x + ii,
+ pos.y +
+ jj)))->getResource();
+ if (r != NULL) {
+ if (r->getType() == rt) {
+ resourcePos = pos + Vec2i(ii, jj);
+ return true;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+
+
+ //returns if there is a resource next to a unit, in "resourcePos" is stored the relative position of the resource
+ bool
+ AiInterface::isResourceNear(const Vec2i & pos, const ResourceType * rt,
+ Vec2i & resourcePos, Faction * faction,
+ bool fallbackToPeersHarvestingSameResource)
+ const {
+ const Map *
+ map = world->getMap();
+ int
+ size = 1;
+ for (int i = -1; i <= size; ++i) {
+ for (int j = -1; j <= size; ++j) {
+ if (map->isInside(pos.x + i, pos.y + j)) {
+ Resource *
+ r =
+ map->getSurfaceCell(map->
+ toSurfCoords(Vec2i
+ (pos.x + i,
+ pos.y +
+ j)))->getResource();
+ if (r != NULL) {
+ if (r->getType() == rt) {
+ resourcePos = pos + Vec2i(i, j);
+
+ return
+ true;
+ }
+ }
+ }
+ }
+ }
+
+ if (fallbackToPeersHarvestingSameResource == true && faction != NULL) {
+ // Look for another unit that is currently harvesting the same resource
+ // type right now
+
+ // Check the faction cache for a known position where we can harvest
+ // this resource type
+ Vec2i
+ result = faction->getClosestResourceTypeTargetFromCache(pos, rt);
+ if (result.x >= 0) {
+ resourcePos = result;
+
+ if (pos.dist(resourcePos) <= size) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ bool
+ AiInterface::getNearestSightedResource(const ResourceType * rt,
+ const Vec2i & pos,
+ Vec2i & resultPos,
+ bool usableResourceTypeOnly) {
+ Faction *
+ faction = world->getFaction(factionIndex);
+ //float tmpDist=0;
+ float
+ nearestDist = infinity;
+ bool
+ anyResource = false;
+ resultPos.x = -1;
+ resultPos.y = -1;
+
+ bool
+ canUseResourceType = (usableResourceTypeOnly == false);
+ if (usableResourceTypeOnly == true) {
+ // can any unit harvest this resource yet?
+ std::map < const ResourceType *, int >::iterator
+ iterFind = cacheUnitHarvestResourceLookup.find(rt);
+
+ if (iterFind != cacheUnitHarvestResourceLookup.end() &&
+ faction->findUnit(iterFind->second) != NULL) {
+ canUseResourceType = true;
+ } else {
+ int
+ unitCount = getMyUnitCount();
+ for (int i = 0; i < unitCount; ++i) {
+ const Unit *
+ unit = getMyUnit(i);
+ const HarvestCommandType *
+ hct =
+ unit->getType()->getFirstHarvestCommand(rt,
+ unit->
+ getFaction());
+ if (hct != NULL) {
+ canUseResourceType = true;
+ cacheUnitHarvestResourceLookup[rt] = unit->getId();
+ break;
+ }
+ }
+ }
+ }
+
+ if (canUseResourceType == true) {
+ bool
+ isResourceClose =
+ isResourceNear(pos, rt, resultPos, faction, true);
+
+ // Found a resource
+ if (isResourceClose == true || resultPos.x >= 0) {
+ anyResource = true;
+ } else {
+ const Map *
+ map = world->getMap();
+ for (int i = 0; i < map->getW(); ++i) {
+ for (int j = 0; j < map->getH(); ++j) {
+ Vec2i
+ resPos = Vec2i(i, j);
+ Vec2i
+ surfPos = Map::toSurfCoords(resPos);
+ SurfaceCell *
+ sc = map->getSurfaceCell(surfPos);
+
+ //if explored cell
+ if (sc != NULL && sc->isExplored(teamIndex)) {
+ Resource *
+ r = sc->getResource();
+
+ //if resource cell
+ if (r != NULL) {
+ if (r->getType() == rt) {
+ float
+ tmpDist = pos.dist(resPos);
+ if (tmpDist < nearestDist) {
+ anyResource = true;
+ nearestDist = tmpDist;
+ resultPos = resPos;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return anyResource;
+ }
+
+ bool
+ AiInterface::isAlly(const Unit * unit) const {
+ return
+ world->
+ getFaction(factionIndex)->
+ isAlly(unit->getFaction());
+ }
+ bool
+ AiInterface::reqsOk(const RequirableType * rt) {
+ return world->getFaction(factionIndex)->reqsOk(rt);
+ }
+
+ bool
+ AiInterface::reqsOk(const CommandType * ct) {
+ return world->getFaction(factionIndex)->reqsOk(ct);
+ }
+
+ bool
+ AiInterface::checkCosts(const ProducibleType * pt,
+ const CommandType * ct) {
+ return world->getFaction(factionIndex)->checkCosts(pt, ct);
+ }
+
+ bool
+ AiInterface::isFreeCells(const Vec2i & pos, int size, Field field) {
+ return world->getMap()->isFreeCells(pos, size, field);
+ }
+
+ void
+ AiInterface::removeEnemyWarningPositionFromList(Vec2i & checkPos) {
+ for (int i = (int) enemyWarningPositionList.size() - 1; i >= 0; --i) {
+ Vec2i & pos = enemyWarningPositionList[i];
+
+ if (checkPos == pos) {
+ enemyWarningPositionList.erase(enemyWarningPositionList.
+ begin() + i);
+ break;
+ }
+ }
+ }
+
+ const Unit *
+ AiInterface::getFirstOnSightEnemyUnit(Vec2i & pos, Field & field,
+ int radius) {
+ Map *
+ map = world->getMap();
+
+ const int
+ CHECK_RADIUS = 12;
+ const int
+ WARNING_ENEMY_COUNT = 6;
+
+ for (int i = 0; i < world->getFactionCount(); ++i) {
+ for (int j = 0; j < world->getFaction(i)->getUnitCount(); ++j) {
+ Unit *
+ unit = world->getFaction(i)->getUnit(j);
+ SurfaceCell *
+ sc =
+ map->getSurfaceCell(Map::toSurfCoords(unit->getPos()));
+ bool
+ cannotSeeUnit = (unit->getType()->hasCellMap() == true &&
+ unit->getType()->getAllowEmptyCellMap() ==
+ true
+ && unit->getType()->hasEmptyCellMap() ==
+ true);
+
+ if (sc->isVisible(teamIndex) && cannotSeeUnit == false &&
+ isAlly(unit) == false && unit->isAlive() == true) {
+ pos = unit->getPos();
+ field = unit->getCurrField();
+ if (pos.dist(getHomeLocation()) < radius) {
+ printLog(2,
+ "Being attacked at pos " + intToStr(pos.x) +
+ "," + intToStr(pos.y) + "\n");
+
+ // Now check if there are more than x enemies in sight and if
+ // so make note of the position
+ int
+ foundEnemies = 0;
+ std::map < int,
+ bool >
+ foundEnemyList;
+ for (int aiX = pos.x - CHECK_RADIUS;
+ aiX < pos.x + CHECK_RADIUS; ++aiX) {
+ for (int aiY = pos.y - CHECK_RADIUS;
+ aiY < pos.y + CHECK_RADIUS; ++aiY) {
+ Vec2i
+ checkPos(aiX, aiY);
+ if (map->isInside(checkPos)
+ && map->isInsideSurface(map->
+ toSurfCoords
+ (checkPos))) {
+ Cell *
+ cAI = map->getCell(checkPos);
+ SurfaceCell *
+ scAI =
+ map->
+ getSurfaceCell(Map::
+ toSurfCoords(checkPos));
+ if (scAI != NULL && cAI != NULL
+ && cAI->getUnit(field) != NULL
+ && sc->isVisible(teamIndex)) {
+ const Unit *
+ checkUnit = cAI->getUnit(field);
+ if (foundEnemyList.
+ find(checkUnit->getId()) ==
+ foundEnemyList.end()) {
+ bool
+ cannotSeeUnitAI =
+ (checkUnit->getType()->
+ hasCellMap() == true
+ && checkUnit->getType()->
+ getAllowEmptyCellMap() == true
+ && checkUnit->getType()->
+ hasEmptyCellMap() == true);
+ if (cannotSeeUnitAI == false
+ && isAlly(checkUnit) == false
+ && checkUnit->isAlive() ==
+ true) {
+ foundEnemies++;
+ foundEnemyList[checkUnit->
+ getId()] = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ if (foundEnemies >= WARNING_ENEMY_COUNT) {
+ if (std::
+ find(enemyWarningPositionList.begin(),
+ enemyWarningPositionList.end(),
+ pos) == enemyWarningPositionList.end()) {
+ enemyWarningPositionList.push_back(pos);
+ }
+ }
+ return unit;
+ }
+ }
+ }
+ }
+ return NULL;
+ }
+
+ Map *
+ AiInterface::getMap() {
+ Map *
+ map = world->getMap();
+ return map;
+ }
+
+ bool
+ AiInterface::factionUsesResourceType(const FactionType * factionType,
+ const ResourceType * rt) {
+ bool
+ factionUsesResourceType = factionType->factionUsesResourceType(rt);
+ return factionUsesResourceType;
+ }
+
+ void
+ AiInterface::saveGame(XmlNode * rootNode) const {
+ std::map <
+ string,
+ string >
+ mapTagReplacements;
+ XmlNode *
+ aiInterfaceNode = rootNode->addChild("AiInterface");
+
+ // World *world;
+ // Commander *commander;
+ // Console *console;
+ // GameSettings *gameSettings;
+ //
+ // Ai ai;
+ ai.
+ saveGame(aiInterfaceNode);
+ // int timer;
+ aiInterfaceNode->
+ addAttribute("timer", intToStr(timer), mapTagReplacements);
+ // int factionIndex;
+ aiInterfaceNode->
+ addAttribute("factionIndex", intToStr(factionIndex),
+ mapTagReplacements);
+ // int teamIndex;
+ aiInterfaceNode->
+ addAttribute("teamIndex", intToStr(teamIndex), mapTagReplacements);
+ // //config
+ // bool redir;
+ aiInterfaceNode->
+ addAttribute("redir", intToStr(redir), mapTagReplacements);
+ // int logLevel;
+ aiInterfaceNode->
+ addAttribute("logLevel", intToStr(logLevel), mapTagReplacements);
+ // std::map cacheUnitHarvestResourceLookup;
+ for (std::map < const ResourceType *, int >::const_iterator iterMap =
+ cacheUnitHarvestResourceLookup.begin();
+ iterMap != cacheUnitHarvestResourceLookup.end(); ++iterMap) {
+ XmlNode *
+ cacheUnitHarvestResourceLookupNode =
+ aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup");
+
+ cacheUnitHarvestResourceLookupNode->
+ addAttribute("key", iterMap->first->getName(),
+ mapTagReplacements);
+ cacheUnitHarvestResourceLookupNode->
+ addAttribute("value", intToStr(iterMap->second),
+ mapTagReplacements);
+ }
+ }
+
+ // AiInterface::AiInterface(Game &game, int factionIndex, int teamIndex, int useStartLocation) {
+ void
+ AiInterface::loadGame(const XmlNode * rootNode, Faction * faction) {
+ XmlNode *
+ aiInterfaceNode = NULL;
+ vector < XmlNode * >aiInterfaceNodeList =
+ rootNode->getChildList("AiInterface");
+ for (unsigned int i = 0; i < aiInterfaceNodeList.size(); ++i) {
+ XmlNode *
+ node = aiInterfaceNodeList[i];
+ if (node->getAttribute("factionIndex")->getIntValue() ==
+ faction->getIndex()) {
+ aiInterfaceNode = node;
+ break;
+ }
+ }
+
+ if (aiInterfaceNode != NULL) {
+ factionIndex =
+ aiInterfaceNode->getAttribute("factionIndex")->getIntValue();
+ teamIndex =
+ aiInterfaceNode->getAttribute("teamIndex")->getIntValue();
+
+ ai.loadGame(aiInterfaceNode, faction);
+ //firstTime = timeflowNode->getAttribute("firstTime")->getFloatValue();
+
+ timer = aiInterfaceNode->getAttribute("timer")->getIntValue();
+ // int factionIndex;
+ //factionIndex = aiInterfaceNode->getAttribute("factionIndex")->getIntValue();
+ // int teamIndex;
+ //teamIndex = aiInterfaceNode->getAttribute("teamIndex")->getIntValue();
+ // //config
+ // bool redir;
+ redir =
+ aiInterfaceNode->getAttribute("redir")->getIntValue() != 0;
+ // int logLevel;
+ logLevel =
+ aiInterfaceNode->getAttribute("logLevel")->getIntValue();
+
+ // std::map cacheUnitHarvestResourceLookup;
+ // for(std::map::const_iterator iterMap = cacheUnitHarvestResourceLookup.begin();
+ // iterMap != cacheUnitHarvestResourceLookup.end(); ++iterMap) {
+ // XmlNode *cacheUnitHarvestResourceLookupNode = aiInterfaceNode->addChild("cacheUnitHarvestResourceLookup");
+ //
+ // cacheUnitHarvestResourceLookupNode->addAttribute("key",iterMap->first->getName(), mapTagReplacements);
+ // cacheUnitHarvestResourceLookupNode->addAttribute("value",intToStr(iterMap->second), mapTagReplacements);
+ // }
+ }
+ }
+
+ }
} //end namespace
diff --git a/source/glest_game/ai/ai_interface.h b/source/glest_game/ai/ai_interface.h
index f37cb20d4..4639ed31b 100644
--- a/source/glest_game/ai/ai_interface.h
+++ b/source/glest_game/ai/ai_interface.h
@@ -33,309 +33,295 @@
# include "leak_dumper.h"
using
- Shared::Util::intToStr;
+Shared::Util::intToStr;
namespace
- Glest
-{
- namespace
- Game
- {
+ Glest {
+ namespace
+ Game {
-// =====================================================
-// class AiInterface
-//
-/// The AI will interact with the game through this interface
-// =====================================================
+ // =====================================================
+ // class AiInterface
+ //
+ /// The AI will interact with the game through this interface
+ // =====================================================
- class
- AiInterfaceThread:
- public
- BaseThread,
- public
- SlaveThreadControllerInterface
- {
- protected:
+ class
+ AiInterfaceThread :
+ public
+ BaseThread,
+ public
+ SlaveThreadControllerInterface {
+ protected:
- AiInterface *
- aiIntf;
- Semaphore
- semTaskSignalled;
- Mutex *
- triggerIdMutex;
- std::pair < int,
- bool >
- frameIndex;
- MasterSlaveThreadController *
- masterController;
+ AiInterface *
+ aiIntf;
+ Semaphore
+ semTaskSignalled;
+ Mutex *
+ triggerIdMutex;
+ std::pair < int,
+ bool >
+ frameIndex;
+ MasterSlaveThreadController *
+ masterController;
- virtual void
- setQuitStatus (bool value);
- virtual void
- setTaskCompleted (int frameIndex);
+ virtual void
+ setQuitStatus(bool value);
+ virtual void
+ setTaskCompleted(int frameIndex);
- public:
- explicit
- AiInterfaceThread (AiInterface * aiIntf);
- virtual ~
- AiInterfaceThread ();
- virtual void
- execute ();
- void
- signal (int frameIndex);
- bool
- isSignalCompleted (int frameIndex);
+ public:
+ explicit
+ AiInterfaceThread(AiInterface * aiIntf);
+ virtual ~
+ AiInterfaceThread();
+ virtual void
+ execute();
+ void
+ signal(int frameIndex);
+ bool
+ isSignalCompleted(int frameIndex);
- virtual void
- setMasterController (MasterSlaveThreadController * master)
- {
- masterController = master;
- }
- virtual void
- signalSlave (void *userdata)
- {
- signal (*((int *) (userdata)));
- }
+ virtual void
+ setMasterController(MasterSlaveThreadController * master) {
+ masterController = master;
+ }
+ virtual void
+ signalSlave(void *userdata) {
+ signal(*((int *) (userdata)));
+ }
- virtual void
- signalQuit ();
- virtual bool
- canShutdown (bool deleteSelfIfShutdownDelayed = false);
- };
+ virtual void
+ signalQuit();
+ virtual bool
+ canShutdown(bool deleteSelfIfShutdownDelayed = false);
+ };
- class
- AiInterface
- {
- private:
- World *
- world;
- Commander *
- commander;
- Console *
- console;
- GameSettings *
- gameSettings;
+ class
+ AiInterface {
+ private:
+ World *
+ world;
+ Commander *
+ commander;
+ Console *
+ console;
+ GameSettings *
+ gameSettings;
- Ai
- ai;
+ Ai
+ ai;
- int
- timer;
- int
- factionIndex;
- int
- teamIndex;
+ int
+ timer;
+ int
+ factionIndex;
+ int
+ teamIndex;
- //config
- bool
- redir;
- int
- logLevel;
- std::string
- aiLogFile;
- FILE *
- fp;
+ //config
+ bool
+ redir;
+ int
+ logLevel;
+ std::string
+ aiLogFile;
+ FILE *
+ fp;
- std::map < const ResourceType *, int >
- cacheUnitHarvestResourceLookup;
+ std::map < const ResourceType *, int >
+ cacheUnitHarvestResourceLookup;
- Mutex *
- aiMutex;
+ Mutex *
+ aiMutex;
- AiInterfaceThread *
- workerThread;
- std::vector <
- Vec2i >
- enemyWarningPositionList;
+ AiInterfaceThread *
+ workerThread;
+ std::vector <
+ Vec2i >
+ enemyWarningPositionList;
- public:
- AiInterface (Game & game, int factionIndex, int teamIndex,
- int useStartLocation = -1);
- ~
- AiInterface ();
+ public:
+ AiInterface(Game & game, int factionIndex, int teamIndex,
+ int useStartLocation = -1);
+ ~
+ AiInterface();
- AiInterface (const AiInterface & obj)
- {
- init ();
- throw
- megaglest_runtime_error ("class AiInterface is NOT safe to copy!");
- }
- AiInterface &
- operator= (const AiInterface & obj)
- {
- init ();
- throw
- megaglest_runtime_error ("class AiInterface is NOT safe to assign!");
- }
+ AiInterface(const AiInterface & obj) {
+ init();
+ throw
+ megaglest_runtime_error("class AiInterface is NOT safe to copy!");
+ }
+ AiInterface &
+ operator= (const AiInterface & obj) {
+ init();
+ throw
+ megaglest_runtime_error("class AiInterface is NOT safe to assign!");
+ }
- //main
- void
- update ();
+ //main
+ void
+ update();
- std::vector < Vec2i > getEnemyWarningPositionList ()const
- {
- return
- enemyWarningPositionList;
- }
- void
- removeEnemyWarningPositionFromList (Vec2i & checkPos);
+ std::vector < Vec2i > getEnemyWarningPositionList()const {
+ return
+ enemyWarningPositionList;
+ }
+ void
+ removeEnemyWarningPositionFromList(Vec2i & checkPos);
- inline Mutex *
- getMutex ()
- {
- return aiMutex;
- }
+ inline Mutex *
+ getMutex() {
+ return aiMutex;
+ }
- void
- signalWorkerThread (int frameIndex);
- bool
- isWorkerThreadSignalCompleted (int frameIndex);
- AiInterfaceThread *
- getWorkerThread ()
- {
- return workerThread;
- }
+ void
+ signalWorkerThread(int frameIndex);
+ bool
+ isWorkerThreadSignalCompleted(int frameIndex);
+ AiInterfaceThread *
+ getWorkerThread() {
+ return workerThread;
+ }
- bool
- isLogLevelEnabled (int level);
+ bool
+ isLogLevelEnabled(int level);
- //get
- int
- getTimer () const
- {
- return
- timer;
- }
- int
- getFactionIndex () const
- {
- return
- factionIndex;
- }
+ //get
+ int
+ getTimer() const {
+ return
+ timer;
+ }
+ int
+ getFactionIndex() const {
+ return
+ factionIndex;
+ }
- //misc
- void
- printLog (int logLevel, const string & s);
+ //misc
+ void
+ printLog(int logLevel, const string & s);
- //interact
- std::pair < CommandResult, string > giveCommand (int unitIndex,
- CommandClass
- commandClass,
- const Vec2i & pos =
- Vec2i (0));
- std::pair < CommandResult, string > giveCommand (int unitIndex,
- const CommandType *
- commandType,
- const Vec2i & pos,
- const UnitType *
- unitType);
- std::pair < CommandResult, string > giveCommand (int unitIndex,
- const CommandType *
- commandType,
- const Vec2i & pos,
- int
- unitGroupCommandId);
- std::pair < CommandResult, string > giveCommand (int unitIndex,
- const CommandType *
- commandType, Unit * u =
- NULL);
- std::pair < CommandResult, string > giveCommand (const Unit * unit,
- const CommandType *
- commandType,
- const Vec2i & pos,
- int
- unitGroupCommandId);
+ //interact
+ std::pair < CommandResult, string > giveCommand(int unitIndex,
+ CommandClass
+ commandClass,
+ const Vec2i & pos =
+ Vec2i(0));
+ std::pair < CommandResult, string > giveCommand(int unitIndex,
+ const CommandType *
+ commandType,
+ const Vec2i & pos,
+ const UnitType *
+ unitType);
+ std::pair < CommandResult, string > giveCommand(int unitIndex,
+ const CommandType *
+ commandType,
+ const Vec2i & pos,
+ int
+ unitGroupCommandId);
+ std::pair < CommandResult, string > giveCommand(int unitIndex,
+ const CommandType *
+ commandType, Unit * u =
+ NULL);
+ std::pair < CommandResult, string > giveCommand(const Unit * unit,
+ const CommandType *
+ commandType,
+ const Vec2i & pos,
+ int
+ unitGroupCommandId);
- std::pair < CommandResult,
- string > giveCommandSwitchTeamVote (const Faction * faction,
- SwitchTeamVote * vote);
+ std::pair < CommandResult,
+ string > giveCommandSwitchTeamVote(const Faction * faction,
+ SwitchTeamVote * vote);
- //get data
- const ControlType
- getControlType ();
- int
- getMapMaxPlayers ();
- Vec2i
- getHomeLocation ();
- Vec2i
- getStartLocation (int locationIndex);
- int
- getFactionCount ();
- int
- getMyUnitCount () const;
- int
- getMyUpgradeCount () const;
- //int onSightUnitCount();
- const Resource *
- getResource (const ResourceType * rt);
- const Unit *
- getMyUnit (int unitIndex);
- Unit *
- getMyUnitPtr (int unitIndex);
- //const Unit *getOnSightUnit(int unitIndex);
- const FactionType *
- getMyFactionType ();
- Faction *
- getMyFaction ();
- const TechTree *
- getTechTree ();
- bool
- isResourceInRegion (const Vec2i & pos, const ResourceType * rt,
- Vec2i & resourcePos, int range) const;
- bool
- isResourceNear (const Vec2i & pos, const ResourceType * rt,
- Vec2i & resourcePos, Faction * faction,
- bool fallbackToPeersHarvestingSameResource) const;
- bool
- getNearestSightedResource (const ResourceType * rt, const Vec2i & pos,
- Vec2i & resultPos,
- bool usableResourceTypeOnly);
- bool
- isAlly (const Unit * unit) const;
- bool
- isAlly (int factionIndex) const;
- bool
- reqsOk (const RequirableType * rt);
- bool
- reqsOk (const CommandType * ct);
- bool
- checkCosts (const ProducibleType * pt, const CommandType * ct);
- bool
- isFreeCells (const Vec2i & pos, int size, Field field);
- const Unit *
- getFirstOnSightEnemyUnit (Vec2i & pos, Field & field, int radius);
- Map *
- getMap ();
- World *
- getWorld ()
- {
- return world;
- }
+ //get data
+ const ControlType
+ getControlType();
+ int
+ getMapMaxPlayers();
+ Vec2i
+ getHomeLocation();
+ Vec2i
+ getStartLocation(int locationIndex);
+ int
+ getFactionCount();
+ int
+ getMyUnitCount() const;
+ int
+ getMyUpgradeCount() const;
+ //int onSightUnitCount();
+ const Resource *
+ getResource(const ResourceType * rt);
+ const Unit *
+ getMyUnit(int unitIndex);
+ Unit *
+ getMyUnitPtr(int unitIndex);
+ //const Unit *getOnSightUnit(int unitIndex);
+ const FactionType *
+ getMyFactionType();
+ Faction *
+ getMyFaction();
+ const TechTree *
+ getTechTree();
+ bool
+ isResourceInRegion(const Vec2i & pos, const ResourceType * rt,
+ Vec2i & resourcePos, int range) const;
+ bool
+ isResourceNear(const Vec2i & pos, const ResourceType * rt,
+ Vec2i & resourcePos, Faction * faction,
+ bool fallbackToPeersHarvestingSameResource) const;
+ bool
+ getNearestSightedResource(const ResourceType * rt, const Vec2i & pos,
+ Vec2i & resultPos,
+ bool usableResourceTypeOnly);
+ bool
+ isAlly(const Unit * unit) const;
+ bool
+ isAlly(int factionIndex) const;
+ bool
+ reqsOk(const RequirableType * rt);
+ bool
+ reqsOk(const CommandType * ct);
+ bool
+ checkCosts(const ProducibleType * pt, const CommandType * ct);
+ bool
+ isFreeCells(const Vec2i & pos, int size, Field field);
+ const Unit *
+ getFirstOnSightEnemyUnit(Vec2i & pos, Field & field, int radius);
+ Map *
+ getMap();
+ World *
+ getWorld() {
+ return world;
+ }
- bool
- factionUsesResourceType (const FactionType * factionType,
- const ResourceType * rt);
+ bool
+ factionUsesResourceType(const FactionType * factionType,
+ const ResourceType * rt);
- void
- saveGame (XmlNode * rootNode) const;
- void
- loadGame (const XmlNode * rootNode, Faction * faction);
+ void
+ saveGame(XmlNode * rootNode) const;
+ void
+ loadGame(const XmlNode * rootNode, Faction * faction);
- private:
- string getLogFilename ()const
- {
- return
- "ai" +
- intToStr (factionIndex) +
- ".log";
- }
- bool
- executeCommandOverNetwork ();
+ private:
+ string getLogFilename()const {
+ return
+ "ai" +
+ intToStr(factionIndex) +
+ ".log";
+ }
+ bool
+ executeCommandOverNetwork();
- void
- init ();
- };
+ void
+ init();
+ };
-}} //end namespace
+ }
+} //end namespace
#endif
diff --git a/source/glest_game/ai/ai_rule.cpp b/source/glest_game/ai/ai_rule.cpp
index 173f46eb1..1bce60de8 100644
--- a/source/glest_game/ai/ai_rule.cpp
+++ b/source/glest_game/ai/ai_rule.cpp
@@ -19,3646 +19,3226 @@
#include "leak_dumper.h"
using
- Shared::Graphics::Vec2i;
+Shared::Graphics::Vec2i;
namespace
- Glest
-{
- namespace
- Game
- {
-
-// =====================================================
-// class AiRule
-// =====================================================
-
- AiRule::AiRule (Ai * ai)
- {
- this->ai = ai;
- }
-
-// =====================================================
-// class AiRuleWorkerHarvest
-// =====================================================
-
- AiRuleWorkerHarvest::AiRuleWorkerHarvest (Ai * ai):
- AiRule (ai)
- {
- stoppedWorkerIndex = -1;
- }
-
- bool
- AiRuleWorkerHarvest::test ()
- {
- return ai->findAbleUnit (&stoppedWorkerIndex, ccHarvest, true);
- }
-
- void
- AiRuleWorkerHarvest::execute ()
- {
- ai->harvest (stoppedWorkerIndex);
- }
-
-// =====================================================
-// class AiRuleRefreshHarvester
-// =====================================================
-
- AiRuleRefreshHarvester::AiRuleRefreshHarvester (Ai * ai):
- AiRule (ai)
- {
- workerIndex = -1;
- }
-
- bool
- AiRuleRefreshHarvester::test ()
- {
- return ai->findAbleUnit (&workerIndex, ccHarvest, ccHarvest);
- }
-
- void
- AiRuleRefreshHarvester::execute ()
- {
- ai->harvest (workerIndex);
- }
-
-// =====================================================
-// class AiRuleScoutPatrol
-// =====================================================
-
- AiRuleScoutPatrol::AiRuleScoutPatrol (Ai * ai):
- AiRule (ai)
- {
- }
-
- bool
- AiRuleScoutPatrol::test ()
- {
- return ai->isStableBase ();
- }
-
- void
- AiRuleScoutPatrol::execute ()
- {
- ai->sendScoutPatrol ();
- }
-// =====================================================
-// class AiRuleRepair
-// =====================================================
-
- AiRuleRepair::AiRuleRepair (Ai * ai):
- AiRule (ai)
- {
- damagedUnitIndex = 0;
- damagedUnitIsCastle = false;
- }
-
- double
- AiRuleRepair::getMinCastleHpRatio () const
- {
- return
- 0.6;
- }
-
- int
- AiRuleRepair::getMinUnitsToRepairCastle ()
- {
- int
- minUnitsRepairingCastle = 7;
- if (ai->getCountOfClass (ucWorker) <= 6)
- {
- minUnitsRepairingCastle = 1;
- }
- else if (ai->getCountOfClass (ucWorker) <= 8)
- {
- minUnitsRepairingCastle = 2;
- }
- else if (ai->getCountOfClass (ucWorker) <= 10)
- {
- minUnitsRepairingCastle = 3;
- }
- else if (ai->getCountOfClass (ucWorker) <= 12)
- {
- minUnitsRepairingCastle = 5;
- }
- return minUnitsRepairingCastle;
- }
-
- bool
- AiRuleRepair::test ()
- {
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- int
- minUnitsRepairingCastle = getMinUnitsToRepairCastle ();
- const double
- minCastleHpRatio = getMinCastleHpRatio ();
-
- // look for a damaged unit and give priority to the factions bases
- // (units that produce workers and store resources)
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- const Unit *
- u = aiInterface->getMyUnit (i);
- //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade()));
- if (u->getHpRatio () < 1.f)
- {
- //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade()));
-
- bool
- unitCanProduceWorker = false;
- for (int j = 0; unitCanProduceWorker == false &&
- j < u->getType ()->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = u->getType ()->getCommandType (j);
-
- //if the command is produce
- if (ct->getClass () == ccProduce
- || ct->getClass () == ccMorph)
- {
- const ProducibleType *
- pt = ct->getProduced ();
- if (pt != NULL)
- {
- const UnitType *
- ut = dynamic_cast < const
- UnitType * >(pt);
- if (ut != NULL
- && ut->hasCommandClass (ccHarvest) == true
- && u->getType ()->getStoredResourceCount () > 0)
- {
- //printf("\n\n\n\n!!!!!! found candidate castle unit to repair [%d - %s]\n",u->getId(),u->getType()->getName().c_str());
- unitCanProduceWorker = true;
- }
- }
- }
- }
-
- if (unitCanProduceWorker == true)
- {
- int
- candidatedamagedUnitIndex = -1;
- int
- unitCountAlreadyRepairingDamagedUnit = 0;
- // Now check if any other unit is able to repair this unit
- for (int i1 = 0; i1 < aiInterface->getMyUnitCount (); ++i1)
- {
- const Unit *
- u1 = aiInterface->getMyUnit (i1);
- const RepairCommandType *
- rct = static_cast < const
- RepairCommandType *
- >(u1->getType ()->getFirstCtOfClass (ccRepair));
- //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()));
-
- if (rct != NULL)
- {
- //printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio());
-
- if (u1->getCurrSkill ()->getClass () == scStop
- || u1->getCurrSkill ()->getClass () == scMove
- || u->getHpRatio () <= minCastleHpRatio)
- {
- if (rct->isRepairableUnitType (u->getType ()))
- {
- candidatedamagedUnitIndex = i;
- //return true;
- }
- }
- else if (u1->getCurrSkill ()->getClass () ==
- scRepair)
- {
- Command *
- cmd = u1->getCurrCommand ();
- if (cmd != NULL
- && cmd->getCommandType ()->getClass () ==
- ccRepair)
- {
- if (cmd->getUnit () != NULL
- && cmd->getUnit ()->getId () ==
- u->getId ())
- {
- //printf("\n\n\n\n^^^^^^^^^^ unit is ALREADY repairer unit [%d - %s]\n",u1->getId(),u1->getType()->getName().c_str());
- unitCountAlreadyRepairingDamagedUnit++;
- }
- }
- }
- }
- }
-
- if (candidatedamagedUnitIndex >= 0
- && unitCountAlreadyRepairingDamagedUnit <
- minUnitsRepairingCastle)
- {
- //printf("\n\n\n\n^^^^^^^^^^ AI test will repair damaged unit [%d - %s]\n",u->getId(),u->getType()->getName().c_str());
- damagedUnitIndex = candidatedamagedUnitIndex;
- damagedUnitIsCastle = true;
- return true;
- }
- }
- }
- }
- damagedUnitIsCastle = false;
- damagedUnitIndex = -1;
- // Normal Repair checking
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- const Unit *
- u = aiInterface->getMyUnit (i);
- //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade()));
- if (u->getHpRatio () < 1.f)
- {
- // Now check if any other unit is able to repair this unit
- for (int i1 = 0; i1 < aiInterface->getMyUnitCount (); ++i1)
- {
- const Unit *
- u1 = aiInterface->getMyUnit (i1);
- const RepairCommandType *
- rct = static_cast < const
- RepairCommandType *
- >(u1->getType ()->getFirstCtOfClass (ccRepair));
- //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()));
-
- if (rct != NULL
- && (u1->getCurrSkill ()->getClass () == scStop
- || u1->getCurrSkill ()->getClass () == scMove))
- {
- if (rct->isRepairableUnitType (u->getType ()))
- {
- damagedUnitIndex = i;
- //random if return or not so we get different targets from time to time
- if (ai->getRandom ()->randRange (0, 1) == 0)
- return true;
- }
- }
- }
- }
- }
- if (damagedUnitIndex != -1)
- {
- return true;
- }
- return false;
- }
-
- void
- AiRuleRepair::execute ()
- {
- AiInterface *
- aiInterface = ai->getAiInterface ();
- const Unit *
- damagedUnit = aiInterface->getMyUnit (damagedUnitIndex);
- //printf("\n\n\n\n###^^^^^^^^^^ Looking for repairer for damaged unit [%d - %s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str());
-
- int
- minUnitsRepairingCastle = getMinUnitsToRepairCastle ();
- const double
- minCastleHpRatio = getMinCastleHpRatio ();
-
- if (minUnitsRepairingCastle > 2)
- {
- if (damagedUnit->getCurrSkill ()->getClass () == scBeBuilt)
- { // if build is still be build 2 helpers are enough
- minUnitsRepairingCastle = 2;
- }
-
- if (!damagedUnitIsCastle)
- {
- minUnitsRepairingCastle = 2;
- }
- }
- if (aiInterface->getControlType () == ctCpuEasy ||
- aiInterface->getControlType () == ctNetworkCpuEasy)
- {
- if (!damagedUnitIsCastle)
- {
- // cpu easy does not repair!
- minUnitsRepairingCastle = 0;
- }
- }
- if (aiInterface->getControlType () == ctCpu ||
- aiInterface->getControlType () == ctNetworkCpu)
- {
- if (!damagedUnitIsCastle)
- {
- // cpu does only repair with one unit!
- minUnitsRepairingCastle = 1;
- }
- }
- int
- unitCountAlreadyRepairingDamagedUnit = 0;
- //printf("team %d has damaged unit\n", damagedUnit->getTeam());
- // Now check if any other unit is able to repair this unit
- for (int i1 = 0; i1 < aiInterface->getMyUnitCount (); ++i1)
- {
- const Unit *
- u1 = aiInterface->getMyUnit (i1);
- const RepairCommandType *
- rct = static_cast < const
- RepairCommandType *
- >(u1->getType ()->getFirstCtOfClass (ccRepair));
- //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u1->getType()));
- Command *
- cmd = u1->getCurrCommand ();
- if (cmd != NULL && cmd->getCommandType ()->getClass () == ccRepair)
- {
- //if(cmd->getUnit() != NULL && cmd->getUnit()->getId() == damagedUnit->getId())
- //if(cmd->getUnit() != NULL && cmd->getPos() == damagedUnit->getPosWithCellMapSet())
-
- if (rct != NULL)
- {
- //printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio());
-
- if (((RepairCommandType *) (cmd->getCommandType ()))->
- isRepairableUnitType (damagedUnit->getType ()))
- {
- //printf("^^^^test^^^^^^ unit is ALREADY repairer unit [%d - %s]\nminUnitsRepairingCastle=%d\n",u1->getId(), u1->getType()->getName().c_str(), minUnitsRepairingCastle);
- unitCountAlreadyRepairingDamagedUnit++;
- }
- }
- }
- }
-
- if (unitCountAlreadyRepairingDamagedUnit >= minUnitsRepairingCastle)
- {
- return;
- }
-
- int
- unitGroupCommandId = -1;
-
- //find a repairer and issue command
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- const Unit *
- u = aiInterface->getMyUnit (i);
- const RepairCommandType *
- rct = static_cast < const
- RepairCommandType *
- >(u->getType ()->getFirstCtOfClass (ccRepair));
- //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType()));
-
- if (rct != NULL)
- {
- //printf("\n\n\n\n^^^^^^^^^^ possible excute repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType()),damagedUnit->getHpRatio());
-
- if ((u->getCurrSkill ()->getClass () == scStop
- || u->getCurrSkill ()->getClass () == scMove
- || damagedUnit->getHpRatio () <= minCastleHpRatio))
- {
- if ((u->getCurrCommand () == NULL
- || (u->getCurrCommand ()->getCommandType ()->
- getClass () != ccBuild
- && u->getCurrCommand ()->getCommandType ()->
- getClass () != ccProduce))
- && rct->isRepairableUnitType (damagedUnit->getType ()))
- {
- //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
- //printf("\n\n\n\n^^^^^^^^^^ AI execute will repair damaged unit [%d - %s] at pos [%s] cellmapPos [%s] using unit [%d -%s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str(),damagedUnit->getPos().getString().c_str(),damagedUnit->getPosWithCellMapSet().getString().c_str(),u->getId(),u->getType()->getName().c_str());
-
- /*
- Map *map= aiInterface->getWorld()->getMap();
- Cell *cell = map->getCell(damagedUnit->getPosWithCellMapSet());
- if(cell != NULL) {
- printf("\n\n\n\n^^^^^^^^^^ cell is ok\n");
-
- Unit *cellUnit = cell->getUnit(damagedUnit->getCurrField());
- if(cellUnit != NULL) {
- printf("\n\n\n\n^^^^^^^^^^ cell unit [%d - %s] at pos [%s]\n",cellUnit->getId(),cellUnit->getType()->getName().c_str(),cellUnit->getPos().getString().c_str());
- }
- }
- */
-
- //aiInterface->giveCommand(i, rct, damagedUnit->getPos());
- if (unitCountAlreadyRepairingDamagedUnit <
- minUnitsRepairingCastle)
- {
-
- if (unitGroupCommandId == -1)
- {
- unitGroupCommandId =
- aiInterface->getWorld ()->
- getNextCommandGroupId ();
- }
-
- aiInterface->giveCommand (i, rct,
- damagedUnit->
- getPosWithCellMapSet (),
- unitGroupCommandId);
- if (aiInterface->isLogLevelEnabled (3) == true)
- aiInterface->printLog (3,
- "Repairing order issued");
- unitCountAlreadyRepairingDamagedUnit++;
- // printf(
- // "^^^^^^^^^^adding one unit to repair ... unitCountAlreadyRepairingDamagedUnit/minUnitsRepairingCastle=%d/%d\n",
- // unitCountAlreadyRepairingDamagedUnit, minUnitsRepairingCastle);
- }
-
- if (!damagedUnitIsCastle
- || unitCountAlreadyRepairingDamagedUnit >=
- minUnitsRepairingCastle)
- {
- return;
- }
- }
- }
- }
- }
- }
-
-// =====================================================
-// class AiRuleReturnBase
-// =====================================================
-
- AiRuleReturnBase::AiRuleReturnBase (Ai * ai):
- AiRule (ai)
- {
- stoppedUnitIndex = -1;
- }
-
- bool
- AiRuleReturnBase::test ()
- {
- return ai->findAbleUnit (&stoppedUnitIndex, ccMove, true);
- }
-
- void
- AiRuleReturnBase::execute ()
- {
- ai->returnBase (stoppedUnitIndex);
- }
-
-// =====================================================
-// class AiRuleMassiveAttack
-// =====================================================
-
- AiRuleMassiveAttack::AiRuleMassiveAttack (Ai * ai):
- AiRule (ai)
- {
- ultraAttack = false;
- field = fLand;
- }
-
- bool
- AiRuleMassiveAttack::test ()
- {
-
- if (ai->isStableBase ())
- {
- ultraAttack = false;
- return ai->beingAttacked (attackPos, field, INT_MAX);
- }
- else
- {
- ultraAttack = true;
- return ai->beingAttacked (attackPos, field, baseRadius);
- }
- }
-
- void
- AiRuleMassiveAttack::execute ()
- {
- ai->massiveAttack (attackPos, field, ultraAttack);
- }
-// =====================================================
-// class AiRuleAddTasks
-// =====================================================
-
- AiRuleAddTasks::AiRuleAddTasks (Ai * ai):
- AiRule (ai)
- {
- }
-
- bool
- AiRuleAddTasks::test ()
- {
- return !ai->anyTask () || ai->getCountOfClass (ucWorker) < 4;
- }
-
-// This function is what triggers the AI to create new units.
- void
- AiRuleAddTasks::execute ()
- {
- int
- buildingCount = ai->getCountOfClass (ucBuilding);
- UnitClass
- ucWorkerType = ucWorker;
- int
- warriorCount = ai->getCountOfClass (ucWarrior, &ucWorkerType);
- int
- workerCount = ai->getCountOfClass (ucWorker);
- int
- upgradeCount = ai->getAiInterface ()->getMyUpgradeCount ();
-
- float
- buildingRatio = ai->getRatioOfClass (ucBuilding);
- float
- warriorRatio = ai->getRatioOfClass (ucWarrior);
- float
- workerRatio = ai->getRatioOfClass (ucWorker);
-
- //standard tasks
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("Add a TASK - AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = %d, RULE Name[%s]\n",
- workerCount, this->getName ().c_str ());
-
- //emergency workers
- if (workerCount < 4)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("AAA AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = %d, RULE Name[%s]\n",
- workerCount, this->getName ().c_str ());
-
- ai->addPriorityTask (new ProduceTask (ucWorker));
- }
- // The following rules are specific creation rules for different AI.
- else
- {
- if (ai->getAiInterface ()->getControlType () == ctCpuZeta ||
- ai->getAiInterface ()->getControlType () == ctNetworkCpuZeta)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("AAA AiRuleAddTasks adding #1 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n",
- workerCount, workerRatio, buildingCount, buildingRatio,
- warriorCount, warriorRatio, upgradeCount,
- this->getName ().c_str ());
-
- //workers
- if (workerCount < 5)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerCount < 100)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerRatio < 0.20)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerRatio < 0.30)
- ai->addTask (new ProduceTask (ucWorker));
-
- //warriors
- if (warriorCount < 10)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorRatio < 0.20)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorRatio < 0.30)
- ai->addTask (new ProduceTask (ucWarrior));
- if (workerCount >= 10)
- ai->addTask (new ProduceTask (ucWarrior));
- if (workerCount >= 15)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorCount < ai->getMinWarriors () + 2)
- {
- ai->addTask (new ProduceTask (ucWarrior));
- if (buildingCount > 9)
- {
- ai->addTask (new ProduceTask (ucWarrior));
- ai->addTask (new ProduceTask (ucWarrior));
- }
- if (buildingCount > 12)
- {
- ai->addTask (new ProduceTask (ucWarrior));
- ai->addTask (new ProduceTask (ucWarrior));
- }
- }
-
- //buildings
- if (buildingCount < 6 || buildingRatio < 0.20)
- ai->addTask (new BuildTask ((UnitType *) NULL));
- if (buildingCount < 10 && workerCount > 12)
- ai->addTask (new BuildTask ((UnitType *) NULL));
- //upgrades
- if (upgradeCount == 0 && workerCount > 5)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (upgradeCount == 1 && workerCount > 10)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (upgradeCount == 2 && workerCount > 15)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (ai->isStableBase ())
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- }
- else if (ai->getAiInterface ()->getControlType () == ctCpuEasy ||
- ai->getAiInterface ()->getControlType () ==
- ctNetworkCpuEasy)
- { // Easy CPU
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("AAA AiRuleAddTasks adding #2 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n",
- workerCount, workerRatio, buildingCount, buildingRatio,
- warriorCount, warriorRatio, upgradeCount,
- this->getName ().c_str ());
-
- //workers
- if (workerCount < buildingCount + 2)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerCount > 5 && workerRatio < 0.20)
- ai->addTask (new ProduceTask (ucWorker));
-
- //warriors
- if (warriorCount < 10)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorRatio < 0.20)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorRatio < 0.30)
- ai->addTask (new ProduceTask (ucWarrior));
- if (workerCount >= 10)
- ai->addTask (new ProduceTask (ucWarrior));
- if (workerCount >= 15)
- ai->addTask (new ProduceTask (ucWarrior));
-
- //buildings
- if (buildingCount < 6 || buildingRatio < 0.20)
- ai->addTask (new BuildTask ((UnitType *) NULL));
- if (buildingCount < 10 && ai->isStableBase ())
- ai->addTask (new BuildTask ((UnitType *) NULL));
-
- //upgrades
- if (upgradeCount == 0 && workerCount > 6)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (upgradeCount == 1 && workerCount > 7)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (upgradeCount == 2 && workerCount > 9)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- //if(ai->isStableBase()) ai->addTask(new UpgradeTask());
- }
- else
- { // normal CPU / UltraCPU ...
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("AAA AiRuleAddTasks adding #3 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n",
- workerCount, workerRatio, buildingCount, buildingRatio,
- warriorCount, warriorRatio, upgradeCount,
- this->getName ().c_str ());
-
- //workers
- if (workerCount < 5)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerCount < 10)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerRatio < 0.20)
- ai->addTask (new ProduceTask (ucWorker));
- if (workerRatio < 0.30)
- ai->addTask (new ProduceTask (ucWorker));
-
- //warriors
- if (warriorCount < 10)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorRatio < 0.20)
- ai->addTask (new ProduceTask (ucWarrior));
- if (warriorRatio < 0.30)
- ai->addTask (new ProduceTask (ucWarrior));
- if (workerCount >= 10)
- ai->addTask (new ProduceTask (ucWarrior));
- if (workerCount >= 15)
- ai->addTask (new ProduceTask (ucWarrior));
-
- //buildings
- if (buildingCount < 6 || buildingRatio < 0.20)
- ai->addTask (new BuildTask ((UnitType *) NULL));
- if (buildingCount < 10 && workerCount > 12)
- ai->addTask (new BuildTask ((UnitType *) NULL));
-
- //upgrades
- if (upgradeCount == 0 && workerCount > 5)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (upgradeCount == 1 && workerCount > 10)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (upgradeCount == 2 && workerCount > 15)
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- if (ai->isStableBase ())
- ai->addTask (new UpgradeTask ((const UpgradeType *) NULL));
- }
- }
- }
-
-// =====================================================
-// class AiRuleBuildOneFarm
-// =====================================================
-
- AiRuleBuildOneFarm::AiRuleBuildOneFarm (Ai * ai):
- AiRule (ai)
- {
- farm = NULL;
- }
-
- bool
- AiRuleBuildOneFarm::test ()
- {
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- //for all units
- for (int i = 0;
- i < aiInterface->getMyFactionType ()->getUnitTypeCount (); ++i)
- {
- const UnitType *
- ut = aiInterface->getMyFactionType ()->getUnitType (i);
-
- //for all production commands
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
- if (ct->getClass () == ccProduce)
- {
- const UnitType *
- producedType = static_cast < const
- ProduceCommandType * >(ct)->
- getProducedUnit ();
-
- //for all resources
- for (int k = 0; k < producedType->getCostCount (); ++k)
- {
- const Resource *
- r = producedType->getCost (k);
-
- //find a food producer in the farm produced units
- if (r->getAmount () < 0
- && r->getType ()->getClass () == rcConsumable
- && ai->getCountOfType (ut) == 0)
- {
- if (aiInterface->reqsOk (ct)
- && aiInterface->getMyFaction ()->
- canCreateUnit (ut, true, true, true) == true)
- {
- farm = ut;
- //printf("AiRuleBuildOneFarm returning true, RULE Name[%s] ut [%s] producedType [%s]\n",this->getName().c_str(),ut->getName().c_str(),producedType->getName().c_str());
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("AiRuleBuildOneFarm returning true, RULE Name[%s]\n",
- this->getName ().c_str ());
-
- return true;
- }
- }
- }
- }
- }
- }
- return false;
- }
-
- void
- AiRuleBuildOneFarm::execute ()
- {
- ai->addPriorityTask (new BuildTask (farm));
- }
-
-// =====================================================
-// class AiRuleProduceResourceProducer
-// =====================================================
-
- AiRuleProduceResourceProducer::AiRuleProduceResourceProducer (Ai * ai):
- AiRule (ai)
- {
- interval = shortInterval;
- rt = NULL;
- newResourceBehaviour =
- Config::getInstance ().getBool ("NewResourceBehaviour", "false");;
- }
-
- bool
- AiRuleProduceResourceProducer::test ()
- {
- //emergency tasks: resource buildings
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- //consumables first
- for (int i = 0;
- i < aiInterface->getTechTree ()->getResourceTypeCount (); ++i)
- {
- rt = aiInterface->getTechTree ()->getResourceType (i);
- const Resource *
- r = aiInterface->getResource (rt);
-
- if (ai->outputAIBehaviourToConsole ())
- printf ("CONSUMABLE [%s][%d] Testing AI RULE Name[%s]\n",
- rt->getName ().c_str (), r->getBalance (),
- this->getName ().c_str ());
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "CONSUMABLE [%s][%d] Testing AI RULE Name[%s]",
- rt->getName ().c_str (), r->getBalance (),
- this->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- bool
- factionUsesResourceType =
- aiInterface->factionUsesResourceType (aiInterface->
- getMyFactionType (), rt);
- if (factionUsesResourceType == true
- && rt->getClass () == rcConsumable)
- {
- // The consumable balance is negative
- if (r->getBalance () < 0)
- {
- if (newResourceBehaviour == true)
- {
- interval = shortInterval;
- }
- else
- {
- interval = longInterval;
- }
-
- return true;
- }
- // If the consumable balance is down to 1/3 of what we need
- else
- {
- if (r->getBalance () * 3 + r->getAmount () < 0)
- {
- if (newResourceBehaviour == true)
- {
- interval = shortInterval;
- }
- else
- {
- interval = longInterval;
- }
-
- return true;
- }
- }
- }
- }
-
- int
- targetStaticResourceCount = minStaticResources;
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorStaticOverideValue (aibsvcMinStaticResourceCount) !=
- INT_MAX)
- {
- targetStaticResourceCount =
- aiInterface->getMyFactionType ()->
- getAIBehaviorStaticOverideValue (aibsvcMinStaticResourceCount);
- }
-
- //statics second
- for (int i = 0;
- i < aiInterface->getTechTree ()->getResourceTypeCount (); ++i)
- {
- rt = aiInterface->getTechTree ()->getResourceType (i);
- const Resource *
- r = aiInterface->getResource (rt);
-
- if (ai->outputAIBehaviourToConsole ())
- printf ("STATIC [%s][%d] [min %d] Testing AI RULE Name[%s]\n",
- rt->getName ().c_str (), r->getAmount (),
- targetStaticResourceCount, this->getName ().c_str ());
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "STATIC resource check [%s][%d] [min %d] Testing AI RULE Name[%s]",
- rt->getName ().c_str (), r->getAmount (),
- targetStaticResourceCount, this->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- if (rt->getClass () == rcStatic
- && r->getAmount () < targetStaticResourceCount)
- {
- bool
- factionUsesResourceType =
- aiInterface->factionUsesResourceType (aiInterface->
- getMyFactionType (),
- rt);
- if (factionUsesResourceType == true)
- {
- if (newResourceBehaviour == true)
- interval = shortInterval;
- else
- interval = longInterval;
- return true;
- }
- }
- }
-
- if (ai->outputAIBehaviourToConsole ())
- printf ("STATIC returning FALSE\n");
- if (aiInterface->isLogLevelEnabled (4) == true)
- aiInterface->printLog (4, "Static Resource check returning FALSE");
-
- if (newResourceBehaviour == true)
- interval = longInterval;
- else
- interval = shortInterval;
- return false;
- }
-
- void
- AiRuleProduceResourceProducer::execute ()
- {
- ai->addPriorityTask (new ProduceTask (rt));
- ai->addTask (new BuildTask (rt));
- }
-
-// =====================================================
-// class AiRuleProduce
-// =====================================================
-
- AiRuleProduce::AiRuleProduce (Ai * ai):
- AiRule (ai)
- {
- produceTask = NULL;
- newResourceBehaviour =
- Config::getInstance ().getBool ("NewResourceBehaviour", "false");
- }
-
- bool
- AiRuleProduce::test ()
- {
- const Task *
- task = ai->getTask ();
-
- if (task == NULL || task->getClass () != tcProduce)
- {
- return false;
- }
-
- produceTask = static_cast < const ProduceTask *>(task);
- return true;
- }
-
- void
- AiRuleProduce::execute ()
- {
- AiInterface *
- aiInterface = ai->getAiInterface ();
- if (produceTask != NULL)
- {
-
- if (ai->outputAIBehaviourToConsole ())
- printf ("AiRuleProduce producing [%s]\n",
- (produceTask->getUnitType () !=
- NULL ? produceTask->getUnitType ()->getName (false).
- c_str () : "null"));
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "AiRuleProduce producing [%s]",
- (produceTask->getUnitType () !=
- NULL ? produceTask->getUnitType ()->getName (false).
- c_str () : "null"));
- aiInterface->printLog (4, szBuf);
- }
-
- //generic produce task, produce random unit that has the skill or produces the resource
- if (produceTask->getUnitType () == NULL)
- {
- if (newResourceBehaviour)
- {
- produceGenericNew (produceTask);
- }
- else
- produceGeneric (produceTask);
- }
-
- //specific produce task, produce if possible, retry if not enough resources
- else
- {
- produceSpecific (produceTask);
- }
-
- //remove the task
- ai->removeTask (produceTask);
- }
- }
-
- bool
- AiRuleProduce::canUnitTypeOfferResourceType (const UnitType * ut,
- const ResourceType * rt)
- {
- bool
- unitTypeOffersResourceType = false;
-
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- if (ut != NULL && rt != NULL && aiInterface != NULL
- && aiInterface->reqsOk (ut))
- {
- // Check of the unit 'gives' the resource
- // if the unit produces the resource
- const Resource *
- r = ut->getCost (rt);
- if (r != NULL)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
- r->getDescription (false).c_str (), r->getAmount (),
- this->getName ().c_str ());
- }
-
- if (r != NULL && r->getAmount () < 0)
- {
- unitTypeOffersResourceType = true;
- }
- else
- {
- // for each command check if we produce a unit that handles the resource
- for (int commandIndex = 0;
- commandIndex < ut->getCommandTypeCount (); ++commandIndex)
- {
- const CommandType *
- ct = ut->getCommandType (commandIndex);
-
- //if the command is produce
- if (ct->getClass () == ccProduce
- || ct->getClass () == ccMorph)
- {
- const UnitType *
- producedUnit = static_cast < const
- UnitType * >(ct->getProduced ());
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric [%p] Testing AI RULE Name[%s]\n",
- rt, this->getName ().c_str ());
-
- //if the unit produces the resource
- const Resource *
- r = producedUnit->getCost (rt);
- if (r != NULL)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
- r->getDescription (false).c_str (),
- r->getAmount (), this->getName ().c_str ());
- }
-
- if (r != NULL && r->getAmount () < 0)
- {
- unitTypeOffersResourceType = true;
- break;
- }
- }
- }
- }
- }
-
- if (aiInterface != NULL && aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "canUnitTypeOfferResourceType for unit type [%s] for resource type [%s] returned: %d",
- (ut != NULL ? ut->getName (false).c_str () : "n/a"),
- (rt != NULL ? rt->getName (false).c_str () : "n/a"),
- unitTypeOffersResourceType);
- aiInterface->printLog (4, szBuf);
- }
-
- return unitTypeOffersResourceType;
- }
-
- bool
- AiRuleProduce::setAIProduceTaskForResourceType (const ProduceTask * pt,
- AiInterface * aiInterface)
- {
- bool
- taskAdded = false;
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcResourceProducerUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcResourceProducerUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- const UnitType *
- ut = priorityUnit.first;
- if (ai->getCountOfType (ut) < priorityUnit.second &&
- canUnitTypeOfferResourceType (ut,
- pt->getResourceType ()) ==
- true
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, false, true,
- true) == true)
- {
- ai->addTask (new ProduceTask (priorityUnit.first));
- taskAdded = true;
- break;
- }
- }
- }
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "setAIProduceTaskForResourceType for resource type [%s] returned: %d",
- pt->getResourceType ()->getName (false).c_str (),
- taskAdded);
- aiInterface->printLog (4, szBuf);
- }
-
- return taskAdded;
- }
-
- void
- AiRuleProduce::addUnitTypeToCandidates (const UnitType * producedUnit,
- UnitTypes & ableUnits,
- UnitTypesGiveBack &
- ableUnitsGiveBack,
- bool unitCanGiveBackResource)
- {
- // if the unit is not already on the list
- if (find (ableUnits.begin (), ableUnits.end (), producedUnit) ==
- ableUnits.end ())
- {
- ableUnits.push_back (producedUnit);
- ableUnitsGiveBack.push_back (unitCanGiveBackResource);
-
- AiInterface *
- aiInterface = ai->getAiInterface ();
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "addUnitTypeToCandidates for unit type [%s] unitCanGiveBackResource = %d",
- producedUnit->getName (false).c_str (),
- unitCanGiveBackResource);
- aiInterface->printLog (4, szBuf);
- }
-
- }
- }
-
- void
- AiRuleProduce::produceGenericNew (const ProduceTask * pt)
- {
- UnitTypes
- ableUnits;
- UnitTypesGiveBack
- ableUnitsGiveBack;
-
- AiInterface *
- aiInterface = ai->getAiInterface ();
- if (pt->getResourceType () != NULL)
- {
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "****START: produceGeneric for resource type [%s]",
- pt->getResourceType ()->getName (false).c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- if (setAIProduceTaskForResourceType (pt, aiInterface) == true)
- {
- return;
- }
- }
- else if (pt->getUnitClass () == ucWorker)
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWorkerUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWorkerUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, false, true,
- true) == true)
- {
- ai->addTask (new ProduceTask (priorityUnit.first));
- return;
- }
- }
- }
- }
- else if (pt->getUnitClass () == ucWarrior)
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWarriorUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWarriorUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, false, true,
- true) == true)
- {
- ai->addTask (new ProduceTask (priorityUnit.first));
- return;
- }
- }
- }
- }
-
- //for each unit, produce it if possible
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- if (aiInterface->getMyUnit (i)->getCurrCommand () != NULL
- && aiInterface->getMyUnit (i)->getCurrCommand ()->
- getCommandType ()->getClass () == ccBuild)
- {
- //skip this units as it is currently building something
- continue;
- }
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
-
- //bool produceIt= false;
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is produce
- //bool produceIt= false;
- if (ct->getClass () == ccProduce || ct->getClass () == ccMorph)
- {
- const UnitType *
- producedUnit = static_cast < const
- UnitType * >(ct->getProduced ());
-
- if (ai->outputAIBehaviourToConsole ())
- printf ("produceGeneric [%p] Testing AI RULE Name[%s]\n",
- pt->getResourceType (),
- this->getName ().c_str ());
-
- //if the unit produces the resource
- if (pt->getResourceType () != NULL)
- {
- const Resource *
- r = producedUnit->getCost (pt->getResourceType ());
- if (r != NULL)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
- r->getDescription (false).c_str (),
- r->getAmount (), this->getName ().c_str ());
- }
-
- if (r != NULL && r->getAmount () < 0)
- {
- if (aiInterface->reqsOk (ct)
- && aiInterface->reqsOk (producedUnit))
- {
- //produceIt= true;
- addUnitTypeToCandidates (producedUnit,
- ableUnits,
- ableUnitsGiveBack,
- false);
- }
- }
- }
- else
- {
- //if the unit is from the right class
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric right class = [%d] Testing AI RULE Name[%s]\n",
- producedUnit->isOfClass (pt->getUnitClass ()),
- this->getName ().c_str ());
-
- if (producedUnit->isOfClass (pt->getUnitClass ()))
- {
- if (aiInterface->reqsOk (ct)
- && aiInterface->reqsOk (producedUnit))
- {
- //produceIt= true;
- addUnitTypeToCandidates (producedUnit,
- ableUnits,
- ableUnitsGiveBack,
- false);
- }
- }
- }
- }
- }
- // Now check of the unit 'gives' the resource
-// This is likely a unit that it BUILT by another and that is handled by a different AI task type: Build
-// if(produceIt == false && pt->getResourceType() != NULL) {
-// const Resource *r= ut->getCost(pt->getResourceType());
-// if(r != NULL) {
-// if(ai->outputAIBehaviourToConsole()) printf("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str());
-// }
-//
-// if(r != NULL && r->getAmount() < 0) {
-// if(aiInterface->reqsOk(ut)){
-// produceIt= true;
-// addUnitTypeToCandidates(ut, ableUnits,ableUnitsGiveBack, true);
-// }
-// }
-// }
-
- }
-
- //add specific produce task
- if (ableUnits.empty () == false)
- {
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] Testing AI RULE Name[%s]\n",
- (int) ableUnits.size (), this->getName ().c_str ());
-
- // Now check if we already have at least 2 produce or morph
- // resource based units, if so prefer units that give back the resource
- if (pt->getResourceType () != NULL && ableUnits.size () > 1)
- {
- //priority for non produced units
- UnitTypes
- newAbleUnits;
- bool
- haveEnoughProducers = true;
- bool
- haveNonProducers = false;
- for (unsigned int i = 0; i < ableUnits.size (); ++i)
- {
- const UnitType *
- ut = ableUnits[i];
- bool
- givesBack = ableUnitsGiveBack[i];
- if (givesBack == false && ai->getCountOfType (ut) < 2)
- {
- haveEnoughProducers = false;
- }
- else if (givesBack == true)
- {
- haveNonProducers = true;
- newAbleUnits.push_back (ut);
- }
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In produceGeneric for unit type [%s] givesBack: %d count of unit type: %d",
- ut->getName (false).c_str (), givesBack,
- ai->getCountOfType (ut));
- aiInterface->printLog (4, szBuf);
- }
-
- }
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "haveEnoughProducers [%d] haveNonProducers [%d]",
- haveEnoughProducers, haveNonProducers);
- aiInterface->printLog (4, szBuf);
-
- for (unsigned int i = 0; i < ableUnits.size (); ++i)
- {
- const UnitType *
- ut = ableUnits[i];
- snprintf (szBuf, 8096, "i: %u unit type [%s]", i,
- ut->getName (false).c_str ());
- aiInterface->printLog (4, szBuf);
- }
- for (unsigned int i = 0; i < newAbleUnits.size (); ++i)
- {
- const UnitType *
- ut = newAbleUnits[i];
- snprintf (szBuf, 8096, "i: %u new unit type [%s]", i,
- ut->getName (false).c_str ());
- aiInterface->printLog (4, szBuf);
- }
- }
-
- if (haveEnoughProducers == true && haveNonProducers == true)
- {
- ableUnits = newAbleUnits;
- }
- }
-
- //priority for non produced units
- for (unsigned int i = 0; i < ableUnits.size (); ++i)
- {
- if (ai->getCountOfType (ableUnits[i]) == 0)
- {
- if (ai->getRandom ()->randRange (0, 1) == 0)
- {
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In produceGeneric priority adding produce task: %d of "
- MG_SIZE_T_SPECIFIER " for unit type [%s]",
- i, ableUnits.size (),
- ableUnits[i]->getName (false).c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new ProduceTask (ableUnits[i]));
- return;
- }
- }
- }
-
- //normal case
- int
- randomUnitTypeIndex =
- ai->getRandom ()->randRange (0, (int) ableUnits.size () - 1);
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In produceGeneric randomUnitTypeIndex = %d of "
- MG_SIZE_T_SPECIFIER " equals unit type [%s]",
- randomUnitTypeIndex, ableUnits.size () - 1,
- ableUnits[randomUnitTypeIndex]->getName (false).
- c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- const UnitType *
- ut = ableUnits[randomUnitTypeIndex];
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "== END In produceGeneric normal adding produce task for unit type [%s]",
- ut->getName (false).c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new ProduceTask (ut));
- }
- }
-
- void
- AiRuleProduce::produceGeneric (const ProduceTask * pt)
- {
- typedef
- vector < const UnitType *>
- UnitTypes;
- UnitTypes
- ableUnits;
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- if (pt->getResourceType () != NULL)
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcResourceProducerUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcResourceProducerUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, false, true,
- true) == true)
- {
- //if(ai->getRandom()->randRange(0, 1)==0) {
- ai->addTask (new ProduceTask (priorityUnit.first));
- return;
- //}
- }
- }
- }
- }
- else if (pt->getUnitClass () == ucWorker)
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWorkerUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWorkerUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, false, true,
- true) == true)
- {
- //if(ai->getRandom()->randRange(0, 1)==0) {
- ai->addTask (new ProduceTask (priorityUnit.first));
- return;
- //}
- }
- }
- }
- }
- else if (pt->getUnitClass () == ucWarrior)
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWarriorUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcWarriorUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, false, true,
- true) == true)
- {
- //if(ai->getRandom()->randRange(0, 1)==0) {
- ai->addTask (new ProduceTask (priorityUnit.first));
- return;
- //}
- }
- }
- }
- }
-
- //for each unit, produce it if possible
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- if (aiInterface->getMyUnit (i)->getCurrCommand () != NULL
- && aiInterface->getMyUnit (i)->getCurrCommand ()->
- getCommandType ()->getClass () == ccBuild)
- {
- //skip this units as it is currently building something
- continue;
- }
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is produce
- if (ct->getClass () == ccProduce || ct->getClass () == ccMorph)
- {
-
- const UnitType *
- producedUnit = static_cast < const
- UnitType * >(ct->getProduced ());
- bool
- produceIt = false;
-
- if (ai->outputAIBehaviourToConsole ())
- printf ("produceGeneric [%p] Testing AI RULE Name[%s]\n",
- pt->getResourceType (),
- this->getName ().c_str ());
-
- //if the unit produces the resource
- if (pt->getResourceType () != NULL)
- {
- const Resource *
- r = producedUnit->getCost (pt->getResourceType ());
-
- if (r != NULL)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
- r->getDescription (false).c_str (),
- r->getAmount (), this->getName ().c_str ());
- }
-
- if (r != NULL && r->getAmount () < 0)
- {
- produceIt = true;
- }
- }
-
- else
- {
- //if the unit is from the right class
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric right class = [%d] Testing AI RULE Name[%s]\n",
- producedUnit->isOfClass (pt->getUnitClass ()),
- this->getName ().c_str ());
-
- if (producedUnit->isOfClass (pt->getUnitClass ()))
- {
- if (aiInterface->reqsOk (ct)
- && aiInterface->reqsOk (producedUnit))
- {
- produceIt = true;
- }
- }
- }
-
- if (produceIt)
- {
- //if the unit is not already on the list
- if (find
- (ableUnits.begin (), ableUnits.end (),
- producedUnit) == ableUnits.end ())
- {
- ableUnits.push_back (producedUnit);
- }
- }
- }
- }
- }
-
- //add specific produce task
- if (ableUnits.empty () == false)
- {
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] Testing AI RULE Name[%s]\n",
- (int) ableUnits.size (), this->getName ().c_str ());
-
- //priority for non produced units
- for (unsigned int i = 0; i < ableUnits.size (); ++i)
- {
- if (ai->getCountOfType (ableUnits[i]) == 0)
- {
- if (ai->getRandom ()->randRange (0, 1) == 0)
- {
- ai->addTask (new ProduceTask (ableUnits[i]));
- return;
- }
- }
- }
-
- //normal case
- ai->
- addTask (new
- ProduceTask (ableUnits
- [ai->getRandom ()->
- randRange (0,
- (int) ableUnits.size () - 1)]));
- }
- }
-
- void
- AiRuleProduce::produceSpecific (const ProduceTask * pt)
- {
-
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] Testing AI RULE Name[%s]\n",
- pt->getUnitType ()->getName ().c_str (),
- aiInterface->reqsOk (pt->getUnitType ()),
- this->getName ().c_str ());
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "== START produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] Testing AI RULE Name[%s]",
- pt->getUnitType ()->getName ().c_str (),
- aiInterface->reqsOk (pt->getUnitType ()),
- this->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- //if unit meets requirements
- if (aiInterface->reqsOk (pt->getUnitType ()))
- {
-
- const CommandType *
- ctypeForCostCheck = NULL;
- //for each unit
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- //don't use units which are currently building
- if (aiInterface->getMyUnit (i)->getCurrCommand () != NULL
- && aiInterface->getMyUnit (i)->getCurrCommand ()->
- getCommandType ()->getClass () == ccBuild)
- {
- //skip this units as it is currently building something
- continue;
- }
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is produce
- if (ct->getClass () == ccProduce
- || ct->getClass () == ccMorph)
- {
- const UnitType *
- producedUnit = static_cast < const
- UnitType * >(ct->getProduced ());
-
- //if units match
- if (producedUnit == pt->getUnitType ())
- {
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing AI RULE Name[%s]\n",
- aiInterface->reqsOk (ct),
- this->getName ().c_str ());
-
- if (aiInterface->reqsOk (ct))
- {
- if (ctypeForCostCheck == NULL
- || ct->getClass () == ccMorph)
- {
- if (ctypeForCostCheck != NULL
- && ct->getClass () == ccMorph)
- {
- const MorphCommandType *
- mct = dynamic_cast < const
- MorphCommandType * >(ct);
- if (mct == NULL)
- {
- throw
- megaglest_runtime_error
- ("mct == NULL");
- }
- if (mct->
- getIgnoreResourceRequirements () ==
- true)
- {
- ctypeForCostCheck = ct;
- }
- }
- else
- {
- ctypeForCostCheck = ct;
- }
- }
- }
- }
- }
- }
- }
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceSpecific aiInterface->checkCosts(pt->getUnitType()) = [%d] Testing AI RULE Name[%s]\n",
- aiInterface->checkCosts (pt->getUnitType (),
- ctypeForCostCheck),
- this->getName ().c_str ());
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "produceSpecific aiInterface->checkCosts(pt->getUnitType()) = [%d] Testing AI RULE Name[%s]",
- aiInterface->checkCosts (pt->getUnitType (),
- ctypeForCostCheck),
- this->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- //if unit doesnt meet resources retry
- if (aiInterface->
- checkCosts (pt->getUnitType (), ctypeForCostCheck) == false)
- {
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "Check costs FAILED.");
- aiInterface->printLog (4, szBuf);
- }
-
- ai->retryTask (pt);
- return;
- }
-
- //produce specific unit
- vector < int >
- producers;
- // Hold a list of units which can produce or morph
- // then a list of commandtypes for each unit
- map < int,
- vector < const CommandType *> >
- producersDefaultCommandType;
- const CommandType *
- defCt = NULL;
-
- //for each unit
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
- if (aiInterface->getMyUnit (i)->getCurrCommand () != NULL
- && aiInterface->getMyUnit (i)->getCurrCommand ()->
- getCommandType ()->getClass () == ccBuild)
- {
- //skip this units as it is currently building something
- continue;
- }
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is produce
- if (ct->getClass () == ccProduce
- || ct->getClass () == ccMorph)
- {
- const UnitType *
- producedUnit = static_cast < const
- UnitType * >(ct->getProduced ());
-
- //if units match
- if (producedUnit == pt->getUnitType ())
- {
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing AI RULE Name[%s]\n",
- aiInterface->reqsOk (ct),
- this->getName ().c_str ());
-
- if (aiInterface->reqsOk (ct))
- {
- //defCt= ct;
- producers.push_back (i);
- producersDefaultCommandType[i].push_back (ct);
- }
- }
- }
- }
- }
-
- //produce from random producer
- if (producers.empty () == false)
- {
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]\n",
- producers.empty (), this->getName ().c_str ());
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]",
- producers.empty (), this->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- // Narrow down producers list to those who are not busy if possible
- vector < int >
- idle_producers;
- for (unsigned int i = 0; i < producers.size (); ++i)
- {
- int
- currentProducerIndex = producers[i];
- if (currentProducerIndex >= aiInterface->getMyUnitCount ())
- {
- char
- szBuf[8096] = "";
- printf
- ("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,producers.size() = "
- MG_SIZE_T_SPECIFIER "\n", __FILE__, __FUNCTION__,
- __LINE__, currentProducerIndex,
- aiInterface->getMyUnitCount (), i,
- producers.size ());
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %u, i = %u,producers.size() = "
- MG_SIZE_T_SPECIFIER "", __FILE__,
- __FUNCTION__, __LINE__, currentProducerIndex,
- aiInterface->getMyUnitCount (), i,
- producers.size ());
- throw
- megaglest_runtime_error (szBuf);
- }
-
- const Unit *
- unit = aiInterface->getMyUnit (currentProducerIndex);
- if (unit->anyCommand () == false)
- {
- idle_producers.push_back (currentProducerIndex);
- }
- }
- if (idle_producers.empty () == false)
- {
- producers = idle_producers;
- }
-
- if (aiInterface->getControlType () == ctCpuZeta ||
- aiInterface->getControlType () == ctNetworkCpuZeta)
- { // zeta cpu trys to balance the commands to the producers
- int
- randomstart =
- ai->getRandom ()->randRange (0,
- (int) producers.size () - 1);
- int
- lowestCommandCount = 1000000;
- int
- currentProducerIndex = producers[randomstart];
- int
- bestIndex = -1;
- //int besti=0;
- int
- currentCommandCount = 0;
- for (unsigned int i = randomstart;
- i < producers.size () + randomstart; i++)
- {
- int
- prIndex = i;
- if (i >= producers.size ())
- {
- prIndex = (i - (int) producers.size ());
- }
- currentProducerIndex = producers[prIndex];
-
- if (currentProducerIndex >=
- aiInterface->getMyUnitCount ())
- {
- char
- szBuf[8096] = "";
- printf
- ("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,producers.size() = "
- MG_SIZE_T_SPECIFIER "\n", __FILE__, __FUNCTION__,
- __LINE__, currentProducerIndex,
- aiInterface->getMyUnitCount (), i,
- producers.size ());
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %u, i = %u,producers.size() = "
- MG_SIZE_T_SPECIFIER "", __FILE__,
- __FUNCTION__, __LINE__,
- currentProducerIndex,
- aiInterface->getMyUnitCount (), i,
- producers.size ());
- throw
- megaglest_runtime_error (szBuf);
- }
- if (prIndex >= (int) producers.size ())
- {
- char
- szBuf[8096] = "";
- printf
- ("In [%s::%s Line: %d] prIndex >= producers.size(), currentProducerIndex = %d, i = %u,producers.size() = "
- MG_SIZE_T_SPECIFIER " \n", __FILE__,
- __FUNCTION__, __LINE__, prIndex, i,
- producers.size ());
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] currentProducerIndex >= producers.size(), currentProducerIndex = %d, i = %u,producers.size() = "
- MG_SIZE_T_SPECIFIER "", __FILE__,
- __FUNCTION__, __LINE__,
- currentProducerIndex, i,
- producers.size ());
- throw
- megaglest_runtime_error (szBuf);
- }
-
- currentCommandCount =
- aiInterface->getMyUnit (currentProducerIndex)->
- getCommandSize ();
- if (currentCommandCount == 1
- && aiInterface->getMyUnit (currentProducerIndex)->
- getCurrCommand ()->getCommandType ()->getClass () ==
- ccStop)
- { // special for non buildings
- currentCommandCount = 0;
- }
- if (lowestCommandCount > currentCommandCount)
- {
- lowestCommandCount =
- aiInterface->getMyUnit (currentProducerIndex)->
- getCommandSize ();
- bestIndex = currentProducerIndex;
- //besti=i%(producers.size());
- }
- }
- if (bestIndex >= 0)
- {
- if (aiInterface->getMyUnit (bestIndex)->
- getCommandSize () > 2)
- {
- // maybe we need another producer of this kind if possible!
- if (aiInterface->
- reqsOk (aiInterface->getMyUnit (bestIndex)->
- getType ()))
- {
- if (ai->getCountOfClass (ucBuilding) > 5)
- {
- ai->
- addTask (new
- BuildTask (aiInterface->
- getMyUnit
- (bestIndex)->
- getType ()));
- }
- }
- // need to calculate another producer, maybe its better to produce another warrior with another producer
- vector < int >
- backupProducers;
- // find another producer unit which is free and produce any kind of warrior.
- //for each unit
- for (int i = 0; i < aiInterface->getMyUnitCount ();
- ++i)
- {
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- //for each command
- for (int j = 0; j < ut->getCommandTypeCount ();
- ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
- //if the command is produce
- if (ct->getClass () == ccProduce)
- {
- const UnitType *
- unitType = static_cast < const
- UnitType * >(ct->getProduced ());
- if (unitType->hasSkillClass (scAttack)
- && !unitType->
- hasCommandClass (ccHarvest)
- && aiInterface->reqsOk (ct))
- { //this can produce a warrior
- backupProducers.push_back (i);
- }
- }
- }
- }
- if (!backupProducers.empty ())
- {
- int
- randomstart =
- ai->getRandom ()->randRange (0,
- (int)
- backupProducers.
- size () - 1);
- int
- lowestCommandCount = 1000000;
- int
- currentProducerIndex =
- backupProducers[randomstart];
- int
- bestIndex = -1;
- for (unsigned int i = randomstart;
- i < backupProducers.size () + randomstart;
- i++)
- {
- int
- prIndex = i;
- if (i >= backupProducers.size ())
- {
- prIndex =
- (i - (int) backupProducers.size ());
- }
-
- currentProducerIndex =
- backupProducers[prIndex];
-
- if (currentProducerIndex >=
- aiInterface->getMyUnitCount ())
- {
- char
- szBuf[8096] = "";
- printf
- ("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,backupProducers.size() = "
- MG_SIZE_T_SPECIFIER "\n", __FILE__,
- __FUNCTION__, __LINE__,
- currentProducerIndex,
- aiInterface->getMyUnitCount (), i,
- backupProducers.size ());
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,backupProducers.size() = "
- MG_SIZE_T_SPECIFIER "",
- __FILE__, __FUNCTION__,
- __LINE__,
- currentProducerIndex,
- aiInterface->
- getMyUnitCount (), i,
- backupProducers.size ());
- throw
- megaglest_runtime_error (szBuf);
- }
- if (prIndex >=
- (int) backupProducers.size ())
- {
- char
- szBuf[8096] = "";
- printf
- ("In [%s::%s Line: %d] prIndex >= backupProducers.size(), currentProducerIndex = %d, i = %u,backupProducers.size() = "
- MG_SIZE_T_SPECIFIER " \n", __FILE__,
- __FUNCTION__, __LINE__, prIndex, i,
- backupProducers.size ());
- snprintf (szBuf, 8096,
- "In [%s::%s Line: %d] currentProducerIndex >= backupProducers.size(), currentProducerIndex = %d, i = %u,backupProducers.size() = "
- MG_SIZE_T_SPECIFIER "",
- __FILE__, __FUNCTION__,
- __LINE__,
- currentProducerIndex, i,
- backupProducers.size ());
- throw
- megaglest_runtime_error (szBuf);
- }
-
- int
- currentCommandCount =
- aiInterface->
- getMyUnit (currentProducerIndex)->
- getCommandSize ();
- if (currentCommandCount == 1
- && aiInterface->
- getMyUnit (currentProducerIndex)->
- getCurrCommand ()->getCommandType ()->
- getClass () == ccStop)
- { // special for non buildings
- currentCommandCount = 0;
- }
- if (lowestCommandCount >
- currentCommandCount)
- {
- lowestCommandCount =
- currentCommandCount;
- bestIndex = currentProducerIndex;
- if (lowestCommandCount == 0)
- break;
- }
- }
- // a good producer is found, lets choose a warrior production
- vector < int >
- productionCommandIndexes;
- if (bestIndex >= 0)
- {
- const UnitType *
- ut =
- aiInterface->getMyUnit (bestIndex)->
- getType ();
- for (int j = 0;
- j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is produce
- if (ct->getClass () == ccProduce)
- {
- const UnitType *
- unitType = static_cast < const
- UnitType * >(ct->getProduced ());
- if (unitType->
- hasSkillClass (scAttack)
- && !unitType->
- hasCommandClass (ccHarvest)
- && aiInterface->reqsOk (ct))
- { //this can produce a warrior
- productionCommandIndexes.
- push_back (j);
- }
- }
- }
-
- int
- commandIndex =
- productionCommandIndexes[ai->
- getRandom ()->
- randRange (0,
- (int)
- productionCommandIndexes.
- size
- () -
- 1)];
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__,
- __FUNCTION__,
- __LINE__);
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("zeta #1 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
- aiInterface->getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- ut->getCommandType (commandIndex)->
- getName ().c_str ());
- if (aiInterface->isLogLevelEnabled (4) ==
- true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "zeta #1 produceSpecific giveCommand to unit [%s] commandType [%s]",
- aiInterface->
- getMyUnit (bestIndex)->
- getType ()->getName ().
- c_str (),
- ut->
- getCommandType
- (commandIndex)->getName ().
- c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- aiInterface->giveCommand (bestIndex,
- ut->
- getCommandType
- (commandIndex));
- }
- }
- else
- { // do it like normal CPU
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__,
- __FUNCTION__,
- __LINE__);
- defCt = NULL;
- if (producersDefaultCommandType.
- find (bestIndex) !=
- producersDefaultCommandType.end ())
- {
- int
- bestCommandTypeCount =
- (int)
- producersDefaultCommandType[bestIndex].
- size ();
- int
- bestCommandTypeIndex =
- ai->getRandom ()->randRange (0,
- bestCommandTypeCount
- - 1);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
- __FILE__,
- __FUNCTION__,
- __LINE__,
- bestCommandTypeIndex,
- bestCommandTypeCount);
-
- defCt =
- producersDefaultCommandType[bestIndex]
- [bestCommandTypeIndex];
- }
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("zeta #2 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
- aiInterface->getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().
- c_str () : "n/a"));
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "zeta #2 produceSpecific giveCommand to unit [%s] commandType [%s]",
- aiInterface->
- getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().
- c_str () : "n/a"));
- aiInterface->printLog (4, szBuf);
- }
- aiInterface->giveCommand (bestIndex, defCt);
- }
- }
- else
- {
- if (currentCommandCount == 0)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__,
- __FUNCTION__,
- __LINE__);
- defCt = NULL;
- if (producersDefaultCommandType.
- find (bestIndex) !=
- producersDefaultCommandType.end ())
- {
- //defCt = producersDefaultCommandType[bestIndex];
- int
- bestCommandTypeCount =
- (int)
- producersDefaultCommandType[bestIndex].
- size ();
- int
- bestCommandTypeIndex =
- ai->getRandom ()->randRange (0,
- bestCommandTypeCount
- - 1);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
- __FILE__,
- __FUNCTION__,
- __LINE__,
- bestCommandTypeIndex,
- bestCommandTypeCount);
-
- defCt =
- producersDefaultCommandType[bestIndex]
- [bestCommandTypeIndex];
- }
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("zeta #3 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
- aiInterface->getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().
- c_str () : "n/a"));
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "zeta #3 produceSpecific giveCommand to unit [%s] commandType [%s]",
- aiInterface->
- getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().
- c_str () : "n/a"));
- aiInterface->printLog (4, szBuf);
- }
-
- aiInterface->giveCommand (bestIndex, defCt);
- }
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__, __FUNCTION__,
- __LINE__);
- defCt = NULL;
- if (producersDefaultCommandType.find (bestIndex) !=
- producersDefaultCommandType.end ())
- {
- //defCt = producersDefaultCommandType[bestIndex];
- int
- bestCommandTypeCount =
- (int) producersDefaultCommandType[bestIndex].
- size ();
- int
- bestCommandTypeIndex =
- ai->getRandom ()->randRange (0,
- bestCommandTypeCount
- - 1);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
- __FILE__,
- __FUNCTION__,
- __LINE__,
- bestCommandTypeIndex,
- bestCommandTypeCount);
-
- defCt =
- producersDefaultCommandType[bestIndex]
- [bestCommandTypeIndex];
- }
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("zeta #4 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
- aiInterface->getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().c_str () : "n/a"));
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "zeta #4 produceSpecific giveCommand to unit [%s] commandType [%s]",
- aiInterface->getMyUnit (bestIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().
- c_str () : "n/a"));
- aiInterface->printLog (4, szBuf);
- }
-
- aiInterface->giveCommand (bestIndex, defCt);
- }
- }
- }
- else
- {
- int
- pIndex =
- ai->getRandom ()->randRange (0,
- (int) producers.size () - 1);
- int
- producerIndex = producers[pIndex];
- defCt = NULL;
- if (producersDefaultCommandType.find (producerIndex) !=
- producersDefaultCommandType.end ())
- {
- //defCt = producersDefaultCommandType[producerIndex];
- int
- bestCommandTypeCount =
- (int) producersDefaultCommandType[producerIndex].
- size ();
- int
- bestCommandTypeIndex =
- ai->getRandom ()->randRange (0,
- bestCommandTypeCount -
- 1);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
- __FILE__, __FUNCTION__,
- __LINE__,
- bestCommandTypeIndex,
- bestCommandTypeCount);
-
- defCt =
- producersDefaultCommandType[producerIndex]
- [bestCommandTypeIndex];
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] producers.size() = %d, producerIndex = %d, pIndex = %d, producersDefaultCommandType.size() = %d\n",
- __FILE__, __FUNCTION__,
- __LINE__, producers.size (),
- producerIndex, pIndex,
- producersDefaultCommandType.
- size ());
-
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("produceSpecific giveCommand to unit [%s] commandType [%s]\n",
- aiInterface->getMyUnit (producerIndex)->getType ()->
- getName ().c_str (),
- (defCt != NULL ? defCt->getName ().c_str () : "n/a"));
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "produceSpecific giveCommand to unit [%s] commandType [%s]",
- aiInterface->getMyUnit (producerIndex)->
- getType ()->getName ().c_str (),
- (defCt !=
- NULL ? defCt->getName ().
- c_str () : "(null)"));
- aiInterface->printLog (4, szBuf);
- }
- aiInterface->giveCommand (producerIndex, defCt);
- }
- }
- }
- }
-
-// ========================================
-// class AiRuleBuild
-// ========================================
-
- AiRuleBuild::AiRuleBuild (Ai * ai):
- AiRule (ai)
- {
- buildTask = NULL;
- }
-
- bool
- AiRuleBuild::test ()
- {
- const Task *
- task = ai->getTask ();
-
- if (task == NULL || task->getClass () != tcBuild)
- {
- return false;
- }
-
- buildTask = static_cast < const BuildTask *>(task);
- return true;
- }
-
-
- void
- AiRuleBuild::execute ()
- {
- if (buildTask != NULL)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf ("BUILD AiRuleBuild Unit Name[%s]\n",
- (buildTask->getUnitType () !=
- NULL ? buildTask->getUnitType ()->getName (false).
- c_str () : "null"));
-
- //generic build task, build random building that can be built
- if (buildTask->getUnitType () == NULL)
- {
- buildGeneric (buildTask);
- }
- //specific building task, build if possible, retry if not enough resources or not position
- else
- {
- buildSpecific (buildTask);
- }
-
- //remove the task
- ai->removeTask (buildTask);
- }
- }
-
- void
- AiRuleBuild::buildGeneric (const BuildTask * bt)
- {
-
- //find buildings that can be built
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "== START: buildGeneric for resource type [%s]",
- (bt->getResourceType () !=
- NULL ? bt->getResourceType ()->getName ().
- c_str () : "null"));
- aiInterface->printLog (4, szBuf);
- }
-
- typedef
- vector < const UnitType *>
- UnitTypes;
- UnitTypes
- buildings;
-
- if (bt->getResourceType () != NULL)
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcResourceProducerUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcResourceProducerUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, true, false,
- false) == true)
- {
- //if(ai->getRandom()->randRange(0, 1)==0) {
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildGeneric for resource type [%s] aibcResourceProducerUnits = "
- MG_SIZE_T_SPECIFIER
- " priorityUnit.first: [%s]\n",
- bt->getResourceType ()->getName ().
- c_str (), unitList.size (),
- priorityUnit.first->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new BuildTask (priorityUnit.first));
- return;
- //}
- }
- }
- }
- }
- else
- {
- if (aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcBuildingUnits).size () > 0)
- {
- const
- std::vector <
- FactionType::PairPUnitTypeInt > &
- unitList =
- aiInterface->getMyFactionType ()->
- getAIBehaviorUnits (aibcBuildingUnits);
- for (unsigned int i = 0; i < unitList.size (); ++i)
- {
- const
- FactionType::PairPUnitTypeInt &
- priorityUnit = unitList[i];
- if (ai->getCountOfType (priorityUnit.first) <
- priorityUnit.second
- && aiInterface->getMyFaction ()->
- canCreateUnit (priorityUnit.first, true, false,
- false) == true)
- {
- //if(ai->getRandom()->randRange(0, 1)==0) {
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildGeneric for resource type [%s] aibcBuildingUnits = "
- MG_SIZE_T_SPECIFIER
- " priorityUnit.first: [%s]\n",
- bt->getResourceType ()->getName ().
- c_str (), unitList.size (),
- priorityUnit.first->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new BuildTask (priorityUnit.first));
- return;
- //}
- }
- }
- }
- }
-
- //for each unit
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
-
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is build
- if (ct->getClass () == ccBuild)
- {
- const BuildCommandType *
- bct = static_cast < const
- BuildCommandType * >(ct);
-
- //for each building
- for (int k = 0; k < bct->getBuildingCount (); ++k)
- {
- const UnitType *
- building = bct->getBuilding (k);
- if (aiInterface->reqsOk (bct)
- && aiInterface->reqsOk (building))
- {
-
- //if any building, or produces resource
- const ResourceType *
- rt = bt->getResourceType ();
- const Resource *
- cost = building->getCost (rt);
- if (rt == NULL
- || (cost != NULL && cost->getAmount () < 0))
- {
- if (find
- (buildings.begin (), buildings.end (),
- building) == buildings.end ())
- {
- buildings.push_back (building);
- }
- }
- }
- }
- }
- }
- }
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- for (int i = 0; i < (int) buildings.size (); ++i)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildGeneric i = %d unit type: [%s]\n", i,
- buildings[i]->getName ().c_str ());
- aiInterface->printLog (4, szBuf);
- }
- }
-
- //add specific build task
- buildBestBuilding (buildings);
- }
-
- void
- AiRuleBuild::buildBestBuilding (const vector <
- const UnitType * >&buildings)
- {
-
- AiInterface *
- aiInterface = ai->getAiInterface ();
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "==> START buildBestBuilding buildings.size = "
- MG_SIZE_T_SPECIFIER "\n", buildings.size ());
- aiInterface->printLog (4, szBuf);
- }
-
- if (!buildings.empty ())
- {
-
- //build the least built building
- bool
- buildingFound = false;
- for (int i = 0; i < 10 && !buildingFound; ++i)
- {
-
- if (i > 0)
- {
-
- //Defensive buildings have priority
- for (int j = 0;
- j < (int) buildings.size () && buildingFound == false;
- ++j)
- {
- const UnitType *
- building = buildings[j];
- if (ai->getCountOfType (building) <= i + 1
- && isDefensive (building))
- {
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildBestBuilding defensive building unit type: [%s] i = %d j = %d\n",
- building->getName ().c_str (), i, j);
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new BuildTask (building));
- buildingFound = true;
- }
- }
-
- //Warrior producers next
- for (unsigned int j = 0;
- j < buildings.size () && !buildingFound; ++j)
- {
- const UnitType *
- building = buildings[j];
- if (ai->getCountOfType (building) <= i + 1
- && isWarriorProducer (building))
- {
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildBestBuilding warriorproducer building unit type: [%s] i = %d j = %u\n",
- building->getName ().c_str (), i, j);
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new BuildTask (building));
- buildingFound = true;
- }
- }
-
- //Resource producers next
- for (unsigned int j = 0;
- j < buildings.size () && !buildingFound; ++j)
- {
- const UnitType *
- building = buildings[j];
- if (ai->getCountOfType (building) <= i + 1
- && isResourceProducer (building))
- {
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildBestBuilding resourceproducer building unit type: [%s] i = %d j = %u\n",
- building->getName ().c_str (), i, j);
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new BuildTask (building));
- buildingFound = true;
- }
- }
- }
-
- //Any building
- for (unsigned int j = 0;
- j < buildings.size () && !buildingFound; ++j)
- {
- const UnitType *
- building = buildings[j];
- if (ai->getCountOfType (building) <= i)
- {
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildBestBuilding ANY building unit type: [%s] i = %d j = %u\n",
- building->getName ().c_str (), i, j);
- aiInterface->printLog (4, szBuf);
- }
-
- ai->addTask (new BuildTask (building));
- buildingFound = true;
- }
- }
- }
- }
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "==> END buildBestBuilding buildings.size = "
- MG_SIZE_T_SPECIFIER "\n", buildings.size ());
- aiInterface->printLog (4, szBuf);
- }
- }
-
- void
- AiRuleBuild::buildSpecific (const BuildTask * bt)
- {
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "== START: buildSpecific for resource type [%s] bt->getUnitType() [%s]",
- (bt->getResourceType () !=
- NULL ? bt->getResourceType ()->getName ().
- c_str () : "null"),
- (bt->getUnitType () !=
- NULL ? bt->getUnitType ()->getName (false).
- c_str () : "null"));
- aiInterface->printLog (4, szBuf);
- }
-
- //if reqs ok
- if (aiInterface->reqsOk (bt->getUnitType ()))
- {
-
- //retry if not enough resources
- if (aiInterface->checkCosts (bt->getUnitType (), NULL) == false)
- {
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildSpecific for resource type [%s] checkcosts == false RETRYING",
- (bt->getResourceType () !=
- NULL ? bt->getResourceType ()->getName ().
- c_str () : "null"));
- aiInterface->printLog (4, szBuf);
- }
-
- ai->retryTask (bt);
- return;
- }
-
- vector < int >
- builders;
- // Hold a list of units which can build
- // then a list of build commandtypes for each unit
- map < int,
- vector < const BuildCommandType *> >
- buildersDefaultCommandType;
- const BuildCommandType *
- defBct = NULL;
-
- //for each unit
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
-
- //if the unit is not going to build
- const Unit *
- u = aiInterface->getMyUnit (i);
- if (u->anyCommand () == false
- || u->getCurrCommand ()->getCommandType ()->getClass () !=
- ccBuild)
- {
-
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is build
- if (ct->getClass () == ccBuild)
- {
- const BuildCommandType *
- bct = static_cast < const
- BuildCommandType * >(ct);
-
- //for each building
- for (int k = 0; k < bct->getBuildingCount (); ++k)
- {
- const UnitType *
- building = bct->getBuilding (k);
-
- //if building match
- if (bt->getUnitType () == building)
- {
- if (aiInterface->reqsOk (bct))
- {
- builders.push_back (i);
- buildersDefaultCommandType[i].
- push_back (bct);
- //defBct= bct;
- }
- }
- }
- }
- }
- }
- }
-
- //use random builder to build
- if (builders.empty () == false)
- {
- int
- bIndex =
- ai->getRandom ()->randRange (0, (int) builders.size () - 1);
- int
- builderIndex = builders[bIndex];
- Vec2i
- pos;
- Vec2i
- searchPos =
- bt->getForcePos ()? bt->getPos () : ai->
- getRandomHomePosition ();
- if (bt->getForcePos () == false)
- {
- const int
- enemySightDistanceToAvoid = 18;
- vector < Unit * >enemies;
- ai->getAiInterface ()->getWorld ()->getUnitUpdater ()->
- findEnemiesForCell (searchPos,
- bt->getUnitType ()->getSize (),
- enemySightDistanceToAvoid,
- ai->getAiInterface ()->
- getMyFaction (), enemies, true);
- if (enemies.empty () == false)
- {
- for (int i1 = 0; i1 < 25 && enemies.empty () == false;
- ++i1)
- {
- for (int j1 = 0;
- j1 < 25 && enemies.empty () == false; ++j1)
- {
- Vec2i
- tryPos = searchPos + Vec2i (i1, j1);
-
- const int
- spacing = 1;
- if (ai->getAiInterface ()->
- isFreeCells (tryPos - Vec2i (spacing),
- bt->getUnitType ()->
- getSize () + spacing * 2,
- fLand))
- {
- enemies.clear ();
- ai->getAiInterface ()->getWorld ()->
- getUnitUpdater ()->
- findEnemiesForCell (tryPos,
- bt->getUnitType ()->
- getSize (),
- enemySightDistanceToAvoid,
- ai->
- getAiInterface ()->
- getMyFaction (),
- enemies, true);
- if (enemies.empty () == true)
- {
- searchPos = tryPos;
- }
- }
- }
- }
- }
- if (enemies.empty () == false)
- {
- for (int i1 = -1;
- i1 >= -25 && enemies.empty () == false; --i1)
- {
- for (int j1 = -1;
- j1 >= -25 && enemies.empty () == false; --j1)
- {
- Vec2i
- tryPos = searchPos + Vec2i (i1, j1);
-
- const int
- spacing = 1;
- if (ai->getAiInterface ()->
- isFreeCells (tryPos - Vec2i (spacing),
- bt->getUnitType ()->
- getSize () + spacing * 2,
- fLand))
- {
- enemies.clear ();
- ai->getAiInterface ()->getWorld ()->
- getUnitUpdater ()->
- findEnemiesForCell (tryPos,
- bt->getUnitType ()->
- getSize (),
- enemySightDistanceToAvoid,
- ai->
- getAiInterface ()->
- getMyFaction (),
- enemies, true);
- if (enemies.empty () == true)
- {
- searchPos = tryPos;
- }
- }
- }
- }
- }
- }
-
- //if free pos give command, else retry
- if (ai->findPosForBuilding (bt->getUnitType (), searchPos, pos))
- {
- defBct = NULL;
- if (buildersDefaultCommandType.find (builderIndex) !=
- buildersDefaultCommandType.end ())
- {
- //defBct = buildersDefaultCommandType[builderIndex];
- int
- bestCommandTypeCount =
- (int) buildersDefaultCommandType[builderIndex].
- size ();
- int
- bestCommandTypeIndex =
- ai->getRandom ()->randRange (0,
- bestCommandTypeCount -
- 1);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
- __FILE__, __FUNCTION__,
- __LINE__,
- bestCommandTypeIndex,
- bestCommandTypeCount);
-
- defBct =
- buildersDefaultCommandType[builderIndex]
- [bestCommandTypeIndex];
- }
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d] builderIndex = %d, bIndex = %d, defBct = %p\n",
- __FILE__, __FUNCTION__,
- __LINE__, builderIndex, bIndex,
- defBct);
-
- aiInterface->giveCommand (builderIndex, defBct, pos,
- bt->getUnitType ());
- }
- else
- {
- ai->retryTask (bt);
- return;
- }
- }
- }
- else
- {
- if (aiInterface->isLogLevelEnabled (4) == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In buildSpecific for resource type [%s] reqsok == false",
- (bt->getResourceType () !=
- NULL ? bt->getResourceType ()->getName ().
- c_str () : "null"));
- aiInterface->printLog (4, szBuf);
- }
-
- }
- }
-
- bool
- AiRuleBuild::isDefensive (const UnitType * building)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf ("BUILD isDefensive check for Unit Name[%s] result = %d\n",
- building->getName (false).c_str (),
- building->hasSkillClass (scAttack));
-
- return building->hasSkillClass (scAttack);
- }
-
- bool
- AiRuleBuild::isResourceProducer (const UnitType * building)
- {
- for (int i = 0; i < building->getCostCount (); i++)
- {
- if (building->getCost (i)->getAmount () < 0)
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("BUILD isResourceProducer check for Unit Name[%s] result = true\n",
- building->getName (false).c_str ());
-
- return true;
- }
- }
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("BUILD isResourceProducer check for Unit Name[%s] result = false\n",
- building->getName (false).c_str ());
-
- return false;
- }
-
- bool
- AiRuleBuild::isWarriorProducer (const UnitType * building)
- {
- for (int i = 0; i < building->getCommandTypeCount (); i++)
- {
- const CommandType *
- ct = building->getCommandType (i);
- if (ct->getClass () == ccProduce)
- {
- const UnitType *
- ut = static_cast < const
- ProduceCommandType * >(ct)->
- getProducedUnit ();
-
- if (ut->isOfClass (ucWarrior))
- {
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("BUILD isWarriorProducer check for Unit Name[%s] result = true\n",
- building->getName (false).c_str ());
-
- return true;
- }
- }
- }
- if (ai->outputAIBehaviourToConsole ())
- printf
- ("BUILD isWarriorProducer check for Unit Name[%s] result = false\n",
- building->getName (false).c_str ());
-
- return false;
- }
-
-// ========================================
-// class AiRuleUpgrade
-// ========================================
-
- AiRuleUpgrade::AiRuleUpgrade (Ai * ai):
- AiRule (ai)
- {
- upgradeTask = NULL;
- }
-
- bool
- AiRuleUpgrade::test ()
- {
- const Task *
- task = ai->getTask ();
-
- if (task == NULL || task->getClass () != tcUpgrade)
- {
- return false;
- }
-
- upgradeTask = static_cast < const UpgradeTask *>(task);
- return true;
- }
-
- void
- AiRuleUpgrade::execute ()
- {
-
- //upgrade any upgrade
- if (upgradeTask->getUpgradeType () == NULL)
- {
- upgradeGeneric (upgradeTask);
- }
- //upgrade specific upgrade
- else
- {
- upgradeSpecific (upgradeTask);
- }
-
- //remove the task
- ai->removeTask (upgradeTask);
- }
-
- void
- AiRuleUpgrade::upgradeGeneric (const UpgradeTask * upgt)
- {
-
- typedef
- vector < const UpgradeType *>
- UpgradeTypes;
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- //find upgrades that can be upgraded
- UpgradeTypes
- upgrades;
-
- if (aiInterface->getMyFactionType ()->getAIBehaviorUpgrades ().size () >
- 0)
- {
- const
- std::vector < const UpgradeType *>&
- upgradeList =
- aiInterface->getMyFactionType ()->getAIBehaviorUpgrades ();
- for (unsigned int i = 0; i < upgradeList.size (); ++i)
- {
- const UpgradeType *
- priorityUpgrade = upgradeList[i];
-
- //for each upgrade, upgrade it if possible
- for (int k = 0; k < aiInterface->getMyUnitCount (); ++k)
- {
-
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (k)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is upgrade
- if (ct->getClass () == ccUpgrade)
- {
- const UpgradeCommandType *
- upgct = dynamic_cast < const
- UpgradeCommandType * >(ct);
- if (upgct != NULL)
- {
- const UpgradeType *
- upgrade = upgct->getProducedUpgrade ();
- if (upgrade == priorityUpgrade)
- {
- if (aiInterface->reqsOk (upgct) == true &&
- aiInterface->getMyFaction ()->
- getUpgradeManager ()->
- isUpgradingOrUpgraded (priorityUpgrade)
- == false)
- {
- //if(ai->getRandom()->randRange(0, 1)==0) {
- ai->
- addTask (new
- UpgradeTask
- (priorityUpgrade));
- return;
- //}
- }
- }
- }
- }
- }
- }
- }
- }
-
- //for each upgrade, upgrade it if possible
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
-
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is upgrade
- if (ct->getClass () == ccUpgrade)
- {
- const UpgradeCommandType *
- upgct = static_cast < const
- UpgradeCommandType * >(ct);
- const UpgradeType *
- upgrade = upgct->getProducedUpgrade ();
- if (aiInterface->reqsOk (upgct))
- {
- upgrades.push_back (upgrade);
- }
- }
- }
- }
-
- //add specific upgrade task
- if (!upgrades.empty ())
- {
- ai->
- addTask (new
- UpgradeTask (upgrades
- [ai->getRandom ()->
- randRange (0,
- (int) upgrades.size () - 1)]));
- }
- }
-
- void
- AiRuleUpgrade::upgradeSpecific (const UpgradeTask * upgt)
- {
-
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- //if reqs ok
- if (aiInterface->reqsOk (upgt->getUpgradeType ()))
- {
-
- //if resources dont meet retry
- if (!aiInterface->checkCosts (upgt->getUpgradeType (), NULL))
- {
- ai->retryTask (upgt);
- return;
- }
-
- //for each unit
- for (int i = 0; i < aiInterface->getMyUnitCount (); ++i)
- {
-
- //for each command
- const UnitType *
- ut = aiInterface->getMyUnit (i)->getType ();
- for (int j = 0; j < ut->getCommandTypeCount (); ++j)
- {
- const CommandType *
- ct = ut->getCommandType (j);
-
- //if the command is upgrade
- if (ct->getClass () == ccUpgrade)
- {
- const UpgradeCommandType *
- uct = static_cast < const
- UpgradeCommandType * >(ct);
- const UpgradeType *
- producedUpgrade = uct->getProducedUpgrade ();
-
- //if upgrades match
- if (producedUpgrade == upgt->getUpgradeType ())
- {
- if (aiInterface->reqsOk (uct))
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugSystem).enabled)
- SystemFlags::OutputDebug (SystemFlags::
- debugSystem,
- "In [%s::%s Line: %d]\n",
- __FILE__,
- __FUNCTION__,
- __LINE__);
- aiInterface->giveCommand (i, uct);
- }
- }
- }
- }
- }
-
- }
- }
-
-// ========================================
-// class AiRuleExpand
-// ========================================
-
- AiRuleExpand::AiRuleExpand (Ai * ai):
- AiRule (ai)
- {
- storeType = NULL;
- }
-
- bool
- AiRuleExpand::test ()
- {
- AiInterface *
- aiInterface = ai->getAiInterface ();
-
- int
- unitCount = aiInterface->getMyUnitCount ();
- for (int i = 0;
- i < aiInterface->getTechTree ()->getResourceTypeCount (); ++i)
- {
- const ResourceType *
- rt = aiInterface->getTechTree ()->getResourceType (i);
- if (rt->getClass () == rcTech)
- {
- bool
- factionUsesResourceType =
- aiInterface->factionUsesResourceType (aiInterface->
- getMyFactionType (),
- rt);
- if (factionUsesResourceType == true)
- {
- // If any resource sighted
- if (aiInterface->
- getNearestSightedResource (rt,
- aiInterface->
- getHomeLocation (),
- expandPos, true))
- {
- int
- minDistance = INT_MAX;
- storeType = NULL;
-
- //If there is no close store
- for (int j = 0; j < unitCount; ++j)
- {
- const Unit *
- u = aiInterface->getMyUnit (j);
- const UnitType *
- ut = u->getType ();
-
- // If this building is a store
- if (ut->getStore (rt) > 0)
- {
- storeType = ut;
- int
- distance =
- static_cast <
- int >(u->getPosNotThreadSafe ().
- dist (expandPos));
- if (distance < minDistance)
- {
- minDistance = distance;
- }
- }
- }
-
- if (minDistance > expandDistance)
- {
- return true;
- }
- }
- else
- {
- // send patrol to look for resource
- ai->sendScoutPatrol ();
- }
- }
- }
- }
-
- return false;
- }
-
- void
- AiRuleExpand::execute ()
- {
- ai->addExpansion (expandPos);
- ai->addPriorityTask (new BuildTask (storeType, expandPos));
- }
-
-
-// ========================================
-// class AiRuleUnBlock
-// ========================================
-
- AiRuleUnBlock::AiRuleUnBlock (Ai * ai):
- AiRule (ai)
- {
-
- }
-
- bool
- AiRuleUnBlock::test ()
- {
- return ai->haveBlockedUnits ();
- }
-
- void
- AiRuleUnBlock::execute ()
- {
- ai->unblockUnits ();
- }
-
-}} //end namespace
+ Glest {
+ namespace
+ Game {
+
+ // =====================================================
+ // class AiRule
+ // =====================================================
+
+ AiRule::AiRule(Ai * ai) {
+ this->ai = ai;
+ }
+
+ // =====================================================
+ // class AiRuleWorkerHarvest
+ // =====================================================
+
+ AiRuleWorkerHarvest::AiRuleWorkerHarvest(Ai * ai) :
+ AiRule(ai) {
+ stoppedWorkerIndex = -1;
+ }
+
+ bool
+ AiRuleWorkerHarvest::test() {
+ return ai->findAbleUnit(&stoppedWorkerIndex, ccHarvest, true);
+ }
+
+ void
+ AiRuleWorkerHarvest::execute() {
+ ai->harvest(stoppedWorkerIndex);
+ }
+
+ // =====================================================
+ // class AiRuleRefreshHarvester
+ // =====================================================
+
+ AiRuleRefreshHarvester::AiRuleRefreshHarvester(Ai * ai) :
+ AiRule(ai) {
+ workerIndex = -1;
+ }
+
+ bool
+ AiRuleRefreshHarvester::test() {
+ return ai->findAbleUnit(&workerIndex, ccHarvest, ccHarvest);
+ }
+
+ void
+ AiRuleRefreshHarvester::execute() {
+ ai->harvest(workerIndex);
+ }
+
+ // =====================================================
+ // class AiRuleScoutPatrol
+ // =====================================================
+
+ AiRuleScoutPatrol::AiRuleScoutPatrol(Ai * ai) :
+ AiRule(ai) {
+ }
+
+ bool
+ AiRuleScoutPatrol::test() {
+ return ai->isStableBase();
+ }
+
+ void
+ AiRuleScoutPatrol::execute() {
+ ai->sendScoutPatrol();
+ }
+ // =====================================================
+ // class AiRuleRepair
+ // =====================================================
+
+ AiRuleRepair::AiRuleRepair(Ai * ai) :
+ AiRule(ai) {
+ damagedUnitIndex = 0;
+ damagedUnitIsCastle = false;
+ }
+
+ double
+ AiRuleRepair::getMinCastleHpRatio() const {
+ return
+ 0.6;
+ }
+
+ int
+ AiRuleRepair::getMinUnitsToRepairCastle() {
+ int
+ minUnitsRepairingCastle = 7;
+ if (ai->getCountOfClass(ucWorker) <= 6) {
+ minUnitsRepairingCastle = 1;
+ } else if (ai->getCountOfClass(ucWorker) <= 8) {
+ minUnitsRepairingCastle = 2;
+ } else if (ai->getCountOfClass(ucWorker) <= 10) {
+ minUnitsRepairingCastle = 3;
+ } else if (ai->getCountOfClass(ucWorker) <= 12) {
+ minUnitsRepairingCastle = 5;
+ }
+ return minUnitsRepairingCastle;
+ }
+
+ bool
+ AiRuleRepair::test() {
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ int
+ minUnitsRepairingCastle = getMinUnitsToRepairCastle();
+ const double
+ minCastleHpRatio = getMinCastleHpRatio();
+
+ // look for a damaged unit and give priority to the factions bases
+ // (units that produce workers and store resources)
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ const Unit *
+ u = aiInterface->getMyUnit(i);
+ //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade()));
+ if (u->getHpRatio() < 1.f) {
+ //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade()));
+
+ bool
+ unitCanProduceWorker = false;
+ for (int j = 0; unitCanProduceWorker == false &&
+ j < u->getType()->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = u->getType()->getCommandType(j);
+
+ //if the command is produce
+ if (ct->getClass() == ccProduce
+ || ct->getClass() == ccMorph) {
+ const ProducibleType *
+ pt = ct->getProduced();
+ if (pt != NULL) {
+ const UnitType *
+ ut = dynamic_cast (pt);
+ if (ut != NULL
+ && ut->hasCommandClass(ccHarvest) == true
+ && u->getType()->getStoredResourceCount() > 0) {
+ //printf("\n\n\n\n!!!!!! found candidate castle unit to repair [%d - %s]\n",u->getId(),u->getType()->getName().c_str());
+ unitCanProduceWorker = true;
+ }
+ }
+ }
+ }
+
+ if (unitCanProduceWorker == true) {
+ int
+ candidatedamagedUnitIndex = -1;
+ int
+ unitCountAlreadyRepairingDamagedUnit = 0;
+ // Now check if any other unit is able to repair this unit
+ for (int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) {
+ const Unit *
+ u1 = aiInterface->getMyUnit(i1);
+ const RepairCommandType *
+ rct = static_cast (u1->getType()->getFirstCtOfClass(ccRepair));
+ //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()));
+
+ if (rct != NULL) {
+ //printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio());
+
+ if (u1->getCurrSkill()->getClass() == scStop
+ || u1->getCurrSkill()->getClass() == scMove
+ || u->getHpRatio() <= minCastleHpRatio) {
+ if (rct->isRepairableUnitType(u->getType())) {
+ candidatedamagedUnitIndex = i;
+ //return true;
+ }
+ } else if (u1->getCurrSkill()->getClass() ==
+ scRepair) {
+ Command *
+ cmd = u1->getCurrCommand();
+ if (cmd != NULL
+ && cmd->getCommandType()->getClass() ==
+ ccRepair) {
+ if (cmd->getUnit() != NULL
+ && cmd->getUnit()->getId() ==
+ u->getId()) {
+ //printf("\n\n\n\n^^^^^^^^^^ unit is ALREADY repairer unit [%d - %s]\n",u1->getId(),u1->getType()->getName().c_str());
+ unitCountAlreadyRepairingDamagedUnit++;
+ }
+ }
+ }
+ }
+ }
+
+ if (candidatedamagedUnitIndex >= 0
+ && unitCountAlreadyRepairingDamagedUnit <
+ minUnitsRepairingCastle) {
+ //printf("\n\n\n\n^^^^^^^^^^ AI test will repair damaged unit [%d - %s]\n",u->getId(),u->getType()->getName().c_str());
+ damagedUnitIndex = candidatedamagedUnitIndex;
+ damagedUnitIsCastle = true;
+ return true;
+ }
+ }
+ }
+ }
+ damagedUnitIsCastle = false;
+ damagedUnitIndex = -1;
+ // Normal Repair checking
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ const Unit *
+ u = aiInterface->getMyUnit(i);
+ //printf("\n\n\n\n!!!!!! Is damaged unit [%d - %s] u->getHpRatio() = %f, hp = %d, mapHp = %d\n",u->getId(),u->getType()->getName().c_str(),u->getHpRatio(),u->getHp(),u->getType()->getTotalMaxHp(u->getTotalUpgrade()));
+ if (u->getHpRatio() < 1.f) {
+ // Now check if any other unit is able to repair this unit
+ for (int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) {
+ const Unit *
+ u1 = aiInterface->getMyUnit(i1);
+ const RepairCommandType *
+ rct = static_cast (u1->getType()->getFirstCtOfClass(ccRepair));
+ //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()));
+
+ if (rct != NULL
+ && (u1->getCurrSkill()->getClass() == scStop
+ || u1->getCurrSkill()->getClass() == scMove)) {
+ if (rct->isRepairableUnitType(u->getType())) {
+ damagedUnitIndex = i;
+ //random if return or not so we get different targets from time to time
+ if (ai->getRandom()->randRange(0, 1) == 0)
+ return true;
+ }
+ }
+ }
+ }
+ }
+ if (damagedUnitIndex != -1) {
+ return true;
+ }
+ return false;
+ }
+
+ void
+ AiRuleRepair::execute() {
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+ const Unit *
+ damagedUnit = aiInterface->getMyUnit(damagedUnitIndex);
+ //printf("\n\n\n\n###^^^^^^^^^^ Looking for repairer for damaged unit [%d - %s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str());
+
+ int
+ minUnitsRepairingCastle = getMinUnitsToRepairCastle();
+ const double
+ minCastleHpRatio = getMinCastleHpRatio();
+
+ if (minUnitsRepairingCastle > 2) {
+ if (damagedUnit->getCurrSkill()->getClass() == scBeBuilt) { // if build is still be build 2 helpers are enough
+ minUnitsRepairingCastle = 2;
+ }
+
+ if (!damagedUnitIsCastle) {
+ minUnitsRepairingCastle = 2;
+ }
+ }
+ if (aiInterface->getControlType() == ctCpuEasy ||
+ aiInterface->getControlType() == ctNetworkCpuEasy) {
+ if (!damagedUnitIsCastle) {
+ // cpu easy does not repair!
+ minUnitsRepairingCastle = 0;
+ }
+ }
+ if (aiInterface->getControlType() == ctCpu ||
+ aiInterface->getControlType() == ctNetworkCpu) {
+ if (!damagedUnitIsCastle) {
+ // cpu does only repair with one unit!
+ minUnitsRepairingCastle = 1;
+ }
+ }
+ int
+ unitCountAlreadyRepairingDamagedUnit = 0;
+ //printf("team %d has damaged unit\n", damagedUnit->getTeam());
+ // Now check if any other unit is able to repair this unit
+ for (int i1 = 0; i1 < aiInterface->getMyUnitCount(); ++i1) {
+ const Unit *
+ u1 = aiInterface->getMyUnit(i1);
+ const RepairCommandType *
+ rct = static_cast (u1->getType()->getFirstCtOfClass(ccRepair));
+ //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u1->getType()));
+ Command *
+ cmd = u1->getCurrCommand();
+ if (cmd != NULL && cmd->getCommandType()->getClass() == ccRepair) {
+ //if(cmd->getUnit() != NULL && cmd->getUnit()->getId() == damagedUnit->getId())
+ //if(cmd->getUnit() != NULL && cmd->getPos() == damagedUnit->getPosWithCellMapSet())
+
+ if (rct != NULL) {
+ //printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u1->getId(),u1->getType()->getName().c_str(),u1->getCurrSkill()->getClass(),rct->isRepairableUnitType(u->getType()),u->getHpRatio());
+
+ if (((RepairCommandType *) (cmd->getCommandType()))->
+ isRepairableUnitType(damagedUnit->getType())) {
+ //printf("^^^^test^^^^^^ unit is ALREADY repairer unit [%d - %s]\nminUnitsRepairingCastle=%d\n",u1->getId(), u1->getType()->getName().c_str(), minUnitsRepairingCastle);
+ unitCountAlreadyRepairingDamagedUnit++;
+ }
+ }
+ }
+ }
+
+ if (unitCountAlreadyRepairingDamagedUnit >= minUnitsRepairingCastle) {
+ return;
+ }
+
+ int
+ unitGroupCommandId = -1;
+
+ //find a repairer and issue command
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ const Unit *
+ u = aiInterface->getMyUnit(i);
+ const RepairCommandType *
+ rct = static_cast (u->getType()->getFirstCtOfClass(ccRepair));
+ //if(rct) printf("\n\n\n\n^^^^^^^^^^ possible repairer unit [%d - %s] current skill [%d] can reapir damaged unit [%d]\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType()));
+
+ if (rct != NULL) {
+ //printf("\n\n\n\n^^^^^^^^^^ possible excute repairer unit [%d - %s] current skill [%d] can repair damaged unit [%d] Castles hp-ratio = %f\n",u->getId(),u->getType()->getName().c_str(),u->getCurrSkill()->getClass(),rct->isRepairableUnitType(damagedUnit->getType()),damagedUnit->getHpRatio());
+
+ if ((u->getCurrSkill()->getClass() == scStop
+ || u->getCurrSkill()->getClass() == scMove
+ || damagedUnit->getHpRatio() <= minCastleHpRatio)) {
+ if ((u->getCurrCommand() == NULL
+ || (u->getCurrCommand()->getCommandType()->
+ getClass() != ccBuild
+ && u->getCurrCommand()->getCommandType()->
+ getClass() != ccProduce))
+ && rct->isRepairableUnitType(damagedUnit->getType())) {
+ //if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
+ //printf("\n\n\n\n^^^^^^^^^^ AI execute will repair damaged unit [%d - %s] at pos [%s] cellmapPos [%s] using unit [%d -%s]\n",damagedUnit->getId(),damagedUnit->getType()->getName().c_str(),damagedUnit->getPos().getString().c_str(),damagedUnit->getPosWithCellMapSet().getString().c_str(),u->getId(),u->getType()->getName().c_str());
+
+ /*
+ Map *map= aiInterface->getWorld()->getMap();
+ Cell *cell = map->getCell(damagedUnit->getPosWithCellMapSet());
+ if(cell != NULL) {
+ printf("\n\n\n\n^^^^^^^^^^ cell is ok\n");
+
+ Unit *cellUnit = cell->getUnit(damagedUnit->getCurrField());
+ if(cellUnit != NULL) {
+ printf("\n\n\n\n^^^^^^^^^^ cell unit [%d - %s] at pos [%s]\n",cellUnit->getId(),cellUnit->getType()->getName().c_str(),cellUnit->getPos().getString().c_str());
+ }
+ }
+ */
+
+ //aiInterface->giveCommand(i, rct, damagedUnit->getPos());
+ if (unitCountAlreadyRepairingDamagedUnit <
+ minUnitsRepairingCastle) {
+
+ if (unitGroupCommandId == -1) {
+ unitGroupCommandId =
+ aiInterface->getWorld()->
+ getNextCommandGroupId();
+ }
+
+ aiInterface->giveCommand(i, rct,
+ damagedUnit->
+ getPosWithCellMapSet(),
+ unitGroupCommandId);
+ if (aiInterface->isLogLevelEnabled(3) == true)
+ aiInterface->printLog(3,
+ "Repairing order issued");
+ unitCountAlreadyRepairingDamagedUnit++;
+ // printf(
+ // "^^^^^^^^^^adding one unit to repair ... unitCountAlreadyRepairingDamagedUnit/minUnitsRepairingCastle=%d/%d\n",
+ // unitCountAlreadyRepairingDamagedUnit, minUnitsRepairingCastle);
+ }
+
+ if (!damagedUnitIsCastle
+ || unitCountAlreadyRepairingDamagedUnit >=
+ minUnitsRepairingCastle) {
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // =====================================================
+ // class AiRuleReturnBase
+ // =====================================================
+
+ AiRuleReturnBase::AiRuleReturnBase(Ai * ai) :
+ AiRule(ai) {
+ stoppedUnitIndex = -1;
+ }
+
+ bool
+ AiRuleReturnBase::test() {
+ return ai->findAbleUnit(&stoppedUnitIndex, ccMove, true);
+ }
+
+ void
+ AiRuleReturnBase::execute() {
+ ai->returnBase(stoppedUnitIndex);
+ }
+
+ // =====================================================
+ // class AiRuleMassiveAttack
+ // =====================================================
+
+ AiRuleMassiveAttack::AiRuleMassiveAttack(Ai * ai) :
+ AiRule(ai) {
+ ultraAttack = false;
+ field = fLand;
+ }
+
+ bool
+ AiRuleMassiveAttack::test() {
+
+ if (ai->isStableBase()) {
+ ultraAttack = false;
+ return ai->beingAttacked(attackPos, field, INT_MAX);
+ } else {
+ ultraAttack = true;
+ return ai->beingAttacked(attackPos, field, baseRadius);
+ }
+ }
+
+ void
+ AiRuleMassiveAttack::execute() {
+ ai->massiveAttack(attackPos, field, ultraAttack);
+ }
+ // =====================================================
+ // class AiRuleAddTasks
+ // =====================================================
+
+ AiRuleAddTasks::AiRuleAddTasks(Ai * ai) :
+ AiRule(ai) {
+ }
+
+ bool
+ AiRuleAddTasks::test() {
+ return !ai->anyTask() || ai->getCountOfClass(ucWorker) < 4;
+ }
+
+ // This function is what triggers the AI to create new units.
+ void
+ AiRuleAddTasks::execute() {
+ int
+ buildingCount = ai->getCountOfClass(ucBuilding);
+ UnitClass
+ ucWorkerType = ucWorker;
+ int
+ warriorCount = ai->getCountOfClass(ucWarrior, &ucWorkerType);
+ int
+ workerCount = ai->getCountOfClass(ucWorker);
+ int
+ upgradeCount = ai->getAiInterface()->getMyUpgradeCount();
+
+ float
+ buildingRatio = ai->getRatioOfClass(ucBuilding);
+ float
+ warriorRatio = ai->getRatioOfClass(ucWarrior);
+ float
+ workerRatio = ai->getRatioOfClass(ucWorker);
+
+ //standard tasks
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("Add a TASK - AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = %d, RULE Name[%s]\n",
+ workerCount, this->getName().c_str());
+
+ //emergency workers
+ if (workerCount < 4) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("AAA AiRuleAddTasks adding ProduceTask(ucWorker) workerCount = %d, RULE Name[%s]\n",
+ workerCount, this->getName().c_str());
+
+ ai->addPriorityTask(new ProduceTask(ucWorker));
+ }
+ // The following rules are specific creation rules for different AI.
+ else {
+ if (ai->getAiInterface()->getControlType() == ctCpuZeta ||
+ ai->getAiInterface()->getControlType() == ctNetworkCpuZeta) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("AAA AiRuleAddTasks adding #1 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n",
+ workerCount, workerRatio, buildingCount, buildingRatio,
+ warriorCount, warriorRatio, upgradeCount,
+ this->getName().c_str());
+
+ //workers
+ if (workerCount < 5)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerCount < 100)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerRatio < 0.20)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerRatio < 0.30)
+ ai->addTask(new ProduceTask(ucWorker));
+
+ //warriors
+ if (warriorCount < 10)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorRatio < 0.20)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorRatio < 0.30)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (workerCount >= 10)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (workerCount >= 15)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorCount < ai->getMinWarriors() + 2) {
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (buildingCount > 9) {
+ ai->addTask(new ProduceTask(ucWarrior));
+ ai->addTask(new ProduceTask(ucWarrior));
+ }
+ if (buildingCount > 12) {
+ ai->addTask(new ProduceTask(ucWarrior));
+ ai->addTask(new ProduceTask(ucWarrior));
+ }
+ }
+
+ //buildings
+ if (buildingCount < 6 || buildingRatio < 0.20)
+ ai->addTask(new BuildTask((UnitType *) NULL));
+ if (buildingCount < 10 && workerCount > 12)
+ ai->addTask(new BuildTask((UnitType *) NULL));
+ //upgrades
+ if (upgradeCount == 0 && workerCount > 5)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (upgradeCount == 1 && workerCount > 10)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (upgradeCount == 2 && workerCount > 15)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (ai->isStableBase())
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ } else if (ai->getAiInterface()->getControlType() == ctCpuEasy ||
+ ai->getAiInterface()->getControlType() ==
+ ctNetworkCpuEasy) { // Easy CPU
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("AAA AiRuleAddTasks adding #2 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n",
+ workerCount, workerRatio, buildingCount, buildingRatio,
+ warriorCount, warriorRatio, upgradeCount,
+ this->getName().c_str());
+
+ //workers
+ if (workerCount < buildingCount + 2)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerCount > 5 && workerRatio < 0.20)
+ ai->addTask(new ProduceTask(ucWorker));
+
+ //warriors
+ if (warriorCount < 10)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorRatio < 0.20)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorRatio < 0.30)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (workerCount >= 10)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (workerCount >= 15)
+ ai->addTask(new ProduceTask(ucWarrior));
+
+ //buildings
+ if (buildingCount < 6 || buildingRatio < 0.20)
+ ai->addTask(new BuildTask((UnitType *) NULL));
+ if (buildingCount < 10 && ai->isStableBase())
+ ai->addTask(new BuildTask((UnitType *) NULL));
+
+ //upgrades
+ if (upgradeCount == 0 && workerCount > 6)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (upgradeCount == 1 && workerCount > 7)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (upgradeCount == 2 && workerCount > 9)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ //if(ai->isStableBase()) ai->addTask(new UpgradeTask());
+ } else { // normal CPU / UltraCPU ...
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("AAA AiRuleAddTasks adding #3 workerCount = %d[%.2f], buildingCount = %d[%.2f] warriorCount = %d[%.2f] upgradeCount = %d RULE Name[%s]\n",
+ workerCount, workerRatio, buildingCount, buildingRatio,
+ warriorCount, warriorRatio, upgradeCount,
+ this->getName().c_str());
+
+ //workers
+ if (workerCount < 5)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerCount < 10)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerRatio < 0.20)
+ ai->addTask(new ProduceTask(ucWorker));
+ if (workerRatio < 0.30)
+ ai->addTask(new ProduceTask(ucWorker));
+
+ //warriors
+ if (warriorCount < 10)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorRatio < 0.20)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (warriorRatio < 0.30)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (workerCount >= 10)
+ ai->addTask(new ProduceTask(ucWarrior));
+ if (workerCount >= 15)
+ ai->addTask(new ProduceTask(ucWarrior));
+
+ //buildings
+ if (buildingCount < 6 || buildingRatio < 0.20)
+ ai->addTask(new BuildTask((UnitType *) NULL));
+ if (buildingCount < 10 && workerCount > 12)
+ ai->addTask(new BuildTask((UnitType *) NULL));
+
+ //upgrades
+ if (upgradeCount == 0 && workerCount > 5)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (upgradeCount == 1 && workerCount > 10)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (upgradeCount == 2 && workerCount > 15)
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ if (ai->isStableBase())
+ ai->addTask(new UpgradeTask((const UpgradeType *) NULL));
+ }
+ }
+ }
+
+ // =====================================================
+ // class AiRuleBuildOneFarm
+ // =====================================================
+
+ AiRuleBuildOneFarm::AiRuleBuildOneFarm(Ai * ai) :
+ AiRule(ai) {
+ farm = NULL;
+ }
+
+ bool
+ AiRuleBuildOneFarm::test() {
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ //for all units
+ for (int i = 0;
+ i < aiInterface->getMyFactionType()->getUnitTypeCount(); ++i) {
+ const UnitType *
+ ut = aiInterface->getMyFactionType()->getUnitType(i);
+
+ //for all production commands
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+ if (ct->getClass() == ccProduce) {
+ const UnitType *
+ producedType = static_cast (ct)->
+ getProducedUnit();
+
+ //for all resources
+ for (int k = 0; k < producedType->getCostCount(); ++k) {
+ const Resource *
+ r = producedType->getCost(k);
+
+ //find a food producer in the farm produced units
+ if (r->getAmount() < 0
+ && r->getType()->getClass() == rcConsumable
+ && ai->getCountOfType(ut) == 0) {
+ if (aiInterface->reqsOk(ct)
+ && aiInterface->getMyFaction()->
+ canCreateUnit(ut, true, true, true) == true) {
+ farm = ut;
+ //printf("AiRuleBuildOneFarm returning true, RULE Name[%s] ut [%s] producedType [%s]\n",this->getName().c_str(),ut->getName().c_str(),producedType->getName().c_str());
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("AiRuleBuildOneFarm returning true, RULE Name[%s]\n",
+ this->getName().c_str());
+
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ void
+ AiRuleBuildOneFarm::execute() {
+ ai->addPriorityTask(new BuildTask(farm));
+ }
+
+ // =====================================================
+ // class AiRuleProduceResourceProducer
+ // =====================================================
+
+ AiRuleProduceResourceProducer::AiRuleProduceResourceProducer(Ai * ai) :
+ AiRule(ai) {
+ interval = shortInterval;
+ rt = NULL;
+ newResourceBehaviour =
+ Config::getInstance().getBool("NewResourceBehaviour", "false");;
+ }
+
+ bool
+ AiRuleProduceResourceProducer::test() {
+ //emergency tasks: resource buildings
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ //consumables first
+ for (int i = 0;
+ i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) {
+ rt = aiInterface->getTechTree()->getResourceType(i);
+ const Resource *
+ r = aiInterface->getResource(rt);
+
+ if (ai->outputAIBehaviourToConsole())
+ printf("CONSUMABLE [%s][%d] Testing AI RULE Name[%s]\n",
+ rt->getName().c_str(), r->getBalance(),
+ this->getName().c_str());
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "CONSUMABLE [%s][%d] Testing AI RULE Name[%s]",
+ rt->getName().c_str(), r->getBalance(),
+ this->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ bool
+ factionUsesResourceType =
+ aiInterface->factionUsesResourceType(aiInterface->
+ getMyFactionType(), rt);
+ if (factionUsesResourceType == true
+ && rt->getClass() == rcConsumable) {
+ // The consumable balance is negative
+ if (r->getBalance() < 0) {
+ if (newResourceBehaviour == true) {
+ interval = shortInterval;
+ } else {
+ interval = longInterval;
+ }
+
+ return true;
+ }
+ // If the consumable balance is down to 1/3 of what we need
+ else {
+ if (r->getBalance() * 3 + r->getAmount() < 0) {
+ if (newResourceBehaviour == true) {
+ interval = shortInterval;
+ } else {
+ interval = longInterval;
+ }
+
+ return true;
+ }
+ }
+ }
+ }
+
+ int
+ targetStaticResourceCount = minStaticResources;
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorStaticOverideValue(aibsvcMinStaticResourceCount) !=
+ INT_MAX) {
+ targetStaticResourceCount =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorStaticOverideValue(aibsvcMinStaticResourceCount);
+ }
+
+ //statics second
+ for (int i = 0;
+ i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) {
+ rt = aiInterface->getTechTree()->getResourceType(i);
+ const Resource *
+ r = aiInterface->getResource(rt);
+
+ if (ai->outputAIBehaviourToConsole())
+ printf("STATIC [%s][%d] [min %d] Testing AI RULE Name[%s]\n",
+ rt->getName().c_str(), r->getAmount(),
+ targetStaticResourceCount, this->getName().c_str());
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "STATIC resource check [%s][%d] [min %d] Testing AI RULE Name[%s]",
+ rt->getName().c_str(), r->getAmount(),
+ targetStaticResourceCount, this->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ if (rt->getClass() == rcStatic
+ && r->getAmount() < targetStaticResourceCount) {
+ bool
+ factionUsesResourceType =
+ aiInterface->factionUsesResourceType(aiInterface->
+ getMyFactionType(),
+ rt);
+ if (factionUsesResourceType == true) {
+ if (newResourceBehaviour == true)
+ interval = shortInterval;
+ else
+ interval = longInterval;
+ return true;
+ }
+ }
+ }
+
+ if (ai->outputAIBehaviourToConsole())
+ printf("STATIC returning FALSE\n");
+ if (aiInterface->isLogLevelEnabled(4) == true)
+ aiInterface->printLog(4, "Static Resource check returning FALSE");
+
+ if (newResourceBehaviour == true)
+ interval = longInterval;
+ else
+ interval = shortInterval;
+ return false;
+ }
+
+ void
+ AiRuleProduceResourceProducer::execute() {
+ ai->addPriorityTask(new ProduceTask(rt));
+ ai->addTask(new BuildTask(rt));
+ }
+
+ // =====================================================
+ // class AiRuleProduce
+ // =====================================================
+
+ AiRuleProduce::AiRuleProduce(Ai * ai) :
+ AiRule(ai) {
+ produceTask = NULL;
+ newResourceBehaviour =
+ Config::getInstance().getBool("NewResourceBehaviour", "false");
+ }
+
+ bool
+ AiRuleProduce::test() {
+ const Task *
+ task = ai->getTask();
+
+ if (task == NULL || task->getClass() != tcProduce) {
+ return false;
+ }
+
+ produceTask = static_cast (task);
+ return true;
+ }
+
+ void
+ AiRuleProduce::execute() {
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+ if (produceTask != NULL) {
+
+ if (ai->outputAIBehaviourToConsole())
+ printf("AiRuleProduce producing [%s]\n",
+ (produceTask->getUnitType() !=
+ NULL ? produceTask->getUnitType()->getName(false).
+ c_str() : "null"));
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "AiRuleProduce producing [%s]",
+ (produceTask->getUnitType() !=
+ NULL ? produceTask->getUnitType()->getName(false).
+ c_str() : "null"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ //generic produce task, produce random unit that has the skill or produces the resource
+ if (produceTask->getUnitType() == NULL) {
+ if (newResourceBehaviour) {
+ produceGenericNew(produceTask);
+ } else
+ produceGeneric(produceTask);
+ }
+
+ //specific produce task, produce if possible, retry if not enough resources
+ else {
+ produceSpecific(produceTask);
+ }
+
+ //remove the task
+ ai->removeTask(produceTask);
+ }
+ }
+
+ bool
+ AiRuleProduce::canUnitTypeOfferResourceType(const UnitType * ut,
+ const ResourceType * rt) {
+ bool
+ unitTypeOffersResourceType = false;
+
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ if (ut != NULL && rt != NULL && aiInterface != NULL
+ && aiInterface->reqsOk(ut)) {
+ // Check of the unit 'gives' the resource
+ // if the unit produces the resource
+ const Resource *
+ r = ut->getCost(rt);
+ if (r != NULL) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
+ r->getDescription(false).c_str(), r->getAmount(),
+ this->getName().c_str());
+ }
+
+ if (r != NULL && r->getAmount() < 0) {
+ unitTypeOffersResourceType = true;
+ } else {
+ // for each command check if we produce a unit that handles the resource
+ for (int commandIndex = 0;
+ commandIndex < ut->getCommandTypeCount(); ++commandIndex) {
+ const CommandType *
+ ct = ut->getCommandType(commandIndex);
+
+ //if the command is produce
+ if (ct->getClass() == ccProduce
+ || ct->getClass() == ccMorph) {
+ const UnitType *
+ producedUnit = static_cast (ct->getProduced());
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric [%p] Testing AI RULE Name[%s]\n",
+ rt, this->getName().c_str());
+
+ //if the unit produces the resource
+ const Resource *
+ r = producedUnit->getCost(rt);
+ if (r != NULL) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
+ r->getDescription(false).c_str(),
+ r->getAmount(), this->getName().c_str());
+ }
+
+ if (r != NULL && r->getAmount() < 0) {
+ unitTypeOffersResourceType = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (aiInterface != NULL && aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "canUnitTypeOfferResourceType for unit type [%s] for resource type [%s] returned: %d",
+ (ut != NULL ? ut->getName(false).c_str() : "n/a"),
+ (rt != NULL ? rt->getName(false).c_str() : "n/a"),
+ unitTypeOffersResourceType);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ return unitTypeOffersResourceType;
+ }
+
+ bool
+ AiRuleProduce::setAIProduceTaskForResourceType(const ProduceTask * pt,
+ AiInterface * aiInterface) {
+ bool
+ taskAdded = false;
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcResourceProducerUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcResourceProducerUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ const UnitType *
+ ut = priorityUnit.first;
+ if (ai->getCountOfType(ut) < priorityUnit.second &&
+ canUnitTypeOfferResourceType(ut,
+ pt->getResourceType()) ==
+ true
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, false, true,
+ true) == true) {
+ ai->addTask(new ProduceTask(priorityUnit.first));
+ taskAdded = true;
+ break;
+ }
+ }
+ }
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "setAIProduceTaskForResourceType for resource type [%s] returned: %d",
+ pt->getResourceType()->getName(false).c_str(),
+ taskAdded);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ return taskAdded;
+ }
+
+ void
+ AiRuleProduce::addUnitTypeToCandidates(const UnitType * producedUnit,
+ UnitTypes & ableUnits,
+ UnitTypesGiveBack &
+ ableUnitsGiveBack,
+ bool unitCanGiveBackResource) {
+ // if the unit is not already on the list
+ if (find(ableUnits.begin(), ableUnits.end(), producedUnit) ==
+ ableUnits.end()) {
+ ableUnits.push_back(producedUnit);
+ ableUnitsGiveBack.push_back(unitCanGiveBackResource);
+
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "addUnitTypeToCandidates for unit type [%s] unitCanGiveBackResource = %d",
+ producedUnit->getName(false).c_str(),
+ unitCanGiveBackResource);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ }
+ }
+
+ void
+ AiRuleProduce::produceGenericNew(const ProduceTask * pt) {
+ UnitTypes
+ ableUnits;
+ UnitTypesGiveBack
+ ableUnitsGiveBack;
+
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+ if (pt->getResourceType() != NULL) {
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "****START: produceGeneric for resource type [%s]",
+ pt->getResourceType()->getName(false).c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ if (setAIProduceTaskForResourceType(pt, aiInterface) == true) {
+ return;
+ }
+ } else if (pt->getUnitClass() == ucWorker) {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWorkerUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWorkerUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, false, true,
+ true) == true) {
+ ai->addTask(new ProduceTask(priorityUnit.first));
+ return;
+ }
+ }
+ }
+ } else if (pt->getUnitClass() == ucWarrior) {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWarriorUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWarriorUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, false, true,
+ true) == true) {
+ ai->addTask(new ProduceTask(priorityUnit.first));
+ return;
+ }
+ }
+ }
+ }
+
+ //for each unit, produce it if possible
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL
+ && aiInterface->getMyUnit(i)->getCurrCommand()->
+ getCommandType()->getClass() == ccBuild) {
+ //skip this units as it is currently building something
+ continue;
+ }
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+
+ //bool produceIt= false;
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is produce
+ //bool produceIt= false;
+ if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) {
+ const UnitType *
+ producedUnit = static_cast (ct->getProduced());
+
+ if (ai->outputAIBehaviourToConsole())
+ printf("produceGeneric [%p] Testing AI RULE Name[%s]\n",
+ pt->getResourceType(),
+ this->getName().c_str());
+
+ //if the unit produces the resource
+ if (pt->getResourceType() != NULL) {
+ const Resource *
+ r = producedUnit->getCost(pt->getResourceType());
+ if (r != NULL) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
+ r->getDescription(false).c_str(),
+ r->getAmount(), this->getName().c_str());
+ }
+
+ if (r != NULL && r->getAmount() < 0) {
+ if (aiInterface->reqsOk(ct)
+ && aiInterface->reqsOk(producedUnit)) {
+ //produceIt= true;
+ addUnitTypeToCandidates(producedUnit,
+ ableUnits,
+ ableUnitsGiveBack,
+ false);
+ }
+ }
+ } else {
+ //if the unit is from the right class
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric right class = [%d] Testing AI RULE Name[%s]\n",
+ producedUnit->isOfClass(pt->getUnitClass()),
+ this->getName().c_str());
+
+ if (producedUnit->isOfClass(pt->getUnitClass())) {
+ if (aiInterface->reqsOk(ct)
+ && aiInterface->reqsOk(producedUnit)) {
+ //produceIt= true;
+ addUnitTypeToCandidates(producedUnit,
+ ableUnits,
+ ableUnitsGiveBack,
+ false);
+ }
+ }
+ }
+ }
+ }
+ // Now check of the unit 'gives' the resource
+ // This is likely a unit that it BUILT by another and that is handled by a different AI task type: Build
+ // if(produceIt == false && pt->getResourceType() != NULL) {
+ // const Resource *r= ut->getCost(pt->getResourceType());
+ // if(r != NULL) {
+ // if(ai->outputAIBehaviourToConsole()) printf("#2 produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",r->getDescription(false).c_str(),r->getAmount(), this->getName().c_str());
+ // }
+ //
+ // if(r != NULL && r->getAmount() < 0) {
+ // if(aiInterface->reqsOk(ut)){
+ // produceIt= true;
+ // addUnitTypeToCandidates(ut, ableUnits,ableUnitsGiveBack, true);
+ // }
+ // }
+ // }
+
+ }
+
+ //add specific produce task
+ if (ableUnits.empty() == false) {
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] Testing AI RULE Name[%s]\n",
+ (int) ableUnits.size(), this->getName().c_str());
+
+ // Now check if we already have at least 2 produce or morph
+ // resource based units, if so prefer units that give back the resource
+ if (pt->getResourceType() != NULL && ableUnits.size() > 1) {
+ //priority for non produced units
+ UnitTypes
+ newAbleUnits;
+ bool
+ haveEnoughProducers = true;
+ bool
+ haveNonProducers = false;
+ for (unsigned int i = 0; i < ableUnits.size(); ++i) {
+ const UnitType *
+ ut = ableUnits[i];
+ bool
+ givesBack = ableUnitsGiveBack[i];
+ if (givesBack == false && ai->getCountOfType(ut) < 2) {
+ haveEnoughProducers = false;
+ } else if (givesBack == true) {
+ haveNonProducers = true;
+ newAbleUnits.push_back(ut);
+ }
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In produceGeneric for unit type [%s] givesBack: %d count of unit type: %d",
+ ut->getName(false).c_str(), givesBack,
+ ai->getCountOfType(ut));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ }
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "haveEnoughProducers [%d] haveNonProducers [%d]",
+ haveEnoughProducers, haveNonProducers);
+ aiInterface->printLog(4, szBuf);
+
+ for (unsigned int i = 0; i < ableUnits.size(); ++i) {
+ const UnitType *
+ ut = ableUnits[i];
+ snprintf(szBuf, 8096, "i: %u unit type [%s]", i,
+ ut->getName(false).c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+ for (unsigned int i = 0; i < newAbleUnits.size(); ++i) {
+ const UnitType *
+ ut = newAbleUnits[i];
+ snprintf(szBuf, 8096, "i: %u new unit type [%s]", i,
+ ut->getName(false).c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+ }
+
+ if (haveEnoughProducers == true && haveNonProducers == true) {
+ ableUnits = newAbleUnits;
+ }
+ }
+
+ //priority for non produced units
+ for (unsigned int i = 0; i < ableUnits.size(); ++i) {
+ if (ai->getCountOfType(ableUnits[i]) == 0) {
+ if (ai->getRandom()->randRange(0, 1) == 0) {
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In produceGeneric priority adding produce task: %d of "
+ MG_SIZE_T_SPECIFIER " for unit type [%s]",
+ i, ableUnits.size(),
+ ableUnits[i]->getName(false).c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new ProduceTask(ableUnits[i]));
+ return;
+ }
+ }
+ }
+
+ //normal case
+ int
+ randomUnitTypeIndex =
+ ai->getRandom()->randRange(0, (int) ableUnits.size() - 1);
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In produceGeneric randomUnitTypeIndex = %d of "
+ MG_SIZE_T_SPECIFIER " equals unit type [%s]",
+ randomUnitTypeIndex, ableUnits.size() - 1,
+ ableUnits[randomUnitTypeIndex]->getName(false).
+ c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ const UnitType *
+ ut = ableUnits[randomUnitTypeIndex];
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "== END In produceGeneric normal adding produce task for unit type [%s]",
+ ut->getName(false).c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new ProduceTask(ut));
+ }
+ }
+
+ void
+ AiRuleProduce::produceGeneric(const ProduceTask * pt) {
+ typedef
+ vector < const UnitType *>
+ UnitTypes;
+ UnitTypes
+ ableUnits;
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ if (pt->getResourceType() != NULL) {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcResourceProducerUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcResourceProducerUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, false, true,
+ true) == true) {
+ //if(ai->getRandom()->randRange(0, 1)==0) {
+ ai->addTask(new ProduceTask(priorityUnit.first));
+ return;
+ //}
+ }
+ }
+ }
+ } else if (pt->getUnitClass() == ucWorker) {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWorkerUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWorkerUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, false, true,
+ true) == true) {
+ //if(ai->getRandom()->randRange(0, 1)==0) {
+ ai->addTask(new ProduceTask(priorityUnit.first));
+ return;
+ //}
+ }
+ }
+ }
+ } else if (pt->getUnitClass() == ucWarrior) {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWarriorUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcWarriorUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, false, true,
+ true) == true) {
+ //if(ai->getRandom()->randRange(0, 1)==0) {
+ ai->addTask(new ProduceTask(priorityUnit.first));
+ return;
+ //}
+ }
+ }
+ }
+ }
+
+ //for each unit, produce it if possible
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL
+ && aiInterface->getMyUnit(i)->getCurrCommand()->
+ getCommandType()->getClass() == ccBuild) {
+ //skip this units as it is currently building something
+ continue;
+ }
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is produce
+ if (ct->getClass() == ccProduce || ct->getClass() == ccMorph) {
+
+ const UnitType *
+ producedUnit = static_cast (ct->getProduced());
+ bool
+ produceIt = false;
+
+ if (ai->outputAIBehaviourToConsole())
+ printf("produceGeneric [%p] Testing AI RULE Name[%s]\n",
+ pt->getResourceType(),
+ this->getName().c_str());
+
+ //if the unit produces the resource
+ if (pt->getResourceType() != NULL) {
+ const Resource *
+ r = producedUnit->getCost(pt->getResourceType());
+
+ if (r != NULL) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric r = [%s][%d] Testing AI RULE Name[%s]\n",
+ r->getDescription(false).c_str(),
+ r->getAmount(), this->getName().c_str());
+ }
+
+ if (r != NULL && r->getAmount() < 0) {
+ produceIt = true;
+ }
+ }
+
+ else {
+ //if the unit is from the right class
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric right class = [%d] Testing AI RULE Name[%s]\n",
+ producedUnit->isOfClass(pt->getUnitClass()),
+ this->getName().c_str());
+
+ if (producedUnit->isOfClass(pt->getUnitClass())) {
+ if (aiInterface->reqsOk(ct)
+ && aiInterface->reqsOk(producedUnit)) {
+ produceIt = true;
+ }
+ }
+ }
+
+ if (produceIt) {
+ //if the unit is not already on the list
+ if (find
+ (ableUnits.begin(), ableUnits.end(),
+ producedUnit) == ableUnits.end()) {
+ ableUnits.push_back(producedUnit);
+ }
+ }
+ }
+ }
+ }
+
+ //add specific produce task
+ if (ableUnits.empty() == false) {
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceGeneric !ableUnits.empty(), ableUnits.size() = [%d] Testing AI RULE Name[%s]\n",
+ (int) ableUnits.size(), this->getName().c_str());
+
+ //priority for non produced units
+ for (unsigned int i = 0; i < ableUnits.size(); ++i) {
+ if (ai->getCountOfType(ableUnits[i]) == 0) {
+ if (ai->getRandom()->randRange(0, 1) == 0) {
+ ai->addTask(new ProduceTask(ableUnits[i]));
+ return;
+ }
+ }
+ }
+
+ //normal case
+ ai->
+ addTask(new
+ ProduceTask(ableUnits
+ [ai->getRandom()->
+ randRange(0,
+ (int) ableUnits.size() - 1)]));
+ }
+ }
+
+ void
+ AiRuleProduce::produceSpecific(const ProduceTask * pt) {
+
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] Testing AI RULE Name[%s]\n",
+ pt->getUnitType()->getName().c_str(),
+ aiInterface->reqsOk(pt->getUnitType()),
+ this->getName().c_str());
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "== START produceSpecific aiInterface->reqsOk(pt->getUnitType()) = [%s][%d] Testing AI RULE Name[%s]",
+ pt->getUnitType()->getName().c_str(),
+ aiInterface->reqsOk(pt->getUnitType()),
+ this->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ //if unit meets requirements
+ if (aiInterface->reqsOk(pt->getUnitType())) {
+
+ const CommandType *
+ ctypeForCostCheck = NULL;
+ //for each unit
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ //don't use units which are currently building
+ if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL
+ && aiInterface->getMyUnit(i)->getCurrCommand()->
+ getCommandType()->getClass() == ccBuild) {
+ //skip this units as it is currently building something
+ continue;
+ }
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is produce
+ if (ct->getClass() == ccProduce
+ || ct->getClass() == ccMorph) {
+ const UnitType *
+ producedUnit = static_cast (ct->getProduced());
+
+ //if units match
+ if (producedUnit == pt->getUnitType()) {
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing AI RULE Name[%s]\n",
+ aiInterface->reqsOk(ct),
+ this->getName().c_str());
+
+ if (aiInterface->reqsOk(ct)) {
+ if (ctypeForCostCheck == NULL
+ || ct->getClass() == ccMorph) {
+ if (ctypeForCostCheck != NULL
+ && ct->getClass() == ccMorph) {
+ const MorphCommandType *
+ mct = dynamic_cast (ct);
+ if (mct == NULL) {
+ throw
+ megaglest_runtime_error
+ ("mct == NULL");
+ }
+ if (mct->
+ getIgnoreResourceRequirements() ==
+ true) {
+ ctypeForCostCheck = ct;
+ }
+ } else {
+ ctypeForCostCheck = ct;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceSpecific aiInterface->checkCosts(pt->getUnitType()) = [%d] Testing AI RULE Name[%s]\n",
+ aiInterface->checkCosts(pt->getUnitType(),
+ ctypeForCostCheck),
+ this->getName().c_str());
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "produceSpecific aiInterface->checkCosts(pt->getUnitType()) = [%d] Testing AI RULE Name[%s]",
+ aiInterface->checkCosts(pt->getUnitType(),
+ ctypeForCostCheck),
+ this->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ //if unit doesnt meet resources retry
+ if (aiInterface->
+ checkCosts(pt->getUnitType(), ctypeForCostCheck) == false) {
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "Check costs FAILED.");
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->retryTask(pt);
+ return;
+ }
+
+ //produce specific unit
+ vector < int >
+ producers;
+ // Hold a list of units which can produce or morph
+ // then a list of commandtypes for each unit
+ map < int,
+ vector < const CommandType *> >
+ producersDefaultCommandType;
+ const CommandType *
+ defCt = NULL;
+
+ //for each unit
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+ if (aiInterface->getMyUnit(i)->getCurrCommand() != NULL
+ && aiInterface->getMyUnit(i)->getCurrCommand()->
+ getCommandType()->getClass() == ccBuild) {
+ //skip this units as it is currently building something
+ continue;
+ }
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is produce
+ if (ct->getClass() == ccProduce
+ || ct->getClass() == ccMorph) {
+ const UnitType *
+ producedUnit = static_cast (ct->getProduced());
+
+ //if units match
+ if (producedUnit == pt->getUnitType()) {
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceSpecific aiInterface->reqsOk(ct) = [%d] Testing AI RULE Name[%s]\n",
+ aiInterface->reqsOk(ct),
+ this->getName().c_str());
+
+ if (aiInterface->reqsOk(ct)) {
+ //defCt= ct;
+ producers.push_back(i);
+ producersDefaultCommandType[i].push_back(ct);
+ }
+ }
+ }
+ }
+ }
+
+ //produce from random producer
+ if (producers.empty() == false) {
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]\n",
+ producers.empty(), this->getName().c_str());
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "produceSpecific producers.empty() = [%d] Testing AI RULE Name[%s]",
+ producers.empty(), this->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ // Narrow down producers list to those who are not busy if possible
+ vector < int >
+ idle_producers;
+ for (unsigned int i = 0; i < producers.size(); ++i) {
+ int
+ currentProducerIndex = producers[i];
+ if (currentProducerIndex >= aiInterface->getMyUnitCount()) {
+ char
+ szBuf[8096] = "";
+ printf
+ ("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,producers.size() = "
+ MG_SIZE_T_SPECIFIER "\n", __FILE__, __FUNCTION__,
+ __LINE__, currentProducerIndex,
+ aiInterface->getMyUnitCount(), i,
+ producers.size());
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %u, i = %u,producers.size() = "
+ MG_SIZE_T_SPECIFIER "", __FILE__,
+ __FUNCTION__, __LINE__, currentProducerIndex,
+ aiInterface->getMyUnitCount(), i,
+ producers.size());
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ const Unit *
+ unit = aiInterface->getMyUnit(currentProducerIndex);
+ if (unit->anyCommand() == false) {
+ idle_producers.push_back(currentProducerIndex);
+ }
+ }
+ if (idle_producers.empty() == false) {
+ producers = idle_producers;
+ }
+
+ if (aiInterface->getControlType() == ctCpuZeta ||
+ aiInterface->getControlType() == ctNetworkCpuZeta) { // zeta cpu trys to balance the commands to the producers
+ int
+ randomstart =
+ ai->getRandom()->randRange(0,
+ (int) producers.size() - 1);
+ int
+ lowestCommandCount = 1000000;
+ int
+ currentProducerIndex = producers[randomstart];
+ int
+ bestIndex = -1;
+ //int besti=0;
+ int
+ currentCommandCount = 0;
+ for (unsigned int i = randomstart;
+ i < producers.size() + randomstart; i++) {
+ int
+ prIndex = i;
+ if (i >= producers.size()) {
+ prIndex = (i - (int) producers.size());
+ }
+ currentProducerIndex = producers[prIndex];
+
+ if (currentProducerIndex >=
+ aiInterface->getMyUnitCount()) {
+ char
+ szBuf[8096] = "";
+ printf
+ ("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,producers.size() = "
+ MG_SIZE_T_SPECIFIER "\n", __FILE__, __FUNCTION__,
+ __LINE__, currentProducerIndex,
+ aiInterface->getMyUnitCount(), i,
+ producers.size());
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %u, i = %u,producers.size() = "
+ MG_SIZE_T_SPECIFIER "", __FILE__,
+ __FUNCTION__, __LINE__,
+ currentProducerIndex,
+ aiInterface->getMyUnitCount(), i,
+ producers.size());
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ if (prIndex >= (int) producers.size()) {
+ char
+ szBuf[8096] = "";
+ printf
+ ("In [%s::%s Line: %d] prIndex >= producers.size(), currentProducerIndex = %d, i = %u,producers.size() = "
+ MG_SIZE_T_SPECIFIER " \n", __FILE__,
+ __FUNCTION__, __LINE__, prIndex, i,
+ producers.size());
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] currentProducerIndex >= producers.size(), currentProducerIndex = %d, i = %u,producers.size() = "
+ MG_SIZE_T_SPECIFIER "", __FILE__,
+ __FUNCTION__, __LINE__,
+ currentProducerIndex, i,
+ producers.size());
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ currentCommandCount =
+ aiInterface->getMyUnit(currentProducerIndex)->
+ getCommandSize();
+ if (currentCommandCount == 1
+ && aiInterface->getMyUnit(currentProducerIndex)->
+ getCurrCommand()->getCommandType()->getClass() ==
+ ccStop) { // special for non buildings
+ currentCommandCount = 0;
+ }
+ if (lowestCommandCount > currentCommandCount) {
+ lowestCommandCount =
+ aiInterface->getMyUnit(currentProducerIndex)->
+ getCommandSize();
+ bestIndex = currentProducerIndex;
+ //besti=i%(producers.size());
+ }
+ }
+ if (bestIndex >= 0) {
+ if (aiInterface->getMyUnit(bestIndex)->
+ getCommandSize() > 2) {
+ // maybe we need another producer of this kind if possible!
+ if (aiInterface->
+ reqsOk(aiInterface->getMyUnit(bestIndex)->
+ getType())) {
+ if (ai->getCountOfClass(ucBuilding) > 5) {
+ ai->
+ addTask(new
+ BuildTask(aiInterface->
+ getMyUnit
+ (bestIndex)->
+ getType()));
+ }
+ }
+ // need to calculate another producer, maybe its better to produce another warrior with another producer
+ vector < int >
+ backupProducers;
+ // find another producer unit which is free and produce any kind of warrior.
+ //for each unit
+ for (int i = 0; i < aiInterface->getMyUnitCount();
+ ++i) {
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ //for each command
+ for (int j = 0; j < ut->getCommandTypeCount();
+ ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+ //if the command is produce
+ if (ct->getClass() == ccProduce) {
+ const UnitType *
+ unitType = static_cast (ct->getProduced());
+ if (unitType->hasSkillClass(scAttack)
+ && !unitType->
+ hasCommandClass(ccHarvest)
+ && aiInterface->reqsOk(ct)) { //this can produce a warrior
+ backupProducers.push_back(i);
+ }
+ }
+ }
+ }
+ if (!backupProducers.empty()) {
+ int
+ randomstart =
+ ai->getRandom()->randRange(0,
+ (int)
+ backupProducers.
+ size() - 1);
+ int
+ lowestCommandCount = 1000000;
+ int
+ currentProducerIndex =
+ backupProducers[randomstart];
+ int
+ bestIndex = -1;
+ for (unsigned int i = randomstart;
+ i < backupProducers.size() + randomstart;
+ i++) {
+ int
+ prIndex = i;
+ if (i >= backupProducers.size()) {
+ prIndex =
+ (i - (int) backupProducers.size());
+ }
+
+ currentProducerIndex =
+ backupProducers[prIndex];
+
+ if (currentProducerIndex >=
+ aiInterface->getMyUnitCount()) {
+ char
+ szBuf[8096] = "";
+ printf
+ ("In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,backupProducers.size() = "
+ MG_SIZE_T_SPECIFIER "\n", __FILE__,
+ __FUNCTION__, __LINE__,
+ currentProducerIndex,
+ aiInterface->getMyUnitCount(), i,
+ backupProducers.size());
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] currentProducerIndex >= aiInterface->getMyUnitCount(), currentProducerIndex = %d, aiInterface->getMyUnitCount() = %d, i = %u,backupProducers.size() = "
+ MG_SIZE_T_SPECIFIER "",
+ __FILE__, __FUNCTION__,
+ __LINE__,
+ currentProducerIndex,
+ aiInterface->
+ getMyUnitCount(), i,
+ backupProducers.size());
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+ if (prIndex >=
+ (int) backupProducers.size()) {
+ char
+ szBuf[8096] = "";
+ printf
+ ("In [%s::%s Line: %d] prIndex >= backupProducers.size(), currentProducerIndex = %d, i = %u,backupProducers.size() = "
+ MG_SIZE_T_SPECIFIER " \n", __FILE__,
+ __FUNCTION__, __LINE__, prIndex, i,
+ backupProducers.size());
+ snprintf(szBuf, 8096,
+ "In [%s::%s Line: %d] currentProducerIndex >= backupProducers.size(), currentProducerIndex = %d, i = %u,backupProducers.size() = "
+ MG_SIZE_T_SPECIFIER "",
+ __FILE__, __FUNCTION__,
+ __LINE__,
+ currentProducerIndex, i,
+ backupProducers.size());
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ int
+ currentCommandCount =
+ aiInterface->
+ getMyUnit(currentProducerIndex)->
+ getCommandSize();
+ if (currentCommandCount == 1
+ && aiInterface->
+ getMyUnit(currentProducerIndex)->
+ getCurrCommand()->getCommandType()->
+ getClass() == ccStop) { // special for non buildings
+ currentCommandCount = 0;
+ }
+ if (lowestCommandCount >
+ currentCommandCount) {
+ lowestCommandCount =
+ currentCommandCount;
+ bestIndex = currentProducerIndex;
+ if (lowestCommandCount == 0)
+ break;
+ }
+ }
+ // a good producer is found, lets choose a warrior production
+ vector < int >
+ productionCommandIndexes;
+ if (bestIndex >= 0) {
+ const UnitType *
+ ut =
+ aiInterface->getMyUnit(bestIndex)->
+ getType();
+ for (int j = 0;
+ j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is produce
+ if (ct->getClass() == ccProduce) {
+ const UnitType *
+ unitType = static_cast (ct->getProduced());
+ if (unitType->
+ hasSkillClass(scAttack)
+ && !unitType->
+ hasCommandClass(ccHarvest)
+ && aiInterface->reqsOk(ct)) { //this can produce a warrior
+ productionCommandIndexes.
+ push_back(j);
+ }
+ }
+ }
+
+ int
+ commandIndex =
+ productionCommandIndexes[ai->
+ getRandom()->
+ randRange(0,
+ (int)
+ productionCommandIndexes.
+ size
+ () -
+ 1)];
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__);
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("zeta #1 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
+ aiInterface->getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ ut->getCommandType(commandIndex)->
+ getName().c_str());
+ if (aiInterface->isLogLevelEnabled(4) ==
+ true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "zeta #1 produceSpecific giveCommand to unit [%s] commandType [%s]",
+ aiInterface->
+ getMyUnit(bestIndex)->
+ getType()->getName().
+ c_str(),
+ ut->
+ getCommandType
+ (commandIndex)->getName().
+ c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ aiInterface->giveCommand(bestIndex,
+ ut->
+ getCommandType
+ (commandIndex));
+ }
+ } else { // do it like normal CPU
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__);
+ defCt = NULL;
+ if (producersDefaultCommandType.
+ find(bestIndex) !=
+ producersDefaultCommandType.end()) {
+ int
+ bestCommandTypeCount =
+ (int)
+ producersDefaultCommandType[bestIndex].
+ size();
+ int
+ bestCommandTypeIndex =
+ ai->getRandom()->randRange(0,
+ bestCommandTypeCount
+ - 1);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__,
+ bestCommandTypeIndex,
+ bestCommandTypeCount);
+
+ defCt =
+ producersDefaultCommandType[bestIndex]
+ [bestCommandTypeIndex];
+ }
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("zeta #2 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
+ aiInterface->getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().
+ c_str() : "n/a"));
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "zeta #2 produceSpecific giveCommand to unit [%s] commandType [%s]",
+ aiInterface->
+ getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().
+ c_str() : "n/a"));
+ aiInterface->printLog(4, szBuf);
+ }
+ aiInterface->giveCommand(bestIndex, defCt);
+ }
+ } else {
+ if (currentCommandCount == 0) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__);
+ defCt = NULL;
+ if (producersDefaultCommandType.
+ find(bestIndex) !=
+ producersDefaultCommandType.end()) {
+ //defCt = producersDefaultCommandType[bestIndex];
+ int
+ bestCommandTypeCount =
+ (int)
+ producersDefaultCommandType[bestIndex].
+ size();
+ int
+ bestCommandTypeIndex =
+ ai->getRandom()->randRange(0,
+ bestCommandTypeCount
+ - 1);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__,
+ bestCommandTypeIndex,
+ bestCommandTypeCount);
+
+ defCt =
+ producersDefaultCommandType[bestIndex]
+ [bestCommandTypeIndex];
+ }
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("zeta #3 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
+ aiInterface->getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().
+ c_str() : "n/a"));
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "zeta #3 produceSpecific giveCommand to unit [%s] commandType [%s]",
+ aiInterface->
+ getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().
+ c_str() : "n/a"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ aiInterface->giveCommand(bestIndex, defCt);
+ }
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__, __FUNCTION__,
+ __LINE__);
+ defCt = NULL;
+ if (producersDefaultCommandType.find(bestIndex) !=
+ producersDefaultCommandType.end()) {
+ //defCt = producersDefaultCommandType[bestIndex];
+ int
+ bestCommandTypeCount =
+ (int) producersDefaultCommandType[bestIndex].
+ size();
+ int
+ bestCommandTypeIndex =
+ ai->getRandom()->randRange(0,
+ bestCommandTypeCount
+ - 1);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__,
+ bestCommandTypeIndex,
+ bestCommandTypeCount);
+
+ defCt =
+ producersDefaultCommandType[bestIndex]
+ [bestCommandTypeIndex];
+ }
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("zeta #4 produceSpecific giveCommand to unit [%s] commandType [%s]\n",
+ aiInterface->getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().c_str() : "n/a"));
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "zeta #4 produceSpecific giveCommand to unit [%s] commandType [%s]",
+ aiInterface->getMyUnit(bestIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().
+ c_str() : "n/a"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ aiInterface->giveCommand(bestIndex, defCt);
+ }
+ }
+ } else {
+ int
+ pIndex =
+ ai->getRandom()->randRange(0,
+ (int) producers.size() - 1);
+ int
+ producerIndex = producers[pIndex];
+ defCt = NULL;
+ if (producersDefaultCommandType.find(producerIndex) !=
+ producersDefaultCommandType.end()) {
+ //defCt = producersDefaultCommandType[producerIndex];
+ int
+ bestCommandTypeCount =
+ (int) producersDefaultCommandType[producerIndex].
+ size();
+ int
+ bestCommandTypeIndex =
+ ai->getRandom()->randRange(0,
+ bestCommandTypeCount -
+ 1);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
+ __FILE__, __FUNCTION__,
+ __LINE__,
+ bestCommandTypeIndex,
+ bestCommandTypeCount);
+
+ defCt =
+ producersDefaultCommandType[producerIndex]
+ [bestCommandTypeIndex];
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] producers.size() = %d, producerIndex = %d, pIndex = %d, producersDefaultCommandType.size() = %d\n",
+ __FILE__, __FUNCTION__,
+ __LINE__, producers.size(),
+ producerIndex, pIndex,
+ producersDefaultCommandType.
+ size());
+
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("produceSpecific giveCommand to unit [%s] commandType [%s]\n",
+ aiInterface->getMyUnit(producerIndex)->getType()->
+ getName().c_str(),
+ (defCt != NULL ? defCt->getName().c_str() : "n/a"));
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "produceSpecific giveCommand to unit [%s] commandType [%s]",
+ aiInterface->getMyUnit(producerIndex)->
+ getType()->getName().c_str(),
+ (defCt !=
+ NULL ? defCt->getName().
+ c_str() : "(null)"));
+ aiInterface->printLog(4, szBuf);
+ }
+ aiInterface->giveCommand(producerIndex, defCt);
+ }
+ }
+ }
+ }
+
+ // ========================================
+ // class AiRuleBuild
+ // ========================================
+
+ AiRuleBuild::AiRuleBuild(Ai * ai) :
+ AiRule(ai) {
+ buildTask = NULL;
+ }
+
+ bool
+ AiRuleBuild::test() {
+ const Task *
+ task = ai->getTask();
+
+ if (task == NULL || task->getClass() != tcBuild) {
+ return false;
+ }
+
+ buildTask = static_cast (task);
+ return true;
+ }
+
+
+ void
+ AiRuleBuild::execute() {
+ if (buildTask != NULL) {
+ if (ai->outputAIBehaviourToConsole())
+ printf("BUILD AiRuleBuild Unit Name[%s]\n",
+ (buildTask->getUnitType() !=
+ NULL ? buildTask->getUnitType()->getName(false).
+ c_str() : "null"));
+
+ //generic build task, build random building that can be built
+ if (buildTask->getUnitType() == NULL) {
+ buildGeneric(buildTask);
+ }
+ //specific building task, build if possible, retry if not enough resources or not position
+ else {
+ buildSpecific(buildTask);
+ }
+
+ //remove the task
+ ai->removeTask(buildTask);
+ }
+ }
+
+ void
+ AiRuleBuild::buildGeneric(const BuildTask * bt) {
+
+ //find buildings that can be built
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "== START: buildGeneric for resource type [%s]",
+ (bt->getResourceType() !=
+ NULL ? bt->getResourceType()->getName().
+ c_str() : "null"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ typedef
+ vector < const UnitType *>
+ UnitTypes;
+ UnitTypes
+ buildings;
+
+ if (bt->getResourceType() != NULL) {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcResourceProducerUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcResourceProducerUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, true, false,
+ false) == true) {
+ //if(ai->getRandom()->randRange(0, 1)==0) {
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildGeneric for resource type [%s] aibcResourceProducerUnits = "
+ MG_SIZE_T_SPECIFIER
+ " priorityUnit.first: [%s]\n",
+ bt->getResourceType()->getName().
+ c_str(), unitList.size(),
+ priorityUnit.first->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new BuildTask(priorityUnit.first));
+ return;
+ //}
+ }
+ }
+ }
+ } else {
+ if (aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcBuildingUnits).size() > 0) {
+ const
+ std::vector <
+ FactionType::PairPUnitTypeInt > &
+ unitList =
+ aiInterface->getMyFactionType()->
+ getAIBehaviorUnits(aibcBuildingUnits);
+ for (unsigned int i = 0; i < unitList.size(); ++i) {
+ const
+ FactionType::PairPUnitTypeInt &
+ priorityUnit = unitList[i];
+ if (ai->getCountOfType(priorityUnit.first) <
+ priorityUnit.second
+ && aiInterface->getMyFaction()->
+ canCreateUnit(priorityUnit.first, true, false,
+ false) == true) {
+ //if(ai->getRandom()->randRange(0, 1)==0) {
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildGeneric for resource type [%s] aibcBuildingUnits = "
+ MG_SIZE_T_SPECIFIER
+ " priorityUnit.first: [%s]\n",
+ bt->getResourceType()->getName().
+ c_str(), unitList.size(),
+ priorityUnit.first->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new BuildTask(priorityUnit.first));
+ return;
+ //}
+ }
+ }
+ }
+ }
+
+ //for each unit
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is build
+ if (ct->getClass() == ccBuild) {
+ const BuildCommandType *
+ bct = static_cast (ct);
+
+ //for each building
+ for (int k = 0; k < bct->getBuildingCount(); ++k) {
+ const UnitType *
+ building = bct->getBuilding(k);
+ if (aiInterface->reqsOk(bct)
+ && aiInterface->reqsOk(building)) {
+
+ //if any building, or produces resource
+ const ResourceType *
+ rt = bt->getResourceType();
+ const Resource *
+ cost = building->getCost(rt);
+ if (rt == NULL
+ || (cost != NULL && cost->getAmount() < 0)) {
+ if (find
+ (buildings.begin(), buildings.end(),
+ building) == buildings.end()) {
+ buildings.push_back(building);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ for (int i = 0; i < (int) buildings.size(); ++i) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildGeneric i = %d unit type: [%s]\n", i,
+ buildings[i]->getName().c_str());
+ aiInterface->printLog(4, szBuf);
+ }
+ }
+
+ //add specific build task
+ buildBestBuilding(buildings);
+ }
+
+ void
+ AiRuleBuild::buildBestBuilding(const vector <
+ const UnitType * >&buildings) {
+
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "==> START buildBestBuilding buildings.size = "
+ MG_SIZE_T_SPECIFIER "\n", buildings.size());
+ aiInterface->printLog(4, szBuf);
+ }
+
+ if (!buildings.empty()) {
+
+ //build the least built building
+ bool
+ buildingFound = false;
+ for (int i = 0; i < 10 && !buildingFound; ++i) {
+
+ if (i > 0) {
+
+ //Defensive buildings have priority
+ for (int j = 0;
+ j < (int) buildings.size() && buildingFound == false;
+ ++j) {
+ const UnitType *
+ building = buildings[j];
+ if (ai->getCountOfType(building) <= i + 1
+ && isDefensive(building)) {
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildBestBuilding defensive building unit type: [%s] i = %d j = %d\n",
+ building->getName().c_str(), i, j);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new BuildTask(building));
+ buildingFound = true;
+ }
+ }
+
+ //Warrior producers next
+ for (unsigned int j = 0;
+ j < buildings.size() && !buildingFound; ++j) {
+ const UnitType *
+ building = buildings[j];
+ if (ai->getCountOfType(building) <= i + 1
+ && isWarriorProducer(building)) {
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildBestBuilding warriorproducer building unit type: [%s] i = %d j = %u\n",
+ building->getName().c_str(), i, j);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new BuildTask(building));
+ buildingFound = true;
+ }
+ }
+
+ //Resource producers next
+ for (unsigned int j = 0;
+ j < buildings.size() && !buildingFound; ++j) {
+ const UnitType *
+ building = buildings[j];
+ if (ai->getCountOfType(building) <= i + 1
+ && isResourceProducer(building)) {
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildBestBuilding resourceproducer building unit type: [%s] i = %d j = %u\n",
+ building->getName().c_str(), i, j);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new BuildTask(building));
+ buildingFound = true;
+ }
+ }
+ }
+
+ //Any building
+ for (unsigned int j = 0;
+ j < buildings.size() && !buildingFound; ++j) {
+ const UnitType *
+ building = buildings[j];
+ if (ai->getCountOfType(building) <= i) {
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildBestBuilding ANY building unit type: [%s] i = %d j = %u\n",
+ building->getName().c_str(), i, j);
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->addTask(new BuildTask(building));
+ buildingFound = true;
+ }
+ }
+ }
+ }
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "==> END buildBestBuilding buildings.size = "
+ MG_SIZE_T_SPECIFIER "\n", buildings.size());
+ aiInterface->printLog(4, szBuf);
+ }
+ }
+
+ void
+ AiRuleBuild::buildSpecific(const BuildTask * bt) {
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "== START: buildSpecific for resource type [%s] bt->getUnitType() [%s]",
+ (bt->getResourceType() !=
+ NULL ? bt->getResourceType()->getName().
+ c_str() : "null"),
+ (bt->getUnitType() !=
+ NULL ? bt->getUnitType()->getName(false).
+ c_str() : "null"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ //if reqs ok
+ if (aiInterface->reqsOk(bt->getUnitType())) {
+
+ //retry if not enough resources
+ if (aiInterface->checkCosts(bt->getUnitType(), NULL) == false) {
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildSpecific for resource type [%s] checkcosts == false RETRYING",
+ (bt->getResourceType() !=
+ NULL ? bt->getResourceType()->getName().
+ c_str() : "null"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ ai->retryTask(bt);
+ return;
+ }
+
+ vector < int >
+ builders;
+ // Hold a list of units which can build
+ // then a list of build commandtypes for each unit
+ map < int,
+ vector < const BuildCommandType *> >
+ buildersDefaultCommandType;
+ const BuildCommandType *
+ defBct = NULL;
+
+ //for each unit
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+
+ //if the unit is not going to build
+ const Unit *
+ u = aiInterface->getMyUnit(i);
+ if (u->anyCommand() == false
+ || u->getCurrCommand()->getCommandType()->getClass() !=
+ ccBuild) {
+
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is build
+ if (ct->getClass() == ccBuild) {
+ const BuildCommandType *
+ bct = static_cast (ct);
+
+ //for each building
+ for (int k = 0; k < bct->getBuildingCount(); ++k) {
+ const UnitType *
+ building = bct->getBuilding(k);
+
+ //if building match
+ if (bt->getUnitType() == building) {
+ if (aiInterface->reqsOk(bct)) {
+ builders.push_back(i);
+ buildersDefaultCommandType[i].
+ push_back(bct);
+ //defBct= bct;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //use random builder to build
+ if (builders.empty() == false) {
+ int
+ bIndex =
+ ai->getRandom()->randRange(0, (int) builders.size() - 1);
+ int
+ builderIndex = builders[bIndex];
+ Vec2i
+ pos;
+ Vec2i
+ searchPos =
+ bt->getForcePos() ? bt->getPos() : ai->
+ getRandomHomePosition();
+ if (bt->getForcePos() == false) {
+ const int
+ enemySightDistanceToAvoid = 18;
+ vector < Unit * >enemies;
+ ai->getAiInterface()->getWorld()->getUnitUpdater()->
+ findEnemiesForCell(searchPos,
+ bt->getUnitType()->getSize(),
+ enemySightDistanceToAvoid,
+ ai->getAiInterface()->
+ getMyFaction(), enemies, true);
+ if (enemies.empty() == false) {
+ for (int i1 = 0; i1 < 25 && enemies.empty() == false;
+ ++i1) {
+ for (int j1 = 0;
+ j1 < 25 && enemies.empty() == false; ++j1) {
+ Vec2i
+ tryPos = searchPos + Vec2i(i1, j1);
+
+ const int
+ spacing = 1;
+ if (ai->getAiInterface()->
+ isFreeCells(tryPos - Vec2i(spacing),
+ bt->getUnitType()->
+ getSize() + spacing * 2,
+ fLand)) {
+ enemies.clear();
+ ai->getAiInterface()->getWorld()->
+ getUnitUpdater()->
+ findEnemiesForCell(tryPos,
+ bt->getUnitType()->
+ getSize(),
+ enemySightDistanceToAvoid,
+ ai->
+ getAiInterface()->
+ getMyFaction(),
+ enemies, true);
+ if (enemies.empty() == true) {
+ searchPos = tryPos;
+ }
+ }
+ }
+ }
+ }
+ if (enemies.empty() == false) {
+ for (int i1 = -1;
+ i1 >= -25 && enemies.empty() == false; --i1) {
+ for (int j1 = -1;
+ j1 >= -25 && enemies.empty() == false; --j1) {
+ Vec2i
+ tryPos = searchPos + Vec2i(i1, j1);
+
+ const int
+ spacing = 1;
+ if (ai->getAiInterface()->
+ isFreeCells(tryPos - Vec2i(spacing),
+ bt->getUnitType()->
+ getSize() + spacing * 2,
+ fLand)) {
+ enemies.clear();
+ ai->getAiInterface()->getWorld()->
+ getUnitUpdater()->
+ findEnemiesForCell(tryPos,
+ bt->getUnitType()->
+ getSize(),
+ enemySightDistanceToAvoid,
+ ai->
+ getAiInterface()->
+ getMyFaction(),
+ enemies, true);
+ if (enemies.empty() == true) {
+ searchPos = tryPos;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //if free pos give command, else retry
+ if (ai->findPosForBuilding(bt->getUnitType(), searchPos, pos)) {
+ defBct = NULL;
+ if (buildersDefaultCommandType.find(builderIndex) !=
+ buildersDefaultCommandType.end()) {
+ //defBct = buildersDefaultCommandType[builderIndex];
+ int
+ bestCommandTypeCount =
+ (int) buildersDefaultCommandType[builderIndex].
+ size();
+ int
+ bestCommandTypeIndex =
+ ai->getRandom()->randRange(0,
+ bestCommandTypeCount -
+ 1);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] bestCommandTypeIndex = %d, bestCommandTypeCount = %d\n",
+ __FILE__, __FUNCTION__,
+ __LINE__,
+ bestCommandTypeIndex,
+ bestCommandTypeCount);
+
+ defBct =
+ buildersDefaultCommandType[builderIndex]
+ [bestCommandTypeIndex];
+ }
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d] builderIndex = %d, bIndex = %d, defBct = %p\n",
+ __FILE__, __FUNCTION__,
+ __LINE__, builderIndex, bIndex,
+ defBct);
+
+ aiInterface->giveCommand(builderIndex, defBct, pos,
+ bt->getUnitType());
+ } else {
+ ai->retryTask(bt);
+ return;
+ }
+ }
+ } else {
+ if (aiInterface->isLogLevelEnabled(4) == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In buildSpecific for resource type [%s] reqsok == false",
+ (bt->getResourceType() !=
+ NULL ? bt->getResourceType()->getName().
+ c_str() : "null"));
+ aiInterface->printLog(4, szBuf);
+ }
+
+ }
+ }
+
+ bool
+ AiRuleBuild::isDefensive(const UnitType * building) {
+ if (ai->outputAIBehaviourToConsole())
+ printf("BUILD isDefensive check for Unit Name[%s] result = %d\n",
+ building->getName(false).c_str(),
+ building->hasSkillClass(scAttack));
+
+ return building->hasSkillClass(scAttack);
+ }
+
+ bool
+ AiRuleBuild::isResourceProducer(const UnitType * building) {
+ for (int i = 0; i < building->getCostCount(); i++) {
+ if (building->getCost(i)->getAmount() < 0) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("BUILD isResourceProducer check for Unit Name[%s] result = true\n",
+ building->getName(false).c_str());
+
+ return true;
+ }
+ }
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("BUILD isResourceProducer check for Unit Name[%s] result = false\n",
+ building->getName(false).c_str());
+
+ return false;
+ }
+
+ bool
+ AiRuleBuild::isWarriorProducer(const UnitType * building) {
+ for (int i = 0; i < building->getCommandTypeCount(); i++) {
+ const CommandType *
+ ct = building->getCommandType(i);
+ if (ct->getClass() == ccProduce) {
+ const UnitType *
+ ut = static_cast (ct)->
+ getProducedUnit();
+
+ if (ut->isOfClass(ucWarrior)) {
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("BUILD isWarriorProducer check for Unit Name[%s] result = true\n",
+ building->getName(false).c_str());
+
+ return true;
+ }
+ }
+ }
+ if (ai->outputAIBehaviourToConsole())
+ printf
+ ("BUILD isWarriorProducer check for Unit Name[%s] result = false\n",
+ building->getName(false).c_str());
+
+ return false;
+ }
+
+ // ========================================
+ // class AiRuleUpgrade
+ // ========================================
+
+ AiRuleUpgrade::AiRuleUpgrade(Ai * ai) :
+ AiRule(ai) {
+ upgradeTask = NULL;
+ }
+
+ bool
+ AiRuleUpgrade::test() {
+ const Task *
+ task = ai->getTask();
+
+ if (task == NULL || task->getClass() != tcUpgrade) {
+ return false;
+ }
+
+ upgradeTask = static_cast (task);
+ return true;
+ }
+
+ void
+ AiRuleUpgrade::execute() {
+
+ //upgrade any upgrade
+ if (upgradeTask->getUpgradeType() == NULL) {
+ upgradeGeneric(upgradeTask);
+ }
+ //upgrade specific upgrade
+ else {
+ upgradeSpecific(upgradeTask);
+ }
+
+ //remove the task
+ ai->removeTask(upgradeTask);
+ }
+
+ void
+ AiRuleUpgrade::upgradeGeneric(const UpgradeTask * upgt) {
+
+ typedef
+ vector < const UpgradeType *>
+ UpgradeTypes;
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ //find upgrades that can be upgraded
+ UpgradeTypes
+ upgrades;
+
+ if (aiInterface->getMyFactionType()->getAIBehaviorUpgrades().size() >
+ 0) {
+ const
+ std::vector < const UpgradeType *>&
+ upgradeList =
+ aiInterface->getMyFactionType()->getAIBehaviorUpgrades();
+ for (unsigned int i = 0; i < upgradeList.size(); ++i) {
+ const UpgradeType *
+ priorityUpgrade = upgradeList[i];
+
+ //for each upgrade, upgrade it if possible
+ for (int k = 0; k < aiInterface->getMyUnitCount(); ++k) {
+
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(k)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is upgrade
+ if (ct->getClass() == ccUpgrade) {
+ const UpgradeCommandType *
+ upgct = dynamic_cast (ct);
+ if (upgct != NULL) {
+ const UpgradeType *
+ upgrade = upgct->getProducedUpgrade();
+ if (upgrade == priorityUpgrade) {
+ if (aiInterface->reqsOk(upgct) == true &&
+ aiInterface->getMyFaction()->
+ getUpgradeManager()->
+ isUpgradingOrUpgraded(priorityUpgrade)
+ == false) {
+ //if(ai->getRandom()->randRange(0, 1)==0) {
+ ai->
+ addTask(new
+ UpgradeTask
+ (priorityUpgrade));
+ return;
+ //}
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //for each upgrade, upgrade it if possible
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is upgrade
+ if (ct->getClass() == ccUpgrade) {
+ const UpgradeCommandType *
+ upgct = static_cast (ct);
+ const UpgradeType *
+ upgrade = upgct->getProducedUpgrade();
+ if (aiInterface->reqsOk(upgct)) {
+ upgrades.push_back(upgrade);
+ }
+ }
+ }
+ }
+
+ //add specific upgrade task
+ if (!upgrades.empty()) {
+ ai->
+ addTask(new
+ UpgradeTask(upgrades
+ [ai->getRandom()->
+ randRange(0,
+ (int) upgrades.size() - 1)]));
+ }
+ }
+
+ void
+ AiRuleUpgrade::upgradeSpecific(const UpgradeTask * upgt) {
+
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ //if reqs ok
+ if (aiInterface->reqsOk(upgt->getUpgradeType())) {
+
+ //if resources dont meet retry
+ if (!aiInterface->checkCosts(upgt->getUpgradeType(), NULL)) {
+ ai->retryTask(upgt);
+ return;
+ }
+
+ //for each unit
+ for (int i = 0; i < aiInterface->getMyUnitCount(); ++i) {
+
+ //for each command
+ const UnitType *
+ ut = aiInterface->getMyUnit(i)->getType();
+ for (int j = 0; j < ut->getCommandTypeCount(); ++j) {
+ const CommandType *
+ ct = ut->getCommandType(j);
+
+ //if the command is upgrade
+ if (ct->getClass() == ccUpgrade) {
+ const UpgradeCommandType *
+ uct = static_cast (ct);
+ const UpgradeType *
+ producedUpgrade = uct->getProducedUpgrade();
+
+ //if upgrades match
+ if (producedUpgrade == upgt->getUpgradeType()) {
+ if (aiInterface->reqsOk(uct)) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugSystem).enabled)
+ SystemFlags::OutputDebug(SystemFlags::
+ debugSystem,
+ "In [%s::%s Line: %d]\n",
+ __FILE__,
+ __FUNCTION__,
+ __LINE__);
+ aiInterface->giveCommand(i, uct);
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+
+ // ========================================
+ // class AiRuleExpand
+ // ========================================
+
+ AiRuleExpand::AiRuleExpand(Ai * ai) :
+ AiRule(ai) {
+ storeType = NULL;
+ }
+
+ bool
+ AiRuleExpand::test() {
+ AiInterface *
+ aiInterface = ai->getAiInterface();
+
+ int
+ unitCount = aiInterface->getMyUnitCount();
+ for (int i = 0;
+ i < aiInterface->getTechTree()->getResourceTypeCount(); ++i) {
+ const ResourceType *
+ rt = aiInterface->getTechTree()->getResourceType(i);
+ if (rt->getClass() == rcTech) {
+ bool
+ factionUsesResourceType =
+ aiInterface->factionUsesResourceType(aiInterface->
+ getMyFactionType(),
+ rt);
+ if (factionUsesResourceType == true) {
+ // If any resource sighted
+ if (aiInterface->
+ getNearestSightedResource(rt,
+ aiInterface->
+ getHomeLocation(),
+ expandPos, true)) {
+ int
+ minDistance = INT_MAX;
+ storeType = NULL;
+
+ //If there is no close store
+ for (int j = 0; j < unitCount; ++j) {
+ const Unit *
+ u = aiInterface->getMyUnit(j);
+ const UnitType *
+ ut = u->getType();
+
+ // If this building is a store
+ if (ut->getStore(rt) > 0) {
+ storeType = ut;
+ int
+ distance =
+ static_cast <
+ int>(u->getPosNotThreadSafe().
+ dist(expandPos));
+ if (distance < minDistance) {
+ minDistance = distance;
+ }
+ }
+ }
+
+ if (minDistance > expandDistance) {
+ return true;
+ }
+ } else {
+ // send patrol to look for resource
+ ai->sendScoutPatrol();
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ void
+ AiRuleExpand::execute() {
+ ai->addExpansion(expandPos);
+ ai->addPriorityTask(new BuildTask(storeType, expandPos));
+ }
+
+
+ // ========================================
+ // class AiRuleUnBlock
+ // ========================================
+
+ AiRuleUnBlock::AiRuleUnBlock(Ai * ai) :
+ AiRule(ai) {
+
+ }
+
+ bool
+ AiRuleUnBlock::test() {
+ return ai->haveBlockedUnits();
+ }
+
+ void
+ AiRuleUnBlock::execute() {
+ ai->unblockUnits();
+ }
+
+ }
+} //end namespace
diff --git a/source/glest_game/ai/ai_rule.h b/source/glest_game/ai/ai_rule.h
index c1757fabe..d96f2ea91 100644
--- a/source/glest_game/ai/ai_rule.h
+++ b/source/glest_game/ai/ai_rule.h
@@ -23,642 +23,597 @@
# include "leak_dumper.h"
using
- std::string;
+std::string;
using
- Shared::Graphics::Vec2i;
+Shared::Graphics::Vec2i;
namespace
- Glest
-{
- namespace
- Game
- {
-
- class
- Ai;
- class
- AiInterface;
- class
- Unit;
- class
- UnitType;
- class
- ProduceTask;
- class
- BuildTask;
- class
- UpgradeTask;
- class
- ResourceType;
-
-// =====================================================
-// class AiRule
-//
-/// An action that the AI will perform periodically
-/// if the test succeeds
-// =====================================================
-
-// The general structure of the rules for an AI to do a task.
- class
- AiRule
- {
- protected:
- Ai *
- ai;
-
- public:
- explicit
- AiRule (Ai * ai);
- virtual ~
- AiRule ()
- {
- }
-
- virtual int
- getTestInterval () const = 0; //in milliseconds
- virtual string
- getName () const = 0;
-
- virtual bool
- test () = 0;
- virtual void
- execute () = 0;
- };
-
-// =====================================================
-// class AiRuleWorkerHarvest
-// =====================================================
-
-// The rules for AI tasks inherit from the generic AiRule class.
- class
- AiRuleWorkerHarvest:
- public
- AiRule
- {
- private:
- int
- stoppedWorkerIndex;
-
- public:
- explicit
- AiRuleWorkerHarvest (Ai * ai);
- // This value returned byt getTestInterval()
- // is called in ai.cpp to determine the chance the rule is executed.
- virtual int
- getTestInterval () const
- {
- return
- 1000;
- }
- virtual string
- getName () const
- {
- return
- "Worker stopped => Order worker to harvest";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleRefreshHarvester
-// =====================================================
-
- class
- AiRuleRefreshHarvester:
- public
- AiRule
- {
- private:
- int
- workerIndex;
-
- public:
- explicit
- AiRuleRefreshHarvester (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 20000;
- }
- virtual string
- getName () const
- {
- return
- "Worker reassigned to needed resource";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleScoutPatrol
-// =====================================================
-
- class
- AiRuleScoutPatrol:
- public
- AiRule
- {
- public:
- explicit
- AiRuleScoutPatrol (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 10000;
- }
- virtual string
- getName () const
- {
- return
- "Base is stable => Send scout patrol";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleRepair
-// =====================================================
-
- class
- AiRuleRepair:
- public
- AiRule
- {
- private:
- int
- damagedUnitIndex;
- bool
- damagedUnitIsCastle;
-
- int
- getMinUnitsToRepairCastle ();
- double
- getMinCastleHpRatio () const;
-
- public:
- explicit
- AiRuleRepair (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 10000;
- }
- virtual string
- getName () const
- {
- return
- "Building Damaged => Repair";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleReturnBase
-// =====================================================
-
- class
- AiRuleReturnBase:
- public
- AiRule
- {
- private:
- int
- stoppedUnitIndex;
- public:
- explicit
- AiRuleReturnBase (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 5000;
- }
- virtual string
- getName () const
- {
- return
- "Stopped unit => Order return base";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleMassiveAttack
-// =====================================================
-
- class
- AiRuleMassiveAttack:
- public
- AiRule
- {
- private:
- static const int
- baseRadius = 25;
-
- private:
- Vec2i
- attackPos;
- Field
- field;
- bool
- ultraAttack;
-
- public:
- explicit
- AiRuleMassiveAttack (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 1000;
- }
- virtual string
- getName () const
- {
- return
- "Unit under attack => Order massive attack";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleAddTasks
-// =====================================================
-
- class
- AiRuleAddTasks:
- public
- AiRule
- {
- public:
- explicit
- AiRuleAddTasks (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 5000;
- }
- virtual string
- getName () const
- {
- return
- "Tasks empty => Add tasks";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleBuildOneFarm
-// =====================================================
-
- class
- AiRuleBuildOneFarm:
- public
- AiRule
- {
- private:
- const UnitType *
- farm;
-
- public:
- explicit
- AiRuleBuildOneFarm (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 10000;
- }
- virtual string
- getName () const
- {
- return
- "No farms => Build one";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleProduceResourceProducer
-// =====================================================
-
- class
- AiRuleProduceResourceProducer:
- public
- AiRule
- {
- private:
- static const int
- minStaticResources = 20;
- static const int
- longInterval = 60000;
- static const int
- shortInterval = 5000;
- const ResourceType *
- rt;
- int
- interval;
- bool
- newResourceBehaviour;
-
- public:
- explicit
- AiRuleProduceResourceProducer (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- interval;
- }
- virtual string
- getName () const
- {
- return
- "No resources => Build Resource Producer";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleProduce
-// =====================================================
-
- class
- AiRuleProduce:
- public
- AiRule
- {
- private:
- const ProduceTask *
- produceTask;
-
- typedef
- vector < const UnitType *>
- UnitTypes;
- typedef
- vector <
- bool >
- UnitTypesGiveBack;
- bool
- newResourceBehaviour;
-
- public:
- explicit
- AiRuleProduce (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 100;
- }
- virtual string
- getName () const
- {
- return
- "Performing produce task";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
-
- private:
- void
- produceGeneric (const ProduceTask * pt);
- void
- produceGenericNew (const ProduceTask * pt);
- void
- produceSpecific (const ProduceTask * pt);
- bool
- canUnitTypeOfferResourceType (const UnitType * ut,
- const ResourceType * rt);
- bool
- setAIProduceTaskForResourceType (const ProduceTask * pt,
- AiInterface * aiInterface);
- void
- addUnitTypeToCandidates (const UnitType * producedUnit,
- UnitTypes & ableUnits,
- UnitTypesGiveBack & ableUnitsGiveBack,
- bool unitCanGiveBackResource);
- };
-// =====================================================
-// class AiRuleBuild
-// =====================================================
-
- class
- AiRuleBuild:
- public
- AiRule
- {
- private:
- const BuildTask *
- buildTask;
-
- public:
- explicit
- AiRuleBuild (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 2000;
- }
- virtual string
- getName () const
- {
- return
- "Performing build task";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
-
- private:
- void
- buildGeneric (const BuildTask * bt);
- void
- buildSpecific (const BuildTask * bt);
- void
- buildBestBuilding (const vector < const UnitType * >&buildings);
-
- bool
- isDefensive (const UnitType * building);
- bool
- isResourceProducer (const UnitType * building);
- bool
- isWarriorProducer (const UnitType * building);
- };
-
-// =====================================================
-// class AiRuleUpgrade
-// =====================================================
-
- class
- AiRuleUpgrade:
- public
- AiRule
- {
- private:
- const UpgradeTask *
- upgradeTask;
-
- public:
- explicit
- AiRuleUpgrade (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 2000;
- }
- virtual string
- getName () const
- {
- return
- "Performing upgrade task";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
-
- private:
- void
- upgradeSpecific (const UpgradeTask * upgt);
- void
- upgradeGeneric (const UpgradeTask * upgt);
- };
-
-// =====================================================
-// class AiRuleExpand
-// =====================================================
-
- class
- AiRuleExpand:
- public
- AiRule
- {
- private:
- static const int
- expandDistance = 30;
-
- private:
- Vec2i
- expandPos;
- const UnitType *
- storeType;
-
- public:
- explicit
- AiRuleExpand (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 30000;
- }
- virtual string
- getName () const
- {
- return
- "Expanding";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-// =====================================================
-// class AiRuleUnBlock
-// =====================================================
-
- class
- AiRuleUnBlock:
- public
- AiRule
- {
- public:
- explicit
- AiRuleUnBlock (Ai * ai);
-
- virtual int
- getTestInterval () const
- {
- return
- 3000;
- }
- virtual string
- getName () const
- {
- return
- "Blocked Units => Move surrounding units";
- }
-
- virtual bool
- test ();
- virtual void
- execute ();
- };
-
-}} //end namespace
+ Glest {
+ namespace
+ Game {
+
+ class
+ Ai;
+ class
+ AiInterface;
+ class
+ Unit;
+ class
+ UnitType;
+ class
+ ProduceTask;
+ class
+ BuildTask;
+ class
+ UpgradeTask;
+ class
+ ResourceType;
+
+ // =====================================================
+ // class AiRule
+ //
+ /// An action that the AI will perform periodically
+ /// if the test succeeds
+ // =====================================================
+
+ // The general structure of the rules for an AI to do a task.
+ class
+ AiRule {
+ protected:
+ Ai *
+ ai;
+
+ public:
+ explicit
+ AiRule(Ai * ai);
+ virtual ~
+ AiRule() {
+ }
+
+ virtual int
+ getTestInterval() const = 0; //in milliseconds
+ virtual string
+ getName() const = 0;
+
+ virtual bool
+ test() = 0;
+ virtual void
+ execute() = 0;
+ };
+
+ // =====================================================
+ // class AiRuleWorkerHarvest
+ // =====================================================
+
+ // The rules for AI tasks inherit from the generic AiRule class.
+ class
+ AiRuleWorkerHarvest :
+ public
+ AiRule {
+ private:
+ int
+ stoppedWorkerIndex;
+
+ public:
+ explicit
+ AiRuleWorkerHarvest(Ai * ai);
+ // This value returned byt getTestInterval()
+ // is called in ai.cpp to determine the chance the rule is executed.
+ virtual int
+ getTestInterval() const {
+ return
+ 1000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Worker stopped => Order worker to harvest";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleRefreshHarvester
+ // =====================================================
+
+ class
+ AiRuleRefreshHarvester :
+ public
+ AiRule {
+ private:
+ int
+ workerIndex;
+
+ public:
+ explicit
+ AiRuleRefreshHarvester(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 20000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Worker reassigned to needed resource";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleScoutPatrol
+ // =====================================================
+
+ class
+ AiRuleScoutPatrol :
+ public
+ AiRule {
+ public:
+ explicit
+ AiRuleScoutPatrol(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 10000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Base is stable => Send scout patrol";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleRepair
+ // =====================================================
+
+ class
+ AiRuleRepair :
+ public
+ AiRule {
+ private:
+ int
+ damagedUnitIndex;
+ bool
+ damagedUnitIsCastle;
+
+ int
+ getMinUnitsToRepairCastle();
+ double
+ getMinCastleHpRatio() const;
+
+ public:
+ explicit
+ AiRuleRepair(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 10000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Building Damaged => Repair";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleReturnBase
+ // =====================================================
+
+ class
+ AiRuleReturnBase :
+ public
+ AiRule {
+ private:
+ int
+ stoppedUnitIndex;
+ public:
+ explicit
+ AiRuleReturnBase(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 5000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Stopped unit => Order return base";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleMassiveAttack
+ // =====================================================
+
+ class
+ AiRuleMassiveAttack :
+ public
+ AiRule {
+ private:
+ static const int
+ baseRadius = 25;
+
+ private:
+ Vec2i
+ attackPos;
+ Field
+ field;
+ bool
+ ultraAttack;
+
+ public:
+ explicit
+ AiRuleMassiveAttack(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 1000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Unit under attack => Order massive attack";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleAddTasks
+ // =====================================================
+
+ class
+ AiRuleAddTasks :
+ public
+ AiRule {
+ public:
+ explicit
+ AiRuleAddTasks(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 5000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Tasks empty => Add tasks";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleBuildOneFarm
+ // =====================================================
+
+ class
+ AiRuleBuildOneFarm :
+ public
+ AiRule {
+ private:
+ const UnitType *
+ farm;
+
+ public:
+ explicit
+ AiRuleBuildOneFarm(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 10000;
+ }
+ virtual string
+ getName() const {
+ return
+ "No farms => Build one";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleProduceResourceProducer
+ // =====================================================
+
+ class
+ AiRuleProduceResourceProducer :
+ public
+ AiRule {
+ private:
+ static const int
+ minStaticResources = 20;
+ static const int
+ longInterval = 60000;
+ static const int
+ shortInterval = 5000;
+ const ResourceType *
+ rt;
+ int
+ interval;
+ bool
+ newResourceBehaviour;
+
+ public:
+ explicit
+ AiRuleProduceResourceProducer(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ interval;
+ }
+ virtual string
+ getName() const {
+ return
+ "No resources => Build Resource Producer";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleProduce
+ // =====================================================
+
+ class
+ AiRuleProduce :
+ public
+ AiRule {
+ private:
+ const ProduceTask *
+ produceTask;
+
+ typedef
+ vector < const UnitType *>
+ UnitTypes;
+ typedef
+ vector <
+ bool >
+ UnitTypesGiveBack;
+ bool
+ newResourceBehaviour;
+
+ public:
+ explicit
+ AiRuleProduce(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 2000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Performing produce task";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+
+ private:
+ void
+ produceGeneric(const ProduceTask * pt);
+ void
+ produceGenericNew(const ProduceTask * pt);
+ void
+ produceSpecific(const ProduceTask * pt);
+ bool
+ canUnitTypeOfferResourceType(const UnitType * ut,
+ const ResourceType * rt);
+ bool
+ setAIProduceTaskForResourceType(const ProduceTask * pt,
+ AiInterface * aiInterface);
+ void
+ addUnitTypeToCandidates(const UnitType * producedUnit,
+ UnitTypes & ableUnits,
+ UnitTypesGiveBack & ableUnitsGiveBack,
+ bool unitCanGiveBackResource);
+ };
+ // =====================================================
+ // class AiRuleBuild
+ // =====================================================
+
+ class
+ AiRuleBuild :
+ public
+ AiRule {
+ private:
+ const BuildTask *
+ buildTask;
+
+ public:
+ explicit
+ AiRuleBuild(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 1000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Performing build task";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+
+ private:
+ void
+ buildGeneric(const BuildTask * bt);
+ void
+ buildSpecific(const BuildTask * bt);
+ void
+ buildBestBuilding(const vector < const UnitType * >&buildings);
+
+ bool
+ isDefensive(const UnitType * building);
+ bool
+ isResourceProducer(const UnitType * building);
+ bool
+ isWarriorProducer(const UnitType * building);
+ };
+
+ // =====================================================
+ // class AiRuleUpgrade
+ // =====================================================
+
+ class
+ AiRuleUpgrade :
+ public
+ AiRule {
+ private:
+ const UpgradeTask *
+ upgradeTask;
+
+ public:
+ explicit
+ AiRuleUpgrade(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 2000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Performing upgrade task";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+
+ private:
+ void
+ upgradeSpecific(const UpgradeTask * upgt);
+ void
+ upgradeGeneric(const UpgradeTask * upgt);
+ };
+
+ // =====================================================
+ // class AiRuleExpand
+ // =====================================================
+
+ class
+ AiRuleExpand :
+ public
+ AiRule {
+ private:
+ static const int
+ expandDistance = 30;
+
+ private:
+ Vec2i
+ expandPos;
+ const UnitType *
+ storeType;
+
+ public:
+ explicit
+ AiRuleExpand(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 30000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Expanding";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ // =====================================================
+ // class AiRuleUnBlock
+ // =====================================================
+
+ class
+ AiRuleUnBlock :
+ public
+ AiRule {
+ public:
+ explicit
+ AiRuleUnBlock(Ai * ai);
+
+ virtual int
+ getTestInterval() const {
+ return
+ 3000;
+ }
+ virtual string
+ getName() const {
+ return
+ "Blocked Units => Move surrounding units";
+ }
+
+ virtual bool
+ test();
+ virtual void
+ execute();
+ };
+
+ }
+} //end namespace
#endif
diff --git a/source/glest_game/ai/path_finder.cpp b/source/glest_game/ai/path_finder.cpp
index c383dc71b..d03016ec7 100644
--- a/source/glest_game/ai/path_finder.cpp
+++ b/source/glest_game/ai/path_finder.cpp
@@ -24,2096 +24,1852 @@
using namespace std;
using namespace
- Shared::Graphics;
+Shared::Graphics;
using namespace
- Shared::Util;
+Shared::Util;
using namespace
- Shared::PlatformCommon;
+Shared::PlatformCommon;
using
- Shared::Util::RandomGen;
+Shared::Util::RandomGen;
namespace
- Glest
-{
- namespace
- Game
- {
-
-// =====================================================
-// class PathFinder
-// =====================================================
-
-// ===================== PUBLIC ========================
-
- const int
- PathFinder::maxFreeSearchRadius = 10;
-
- int
- PathFinder::pathFindNodesAbsoluteMax = 900;
- int
- PathFinder::pathFindNodesMax = 2000;
- const int
- PathFinder::pathFindBailoutRadius = 20;
- const int
- PathFinder::pathFindExtendRefreshForNodeCount = 25;
- const int
- PathFinder::pathFindExtendRefreshNodeCountMin = 40;
- const int
- PathFinder::pathFindExtendRefreshNodeCountMax = 40;
-
- PathFinder::PathFinder ()
- {
- minorDebugPathfinder = false;
- map = NULL;
- }
-
- int
- PathFinder::getPathFindExtendRefreshNodeCount (FactionState & faction)
- {
- //int refreshNodeCount = faction.random.randRange(PathFinder::pathFindExtendRefreshNodeCountMin,PathFinder::pathFindExtendRefreshNodeCountMax);
- //return refreshNodeCount;
- return PathFinder::pathFindExtendRefreshNodeCountMin;
- }
-
- PathFinder::PathFinder (const Map * map)
- {
- minorDebugPathfinder = false;
-
- map = NULL;
- init (map);
- }
-
- void
- PathFinder::init (const Map * map)
- {
- for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers;
- ++factionIndex)
- {
- FactionState & faction = factions.getFactionState (factionIndex);
-
- faction.nodePool.resize (pathFindNodesAbsoluteMax);
- faction.useMaxNodeCount = PathFinder::pathFindNodesMax;
- }
- this->map = map;
- }
-
- void
- PathFinder::init ()
- {
- minorDebugPathfinder = false;
- map = NULL;
- }
-
- PathFinder::~PathFinder ()
- {
- for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers;
- ++factionIndex)
- {
- FactionState & faction = factions.getFactionState (factionIndex);
-
- faction.nodePool.clear ();
- }
- factions.clear ();
- map = NULL;
- }
-
- void
- PathFinder::clearCaches ()
- {
- for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers;
- ++factionIndex)
- {
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- FactionState & faction = factions.getFactionState (factionIndex);
- MutexSafeWrapper
- safeMutex (faction.getMutexPreCache (), mutexOwnerId);
-
- faction.precachedTravelState.clear ();
- faction.precachedPath.clear ();
- }
- }
-
- void
- PathFinder::clearUnitPrecache (Unit * unit)
- {
- if (unit != NULL && factions.size () > unit->getFactionIndex ())
- {
- int
- factionIndex = unit->getFactionIndex ();
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- FactionState & faction = factions.getFactionState (factionIndex);
- MutexSafeWrapper
- safeMutex (faction.getMutexPreCache (), mutexOwnerId);
-
- faction.precachedTravelState[unit->getId ()] = tsImpossible;
- faction.precachedPath[unit->getId ()].clear ();
- }
- }
-
- void
- PathFinder::removeUnitPrecache (Unit * unit)
- {
- if (unit != NULL && factions.size () > unit->getFactionIndex ())
- {
- int
- factionIndex = unit->getFactionIndex ();
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- FactionState & faction = factions.getFactionState (factionIndex);
- MutexSafeWrapper
- safeMutex (faction.getMutexPreCache (), mutexOwnerId);
-
- if (faction.precachedTravelState.find (unit->getId ()) !=
- faction.precachedTravelState.end ())
- {
- faction.precachedTravelState.erase (unit->getId ());
- }
- if (faction.precachedPath.find (unit->getId ()) !=
- faction.precachedPath.end ())
- {
- faction.precachedPath.erase (unit->getId ());
- }
- }
- }
-
- TravelState
- PathFinder::findPath (Unit * unit, const Vec2i & finalPos,
- bool * wasStuck, int frameIndex)
- {
- TravelState
- ts = tsImpossible;
-
- try
- {
-
- int
- factionIndex = unit->getFactionIndex ();
- FactionState & faction = factions.getFactionState (factionIndex);
- static string
- mutexOwnerId =
- string (__FILE__) + string ("_") + intToStr (__LINE__);
- MutexSafeWrapper
- safeMutexPrecache (faction.getMutexPreCache (), mutexOwnerId);
-
- if (map == NULL)
- {
- throw
- megaglest_runtime_error ("map == NULL");
- }
-
- unit->setCurrentPathFinderDesiredFinalPos (finalPos);
-
-
- if (frameIndex >= 0)
- {
- clearUnitPrecache (unit);
- }
- if (unit->getFaction ()->canUnitsPathfind () == true)
- {
- unit->getFaction ()->addUnitToPathfindingList (unit->getId ());
- }
- else
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "canUnitsPathfind() == false");
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- return tsBlocked;
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "[findPath] unit->getPos() [%s] finalPos [%s]",
- unit->getPos ().getString ().c_str (),
- finalPos.getString ().c_str ());
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- //route cache
- if (finalPos == unit->getPos ())
- {
- if (frameIndex < 0)
- {
- //if arrived
- unit->setCurrSkill (scStop);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Unit finalPos [%s] == unit->getPos() [%s]",
- finalPos.getString ().c_str (),
- unit->getPos ().getString ().c_str ());
- unit->
- logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- }
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPathFinder).enabled ==
- true)
- {
- string
- commandDesc = "none";
- Command *
- command = unit->getCurrCommand ();
- if (command != NULL && command->getCommandType () != NULL)
- {
- commandDesc =
- command->getCommandType ()->toString (false);
- }
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "State: arrived#1 at pos: %s, command [%s]",
- finalPos.getString ().c_str (),
- commandDesc.c_str ());
- unit->setCurrentUnitTitle (szBuf);
- }
-
- return tsArrived;
- }
-
- UnitPathInterface *
- path = unit->getPath ();
- if (path->isEmpty () == false)
- {
- UnitPathBasic *
- basic_path = dynamic_cast < UnitPathBasic * >(path);
- if (basic_path != NULL)
- {
- //route cache
- Vec2i
- pos = basic_path->pop (frameIndex < 0);
-
- if (map->canMove (unit, unit->getPos (), pos))
- {
- if (frameIndex < 0)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).enabled ==
- true
- && SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "#1 map->canMove to pos [%s] from [%s]",
- pos.getString ().c_str (),
- unit->getPos ().getString ().c_str ());
- unit->
- logSynchData (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
-
- unit->setTargetPos (pos, frameIndex < 0);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).enabled ==
- true
- && SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "#2 map->canMove to pos [%s] from [%s]",
- pos.getString ().c_str (),
- unit->getPos ().getString ().c_str ());
- unit->
- logSynchData (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
-
- }
-
- return tsMoving;
- }
- }
- else if (dynamic_cast < UnitPath * >(path) != NULL)
- {
- UnitPath *
- advPath = dynamic_cast < UnitPath * >(path);
- //route cache
- Vec2i
- pos = advPath->peek ();
- if (map->canMove (unit, unit->getPos (), pos))
- {
- if (frameIndex < 0)
- {
- advPath->pop ();
- unit->setTargetPos (pos, frameIndex < 0);
- }
-
- return tsMoving;
- }
- }
- else
- {
- throw
- megaglest_runtime_error
- ("unsupported or missing path finder detected!");
- }
- }
-
- if (path->isStuck () == true &&
- (unit->getLastStuckPos () == finalPos
- || path->getBlockCount () > 500)
- && unit->
- isLastStuckFrameWithinCurrentFrameTolerance (frameIndex >= 0) ==
- true)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "path->isStuck() == true unit->getLastStuckPos() [%s] finalPos [%s] path->getBlockCount() [%d]",
- unit->getLastStuckPos ().getString ().c_str (),
- finalPos.getString ().c_str (),
- path->getBlockCount ());
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- return tsBlocked;
- }
-
- //route cache miss
- int
- maxNodeCount = -1;
- if (unit->getUsePathfinderExtendedMaxNodes () == true)
- {
-
- maxNodeCount = PathFinder::pathFindNodesAbsoluteMax;
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "maxNodeCount: %d", maxNodeCount);
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
- }
-
- bool
- minorDebugPathfinderPerformance = false;
- Chrono
- chrono;
- if (minorDebugPathfinderPerformance)
- chrono.start ();
-
- uint32
- searched_node_count = 0;
- minorDebugPathfinder = false;
- if (minorDebugPathfinder)
- printf
- ("Legacy Pathfind Unit [%d - %s] from = %s to = %s frameIndex = %d\n",
- unit->getId (), unit->getType ()->getName (false).c_str (),
- unit->getPos ().getString ().c_str (),
- finalPos.getString ().c_str (), frameIndex);
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "calling aStar()");
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- ts =
- aStar (unit, finalPos, false, frameIndex, maxNodeCount,
- &searched_node_count);
- //post actions
- switch (ts)
- {
- case tsBlocked:
- case tsArrived:
- // The unit is stuck (not only blocked but unable to go anywhere for a while)
- // We will try to bail out of the immediate area
- if (ts == tsBlocked && unit->getInBailOutAttempt () == false &&
- path->isStuck () == true)
- {
-
- if (minorDebugPathfinder)
- printf
- ("Pathfind Unit [%d - %s] START BAILOUT ATTEMPT frameIndex = %d\n",
- unit->getId (),
- unit->getType ()->getName (false).c_str (), frameIndex);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "[attempting to BAIL OUT] finalPos [%s] ts [%d]",
- finalPos.getString ().c_str (), ts);
- unit->
- logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- if (wasStuck != NULL)
- {
- *wasStuck = true;
- }
- unit->setInBailOutAttempt (true);
-
- bool
- unitImmediatelyBlocked = false;
-
- // First check if unit currently blocked all around them, if so don't try to pathfind
- const Vec2i
- unitPos = unit->getPos ();
- int
- failureCount = 0;
- int
- cellCount = 0;
-
- for (int i = -1; i <= 1; ++i)
- {
- for (int j = -1; j <= 1; ++j)
- {
- Vec2i
- pos = unitPos + Vec2i (i, j);
- if (pos != unitPos)
- {
- bool
- canUnitMoveToCell =
- map->aproxCanMove (unit, unitPos, pos);
- if (canUnitMoveToCell == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- unitImmediatelyBlocked = (failureCount == cellCount);
- if (unitImmediatelyBlocked == false)
- {
-
- int
- factionIndex = unit->getFactionIndex ();
- FactionState & faction =
- factions.getFactionState (factionIndex);
-
- //if(Thread::isCurrentThreadMainThread() == false) {
- // throw megaglest_runtime_error("#2 Invalid access to FactionState random from outside main thread current id = " +
- // intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId()));
- //}
-
- int
- tryRadius = faction.random.randRange (1, 2);
- //int tryRadius = faction.random.IRandomX(1,2);
- //int tryRadius = 1;
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In astar bailout() tryRadius %d",
- tryRadius);
-
- if (frameIndex >= 0)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__,
- szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- // Try to bail out up to PathFinder::pathFindBailoutRadius cells away
- if (tryRadius == 2)
- {
- for (int bailoutX =
- -PathFinder::pathFindBailoutRadius;
- bailoutX <= PathFinder::pathFindBailoutRadius
- && ts == tsBlocked; ++bailoutX)
- {
- for (int bailoutY =
- -PathFinder::pathFindBailoutRadius;
- bailoutY <= PathFinder::pathFindBailoutRadius
- && ts == tsBlocked; ++bailoutY)
- {
- const Vec2i
- newFinalPos =
- finalPos + Vec2i (bailoutX, bailoutY);
- bool
- canUnitMove =
- map->canMove (unit, unit->getPos (),
- newFinalPos);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "[attempting to BAIL OUT] finalPos [%s] newFinalPos [%s] ts [%d] canUnitMove [%d]",
- finalPos.getString ().c_str (),
- newFinalPos.getString ().
- c_str (), ts, canUnitMove);
- unit->
- logSynchData
- (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__, szBuf);
- }
-
- if (canUnitMove)
- {
-
- int
- maxBailoutNodeCount =
- (PathFinder::pathFindBailoutRadius * 2);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "calling aStar()");
- unit->
- logSynchData
- (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
-
- ts =
- aStar (unit, newFinalPos, true,
- frameIndex, maxBailoutNodeCount,
- &searched_node_count);
- }
- }
- }
- }
- else
- {
- for (int bailoutX = PathFinder::pathFindBailoutRadius;
- bailoutX >= -PathFinder::pathFindBailoutRadius
- && ts == tsBlocked; --bailoutX)
- {
- for (int bailoutY =
- PathFinder::pathFindBailoutRadius;
- bailoutY >=
- -PathFinder::pathFindBailoutRadius
- && ts == tsBlocked; --bailoutY)
- {
- const Vec2i
- newFinalPos =
- finalPos + Vec2i (bailoutX, bailoutY);
- bool
- canUnitMove =
- map->canMove (unit, unit->getPos (),
- newFinalPos);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "[attempting to BAIL OUT] finalPos [%s] newFinalPos [%s] ts [%d] canUnitMove [%d]",
- finalPos.getString ().c_str (),
- newFinalPos.getString ().
- c_str (), ts, canUnitMove);
- unit->
- logSynchData
- (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__, szBuf);
- }
-
- if (canUnitMove)
- {
- int
- maxBailoutNodeCount =
- (PathFinder::pathFindBailoutRadius * 2);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "calling aStar()");
- unit->
- logSynchData
- (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
-
- ts =
- aStar (unit, newFinalPos, true,
- frameIndex, maxBailoutNodeCount,
- &searched_node_count);
- }
- }
- }
- }
- }
- unit->setInBailOutAttempt (false);
-
- if (ts == tsBlocked)
- {
- unit->setLastStuckFrameToCurrentFrame ();
- unit->setLastStuckPos (finalPos);
- }
- }
- if (ts == tsArrived || ts == tsBlocked)
- {
- if (frameIndex < 0)
- {
- unit->setCurrSkill (scStop);
- }
- }
- break;
- case tsMoving:
- {
- if (dynamic_cast < UnitPathBasic * >(path) != NULL)
- {
- UnitPathBasic *
- basicPath = dynamic_cast < UnitPathBasic * >(path);
- Vec2i
- pos;
- if (frameIndex < 0 && basicPath != NULL)
- {
- pos = basicPath->pop (frameIndex < 0);
- }
- else
- {
-
- if (faction.precachedPath[unit->getId ()].size () <= 0)
- {
- throw
- megaglest_runtime_error
- ("factions[unit->getFactionIndex()].precachedPath[unit->getId()].size() <= 0!");
- }
-
- pos = faction.precachedPath[unit->getId ()][0];
-
- }
-
- if (map->canMove (unit, unit->getPos (), pos))
- {
- if (frameIndex < 0)
- {
- unit->setTargetPos (pos, frameIndex < 0);
- }
- }
- else
- {
- if (frameIndex < 0)
- {
- unit->setCurrSkill (scStop);
- }
-
- if (minorDebugPathfinderPerformance
- && chrono.getMillis () >= 1)
- printf
- ("Unit [%d - %s] astar #2 took [%lld] msecs, ts = %d searched_node_count = %d.\n",
- unit->getId (),
- unit->getType ()->getName (false).c_str (),
- (long long int) chrono.getMillis (), ts,
- searched_node_count);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "tsBlocked");
- unit->
- logSynchData (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
-
- return tsBlocked;
- }
- }
- else if (dynamic_cast < UnitPath * >(path) != NULL)
- {
- UnitPath *
- advPath = dynamic_cast < UnitPath * >(path);
- Vec2i
- pos = advPath->peek ();
- if (map->canMove (unit, unit->getPos (), pos))
- {
- if (frameIndex < 0)
- {
- advPath->pop ();
- unit->setTargetPos (pos, frameIndex < 0);
- }
- }
- else
- {
- if (frameIndex < 0)
- {
- unit->setCurrSkill (scStop);
- }
-
- if (minorDebugPathfinder)
- printf
- ("Pathfind Unit [%d - %s] INT BAILOUT ATTEMPT BLOCKED frameIndex = %d\n",
- unit->getId (),
- unit->getType ()->getName (false).c_str (),
- frameIndex);
-
- if (minorDebugPathfinderPerformance
- && chrono.getMillis () >= 1)
- printf
- ("Unit [%d - %s] astar #3 took [%lld] msecs, ts = %d searched_node_count = %d.\n",
- unit->getId (),
- unit->getType ()->getName (false).c_str (),
- (long long int) chrono.getMillis (), ts,
- searched_node_count);
- return tsBlocked;
- }
- }
- else
- {
- throw
- megaglest_runtime_error
- ("unsupported or missing path finder detected!");
- }
- }
- break;
-
- default:
- break;
- }
- if (minorDebugPathfinderPerformance && chrono.getMillis () >= 1)
- printf
- ("Unit [%d - %s] astar took [%lld] msecs, ts = %d searched_node_count = %d.\n",
- unit->getId (), unit->getType ()->getName (false).c_str (),
- (long long int) chrono.getMillis (), ts, searched_node_count);
-
- }
- catch (const exception & ex)
- {
- //setRunningStatus(false);
-
- SystemFlags::OutputDebug (SystemFlags::debugError,
- "In [%s::%s Line: %d] Error [%s]\n",
- __FILE__, __FUNCTION__, __LINE__,
- ex.what ());
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- throw
- megaglest_runtime_error (ex.what ());
- }
- catch ( ...)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
- __FUNCTION__, __LINE__);
- SystemFlags::OutputDebug (SystemFlags::debugError, szBuf);
- throw
- megaglest_runtime_error (szBuf);
- }
-
- return ts;
- }
-
-// ==================== PRIVATE ====================
-
-//route a unit using A* algorithm
- TravelState
- PathFinder::aStar (Unit * unit, const Vec2i & targetPos, bool inBailout,
- int frameIndex, int maxNodeCount,
- uint32 * searched_node_count)
- {
- TravelState
- ts = tsImpossible;
-
- try
- {
-
- int
- unitFactionIndex = unit->getFactionIndex ();
- int
- factionIndex = unit->getFactionIndex ();
- FactionState & faction = factions.getFactionState (factionIndex);
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex >= 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "In aStar()");
- unit->logSynchDataThreaded (__FILE__, __LINE__, szBuf);
- }
-
- Chrono
- chrono;
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled)
- chrono.start ();
-
- if (map == NULL)
- {
- throw
- megaglest_runtime_error ("map == NULL");
- }
-
-
- if (maxNodeCount < 0)
- {
-
- int
- factionIndex = unit->getFactionIndex ();
- FactionState & faction = factions.getFactionState (factionIndex);
-
- maxNodeCount = faction.useMaxNodeCount;
- }
-
- if (maxNodeCount >= 1
- && unit->getPathfindFailedConsecutiveFrameCount () >= 3)
- {
- maxNodeCount = 200;
- }
-
- UnitPathInterface *
- path = unit->getPath ();
-
- faction.nodePoolCount = 0;
- faction.openNodesList.clear ();
- faction.openPosList.clear ();
- faction.closedNodesList.clear ();
-
- // check the pre-cache to see if we can re-use a cached path
- if (frameIndex < 0)
- {
-
- bool
- foundPrecacheTravelState =
- (faction.precachedTravelState.find (unit->getId ()) !=
- faction.precachedTravelState.end ());
- if (foundPrecacheTravelState == true)
- {
-
-// if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) {
-// char szBuf[8096]="";
-// snprintf(szBuf,8096,"factions[unitFactionIndex].precachedTravelState[unit->getId()]: %d",faction.precachedTravelState[unit->getId()]);
-// unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf);
-// }
-
- bool
- foundPrecacheTravelStateIsMoving =
- (faction.precachedTravelState[unit->getId ()] == tsMoving);
- if (foundPrecacheTravelStateIsMoving == true)
- {
- bool
- canMoveToCells = true;
-
- Vec2i
- lastPos = unit->getPos ();
-
- int
- unitPrecachePathSize =
- (int) faction.precachedPath[unit->getId ()].size ();
-
- for (int i = 0; i < unitPrecachePathSize; i++)
- {
-
- Vec2i
- nodePos = faction.precachedPath[unit->getId ()][i];
-
- if (map->isInside (nodePos) == false
- || map->isInsideSurface (map->
- toSurfCoords (nodePos))
- == false)
- {
- throw
- megaglest_runtime_error
- ("Pathfinder invalid node path position = " +
- nodePos.getString () + " i = " + intToStr (i));
- }
-
- if (i < unit->getPathFindRefreshCellCount () ||
- (unitPrecachePathSize >=
- pathFindExtendRefreshForNodeCount
- && i <
- getPathFindExtendRefreshNodeCount (faction)))
- {
-
- if (canUnitMoveSoon (unit, lastPos, nodePos) ==
- false)
- {
- canMoveToCells = false;
- break;
- }
- lastPos = nodePos;
- }
- else
- {
- break;
- }
- }
-
- if (canMoveToCells == true)
- {
- path->clear ();
- //UnitPathBasic *basicPathFinder = dynamic_cast(path);
-
- int
- unitPrecachePathSize =
- (int) faction.precachedPath[unit->getId ()].size ();
-
- for (int i = 0; i < unitPrecachePathSize; i++)
- {
-
- Vec2i
- nodePos =
- faction.precachedPath[unit->getId ()][i];
-
- if (map->isInside (nodePos) == false
- || map->isInsideSurface (map->
- toSurfCoords
- (nodePos)) == false)
- {
- throw
- megaglest_runtime_error
- ("Pathfinder invalid node path position = "
- + nodePos.getString () + " i = " +
- intToStr (i));
- }
-
- //if(i < pathFindRefresh ||
- if (i < unit->getPathFindRefreshCellCount () ||
- (unitPrecachePathSize >=
- pathFindExtendRefreshForNodeCount
- && i <
- getPathFindExtendRefreshNodeCount (faction)))
- {
- path->add (nodePos);
- }
- }
- unit->setUsePathfinderExtendedMaxNodes (false);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::
- debugWorldSynch).enabled ==
- true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "return factions[unitFactionIndex].precachedTravelState[unit->getId()];");
- unit->
- logSynchData (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
-
- return faction.precachedTravelState[unit->getId ()];
- }
- else
- {
- clearUnitPrecache (unit);
- }
- }
- else
- {
-
- bool
- foundPrecacheTravelStateIsBlocked =
- (faction.precachedTravelState[unit->getId ()] ==
- tsBlocked);
-
- if (foundPrecacheTravelStateIsBlocked == true)
- {
- path->incBlockCount ();
- unit->setUsePathfinderExtendedMaxNodes (false);
-
-// if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) {
-// char szBuf[8096]="";
-// snprintf(szBuf,8096,"return factions[unitFactionIndex].precachedTravelState[unit->getId()];");
-// unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf);
-// }
-
- return faction.precachedTravelState[unit->getId ()];
- }
- }
- }
- }
- else
- {
- clearUnitPrecache (unit);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "[clearUnitPrecache]");
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
- }
-
- const Vec2i
- unitPos = unit->getPos ();
- const Vec2i
- finalPos = computeNearestFreePos (unit, targetPos);
-
- float
- dist = unitPos.dist (finalPos);
-
- faction.useMaxNodeCount = PathFinder::pathFindNodesMax;
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath (__FILE__).
- c_str (), __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- //path find algorithm
-
- //a) push starting pos into openNodes
- Node *
- firstNode = newNode (faction, maxNodeCount);
- if (firstNode == NULL)
- {
- throw
- megaglest_runtime_error ("firstNode == NULL");
- }
-
- firstNode->next = NULL;
- firstNode->prev = NULL;
- firstNode->pos = unitPos;
- firstNode->heuristic = heuristic (unitPos, finalPos);
- firstNode->exploredCell = true;
- if (faction.openNodesList.find (firstNode->heuristic) ==
- faction.openNodesList.end ())
- {
- faction.openNodesList[firstNode->heuristic].clear ();
- }
- faction.openNodesList[firstNode->heuristic].push_back (firstNode);
- faction.openPosList[firstNode->pos] = true;
-
- //b) loop
- bool
- pathFound = true;
- bool
- nodeLimitReached = false;
- Node *
- node = NULL;
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath (__FILE__).
- c_str (), __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- // First check if unit currently blocked all around them, if so don't try to pathfind
- if (inBailout == false && unitPos != finalPos)
- {
- int
- failureCount = 0;
- int
- cellCount = 0;
-
- for (int i = -1; i <= 1; ++i)
- {
- for (int j = -1; j <= 1; ++j)
- {
- Vec2i
- pos = unitPos + Vec2i (i, j);
- if (pos != unitPos)
- {
- bool
- canUnitMoveToCell =
- canUnitMoveSoon (unit, unitPos, pos);
- if (canUnitMoveToCell == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- nodeLimitReached = (failureCount == cellCount);
- pathFound = !nodeLimitReached;
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "nodeLimitReached: %d failureCount: %d cellCount: %d",
- nodeLimitReached, failureCount, cellCount);
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 1)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] **Check if dest blocked, distance for unit [%d - %s] from [%s] to [%s] is %.2f took msecs: %lld nodeLimitReached = %d, failureCount = %d\n",
- extractFileFromDirectoryPath
- (__FILE__).c_str (), __FUNCTION__,
- __LINE__, unit->getId (),
- unit->getFullName (false).c_str (),
- unitPos.getString ().c_str (),
- finalPos.getString ().c_str (), dist,
- (long long int) chrono.getMillis (),
- nodeLimitReached, failureCount);
-
- if (nodeLimitReached == false)
- {
- // First check if final destination blocked
- failureCount = 0;
- cellCount = 0;
-
- for (int i = -1; i <= 1; ++i)
- {
- for (int j = -1; j <= 1; ++j)
- {
- Vec2i
- pos = finalPos + Vec2i (i, j);
- if (pos != finalPos)
- {
- bool
- canUnitMoveToCell =
- canUnitMoveSoon (unit, pos, finalPos);
- if (canUnitMoveToCell == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- nodeLimitReached = (failureCount == cellCount);
- pathFound = !nodeLimitReached;
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "nodeLimitReached: %d failureCount: %d cellCount: %d",
- nodeLimitReached, failureCount, cellCount);
- unit->
- logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 1)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] **Check if dest blocked, distance for unit [%d - %s] from [%s] to [%s] is %.2f took msecs: %lld nodeLimitReached = %d, failureCount = %d\n",
- extractFileFromDirectoryPath
- (__FILE__).c_str (), __FUNCTION__,
- __LINE__, unit->getId (),
- unit->getFullName (false).
- c_str (),
- unitPos.getString ().c_str (),
- finalPos.getString ().c_str (),
- dist,
- (long long int) chrono.
- getMillis (), nodeLimitReached,
- failureCount);
- }
- }
- else
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "inBailout: %d unitPos: [%s] finalPos [%s]",
- inBailout, unitPos.getString ().c_str (),
- finalPos.getString ().c_str ());
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
- }
- //
-
- // START
- std::map < std::pair < Vec2i, Vec2i >, bool > canAddNode;
- std::map < Vec2i, bool > closedNodes;
- std::map < Vec2i, Vec2i > cameFrom;
- cameFrom[unitPos] = Vec2i (-1, -1);
-
- // Do the a-star base pathfind work if required
- int
- whileLoopCount = 0;
- if (nodeLimitReached == false)
- {
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d frameIndex: %d",
- nodeLimitReached, whileLoopCount, unitFactionIndex,
- pathFound, finalPos.getString ().c_str (),
- maxNodeCount, frameIndex);
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- doAStarPathSearch (nodeLimitReached, whileLoopCount,
- unitFactionIndex, pathFound, node, finalPos,
- closedNodes, cameFrom, canAddNode, unit,
- maxNodeCount, frameIndex);
-
- if (searched_node_count != NULL)
- {
- *searched_node_count = whileLoopCount;
- }
-
- // Now see if the unit is eligible for pathfind max nodes boost?
- if (nodeLimitReached == true)
- {
- unit->incrementPathfindFailedConsecutiveFrameCount ();
- }
- else
- {
- unit->resetPathfindFailedConsecutiveFrameCount ();
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d pathFindNodesAbsoluteMax: %d frameIndex: %d",
- nodeLimitReached, whileLoopCount, unitFactionIndex,
- pathFound, finalPos.getString ().c_str (),
- maxNodeCount, pathFindNodesAbsoluteMax, frameIndex);
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- if (nodeLimitReached == true
- && maxNodeCount != pathFindNodesAbsoluteMax)
- {
- if (unit->
- isLastPathfindFailedFrameWithinCurrentFrameTolerance () ==
- true)
- {
- if (frameIndex < 0)
- {
- unit->setLastPathfindFailedFrameToCurrentFrame ();
- unit->setLastPathfindFailedPos (finalPos);
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "calling aStar()");
- unit->
- logSynchData (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__, szBuf);
- }
-
- return aStar (unit, targetPos, false, frameIndex,
- pathFindNodesAbsoluteMax);
- }
- }
- }
- else
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "nodeLimitReached: %d",
- nodeLimitReached);
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
- }
-
-
- Node *
- lastNode = node;
-
- //if consumed all nodes find best node (to avoid strange behaviour)
- if (nodeLimitReached == true)
- {
-
- if (faction.closedNodesList.empty () == false)
- {
- float
- bestHeuristic =
- truncateDecimal <
- float >(faction.closedNodesList.begin ()->first, 6);
- if (lastNode != NULL && bestHeuristic < lastNode->heuristic)
- {
- lastNode =
- faction.closedNodesList.begin ()->second.front ();
- }
- }
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath (__FILE__).
- c_str (), __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- //check results of path finding
- ts = tsImpossible;
- if (pathFound == false || lastNode == firstNode)
- {
- if (minorDebugPathfinder)
- printf
- ("Legacy Pathfind Unit [%d - %s] NOT FOUND PATH count = %d frameIndex = %d\n",
- unit->getId (), unit->getType ()->getName ().c_str (),
- whileLoopCount, frameIndex);
-
- //blocked
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPathFinder).enabled ==
- true)
- {
- string
- commandDesc = "none";
- Command *
- command = unit->getCurrCommand ();
- if (command != NULL && command->getCommandType () != NULL)
- {
- commandDesc =
- command->getCommandType ()->toString (false);
- }
-
- std::pair < Vec2i, int >
- lastHarvest = unit->getLastHarvestResourceTarget ();
-
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "State: blocked, cmd [%s] pos: [%s], dest pos: [%s], lastHarvest = [%s - %d], reason A= %d, B= %d, C= %d, D= %d, E= %d, F = %d",
- commandDesc.c_str (),
- unit->getPos ().getString ().c_str (),
- targetPos.getString ().c_str (),
- lastHarvest.first.getString ().c_str (),
- lastHarvest.second, pathFound,
- (lastNode == firstNode), path->getBlockCount (),
- path->isBlocked (), nodeLimitReached,
- path->isStuck ());
- unit->setCurrentUnitTitle (szBuf);
- }
-
- if (frameIndex < 0)
- {
- unit->setUsePathfinderExtendedMaxNodes (false);
- }
-
- ts = tsBlocked;
- if (frameIndex < 0)
- {
- path->incBlockCount ();
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath
- (__FILE__).c_str (), __FUNCTION__,
- __LINE__, chrono.getMillis ());
- }
- else
- {
- if (minorDebugPathfinder)
- printf
- ("Legacy Pathfind Unit [%d - %s] FOUND PATH count = %d frameIndex = %d\n",
- unit->getId (), unit->getType ()->getName ().c_str (),
- whileLoopCount, frameIndex);
- //on the way
- ts = tsMoving;
-
- //build next pointers
- Node *
- currNode = lastNode;
- while (currNode->prev != NULL)
- {
- currNode->prev->next = currNode;
- currNode = currNode->prev;
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath
- (__FILE__).c_str (), __FUNCTION__,
- __LINE__, chrono.getMillis ());
-
- if (frameIndex < 0)
- {
- if (maxNodeCount == pathFindNodesAbsoluteMax)
- {
- unit->setUsePathfinderExtendedMaxNodes (true);
- }
- else
- {
- unit->setUsePathfinderExtendedMaxNodes (false);
- }
- }
-
- //store path
- if (frameIndex < 0)
- {
- path->clear ();
- }
-
- //UnitPathBasic *basicPathFinder = dynamic_cast(path);
-
- currNode = firstNode;
-
- for (int i = 0; currNode->next != NULL;
- currNode = currNode->next, i++)
- {
- Vec2i
- nodePos = currNode->next->pos;
- if (map->isInside (nodePos) == false
- || map->isInsideSurface (map->toSurfCoords (nodePos)) ==
- false)
- {
- throw
- megaglest_runtime_error
- ("Pathfinder invalid node path position = " +
- nodePos.getString () + " i = " + intToStr (i));
- }
-
- if (minorDebugPathfinder)
- printf ("nodePos [%s]\n", nodePos.getString ().c_str ());
-
- if (frameIndex >= 0)
- {
- faction.precachedPath[unit->getId ()].push_back (nodePos);
- }
- else
- {
- if (i < unit->getPathFindRefreshCellCount () ||
- (whileLoopCount >= pathFindExtendRefreshForNodeCount
- && i < getPathFindExtendRefreshNodeCount (faction)))
- {
- path->add (nodePos);
- }
- }
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath
- (__FILE__).c_str (), __FUNCTION__,
- __LINE__, chrono.getMillis ());
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
-
- string
- pathToTake = "";
- if (frameIndex < 0)
- {
- vector < Vec2i > pathQueue = path->getQueue ();
- for (unsigned int index = 0; index < pathQueue.size ();
- ++index)
- {
- Vec2i & pos = pathQueue[index];
- if (pathToTake != "")
- {
- pathToTake += ", ";
- }
- pathToTake += pos.getString ();
- }
- }
- else
- {
- for (unsigned int index = 0;
- index <
- faction.precachedPath[unit->getId ()].size ();
- ++index)
- {
- Vec2i & pos =
- faction.precachedPath[unit->getId ()][index];
- if (pathToTake != "")
- {
- pathToTake += ", ";
- }
- pathToTake += pos.getString ();
- }
- }
- snprintf (szBuf, 8096, "Path for unit to take = %s",
- pathToTake.c_str ());
- if (frameIndex < 0)
- {
- unit->
- logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
- else
- {
- unit->
- logSynchDataThreaded (extractFileFromDirectoryPath
- (__FILE__).c_str (), __LINE__,
- szBuf);
- }
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPathFinder).enabled ==
- true)
- {
- string
- commandDesc = "none";
- Command *
- command = unit->getCurrCommand ();
- if (command != NULL && command->getCommandType () != NULL)
- {
- commandDesc =
- command->getCommandType ()->toString (false);
- }
-
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "State: moving, cmd [%s] pos: %s dest pos: %s, Queue= %d",
- commandDesc.c_str (),
- unit->getPos ().getString ().c_str (),
- targetPos.getString ().c_str (),
- path->getQueueCount ());
- unit->setCurrentUnitTitle (szBuf);
- }
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s Line: %d] took msecs: %lld\n",
- extractFileFromDirectoryPath
- (__FILE__).c_str (), __FUNCTION__,
- __LINE__, chrono.getMillis ());
- }
-
-
- faction.openNodesList.clear ();
- faction.openPosList.clear ();
- faction.closedNodesList.clear ();
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugPerformance).
- enabled == true && chrono.getMillis () > 4)
- SystemFlags::OutputDebug (SystemFlags::debugPerformance,
- "In [%s::%s] Line: %d took msecs: %lld --------------------------- [END OF METHOD] ---------------------------\n",
- extractFileFromDirectoryPath (__FILE__).
- c_str (), __FUNCTION__, __LINE__,
- chrono.getMillis ());
-
- if (frameIndex >= 0)
- {
-
- FactionState & faction = factions.getFactionState (factionIndex);
- faction.precachedTravelState[unit->getId ()] = ts;
- }
- else
- {
- if (SystemFlags::VERBOSE_MODE_ENABLED && chrono.getMillis () >= 5)
- printf
- ("In [%s::%s Line: %d] astar took [%lld] msecs, ts = %d.\n",
- extractFileFromDirectoryPath (__FILE__).c_str (),
- __FUNCTION__, __LINE__, (long long int) chrono.getMillis (),
- ts);
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true && frameIndex < 0)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "return ts: %d", ts);
- unit->logSynchData (extractFileFromDirectoryPath (__FILE__).
- c_str (), __LINE__, szBuf);
- }
-
- }
- catch (const exception & ex)
- {
-
- SystemFlags::OutputDebug (SystemFlags::debugError,
- "In [%s::%s Line: %d] Error [%s]\n",
- __FILE__, __FUNCTION__, __LINE__,
- ex.what ());
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- throw
- megaglest_runtime_error (ex.what ());
- }
- catch ( ...)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
- __FUNCTION__, __LINE__);
- SystemFlags::OutputDebug (SystemFlags::debugError, szBuf);
- throw
- megaglest_runtime_error (szBuf);
- }
-
- return ts;
- }
-
- void
- PathFinder::processNearestFreePos (const Vec2i & finalPos, int i, int j,
- int size, Field field, int teamIndex,
- Vec2i unitPos, Vec2i & nearestPos,
- float &nearestDist)
- {
-
- try
- {
- Vec2i
- currPos = finalPos + Vec2i (i, j);
-
- if (map->isAproxFreeCells (currPos, size, field, teamIndex))
- {
- float
- dist = currPos.dist (finalPos);
-
- //if nearer from finalPos
- if (dist < nearestDist)
- {
- nearestPos = currPos;
- nearestDist = dist;
- }
- //if the distance is the same compare distance to unit
- else if (dist == nearestDist)
- {
- if (currPos.dist (unitPos) < nearestPos.dist (unitPos))
- {
- nearestPos = currPos;
- }
- }
- }
- }
- catch (const exception & ex)
- {
-
- SystemFlags::OutputDebug (SystemFlags::debugError,
- "In [%s::%s Line: %d] Error [%s]\n",
- __FILE__, __FUNCTION__, __LINE__,
- ex.what ());
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- throw
- megaglest_runtime_error (ex.what ());
- }
- catch ( ...)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
- __FUNCTION__, __LINE__);
- SystemFlags::OutputDebug (SystemFlags::debugError, szBuf);
- throw
- megaglest_runtime_error (szBuf);
- }
-
- }
-
- Vec2i
- PathFinder::computeNearestFreePos (const Unit * unit,
- const Vec2i & finalPos)
- {
-
- Vec2i
- nearestPos (0, 0);
- try
- {
-
- if (map == NULL)
- {
- throw
- megaglest_runtime_error ("map == NULL");
- }
-
- //unit data
- int
- size = unit->getType ()->getSize ();
- Field
- field = unit->getCurrField ();
- int
- teamIndex = unit->getTeam ();
-
- //if finalPos is free return it
- if (map->isAproxFreeCells (finalPos, size, field, teamIndex))
- {
- return finalPos;
- }
-
- //find nearest pos
- Vec2i
- unitPos = unit->getPosNotThreadSafe ();
- nearestPos = unitPos;
-
- float
- nearestDist = unitPos.dist (finalPos);
-
- for (int i = -maxFreeSearchRadius; i <= maxFreeSearchRadius; ++i)
- {
- for (int j = -maxFreeSearchRadius; j <= maxFreeSearchRadius; ++j)
- {
- processNearestFreePos (finalPos, i, j, size, field, teamIndex,
- unitPos, nearestPos, nearestDist);
- }
- }
-
- }
- catch (const exception & ex)
- {
-
- SystemFlags::OutputDebug (SystemFlags::debugError,
- "In [%s::%s Line: %d] Error [%s]\n",
- __FILE__, __FUNCTION__, __LINE__,
- ex.what ());
- if (SystemFlags::getSystemSettingType (SystemFlags::debugSystem).
- enabled)
- SystemFlags::OutputDebug (SystemFlags::debugSystem,
- "In [%s::%s Line: %d]\n", __FILE__,
- __FUNCTION__, __LINE__);
-
- throw
- megaglest_runtime_error (ex.what ());
- }
- catch ( ...)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
- __FUNCTION__, __LINE__);
- SystemFlags::OutputDebug (SystemFlags::debugError, szBuf);
- throw
- megaglest_runtime_error (szBuf);
- }
-
- return nearestPos;
- }
-
- int
- PathFinder::findNodeIndex (Node * node, Nodes & nodeList)
- {
- int
- index = -1;
- if (node != NULL)
- {
- for (unsigned int i = 0; i < nodeList.size (); ++i)
- {
- Node *
- curnode = nodeList[i];
- if (node == curnode)
- {
- index = i;
- break;
- }
- }
- }
- return index;
- }
-
- int
- PathFinder::findNodeIndex (Node * node, std::vector < Node > &nodeList)
- {
- int
- index = -1;
- if (node != NULL)
- {
- for (unsigned int i = 0; i < nodeList.size (); ++i)
- {
- Node & curnode = nodeList[i];
- if (node == &curnode)
- {
- index = i;
- break;
- }
- }
- }
- return index;
- }
-
-//bool PathFinder::unitCannotMove(Unit *unit) {
-// bool unitImmediatelyBlocked = false;
-//
-// try {
-// // First check if unit currently blocked all around them, if so don't try to pathfind
-// const Vec2i unitPos = unit->getPos();
-// int failureCount = 0;
-// int cellCount = 0;
-//
-// for(int i = -1; i <= 1; ++i) {
-// for(int j = -1; j <= 1; ++j) {
-// Vec2i pos = unitPos + Vec2i(i, j);
-// if(pos != unitPos) {
-// bool canUnitMoveToCell = map->aproxCanMove(unit, unitPos, pos);
-// if(canUnitMoveToCell == false) {
-// failureCount++;
-// }
-// cellCount++;
-// }
-// }
-// }
-// unitImmediatelyBlocked = (failureCount == cellCount);
-//
-// }
-// catch(const exception &ex) {
-// //setRunningStatus(false);
-//
-// SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what());
-// if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
-//
-// throw megaglest_runtime_error(ex.what());
-// }
-// catch(...) {
-// char szBuf[8096]="";
-// snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__);
-// SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
-// throw megaglest_runtime_error(szBuf);
-// }
-//
-// return unitImmediatelyBlocked;
-//}
-
- void
- PathFinder::saveGame (XmlNode * rootNode)
- {
- std::map < string, string > mapTagReplacements;
- XmlNode *
- pathfinderNode = rootNode->addChild ("PathFinder");
-
- pathfinderNode->addAttribute ("pathFindNodesMax",
- intToStr (pathFindNodesMax),
- mapTagReplacements);
- pathfinderNode->addAttribute ("pathFindNodesAbsoluteMax",
- intToStr (pathFindNodesAbsoluteMax),
- mapTagReplacements);
- for (unsigned int i = 0; i < (unsigned int) factions.size (); ++i)
- {
- FactionState & factionState = factions.getFactionState (i);
- XmlNode *
- factionsNode = pathfinderNode->addChild ("factions");
-
- for (unsigned int j = 0;
- j < (unsigned int) factionState.nodePool.size (); ++j)
- {
- Node *
- curNode = &factionState.nodePool[j];
- XmlNode *
- nodePoolNode = factionsNode->addChild ("nodePool");
-
- nodePoolNode->addAttribute ("pos", curNode->pos.getString (),
- mapTagReplacements);
- int
- nextIdx =
- findNodeIndex (curNode->next, factionState.nodePool);
- nodePoolNode->addAttribute ("next", intToStr (nextIdx),
- mapTagReplacements);
- int
- prevIdx =
- findNodeIndex (curNode->prev, factionState.nodePool);
- nodePoolNode->addAttribute ("prev", intToStr (prevIdx),
- mapTagReplacements);
- nodePoolNode->addAttribute ("heuristic",
- floatToStr (curNode->heuristic, 6),
- mapTagReplacements);
- nodePoolNode->addAttribute ("exploredCell",
- intToStr (curNode->exploredCell),
- mapTagReplacements);
- }
-
- factionsNode->addAttribute ("nodePoolCount",
- intToStr (factionState.nodePoolCount),
- mapTagReplacements);
- factionsNode->addAttribute ("random",
- intToStr (factionState.random.
- getLastNumber ()),
- mapTagReplacements);
- factionsNode->addAttribute ("useMaxNodeCount",
- intToStr (factionState.useMaxNodeCount),
- mapTagReplacements);
- }
- }
-
- void
- PathFinder::loadGame (const XmlNode * rootNode)
- {
- const XmlNode *
- pathfinderNode = rootNode->getChild ("PathFinder");
-
- vector < XmlNode * >factionsNodeList =
- pathfinderNode->getChildList ("factions");
- for (unsigned int i = 0; i < (unsigned int) factionsNodeList.size ();
- ++i)
- {
- XmlNode *
- factionsNode = factionsNodeList[i];
-
- FactionState & factionState = factions.getFactionState (i);
- vector < XmlNode * >nodePoolListNode =
- factionsNode->getChildList ("nodePool");
- for (unsigned int j = 0;
- j < (unsigned int) nodePoolListNode.size ()
- && j < (unsigned int) pathFindNodesAbsoluteMax; ++j)
- {
- XmlNode *
- nodePoolNode = nodePoolListNode[j];
-
- Node *
- curNode = &factionState.nodePool[j];
- curNode->pos =
- Vec2i::strToVec2 (nodePoolNode->getAttribute ("pos")->
- getValue ());
- int
- nextNode =
- nodePoolNode->getAttribute ("next")->getIntValue ();
- if (nextNode >= 0)
- {
- curNode->next = &factionState.nodePool[nextNode];
- }
- else
- {
- curNode->next = NULL;
- }
-
- int
- prevNode =
- nodePoolNode->getAttribute ("prev")->getIntValue ();
- if (prevNode >= 0)
- {
- curNode->prev = &factionState.nodePool[prevNode];
- }
- else
- {
- curNode->prev = NULL;
- }
- curNode->heuristic =
- nodePoolNode->getAttribute ("heuristic")->getFloatValue ();
- curNode->exploredCell =
- nodePoolNode->getAttribute ("exploredCell")->getIntValue () !=
- 0;
- }
-
- factionState.nodePoolCount =
- factionsNode->getAttribute ("nodePoolCount")->getIntValue ();
- factionState.random.setLastNumber (factionsNode->
- getAttribute ("random")->
- getIntValue ());
- factionState.useMaxNodeCount = PathFinder::pathFindNodesMax;
- }
- }
-
- }
+ Glest {
+ namespace
+ Game {
+
+ // =====================================================
+ // class PathFinder
+ // =====================================================
+
+ // ===================== PUBLIC ========================
+
+ const int
+ PathFinder::maxFreeSearchRadius = 10;
+
+ int
+ PathFinder::pathFindNodesAbsoluteMax = 900;
+ int
+ PathFinder::pathFindNodesMax = 2000;
+ const int
+ PathFinder::pathFindBailoutRadius = 20;
+ const int
+ PathFinder::pathFindExtendRefreshForNodeCount = 25;
+ const int
+ PathFinder::pathFindExtendRefreshNodeCountMin = 40;
+ const int
+ PathFinder::pathFindExtendRefreshNodeCountMax = 40;
+
+ PathFinder::PathFinder() {
+ minorDebugPathfinder = false;
+ map = NULL;
+ }
+
+ int
+ PathFinder::getPathFindExtendRefreshNodeCount(FactionState & faction) {
+ //int refreshNodeCount = faction.random.randRange(PathFinder::pathFindExtendRefreshNodeCountMin,PathFinder::pathFindExtendRefreshNodeCountMax);
+ //return refreshNodeCount;
+ return PathFinder::pathFindExtendRefreshNodeCountMin;
+ }
+
+ PathFinder::PathFinder(const Map * map) {
+ minorDebugPathfinder = false;
+
+ map = NULL;
+ init(map);
+ }
+
+ void
+ PathFinder::init(const Map * map) {
+ for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers;
+ ++factionIndex) {
+ FactionState & faction = factions.getFactionState(factionIndex);
+
+ faction.nodePool.resize(pathFindNodesAbsoluteMax);
+ faction.useMaxNodeCount = PathFinder::pathFindNodesMax;
+ }
+ this->map = map;
+ }
+
+ void
+ PathFinder::init() {
+ minorDebugPathfinder = false;
+ map = NULL;
+ }
+
+ PathFinder::~PathFinder() {
+ for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers;
+ ++factionIndex) {
+ FactionState & faction = factions.getFactionState(factionIndex);
+
+ faction.nodePool.clear();
+ }
+ factions.clear();
+ map = NULL;
+ }
+
+ void
+ PathFinder::clearCaches() {
+ for (int factionIndex = 0; factionIndex < GameConstants::maxPlayers;
+ ++factionIndex) {
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ FactionState & faction = factions.getFactionState(factionIndex);
+ MutexSafeWrapper
+ safeMutex(faction.getMutexPreCache(), mutexOwnerId);
+
+ faction.precachedTravelState.clear();
+ faction.precachedPath.clear();
+ }
+ }
+
+ void
+ PathFinder::clearUnitPrecache(Unit * unit) {
+ if (unit != NULL && factions.size() > unit->getFactionIndex()) {
+ int
+ factionIndex = unit->getFactionIndex();
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ FactionState & faction = factions.getFactionState(factionIndex);
+ MutexSafeWrapper
+ safeMutex(faction.getMutexPreCache(), mutexOwnerId);
+
+ faction.precachedTravelState[unit->getId()] = tsImpossible;
+ faction.precachedPath[unit->getId()].clear();
+ }
+ }
+
+ void
+ PathFinder::removeUnitPrecache(Unit * unit) {
+ if (unit != NULL && factions.size() > unit->getFactionIndex()) {
+ int
+ factionIndex = unit->getFactionIndex();
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ FactionState & faction = factions.getFactionState(factionIndex);
+ MutexSafeWrapper
+ safeMutex(faction.getMutexPreCache(), mutexOwnerId);
+
+ if (faction.precachedTravelState.find(unit->getId()) !=
+ faction.precachedTravelState.end()) {
+ faction.precachedTravelState.erase(unit->getId());
+ }
+ if (faction.precachedPath.find(unit->getId()) !=
+ faction.precachedPath.end()) {
+ faction.precachedPath.erase(unit->getId());
+ }
+ }
+ }
+
+ TravelState
+ PathFinder::findPath(Unit * unit, const Vec2i & finalPos,
+ bool * wasStuck, int frameIndex) {
+ TravelState
+ ts = tsImpossible;
+
+ try {
+
+ int
+ factionIndex = unit->getFactionIndex();
+ FactionState & faction = factions.getFactionState(factionIndex);
+ static string
+ mutexOwnerId =
+ string(__FILE__) + string("_") + intToStr(__LINE__);
+ MutexSafeWrapper
+ safeMutexPrecache(faction.getMutexPreCache(), mutexOwnerId);
+
+ if (map == NULL) {
+ throw
+ megaglest_runtime_error("map == NULL");
+ }
+
+ unit->setCurrentPathFinderDesiredFinalPos(finalPos);
+
+
+ if (frameIndex >= 0) {
+ clearUnitPrecache(unit);
+ }
+ if (unit->getFaction()->canUnitsPathfind() == true) {
+ unit->getFaction()->addUnitToPathfindingList(unit->getId());
+ } else {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "canUnitsPathfind() == false");
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ return tsBlocked;
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "[findPath] unit->getPos() [%s] finalPos [%s]",
+ unit->getPos().getString().c_str(),
+ finalPos.getString().c_str());
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ //route cache
+ if (finalPos == unit->getPos()) {
+ if (frameIndex < 0) {
+ //if arrived
+ unit->setCurrSkill(scStop);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Unit finalPos [%s] == unit->getPos() [%s]",
+ finalPos.getString().c_str(),
+ unit->getPos().getString().c_str());
+ unit->
+ logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ }
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPathFinder).enabled ==
+ true) {
+ string
+ commandDesc = "none";
+ Command *
+ command = unit->getCurrCommand();
+ if (command != NULL && command->getCommandType() != NULL) {
+ commandDesc =
+ command->getCommandType()->toString(false);
+ }
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "State: arrived#1 at pos: %s, command [%s]",
+ finalPos.getString().c_str(),
+ commandDesc.c_str());
+ unit->setCurrentUnitTitle(szBuf);
+ }
+
+ return tsArrived;
+ }
+
+ UnitPathInterface *
+ path = unit->getPath();
+ if (path->isEmpty() == false) {
+ UnitPathBasic *
+ basic_path = dynamic_cast (path);
+ if (basic_path != NULL) {
+ //route cache
+ Vec2i
+ pos = basic_path->pop(frameIndex < 0);
+
+ if (map->canMove(unit, unit->getPos(), pos)) {
+ if (frameIndex < 0) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).enabled ==
+ true
+ && SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "#1 map->canMove to pos [%s] from [%s]",
+ pos.getString().c_str(),
+ unit->getPos().getString().c_str());
+ unit->
+ logSynchData(extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+
+ unit->setTargetPos(pos, frameIndex < 0);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).enabled ==
+ true
+ && SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "#2 map->canMove to pos [%s] from [%s]",
+ pos.getString().c_str(),
+ unit->getPos().getString().c_str());
+ unit->
+ logSynchData(extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+
+ }
+
+ return tsMoving;
+ }
+ } else if (dynamic_cast (path) != NULL) {
+ UnitPath *
+ advPath = dynamic_cast (path);
+ //route cache
+ Vec2i
+ pos = advPath->peek();
+ if (map->canMove(unit, unit->getPos(), pos)) {
+ if (frameIndex < 0) {
+ advPath->pop();
+ unit->setTargetPos(pos, frameIndex < 0);
+ }
+
+ return tsMoving;
+ }
+ } else {
+ throw
+ megaglest_runtime_error
+ ("unsupported or missing path finder detected!");
+ }
+ }
+
+ if (path->isStuck() == true &&
+ (unit->getLastStuckPos() == finalPos
+ || path->getBlockCount() > 500)
+ && unit->
+ isLastStuckFrameWithinCurrentFrameTolerance(frameIndex >= 0) ==
+ true) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "path->isStuck() == true unit->getLastStuckPos() [%s] finalPos [%s] path->getBlockCount() [%d]",
+ unit->getLastStuckPos().getString().c_str(),
+ finalPos.getString().c_str(),
+ path->getBlockCount());
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ return tsBlocked;
+ }
+
+ //route cache miss
+ int
+ maxNodeCount = -1;
+ if (unit->getUsePathfinderExtendedMaxNodes() == true) {
+
+ maxNodeCount = PathFinder::pathFindNodesAbsoluteMax;
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "maxNodeCount: %d", maxNodeCount);
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+ }
+
+ bool
+ minorDebugPathfinderPerformance = false;
+ Chrono
+ chrono;
+ if (minorDebugPathfinderPerformance)
+ chrono.start();
+
+ uint32
+ searched_node_count = 0;
+ minorDebugPathfinder = false;
+ if (minorDebugPathfinder)
+ printf
+ ("Legacy Pathfind Unit [%d - %s] from = %s to = %s frameIndex = %d\n",
+ unit->getId(), unit->getType()->getName(false).c_str(),
+ unit->getPos().getString().c_str(),
+ finalPos.getString().c_str(), frameIndex);
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "calling aStar()");
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ ts =
+ aStar(unit, finalPos, false, frameIndex, maxNodeCount,
+ &searched_node_count);
+ //post actions
+ switch (ts) {
+ case tsBlocked:
+ case tsArrived:
+ // The unit is stuck (not only blocked but unable to go anywhere for a while)
+ // We will try to bail out of the immediate area
+ if (ts == tsBlocked && unit->getInBailOutAttempt() == false &&
+ path->isStuck() == true) {
+
+ if (minorDebugPathfinder)
+ printf
+ ("Pathfind Unit [%d - %s] START BAILOUT ATTEMPT frameIndex = %d\n",
+ unit->getId(),
+ unit->getType()->getName(false).c_str(), frameIndex);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "[attempting to BAIL OUT] finalPos [%s] ts [%d]",
+ finalPos.getString().c_str(), ts);
+ unit->
+ logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ if (wasStuck != NULL) {
+ *wasStuck = true;
+ }
+ unit->setInBailOutAttempt(true);
+
+ bool
+ unitImmediatelyBlocked = false;
+
+ // First check if unit currently blocked all around them, if so don't try to pathfind
+ const Vec2i
+ unitPos = unit->getPos();
+ int
+ failureCount = 0;
+ int
+ cellCount = 0;
+
+ for (int i = -1; i <= 1; ++i) {
+ for (int j = -1; j <= 1; ++j) {
+ Vec2i
+ pos = unitPos + Vec2i(i, j);
+ if (pos != unitPos) {
+ bool
+ canUnitMoveToCell =
+ map->aproxCanMove(unit, unitPos, pos);
+ if (canUnitMoveToCell == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ }
+ unitImmediatelyBlocked = (failureCount == cellCount);
+ if (unitImmediatelyBlocked == false) {
+
+ int
+ factionIndex = unit->getFactionIndex();
+ FactionState & faction =
+ factions.getFactionState(factionIndex);
+
+ //if(Thread::isCurrentThreadMainThread() == false) {
+ // throw megaglest_runtime_error("#2 Invalid access to FactionState random from outside main thread current id = " +
+ // intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId()));
+ //}
+
+ int
+ tryRadius = faction.random.randRange(1, 2);
+ //int tryRadius = faction.random.IRandomX(1,2);
+ //int tryRadius = 1;
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In astar bailout() tryRadius %d",
+ tryRadius);
+
+ if (frameIndex >= 0) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__,
+ szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ // Try to bail out up to PathFinder::pathFindBailoutRadius cells away
+ if (tryRadius == 2) {
+ for (int bailoutX =
+ -PathFinder::pathFindBailoutRadius;
+ bailoutX <= PathFinder::pathFindBailoutRadius
+ && ts == tsBlocked; ++bailoutX) {
+ for (int bailoutY =
+ -PathFinder::pathFindBailoutRadius;
+ bailoutY <= PathFinder::pathFindBailoutRadius
+ && ts == tsBlocked; ++bailoutY) {
+ const Vec2i
+ newFinalPos =
+ finalPos + Vec2i(bailoutX, bailoutY);
+ bool
+ canUnitMove =
+ map->canMove(unit, unit->getPos(),
+ newFinalPos);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "[attempting to BAIL OUT] finalPos [%s] newFinalPos [%s] ts [%d] canUnitMove [%d]",
+ finalPos.getString().c_str(),
+ newFinalPos.getString().
+ c_str(), ts, canUnitMove);
+ unit->
+ logSynchData
+ (extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__, szBuf);
+ }
+
+ if (canUnitMove) {
+
+ int
+ maxBailoutNodeCount =
+ (PathFinder::pathFindBailoutRadius * 2);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "calling aStar()");
+ unit->
+ logSynchData
+ (extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+
+ ts =
+ aStar(unit, newFinalPos, true,
+ frameIndex, maxBailoutNodeCount,
+ &searched_node_count);
+ }
+ }
+ }
+ } else {
+ for (int bailoutX = PathFinder::pathFindBailoutRadius;
+ bailoutX >= -PathFinder::pathFindBailoutRadius
+ && ts == tsBlocked; --bailoutX) {
+ for (int bailoutY =
+ PathFinder::pathFindBailoutRadius;
+ bailoutY >=
+ -PathFinder::pathFindBailoutRadius
+ && ts == tsBlocked; --bailoutY) {
+ const Vec2i
+ newFinalPos =
+ finalPos + Vec2i(bailoutX, bailoutY);
+ bool
+ canUnitMove =
+ map->canMove(unit, unit->getPos(),
+ newFinalPos);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "[attempting to BAIL OUT] finalPos [%s] newFinalPos [%s] ts [%d] canUnitMove [%d]",
+ finalPos.getString().c_str(),
+ newFinalPos.getString().
+ c_str(), ts, canUnitMove);
+ unit->
+ logSynchData
+ (extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__, szBuf);
+ }
+
+ if (canUnitMove) {
+ int
+ maxBailoutNodeCount =
+ (PathFinder::pathFindBailoutRadius * 2);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "calling aStar()");
+ unit->
+ logSynchData
+ (extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+
+ ts =
+ aStar(unit, newFinalPos, true,
+ frameIndex, maxBailoutNodeCount,
+ &searched_node_count);
+ }
+ }
+ }
+ }
+ }
+ unit->setInBailOutAttempt(false);
+
+ if (ts == tsBlocked) {
+ unit->setLastStuckFrameToCurrentFrame();
+ unit->setLastStuckPos(finalPos);
+ }
+ }
+ if (ts == tsArrived || ts == tsBlocked) {
+ if (frameIndex < 0) {
+ unit->setCurrSkill(scStop);
+ }
+ }
+ break;
+ case tsMoving:
+ {
+ if (dynamic_cast (path) != NULL) {
+ UnitPathBasic *
+ basicPath = dynamic_cast (path);
+ Vec2i
+ pos;
+ if (frameIndex < 0 && basicPath != NULL) {
+ pos = basicPath->pop(frameIndex < 0);
+ } else {
+
+ if (faction.precachedPath[unit->getId()].size() <= 0) {
+ throw
+ megaglest_runtime_error
+ ("factions[unit->getFactionIndex()].precachedPath[unit->getId()].size() <= 0!");
+ }
+
+ pos = faction.precachedPath[unit->getId()][0];
+
+ }
+
+ if (map->canMove(unit, unit->getPos(), pos)) {
+ if (frameIndex < 0) {
+ unit->setTargetPos(pos, frameIndex < 0);
+ }
+ } else {
+ if (frameIndex < 0) {
+ unit->setCurrSkill(scStop);
+ }
+
+ if (minorDebugPathfinderPerformance
+ && chrono.getMillis() >= 1)
+ printf
+ ("Unit [%d - %s] astar #2 took [%lld] msecs, ts = %d searched_node_count = %d.\n",
+ unit->getId(),
+ unit->getType()->getName(false).c_str(),
+ (long long int) chrono.getMillis(), ts,
+ searched_node_count);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "tsBlocked");
+ unit->
+ logSynchData(extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+
+ return tsBlocked;
+ }
+ } else if (dynamic_cast (path) != NULL) {
+ UnitPath *
+ advPath = dynamic_cast (path);
+ Vec2i
+ pos = advPath->peek();
+ if (map->canMove(unit, unit->getPos(), pos)) {
+ if (frameIndex < 0) {
+ advPath->pop();
+ unit->setTargetPos(pos, frameIndex < 0);
+ }
+ } else {
+ if (frameIndex < 0) {
+ unit->setCurrSkill(scStop);
+ }
+
+ if (minorDebugPathfinder)
+ printf
+ ("Pathfind Unit [%d - %s] INT BAILOUT ATTEMPT BLOCKED frameIndex = %d\n",
+ unit->getId(),
+ unit->getType()->getName(false).c_str(),
+ frameIndex);
+
+ if (minorDebugPathfinderPerformance
+ && chrono.getMillis() >= 1)
+ printf
+ ("Unit [%d - %s] astar #3 took [%lld] msecs, ts = %d searched_node_count = %d.\n",
+ unit->getId(),
+ unit->getType()->getName(false).c_str(),
+ (long long int) chrono.getMillis(), ts,
+ searched_node_count);
+ return tsBlocked;
+ }
+ } else {
+ throw
+ megaglest_runtime_error
+ ("unsupported or missing path finder detected!");
+ }
+ }
+ break;
+
+ default:
+ break;
+ }
+ if (minorDebugPathfinderPerformance && chrono.getMillis() >= 1)
+ printf
+ ("Unit [%d - %s] astar took [%lld] msecs, ts = %d searched_node_count = %d.\n",
+ unit->getId(), unit->getType()->getName(false).c_str(),
+ (long long int) chrono.getMillis(), ts, searched_node_count);
+
+ } catch (const exception & ex) {
+ //setRunningStatus(false);
+
+ SystemFlags::OutputDebug(SystemFlags::debugError,
+ "In [%s::%s Line: %d] Error [%s]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ ex.what());
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ throw
+ megaglest_runtime_error(ex.what());
+ } catch (...) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ SystemFlags::OutputDebug(SystemFlags::debugError, szBuf);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ return ts;
+ }
+
+ // ==================== PRIVATE ====================
+
+ //route a unit using A* algorithm
+ TravelState
+ PathFinder::aStar(Unit * unit, const Vec2i & targetPos, bool inBailout,
+ int frameIndex, int maxNodeCount,
+ uint32 * searched_node_count) {
+ TravelState
+ ts = tsImpossible;
+
+ try {
+
+ int
+ unitFactionIndex = unit->getFactionIndex();
+ int
+ factionIndex = unit->getFactionIndex();
+ FactionState & faction = factions.getFactionState(factionIndex);
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex >= 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "In aStar()");
+ unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf);
+ }
+
+ Chrono
+ chrono;
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled)
+ chrono.start();
+
+ if (map == NULL) {
+ throw
+ megaglest_runtime_error("map == NULL");
+ }
+
+
+ if (maxNodeCount < 0) {
+
+ int
+ factionIndex = unit->getFactionIndex();
+ FactionState & faction = factions.getFactionState(factionIndex);
+
+ maxNodeCount = faction.useMaxNodeCount;
+ }
+
+ if (maxNodeCount >= 1
+ && unit->getPathfindFailedConsecutiveFrameCount() >= 3) {
+ maxNodeCount = 200;
+ }
+
+ UnitPathInterface *
+ path = unit->getPath();
+
+ faction.nodePoolCount = 0;
+ faction.openNodesList.clear();
+ faction.openPosList.clear();
+ faction.closedNodesList.clear();
+
+ // check the pre-cache to see if we can re-use a cached path
+ if (frameIndex < 0) {
+
+ bool
+ foundPrecacheTravelState =
+ (faction.precachedTravelState.find(unit->getId()) !=
+ faction.precachedTravelState.end());
+ if (foundPrecacheTravelState == true) {
+
+ // if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) {
+ // char szBuf[8096]="";
+ // snprintf(szBuf,8096,"factions[unitFactionIndex].precachedTravelState[unit->getId()]: %d",faction.precachedTravelState[unit->getId()]);
+ // unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf);
+ // }
+
+ bool
+ foundPrecacheTravelStateIsMoving =
+ (faction.precachedTravelState[unit->getId()] == tsMoving);
+ if (foundPrecacheTravelStateIsMoving == true) {
+ bool
+ canMoveToCells = true;
+
+ Vec2i
+ lastPos = unit->getPos();
+
+ int
+ unitPrecachePathSize =
+ (int) faction.precachedPath[unit->getId()].size();
+
+ for (int i = 0; i < unitPrecachePathSize; i++) {
+
+ Vec2i
+ nodePos = faction.precachedPath[unit->getId()][i];
+
+ if (map->isInside(nodePos) == false
+ || map->isInsideSurface(map->
+ toSurfCoords(nodePos))
+ == false) {
+ throw
+ megaglest_runtime_error
+ ("Pathfinder invalid node path position = " +
+ nodePos.getString() + " i = " + intToStr(i));
+ }
+
+ if (i < unit->getPathFindRefreshCellCount() ||
+ (unitPrecachePathSize >=
+ pathFindExtendRefreshForNodeCount
+ && i <
+ getPathFindExtendRefreshNodeCount(faction))) {
+
+ if (canUnitMoveSoon(unit, lastPos, nodePos) ==
+ false) {
+ canMoveToCells = false;
+ break;
+ }
+ lastPos = nodePos;
+ } else {
+ break;
+ }
+ }
+
+ if (canMoveToCells == true) {
+ path->clear();
+ //UnitPathBasic *basicPathFinder = dynamic_cast(path);
+
+ int
+ unitPrecachePathSize =
+ (int) faction.precachedPath[unit->getId()].size();
+
+ for (int i = 0; i < unitPrecachePathSize; i++) {
+
+ Vec2i
+ nodePos =
+ faction.precachedPath[unit->getId()][i];
+
+ if (map->isInside(nodePos) == false
+ || map->isInsideSurface(map->
+ toSurfCoords
+ (nodePos)) == false) {
+ throw
+ megaglest_runtime_error
+ ("Pathfinder invalid node path position = "
+ + nodePos.getString() + " i = " +
+ intToStr(i));
+ }
+
+ //if(i < pathFindRefresh ||
+ if (i < unit->getPathFindRefreshCellCount() ||
+ (unitPrecachePathSize >=
+ pathFindExtendRefreshForNodeCount
+ && i <
+ getPathFindExtendRefreshNodeCount(faction))) {
+ path->add(nodePos);
+ }
+ }
+ unit->setUsePathfinderExtendedMaxNodes(false);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::
+ debugWorldSynch).enabled ==
+ true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "return factions[unitFactionIndex].precachedTravelState[unit->getId()];");
+ unit->
+ logSynchData(extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+
+ return faction.precachedTravelState[unit->getId()];
+ } else {
+ clearUnitPrecache(unit);
+ }
+ } else {
+
+ bool
+ foundPrecacheTravelStateIsBlocked =
+ (faction.precachedTravelState[unit->getId()] ==
+ tsBlocked);
+
+ if (foundPrecacheTravelStateIsBlocked == true) {
+ path->incBlockCount();
+ unit->setUsePathfinderExtendedMaxNodes(false);
+
+ // if(SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).enabled == true && frameIndex < 0) {
+ // char szBuf[8096]="";
+ // snprintf(szBuf,8096,"return factions[unitFactionIndex].precachedTravelState[unit->getId()];");
+ // unit->logSynchData(extractFileFromDirectoryPath(__FILE__).c_str(),__LINE__,szBuf);
+ // }
+
+ return faction.precachedTravelState[unit->getId()];
+ }
+ }
+ }
+ } else {
+ clearUnitPrecache(unit);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "[clearUnitPrecache]");
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+ }
+
+ const Vec2i
+ unitPos = unit->getPos();
+ const Vec2i
+ finalPos = computeNearestFreePos(unit, targetPos);
+
+ float
+ dist = unitPos.dist(finalPos);
+
+ faction.useMaxNodeCount = PathFinder::pathFindNodesMax;
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath(__FILE__).
+ c_str(), __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ //path find algorithm
+
+ //a) push starting pos into openNodes
+ Node *
+ firstNode = newNode(faction, maxNodeCount);
+ if (firstNode == NULL) {
+ throw
+ megaglest_runtime_error("firstNode == NULL");
+ }
+
+ firstNode->next = NULL;
+ firstNode->prev = NULL;
+ firstNode->pos = unitPos;
+ firstNode->heuristic = heuristic(unitPos, finalPos);
+ firstNode->exploredCell = true;
+ if (faction.openNodesList.find(firstNode->heuristic) ==
+ faction.openNodesList.end()) {
+ faction.openNodesList[firstNode->heuristic].clear();
+ }
+ faction.openNodesList[firstNode->heuristic].push_back(firstNode);
+ faction.openPosList[firstNode->pos] = true;
+
+ //b) loop
+ bool
+ pathFound = true;
+ bool
+ nodeLimitReached = false;
+ Node *
+ node = NULL;
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath(__FILE__).
+ c_str(), __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ // First check if unit currently blocked all around them, if so don't try to pathfind
+ if (inBailout == false && unitPos != finalPos) {
+ int
+ failureCount = 0;
+ int
+ cellCount = 0;
+
+ for (int i = -1; i <= 1; ++i) {
+ for (int j = -1; j <= 1; ++j) {
+ Vec2i
+ pos = unitPos + Vec2i(i, j);
+ if (pos != unitPos) {
+ bool
+ canUnitMoveToCell =
+ canUnitMoveSoon(unit, unitPos, pos);
+ if (canUnitMoveToCell == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ }
+ nodeLimitReached = (failureCount == cellCount);
+ pathFound = !nodeLimitReached;
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "nodeLimitReached: %d failureCount: %d cellCount: %d",
+ nodeLimitReached, failureCount, cellCount);
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 1)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] **Check if dest blocked, distance for unit [%d - %s] from [%s] to [%s] is %.2f took msecs: %lld nodeLimitReached = %d, failureCount = %d\n",
+ extractFileFromDirectoryPath
+ (__FILE__).c_str(), __FUNCTION__,
+ __LINE__, unit->getId(),
+ unit->getFullName(false).c_str(),
+ unitPos.getString().c_str(),
+ finalPos.getString().c_str(), dist,
+ (long long int) chrono.getMillis(),
+ nodeLimitReached, failureCount);
+
+ if (nodeLimitReached == false) {
+ // First check if final destination blocked
+ failureCount = 0;
+ cellCount = 0;
+
+ for (int i = -1; i <= 1; ++i) {
+ for (int j = -1; j <= 1; ++j) {
+ Vec2i
+ pos = finalPos + Vec2i(i, j);
+ if (pos != finalPos) {
+ bool
+ canUnitMoveToCell =
+ canUnitMoveSoon(unit, pos, finalPos);
+ if (canUnitMoveToCell == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ }
+ nodeLimitReached = (failureCount == cellCount);
+ pathFound = !nodeLimitReached;
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "nodeLimitReached: %d failureCount: %d cellCount: %d",
+ nodeLimitReached, failureCount, cellCount);
+ unit->
+ logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 1)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] **Check if dest blocked, distance for unit [%d - %s] from [%s] to [%s] is %.2f took msecs: %lld nodeLimitReached = %d, failureCount = %d\n",
+ extractFileFromDirectoryPath
+ (__FILE__).c_str(), __FUNCTION__,
+ __LINE__, unit->getId(),
+ unit->getFullName(false).
+ c_str(),
+ unitPos.getString().c_str(),
+ finalPos.getString().c_str(),
+ dist,
+ (long long int) chrono.
+ getMillis(), nodeLimitReached,
+ failureCount);
+ }
+ } else {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "inBailout: %d unitPos: [%s] finalPos [%s]",
+ inBailout, unitPos.getString().c_str(),
+ finalPos.getString().c_str());
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+ }
+ //
+
+ // START
+ std::map < std::pair < Vec2i, Vec2i >, bool > canAddNode;
+ std::map < Vec2i, bool > closedNodes;
+ std::map < Vec2i, Vec2i > cameFrom;
+ cameFrom[unitPos] = Vec2i(-1, -1);
+
+ // Do the a-star base pathfind work if required
+ int
+ whileLoopCount = 0;
+ if (nodeLimitReached == false) {
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d frameIndex: %d",
+ nodeLimitReached, whileLoopCount, unitFactionIndex,
+ pathFound, finalPos.getString().c_str(),
+ maxNodeCount, frameIndex);
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ doAStarPathSearch(nodeLimitReached, whileLoopCount,
+ unitFactionIndex, pathFound, node, finalPos,
+ closedNodes, cameFrom, canAddNode, unit,
+ maxNodeCount, frameIndex);
+
+ if (searched_node_count != NULL) {
+ *searched_node_count = whileLoopCount;
+ }
+
+ // Now see if the unit is eligible for pathfind max nodes boost?
+ if (nodeLimitReached == true) {
+ unit->incrementPathfindFailedConsecutiveFrameCount();
+ } else {
+ unit->resetPathfindFailedConsecutiveFrameCount();
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "Calling doAStarPathSearch nodeLimitReached: %d whileLoopCount: %d unitFactionIndex: %d pathFound: %d finalPos [%s] maxNodeCount: %d pathFindNodesAbsoluteMax: %d frameIndex: %d",
+ nodeLimitReached, whileLoopCount, unitFactionIndex,
+ pathFound, finalPos.getString().c_str(),
+ maxNodeCount, pathFindNodesAbsoluteMax, frameIndex);
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ if (nodeLimitReached == true
+ && maxNodeCount != pathFindNodesAbsoluteMax) {
+ if (unit->
+ isLastPathfindFailedFrameWithinCurrentFrameTolerance() ==
+ true) {
+ if (frameIndex < 0) {
+ unit->setLastPathfindFailedFrameToCurrentFrame();
+ unit->setLastPathfindFailedPos(finalPos);
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "calling aStar()");
+ unit->
+ logSynchData(extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__, szBuf);
+ }
+
+ return aStar(unit, targetPos, false, frameIndex,
+ pathFindNodesAbsoluteMax);
+ }
+ }
+ } else {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "nodeLimitReached: %d",
+ nodeLimitReached);
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+ }
+
+
+ Node *
+ lastNode = node;
+
+ //if consumed all nodes find best node (to avoid strange behaviour)
+ if (nodeLimitReached == true) {
+
+ if (faction.closedNodesList.empty() == false) {
+ float
+ bestHeuristic =
+ truncateDecimal <
+ float >(faction.closedNodesList.begin()->first, 6);
+ if (lastNode != NULL && bestHeuristic < lastNode->heuristic) {
+ lastNode =
+ faction.closedNodesList.begin()->second.front();
+ }
+ }
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath(__FILE__).
+ c_str(), __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ //check results of path finding
+ ts = tsImpossible;
+ if (pathFound == false || lastNode == firstNode) {
+ if (minorDebugPathfinder)
+ printf
+ ("Legacy Pathfind Unit [%d - %s] NOT FOUND PATH count = %d frameIndex = %d\n",
+ unit->getId(), unit->getType()->getName().c_str(),
+ whileLoopCount, frameIndex);
+
+ //blocked
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPathFinder).enabled ==
+ true) {
+ string
+ commandDesc = "none";
+ Command *
+ command = unit->getCurrCommand();
+ if (command != NULL && command->getCommandType() != NULL) {
+ commandDesc =
+ command->getCommandType()->toString(false);
+ }
+
+ std::pair < Vec2i, int >
+ lastHarvest = unit->getLastHarvestResourceTarget();
+
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "State: blocked, cmd [%s] pos: [%s], dest pos: [%s], lastHarvest = [%s - %d], reason A= %d, B= %d, C= %d, D= %d, E= %d, F = %d",
+ commandDesc.c_str(),
+ unit->getPos().getString().c_str(),
+ targetPos.getString().c_str(),
+ lastHarvest.first.getString().c_str(),
+ lastHarvest.second, pathFound,
+ (lastNode == firstNode), path->getBlockCount(),
+ path->isBlocked(), nodeLimitReached,
+ path->isStuck());
+ unit->setCurrentUnitTitle(szBuf);
+ }
+
+ if (frameIndex < 0) {
+ unit->setUsePathfinderExtendedMaxNodes(false);
+ }
+
+ ts = tsBlocked;
+ if (frameIndex < 0) {
+ path->incBlockCount();
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath
+ (__FILE__).c_str(), __FUNCTION__,
+ __LINE__, chrono.getMillis());
+ } else {
+ if (minorDebugPathfinder)
+ printf
+ ("Legacy Pathfind Unit [%d - %s] FOUND PATH count = %d frameIndex = %d\n",
+ unit->getId(), unit->getType()->getName().c_str(),
+ whileLoopCount, frameIndex);
+ //on the way
+ ts = tsMoving;
+
+ //build next pointers
+ Node *
+ currNode = lastNode;
+ while (currNode->prev != NULL) {
+ currNode->prev->next = currNode;
+ currNode = currNode->prev;
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath
+ (__FILE__).c_str(), __FUNCTION__,
+ __LINE__, chrono.getMillis());
+
+ if (frameIndex < 0) {
+ if (maxNodeCount == pathFindNodesAbsoluteMax) {
+ unit->setUsePathfinderExtendedMaxNodes(true);
+ } else {
+ unit->setUsePathfinderExtendedMaxNodes(false);
+ }
+ }
+
+ //store path
+ if (frameIndex < 0) {
+ path->clear();
+ }
+
+ //UnitPathBasic *basicPathFinder = dynamic_cast(path);
+
+ currNode = firstNode;
+
+ for (int i = 0; currNode->next != NULL;
+ currNode = currNode->next, i++) {
+ Vec2i
+ nodePos = currNode->next->pos;
+ if (map->isInside(nodePos) == false
+ || map->isInsideSurface(map->toSurfCoords(nodePos)) ==
+ false) {
+ throw
+ megaglest_runtime_error
+ ("Pathfinder invalid node path position = " +
+ nodePos.getString() + " i = " + intToStr(i));
+ }
+
+ if (minorDebugPathfinder)
+ printf("nodePos [%s]\n", nodePos.getString().c_str());
+
+ if (frameIndex >= 0) {
+ faction.precachedPath[unit->getId()].push_back(nodePos);
+ } else {
+ if (i < unit->getPathFindRefreshCellCount() ||
+ (whileLoopCount >= pathFindExtendRefreshForNodeCount
+ && i < getPathFindExtendRefreshNodeCount(faction))) {
+ path->add(nodePos);
+ }
+ }
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath
+ (__FILE__).c_str(), __FUNCTION__,
+ __LINE__, chrono.getMillis());
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+
+ string
+ pathToTake = "";
+ if (frameIndex < 0) {
+ vector < Vec2i > pathQueue = path->getQueue();
+ for (unsigned int index = 0; index < pathQueue.size();
+ ++index) {
+ Vec2i & pos = pathQueue[index];
+ if (pathToTake != "") {
+ pathToTake += ", ";
+ }
+ pathToTake += pos.getString();
+ }
+ } else {
+ for (unsigned int index = 0;
+ index <
+ faction.precachedPath[unit->getId()].size();
+ ++index) {
+ Vec2i & pos =
+ faction.precachedPath[unit->getId()][index];
+ if (pathToTake != "") {
+ pathToTake += ", ";
+ }
+ pathToTake += pos.getString();
+ }
+ }
+ snprintf(szBuf, 8096, "Path for unit to take = %s",
+ pathToTake.c_str());
+ if (frameIndex < 0) {
+ unit->
+ logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ } else {
+ unit->
+ logSynchDataThreaded(extractFileFromDirectoryPath
+ (__FILE__).c_str(), __LINE__,
+ szBuf);
+ }
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPathFinder).enabled ==
+ true) {
+ string
+ commandDesc = "none";
+ Command *
+ command = unit->getCurrCommand();
+ if (command != NULL && command->getCommandType() != NULL) {
+ commandDesc =
+ command->getCommandType()->toString(false);
+ }
+
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "State: moving, cmd [%s] pos: %s dest pos: %s, Queue= %d",
+ commandDesc.c_str(),
+ unit->getPos().getString().c_str(),
+ targetPos.getString().c_str(),
+ path->getQueueCount());
+ unit->setCurrentUnitTitle(szBuf);
+ }
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s Line: %d] took msecs: %lld\n",
+ extractFileFromDirectoryPath
+ (__FILE__).c_str(), __FUNCTION__,
+ __LINE__, chrono.getMillis());
+ }
+
+
+ faction.openNodesList.clear();
+ faction.openPosList.clear();
+ faction.closedNodesList.clear();
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).
+ enabled == true && chrono.getMillis() > 4)
+ SystemFlags::OutputDebug(SystemFlags::debugPerformance,
+ "In [%s::%s] Line: %d took msecs: %lld --------------------------- [END OF METHOD] ---------------------------\n",
+ extractFileFromDirectoryPath(__FILE__).
+ c_str(), __FUNCTION__, __LINE__,
+ chrono.getMillis());
+
+ if (frameIndex >= 0) {
+
+ FactionState & faction = factions.getFactionState(factionIndex);
+ faction.precachedTravelState[unit->getId()] = ts;
+ } else {
+ if (SystemFlags::VERBOSE_MODE_ENABLED && chrono.getMillis() >= 5)
+ printf
+ ("In [%s::%s Line: %d] astar took [%lld] msecs, ts = %d.\n",
+ extractFileFromDirectoryPath(__FILE__).c_str(),
+ __FUNCTION__, __LINE__, (long long int) chrono.getMillis(),
+ ts);
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true && frameIndex < 0) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "return ts: %d", ts);
+ unit->logSynchData(extractFileFromDirectoryPath(__FILE__).
+ c_str(), __LINE__, szBuf);
+ }
+
+ } catch (const exception & ex) {
+
+ SystemFlags::OutputDebug(SystemFlags::debugError,
+ "In [%s::%s Line: %d] Error [%s]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ ex.what());
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ throw
+ megaglest_runtime_error(ex.what());
+ } catch (...) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ SystemFlags::OutputDebug(SystemFlags::debugError, szBuf);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ return ts;
+ }
+
+ void
+ PathFinder::processNearestFreePos(const Vec2i & finalPos, int i, int j,
+ int size, Field field, int teamIndex,
+ Vec2i unitPos, Vec2i & nearestPos,
+ float &nearestDist) {
+
+ try {
+ Vec2i
+ currPos = finalPos + Vec2i(i, j);
+
+ if (map->isAproxFreeCells(currPos, size, field, teamIndex)) {
+ float
+ dist = currPos.dist(finalPos);
+
+ //if nearer from finalPos
+ if (dist < nearestDist) {
+ nearestPos = currPos;
+ nearestDist = dist;
+ }
+ //if the distance is the same compare distance to unit
+ else if (dist == nearestDist) {
+ if (currPos.dist(unitPos) < nearestPos.dist(unitPos)) {
+ nearestPos = currPos;
+ }
+ }
+ }
+ } catch (const exception & ex) {
+
+ SystemFlags::OutputDebug(SystemFlags::debugError,
+ "In [%s::%s Line: %d] Error [%s]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ ex.what());
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ throw
+ megaglest_runtime_error(ex.what());
+ } catch (...) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ SystemFlags::OutputDebug(SystemFlags::debugError, szBuf);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ }
+
+ Vec2i
+ PathFinder::computeNearestFreePos(const Unit * unit,
+ const Vec2i & finalPos) {
+
+ Vec2i
+ nearestPos(0, 0);
+ try {
+
+ if (map == NULL) {
+ throw
+ megaglest_runtime_error("map == NULL");
+ }
+
+ //unit data
+ int
+ size = unit->getType()->getSize();
+ Field
+ field = unit->getCurrField();
+ int
+ teamIndex = unit->getTeam();
+
+ //if finalPos is free return it
+ if (map->isAproxFreeCells(finalPos, size, field, teamIndex)) {
+ return finalPos;
+ }
+
+ //find nearest pos
+ Vec2i
+ unitPos = unit->getPosNotThreadSafe();
+ nearestPos = unitPos;
+
+ float
+ nearestDist = unitPos.dist(finalPos);
+
+ for (int i = -maxFreeSearchRadius; i <= maxFreeSearchRadius; ++i) {
+ for (int j = -maxFreeSearchRadius; j <= maxFreeSearchRadius; ++j) {
+ processNearestFreePos(finalPos, i, j, size, field, teamIndex,
+ unitPos, nearestPos, nearestDist);
+ }
+ }
+
+ } catch (const exception & ex) {
+
+ SystemFlags::OutputDebug(SystemFlags::debugError,
+ "In [%s::%s Line: %d] Error [%s]\n",
+ __FILE__, __FUNCTION__, __LINE__,
+ ex.what());
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugSystem).
+ enabled)
+ SystemFlags::OutputDebug(SystemFlags::debugSystem,
+ "In [%s::%s Line: %d]\n", __FILE__,
+ __FUNCTION__, __LINE__);
+
+ throw
+ megaglest_runtime_error(ex.what());
+ } catch (...) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "In [%s::%s %d] UNKNOWN error\n", __FILE__,
+ __FUNCTION__, __LINE__);
+ SystemFlags::OutputDebug(SystemFlags::debugError, szBuf);
+ throw
+ megaglest_runtime_error(szBuf);
+ }
+
+ return nearestPos;
+ }
+
+ int
+ PathFinder::findNodeIndex(Node * node, Nodes & nodeList) {
+ int
+ index = -1;
+ if (node != NULL) {
+ for (unsigned int i = 0; i < nodeList.size(); ++i) {
+ Node *
+ curnode = nodeList[i];
+ if (node == curnode) {
+ index = i;
+ break;
+ }
+ }
+ }
+ return index;
+ }
+
+ int
+ PathFinder::findNodeIndex(Node * node, std::vector < Node > &nodeList) {
+ int
+ index = -1;
+ if (node != NULL) {
+ for (unsigned int i = 0; i < nodeList.size(); ++i) {
+ Node & curnode = nodeList[i];
+ if (node == &curnode) {
+ index = i;
+ break;
+ }
+ }
+ }
+ return index;
+ }
+
+ //bool PathFinder::unitCannotMove(Unit *unit) {
+ // bool unitImmediatelyBlocked = false;
+ //
+ // try {
+ // // First check if unit currently blocked all around them, if so don't try to pathfind
+ // const Vec2i unitPos = unit->getPos();
+ // int failureCount = 0;
+ // int cellCount = 0;
+ //
+ // for(int i = -1; i <= 1; ++i) {
+ // for(int j = -1; j <= 1; ++j) {
+ // Vec2i pos = unitPos + Vec2i(i, j);
+ // if(pos != unitPos) {
+ // bool canUnitMoveToCell = map->aproxCanMove(unit, unitPos, pos);
+ // if(canUnitMoveToCell == false) {
+ // failureCount++;
+ // }
+ // cellCount++;
+ // }
+ // }
+ // }
+ // unitImmediatelyBlocked = (failureCount == cellCount);
+ //
+ // }
+ // catch(const exception &ex) {
+ // //setRunningStatus(false);
+ //
+ // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what());
+ // if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
+ //
+ // throw megaglest_runtime_error(ex.what());
+ // }
+ // catch(...) {
+ // char szBuf[8096]="";
+ // snprintf(szBuf,8096,"In [%s::%s %d] UNKNOWN error\n",__FILE__,__FUNCTION__,__LINE__);
+ // SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
+ // throw megaglest_runtime_error(szBuf);
+ // }
+ //
+ // return unitImmediatelyBlocked;
+ //}
+
+ void
+ PathFinder::saveGame(XmlNode * rootNode) {
+ std::map < string, string > mapTagReplacements;
+ XmlNode *
+ pathfinderNode = rootNode->addChild("PathFinder");
+
+ pathfinderNode->addAttribute("pathFindNodesMax",
+ intToStr(pathFindNodesMax),
+ mapTagReplacements);
+ pathfinderNode->addAttribute("pathFindNodesAbsoluteMax",
+ intToStr(pathFindNodesAbsoluteMax),
+ mapTagReplacements);
+ for (unsigned int i = 0; i < (unsigned int) factions.size(); ++i) {
+ FactionState & factionState = factions.getFactionState(i);
+ XmlNode *
+ factionsNode = pathfinderNode->addChild("factions");
+
+ for (unsigned int j = 0;
+ j < (unsigned int) factionState.nodePool.size(); ++j) {
+ Node *
+ curNode = &factionState.nodePool[j];
+ XmlNode *
+ nodePoolNode = factionsNode->addChild("nodePool");
+
+ nodePoolNode->addAttribute("pos", curNode->pos.getString(),
+ mapTagReplacements);
+ int
+ nextIdx =
+ findNodeIndex(curNode->next, factionState.nodePool);
+ nodePoolNode->addAttribute("next", intToStr(nextIdx),
+ mapTagReplacements);
+ int
+ prevIdx =
+ findNodeIndex(curNode->prev, factionState.nodePool);
+ nodePoolNode->addAttribute("prev", intToStr(prevIdx),
+ mapTagReplacements);
+ nodePoolNode->addAttribute("heuristic",
+ floatToStr(curNode->heuristic, 6),
+ mapTagReplacements);
+ nodePoolNode->addAttribute("exploredCell",
+ intToStr(curNode->exploredCell),
+ mapTagReplacements);
+ }
+
+ factionsNode->addAttribute("nodePoolCount",
+ intToStr(factionState.nodePoolCount),
+ mapTagReplacements);
+ factionsNode->addAttribute("random",
+ intToStr(factionState.random.
+ getLastNumber()),
+ mapTagReplacements);
+ factionsNode->addAttribute("useMaxNodeCount",
+ intToStr(factionState.useMaxNodeCount),
+ mapTagReplacements);
+ }
+ }
+
+ void
+ PathFinder::loadGame(const XmlNode * rootNode) {
+ const XmlNode *
+ pathfinderNode = rootNode->getChild("PathFinder");
+
+ vector < XmlNode * >factionsNodeList =
+ pathfinderNode->getChildList("factions");
+ for (unsigned int i = 0; i < (unsigned int) factionsNodeList.size();
+ ++i) {
+ XmlNode *
+ factionsNode = factionsNodeList[i];
+
+ FactionState & factionState = factions.getFactionState(i);
+ vector < XmlNode * >nodePoolListNode =
+ factionsNode->getChildList("nodePool");
+ for (unsigned int j = 0;
+ j < (unsigned int) nodePoolListNode.size()
+ && j < (unsigned int) pathFindNodesAbsoluteMax; ++j) {
+ XmlNode *
+ nodePoolNode = nodePoolListNode[j];
+
+ Node *
+ curNode = &factionState.nodePool[j];
+ curNode->pos =
+ Vec2i::strToVec2(nodePoolNode->getAttribute("pos")->
+ getValue());
+ int
+ nextNode =
+ nodePoolNode->getAttribute("next")->getIntValue();
+ if (nextNode >= 0) {
+ curNode->next = &factionState.nodePool[nextNode];
+ } else {
+ curNode->next = NULL;
+ }
+
+ int
+ prevNode =
+ nodePoolNode->getAttribute("prev")->getIntValue();
+ if (prevNode >= 0) {
+ curNode->prev = &factionState.nodePool[prevNode];
+ } else {
+ curNode->prev = NULL;
+ }
+ curNode->heuristic =
+ nodePoolNode->getAttribute("heuristic")->getFloatValue();
+ curNode->exploredCell =
+ nodePoolNode->getAttribute("exploredCell")->getIntValue() !=
+ 0;
+ }
+
+ factionState.nodePoolCount =
+ factionsNode->getAttribute("nodePoolCount")->getIntValue();
+ factionState.random.setLastNumber(factionsNode->
+ getAttribute("random")->
+ getIntValue());
+ factionState.useMaxNodeCount = PathFinder::pathFindNodesMax;
+ }
+ }
+
+ }
} //end namespace
diff --git a/source/glest_game/ai/path_finder.h b/source/glest_game/ai/path_finder.h
index 7e8c1ebf1..4ef765a56 100644
--- a/source/glest_game/ai/path_finder.h
+++ b/source/glest_game/ai/path_finder.h
@@ -28,730 +28,637 @@
# include "leak_dumper.h"
using
- std::vector;
+std::vector;
using
- Shared::Graphics::Vec2i;
+Shared::Graphics::Vec2i;
namespace
- Glest
-{
- namespace
- Game
- {
-
-// =====================================================
-// class PathFinder
-//
-/// Finds paths for units using a modification of the A* algorithm
-// =====================================================
-
- class
- PathFinder
- {
- public:
- class
- BadUnitNodeList
- {
- public:
- BadUnitNodeList ()
- {
- unitSize = -1;
- field = fLand;
- }
- int
- unitSize;
- Field
- field;
- std::map <
- Vec2i,
- std::map <
- Vec2i,
- bool > >
- badPosList;
-
- inline bool
- isPosBad (const Vec2i & pos1, const Vec2i & pos2)
- {
- bool
- result = false;
-
- std::map <
- Vec2i,
- std::map <
- Vec2i,
- bool > >::iterator
- iterFind = badPosList.find (pos1);
- if (iterFind != badPosList.end ())
- {
- std::map < Vec2i, bool >::iterator iterFind2 =
- iterFind->second.find (pos2);
- if (iterFind2 != iterFind->second.end ())
- {
- result = true;
- }
- }
-
- return
- result;
- }
- };
-
- class
- Node
- {
- public:
- Node ()
- {
- clear ();
- }
- void
- clear ()
- {
- pos.x = 0;
- pos.y = 0;
- next = NULL;
- prev = NULL;
- heuristic = 0.0;
- exploredCell = false;
- }
- Vec2i
- pos;
- Node *
- next;
- Node *
- prev;
- float
- heuristic;
- bool
- exploredCell;
- };
- typedef
- vector <
- Node * >
- Nodes;
-
- class
- FactionState
- {
- protected:
- Mutex *
- factionMutexPrecache;
- public:
- explicit
- FactionState (int factionIndex):
- //factionMutexPrecache(new Mutex) {
- factionMutexPrecache (NULL)
- { //, random(factionIndex) {
-
- openPosList.clear ();
- openNodesList.
- clear ();
- closedNodesList.
- clear ();
- nodePool.
- clear ();
- nodePoolCount = 0;
- this->
- factionIndex = factionIndex;
- useMaxNodeCount = 0;
-
- precachedTravelState.
- clear ();
- precachedPath.
- clear ();
- }
- ~
- FactionState ()
- {
-
- delete
- factionMutexPrecache;
- factionMutexPrecache = NULL;
- }
- Mutex *
- getMutexPreCache ()
- {
- return factionMutexPrecache;
- }
-
- std::map < Vec2i, bool > openPosList;
- std::map < float,
- Nodes >
- openNodesList;
- std::map < float,
- Nodes >
- closedNodesList;
- std::vector < Node > nodePool;
-
- int
- nodePoolCount;
- int
- factionIndex;
- RandomGen
- random;
- //CRandomMersenne random;
- int
- useMaxNodeCount;
-
- std::map < int,
- TravelState >
- precachedTravelState;
- std::map < int,
- std::vector <
- Vec2i > >
- precachedPath;
- };
-
- class
- FactionStateManager
- {
- protected:
- typedef
- vector <
- FactionState * >
- FactionStateList;
- FactionStateList
- factions;
-
- void
- init ()
- {
- for (int index = 0; index < GameConstants::maxPlayers; ++index)
- {
- factions.push_back (new FactionState (index));
- }
- }
-
- public:
- FactionStateManager ()
- {
- init ();
- }
- ~FactionStateManager ()
- {
- clear ();
- }
-
- FactionState & getFactionState (int index)
- {
- FactionState *
- faction = factions[index];
- return *faction;
- }
- void
- clear ()
- {
- for (unsigned int index = 0;
- index < (unsigned int) factions.size (); ++index)
- {
- delete
- factions[index];
- }
-
- factions.clear ();
- }
- int
- size ()
- {
- return (int) factions.size ();
- }
- };
-
- public:
- static const int
- maxFreeSearchRadius;
-
- static const int
- pathFindBailoutRadius;
- static const int
- pathFindExtendRefreshForNodeCount;
- static const int
- pathFindExtendRefreshNodeCountMin;
- static const int
- pathFindExtendRefreshNodeCountMax;
-
- private:
-
- static int
- pathFindNodesMax;
- static int
- pathFindNodesAbsoluteMax;
-
-
- FactionStateManager
- factions;
- const Map *
- map;
- bool
- minorDebugPathfinder;
-
- public:
- PathFinder ();
- explicit
- PathFinder (const Map * map);
- ~PathFinder ();
-
- PathFinder (const PathFinder & obj)
- {
- init ();
- throw
- megaglest_runtime_error ("class PathFinder is NOT safe to copy!");
- }
- PathFinder & operator= (const PathFinder & obj)
- {
- init ();
- throw
- megaglest_runtime_error ("class PathFinder is NOT safe to assign!");
- }
-
- void
- init (const Map * map);
- TravelState
- findPath (Unit * unit, const Vec2i & finalPos, bool * wasStuck =
- NULL, int frameIndex = -1);
- void
- clearUnitPrecache (Unit * unit);
- void
- removeUnitPrecache (Unit * unit);
- void
- clearCaches ();
-
- //bool unitCannotMove(Unit *unit);
-
- int
- findNodeIndex (Node * node, Nodes & nodeList);
- int
- findNodeIndex (Node * node, std::vector < Node > &nodeList);
-
- void
- saveGame (XmlNode * rootNode);
- void
- loadGame (const XmlNode * rootNode);
-
- private:
- void
- init ();
-
- TravelState
- aStar (Unit * unit, const Vec2i & finalPos, bool inBailout,
- int frameIndex, int maxNodeCount =
- -1, uint32 * searched_node_count = NULL);
- inline static Node *
- newNode (FactionState & faction, int maxNodeCount)
- {
- if (faction.nodePoolCount < (int) faction.nodePool.size () &&
- faction.nodePoolCount < maxNodeCount)
- {
- Node *
- node = &(faction.nodePool[faction.nodePoolCount]);
- node->clear ();
- faction.nodePoolCount++;
- return node;
- }
- return NULL;
- }
-
- Vec2i
- computeNearestFreePos (const Unit * unit, const Vec2i & targetPos);
-
- inline static float
- heuristic (const Vec2i & pos, const Vec2i & finalPos)
- {
- return pos.dist (finalPos);
- }
-
- inline static bool
- openPos (const Vec2i & sucPos, FactionState & faction)
- {
- if (faction.openPosList.find (sucPos) == faction.openPosList.end ())
- {
- return false;
- }
- return true;
- }
-
- inline static Node *
- minHeuristicFastLookup (FactionState & faction)
- {
- if (faction.openNodesList.empty () == true)
- {
- throw
- megaglest_runtime_error ("openNodesList.empty() == true");
- }
-
- Node *
- result = faction.openNodesList.begin ()->second.front ();
- faction.openNodesList.begin ()->second.erase (faction.openNodesList.
- begin ()->second.
- begin ());
- if (faction.openNodesList.begin ()->second.empty ())
- {
- faction.openNodesList.erase (faction.openNodesList.begin ());
- }
- return result;
- }
-
- inline bool
- processNode (Unit * unit, Node * node, const Vec2i finalPos,
- int x, int y, bool & nodeLimitReached, int maxNodeCount)
- {
- bool
- result = false;
- Vec2i
- sucPos = node->pos + Vec2i (x, y);
-
- int
- unitFactionIndex = unit->getFactionIndex ();
- FactionState & faction = factions.getFactionState (unitFactionIndex);
-
- bool
- foundOpenPosForPos = openPos (sucPos, faction);
- bool
- allowUnitMoveSoon = canUnitMoveSoon (unit, node->pos, sucPos);
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In processNode() nodeLimitReached %d unitFactionIndex %d foundOpenPosForPos %d allowUnitMoveSoon %d maxNodeCount %d node->pos = %s finalPos = %s sucPos = %s faction.openPosList.size() %lu closedNodesList.size() %lu",
- nodeLimitReached, unitFactionIndex, foundOpenPosForPos,
- allowUnitMoveSoon, maxNodeCount,
- node->pos.getString ().c_str (),
- finalPos.getString ().c_str (),
- sucPos.getString ().c_str (),
- faction.openPosList.size (),
- faction.closedNodesList.size ());
-
- if (Thread::isCurrentThreadMainThread () == false)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__, szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- if (foundOpenPosForPos == false && allowUnitMoveSoon)
- {
- //if node is not open and canMove then generate another node
- Node *
- sucNode = newNode (faction, maxNodeCount);
- if (sucNode != NULL)
- {
- sucNode->pos = sucPos;
- sucNode->heuristic = heuristic (sucNode->pos, finalPos);
- sucNode->prev = node;
- sucNode->next = NULL;
- sucNode->exploredCell =
- map->getSurfaceCell (Map::toSurfCoords (sucPos))->
- isExplored (unit->getTeam ());
- if (faction.openNodesList.find (sucNode->heuristic) ==
- faction.openNodesList.end ())
- {
- faction.openNodesList[sucNode->heuristic].clear ();
- }
- faction.openNodesList[sucNode->heuristic].push_back (sucNode);
- faction.openPosList[sucNode->pos] = true;
-
- result = true;
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096, "In processNode() sucPos = %s",
- sucPos.getString ().c_str ());
-
- if (Thread::isCurrentThreadMainThread () == false)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__,
- szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- }
- else
- {
- nodeLimitReached = true;
- }
- }
-
- return result;
- }
-
- void
- processNearestFreePos (const Vec2i & finalPos, int i, int j, int size,
- Field field, int teamIndex, Vec2i unitPos,
- Vec2i & nearestPos, float &nearestDist);
- int
- getPathFindExtendRefreshNodeCount (FactionState & faction);
-
- inline bool
- canUnitMoveSoon (Unit * unit, const Vec2i & pos1, const Vec2i & pos2)
- {
- bool
- result = map->aproxCanMoveSoon (unit, pos1, pos2);
- return result;
- }
-
- inline void
- doAStarPathSearch (bool & nodeLimitReached, int &whileLoopCount,
- int &unitFactionIndex, bool & pathFound,
- Node * &node, const Vec2i & finalPos,
- const std::map < Vec2i, bool > &closedNodes,
- const std::map < Vec2i, Vec2i > &cameFrom,
- const std::map < std::pair < Vec2i, Vec2i >,
- bool > &canAddNode, Unit * &unit, int &maxNodeCount,
- int curFrameIndex)
- {
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d",
- nodeLimitReached, whileLoopCount, unitFactionIndex,
- pathFound, maxNodeCount);
-
- if (curFrameIndex >= 0)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__, szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- FactionState & faction = factions.getFactionState (unitFactionIndex);
-
- while (nodeLimitReached == false)
- {
- whileLoopCount++;
- if (faction.openNodesList.empty () == true)
- {
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d",
- nodeLimitReached, whileLoopCount,
- unitFactionIndex, pathFound, maxNodeCount);
-
- if (curFrameIndex >= 0)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__,
- szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- pathFound = false;
- break;
- }
- node = minHeuristicFastLookup (faction);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d node->pos = %s finalPos = %s node->exploredCell = %d",
- nodeLimitReached, whileLoopCount, unitFactionIndex,
- pathFound, maxNodeCount,
- node->pos.getString ().c_str (),
- finalPos.getString ().c_str (), node->exploredCell);
-
- if (curFrameIndex >= 0)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__, szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- if (node->pos == finalPos || node->exploredCell == false)
- {
- pathFound = true;
- break;
- }
-
- if (faction.closedNodesList.find (node->heuristic) ==
- faction.closedNodesList.end ())
- {
- faction.closedNodesList[node->heuristic].clear ();
- }
- faction.closedNodesList[node->heuristic].push_back (node);
- faction.openPosList[node->pos] = true;
-
- int
- failureCount = 0;
- int
- cellCount = 0;
-
-// if(Thread::isCurrentThreadMainThread() == false) {
-// throw megaglest_runtime_error("#1 Invalid access to FactionState random from outside main thread current id = " +
-// intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId()));
-// }
-
- //int tryDirection = 1;
- //int tryDirection = faction.random.IRandomX(1, 4);
- int
- tryDirection = faction.random.randRange (1, 4);
- //int tryDirection = unit->getRandom(true)->randRange(1, 4);
-
- if (SystemFlags::
- getSystemSettingType (SystemFlags::debugWorldSynch).enabled ==
- true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In doAStarPathSearch() tryDirection %d",
- tryDirection);
-
- if (curFrameIndex >= 0)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__, szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- if (tryDirection == 4)
- {
- for (int i = 1; i >= -1 && nodeLimitReached == false; --i)
- {
- for (int j = -1; j <= 1 && nodeLimitReached == false; ++j)
- {
- if (processNode
- (unit, node, finalPos, i, j, nodeLimitReached,
- maxNodeCount) == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- else if (tryDirection == 3)
- {
- for (int i = -1; i <= 1 && nodeLimitReached == false; ++i)
- {
- for (int j = 1; j >= -1 && nodeLimitReached == false; --j)
- {
- if (processNode
- (unit, node, finalPos, i, j, nodeLimitReached,
- maxNodeCount) == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- else if (tryDirection == 2)
- {
- for (int i = -1; i <= 1 && nodeLimitReached == false; ++i)
- {
- for (int j = -1; j <= 1 && nodeLimitReached == false; ++j)
- {
- if (processNode
- (unit, node, finalPos, i, j, nodeLimitReached,
- maxNodeCount) == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- else
- {
- for (int i = 1; i >= -1 && nodeLimitReached == false; --i)
- {
- for (int j = 1; j >= -1 && nodeLimitReached == false; --j)
- {
- if (processNode
- (unit, node, finalPos, i, j, nodeLimitReached,
- maxNodeCount) == false)
- {
- failureCount++;
- }
- cellCount++;
- }
- }
- }
- }
-
- if (SystemFlags::getSystemSettingType (SystemFlags::debugWorldSynch).
- enabled == true
- && SystemFlags::getSystemSettingType (SystemFlags::
- debugWorldSynchMax).
- enabled == true)
- {
- char
- szBuf[8096] = "";
- snprintf (szBuf, 8096,
- "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d",
- nodeLimitReached, whileLoopCount, unitFactionIndex,
- pathFound, maxNodeCount);
-
- if (curFrameIndex >= 0)
- {
- unit->logSynchDataThreaded (__FILE__, __LINE__, szBuf);
- }
- else
- {
- unit->logSynchData (__FILE__, __LINE__, szBuf);
- }
- }
-
- }
-
- };
-
- }
+ Glest {
+ namespace
+ Game {
+
+ // =====================================================
+ // class PathFinder
+ //
+ /// Finds paths for units using a modification of the A* algorithm
+ // =====================================================
+
+ class
+ PathFinder {
+ public:
+ class
+ BadUnitNodeList {
+ public:
+ BadUnitNodeList() {
+ unitSize = -1;
+ field = fLand;
+ }
+ int
+ unitSize;
+ Field
+ field;
+ std::map <
+ Vec2i,
+ std::map <
+ Vec2i,
+ bool > >
+ badPosList;
+
+ inline bool
+ isPosBad(const Vec2i & pos1, const Vec2i & pos2) {
+ bool
+ result = false;
+
+ std::map <
+ Vec2i,
+ std::map <
+ Vec2i,
+ bool > >::iterator
+ iterFind = badPosList.find(pos1);
+ if (iterFind != badPosList.end()) {
+ std::map < Vec2i, bool >::iterator iterFind2 =
+ iterFind->second.find(pos2);
+ if (iterFind2 != iterFind->second.end()) {
+ result = true;
+ }
+ }
+
+ return
+ result;
+ }
+ };
+
+ class
+ Node {
+ public:
+ Node() {
+ clear();
+ }
+ void
+ clear() {
+ pos.x = 0;
+ pos.y = 0;
+ next = NULL;
+ prev = NULL;
+ heuristic = 0.0;
+ exploredCell = false;
+ }
+ Vec2i
+ pos;
+ Node *
+ next;
+ Node *
+ prev;
+ float
+ heuristic;
+ bool
+ exploredCell;
+ };
+ typedef
+ vector <
+ Node * >
+ Nodes;
+
+ class
+ FactionState {
+ protected:
+ Mutex *
+ factionMutexPrecache;
+ public:
+ explicit
+ FactionState(int factionIndex) :
+ //factionMutexPrecache(new Mutex) {
+ factionMutexPrecache(NULL) { //, random(factionIndex) {
+
+ openPosList.clear();
+ openNodesList.
+ clear();
+ closedNodesList.
+ clear();
+ nodePool.
+ clear();
+ nodePoolCount = 0;
+ this->
+ factionIndex = factionIndex;
+ useMaxNodeCount = 0;
+
+ precachedTravelState.
+ clear();
+ precachedPath.
+ clear();
+ }
+ ~
+ FactionState() {
+
+ delete
+ factionMutexPrecache;
+ factionMutexPrecache = NULL;
+ }
+ Mutex *
+ getMutexPreCache() {
+ return factionMutexPrecache;
+ }
+
+ std::map < Vec2i, bool > openPosList;
+ std::map < float,
+ Nodes >
+ openNodesList;
+ std::map < float,
+ Nodes >
+ closedNodesList;
+ std::vector < Node > nodePool;
+
+ int
+ nodePoolCount;
+ int
+ factionIndex;
+ RandomGen
+ random;
+ //CRandomMersenne random;
+ int
+ useMaxNodeCount;
+
+ std::map < int,
+ TravelState >
+ precachedTravelState;
+ std::map < int,
+ std::vector <
+ Vec2i > >
+ precachedPath;
+ };
+
+ class
+ FactionStateManager {
+ protected:
+ typedef
+ vector <
+ FactionState * >
+ FactionStateList;
+ FactionStateList
+ factions;
+
+ void
+ init() {
+ for (int index = 0; index < GameConstants::maxPlayers; ++index) {
+ factions.push_back(new FactionState(index));
+ }
+ }
+
+ public:
+ FactionStateManager() {
+ init();
+ }
+ ~FactionStateManager() {
+ clear();
+ }
+
+ FactionState & getFactionState(int index) {
+ FactionState *
+ faction = factions[index];
+ return *faction;
+ }
+ void
+ clear() {
+ for (unsigned int index = 0;
+ index < (unsigned int) factions.size(); ++index) {
+ delete
+ factions[index];
+ }
+
+ factions.clear();
+ }
+ int
+ size() {
+ return (int) factions.size();
+ }
+ };
+
+ public:
+ static const int
+ maxFreeSearchRadius;
+
+ static const int
+ pathFindBailoutRadius;
+ static const int
+ pathFindExtendRefreshForNodeCount;
+ static const int
+ pathFindExtendRefreshNodeCountMin;
+ static const int
+ pathFindExtendRefreshNodeCountMax;
+
+ private:
+
+ static int
+ pathFindNodesMax;
+ static int
+ pathFindNodesAbsoluteMax;
+
+
+ FactionStateManager
+ factions;
+ const Map *
+ map;
+ bool
+ minorDebugPathfinder;
+
+ public:
+ PathFinder();
+ explicit
+ PathFinder(const Map * map);
+ ~PathFinder();
+
+ PathFinder(const PathFinder & obj) {
+ init();
+ throw
+ megaglest_runtime_error("class PathFinder is NOT safe to copy!");
+ }
+ PathFinder & operator= (const PathFinder & obj) {
+ init();
+ throw
+ megaglest_runtime_error("class PathFinder is NOT safe to assign!");
+ }
+
+ void
+ init(const Map * map);
+ TravelState
+ findPath(Unit * unit, const Vec2i & finalPos, bool * wasStuck =
+ NULL, int frameIndex = -1);
+ void
+ clearUnitPrecache(Unit * unit);
+ void
+ removeUnitPrecache(Unit * unit);
+ void
+ clearCaches();
+
+ //bool unitCannotMove(Unit *unit);
+
+ int
+ findNodeIndex(Node * node, Nodes & nodeList);
+ int
+ findNodeIndex(Node * node, std::vector < Node > &nodeList);
+
+ void
+ saveGame(XmlNode * rootNode);
+ void
+ loadGame(const XmlNode * rootNode);
+
+ private:
+ void
+ init();
+
+ TravelState
+ aStar(Unit * unit, const Vec2i & finalPos, bool inBailout,
+ int frameIndex, int maxNodeCount =
+ -1, uint32 * searched_node_count = NULL);
+ inline static Node *
+ newNode(FactionState & faction, int maxNodeCount) {
+ if (faction.nodePoolCount < (int) faction.nodePool.size() &&
+ faction.nodePoolCount < maxNodeCount) {
+ Node *
+ node = &(faction.nodePool[faction.nodePoolCount]);
+ node->clear();
+ faction.nodePoolCount++;
+ return node;
+ }
+ return NULL;
+ }
+
+ Vec2i
+ computeNearestFreePos(const Unit * unit, const Vec2i & targetPos);
+
+ inline static float
+ heuristic(const Vec2i & pos, const Vec2i & finalPos) {
+ return pos.dist(finalPos);
+ }
+
+ inline static bool
+ openPos(const Vec2i & sucPos, FactionState & faction) {
+ if (faction.openPosList.find(sucPos) == faction.openPosList.end()) {
+ return false;
+ }
+ return true;
+ }
+
+ inline static Node *
+ minHeuristicFastLookup(FactionState & faction) {
+ if (faction.openNodesList.empty() == true) {
+ throw
+ megaglest_runtime_error("openNodesList.empty() == true");
+ }
+
+ Node *
+ result = faction.openNodesList.begin()->second.front();
+ faction.openNodesList.begin()->second.erase(faction.openNodesList.
+ begin()->second.
+ begin());
+ if (faction.openNodesList.begin()->second.empty()) {
+ faction.openNodesList.erase(faction.openNodesList.begin());
+ }
+ return result;
+ }
+
+ inline bool
+ processNode(Unit * unit, Node * node, const Vec2i finalPos,
+ int x, int y, bool & nodeLimitReached, int maxNodeCount) {
+ bool
+ result = false;
+ Vec2i
+ sucPos = node->pos + Vec2i(x, y);
+
+ int
+ unitFactionIndex = unit->getFactionIndex();
+ FactionState & faction = factions.getFactionState(unitFactionIndex);
+
+ bool
+ foundOpenPosForPos = openPos(sucPos, faction);
+ bool
+ allowUnitMoveSoon = canUnitMoveSoon(unit, node->pos, sucPos);
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In processNode() nodeLimitReached %d unitFactionIndex %d foundOpenPosForPos %d allowUnitMoveSoon %d maxNodeCount %d node->pos = %s finalPos = %s sucPos = %s faction.openPosList.size() %lu closedNodesList.size() %lu",
+ nodeLimitReached, unitFactionIndex, foundOpenPosForPos,
+ allowUnitMoveSoon, maxNodeCount,
+ node->pos.getString().c_str(),
+ finalPos.getString().c_str(),
+ sucPos.getString().c_str(),
+ faction.openPosList.size(),
+ faction.closedNodesList.size());
+
+ if (Thread::isCurrentThreadMainThread() == false) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ if (foundOpenPosForPos == false && allowUnitMoveSoon) {
+ //if node is not open and canMove then generate another node
+ Node *
+ sucNode = newNode(faction, maxNodeCount);
+ if (sucNode != NULL) {
+ sucNode->pos = sucPos;
+ sucNode->heuristic = heuristic(sucNode->pos, finalPos);
+ sucNode->prev = node;
+ sucNode->next = NULL;
+ sucNode->exploredCell =
+ map->getSurfaceCell(Map::toSurfCoords(sucPos))->
+ isExplored(unit->getTeam());
+ if (faction.openNodesList.find(sucNode->heuristic) ==
+ faction.openNodesList.end()) {
+ faction.openNodesList[sucNode->heuristic].clear();
+ }
+ faction.openNodesList[sucNode->heuristic].push_back(sucNode);
+ faction.openPosList[sucNode->pos] = true;
+
+ result = true;
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096, "In processNode() sucPos = %s",
+ sucPos.getString().c_str());
+
+ if (Thread::isCurrentThreadMainThread() == false) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__,
+ szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ } else {
+ nodeLimitReached = true;
+ }
+ }
+
+ return result;
+ }
+
+ void
+ processNearestFreePos(const Vec2i & finalPos, int i, int j, int size,
+ Field field, int teamIndex, Vec2i unitPos,
+ Vec2i & nearestPos, float &nearestDist);
+ int
+ getPathFindExtendRefreshNodeCount(FactionState & faction);
+
+ inline bool
+ canUnitMoveSoon(Unit * unit, const Vec2i & pos1, const Vec2i & pos2) {
+ bool
+ result = map->aproxCanMoveSoon(unit, pos1, pos2);
+ return result;
+ }
+
+ inline void
+ doAStarPathSearch(bool & nodeLimitReached, int &whileLoopCount,
+ int &unitFactionIndex, bool & pathFound,
+ Node * &node, const Vec2i & finalPos,
+ const std::map < Vec2i, bool > &closedNodes,
+ const std::map < Vec2i, Vec2i > &cameFrom,
+ const std::map < std::pair < Vec2i, Vec2i >,
+ bool > &canAddNode, Unit * &unit, int &maxNodeCount,
+ int curFrameIndex) {
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d",
+ nodeLimitReached, whileLoopCount, unitFactionIndex,
+ pathFound, maxNodeCount);
+
+ if (curFrameIndex >= 0) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ FactionState & faction = factions.getFactionState(unitFactionIndex);
+
+ while (nodeLimitReached == false) {
+ whileLoopCount++;
+ if (faction.openNodesList.empty() == true) {
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d",
+ nodeLimitReached, whileLoopCount,
+ unitFactionIndex, pathFound, maxNodeCount);
+
+ if (curFrameIndex >= 0) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__,
+ szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ pathFound = false;
+ break;
+ }
+ node = minHeuristicFastLookup(faction);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d node->pos = %s finalPos = %s node->exploredCell = %d",
+ nodeLimitReached, whileLoopCount, unitFactionIndex,
+ pathFound, maxNodeCount,
+ node->pos.getString().c_str(),
+ finalPos.getString().c_str(), node->exploredCell);
+
+ if (curFrameIndex >= 0) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ if (node->pos == finalPos || node->exploredCell == false) {
+ pathFound = true;
+ break;
+ }
+
+ if (faction.closedNodesList.find(node->heuristic) ==
+ faction.closedNodesList.end()) {
+ faction.closedNodesList[node->heuristic].clear();
+ }
+ faction.closedNodesList[node->heuristic].push_back(node);
+ faction.openPosList[node->pos] = true;
+
+ int
+ failureCount = 0;
+ int
+ cellCount = 0;
+
+ // if(Thread::isCurrentThreadMainThread() == false) {
+ // throw megaglest_runtime_error("#1 Invalid access to FactionState random from outside main thread current id = " +
+ // intToStr(Thread::getCurrentThreadId()) + " main = " + intToStr(Thread::getMainThreadId()));
+ // }
+
+ //int tryDirection = 1;
+ //int tryDirection = faction.random.IRandomX(1, 4);
+ int
+ tryDirection = faction.random.randRange(1, 4);
+ //int tryDirection = unit->getRandom(true)->randRange(1, 4);
+
+ if (SystemFlags::
+ getSystemSettingType(SystemFlags::debugWorldSynch).enabled ==
+ true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In doAStarPathSearch() tryDirection %d",
+ tryDirection);
+
+ if (curFrameIndex >= 0) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ if (tryDirection == 4) {
+ for (int i = 1; i >= -1 && nodeLimitReached == false; --i) {
+ for (int j = -1; j <= 1 && nodeLimitReached == false; ++j) {
+ if (processNode
+ (unit, node, finalPos, i, j, nodeLimitReached,
+ maxNodeCount) == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ } else if (tryDirection == 3) {
+ for (int i = -1; i <= 1 && nodeLimitReached == false; ++i) {
+ for (int j = 1; j >= -1 && nodeLimitReached == false; --j) {
+ if (processNode
+ (unit, node, finalPos, i, j, nodeLimitReached,
+ maxNodeCount) == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ } else if (tryDirection == 2) {
+ for (int i = -1; i <= 1 && nodeLimitReached == false; ++i) {
+ for (int j = -1; j <= 1 && nodeLimitReached == false; ++j) {
+ if (processNode
+ (unit, node, finalPos, i, j, nodeLimitReached,
+ maxNodeCount) == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ } else {
+ for (int i = 1; i >= -1 && nodeLimitReached == false; --i) {
+ for (int j = 1; j >= -1 && nodeLimitReached == false; --j) {
+ if (processNode
+ (unit, node, finalPos, i, j, nodeLimitReached,
+ maxNodeCount) == false) {
+ failureCount++;
+ }
+ cellCount++;
+ }
+ }
+ }
+ }
+
+ if (SystemFlags::getSystemSettingType(SystemFlags::debugWorldSynch).
+ enabled == true
+ && SystemFlags::getSystemSettingType(SystemFlags::
+ debugWorldSynchMax).
+ enabled == true) {
+ char
+ szBuf[8096] = "";
+ snprintf(szBuf, 8096,
+ "In doAStarPathSearch() nodeLimitReached %d whileLoopCount %d unitFactionIndex %d pathFound %d maxNodeCount %d",
+ nodeLimitReached, whileLoopCount, unitFactionIndex,
+ pathFound, maxNodeCount);
+
+ if (curFrameIndex >= 0) {
+ unit->logSynchDataThreaded(__FILE__, __LINE__, szBuf);
+ } else {
+ unit->logSynchData(__FILE__, __LINE__, szBuf);
+ }
+ }
+
+ }
+
+ };
+
+ }
} //end namespace
#endif
diff --git a/source/glest_game/facilities/auto_test.cpp b/source/glest_game/facilities/auto_test.cpp
index ff2167f02..28fdb3a72 100644
--- a/source/glest_game/facilities/auto_test.cpp
+++ b/source/glest_game/facilities/auto_test.cpp
@@ -23,89 +23,90 @@
#include "leak_dumper.h"
-namespace Glest{ namespace Game{
+namespace Glest {
+ namespace Game {
-// =====================================================
-// class AutoTest
-// =====================================================
+ // =====================================================
+ // class AutoTest
+ // =====================================================
-const time_t AutoTest::invalidTime = -1;
-time_t AutoTest::gameTime = 60 * 20;
-bool AutoTest::wantExitGame = false;
+ const time_t AutoTest::invalidTime = -1;
+ time_t AutoTest::gameTime = 60 * 20;
+ bool AutoTest::wantExitGame = false;
-GameSettings AutoTest::gameSettings;
-string AutoTest::loadGameSettingsFile = "";
+ GameSettings AutoTest::gameSettings;
+ string AutoTest::loadGameSettingsFile = "";
-// ===================== PUBLIC ========================
+ // ===================== PUBLIC ========================
-AutoTest::AutoTest() {
- exitGame = false;
- gameStartTime = invalidTime;
- random.init(time(NULL));
-}
-
-AutoTest & AutoTest::getInstance() {
- static AutoTest autoTest;
- return autoTest;
-}
-
-void AutoTest::updateIntro(Program *program) {
- program->setState(new MainMenu(program));
-}
-
-void AutoTest::updateRoot(Program *program, MainMenu *mainMenu) {
- mainMenu->setState(new MenuStateNewGame(program, mainMenu));
-}
-
-void AutoTest::updateNewGame(Program *program, MainMenu *mainMenu) {
- if(loadGameSettingsFile != "") {
- gameStartTime = invalidTime;
- bool fileFound = CoreData::getInstance().loadGameSettingsFromFile(
- loadGameSettingsFile, &gameSettings);
-
- if(fileFound == false) {
- throw megaglest_runtime_error("Specified game settings file [" + loadGameSettingsFile + "] was NOT found!");
+ AutoTest::AutoTest() {
+ exitGame = false;
+ gameStartTime = invalidTime;
+ random.init(time(NULL));
}
- //printf("Got settings:\n%s",gameSettings.toString().c_str());
- mainMenu->setState(new MenuStateCustomGame(program, mainMenu, false, pNewGame, true, &gameSettings));
- }
- else {
- mainMenu->setState(new MenuStateScenario(program, mainMenu, false,
- Config::getInstance().getPathListForType(ptScenarios)));
- }
-}
-void AutoTest::updateScenario(MenuStateScenario *menuStateScenario) {
- gameStartTime = invalidTime;
-
- int scenarioIndex = random.randRange(0, menuStateScenario->getScenarioCount()-1);
- menuStateScenario->setScenario(scenarioIndex);
-
- menuStateScenario->launchGame();
-}
-
-bool AutoTest::updateGame(Game *game) {
- // record start time
- if(gameStartTime == invalidTime) {
- gameStartTime = time(NULL);
- }
-
- // quit if we've espend enough time in the game
- if(difftime(time(NULL),gameStartTime) > gameTime) {
- Program *program = game->getProgram();
- Stats endStats = game->quitGame();
- if(AutoTest::wantExitGame == true) {
- exitGame = true;
+ AutoTest & AutoTest::getInstance() {
+ static AutoTest autoTest;
+ return autoTest;
}
- Game::exitGameState(program, endStats);
- return true;
+
+ void AutoTest::updateIntro(Program *program) {
+ program->setState(new MainMenu(program));
+ }
+
+ void AutoTest::updateRoot(Program *program, MainMenu *mainMenu) {
+ mainMenu->setState(new MenuStateNewGame(program, mainMenu));
+ }
+
+ void AutoTest::updateNewGame(Program *program, MainMenu *mainMenu) {
+ if (loadGameSettingsFile != "") {
+ gameStartTime = invalidTime;
+ bool fileFound = CoreData::getInstance().loadGameSettingsFromFile(
+ loadGameSettingsFile, &gameSettings);
+
+ if (fileFound == false) {
+ throw megaglest_runtime_error("Specified game settings file [" + loadGameSettingsFile + "] was NOT found!");
+ }
+ //printf("Got settings:\n%s",gameSettings.toString().c_str());
+ mainMenu->setState(new MenuStateCustomGame(program, mainMenu, false, pNewGame, true, &gameSettings));
+ } else {
+ mainMenu->setState(new MenuStateScenario(program, mainMenu, false,
+ Config::getInstance().getPathListForType(ptScenarios)));
+ }
+ }
+
+ void AutoTest::updateScenario(MenuStateScenario *menuStateScenario) {
+ gameStartTime = invalidTime;
+
+ int scenarioIndex = random.randRange(0, menuStateScenario->getScenarioCount() - 1);
+ menuStateScenario->setScenario(scenarioIndex);
+
+ menuStateScenario->launchGame();
+ }
+
+ bool AutoTest::updateGame(Game *game) {
+ // record start time
+ if (gameStartTime == invalidTime) {
+ gameStartTime = time(NULL);
+ }
+
+ // quit if we've espend enough time in the game
+ if (difftime(time(NULL), gameStartTime) > gameTime) {
+ Program *program = game->getProgram();
+ Stats endStats = game->quitGame();
+ if (AutoTest::wantExitGame == true) {
+ exitGame = true;
+ }
+ Game::exitGameState(program, endStats);
+ return true;
+ }
+
+ return false;
+ }
+
+ void AutoTest::updateBattleEnd(Program *program) {
+ program->setState(new MainMenu(program));
+ }
+
}
-
- return false;
-}
-
-void AutoTest::updateBattleEnd(Program *program) {
- program->setState(new MainMenu(program));
-}
-
-}}//end namespace
+}//end namespace
diff --git a/source/glest_game/facilities/auto_test.h b/source/glest_game/facilities/auto_test.h
index 73b878fc4..da6d8c891 100644
--- a/source/glest_game/facilities/auto_test.h
+++ b/source/glest_game/facilities/auto_test.h
@@ -13,8 +13,8 @@
#define _SHARED_UTIL_AUTO_TEST_H_
#ifdef WIN32
- #include
- #include
+#include
+#include
#endif
#include
@@ -26,51 +26,63 @@
using namespace std;
using Shared::Util::RandomGen;
-namespace Glest{ namespace Game{
+namespace Glest {
+ namespace Game {
-class Program;
-class MainMenu;
-class MenuStateScenario;
-class Game;
+ class Program;
+ class MainMenu;
+ class MenuStateScenario;
+ class Game;
-// =====================================================
-// class AutoTest
-//
-/// Interface to write log files
-// =====================================================
+ // =====================================================
+ // class AutoTest
+ //
+ /// Interface to write log files
+ // =====================================================
-class AutoTest{
-private:
- int gameStartTime;
- RandomGen random;
- bool exitGame;
- static bool wantExitGame;
+ class AutoTest {
+ private:
+ int gameStartTime;
+ RandomGen random;
+ bool exitGame;
+ static bool wantExitGame;
- static GameSettings gameSettings;
- static string loadGameSettingsFile;
+ static GameSettings gameSettings;
+ static string loadGameSettingsFile;
- static const time_t invalidTime;
- static time_t gameTime;
+ static const time_t invalidTime;
+ static time_t gameTime;
-public:
- static AutoTest & getInstance();
- AutoTest();
+ public:
+ static AutoTest & getInstance();
+ AutoTest();
- static void setMaxGameTime(time_t value) { gameTime = value; }
- static void setWantExitGameWhenDone(bool value) { wantExitGame = value; }
- static string getLoadGameSettingsFile() { return loadGameSettingsFile; }
- static void setLoadGameSettingsFile(const string &filename) { loadGameSettingsFile = filename; }
+ static void setMaxGameTime(time_t value) {
+ gameTime = value;
+ }
+ static void setWantExitGameWhenDone(bool value) {
+ wantExitGame = value;
+ }
+ static string getLoadGameSettingsFile() {
+ return loadGameSettingsFile;
+ }
+ static void setLoadGameSettingsFile(const string &filename) {
+ loadGameSettingsFile = filename;
+ }
- bool mustExitGame() const { return exitGame; }
+ bool mustExitGame() const {
+ return exitGame;
+ }
- void updateIntro(Program *program);
- void updateRoot(Program *program, MainMenu *mainMenu);
- void updateNewGame(Program *program, MainMenu *mainMenu);
- void updateScenario(MenuStateScenario *menuStateScenario);
- bool updateGame(Game *game);
- void updateBattleEnd(Program *program);
-};
+ void updateIntro(Program *program);
+ void updateRoot(Program *program, MainMenu *mainMenu);
+ void updateNewGame(Program *program, MainMenu *mainMenu);
+ void updateScenario(MenuStateScenario *menuStateScenario);
+ bool updateGame(Game *game);
+ void updateBattleEnd(Program *program);
+ };
-}}//end namespace
+ }
+}//end namespace
#endif
diff --git a/source/glest_game/facilities/components.cpp b/source/glest_game/facilities/components.cpp
index fe581fa74..607624d57 100644
--- a/source/glest_game/facilities/components.cpp
+++ b/source/glest_game/facilities/components.cpp
@@ -26,1155 +26,1136 @@
using namespace std;
using namespace Shared::Util;
-namespace Glest{ namespace Game{
+namespace Glest {
+ namespace Game {
-// =====================================================
-// class GraphicComponent
-// =====================================================
+ // =====================================================
+ // class GraphicComponent
+ // =====================================================
-float GraphicComponent::anim= 0.f;
-float GraphicComponent::fade= 0.f;
-const float GraphicComponent::animSpeed= 0.02f;
-const float GraphicComponent::fadeSpeed= 0.01f;
-// WHITE
-Vec3f GraphicComponent::customTextColor = Vec3f(1.0,1.0,1.0);
+ float GraphicComponent::anim = 0.f;
+ float GraphicComponent::fade = 0.f;
+ const float GraphicComponent::animSpeed = 0.02f;
+ const float GraphicComponent::fadeSpeed = 0.01f;
+ // WHITE
+ Vec3f GraphicComponent::customTextColor = Vec3f(1.0, 1.0, 1.0);
-std::map > GraphicComponent::registeredGraphicComponentList;
+ std::map > GraphicComponent::registeredGraphicComponentList;
-GraphicComponent::GraphicComponent(const std::string &containerName, const std::string &objName, bool registerControl) {
- this->containerName = containerName;
- this->instanceName = "";
- if(containerName == "" || objName == "") {
- //char szBuf[8096]="";
- //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",containerName.c_str(),objName.c_str());
- //throw megaglest_runtime_error(szBuf);
- }
- if(objName != "" && registerControl) {
- registerGraphicComponent(containerName,objName);
- }
- else {
- this->instanceName = objName;
- }
- this->fontCallbackName = objName + "_" + getNewUUD();
- CoreData::getInstance().registerFontChangedCallback(this->getFontCallbackName(), this);
+ GraphicComponent::GraphicComponent(const std::string &containerName, const std::string &objName, bool registerControl) {
+ this->containerName = containerName;
+ this->instanceName = "";
+ if (containerName == "" || objName == "") {
+ //char szBuf[8096]="";
+ //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",containerName.c_str(),objName.c_str());
+ //throw megaglest_runtime_error(szBuf);
+ }
+ if (objName != "" && registerControl) {
+ registerGraphicComponent(containerName, objName);
+ } else {
+ this->instanceName = objName;
+ }
+ this->fontCallbackName = objName + "_" + getNewUUD();
+ CoreData::getInstance().registerFontChangedCallback(this->getFontCallbackName(), this);
- enabled = true;
- editable = true;
- visible = true;
- x = 0;
- y = 0;
- w = 0;
- h = 0;
- text = "";
- font = NULL;
- font3D = NULL;
- textNativeTranslation = "";
-}
-
-string GraphicComponent::getNewUUD() {
- char uuid_str[38];
- get_uuid_string(uuid_str,sizeof(uuid_str));
- return string(uuid_str);
-}
-
-GraphicComponent::~GraphicComponent() {
- CoreData::getInstance().unRegisterFontChangedCallback(this->getFontCallbackName());
-}
-
-void GraphicComponent::clearRegisteredComponents(std::string containerName) {
- if(containerName == "") {
- GraphicComponent::registeredGraphicComponentList.clear();
- }
- else {
- GraphicComponent::registeredGraphicComponentList[containerName].clear();
- }
-}
-
-void GraphicComponent::clearRegisterGraphicComponent(std::string containerName, std::string objName) {
- GraphicComponent *obj = findRegisteredComponent(containerName, objName);
- if(obj) {
- GraphicComponent::registeredGraphicComponentList[containerName].erase(objName);
- }
-}
-
-void GraphicComponent::clearRegisterGraphicComponent(std::string containerName, std::vector objNameList) {
- for(int idx = 0; idx < (int)objNameList.size(); ++idx) {
- GraphicComponent::clearRegisterGraphicComponent(containerName, objNameList[idx]);
- }
-}
-
-void GraphicComponent::registerGraphicComponent(std::string containerName, std::string objName) {
- // unregistered old name if we have been renamed
- if(this->getInstanceName() != "") {
- //printf("RENAME Register Callback detected calling: Control old [%s] new [%s]\n",this->getInstanceName().c_str(),objName.c_str());
- clearRegisterGraphicComponent(this->containerName, this->getInstanceName());
- }
- else {
- //printf("NEW Register Callback detected calling: Control container [%s] name [%s]\n",containerName.c_str(),objName.c_str());
- }
-
- if(containerName == "" || objName == "") {
- //char szBuf[8096]="";
- //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",this->containerName.c_str(),objName.c_str());
- //throw megaglest_runtime_error(szBuf);
- }
-
- this->containerName = containerName;
- this->instanceName = objName;
- registeredGraphicComponentList[containerName][objName] = this;
- //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] registered [%s] [%s] count = %d\n",__FILE__,__FUNCTION__,__LINE__,containerName.c_str(),instanceName.c_str(),registeredGraphicComponentList[containerName].size());
-}
-
-void GraphicComponent::registerGraphicComponentOnlyFontCallbacks(std::string containerName, std::string objName) {
- if(this->getInstanceName() != "") {
- //printf("(FONT ONLY) RENAME Register Callback detected calling: Control old [%s] new [%s]\n",this->getInstanceName().c_str(),objName.c_str());
- clearRegisterGraphicComponent(this->containerName, this->getInstanceName());
- }
- else {
- //printf("(FONT ONLY) NEW Register Callback detected calling: Control container [%s] name [%s]\n",containerName.c_str(),objName.c_str());
- }
-
- if(containerName == "" || objName == "") {
- //char szBuf[8096]="";
- //snprintf(szBuf,8096,"Control not properly registered Container [%s] Control [%s]\n",this->containerName.c_str(),objName.c_str());
- //throw megaglest_runtime_error(szBuf);
- }
-
- this->containerName = containerName;
- this->instanceName = objName;
-}
-
-GraphicComponent * GraphicComponent::findRegisteredComponent(std::string containerName, std::string objName) {
- GraphicComponent *result = NULL;
-
- std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName);
- if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) {
- std::map::iterator iterFind2 = iterFind1->second.find(objName);
- if(iterFind2 != iterFind1->second.end()) {
- result = iterFind2->second;
+ enabled = true;
+ editable = true;
+ visible = true;
+ x = 0;
+ y = 0;
+ w = 0;
+ h = 0;
+ text = "";
+ font = NULL;
+ font3D = NULL;
+ textNativeTranslation = "";
}
- }
- return result;
-}
-void GraphicComponent::applyAllCustomProperties(std::string containerName) {
- std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName);
- if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) {
- for(std::map::iterator iterFind2 = iterFind1->second.begin();
- iterFind2 != iterFind1->second.end(); ++iterFind2) {
- iterFind2->second->applyCustomProperties(containerName);
+ string GraphicComponent::getNewUUD() {
+ char uuid_str[38];
+ get_uuid_string(uuid_str, sizeof(uuid_str));
+ return string(uuid_str);
}
- }
-}
-void GraphicComponent::applyCustomProperties(std::string containerName) {
- if(instanceName != "") {
- std::map >::iterator iterFind1 = GraphicComponent::registeredGraphicComponentList.find(containerName);
- if(iterFind1 != GraphicComponent::registeredGraphicComponentList.end()) {
- std::map::iterator iterFind2 = iterFind1->second.find(instanceName);
- if(iterFind2 != iterFind1->second.end()) {
- Config &config = Config::getInstance();
+ GraphicComponent::~GraphicComponent() {
+ CoreData::getInstance().unRegisterFontChangedCallback(this->getFontCallbackName());
+ }
- //string languageToken = config.getString("Lang");
- string languageToken = Lang::getInstance().getLanguage();
-
- //if(dynamic_cast(iterFind2->second) != NULL) {
- GraphicComponent *ctl = dynamic_cast