diff --git a/AI/Interfaces/Java/CMakeLists.txt b/AI/Interfaces/Java/CMakeLists.txt deleted file mode 100644 index 9220868084e..00000000000 --- a/AI/Interfaces/Java/CMakeLists.txt +++ /dev/null @@ -1,661 +0,0 @@ -### Java AI Interface -# -# Global variables set in this file: -# * BUILD_Java_AIINTERFACE -# * Java_AIINTERFACE_VERS -# * Java_AIINTERFACE_TARGET -# -# Functions and macros defined in this file: -# * configure_java_skirmish_ai -# - -#enable_language(Java) - - -################################################################################ -### BEGIN: MACROS_AND_FUNCTIONS -# Define macros and functions to be used in this file and by Java Skirmish AIs - -# includes rts/build/cmake/UtilJava.cmake -include(UtilJava) - -# Java Skirmish AI configuration macro. -# This will be called from Java AIs at AI/Skirmish/*/CMakeLists.txt. -macro (configure_java_skirmish_ai wrapperNames) - # Assemble meta data - set(myDir "${CMAKE_CURRENT_SOURCE_DIR}") - get_last_path_part(dirName ${myDir}) - set(myName "${dirName}") - set(myJarFile "SkirmishAI") - set(myBinJarFile "${myJarFile}.jar") - set(mySrcJarFile "${myJarFile}-src.jar") - set(myJLibDir "${myDir}/data/jlib") - get_version_plus_dep_file(myVersion myVersionDepFile) - set(myTarget "${myName}") - set(myInstLibsDir "${SKIRMISH_AI_LIBS}/${myName}/${myVersion}") - set(myInstDataDir "${SKIRMISH_AI_DATA}/${myName}/${myVersion}") - # CMAKE_CURRENT_BINARY_DIR: .../spring-build-dir/AI/Skirmish/${myName} - set(myBuildDir "${CMAKE_CURRENT_BINARY_DIR}") - - # Check if the user wants to compile the AI - set(BUILD_THIS_SKIRMISHAI FALSE) - if (BUILD_Java_AIINTERFACE AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - set(BUILD_THIS_SKIRMISHAI TRUE) - endif (BUILD_Java_AIINTERFACE AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - if (NOT BUILD_THIS_SKIRMISHAI) - message("warning: ${myName} Skirmish AI will not be built!") - endif (NOT BUILD_THIS_SKIRMISHAI) - - # Compile and install - if (BUILD_THIS_SKIRMISHAI) - file(MAKE_DIRECTORY "${myBuildDir}/jlib") - - set(configString "default") - skirmish_ai_message(STATUS "Found Skirmish AI: ${myName} ${myVersion} (config: ${configString})") - - # Assemble project generated targets (and their libraries) we depend on - set(myDependTargets "${Java_AIINTERFACE_TARGET}") - set(myDependLibFiles "${Java_AIINTERFACE_JAR_BIN}") - foreach (wrapperName ${wrapperNames}) - set(myDependTargets ${myDependTargets} "${${wrapperName}_AIWRAPPER_TARGET}") - set(myDependLibFiles ${myDependLibFiles} "${${wrapperName}_AIWRAPPER_JAR_BIN}") - endforeach (wrapperName) - set_source_files_properties(${myDependLibFiles} PROPERTIES GENERATED TRUE) - - # find java source root - if (EXISTS "${myDir}/src/main/java") - # default Maven source dir - set(mySourceDir "${myDir}/src/main/java") - elseif (EXISTS "${myDir}/src") - # simple java source dir path - set(mySourceDir "${myDir}/src") - else (EXISTS "${myDir}/src/main/java") - message(SEND_ERROR "No sources dir found for Skirmish AI: ${myName}") - endif (EXISTS "${myDir}/src/main/java") - - # Create a list of all the AIs source files (for compiling) - file(GLOB_RECURSE mySources RELATIVE "${mySourceDir}" FOLLOW_SYMLINKS "${mySourceDir}/*.java") - # Create a list of all the AIs source files (for dependency tracking) - file(GLOB_RECURSE mySourcesDep FOLLOW_SYMLINKS "${mySourceDir}/*.java") - - set_source_files_properties("${myBuildDir}/${myBinJarFile}" PROPERTIES GENERATED TRUE) - set_source_files_properties("${myBuildDir}/${mySrcJarFile}" PROPERTIES GENERATED TRUE) - - - # If main Java package is "my.ai.pkg", this has to be set to "my". - get_first_sub_dir_name(firstSrcSubDir ${mySourceDir}) - set(myJavaPkgFirstPart "${firstSrcSubDir}") - - # Assemble additional meta data - set(myBinaryTarget "${myTarget}-BIN") - set(mySourceTarget "${myTarget}-SRC") - set(myJavaBuildDir "${myBuildDir}/classes") - - add_custom_target(${myBinaryTarget} - DEPENDS "${myBuildDir}/${myBinJarFile}") - add_dependencies(${myBinaryTarget} ${myDependTargets}) - - add_custom_target(${mySourceTarget} - DEPENDS "${myBuildDir}/${mySrcJarFile}") - - add_custom_target(${myTarget} ALL DEPENDS ${myVersionDepFile}) - add_dependencies(${myTarget} ${myBinaryTarget} ${mySourceTarget}) - - # Create our full Java class-path - create_classpath(myJavaLibs ${myJLibDir}) - concat_classpaths(myClassPath "${CLASSPATH_Java_AIINTERFACE}" "${myJavaLibs}") - foreach (wrapperName ${wrapperNames}) - concat_classpaths(myClassPath "${myClassPath}" "${${wrapperName}_AIWRAPPER_JAR_CLASSPATH}") - endforeach (wrapperName) - - # Locate the manifest file - find_manifest_file("${myDir}" myManifestFile) - if (myManifestFile) - set(myBinJarArgs "cmf" "${myManifestFile}") - else (myManifestFile) - set(myBinJarArgs "cf") - endif (myManifestFile) - - # Write list of source files to an arg-file - set(mySrcArgFile "${myBuildDir}/sourceFiles.txt") - if (EXISTS "${mySrcArgFile}") - file(REMOVE "${mySrcArgFile}") - endif (EXISTS "${mySrcArgFile}") - set(mySrcArgFile "${myBuildDir}/sourceFiles.txt") - foreach (srcFile ${mySources}) - file(APPEND "${mySrcArgFile}" "\"${srcFile}\"\n") - endforeach (srcFile) - - # Compile and pack the library - add_custom_command( - OUTPUT - "${myBuildDir}/${myBinJarFile}" - DEPENDS - ${myDependLibFiles} - ${mySourcesDep} - COMMAND "${CMAKE_COMMAND}" - "-E" "remove_directory" "${myJavaBuildDir}" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myJavaBuildDir}" - COMMAND "${Java_JAVAC_EXECUTABLE}" - "${JAVA_COMPILE_FLAG_CONDITIONAL}" - "-Xlint:deprecation" - "-cp" "${myClassPath}" - "-d" "${myJavaBuildDir}" - "@${mySrcArgFile}" - COMMAND "${Java_JAR_EXECUTABLE}" - ${myBinJarArgs} "${myBuildDir}/${myBinJarFile}" - "-C" "${myJavaBuildDir}" "${myJavaPkgFirstPart}" - WORKING_DIRECTORY - "${mySourceDir}" - COMMENT - " ${myTarget}: Compiling sources and packing library ${myBinJarFile}" VERBATIM - ) - - # Pack the sources - add_custom_command( - OUTPUT - "${myBuildDir}/${mySrcJarFile}" - COMMAND "${Java_JAR_EXECUTABLE}" - "cf" "${myBuildDir}/${mySrcJarFile}" - "-C" "${mySourceDir}" "${myJavaPkgFirstPart}" - DEPENDS - ${mySourcesDeps} - WORKING_DIRECTORY - "${mySourceDir}" - COMMENT - " ${myTarget}: Creating sources archive ${mySrcJarFile}" VERBATIM - ) - - # Install the data files - install(DIRECTORY "${myDir}/data/" DESTINATION ${myInstDataDir}) - # Install the library - install(FILES "${myBuildDir}/${myBinJarFile}" DESTINATION ${myInstDataDir}) - # Install the sources archive (optional) - install(FILES "${myBuildDir}/${mySrcJarFile}" DESTINATION ${myInstDataDir}/jlib OPTIONAL) - - # Install files generated/downloaded during buildtime - install(DIRECTORY "${myBuildDir}/jlib/" DESTINATION ${myInstDataDir}/jlib) - if (EXISTS "${myBuildDir}/resources") - install(DIRECTORY "${myBuildDir}/resources/" DESTINATION ${myInstDataDir}/resources) - endif (EXISTS "${myBuildDir}/resources") - if (EXISTS "${myBuildDir}/config") - install(DIRECTORY "${myBuildDir}/config/" DESTINATION ${myInstDataDir}/config) - endif (EXISTS "${myBuildDir}/config") - if (EXISTS "${myBuildDir}/script") - install(DIRECTORY "${myBuildDir}/script/" DESTINATION ${myInstDataDir}/script) - endif (EXISTS "${myBuildDir}/script") - - # Install special script and config files - if (EXISTS "${myDir}/src/main/groovy") - install(DIRECTORY "${myDir}/src/main/groovy/" DESTINATION ${myInstDataDir}/script) - endif (EXISTS "${myDir}/src/main/groovy") - if (EXISTS "${myDir}/src/main/ruby") - install(DIRECTORY "${myDir}/src/main/ruby/" DESTINATION ${myInstDataDir}/script) - endif (EXISTS "${myDir}/src/main/ruby") - if (EXISTS "${myDir}/src/main/bsh") - install(DIRECTORY "${myDir}/src/main/bsh/" DESTINATION ${myInstDataDir}/script) - endif (EXISTS "${myDir}/src/main/bsh") - if (EXISTS "${myDir}/src/main/config") - install(DIRECTORY "${myDir}/src/main/config/" DESTINATION ${myInstDataDir}/config) - endif (EXISTS "${myDir}/src/main/config") - - # Install jars of wrappers - foreach (wrapperName ${wrapperNames}) - # Install the wrappers main jar - install(FILES "${${wrapperName}_AIWRAPPER_JAR_BIN}" DESTINATION ${myInstDataDir}/jlib) - set(wrapperJLibDir "${CMAKE_SOURCE_DIR}/AI/Wrappers/${wrapperName}/jlib") - # Install the wrappers java libs, if there are any - if (EXISTS ${wrapperJLibDir}) - install(DIRECTORY "${wrapperJLibDir}/" DESTINATION ${myInstDataDir}/jlib) - endif (EXISTS ${wrapperJLibDir}) - endforeach (wrapperName) - endif (BUILD_THIS_SKIRMISHAI) -endmacro (configure_java_skirmish_ai wrapperNames) - - -### END: MACROS_AND_FUNCTIONS -################################################################################ - - -set(myName "Java") -set(myDir "${CMAKE_CURRENT_SOURCE_DIR}") -set(mySourceDirRel "src/main") -set(myJavaSourceDirRel "src/main/java") -set(myNativeSourceDirRel "src/main/native") -set(myPkgFirstPart "com") -set(myPkg "${myPkgFirstPart}/springrts/ai") - - -# Check if the user wants to compile the interface -if ("${AI_TYPES}" STREQUAL "ALL" OR "${AI_TYPES}" STREQUAL "JAVA") - set(AI_TYPES_JAVA TRUE) -else ("${AI_TYPES}" STREQUAL "ALL" OR "${AI_TYPES}" STREQUAL "JAVA") - set(AI_TYPES_JAVA FALSE) -endif ("${AI_TYPES}" STREQUAL "ALL" OR "${AI_TYPES}" STREQUAL "JAVA") - -if (AI_TYPES_JAVA AND myName MATCHES "${AI_EXCLUDE_REGEX}") - set(AI_TYPES_JAVA FALSE) -endif (AI_TYPES_JAVA AND myName MATCHES "${AI_EXCLUDE_REGEX}") - - -# Look for dependencies, but only if the user wants to build the interface -if (AI_TYPES_JAVA) - if (NOT JAVA_FOUND) - find_package(Java REQUIRED COMPONENTS Development) - endif (NOT JAVA_FOUND) - if (MINGW) - set (JNI_FOUND TRUE) - else (MINGW) - # this hack is needed for FindJNI.cmake to use the JDK we want it to use, - # as otherwise it might not find one at all (eg. in the case of OpenJDK) - if ( NOT ENV{JAVA_HOME} AND JAVA_HOME ) - set(ENV{JAVA_HOME} "${JAVA_HOME}") - endif ( NOT ENV{JAVA_HOME} AND JAVA_HOME ) - find_package(JNI REQUIRED) - if (JAVA_INCLUDE_PATH) - set (JNI_FOUND TRUE) - include_directories(${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2} ${JNI_INCLUDE_DIRS}) - else (JAVA_INCLUDE_PATH) - set (JNI_FOUND FALSE) - message(WARNING "No Java includes found!") - endif (JAVA_INCLUDE_PATH) - endif (MINGW) -endif (AI_TYPES_JAVA) - - -# Check if dependencies of the interface are met -if (AI_TYPES_JAVA AND JNI_FOUND AND JAVA_FOUND AND EXISTS ${myDir} AND EXISTS ${myDir}/bin AND AWK_FOUND AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - set_global(BUILD_${myName}_AIINTERFACE TRUE) -else (AI_TYPES_JAVA AND JNI_FOUND AND JAVA_FOUND AND EXISTS ${myDir} AND EXISTS ${myDir}/bin AND AWK_FOUND AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - set_global(BUILD_${myName}_AIINTERFACE FALSE) - message("warning: Java AI Interface will not be built!") -endif (AI_TYPES_JAVA AND JNI_FOUND AND JAVA_FOUND AND EXISTS ${myDir} AND EXISTS ${myDir}/bin AND AWK_FOUND AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - - -# Build -if (BUILD_${myName}_AIINTERFACE) - get_version_plus_dep_file(myVersion myVersionDepFile) - set(myTarget "${myName}-AIInterface") - set(myGenTarget "${myTarget}-generateSources") - set(myNativeTarget "${myTarget}-native") - set(myJavaTarget "${myTarget}-java") - set(myInstLibsDir ${AI_INTERFACES_LIBS}/${myName}/${myVersion}) - set(myInstDataDir ${AI_INTERFACES_DATA}/${myName}/${myVersion}) - set(myJavaSourceDirRel "${mySourceDirRel}/java") - set(myNativeSourceDirRel "${mySourceDirRel}/native") - make_absolute(mySourceDir "${myDir}" "${mySourceDirRel}") - make_absolute(myNativeSourceDir "${myDir}" "${myNativeSourceDirRel}") - make_absolute(myJavaSourceDir "${myDir}" "${myJavaSourceDirRel}") - - ai_interface_message(STATUS "Found AI Interface: ${myTarget} ${myVersion}") - - set_global(${myName}_AIINTERFACE_VERS ${myVersion}) - set_global(${myName}_AIINTERFACE_TARGET ${myTarget}) - set_global(${myName}_AIINTERFACE_TARGET_GENERATE_SOURCES ${myGenTarget}) - - - # Init some vars - # -------------- - set(myAwkScriptsDir "${myDir}/bin") - set(commonAwkScriptsDir "${CMAKE_SOURCE_DIR}/AI/Wrappers/CUtils/bin") - set(myBuildDir "${CMAKE_CURRENT_BINARY_DIR}") - set(springSourceDir "${PROJECT_SOURCE_DIR}") - set(springAIInterfaceSourceDir "${springSourceDir}/rts/ExternalAI/Interface") - set(myJavaBuildDir "${myBuildDir}/classes") - set(myJarFile "AIInterface") - set(myBinJarFile "${myJarFile}.jar") - set(mySrcJarFile "${myJarFile}-src.jar") - set(myGeneratedSourceDir "${myBuildDir}/src-generated/main") - set(myJavaGeneratedSourceDir "${myGeneratedSourceDir}/java") - set(myNativeGeneratedSourceDir "${myGeneratedSourceDir}/native") - set(myJLibDir "${myDir}/data/jlib") - create_classpath(myJavaLibs ${myJLibDir}) - set(myClassPath ".${PATH_DELIM_H}${myJavaLibs}${PATH_DELIM_H}${myJavaSourceDir}") - - # Used by Java Skirmish AIs - set_global(SOURCE_ROOT_${myName}_AIINTERFACE "${myDir}") - set_global(BUILD_ROOT_${myName}_AIINTERFACE "${myBuildDir}") - set_global(${myName}_AIINTERFACE_JAR_BIN "${myBuildDir}/${myBinJarFile}") - set_global(${myName}_AIINTERFACE_JAR_SRC "${myBuildDir}/${mySrcJarFile}") - set_global(${myName}_AIINTERFACE_POM "${myBuildDir}/pom-generated.xml") - set_global(CLASSPATH_${myName}_AIINTERFACE "${myJavaLibs}${PATH_DELIM_H}${myBuildDir}/${myBinJarFile}") - set_global(JAVA_SRC_DIR_${myName}_AIINTERFACE "${myJavaSourceDir}") - set_global(JAVA_GEN_SRC_DIR_${myName}_AIINTERFACE "${myJavaGeneratedSourceDir}") - - - # Generate sources - # ---------------- - - set(commonAwkScriptArgs - "-v" "SPRING_SOURCE_DIR=${springSourceDir}" - "-v" "INTERFACE_SOURCE_DIR=${myJavaSourceDir}" - "-v" "GENERATED_SOURCE_DIR=${myGeneratedSourceDir}" - "-v" "NATIVE_GENERATED_SOURCE_DIR=${myNativeGeneratedSourceDir}" - "-v" "JAVA_GENERATED_SOURCE_DIR=${myJavaGeneratedSourceDir}" - "-f" "${commonAwkScriptsDir}/common.awk" - "-f" "${commonAwkScriptsDir}/commonDoc.awk" - ) - - # A CMake Custom Target will always be built. - # from CMake docu: - # "add_custom_target is ALWAYS CONSIDERED OUT OF DATE" - - # Stub file for dependency tracking - set(myGeneratedSourceDirStubFile "${CMAKE_CURRENT_BINARY_DIR}/myGeneratedSourceDir.stub") - set_source_files_properties(${myGeneratedSourceDirStubFile} PROPERTIES GENERATED TRUE) - - - # source file lists (static and generated) - - set(myNativeSources - "${myNativeSourceDir}/InterfaceExport.c" - "${myNativeSourceDir}/JavaBridge.c" - "${myNativeSourceDir}/JniUtil.c" - "${myNativeSourceDir}/JvmLocater_common.c" - "${myNativeSourceDir}/JvmLocater_linux.c" - "${myNativeSourceDir}/JvmLocater_windows.c" - ) - set(myNativeGeneratedSources - "${myNativeGeneratedSourceDir}/CallbackFunctionPointerBridge.c" - "${myNativeGeneratedSourceDir}/CallbackJNIBridge.c" - "${myNativeGeneratedSourceDir}/EventsJNIBridge.c" - ) - set(myNativeGeneratedHeaders - "${myNativeGeneratedSourceDir}/CallbackFunctionPointerBridge.h" - "${myNativeGeneratedSourceDir}/CallbackJNIBridge.h" - "${myNativeGeneratedSourceDir}/EventsJNIBridge.h" - ) - - set(myJavaSources - "${myJavaSourceDir}/${myPkg}/Util.java" - ) - set(myJavaGeneratedSources - "${myJavaGeneratedSourceDir}/${myPkg}/AI.java" - "${myJavaGeneratedSourceDir}/${myPkg}/AbstractAI.java" - "${myJavaGeneratedSourceDir}/${myPkg}/AICallback.java" - "${myJavaGeneratedSourceDir}/${myPkg}/JniAICallback.java" - "${myJavaGeneratedSourceDir}/${myPkg}/Enumerations.java" - ) - - set(myGeneratedSources - ${myNativeGeneratedSources} - ${myNativeGeneratedHeaders} - ${myJavaGeneratedSources} - ) - set_source_files_properties(${myGeneratedSources} PROPERTIES GENERATED TRUE) - - - # remove all files in the generates sources dir, - # that are not generated sources (of this build) - file(GLOB_RECURSE allGeneratedSrcFiles "${myGeneratedSourceDir}/*") - foreach (genFile ${allGeneratedSrcFiles}) - list(FIND myGeneratedSources "${genFile}" isInList) - if (${isInList} EQUAL -1) - file(REMOVE "${genFile}") - endif () - endforeach (genFile) - - #cleanup generated dir if some input file changed - add_custom_command( - OUTPUT - ${myGeneratedSourceDirStubFile} - COMMAND "${CMAKE_COMMAND}" - "-E" "remove_directory" "${myGeneratedSourceDir}" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myNativeGeneratedSourceDir}" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myJavaGeneratedSourceDir}/${myPkg}" - COMMAND "${CMAKE_COMMAND}" - "-E" "touch" "${myGeneratedSourceDirStubFile}" - DEPENDS - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${myAwkScriptsDir}/native_wrappCallback.awk" - "${myAwkScriptsDir}/native_wrappCommands.awk" - "${myAwkScriptsDir}/jni_wrappCallback.awk" - "${myAwkScriptsDir}/jni_wrappCommands.awk" - "${myAwkScriptsDir}/jni_wrappEvents.awk" - "${springAIInterfaceSourceDir}/SSkirmishAICallback.h" - "${springAIInterfaceSourceDir}/AISCommands.h" - "${springAIInterfaceSourceDir}/AISEvents.h" - WORKING_DIRECTORY - "${myAwkScriptsDir}" - COMMENT - " ${myTarget}: Cleanup & create generated source directories" VERBATIM - ) - - # 1. & 2. Wrapp Callback (native->native) - add_custom_command( - OUTPUT - "${myNativeGeneratedSourceDir}/CallbackFunctionPointerBridge.h" - "${myNativeGeneratedSourceDir}/CallbackFunctionPointerBridge.c" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${myAwkScriptsDir}/native_wrappCallback.awk" - "${springAIInterfaceSourceDir}/SSkirmishAICallback.h" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${myAwkScriptsDir}/native_wrappCommands.awk" - "${springAIInterfaceSourceDir}/AISCommands.h" - DEPENDS - "${myGeneratedSourceDirStubFile}" - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${myAwkScriptsDir}/native_wrappCallback.awk" - "${myAwkScriptsDir}/native_wrappCommands.awk" - "${springAIInterfaceSourceDir}/SSkirmishAICallback.h" - "${springAIInterfaceSourceDir}/AISCommands.h" - WORKING_DIRECTORY - "${myAwkScriptsDir}" - COMMENT - " ${myTarget}: Generating native callback wrapper sources" VERBATIM - ) - - # 3. Wrapp AI Callback (native-JNI->Java) - add_custom_command( - OUTPUT - "${myNativeGeneratedSourceDir}/CallbackJNIBridge.h" - "${myNativeGeneratedSourceDir}/CallbackJNIBridge.c" - "${myJavaGeneratedSourceDir}/${myPkg}/AICallback.java" - "${myJavaGeneratedSourceDir}/${myPkg}/JniAICallback.java" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${myAwkScriptsDir}/jni_wrappCallback.awk" - "${myNativeGeneratedSourceDir}/CallbackFunctionPointerBridge.h" - DEPENDS - "${myGeneratedSourceDirStubFile}" - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${myAwkScriptsDir}/jni_wrappCallback.awk" - "${myNativeGeneratedSourceDir}/CallbackFunctionPointerBridge.h" - WORKING_DIRECTORY - "${myAwkScriptsDir}" - COMMENT - " ${myTarget}: Generating JNI callback wrapper sources" VERBATIM - ) - - # 4. Wrapp AI Events (native-JNI->Java) - add_custom_command( - OUTPUT - "${myNativeGeneratedSourceDir}/EventsJNIBridge.h" - "${myNativeGeneratedSourceDir}/EventsJNIBridge.c" - "${myJavaGeneratedSourceDir}/${myPkg}/AI.java" - "${myJavaGeneratedSourceDir}/${myPkg}/AbstractAI.java" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${myAwkScriptsDir}/jni_wrappEvents.awk" - "${springAIInterfaceSourceDir}/AISEvents.h" - DEPENDS - "${myGeneratedSourceDirStubFile}" - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${myAwkScriptsDir}/jni_wrappEvents.awk" - "${springAIInterfaceSourceDir}/AISEvents.h" - WORKING_DIRECTORY - "${myAwkScriptsDir}" - COMMENT - " ${myTarget}: Generating JNI events wrapper sources" VERBATIM - ) - # 5. Wrapp ENUMS - - add_custom_command( - OUTPUT - "${myJavaGeneratedSourceDir}/${myPkg}/Enumerations.java" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${myAwkScriptsDir}/jni_wrappCommands.awk" - "${springAIInterfaceSourceDir}/AISCommands.h" - DEPENDS - "${myGeneratedSourceDirStubFile}" - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${myAwkScriptsDir}/jni_wrappCommands.awk" - "${springAIInterfaceSourceDir}/AISCommands.h" - WORKING_DIRECTORY - "${myAwkScriptsDir}" - COMMENT - " ${myTarget}: Generating enums wrapper sources" VERBATIM - ) - add_custom_target(${myGenTarget} DEPENDS ${myGeneratedSources}) - add_dependencies(generateSources ${myGenTarget}) - - # Locate the manifest file - find_manifest_file("${myDir}" myManifestFile) - if (myManifestFile) - set(myBinJarArgs "cmf" "${myManifestFile}") - else (myManifestFile) - set(myBinJarArgs "cf") - endif (myManifestFile) - - # Build the native part - # --------------------- - if (MINGW) - # It is important that this is used instead of the one - # from the installed JDK, as the jni_md.h is in here too, - # and this file contains OS (win32) specific information. - include_directories(BEFORE ${MINGWLIBS}/include/java) - endif (MINGW) - include_directories(BEFORE "${rts}/lib/streflop" "${myNativeSourceDir}" "${myNativeGeneratedSourceDir}") - add_library(${myNativeTarget} MODULE ${myNativeSources} ${myNativeGeneratedSources} ${ai_common_SRC} ${myVersionDepFile}) - add_dependencies(${myNativeTarget} generateVersionFiles) - target_link_libraries(${myNativeTarget} CUtils streflop) - set_target_properties(${myNativeTarget} PROPERTIES COMPILE_FLAGS "-DUSING_STREFLOP") - set_target_properties(${myNativeTarget} PROPERTIES OUTPUT_NAME "AIInterface") - fix_lib_name(${myNativeTarget}) - - - # Build the java part - # ------------------- - - # Write list of source files to an arg-file - set(mySrcArgFile "${myBuildDir}/sourceFiles.txt") - if (EXISTS "${mySrcArgFile}") - file(REMOVE "${mySrcArgFile}") - endif (EXISTS "${mySrcArgFile}") - foreach (srcFile ${myJavaSources} ${myJavaGeneratedSources}) - file(APPEND "${mySrcArgFile}" "\"${srcFile}\"\n") - endforeach (srcFile) - - add_custom_command( - OUTPUT - "${myBuildDir}/${myBinJarFile}" - COMMAND "${CMAKE_COMMAND}" - "-E" "remove_directory" "${myJavaBuildDir}" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myJavaBuildDir}" - COMMAND "${Java_JAVAC_EXECUTABLE}" ARGS - "${JAVA_COMPILE_FLAG_CONDITIONAL}" - "-Xlint:deprecation" - "-cp" "${myClassPath}" - "-d" "${myJavaBuildDir}" - "@${mySrcArgFile}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - ${myBinJarArgs} "${myBuildDir}/${myBinJarFile}" - "-C" "${myJavaBuildDir}" "${myPkgFirstPart}" - DEPENDS - ${myJavaSources} - # Using the native target reduces parallelism slightly - # (less then 1s per build => negliable), but prevetns multiple - # execution of the source generating custom-commands - # (which results in wrongly generated source files with "make -j ") - ${myJavaGeneratedSources} - ${myNativeTarget} - WORKING_DIRECTORY - "${myJavaGeneratedSourceDir}" - COMMENT - " ${myTarget}: Compiling sources and packing library ${myBinJarFile}" VERBATIM - ) - - add_custom_command( - OUTPUT - "${myBuildDir}/${mySrcJarFile}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "cf" "${myBuildDir}/${mySrcJarFile}" - "-C" "${myJavaSourceDir}" "${myPkgFirstPart}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "uf" "${myBuildDir}/${mySrcJarFile}" - "-C" "${myJavaGeneratedSourceDir}" "${myPkgFirstPart}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "uf" "${myBuildDir}/${mySrcJarFile}" - "-C" "${mySourceDir}" "native" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "uf" "${myBuildDir}/${mySrcJarFile}" - "-C" "${myGeneratedSourceDir}" "native" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "uf" "${myBuildDir}/${mySrcJarFile}" - "-C" "${myDir}" "VERSION" - DEPENDS - ${myJavaSources} - # Using the native target reduces parallelism slightly - # (less then 1s per build => negliable), but prevetns multiple - # execution of the source generating custom-commands - # (which results in wrongly generated source files with "make -j ") - ${myJavaGeneratedSources} - ${myNativeTarget} - WORKING_DIRECTORY - "${myBuildDir}" - COMMENT - " ${myTarget}: Creating sources archive ${mySrcJarFile}" VERBATIM - ) - - add_custom_target(${myJavaTarget} - DEPENDS - "${myBuildDir}/${myBinJarFile}" - "${myBuildDir}/${mySrcJarFile}" - ) - - add_custom_target(${myTarget} ALL) - add_dependencies(${myTarget} ${myNativeTarget}) - - # this sets the version in pom.xml - set(myMavenProperties "-Dmy.version=${myVersion}") - add_custom_command( - OUTPUT - "${myBuildDir}/pom-generated.xml" - COMMAND "${CMAKE_COMMAND}" - "-Dfile.in=${myDir}/pom.xml" - "-Dfile.out=${myBuildDir}/pom-generated.xml" - ${myMavenProperties} - "-P" "${CMAKE_MODULES_SPRING}/ConfigureFile.cmake" - DEPENDS - "${myDir}/pom.xml" - WORKING_DIRECTORY - "${myDir}" - COMMENT - " ${myTarget}: Configure pom.xml" VERBATIM - ) - set_source_files_properties("${myBuildDir}/pom-generated.xml" PROPERTIES GENERATED TRUE) - - add_dependencies(${myTarget} ${myJavaTarget}) - - # Install the native library - install(TARGETS ${myNativeTarget} DESTINATION ${myInstLibsDir}) - # Install the data files - install(DIRECTORY "${myDir}/data/" DESTINATION ${myInstLibsDir} FILES_MATCHING PATTERN REGEX "InterfaceInfo\\.lua$") - install(DIRECTORY "${myDir}/data/" DESTINATION ${myInstDataDir} FILES_MATCHING PATTERN REGEX "InterfaceInfo\\.lua$" EXCLUDE PATTERN "*") - # Install the library - install(FILES "${myBuildDir}/${myBinJarFile}" DESTINATION ${myInstDataDir}) - # Install the sources archive - install(FILES "${myBuildDir}/${mySrcJarFile}" DESTINATION ${myInstDataDir}/jlib) -endif (BUILD_${myName}_AIINTERFACE) diff --git a/AI/Interfaces/Java/VERSION b/AI/Interfaces/Java/VERSION deleted file mode 100644 index ceab6e11ece..00000000000 --- a/AI/Interfaces/Java/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.1 \ No newline at end of file diff --git a/AI/Interfaces/Java/bin/ant.properties b/AI/Interfaces/Java/bin/ant.properties deleted file mode 100644 index b9c0a35d3ec..00000000000 --- a/AI/Interfaces/Java/bin/ant.properties +++ /dev/null @@ -1,21 +0,0 @@ -# Paths are relative to the project home (which is ../ from this file). -# All values are optional. - -;spring.home=../../.. - -# This is used only in the next property -;build.home=${spring.home}/build -# Where jar files will be built -;build.dir=${build.home}/AI/Interfaces/${interface.name} - -# Where generated sources shall be created in -;src.generated=${build.dir}/src-generated/main -;src.generated.native=${src.generated}/native -;src.generated.java=${src.generated}/java - -# This is used only in the next property -;dist.home=${spring.home}/dist -# Where jar files will be installed to -;dist.dir=${dist.home}/AI/Interfaces/${interface.name}/${interface.version} -# Where HTML JavaDoc files will be generated -;doc.dir=${dist.home}/AI/Interfaces/${interface.name}/${interface.version}/doc/jdoc diff --git a/AI/Interfaces/Java/bin/build.xml b/AI/Interfaces/Java/bin/build.xml deleted file mode 100644 index 86e0033068a..00000000000 --- a/AI/Interfaces/Java/bin/build.xml +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AI/Interfaces/Java/bin/jni_wrappCallback.awk b/AI/Interfaces/Java/bin/jni_wrappCallback.awk deleted file mode 100755 index 833bdb90ec3..00000000000 --- a/AI/Interfaces/Java/bin/jni_wrappCallback.awk +++ /dev/null @@ -1,573 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates a Java class with native/JNI functions, -# plus their respective native counterparts, -# to call to C functions in: -# NATIVE_GENERATED_SOURCE_DIR/CallbackFunctionPointerBridge.h -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR: the generated sources root dir -# -# usage: -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -# awk -f thisScript.awk -f common.awk -f commonDoc.awk \ -# -v 'GENERATED_SOURCE_DIR=/tmp/build/AI/Interfaces/Java/src-generated/main' -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "(,)|(\\()|(\\);)"; - - # Used by other scripts - JAVA_MODE = 1; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!JAVA_GENERATED_SOURCE_DIR) { - JAVA_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/java"; - } - if (!NATIVE_GENERATED_SOURCE_DIR) { - NATIVE_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/native"; - } - - nativeBridge = "CallbackFunctionPointerBridge"; - bridgePrefix = "bridged__"; - - jniBridge = "CallbackJNIBridge"; - - myPkgA = "com.springrts.ai"; - myPkgD = convertJavaNameFormAToD(myPkgA); - myPkgC = convertJavaNameFormAToC(myPkgA); - myInterface = "AICallback"; - myClass = "JniAICallback"; - - fi = 0; -} - -function doWrapp(funcIndex_dw) { - - paramListJava_dw = funcParamList[funcIndex_dw]; - doWrapp_dw = 1; - - fullName_dw = funcFullName[funcIndex_dw]; - if (doWrapp_dw) { - metaInf_dw = funcMetaInf[funcIndex_dw]; - - if (match(metaInf_dw, /ARRAY:/)) { - #doWrapp_dw = 0; - } - if (match(metaInf_dw, /MAP:/)) { - #doWrapp_dw = 0; - } - if (match(fullName_dw, "^" bridgePrefix "File_")) { - doWrapp_dw = 0; - } - } else { - print("Java-AIInterface: NOTE: JNI level: Callback: intentionally not wrapped: " fullName_dw); - } - - return doWrapp_dw; -} - -function createNativeFileName(fileName_fn, isHeader_fn) { - - absFileName_fn = NATIVE_GENERATED_SOURCE_DIR "/" fileName_fn; - if (isHeader_fn) { - absFileName_fn = absFileName_fn ".h"; - } else { - absFileName_fn = absFileName_fn ".c"; - } - - return absFileName_fn; -} - -function printNativeJNI() { - - outFile_nh = createNativeFileName(jniBridge, 1); - outFile_nc = createNativeFileName(jniBridge, 0); - - printCommentsHeader(outFile_nh); - printCommentsHeader(outFile_nc); - - print("") >> outFile_nh; - print("#ifndef __CALLBACK_JNI_BRIDGE_H") >> outFile_nh; - print("#define __CALLBACK_JNI_BRIDGE_H") >> outFile_nh; - print("") >> outFile_nh; - print("#include ") >> outFile_nh; - print("") >> outFile_nh; - print("#ifdef __cplusplus") >> outFile_nh; - print("extern \"C\" {") >> outFile_nh; - print("#endif") >> outFile_nh; - print("") >> outFile_nh; - - print("") >> outFile_nc; - print("#include \"" jniBridge ".h\"") >> outFile_nc; - print("") >> outFile_nc; - print("#include \"" nativeBridge ".h\"") >> outFile_nc; - print("") >> outFile_nc; - print("") >> outFile_nc; - - # print the wrapping functions - for (i=0; i < fi; i++) { - fullName = funcFullName[i]; - retType = funcRetTypeC[i]; - paramList = funcParamListC[i]; - paramListNoTypes = removeParamTypes(paramList); - metaInf = funcMetaInf[i]; - - if (doWrapp(i)) { - isRetString = part_isRetString(fullName, metaInf); - if (isRetString) { - retString = part_getRetString(metaInf); - split(retString, retStringNames, ":"); # must return 2 elements - } - - javaName = fullName; - sub("^" bridgePrefix, "", javaName); - gsub(/_/, "_1", javaName); - jni_funcName = "Java_" myPkgC "_" myClass "_" javaName; - jni_retType = convertCToJNIType(retType); - jni_paramList = ""; - size_params = split(paramList, params, ","); - for (p=1; p <= size_params; p++) { - pType_c = params[p]; - sub(/ [^ ]+$/, "", pType_c); - pType_c = trim(pType_c); - - pName = params[p]; - sub(/^.* /, "", pName); - - pType_jni = convertCToJNIType(pType_c, pName); - - # these are later used for conversion - c_paramTypes[p] = pType_c; - c_paramNames[p] = pName; - jni_paramTypes[p] = pType_jni; - jni_paramNames[p] = pName; - - if (isRetString && (pName == retStringNames[1] || pName == retStringNames[2])) { - if (pName == retStringNames[1]) - jni_retType = convertCToJNIType(pType_c); - continue; - } - jni_paramList = jni_paramList ", " pType_jni " " pName; - } - jni_paramListNoTypes = removeParamTypes(jni_paramList); - isVoidRet = match(jni_retType, /^void$/); - - # print function declaration to *.h - #printFunctionComment_Common(outFile_nh, funcDocComment, i, ""); - print("JNIEXPORT " jni_retType " JNICALL " jni_funcName "(JNIEnv* __env, jobject __obj" jni_paramList ");") >> outFile_nh; - print("") >> outFile_nh; - - # print function definition to *.c - print("JNIEXPORT " jni_retType " JNICALL " jni_funcName "(JNIEnv* __env, jobject __obj" jni_paramList ") {") >> outFile_nc; - print("") >> outFile_nc; - - if (!isVoidRet) { - print("\t" jni_retType " _ret;") >> outFile_nc; - print("") >> outFile_nc; - } - - # Return value conversion - pre call - retType_isString = ((match(retType, /^(const )?char*/) || isRetString) && (jni_retType == "jstring")); - retTypeConv = 0; - if (retType_isString) { - if (isRetString) - print("\t" "char " retStringNames[1] "[2048] = {'\\0'};") >> outFile_nc; - print("\t" retType " _retNative;") >> outFile_nc; - retTypeConv = 1; - } - - hasRetParam = 0; - # Params conversion - pre call - for (p=1; p <= size_params; p++) { - pType_jni = jni_paramTypes[p]; - - if (pType_jni == "jstring") { - # jstring - if (!isRetString || c_paramNames[p] != retStringNames[1]) { - c_paramNames[p] = c_paramNames[p] "_native"; - sub(" " jni_paramNames[p], " " c_paramNames[p], paramListNoTypes); - print("\t" c_paramTypes[p] " " c_paramNames[p] " = (" c_paramTypes[p] ") (*__env)->GetStringUTFChars(__env, " jni_paramNames[p] ", NULL);") >> outFile_nc; - } - } else if (pType_jni == "jint") { - if (isRetString && c_paramNames[p] == retStringNames[2]) - sub(" " jni_paramNames[p], " sizeof(" retStringNames[1] ")", paramListNoTypes); - } else if (match(pType_jni, /^j.+Array$/)) { - # primitive array - c_paramNames[p] = c_paramNames[p] "_native"; - sub(" " jni_paramNames[p], " " c_paramNames[p], paramListNoTypes); - - capArrType = pType_jni; - sub(/^j/, "", capArrType); - sub(/Array$/, "", capArrType); - capArrType = capitalize(capArrType); - - _isPrimitive = (capArrType != "Object"); - _isString = !_isPrimitive && match(c_paramTypes[p], /(const )?char\*\*/); - - print("\t" c_paramTypes[p] " " c_paramNames[p] " = NULL;") >> outFile_nc; - print("\t" "if (" jni_paramNames[p] " != NULL) {") >> outFile_nc; - if (_isPrimitive) { - print("\t\t" c_paramNames[p] " = (" c_paramTypes[p] ") (*__env)->Get" capArrType "ArrayElements(__env, " jni_paramNames[p] ", NULL);") >> outFile_nc; - } else if (_isString) { - print("\t\t" "const int " c_paramNames[p] "_size = (int) (*__env)->GetArrayLength(__env, " jni_paramNames[p] ");") >> outFile_nc; - print("\t\t" c_paramNames[p] " = (" c_paramTypes[p] ") malloc(sizeof(char*) * " c_paramNames[p] "_size);") >> outFile_nc; - } else { - print("ERROR: do not know how to convert parameter type: " pType_jni); - exit(1); - } - print("\t" "}") >> outFile_nc; - } else if (pType_jni == "jobject") { - # StringBuffer - hasRetParam = 1; - cPaNa = c_paramNames[p]; - c_paramNames[p] = cPaNa "_native"; - sub(" " jni_paramNames[p], " " c_paramNames[p], paramListNoTypes); - print("\t" "char " c_paramNames[p] "[MAX_RESPONSE_SIZE];") >> outFile_nc; - retParamConversion = "\t" "jclass clazz = (*__env)->GetObjectClass(__env, " cPaNa ");" "\n"; - retParamConversion = retParamConversion "\t" "jmethodID mid = (*__env)->GetMethodID(__env, clazz, \"append\", \"(Ljava/lang/String;)Ljava/lang/StringBuffer;\");" "\n" - retParamConversion = retParamConversion "\t" "jstring " cPaNa "_jStr = (*__env)->NewStringUTF(__env, " c_paramNames[p] ");" "\n"; - retParamConversion = retParamConversion "\t" "(*__env)->CallObjectMethod(__env, " cPaNa ", mid, " cPaNa "_jStr);" - } - } - - condRet = ""; - if (!isVoidRet) { - if (retTypeConv) { - condRet = "_retNative = "; - } else { - condRet = "_ret = (" jni_retType ") "; - } - } - print("\t" condRet fullName "(" paramListNoTypes ");") >> outFile_nc; - if (hasRetParam) { - print(retParamConversion) >> outFile_nc; - } - - # Params conversion - post call - for (p=1; p <= size_params; p++) { - pType_jni = jni_paramTypes[p]; - - if (pType_jni == "jstring") { - # jstring - if (!isRetString || c_paramNames[p] != retStringNames[1]) - print("\t" "(*__env)->ReleaseStringUTFChars(__env, " jni_paramNames[p] ", " c_paramNames[p] ");") >> outFile_nc; - } else if (match(pType_jni, /^j.+Array$/)) { - # primitive array - capArrType = pType_jni; - sub(/^j/, "", capArrType); - sub(/Array$/, "", capArrType); - capArrType = capitalize(capArrType); - - _isPrimitive = (capArrType != "Object"); - _isString = !_isPrimitive && match(c_paramTypes[p], /(const )?char\*\*/); - - print("\t" "if (" jni_paramNames[p] " != NULL) {") >> outFile_nc; - if (_isPrimitive) { - _elementJNativeType = jni_paramTypes[p]; - sub(/Array$/, "", _elementJNativeType); # jfloatArray -> jfloat - print("\t\t" "(*__env)->Release" capArrType "ArrayElements(__env, " jni_paramNames[p] ", (" _elementJNativeType "*) " c_paramNames[p] ", 0 /* copy back changes and release */);") >> outFile_nc; - } else if (_isString) { - print("\t\t" "const int " c_paramNames[p] "_size = (int) (*__env)->GetArrayLength(__env, " jni_paramNames[p] ");") >> outFile_nc; - print("\t\t" "int " c_paramNames[p] "_i;") >> outFile_nc; - print("\t\t" "jstring " c_paramNames[p] "_jStr;") >> outFile_nc; - print("\t\t" "for (" c_paramNames[p] "_i=0; " c_paramNames[p] "_i < " c_paramNames[p] "_size; ++" c_paramNames[p] "_i) {") >> outFile_nc; - print("\t\t\t" c_paramNames[p] "_jStr = (jstring) (*__env)->NewStringUTF(__env, " c_paramNames[p] "[" c_paramNames[p] "_i]);") >> outFile_nc; - print("\t\t\t" "(*__env)->SetObjectArrayElement(__env, " jni_paramNames[p] ", " c_paramNames[p] "_i, " c_paramNames[p] "_jStr);") >> outFile_nc; - print("\t\t\t" "(*__env)->DeleteLocalRef(__env, " c_paramNames[p] "_jStr);") >> outFile_nc; - print("\t\t" "}") >> outFile_nc; - print("\t\t" "free(" c_paramNames[p] ");") >> outFile_nc; - } - print("\t" "}") >> outFile_nc; - } else if (pType_jni == "jobject" ) { - # StringBuffer - print("\t" "(*__env)->DeleteLocalRef(__env, " cPaNa "_jStr);") >> outFile_nc; - } - } - - # Return value conversion - post call - if (retType_isString) { - print("\t" "_ret = (*__env)->NewStringUTF(__env, " (isRetString ? retStringNames[1] : "_retNative") ");") >> outFile_nc; - } - - if (!isVoidRet) { - print("") >> outFile_nc; - print("\t" "return _ret;") >> outFile_nc; - } - print("" "}") >> outFile_nc; - print("") >> outFile_nc; - } else { - print("Note: The following function is intentionally not wrapped: " fullName); - } - } - - - print("#ifdef __cplusplus") >> outFile_nh; - print("} // extern \"C\"") >> outFile_nh; - print("#endif") >> outFile_nh; - print("") >> outFile_nh; - print("#endif // __CALLBACK_JNI_BRIDGE_H") >> outFile_nh; - print("") >> outFile_nh; - - close(outFile_nh); - close(outFile_nc); -} - - -function printHeader(outFile_h, javaPkg_h, javaClassName_h) { - - printCommentsHeader(outFile_h); - print("") >> outFile_h; - print("package " javaPkg_h ";") >> outFile_h; - print("") >> outFile_h; - print("") >> outFile_h; - print("/**") >> outFile_h; - print(" * Lets Java Skirmish AIs call back to the Spring engine.") >> outFile_h; - print(" * We are using JNI for best speed.") >> outFile_h; - print(" *") >> outFile_h; - print(" * @author AWK wrapper script") >> outFile_h; - print(" * @version GENERATED") >> outFile_h; - print(" */") >> outFile_h; - if (javaClassName_h == myClass) { - print("public class " javaClassName_h " implements " myInterface " {") >> outFile_h; - } else { - print("public interface " javaClassName_h " {") >> outFile_h; - } - print("") >> outFile_h; -} - -function createJavaFileName(clsName_f) { - return JAVA_GENERATED_SOURCE_DIR "/" myPkgD "/" clsName_f ".java"; -} - -function printJavaClsAndInt() { - - outFile_i = createJavaFileName(myInterface); - outFile_c = createJavaFileName(myClass); - - printHeader(outFile_i, myPkgA, myInterface); - printHeader(outFile_c, myPkgA, myClass); - - # print the static registrator - print("\tstatic {") >> outFile_c; - print("\t\tSystem.loadLibrary(\"AIInterface\");") >> outFile_c; - print("\t}") >> outFile_c; - print("") >> outFile_c; - - # print skirmishAIId getter in interface - print("\t" "public int SkirmishAI_getSkirmishAIId();") >> outFile_i; - print("") >> outFile_i; - - # print skirmishAIId member, constructor and getter - print("\t" "private int skirmishAIId;") >> outFile_c; - print("") >> outFile_c; - print("\t" "public " myClass "(int skirmishAIId) {") >> outFile_c; - print("\t\t" "this.skirmishAIId = skirmishAIId;") >> outFile_c; - print("\t}") >> outFile_c; - print("") >> outFile_c; - print("\t" "@Override") >> outFile_c; - print("\t" "public int SkirmishAI_getSkirmishAIId() {") >> outFile_c; - print("\t\t" "return this.skirmishAIId;") >> outFile_c; - print("\t}") >> outFile_c; - print("") >> outFile_c; - - # print the callback methods - for (i=0; i < fi; i++) { - if (doWrapp(i)) { - fullName = funcFullName[i]; - retType = funcRetTypeJ[i]; - paramList = funcParamListJ[i]; - metaInf = funcMetaInf[i]; - - isRetString = part_isRetString(fullName, metaInf); - if (isRetString) { - retString = part_getRetString(metaInf); - split(retString, retStringNames, ":"); # must return 2 elements - size_params = split(paramList, params, ","); - for (p=1; p <= size_params; p++) { - pName = params[p]; - sub(/^.* /, "", pName); - if (pName == retStringNames[1]) { - ps = 1; - } else if (pName == retStringNames[2]) { - ps = 2; - } else continue; - pType_c = params[p]; - sub(/ [^ ]+$/, "", pType_c); - pType_c = trim(pType_c); - retStringTypes[ps] = convertJNIToJavaType(convertCToJNIType(pType_c, pName)); - } - retType = retStringTypes[1]; - sub(", " retStringTypes[1] " " retStringNames[1] ", " retStringTypes[2] " " retStringNames[2], "", paramList); - } - - paramListNoSID = paramList; - sub(/int _skirmishAIId(, )?/, "", paramListNoSID); - paramListNoSIDNoTypes = removeParamTypes(paramListNoSID); - if (paramListNoSIDNoTypes != "") { - paramListNoSIDNoTypes = ", " paramListNoSIDNoTypes; - } - condRet = ""; - if (retType != "void") { - condRet = "return "; - } - - sub("^" bridgePrefix, "", fullName); - - metaInfCommand = ""; - if (metaInf != "") { - metaInfCommand = " // " metaInf; - } - - # print the interface function - printFunctionComment_Common(outFile_i, funcDocComment, i, "\t"); - print("\t" "public " retType " " fullName "(" paramListNoSID ");" metaInfCommand) >> outFile_i; - print("") >> outFile_i; - - # print the interface implementing function - commentText = getFunctionComment_Common(funcDocComment, i); - if (match(commentText, /@deprecated/)) { - # this prevents javac from outputting a warning - print("\t" "/** @deprecated */") >> outFile_c; - } - print("\t" "@Override") >> outFile_c; - print("\t" "public " retType " " fullName "(" paramListNoSID ") {") >> outFile_c; - print("\t\t" condRet "this." fullName "(this.skirmishAIId" paramListNoSIDNoTypes ");") >> outFile_c; - print("\t" "}") >> outFile_c; - - # print the private native function - print("\t" "private native " retType " " fullName "(" paramList ");") >> outFile_c; - print("") >> outFile_c; - } - } - - print("}") >> outFile_i; - print("") >> outFile_i; - close(outFile_i); - - print("}") >> outFile_c; - print("") >> outFile_c; - close(outFile_c); -} - - -function wrappFunction(funcDef, commentEol) { - - doParse = 1; - - if (doParse) { - size_funcParts = split(funcDef, funcParts, "(,)|(\\()|(\\))"); - # because the empty part after ");" would count as part as well - size_funcParts--; - retType_c = trim(funcParts[2]); - retType_j = convertJNIToJavaType(convertCToJNIType(retType_c)); - fullName = trim(funcParts[3]); - - # function parameters - paramList_c = ""; - paramList_j = ""; - paramList = ""; - - for (i=4; i<=size_funcParts && !match(funcParts[i], /.*\/\/.*/); i++) { - type_c = extractParamType(funcParts[i]); - type_c = cleanupCType(type_c); - name = extractParamName(funcParts[i]); - type_j = convertJNIToJavaType(convertCToJNIType(type_c, name)); - if (i == 4) { - cond_comma = ""; - } else { - cond_comma = ", "; - } - paramList_c = paramList_c cond_comma type_c " " name; - paramList_j = paramList_j cond_comma type_j " " name; - } - - funcFullName[fi] = fullName; - funcRetTypeC[fi] = retType_c; - funcRetTypeJ[fi] = retType_j; - funcParamListC[fi] = paramList_c; - funcParamListJ[fi] = paramList_j; - funcMetaInf[fi] = trim(commentEol); - storeDocLines(funcDocComment, fi); - fi++; - } else { - print("warning: function intentionally NOT wrapped: " funcDef); - } -} - - - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return isMultiLineFunc != 1; -} - - - -# save function pointer info into arrays -# ... 2nd, 3rd, ... line of a function pointer definition -{ - if (isMultiLineFunc) { # function is defined on one single line - funcIntermLine = $0; - # separate possible comment at end of line: // fu bar - commentEol = funcIntermLine; - if (sub(/.*\/\//, "", commentEol)) { - commentEolTot = commentEolTot commentEol; - } - # remove possible comment at end of line: // fu bar - sub(/[ \t]*\/\/.*/, "", funcIntermLine); - funcIntermLine = trim(funcIntermLine); - funcSoFar = funcSoFar " " funcIntermLine; - if (match(funcSoFar, /;$/)) { - # function ends in this line - wrappFunction(funcSoFar, commentEolTot); - isMultiLineFunc = 0; - } - } -} -# 1st line of a function pointer definition -/^EXPORT\(/ { - - funcStartLine = $0; - # separate possible comment at end of line: // foo bar - commentEolTot = ""; - commentEol = funcStartLine; - if (sub(/.*\/\//, "", commentEol)) { - commentEolTot = commentEolTot commentEol; - } - # remove possible comment at end of line: // fu bar - sub(/\/\/.*$/, "", funcStartLine); - funcStartLine = trim(funcStartLine); - if (match(funcStartLine, /;$/)) { - # function ends in this line - wrappFunction(funcStartLine, commentEolTot); - } else { - funcSoFar = funcStartLine; - isMultiLineFunc = 1; - } -} - - - - -END { - # finalize things - - printNativeJNI(); - printJavaClsAndInt(); -} diff --git a/AI/Interfaces/Java/bin/jni_wrappCommands.awk b/AI/Interfaces/Java/bin/jni_wrappCommands.awk deleted file mode 100755 index abd4c0e62e1..00000000000 --- a/AI/Interfaces/Java/bin/jni_wrappCommands.awk +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates a Java class containing important enumerations. -# These enumerations are taken from: rts/ExternalAI/Interface/AISCommands.h -# It currently only takes CommandTopic and UnitCommandOptions enumerations -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR: the generated sources root dir -# -# usage: -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -# awk -f thisScript.awk -f common.awk -f commonDoc.awk \ -# -v 'GENERATED_SOURCE_DIR=/tmp/build/AI/Interfaces/Java/src-generated/main' -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "[ \t]+"; - - # Used by other scripts - JAVA_MODE = 1; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!JAVA_GENERATED_SOURCE_DIR) { - JAVA_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/java"; - } - if (!NATIVE_GENERATED_SOURCE_DIR) { - NATIVE_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/native"; - } - - myPkgA = "com.springrts.ai"; - myPkgD = convertJavaNameFormAToD(myPkgA); - myClass = "Enumerations"; - - #create empty arrays, holding names and values of the two enumerations - cmdsTopicNamesLength = 0; - split("", cmdsTopicNames); - cmdsTopicValuesLength = 0; - split("", cmdsTopicValues); - unitCmdsTopicNamesLength = 0; - split("", unitCmdsTopicNames); - unitCmdsTopicValuesLength = 0; - split("", unitCmdsTopicValues); -} - - -function createJavaFileName(fileName_fn) { - return JAVA_GENERATED_SOURCE_DIR "/" myPkgD "/" fileName_fn ".java"; -} - -function printGeneralJavaHeader(outFile_h, javaPkg_h, javaClassName_h) { - - printCommentsHeader(outFile_h); - print("") >> outFile_h; - print("package " javaPkg_h ";") >> outFile_h; - print("") >> outFile_h; - print("") >> outFile_h; - print("/**") >> outFile_h; - print(" * These are the Java exposed enumerations.") >> outFile_h; - print(" * We are not calling the engine, this is a pure Java class.") >> outFile_h; - print(" *") >> outFile_h; - print(" * @author AWK wrapper script") >> outFile_h; - print(" * @version GENERATED") >> outFile_h; - print(" */") >> outFile_h; - print("public abstract class " javaClassName_h " {") >> outFile_h; - print("") >> outFile_h; -} - -function printJavaHeader() { - - outFile_i = createJavaFileName(myClass); - - printGeneralJavaHeader(outFile_i, myPkgA, myClass); -} - -function printJavaEnums(enums) { - printJavaEnum("CommandTopic", cmdsTopicNames, cmdsTopicNamesLength, cmdsTopicValues); - print("") >> outFile_i; - printJavaEnum("UnitCommandOptions", unitCmdsTopicNames, unitCmdsTopicNamesLength, unitCmdsTopicValues); -} - -function printJavaEnum(enumName, names, namesLength, values) { - outFile_i = createJavaFileName(myClass); - printEnumHeader(enumName); - - # Prints the enum members and values - first = 0; - for (i=0; i> outFile_i; - } else { - printf(",\n\t\t") >> outFile_i; - } - printJavaEnumItem(names[i], values[i]); - } - - if (first != 0) { - print(";\n") >> outFile_i; - } - printEnumEnd(enumName); -} - -function printEnumHeader(name) { - outFile_i = createJavaFileName(myClass); - - # Prints the enum start - print("\tpublic enum " name " {") >> outFile_i; -} - -function printEnumEnd(name) { - outFile_i = createJavaFileName(myClass); - - # Prints the enum end - print("\t\tprivate final int id;") >> outFile_i; - print("\t\t" name "(int id) { this.id = id; }") >> outFile_i; - print("\t\tpublic int getValue() { return id; }") >> outFile_i; - print("\t}") >> outFile_i; -} - -function printJavaEnumItem(key, value) { - printf(key "(" value ")") >> outFile_i; -} - -function printJavaEnd() { - - outFile_i = createJavaFileName(myClass); - - print("}") >> outFile_i; - print("") >> outFile_i; - - close(outFile_i); -} - -/^[ \t]*COMMAND_.*$/ { - - doWrapp = !match(($0), /.*COMMAND_NULL.*/); - if (doWrapp) { - #parse enumeration of format x = number1, - sub(",", "", $4); - cmdsTopicNames[cmdsTopicNamesLength] = $2; - cmdsTopicNamesLength++; - cmdsTopicValues[cmdsTopicValuesLength] = $4; - cmdsTopicValuesLength++; - } else { - print("Java-AIInterface: NOTE: JNI level: COMMANDS: intentionally not wrapped: " $2); - } -} - -/^[ \t]*UNIT_COMMAND_.*$/ { - doWrapp = !match(($0), /.*COMMAND_NULL.*/); - if (doWrapp) { - unitCmdsTopicNames[unitCmdsTopicNamesLength] = $2; - unitCmdsTopicNamesLength++; - #parse enumeration of format x = (number1 << number2), - sub("[ \t]*//.*", "", $0); - sub(",", "", $0); - sub($3, "", $0); - sub($2, "", $0); - sub("[ \t]*", "", $0); - unitCmdsTopicValues[unitCmdsTopicValuesLength] = $0; - unitCmdsTopicValuesLength++; - } else { - print("Java-AIInterface: NOTE: JNI level: UNIT_COMMANDS: intentionally not wrapped: " $2); - } -} - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return isInsideEvtStruct != 1; -} - -END { - # finalize things - printJavaHeader(); - printJavaEnums(); - printJavaEnd(); -} diff --git a/AI/Interfaces/Java/bin/jni_wrappEvents.awk b/AI/Interfaces/Java/bin/jni_wrappEvents.awk deleted file mode 100755 index a1907084b30..00000000000 --- a/AI/Interfaces/Java/bin/jni_wrappEvents.awk +++ /dev/null @@ -1,570 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates a Java class with one function per event, -# plus a C wrapper to easily/comfortably call these functions from C. -# input is taken from file: -# rts/ExternalAI/Interface/AISEvents.h -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR: the generated sources root dir -# -# usage: -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -# awk -f thisScript.awk -f common.awk -f commonDoc.awk \ -# -v 'GENERATED_SOURCE_DIR=/tmp/build/AI/Interfaces/Java/src-generated/main' -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "[ \t]+"; - - # Used by other scripts - JAVA_MODE = 1; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!JAVA_GENERATED_SOURCE_DIR) { - JAVA_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/java"; - } - if (!NATIVE_GENERATED_SOURCE_DIR) { - NATIVE_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/native"; - } - - myWrapperName = "EventsJNIBridge"; - myWrapperPrefix = "eventsJniBridge_"; - - myPkgA = "com.springrts.ai"; - myPkgD = convertJavaNameFormAToD(myPkgA); - myAIClass = "AI"; - myAIAbstractClass = "AbstractAI"; - myAICallbackInt = "AICallback"; - - ind_evtTopics = 0; - ind_evtStructs = 0; - isInsideEvtStruct = 0; -} - - - -# Checks if a field is available and is no comment -function isFieldUsable(f) { - - valid = 0; - - if (f && !match(f, /.*\/\/.*/)) { - valid = 1; - } - - return valid; -} - -function createNativeFileName(fileName_fn, isHeader_fn) { - - absFileName_fn = NATIVE_GENERATED_SOURCE_DIR "/" fileName_fn; - if (isHeader_fn) { - absFileName_fn = absFileName_fn ".h"; - } else { - absFileName_fn = absFileName_fn ".c"; - } - - return absFileName_fn; -} -function createJavaFileName(fileName_fn) { - return JAVA_GENERATED_SOURCE_DIR "/" myPkgD "/" fileName_fn ".java"; -} - - -function printNativeHeader() { - - outFile_nh = createNativeFileName(myWrapperName, 1); - outFile_nc = createNativeFileName(myWrapperName, 0); - printCommentsHeader(outFile_nh); - printCommentsHeader(outFile_nc); - - # print includes (header) - print("") >> outFile_nh; - print("#ifndef __EVENTS_JNI_BRIDGE_H") >> outFile_nh; - print("#define __EVENTS_JNI_BRIDGE_H") >> outFile_nh; - print("") >> outFile_nh; - print("#include ") >> outFile_nh; - print("") >> outFile_nh; - print("#ifdef __cplusplus") >> outFile_nh; - print("extern \"C\" {") >> outFile_nh; - print("#endif") >> outFile_nh; - print("") >> outFile_nh; - - # print includes (source) - print("") >> outFile_nc; - print("#include \"" myWrapperName ".h\"") >> outFile_nc; - print("") >> outFile_nc; - print("#include \"JavaBridge.h\" // for INT_AI") >> outFile_nc; - print("#include \"JniUtil.h\"") >> outFile_nc; - print("#include \"ExternalAI/Interface/AISEvents.h\"") >> outFile_nc; - print("#include // for calloc(), free()") >> outFile_nc; - print("") >> outFile_nc; - print("") >> outFile_nc; - - # print global vars (source) - print("size_t skirmishAIId_size = 0;") >> outFile_nc; - print("jobject* skirmishAIId_callback = NULL;") >> outFile_nc; - print("") >> outFile_nc; -} - -function printNativeEventMethodVars() { - - for (e=0; e < ind_evtStructs; e++) { - printNativeEventMethodVar(e); - } - print("") >> outFile_nc; -} -function printNativeEventMethodVar(evtIndex) { - - outFile_nc = createNativeFileName(myWrapperName, 0); - - eName = evtsName[evtIndex]; - eNameLowerized = lowerize(eName); - - print("jmethodID m_ai_" eNameLowerized " = NULL;") >> outFile_nc; -} - -function printNativeStaticInitFuncHead() { - - # ... header - print("/**") >> outFile_nh; - print(" * Initialized stuff needed for sending events to an AI library instance.") >> outFile_nh; - print(" *") >> outFile_nh; - print(" * @author hoijui") >> outFile_nh; - print(" * @version GENERATED") >> outFile_nh; - print(" */") >> outFile_nh; - print("int " myWrapperPrefix "initStatic(JNIEnv* env, size_t skirmishAIId_size);") >> outFile_nh; - print("") >> outFile_nh; - # ... source - print("int " myWrapperPrefix "initStatic(JNIEnv* env, size_t _skirmishAIId_size) {") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "skirmishAIId_size = _skirmishAIId_size;") >> outFile_nc; - print("\t" "skirmishAIId_callback = (jobject*) calloc(skirmishAIId_size, sizeof(jobject));") >> outFile_nc; - print("\t" "size_t t;") >> outFile_nc; - print("\t" "for (t=0; t < skirmishAIId_size; ++t) {") >> outFile_nc; - print("\t\t" "skirmishAIId_callback[t] = NULL;") >> outFile_nc; - print("\t" "}") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "jobject c_aiInt = (*env)->FindClass(env, \"" myPkgD "/" myAIClass "\");") >> outFile_nc; - print("\t" "if (jniUtil_checkException(env, \"Failed fetching AI interface class " myPkgA "." myAIClass "\")) { return -2; }") >> outFile_nc; - print("") >> outFile_nc; -} - -function printNativeEventStaticInits() { - - for (e=0; e < ind_evtStructs; e++) { - printNativeEventStaticInit(e); - } - print("") >> outFile_nc; -} -function printNativeEventStaticInit(evtIndex) { - - outFile_nc = createNativeFileName(myWrapperName, 0); - - eName = evtsName[evtIndex]; - eNameLowerized = lowerize(eName); - eSignature = "("; - for (m=0; m < evtsNumMembers[evtIndex]; m++) { - type_c = evtsMembers_type_c[evtIndex, m]; - type_jni = convertCToJNIType(type_c); - type_sig = convertJNIToSignatureType(type_jni); - eSignature = eSignature type_sig; - } - eSignature = eSignature ")I"; - if (eNameLowerized == "init") { - eSignature = "(IL" myPkgD "/" myAICallbackInt ";)I"; - } - - print("\t" "m_ai_" eNameLowerized " = jniUtil_getMethodID(env, c_aiInt, \"" eNameLowerized "\", \"" eSignature "\");") >> outFile_nc; - print("\t" "if (jniUtil_checkException(env, \"Failed fetching Java AI method ID for: " eNameLowerized "\")) { return -3; }") >> outFile_nc; - print("") >> outFile_nc; -} - -function printNativeInitFunc() { - - print("\t" "return 0; // -> no error") >> outFile_nc; - print("}") >> outFile_nc; - print("") >> outFile_nc; - - # ... header - print("/**") >> outFile_nh; - print(" * Initialized stuff needed for an AI instance.") >> outFile_nh; - print(" *") >> outFile_nh; - print(" * @author hoijui") >> outFile_nh; - print(" * @version GENERATED") >> outFile_nh; - print(" */") >> outFile_nh; - print("int " myWrapperPrefix "initAI(JNIEnv* env, int skirmishAIId, jobject callback);") >> outFile_nh; - print("") >> outFile_nh; - # ... source - print("int " myWrapperPrefix "initAI(JNIEnv* env, int skirmishAIId, jobject callback) {") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "int res = -1;") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "skirmishAIId_callback[skirmishAIId] = callback;") >> outFile_nc; - print("\t" "res = 0;") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "return res;") >> outFile_nc; - print("}") >> outFile_nc; - print("") >> outFile_nc; -} - -function printNativeHandleFuncHead() { - - # ... header - print("/**") >> outFile_nh; - print(" * For documentation, see SSkirmishAILibrary::handleEvent() in:") >> outFile_nh; - print(" * ExternalAI/Interface/SSkirmishAILibrary.h") >> outFile_nh; - print(" *") >> outFile_nh; - print(" * @author hoijui") >> outFile_nh; - print(" * @version GENERATED") >> outFile_nh; - print(" */") >> outFile_nh; - print("int " myWrapperPrefix "handleEvent(JNIEnv* env, jobject aiInstance, int skirmishAIId, int topic, const void* data);") >> outFile_nh; - print("") >> outFile_nh; - # ... source - print("int " myWrapperPrefix "handleEvent(JNIEnv* env, jobject aiInstance, int skirmishAIId, int topic, const void* data) {") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "int _ret = -1;") >> outFile_nc; - print("") >> outFile_nc; -# print("\t" "jobject o_ai = skirmishAIId_aiObject[skirmishAIId];") >> outFile_nc; -# print("\t" "//assert(o_ai != NULL);") >> outFile_nc; -# print("") >> outFile_nc; - - # only add this for debugging purposes -# print("\t" "// in case we missed handling an exception elsewhere") >> outFile_nc; -# print("\t" "// and it is therefore still pending, we handle it here") >> outFile_nc; -# print("\t" "if ((*env)->ExceptionCheck(env)) {") >> outFile_nc; -# print("\t\t" "(*env)->ExceptionDescribe(env);") >> outFile_nc; -# print("\t\t" "_ret = -6;") >> outFile_nc; -# print("\t\t" "return _ret;") >> outFile_nc; -# print("\t" "}") >> outFile_nc; -# print("") >> outFile_nc; - - print("\t" "switch (topic) {") >> outFile_nc; -} - - -function printNativeEventCases() { - - for (e=0; e < ind_evtStructs; e++) { - printNativeEventCase(e); - } -} -function printNativeEventCase(evtIndex) { - - outFile_nc = createNativeFileName(myWrapperName, 0); - - topicName = evtsTopicName[evtIndex]; - topicValue = evtsTopicNameValue[topicName]; - eName = evtsName[evtIndex]; - eNameLowerized = lowerize(eName); - eStruct = "S" eName "Event"; - - print("\t\t" "case " topicName ": {") >> outFile_nc; - print("\t\t\t" "const struct " eStruct "* evt = (const struct "eStruct"*) data;") >> outFile_nc; - - paramsEvt = ""; - conversion_pre = ""; - for (m=0; m < evtsNumMembers[evtIndex]; m++) { - type_c = evtsMembers_type_c[evtIndex, m]; - name_c = evtsMembers_name[evtIndex, m]; - value_c = "evt->" name_c; - name_jni = value_c; - - type_jni = convertCToJNIType(type_c); - if (type_jni == "jstring") { - name_jni = name_c "_jni"; - conversion_pre = conversion_pre "\n\t\t\t" type_jni " " name_jni " = (*env)->NewStringUTF(env, " value_c ");"; - } else if (type_jni == "jfloatArray") { - name_jni = name_c "_jni"; - - array_size = "sizeof(" value_c ")"; - if (match(name_c, /_posF3$/)) { - array_size = "3"; - } - - conversion_pre = conversion_pre "\n\t\t\t" type_jni " " name_jni " = (*env)->NewFloatArray(env, " array_size ");"; - conversion_pre = conversion_pre "\n\t\t\t" "(*env)->SetFloatArrayRegion(env, " name_jni ", 0, " array_size ", " value_c ");"; - } else if (type_jni == "jintArray") { - name_jni = name_c "_jni"; - - array_size = "sizeof(" value_c ")"; - - conversion_pre = conversion_pre "\n\t\t\t" type_jni " " name_jni " = (*env)->NewIntArray(env, " array_size ");"; - conversion_pre = conversion_pre "\n\t\t\t" "(*env)->SetIntArrayRegion(env, " name_jni ", 0, " array_size ", " value_c ");"; - } - - paramsEvt = paramsEvt ", " name_jni; - } - sub(/^, /, "", paramsEvt); - if (eNameLowerized == "init") { - sub(/evt->callback/, "skirmishAIId_callback[evt->skirmishAIId]", paramsEvt); - } - - print(conversion_pre) >> outFile_nc; - print("\t\t\t" "_ret = (*env)->CallIntMethod(env, aiInstance, m_ai_" eNameLowerized ", " paramsEvt ");") >> outFile_nc; - - print("\t\t\t" "break;") >> outFile_nc; - print("\t\t" "}") >> outFile_nc; -} - -function printNativeEnd() { - - outFile_nh = createNativeFileName(myWrapperName, 1); - outFile_nc = createNativeFileName(myWrapperName, 0); - - print("#ifdef __cplusplus") >> outFile_nh; - print("} // extern \"C\"") >> outFile_nh; - print("#endif") >> outFile_nh; - print("") >> outFile_nh; - print("#endif // __EVENTS_JNI_BRIDGE_H") >> outFile_nh; - print("") >> outFile_nh; - - print("\t\t" "default: {") >> outFile_nc; - print("\t\t\t" "_ret = -4;") >> outFile_nc; - print("\t\t\t" "break;") >> outFile_nc; - print("\t\t" "}") >> outFile_nc; - print("\t" "}") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "if ((*env)->ExceptionCheck(env)) {") >> outFile_nc; - print("\t\t" "(*env)->ExceptionDescribe(env);") >> outFile_nc; - print("\t\t" "_ret = -5;") >> outFile_nc; - print("\t" "}") >> outFile_nc; - print("") >> outFile_nc; - print("\t" "return _ret;") >> outFile_nc; - print("}") >> outFile_nc; - - close(outFile_nh); - close(outFile_nc); -} - - -function printGeneralJavaHeader(outFile_h, javaPkg_h, javaClassName_h) { - - printCommentsHeader(outFile_h); - print("") >> outFile_h; - print("package " javaPkg_h ";") >> outFile_h; - print("") >> outFile_h; - print("") >> outFile_h; - print("/**") >> outFile_h; - print(" * This is the Java entry point from events coming from the engine.") >> outFile_h; - print(" * We are using JNI for best in speed.") >> outFile_h; - print(" *") >> outFile_h; - print(" * @author AWK wrapper script") >> outFile_h; - print(" * @version GENERATED") >> outFile_h; - print(" */") >> outFile_h; - if (javaClassName_h == myAIAbstractClass) { - print("public abstract class " javaClassName_h " implements " myAIClass " {") >> outFile_h; - } else { - print("public interface " javaClassName_h " {") >> outFile_h; - } - print("") >> outFile_h; -} - -function printJavaHeader() { - - outFile_i = createJavaFileName(myAIClass); - outFile_a = createJavaFileName(myAIAbstractClass); - - printGeneralJavaHeader(outFile_i, myPkgA, myAIClass); - printGeneralJavaHeader(outFile_a, myPkgA, myAIAbstractClass); -} - -function printJavaEvents() { - - for (e=0; e < ind_evtStructs; e++) { - printJavaEvent(e); - } -} -function printJavaEvent(evtIndex) { - - outFile_i = createJavaFileName(myAIClass); - outFile_a = createJavaFileName(myAIAbstractClass); - - topicName = evtsTopicName[evtIndex]; - topicValue = evtsTopicNameValue[topicName]; - eName = evtsName[evtIndex]; - eMetaComment = evtsMetaComment[evtIndex]; - eNameLowerized = lowerize(eName); - eCls = eName "AIEvent"; - - # Add the member comments to the main comment as @param attributes - numEvtDocLines = evtsDocComment[evtIndex, "*"]; - for (m=firstMember; m < evtsNumMembers[evtIndex]; m++) { - numLines = evtMbrsDocComments[evtIndex*1000 + m, "*"]; - if (numLines > 0) { - evtsDocComment[evtIndex, numEvtDocLines] = "@param " evtsMembers_name[evtIndex, m]; - } - for (l=0; l < numLines; l++) { - if (l == 0) { - _preDocLine = "@param " evtsMembers_name[evtIndex, m] " "; - } else { - _preDocLine = " " lengtAsSpaces(evtsMembers_name[evtIndex, m]) " "; - } - evtsDocComment[evtIndex, numEvtDocLines] = _preDocLine evtMbrsDocComments[evtIndex*1000 + m, l]; - numEvtDocLines++; - } - } - evtsDocComment[evtIndex, "*"] = numEvtDocLines; - - paramsTypes = ""; - for (m=0; m < evtsNumMembers[evtIndex]; m++) { - name_c = evtsMembers_name[evtIndex, m]; - type_c = evtsMembers_type_c[evtIndex, m]; - type_java = convertJNIToJavaType(convertCToJNIType(type_c)); - - paramsTypes = paramsTypes ", " type_java " " name_c; - } - sub(/^, /, "", paramsTypes); - if (eNameLowerized == "init") { - paramsTypes = "int skirmishAIId, AICallback callback"; - } - - _condMetaComments = eMetaComment; - if (_condMetaComments != "") { - _condMetaComments = " // " _condMetaComments; - } - - print("") >> outFile_i; - printFunctionComment_Common(outFile_i, evtsDocComment, evtIndex, "\t"); - print("\t" "public int " eNameLowerized "(" paramsTypes ");" _condMetaComments) >> outFile_i; - - print("") >> outFile_a; - print("\t" "@Override") >> outFile_a; - print("\t" "public int " eNameLowerized "(" paramsTypes ") {") >> outFile_a; - print("") >> outFile_a; - print("\t\t" "// signal: event handled OK") >> outFile_a; - print("\t\t" "return 0;") >> outFile_a; - print("\t" "}") >> outFile_a; -} - -function printJavaEnd() { - - outFile_i = createJavaFileName(myAIClass); - outFile_a = createJavaFileName(myAIAbstractClass); - - print("}") >> outFile_i; - print("") >> outFile_i; - - print("}") >> outFile_a; - print("") >> outFile_a; - - close(outFile_i); - close(outFile_a); -} - - -function saveMember(ind_mem_s, member_s) { - - name_s = extractParamName(member_s); - type_c_s = extractCType(member_s); - - evtsMembers_name[ind_evtStructs, ind_mem_s] = name_s; - evtsMembers_type_c[ind_evtStructs, ind_mem_s] = type_c_s; -} - - -# aggare te los event defines in order -/^[ \t]*EVENT_.*$/ { - - doWrapp = !match(($0), /.*EVENT_NULL.*/) && !match(($0), /.*EVENT_TO_ID_ENGINE.*/); - if (doWrapp) { - sub(",", "", $4); - evtsTopicNameValue[$2] = $4; - } else { - print("Java-AIInterface: NOTE: JNI level: Events: intentionally not wrapped: " $2); - } -} - - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return isInsideEvtStruct != 1; -} - -################################################################################ -### BEGIN: parsing and saving the event structs - -# end of struct S*Event -/^}; \/\/\$ EVENT_/ { - - evtsNumMembers[ind_evtStructs] = ind_evtMember; - evtsTopicName[ind_evtStructs] = $3; - _metaComment = $0; - sub("^.*" evtsTopicName[ind_evtStructs], "", _metaComment); - evtsMetaComment[ind_evtStructs] = trim(_metaComment); - - ind_evtStructs++; - isInsideEvtStruct = 0; -} - - -# inside of struct S*Event -{ - if (isInsideEvtStruct == 1) { - size_tmpMembers = split($0, tmpMembers, ";"); - # cause there is an empty part behind the ';' - size_tmpMembers--; - for (i=1; i<=size_tmpMembers; i++) { - tmpMembers[i] = trim(tmpMembers[i]); - if (tmpMembers[i] == "" || match(tmpMembers[i], /^\/\//)) { - break; - } - # This would bork with more then 1000 members in an event, - # or more then 1000 events - storeDocLines(evtMbrsDocComments, ind_evtStructs*1000 + ind_evtMember); - saveMember(ind_evtMember, tmpMembers[i]); - ind_evtMember++; - } - } -} - -# beginning of struct S*Event -/^struct S.*Event( \{)?/ { - - isInsideEvtStruct = 1; - ind_evtMember = 0; - eventName = $2; - sub(/^S/, "", eventName); - sub(/Event$/, "", eventName); - - evtsName[ind_evtStructs] = eventName; - storeDocLines(evtsDocComment, ind_evtStructs); -} - -### END: parsing and saving the event structs -################################################################################ - - - - -END { - # finalize things - printNativeHeader(); - printNativeEventMethodVars(); - printNativeStaticInitFuncHead(); - printNativeEventStaticInits(); - printNativeInitFunc(); - printNativeHandleFuncHead(); - printNativeEventCases(); - printNativeEnd(); - - printJavaHeader(); - printJavaEvents(); - printJavaEnd(); -} diff --git a/AI/Interfaces/Java/bin/native_createCallbackFPInitializations.awk b/AI/Interfaces/Java/bin/native_createCallbackFPInitializations.awk deleted file mode 100755 index c6aed9bdeef..00000000000 --- a/AI/Interfaces/Java/bin/native_createCallbackFPInitializations.awk +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates the function pointer initializations -# for the C callbacks; eg: -# rts/ExternalAI/Interface/SSkirmishAICallback.h -# rts/ExternalAI/Interface/SAIInterfaceCallback.h -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - #FS="[ \t]+" -} - - -# Some utility functions - -function ltrim(s) { sub(/^[ \t]+/, "", s); return s; } -function rtrim(s) { sub(/[ \t]+$/, "", s); return s; } -function trim(s) { return rtrim(ltrim(s)); } - - -function printInit(functionPointerName) { - - functionName = functionPointerName; - sub(/Clb_/, "skirmishAiCallback_", functionName); - - print(" callback->" functionPointerName " = &" functionName ";") -} - - -/^.*CALLING_CONV.*$/ { - - line = trim($0); - doWrapp = !match(line, /^[ \t]*\/\/.*/); - if (doWrapp) { - numParts = split(line, parts, /\(CALLING_CONV \*/); - if (numParts == 2) { - numParts2 = split(parts[2], parts2, /\)\(/); - if (numParts2 == 2) { - fn = parts2[1]; - printInit(fn); - } - } - } -} - - - -END { - # finalize things -} diff --git a/AI/Interfaces/Java/bin/native_createCallbackFunctionImpls.awk b/AI/Interfaces/Java/bin/native_createCallbackFunctionImpls.awk deleted file mode 100755 index c9a789ab005..00000000000 --- a/AI/Interfaces/Java/bin/native_createCallbackFunctionImpls.awk +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates function impls that can be used in the C callbacks -# with some little adjustments; eg: -# rts/ExternalAI/SSkirmishAICallbackImpl.cpp -# rts/ExternalAI/SAIInterfaceCallbackImpl.cpp -# -# Accepts input like this: -# [code] -# bool requireSonarUnderWater; -# -# // construction related fields -# /// Should constructions without builders decay? -# bool constructionDecay; -# [/code] -# -# use like this: -# awk -f yourScript.awk -f common.awk -f commonDoc.awk [additional-params] -# this should work with all flavours of AWK (eg. gawk, mawk, nawk, ...) -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - #FS="[ \t]+" - - # 0 -> print impl - # 1 -> print impl header - # 2 -> print interface header - printingHeader = 1; -} - -function getCType(gct_type) { - - if (match(gct_type, /string/)) { - return "const char* const"; - } else { - return gct_type; - } -} -function getToCTypeConv(gtctc_type) { - - if (match(gtctc_type, /string/)) { - return ".c_str()"; - } else { - return ""; - } -} -function getFuncPrefix(gfp_type) { - - #if (match(gfp_type, /bool/)) { - # return "is"; - #} else { - return "get"; - #} -} - -function printFunc(pf_fieldName, pf_type, pf_header) { - - pf_cType = getCType(pf_type); - pf_toCTypeConv = getToCTypeConv(pf_type); - pf_funcPrefix = getFuncPrefix(pf_type); - - if (pf_header == 2 && hasStoredDoc()) { - printStoredDoc(""); - } - - if (pf_header != 0) { - pf_firstLineEnd = ";"; - pf_sizeToFill = length("const char* const") - length(pf_cType); - if (pf_sizeToFill < 0) { - pf_sizeToFill = 0; - } - pf_filler = ""; - for (pf_i = 0; pf_i < pf_sizeToFill; pf_i++) { - pf_filler = pf_filler " "; - } - } else { - pf_firstLineEnd = " {"; - pf_filler = ""; - } - - if (pf_header == 2) { - print(pf_cType pf_filler " (CALLING_CONV *PreFixName_" pf_funcPrefix capitalize(pf_fieldName) ")(int teamId)" pf_firstLineEnd); - } else { - print("EXPORT(" pf_cType pf_filler ") PreFixName_" pf_funcPrefix capitalize(pf_fieldName) "(int teamId)" pf_firstLineEnd); - } - if (!pf_header) { - print("\t" "return modInfo->" pf_fieldName pf_toCTypeConv ";"); - print("}"); - } -} - -# needed by commonDoc.awk -function canDeleteDocumentation() { - return 1; -} - - -{ - line = trim($0); - - if (line == "") { - print(line); - } else if (!isInsideDoc()) { - sub(/\;$/, "", line); - - name = line; - sub(/^.*[ \t]/, "", name); - - cppType = line; - sub(name, "", cppType); - cppType = rtrim(cppType); - - printFunc(name, cppType, printingHeader); - } -} - - - -END { - # finalize things -} diff --git a/AI/Interfaces/Java/bin/native_wrappCallback.awk b/AI/Interfaces/Java/bin/native_wrappCallback.awk deleted file mode 100755 index b920c196a6e..00000000000 --- a/AI/Interfaces/Java/bin/native_wrappCallback.awk +++ /dev/null @@ -1,290 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates C functions which call C function pointers in: -# rts/ExternalAI/Interface/SSkirmishAICallback.h -# -# Right after running this script, you have to wrap the native command structs -# into functions. -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR the root generated sources dir -# default: "../src-generated/main" -# * NATIVE_GENERATED_SOURCE_DIR the native generated sources dir -# default: GENERATED_SOURCE_DIR + "/native" -# -# usage: -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -# awk -f thisScript.awk -f common.awk -f commonDoc.awk \ -# -v 'NATIVE_GENERATED_SOURCE_DIR=/tmp/build/AI/Interfaces/Java/src-generated/main/native' -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "(,)|(\\()|(\\);)"; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!NATIVE_GENERATED_SOURCE_DIR) { - NATIVE_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/native"; - } - - nativeBridge = "CallbackFunctionPointerBridge"; - bridgePrefix = "bridged__"; - - fi = 0; -} - -function doWrapp(funcIndex_dw) { - - paramListC_dw = funcParamListC[funcIndex_dw]; - doWrapp_dw = 1; - - fullName_dw = funcFullName[funcIndex_dw]; - if (doWrapp_dw) { - metaInf_dw = funcMetaInf[funcIndex_dw]; - - if (match(metaInf_dw, /ARRAY:/)) { - #doWrapp_dw = 0; - } - if (match(metaInf_dw, /MAP:/)) { - #doWrapp_dw = 0; - } - if (match(fullName_dw, "^" bridgePrefix "File_")) { - doWrapp_dw = 0; - } - if (fullName_dw == "Engine_handleCommand") { - doWrapp_dw = 0; - } - # not wrapped, legacy C++ only - if (fullName_dw == "Engine_executeCommand") { - doWrapp_dw = 0; - } - } else { - print("Java-AIInterface: NOTE: native level: Callback: intentionally not wrapped: " fullName_dw); - } - - return doWrapp_dw; -} - -function createNativeFileName(fileName_fn, isHeader_fn) { - - absFileName_fn = NATIVE_GENERATED_SOURCE_DIR "/" fileName_fn; - if (isHeader_fn) { - absFileName_fn = absFileName_fn ".h"; - } else { - absFileName_fn = absFileName_fn ".c"; - } - - return absFileName_fn; -} - -function printNativeFP2F() { - - outFile_nh = createNativeFileName(nativeBridge, 1); - outFile_nc = createNativeFileName(nativeBridge, 0); - - printCommentsHeader(outFile_nh); - printCommentsHeader(outFile_nc); - - print("") >> outFile_nh; - print("#ifndef __CALLBACK_FUNCTION_POINTER_BRIDGE_H") >> outFile_nh; - print("#define __CALLBACK_FUNCTION_POINTER_BRIDGE_H") >> outFile_nh; - print("") >> outFile_nh; - print("#include \"ExternalAI/Interface/aidefines.h\"") >> outFile_nh; - print("") >> outFile_nh; - print("#include // size_t") >> outFile_nh; - print("#include // bool, true, false") >> outFile_nh; - print("") >> outFile_nh; - print("struct SSkirmishAICallback;") >> outFile_nh; - print("") >> outFile_nh; - print("#ifdef __cplusplus") >> outFile_nh; - print("extern \"C\" {") >> outFile_nh; - print("#endif") >> outFile_nh; - print("") >> outFile_nh; - print("void funcPntBrdg_addCallback(const size_t skirmishAIId, const struct SSkirmishAICallback* clb);") >> outFile_nh; - print("void funcPntBrdg_removeCallback(const size_t skirmishAIId);") >> outFile_nh; - print("") >> outFile_nh; - - print("") >> outFile_nc; - print("#include \"" nativeBridge ".h\"") >> outFile_nc; - print("") >> outFile_nc; - print("#include \"ExternalAI/Interface/SSkirmishAICallback.h\"") >> outFile_nc; - print("#include \"ExternalAI/Interface/AISCommands.h\"") >> outFile_nc; - print("") >> outFile_nc; - print("") >> outFile_nc; - print("#define id_clb_sizeMax 8192") >> outFile_nc; - print("static const struct SSkirmishAICallback* id_clb[id_clb_sizeMax];") >> outFile_nc; - print("") >> outFile_nc; - print("void funcPntBrdg_addCallback(const size_t skirmishAIId, const struct SSkirmishAICallback* clb) {") >> outFile_nc; - print(" //assert(skirmishAIId < id_clb_sizeMax);") >> outFile_nc; - print(" id_clb[skirmishAIId] = clb;") >> outFile_nc; - print("}") >> outFile_nc; - print("void funcPntBrdg_removeCallback(const size_t skirmishAIId) {") >> outFile_nc; - print(" //assert(skirmishAIId < id_clb_sizeMax);") >> outFile_nc; - print(" id_clb[skirmishAIId] = NULL;") >> outFile_nc; - print("}") >> outFile_nc; - print("") >> outFile_nc; - - # print the wrapping functions - for (i=0; i < fi; i++) { - fullName = funcFullName[i]; - retType = funcRetTypeC[i]; - paramList = funcParamListC[i]; - sub(/int skirmishAIId/, "int _skirmishAIId", paramList); - paramListNoTypes = removeParamTypes(paramList); - commentEol = funcCommentEol[i]; - - if (doWrapp(i)) { - # print function declaration to *.h - printFunctionComment_Common(outFile_nh, funcDocComment, i, ""); - - outName = bridgePrefix fullName; - - if (commentEol != "") { - commentEol = " // " commentEol; - } - print("EXPORT(" retType ") " outName "(" paramList ");" commentEol) >> outFile_nh; - print("") >> outFile_nh; - - # print function definition to *.c - print("EXPORT(" retType ") " outName "(" paramList ") {") >> outFile_nc; - - print(preConversion) >> outFile_nc; - if (hasRetParam) { - print("\t" retParamType " " retNameTmp " = id_clb[_skirmishAIId]->" fullName "(" paramListNoTypes ");") >> outFile_nc; - print(retParamConversion) >> outFile_nc; - } else { - condRet = "return "; - if (retType == "void") { - condRet = ""; - } - print("\t" condRet "id_clb[_skirmishAIId]->" fullName "(" paramListNoTypes ");") >> outFile_nc; - } - print("" "}") >> outFile_nc; - } else { - print("Note: The following function is intentionally not wrapped: " fullName); - } - } - - - print("") >> outFile_nh; - print("") >> outFile_nc; - - close(outFile_nh); - close(outFile_nc); -} - - -function wrappFunction(funcDef, commentEolTot) { - - doParse = 1; # add a function in case you want to exclude some - - if (doParse) { - size_funcParts = split(funcDef, funcParts, "(,)|(\\()|(\\);)"); - # because the empty part after ");" would count as part as well - size_funcParts--; - retType_c = trim(funcParts[1]); - fullName = funcParts[2]; - sub(/CALLING_CONV \*/, "", fullName); - sub(/\)/, "", fullName); - - # function parameters - paramList_c = ""; - paramList = ""; - - for (i=3; i<=size_funcParts && !match(funcParts[i], /.*\/\/.*/); i++) { - type_c = extractParamType(funcParts[i]); - type_c = cleanupCType(type_c); - name = extractParamName(funcParts[i]); - if (i == 3) { - cond_comma = ""; - } else { - cond_comma = ", "; - } - paramList_c = paramList_c cond_comma type_c " " name; - } - - funcFullName[fi] = fullName; - funcRetTypeC[fi] = retType_c; - funcParamListC[fi] = paramList_c; - funcParamList[fi] = paramList; - funcCommentEol[fi] = trim(commentEolTot); - storeDocLines(funcDocComment, fi); - fi++; - } else { - print("warninig: function intentionally NOT wrapped: " funcDef); - } -} - - - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return isMultiLineFunc != 1; -} - - - -# save function pointer info into arrays -# ... 2nd, 3rd, ... line of a function pointer definition -{ - if (isMultiLineFunc) { # function is defined on one single line - funcIntermLine = $0; - # separate possible comment at end of line: //$ foo bar - commentEol = funcIntermLine; - if (sub(/.*\/\/\$/, "", commentEol)) { - commentEolTot = commentEolTot commentEol; - } - # remove possible comment at end of line: //$ foo bar - sub(/[ \t]*\/\/.*/, "", funcIntermLine); - funcIntermLine = trim(funcIntermLine); - funcSoFar = funcSoFar " " funcIntermLine; - if (match(funcSoFar, /;$/)) { - # function ends in this line - wrappFunction(funcSoFar, commentEolTot); - isMultiLineFunc = 0; - } - } -} -# 1st line of a function pointer definition -/^[^\/]*CALLING_CONV.*$/ { - - funcStartLine = $0; - # separate possible comment at end of line: //$ foo bar - commentEolTot = ""; - commentEol = funcStartLine; - if (sub(/.*\/\/\$/, "", commentEol)) { - commentEolTot = commentEolTot commentEol; - } - # remove possible comment at end of line: //$ foo bar - sub(/\/\/.*$/, "", funcStartLine); - funcStartLine = trim(funcStartLine); - if (match(funcStartLine, /;$/)) { - # function ends in this line - wrappFunction(funcStartLine, commentEolTot); - } else { - funcSoFar = funcStartLine; - isMultiLineFunc = 1; - } -} - - - -END { - # finalize things - - printNativeFP2F(); -} diff --git a/AI/Interfaces/Java/bin/native_wrappCommands.awk b/AI/Interfaces/Java/bin/native_wrappCommands.awk deleted file mode 100755 index 9de74c4a95f..00000000000 --- a/AI/Interfaces/Java/bin/native_wrappCommands.awk +++ /dev/null @@ -1,384 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates the C functions for wrapping the C command structs in: -# rts/ExternalAI/Interface/AISCommands.h -# -# Before running this script, you have to wrap the native callback struct -# into functions. -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR the root generated sources dir -# default: "../src-generated/main" -# * NATIVE_GENERATED_SOURCE_DIR the native generated sources dir -# default: GENERATED_SOURCE_DIR + "/native" -# -# usage: -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -# awk -f thisScript.awk -f common.awk -f commonDoc.awk \ -# -v 'NATIVE_GENERATED_SOURCE_DIR=/tmp/build/AI/Interfaces/Java/src-generated/main/native' -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "[ \t]+"; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!NATIVE_GENERATED_SOURCE_DIR) { - NATIVE_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/native"; - } - - nativeBridge = "CallbackFunctionPointerBridge"; - bridgePrefix = "bridged__"; - - indent = " "; - - ind_cmdTopics = 0; - ind_cmdStructs = 0; - insideCmdStruct = 0; -} - - -# Checks if a field is available and is no comment -function isFieldUsable(f) { - - valid = 0; - - if (f && !match(f, /.*\/\/.*/)) { - valid = 1; - } - - return valid; -} - - - - -function saveMember(ind_mem, member) { - - name = extractParamName(member); - type_c = extractCType(member); - - cmdsMembers_name[ind_cmdStructs, ind_mem] = name; - cmdsMembers_type_c[ind_cmdStructs, ind_mem] = type_c; -} - - -function doWrapp(ind_cmdStructs_dw) { - - doWrp_dw = 1; - - if (match(cmdsName[ind_cmdStructs_dw], /SharedMemArea/)) { - doWrp_dw = 0; - } else if (match(cmdsName[ind_cmdStructs_dw], /^SCallLuaRulesCommand$/)) { - doWrp_dw = 0; - } - - return doWrp_dw; -} - - -function createNativeFileName(fileName_fn, isHeader_fn) { - - absFileName_fn = NATIVE_GENERATED_SOURCE_DIR "/" fileName_fn; - if (isHeader_fn) { - absFileName_fn = absFileName_fn ".h"; - } else { - absFileName_fn = absFileName_fn ".c"; - } - - return absFileName_fn; -} - - -function printNativeFP2F() { - - outFile_nh = createNativeFileName(nativeBridge, 1); - outFile_nc = createNativeFileName(nativeBridge, 0); - - print("// END: COMMAND_WRAPPERS") >> outFile_nh; - print("") >> outFile_nh; - print("") >> outFile_nc; - - # print the command wrapping functions - for (cmdIndex=0; cmdIndex < ind_cmdStructs; cmdIndex++) { - topicName = cmdsTopicName[cmdIndex]; - topicValue = cmdsTopicNameValue[topicName]; - name = cmdsName[cmdIndex]; - metaInf = cmdsMetaInfo[cmdIndex]; - fullName = metaInf; - sub(/ .*$/, "", fullName); - sub(/^[^ \t]*/, "", metaInf); - - hasRetType = 0; - retType = "int"; - retParam = ""; - paramList = "int _skirmishAIId"; - firstMember = 0; - if (cmdsNumMembers[cmdIndex] > 0) { - for (m=firstMember; m < cmdsNumMembers[cmdIndex]; m++) { - memName = cmdsMembers_name[cmdIndex, m]; - memType_c = cmdsMembers_type_c[cmdIndex, m]; - - if (match(memName, /^ret_/) && !match(memType_c, /\*/)) { - retParam = memName; - retType = memType_c; - hasRetType = 1; - # rewrite the meta info - sub(memName, "RETURN", metaInf); - } else { - paramList = paramList ", " memType_c " " memName; - } - } - } - if (!hasRetType) { - metaInf = metaInf " error-return:0=OK"; - } - paramListNoTypes = removeParamTypes(paramList); - metaInf = trim(metaInf); - - - if (doWrapp(cmdIndex)) { - # print function declaration to *.h - - # Add the member comments to the main comment as @param attributes - numCmdDocLines = cmdsDocComment[cmdIndex, "*"]; - for (m=firstMember; m < cmdsNumMembers[cmdIndex]; m++) { - numLines = cmdMbrsDocComments[cmdIndex*1000 + m, "*"]; - if (numLines > 0) { - cmdsDocComment[cmdIndex, numCmdDocLines] = "@param " cmdsMembers_name[cmdIndex, m]; - } - for (l=0; l < numLines; l++) { - if (l == 0) { - _preDocLine = "@param " cmdsMembers_name[cmdIndex, m] " "; - } else { - _preDocLine = " " lengtAsSpaces(cmdsMembers_name[cmdIndex, m]) " "; - } - cmdsDocComment[cmdIndex, numCmdDocLines] = _preDocLine cmdMbrsDocComments[cmdIndex*1000 + m, l]; - numCmdDocLines++; - } - } - cmdsDocComment[cmdIndex, "*"] = numCmdDocLines; - - outName = bridgePrefix fullName; - - commentEol = ""; - if (metaInf != "") { - commentEol = " // " metaInf; - } - - if (match(fullName, /^Unit_/)) { - # To make this fit in smoothly with the OO structure, - # we want to present each unit command once for the unit class - # and once for the Group class. - - # An other thing we do, is move the common UnitAICommand params - # to the end of the params list, so we can supply default values - # for them more easily later on. - paramList_commonEnd = paramList; - sub(/, short options, int timeOut/, "", paramList_commonEnd); - paramList_commonEnd = paramList_commonEnd ", short options, int timeOut"; - - # Unit version: - paramList_unit = paramList_commonEnd; - sub(/int groupId, /, "", paramList_unit); - printFunctionComment_Common(outFile_nh, cmdsDocComment, cmdIndex, ""); - print("EXPORT(" retType ") " outName "(" paramList_unit ");" commentEol) >> outFile_nh; - print("") >> outFile_nh; - - # Group version: - paramList_group = paramList_commonEnd; - sub(/int unitId, /, "", paramList_group); - outName_group = outName; - sub(/Unit_/, "Group_", outName_group); - printFunctionComment_Common(outFile_nh, cmdsDocComment, cmdIndex, ""); - print("EXPORT(" retType ") " outName_group "(" paramList_group ");" commentEol) >> outFile_nh; - } else { - printFunctionComment_Common(outFile_nh, cmdsDocComment, cmdIndex, ""); - print("EXPORT(" retType ") " outName "(" paramList ");" commentEol) >> outFile_nh; - } - print("") >> outFile_nh; - - # print function definition to *.c - print("") >> outFile_nc; - if (match(fullName, /^Unit_/)) { - # inner version: - print("static " retType " _" outName "(" paramList ") {") >> outFile_nc; - } else { - print("EXPORT(" retType ") " outName "(" paramList ") {") >> outFile_nc; - } - print("") >> outFile_nc; - - print("\t" "struct S" name "Command commandData;") >> outFile_nc; - for (m=firstMember; m < cmdsNumMembers[cmdIndex]; m++) { - memName = cmdsMembers_name[cmdIndex, m]; - memType_c = cmdsMembers_type_c[cmdIndex, m]; - - if (memName == retParam) { - # do nothing - } else { - print("\t" "commandData." memName " = " memName ";") >> outFile_nc; - } - } - print("") >> outFile_nc; - - print("\t" "int _ret = id_clb[_skirmishAIId]->Engine_handleCommand(_skirmishAIId, COMMAND_TO_ID_ENGINE, -1, " topicName ", &commandData);") >> outFile_nc; - print("") >> outFile_nc; - - if (hasRetType) { - # this is unused, delete - print("\t" "if (_ret == 0) {") >> outFile_nc; - print("\t\t" "_ret = commandData." retParam ";") >> outFile_nc; - print("\t" "} else {") >> outFile_nc; - print("\t\t" "_ret = 0;") >> outFile_nc; - print("\t" "}") >> outFile_nc; - } - - print("\t" "return _ret;") >> outFile_nc; - print("}") >> outFile_nc; - - if (match(fullName, /^Unit_/)) { - paramListNoTypes = removeParamTypes(paramList); - - # Unit version: - print("") >> outFile_nc; - print("EXPORT(" retType ") " outName "(" paramList_unit ") {" commentEol) >> outFile_nc; - print("") >> outFile_nc; - print("\t" "const int groupId = -1;") >> outFile_nc; - print("\t" "return _" outName "(" paramListNoTypes ");") >> outFile_nc; - print("}") >> outFile_nc; - print("") >> outFile_nc; - - # Group version: - print("EXPORT(" retType ") " outName_group "(" paramList_group ") {" commentEol) >> outFile_nc; - print("") >> outFile_nc; - print("\t" "const int unitId = -1;") >> outFile_nc; - print("\t" "return _" outName "(" paramListNoTypes ");") >> outFile_nc; - print("}") >> outFile_nc; - } - } else { - print("Java-AIInterface: NOTE: native level: Commands: intentionally not wrapped: " fullName); - } - } - - print("// END: COMMAND_WRAPPERS") >> outFile_nh; - print("") >> outFile_nh; - print("#ifdef __cplusplus") >> outFile_nh; - print("} // extern \"C\"") >> outFile_nh; - print("#endif") >> outFile_nh; - print("") >> outFile_nh; - print("#endif // __CALLBACK_FUNCTION_POINTER_BRIDGE_H") >> outFile_nh; - print("") >> outFile_nh; - - print("") >> outFile_nc; - - close(outFile_nh); - close(outFile_nc); -} - - - - - - -# aggare te los command defines in order -/^[ \t]*COMMAND_.*$/ { - - sub(",", "", $4); - cmdsTopicNameValue[$2] = $4; -} - - - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return isInsideCmdStruct != 1; -} - -################################################################################ -### BEGIN: parsing and saving the command structs - -# end of struct S*Command -/^}; \/\/\$ COMMAND_.*$/ { - - cmdsNumMembers[ind_cmdStructs] = ind_cmdMember; - cmdsTopicName[ind_cmdStructs] = $3; - metaInfo = $0; - sub(/^}; \/\/\$ COMMAND_[^ \t]+/, "", metaInfo); - metaInfo = trim(metaInfo); - cmdsMetaInfo[ind_cmdStructs] = metaInfo; - - if (doWrapp(ind_cmdStructs)) { - #printCommandJava(ind_cmdStructs); - } - - ind_cmdStructs++; - isInsideCmdStruct = 0; -} - - -# inside of struct S*Command -{ - if (isInsideCmdStruct == 1) { - size_tmpMembers = split($0, tmpMembers, ";"); - # cause there is an empty part behind the ';' - size_tmpMembers--; - for (i=1; i<=size_tmpMembers; i++) { - tmpMembers[i] = trim(tmpMembers[i]); - if (tmpMembers[i] == "" || match(tmpMembers[i], /^\/\//)) { - break; - } - # This would bork with more then 1000 members in a command, - # or more then 1000 commands - storeDocLines(cmdMbrsDocComments, ind_cmdStructs*1000 + ind_cmdMember); - saveMember(ind_cmdMember, tmpMembers[i]); - ind_cmdMember++; - } - } -} - -# beginning of struct S*Command -/^struct S.*Command( \{)?/ { - - isInsideCmdStruct = 1; - ind_cmdMember = 0; - commandName = $2; - sub(/^S/, "", commandName); - sub(/Command$/, "", commandName); - - isUnitCommand = match(commandName, /.*Unit$/); - - cmdsIsUnitCmd[ind_cmdStructs] = isUnitCommand; - cmdsName[ind_cmdStructs] = commandName; - storeDocLines(cmdsDocComment, ind_cmdStructs); -} - -# find COMMAND_TO_ID_ENGINE id -/COMMAND_TO_ID_ENGINE/ { - - cmdToIdEngine = $3; -} - -### END: parsing and saving the command structs -################################################################################ - - - -END { - # finalize things - - printNativeFP2F() -} diff --git a/AI/Interfaces/Java/data/InterfaceInfo.lua b/AI/Interfaces/Java/data/InterfaceInfo.lua deleted file mode 100644 index 13b586912a8..00000000000 --- a/AI/Interfaces/Java/data/InterfaceInfo.lua +++ /dev/null @@ -1,51 +0,0 @@ --- --- Info Definition Table format --- --- --- These keywords must be lowercase for LuaParser to read them. --- --- key: user defined or one of the AI_INTERFACE_PROPERTY_* defines in --- SAIInterfaceLibrary.h --- value: the value of the property --- desc: the description (could be used as a tooltip) --- --- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local infos = { - { - key = 'shortName', - value = 'Java', - desc = 'machine conform name.', - }, - { - key = 'version', - value = '0.1', - }, - { - key = 'name', - value = 'default Java AI Interface', - desc = 'human readable name.', - }, - { - key = 'description', - value = 'This interface is needed for Java AIs', - desc = 'tooltip.', - }, - { - key = 'url', - value = 'https://springrts.com/wiki/AIInterface:Java', - desc = 'URL with more detailed info about the AI', - }, - { - key = 'supportedLanguages', - value = 'Java (possily Groovy, JRuby, ...)', - }, - { - key = 'supportsLookup', - value = 'false', - }, -} - -return infos diff --git a/AI/Interfaces/Java/data/jvm.properties b/AI/Interfaces/Java/data/jvm.properties deleted file mode 100644 index a9642fc78ed..00000000000 --- a/AI/Interfaces/Java/data/jvm.properties +++ /dev/null @@ -1,86 +0,0 @@ -# These options are passed to the JVM instance in which all Java AIs run in. -# CAUTION: Please only change these settings if you know what you are doing!! -# For a list of possible options, please see: -# http://blogs.sun.com/watt/resource/jvm-options-list.html -# and: -# http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp -# If you use do not use the SUN JVM, -# the supported options may differ from this list. -# Each line that does not start with '#' or ';' and contains -# other characters then whitespaces is taken as an option. -# -# NOTE: When specifying relative paths to files (eg. log files), -# be aware that these files will likely end up in springs writable data dir, -# though this is not guaranteed, which means you may have to search for them -# in the CWD of the JVM, which differs between platforms. -# -# NOTE: When specifying paths to files (eg. log files), -# you can make use of ${home-dir}, which will be replaced with something like: -# "{abs-path-to-spring-writable-data-dir}/AI/Interfaces/Java/0.1" -# - -# NOTE: only really useful for debugging -# false: crash and report error when a JVM option was specified, -# that is unknown to the used JVM -# default: true -;jvm.arguments.ignoreUnrecognized=false - -# NOTE: change this if you need fancy stuff only -# specify as hex value, eg. 0x00010004 is JNI_VERSION_1_4 -# see jni.h (look for JNI_VERSION_* defines) -# default: 0x00010004 -;jvm.jni.version=0x00010002 - - -# NOTE: this should not be used, as it is auto-generated -;jvm.option.java.class.path=... -# you may simply store .jar and .class files in the jlib/ folder -# of the Java AI Interface or your Java Skirmish AI. -# the value of this property is appended to the generated java.class.path - -# NOTE: you shall NOT specify the following, as they are auto-generated: -;jvm.option.java.library.path=... -# simply store .dll, .so or .dylib files in the lib/ folder -# of the Java AI Interface or your Java Skirmish AI. -# the value of this property is appended to the generated java.library.path - -# Specify which type of the JVM to use -# possible values: client, server -# default: 32bit: client -# 64bit: server -;jvm.type=server - -# NOTE: do not use these, as the interface will ignore them; -# see jvm.option.java.*.path options above -;jvm.option.x=-Djava.class.path=... -;jvm.option.x=-Djava.library.path=... - -# footprint (memory) related -jvm.option.x=-Xms64M -jvm.option.x=-Xmx512M -jvm.option.x=-Xss512K -jvm.option.x=-Xoss400K - - -# Misc -;jvm.option.x=-XX:+AlwaysRestoreFPU -;jvm.option.x=-Djava.util.logging.config.file=./logging.properties - -# example settings for debugging -# logging related (only recommended when debugging) -;jvm.option.x=-Xcheck:jni -;jvm.option.x=-verbose:jni -;jvm.option.x=-XX:+UnlockDiagnosticVMOptions -;jvm.option.x=-XX:+LogVMOutput -;jvm.option.x=-XX:LogFile=${home-dir}/log/jvm-log.xml - -;jvm.option.x=-Xdebug -;jvm.option.x=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=7777 -# disable JIT (required for debugging under the classical VM) -;jvm.option.x=-Djava.compiler=NONE -# disables old JDB -;jvm.option.x=-Xnoagent - -;jvm.option.x=-XX:ErrorFile=./hs_err_pid.log -;jvm.option.x=-XX:+CheckJNICalls - diff --git a/AI/Interfaces/Java/pom.xml b/AI/Interfaces/Java/pom.xml deleted file mode 100644 index bddb566ede4..00000000000 --- a/AI/Interfaces/Java/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - 4.0.0 - - - - - - 0.1 - - - - com.springrts - common-spring - 1.0 - ../../../rts/build/maven/support/common/spring/pom.xml - - - com.springrts - ai-interface-java - ${my.version} - - jar - - Java AI Interface - Java Artificial Intelligence interface plugin for the Spring RTS engine - https://springrts.com/wiki/AIInterface:Java - 2008 - - - - - scm:git:git://github.com/spring/spring.git - scm:git:git@github.com:spring/spring.git - http://github.com/spring/spring/tree/master/AI/Interfaces/Java/ - - - diff --git a/AI/Interfaces/Java/src/main/java/com/springrts/ai/Util.java b/AI/Interfaces/Java/src/main/java/com/springrts/ai/Util.java deleted file mode 100644 index e3a45ebcc99..00000000000 --- a/AI/Interfaces/Java/src/main/java/com/springrts/ai/Util.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright (c) 2009 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package com.springrts.ai; - - -import java.awt.Color; - -/** - * Contains utility functions used within all of the Java AI Interface code. - * - * @author hoijui.quaero@gmail.com - * @version 0.1 - */ -public final class Util { - - /** We need no instances of this class */ - private Util() {} - - public static short[] toShort3Array(final Color color) { - - short[] shortArr = new short[3]; - - shortArr[0] = (short) color.getRed(); - shortArr[1] = (short) color.getGreen(); - shortArr[2] = (short) color.getBlue(); - - return shortArr; - } - - public static Color toColor(final short[] shortArr) { - - Color color = new Color( - (int) shortArr[0], - (int) shortArr[1], - (int) shortArr[2] - ); - - return color; - } -} diff --git a/AI/Interfaces/Java/src/main/native/InterfaceDefines.h b/AI/Interfaces/Java/src/main/native/InterfaceDefines.h deleted file mode 100644 index ceb2ebcae59..00000000000 --- a/AI/Interfaces/Java/src/main/native/InterfaceDefines.h +++ /dev/null @@ -1,23 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#ifndef _INTERFACE_DEFINES_H -#define _INTERFACE_DEFINES_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define JAVA_SKIRMISH_AI_PROPERTY_CLASS_NAME "className" - -#define MY_LOG_FILE "interface-log.txt" -#define JAVA_AI_INTERFACE_LIBRARY_FILE_NAME "AIInterface.jar" -#define NATIVE_LIBS_DIR "lib" -#define JRE_LOCATION_FILE "jre-location.txt" - -#include // for NULL - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _INTERFACE_DEFINES_H diff --git a/AI/Interfaces/Java/src/main/native/InterfaceExport.c b/AI/Interfaces/Java/src/main/native/InterfaceExport.c deleted file mode 100644 index d68714c722e..00000000000 --- a/AI/Interfaces/Java/src/main/native/InterfaceExport.c +++ /dev/null @@ -1,157 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#include "InterfaceExport.h" - -#include "InterfaceDefines.h" -#include "JavaBridge.h" - -// generated at build time -#include "CallbackFunctionPointerBridge.h" - -#include "CUtils/Util.h" -#include "CUtils/SimpleLog.h" - -#include "ExternalAI/Interface/SAIInterfaceLibrary.h" -#include "ExternalAI/Interface/SAIInterfaceCallback.h" -#include "ExternalAI/Interface/SSkirmishAICallback.h" -#include "ExternalAI/Interface/SSkirmishAILibrary.h" - -#include // bool, true, false -#include // strlen(), strcat(), strcpy() -#include // malloc(), calloc(), free() - -static int interfaceId = -1; - -static const struct SAIInterfaceCallback* callback = NULL; -static struct SSkirmishAILibrary jvmSSkirmishAILibrary = {NULL, NULL, NULL, NULL}; - - -EXPORT(int) initStatic(int _interfaceId, const struct SAIInterfaceCallback* _callback) -{ - simpleLog_initcallback(_interfaceId, "Java Interface", _callback->Log_logsl, LOG_LEVEL_INFO); - - // initialize C part of the interface - interfaceId = _interfaceId; - callback = _callback; - - const char* const myShortName = callback->AIInterface_Info_getValueByKey(interfaceId, AI_INTERFACE_PROPERTY_SHORT_NAME); - const char* const myVersion = callback->AIInterface_Info_getValueByKey(interfaceId, AI_INTERFACE_PROPERTY_VERSION); - - if (myShortName == NULL || myVersion == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, "Couldn't fetch AI Name / Version \"%d\"", _interfaceId); - return -1; - } - - simpleLog_log("Initialized %s v%s AI Interface", myShortName, myVersion); - - // initialize Java part of the interface and the JVM - if (java_initStatic(interfaceId, callback)) { - simpleLog_logL(LOG_LEVEL_NOTICE, "Initialization successful."); - return 0; - } - - simpleLog_logL(LOG_LEVEL_ERROR, "Initialization failed."); - return -1; -} - -EXPORT(int) releaseStatic() -{ - // release Java part of the interface - if (java_releaseStatic() && java_unloadJNIEnv()) - return 0; - - return -1; -} - -EXPORT(enum LevelOfSupport) getLevelOfSupportFor(const char* engineVersion, int engineAIInterfaceGeneratedVersion) -{ - return LOS_Unknown; -} - - -// skirmish AI methods -enum LevelOfSupport CALLING_CONV proxy_skirmishAI_getLevelOfSupportFor( - const char* aiShortName, - const char* aiVersion, - const char* engineVersionString, - int engineVersionNumber, - const char* aiInterfaceShortName, - const char* aiInterfaceVersion -) { - return LOS_Unknown; -} - - -int CALLING_CONV proxy_skirmishAI_init(int skirmishAIId, const struct SSkirmishAICallback* aiCallback) -{ - int ret = -1; - - const char* const shortName = aiCallback->SkirmishAI_Info_getValueByKey(skirmishAIId, SKIRMISH_AI_PROPERTY_SHORT_NAME); - const char* const version = aiCallback->SkirmishAI_Info_getValueByKey(skirmishAIId, SKIRMISH_AI_PROPERTY_VERSION); - const char* const className = aiCallback->SkirmishAI_Info_getValueByKey(skirmishAIId, JAVA_SKIRMISH_AI_PROPERTY_CLASS_NAME); - - if (className != NULL) - ret = java_initSkirmishAIClass(shortName, version, className, skirmishAIId) ? 0 : 1; - - if (ret == 0) { - // init OK - funcPntBrdg_addCallback(skirmishAIId, aiCallback); - ret = java_skirmishAI_init(skirmishAIId, aiCallback); - } - - return ret; -} - -int CALLING_CONV proxy_skirmishAI_release(int skirmishAIId) -{ - // does nothing - const int ret = java_skirmishAI_release(skirmishAIId); - funcPntBrdg_removeCallback(skirmishAIId); - return ret; -} - -int CALLING_CONV proxy_skirmishAI_handleEvent(int skirmishAIId, int topicId, const void* data) -{ - return java_skirmishAI_handleEvent(skirmishAIId, topicId, data); -} - - -EXPORT(const struct SSkirmishAILibrary*) loadSkirmishAILibrary( - const char* const shortName, - const char* const version -) { - // all Java AI's run inside a single JVM proxied by this lib - if (jvmSSkirmishAILibrary.init == NULL) { - jvmSSkirmishAILibrary.getLevelOfSupportFor = &proxy_skirmishAI_getLevelOfSupportFor; -/* - jvmSSkirmishAILibrary.getInfo = proxy_skirmishAI_getInfo; - jvmSSkirmishAILibrary.getOptions = proxy_skirmishAI_getOptions; -*/ - jvmSSkirmishAILibrary.init = &proxy_skirmishAI_init; - jvmSSkirmishAILibrary.release = &proxy_skirmishAI_release; - jvmSSkirmishAILibrary.handleEvent = &proxy_skirmishAI_handleEvent; - } - - return &jvmSSkirmishAILibrary; -} - -EXPORT(int) unloadSkirmishAILibrary( - const char* const shortName, - const char* const version -) { - const char* const className = callback->SkirmishAI_Info_getValueByKey(interfaceId, shortName, version, JAVA_SKIRMISH_AI_PROPERTY_CLASS_NAME); - - if (java_releaseSkirmishAIClass(className)) - return 0; - - return -1; -} - -EXPORT(int) unloadAllSkirmishAILibraries() -{ - if (java_releaseAllSkirmishAIClasses()) - return 0; - - return -1; -} - diff --git a/AI/Interfaces/Java/src/main/native/InterfaceExport.h b/AI/Interfaces/Java/src/main/native/InterfaceExport.h deleted file mode 100644 index 20920ccb563..00000000000 --- a/AI/Interfaces/Java/src/main/native/InterfaceExport.h +++ /dev/null @@ -1,61 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#ifndef _INTERFACE_EXPORT_H -#define _INTERFACE_EXPORT_H - -// check if the correct defines are set by the build system -#if !defined BUILDING_AI_INTERFACE -# error BUILDING_AI_INTERFACE should be defined when building AI Interfaces -#endif -#if !defined BUILDING_AI -# error BUILDING_AI should be defined when building AI Interfaces -#endif -#if defined BUILDING_SKIRMISH_AI -# error BUILDING_SKIRMISH_AI should not be defined when building AI Interfaces -#endif -#if defined SYNCIFY -# error SYNCIFY should not be defined when building AI Interfaces -#endif - - -#include "ExternalAI/Interface/aidefines.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//#include "ExternalAI/Interface/ELevelOfSupport.h" - -struct SSkirmishAILibrary; -struct SAIInterfaceCallback; - -// for a list of the functions that have to be exported, -// see struct SAIInterfaceLibrary in: -// "rts/ExternalAI/Interface/SAIInterfaceLibrary.h" - - -// static AI interface library functions - -EXPORT(int) initStatic(int interfaceId, - const struct SAIInterfaceCallback* callback); -EXPORT(int) releaseStatic(); -//EXPORT(enum LevelOfSupport) getLevelOfSupportFor( -// const char* engineVersion, int engineAIInterfaceGeneratedVersion); - - -// skirmish AI related methods - -EXPORT(const struct SSkirmishAILibrary*) loadSkirmishAILibrary( - const char* const shortName, - const char* const version); -EXPORT(int) unloadSkirmishAILibrary( - const char* const shortName, - const char* const version); -EXPORT(int) unloadAllSkirmishAILibraries(); - - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _INTERFACE_EXPORT_H diff --git a/AI/Interfaces/Java/src/main/native/JavaBridge.c b/AI/Interfaces/Java/src/main/native/JavaBridge.c deleted file mode 100644 index 1827f63c806..00000000000 --- a/AI/Interfaces/Java/src/main/native/JavaBridge.c +++ /dev/null @@ -1,1219 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#include "JavaBridge.h" - -#include "InterfaceDefines.h" -#include "JvmLocater.h" -#include "JniUtil.h" -#include "EventsJNIBridge.h" -#include "CUtils/Util.h" -#include "CUtils/SimpleLog.h" -#include "CUtils/SharedLibrary.h" - -#include "ExternalAI/Interface/aidefines.h" -#include "ExternalAI/Interface/SAIInterfaceLibrary.h" -#include "ExternalAI/Interface/SAIInterfaceCallback.h" -#include "ExternalAI/Interface/SSkirmishAILibrary.h" -#include "ExternalAI/Interface/SSkirmishAICallback.h" -#include "System/SafeCStrings.h" -#include "lib/streflop/streflopC.h" - -#include - -#include // strlen(), strcat(), strcpy() -#include // malloc(), calloc(), free() -#include - -struct Properties { - size_t size; - const char** keys; - const char** values; -}; - -static int interfaceId = -1; - -static const struct SAIInterfaceCallback* callback = NULL; -static struct Properties jvmCfgProps = {0, NULL, NULL}; - -static size_t numSkirmishAIs = 0; -// static const size_t maxSkirmishAIs = 255; // MAX_AIS -#define maxSkirmishAIs 255 - -static size_t skirmishAIId_skirmishAiImpl[maxSkirmishAIs] = {999999}; - -static char* jAIClassNames[maxSkirmishAIs] = {NULL}; - -static jobject jAIInstances[maxSkirmishAIs] = {NULL}; -static jobject jAIClassLoaders[maxSkirmishAIs] = {NULL}; -static jobject jAICallBacks[maxSkirmishAIs] = {NULL}; - -// vars used to integrate the JVM -// it is loaded at runtime, not at loadtime -static sharedLib_t jvmSharedLib = NULL; - -typedef jint (JNICALL JNI_GetDefaultJavaVMInitArgs_t)(void* vmArgs); -typedef jint (JNICALL JNI_CreateJavaVM_t)(JavaVM** vm, void** jniEnv, void* vmArgs); -typedef jint (JNICALL JNI_GetCreatedJavaVMs_t)(JavaVM** vms, jsize vms_sizeMax, jsize* vms_size); - -static JNI_GetDefaultJavaVMInitArgs_t* JNI_GetDefaultJavaVMInitArgs_f; -static JNI_CreateJavaVM_t* JNI_CreateJavaVM_f; -static JNI_GetCreatedJavaVMs_t* JNI_GetCreatedJavaVMs_f; - - -// ### JNI global vars ### - -/// Java VM instance reference -static JavaVM* g_jvm = NULL; - -/// AI Callback class -static jclass g_cls_aiCallback = NULL; -/// AI Callback Constructor: AICallback(int skirmishAIId) -static jmethodID g_m_aiCallback_ctor_I = NULL; - -/// Basic AI interface. -static jclass g_cls_ai_int = NULL; - - - -// ### General helper functions following ### - -/// Sets the FPU state to how spring likes it -static inline void java_establishSpringEnv() { - // only detach in java_unloadJNIEnv - // (*g_jvm)->DetachCurrentThread(g_jvm); - streflop_init_Simple(); -} - -/// The JVM sets the environment it wants automatically, so this is a no-op -static inline void java_establishJavaEnv() {} - - -static inline size_t minSize(size_t size1, size_t size2) { - return (size1 < size2) ? size1 : size2; -} - -static const char* java_getValueByKey(const struct Properties* props, const char* key) { - return util_map_getValueByKey(props->size, props->keys, props->values, key); -} - - -// /** -// * Called when the JVM loads this native library. -// */ -// JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { -// return JNI_VERSION_1_6; -// } -// -// /** -// * Called when the JVM unloads this native library. -// */ -// JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {} - - - - -// ### JNI helper functions following ### - -/** - * Creates the AI Interface global Java class path. - * - * It will consist of the following: - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/AIInterface.jar - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/(j)?config/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/(j)?config/[*].jar - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/(j)?resources/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/(j)?resources/[*].jar - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/(j)?script/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/(j)?script/[*].jar - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/jlib/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/jlib/[*].jar - * TODO: {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/common/jlib/ - * TODO: {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/common/jlib/[*].jar - */ -static bool java_createClassPath(char* classPathStr, const size_t classPathStr_sizeMax) -{ - // the dirs and .jar files in the following array - // will be concatenated with intermediate path separators - // to form the classPathStr - static const size_t classPath_sizeMax = 128; - char** classPath = (char**) calloc(classPath_sizeMax, sizeof(char*)); - size_t classPath_size = 0; - - // the Java AI Interfaces java library file path (.../AIInterface.jar) - // We need to search for this jar, instead of looking only where - // the AIInterface.so/InterfaceInfo.lua is, because on some systems - // (eg. Debian), the .so is in /usr/lib, and the .jar's are in /usr/shared. - char mainJarPath[2048]; - const bool located = callback->DataDirs_locatePath(interfaceId, - mainJarPath, sizeof(mainJarPath), - JAVA_AI_INTERFACE_LIBRARY_FILE_NAME, - false, false, false, false); - - if (!located) { - simpleLog_logL(LOG_LEVEL_ERROR, "Couldn't find %s", JAVA_AI_INTERFACE_LIBRARY_FILE_NAME); - return false; - } - - classPath[classPath_size++] = util_allocStrCpy(mainJarPath); - - if (!util_getParentDir(mainJarPath)) { - simpleLog_logL(LOG_LEVEL_ERROR, "Retrieving the parent dir of the path to AIInterface.jar (%s) failed.", mainJarPath); - return false; - } - - char* jarsDataDir = mainJarPath; - - // the directories in the following list will be searched for .jar files - // which will then be added to the classPathStr, plus the dirs will be added - // to the classPathStr directly, so you can keep .class files in there - static const size_t jarDirs_sizeMax = 128; - char** jarDirs = (char**) calloc(jarDirs_sizeMax, sizeof(char*)); - size_t jarDirs_size = 0; - - // add to classpath: - // {spring-data-dir}/Interfaces/Java/0.1/${x}/ - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "jconfig"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "config"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "jresources"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "resources"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "jscript"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "script"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, jarsDataDir, "jlib"); - // "lib" is for native libs only - - // add the jar dirs (for .class files) and all contained .jars recursively - size_t jd, jf; - for (jd = 0; (jd < jarDirs_size) && (classPath_size < classPath_sizeMax); ++jd) { - if (util_fileExists(jarDirs[jd])) { - // add the dir directly - // For this to work properly with URLClassPathHandler, - // we have to ensure there is a '/' at the end, - // for the class-path-part to be recognized as a directory. - classPath[classPath_size++] = util_allocStrCat(2, jarDirs[jd], "/"); - - // add the contained jars recursively - static const size_t jarFiles_sizeMax = 128; - char** jarFiles = (char**) calloc(jarFiles_sizeMax, sizeof(char*)); - const size_t jarFiles_size = util_listFiles(jarDirs[jd], ".jar", jarFiles, true, jarFiles_sizeMax); - - for (jf = 0; (jf < jarFiles_size) && (classPath_size < classPath_sizeMax); ++jf) { - classPath[classPath_size++] = util_allocStrCatFSPath(2, jarDirs[jd], jarFiles[jf]); - FREE(jarFiles[jf]); - } - - FREE(jarFiles); - } - - FREE(jarDirs[jd]); - } - - FREE(jarDirs); - - - // concat the classpath entries - classPathStr[0] = '\0'; - if (classPath[0] != NULL) { - STRCAT_T(classPathStr, classPathStr_sizeMax, classPath[0]); - FREE(classPath[0]); - } - - size_t cp; - - for (cp = 1; cp < classPath_size; ++cp) { - if (classPath[cp] == NULL) - continue; - - STRCAT_T(classPathStr, classPathStr_sizeMax, ENTRY_DELIM); - STRCAT_T(classPathStr, classPathStr_sizeMax, classPath[cp]); - FREE(classPath[cp]); - } - - FREE(classPath); - return true; -} - -/** - * Creates a Skirmish AI local Java class path. - * - * It will consist of the following: - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/SkirmishAI.jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/(j)?config/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/(j)?config/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/(j)?resources/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/(j)?resources/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/(j)?script/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/(j)?script/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/jlib/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/jlib/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/(j)?config/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/(j)?config/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/(j)?resources/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/(j)?resources/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/(j)?script/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/(j)?script/[*].jar - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/jlib/ - * {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/common/jlib/[*].jar - */ -static size_t java_createAIClassPath( - const char* shortName, - const char* version, - char** classPathParts, - const size_t classPathParts_sizeMax -) { - size_t classPathParts_size = 0; - - // the .jar files in the following list will be added to the classpath - const size_t jarFiles_sizeMax = classPathParts_sizeMax; - char** jarFiles = (char**) calloc(jarFiles_sizeMax, sizeof(char*)); - size_t jarFiles_size = 0; - - const char* const skirmDD = - callback->SkirmishAI_Info_getValueByKey(interfaceId, - shortName, version, - SKIRMISH_AI_PROPERTY_DATA_DIR); - if (skirmDD == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, - "Retrieving the data-dir of Skirmish AI %s-%s failed.", - shortName, version); - } - // {spring-data-dir}/{SKIRMISH_AI_DATA_DIR}/{ai-name}/{ai-version}/SkirmishAI.jar - jarFiles[jarFiles_size++] = util_allocStrCatFSPath(2, - skirmDD, "SkirmishAI.jar"); - - // the directories in the following list will be searched for .jar files - // which then will be added to the classpath, plus they will be added - // to the classpath directly, so you can keep .class files in there - const size_t jarDirs_sizeMax = classPathParts_sizeMax; - char** jarDirs = (char**) calloc(jarDirs_sizeMax, sizeof(char*)); - size_t jarDirs_size = 0; - - // add to classpath ... - - // {spring-data-dir}/Skirmish/MyJavaAI/0.1/SkirmishAI/ - // this can be useful for AI devs while testing, - // if they do not want to put everything into a jar all the time - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "SkirmishAI"); - - // add to classpath: - // {spring-data-dir}/Skirmish/MyJavaAI/0.1/${x}/ - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "jconfig"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "config"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "jresources"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "resources"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "jscript"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "script"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDD, "jlib"); - // "lib" is for native libs only - - // add the dir common for all versions of the Skirmish AI, - // if it is specified and exists - const char* const skirmDDCommon = - callback->SkirmishAI_Info_getValueByKey(interfaceId, - shortName, version, - SKIRMISH_AI_PROPERTY_DATA_DIR_COMMON); - - if (skirmDDCommon != NULL) { - // add to classpath: - // {spring-data-dir}/Skirmish/MyJavaAI/common/${x}/ - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "jconfig"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "config"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "jresources"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "resources"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "jscript"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "script"); - jarDirs[jarDirs_size++] = util_allocStrCatFSPath(2, skirmDDCommon, "jlib"); - // "lib" is for native libs only - } - - // add the directly specified .jar files - size_t jf; - for (jf = 0; (jf < jarFiles_size) && (classPathParts_size < classPathParts_sizeMax); ++jf) { - classPathParts[classPathParts_size++] = util_allocStrCpy(jarFiles[jf]); - FREE(jarFiles[jf]); - } - - // add the dirs and the contained .jar files - size_t jd, sjf; - for (jd = 0; (jd < jarDirs_size) && (classPathParts_size < classPathParts_sizeMax); ++jd) { - if (jarDirs[jd] != NULL && util_fileExists(jarDirs[jd])) { - // add the jar dir (for .class files) - // For this to work properly with URLClassPathHandler, - // we have to ensure there is a '/' at the end, - // for the class-path-part to be recognized as a directory. - classPathParts[classPathParts_size++] = util_allocStrCat(2, jarDirs[jd], "/"); - - // add the jars in the dir - const size_t subJarFiles_sizeMax = classPathParts_sizeMax - classPathParts_size; - char** subJarFiles = (char**) calloc(subJarFiles_sizeMax, sizeof(char*)); - const size_t subJarFiles_size = util_listFiles(jarDirs[jd], ".jar", subJarFiles, true, subJarFiles_sizeMax); - - for (sjf = 0; (sjf < subJarFiles_size) && (classPathParts_size < classPathParts_sizeMax); ++sjf) { - // .../[*].jar - classPathParts[classPathParts_size++] = util_allocStrCatFSPath(2, jarDirs[jd], subJarFiles[sjf]); - FREE(subJarFiles[sjf]); - } - - FREE(subJarFiles); - } - - FREE(jarDirs[jd]); - } - - FREE(jarDirs); - FREE(jarFiles); - - return classPathParts_size; -} - -static jobject java_createAIClassLoader(JNIEnv* env, const char* shortName, const char* version) -{ - static const size_t classPathParts_sizeMax = 512; - char** classPathParts = (char**) calloc(classPathParts_sizeMax, sizeof(char*)); - const size_t classPathParts_size = java_createAIClassPath(shortName, version, classPathParts, classPathParts_sizeMax); - - jobject o_jClsLoader = NULL; - jobjectArray o_cppURLs = jniUtil_createURLArray(env, classPathParts_size); - - if (o_cppURLs != NULL) { -#ifdef _WIN32 - static const char* FILE_URL_PREFIX = "file:///"; -#else // _WIN32 - static const char* FILE_URL_PREFIX = "file://"; -#endif // _WIN32 - size_t cpp; - for (cpp = 0; cpp < classPathParts_size; ++cpp) { - #ifdef _WIN32 - // we can not use windows path separators in file URLs - util_strReplaceChar(classPathParts[cpp], '\\', '/'); - #endif - - char* str_fileUrl = util_allocStrCat(2, FILE_URL_PREFIX, classPathParts[cpp]); - // TODO: check/test if this is allowed/ok - FREE(classPathParts[cpp]); - simpleLog_logL(LOG_LEVEL_INFO, - "Skirmish AI %s %s class-path part %i: \"%s\"", - shortName, version, cpp, str_fileUrl); - jobject jurl_fileUrl = jniUtil_createURLObject(env, str_fileUrl); - FREE(str_fileUrl); - if (jurl_fileUrl == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, - "Skirmish AI %s %s class-path part %i (\"%s\"): failed to create a URL", - shortName, version, cpp, str_fileUrl); - o_cppURLs = NULL; - break; - } - const bool inserted = jniUtil_insertURLIntoArray(env, o_cppURLs, cpp, jurl_fileUrl); - if (!inserted) { - simpleLog_logL(LOG_LEVEL_ERROR, - "Skirmish AI %s %s class-path part %i (\"%s\"): failed to insert", - shortName, version, cpp, str_fileUrl); - o_cppURLs = NULL; - break; - } - } - } - - if (o_cppURLs != NULL) { - if ((o_jClsLoader = jniUtil_createURLClassLoader(env, o_cppURLs)) != NULL) - o_jClsLoader = jniUtil_makeGlobalRef(env, o_jClsLoader, "Skirmish AI class-loader"); - } - - FREE(classPathParts); - return o_jClsLoader; -} - -/** - * Load the interfaces JVM properties file. - */ -static bool java_readJvmCfgFile(struct Properties* props) -{ - bool read = false; - - const size_t props_sizeMax = 256; - - props->size = 0; - props->keys = (const char**) calloc(props_sizeMax, sizeof(char*)); - props->values = (const char**) calloc(props_sizeMax, sizeof(char*)); - - // ### read JVM options config file ### - char jvmPropFile[2048]; - bool located = callback->DataDirs_locatePath(interfaceId, jvmPropFile, sizeof(jvmPropFile), JVM_PROPERTIES_FILE, false, false, false, false); - - // if the version specific file does not exist, - // try to get the common one - if (!located) - located = callback->DataDirs_locatePath(interfaceId, jvmPropFile, sizeof(jvmPropFile), JVM_PROPERTIES_FILE, false, false, false, true); - - if (located) { - props->size = util_parsePropertiesFile(jvmPropFile, props->keys, props->values, props_sizeMax); - read = true; - simpleLog_logL(LOG_LEVEL_INFO, "JVM: arguments loaded from: %s", jvmPropFile); - } else { - props->size = 0; - read = false; - simpleLog_logL(LOG_LEVEL_INFO, "JVM: arguments NOT loaded"); - } - - return read; -} - -/** - * Creates the Java library path. - * -> where native shared libraries are searched - * - * It will consist of the following: - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/lib/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/common/ - * {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/common/lib/ - */ -static bool java_createNativeLibsPath(char* libraryPath, const size_t libraryPath_sizeMax) -{ - // {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/ - const char* const dd_r = callback->AIInterface_Info_getValueByKey(interfaceId, AI_INTERFACE_PROPERTY_DATA_DIR); - - if (dd_r == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, "Unable to find read-only data-dir."); - return false; - } - - STRCPY_T(libraryPath, libraryPath_sizeMax, dd_r); - - // {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/{version}/lib/ - char dd_lib_r[2048]; - const bool located = callback->DataDirs_locatePath(interfaceId, dd_lib_r, sizeof(dd_lib_r), NATIVE_LIBS_DIR, false, false, true, false); - - if (!located) { - simpleLog_logL(LOG_LEVEL_NOTICE, "Unable to find read-only native libs data-dir (optional): %s", NATIVE_LIBS_DIR); - } else { - STRCAT_T(libraryPath, libraryPath_sizeMax, ENTRY_DELIM); - STRCAT_T(libraryPath, libraryPath_sizeMax, dd_lib_r); - } - - - // {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/common/ - const char* const dd_r_common = callback->AIInterface_Info_getValueByKey(interfaceId, AI_INTERFACE_PROPERTY_DATA_DIR_COMMON); - - if (dd_r_common == NULL || !util_fileExists(dd_r_common)) { - simpleLog_logL(LOG_LEVEL_NOTICE, "Unable to find common read-only data-dir (optional)."); - } else { - STRCAT_T(libraryPath, libraryPath_sizeMax, ENTRY_DELIM); - STRCAT_T(libraryPath, libraryPath_sizeMax, dd_r_common); - } - - - // {spring-data-dir}/{AI_INTERFACES_DATA_DIR}/Java/common/lib/ - if (dd_r_common != NULL) { - char dd_lib_r_common[2048]; - const bool located = callback->DataDirs_locatePath(interfaceId, dd_lib_r_common, sizeof(dd_lib_r_common), NATIVE_LIBS_DIR, false, false, true, true); - - if (!located || !util_fileExists(dd_lib_r_common)) { - simpleLog_logL(LOG_LEVEL_NOTICE, "Unable to find common read-only native libs data-dir (optional)."); - } else { - STRCAT_T(libraryPath, libraryPath_sizeMax, ENTRY_DELIM); - STRCAT_T(libraryPath, libraryPath_sizeMax, dd_lib_r_common); - } - } - - return true; -} - - -static bool java_createJavaVMInitArgs(struct JavaVMInitArgs* vm_args, const struct Properties* jvmProps) -{ - // jint jniVersion = JNI_VERSION_1_1; - // jint jniVersion = JNI_VERSION_1_2; - jint jniVersion = JNI_VERSION_1_4; - // jint jniVersion = JNI_VERSION_1_6; - - char classPath [8 * 1024] = {0}; - char classPathOpt[8 * 1024] = {0}; - char libraryPath [4 * 1024] = {0}; - char libraryPathOpt[4 * 1024] = {0}; - - bool ignoreUnrecognized = true; - - if (jvmProps != NULL) { - const char* jniVersionFromCfg = java_getValueByKey(jvmProps, "jvm.jni.version"); - const char* ignoreUnrecognizedFromCfg = java_getValueByKey(jvmProps, "jvm.arguments.ignoreUnrecognized"); - - // ### evaluate JNI version to use ### - if (jniVersionFromCfg != NULL) { - const unsigned long int jniVersion_tmp = strtoul(jniVersionFromCfg, NULL, 16); - - if (jniVersion_tmp != 0 /*&& jniVersion_tmp != ULONG_MAX*/) - jniVersion = (jint) jniVersion_tmp; - } - - // ### check if unrecognized JVM options should be ignored ### - // if false, the JVM creation will fail if an - // unknown or invalid option was specified - if (ignoreUnrecognizedFromCfg != NULL && !util_strToBool(ignoreUnrecognizedFromCfg)) - ignoreUnrecognized = false; - } - - simpleLog_logL(LOG_LEVEL_INFO, "JVM: JNI version: %#x", jniVersion); - vm_args->version = jniVersion; - - - if (ignoreUnrecognized) { - simpleLog_logL(LOG_LEVEL_INFO, "JVM: ignoring unrecognized options"); - vm_args->ignoreUnrecognized = JNI_TRUE; - } else { - simpleLog_logL(LOG_LEVEL_INFO, "JVM: NOT ignoring unrecognized options"); - vm_args->ignoreUnrecognized = JNI_FALSE; - } - - - // ### create the Java class-path option ### - // autogenerate the class path - if (!java_createClassPath(classPath, sizeof(classPath))) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed creating Java class-path."); - return false; - } - if (jvmProps != NULL) { - // ..., and append the part from the jvm options properties file, - // if it is specified there - const char* clsPathFromCfg = java_getValueByKey(jvmProps, "jvm.option.java.class.path"); - - if (clsPathFromCfg != NULL) { - STRCAT_T(classPath, sizeof(classPath), ENTRY_DELIM); - STRCAT_T(classPath, sizeof(classPath), clsPathFromCfg); - } - } - - - // create the java.class.path option - STRCPY_T(classPathOpt, sizeof(classPathOpt), "-Djava.class.path="); - STRCAT_T(classPathOpt, sizeof(classPathOpt), classPath); - - - // ### create the Java library-path option ### - // autogenerate the java library path - if (!java_createNativeLibsPath(libraryPath, sizeof(libraryPath))) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed creating Java library-path."); - return false; - } - if (jvmProps != NULL) { - // ..., and append the part from the jvm options properties file, - // if it is specified there - const char* libPathFromCfg = java_getValueByKey(jvmProps, "jvm.option.java.library.path"); - - if (libPathFromCfg != NULL) { - STRCAT_T(libraryPath, sizeof(libraryPath), ENTRY_DELIM); - STRCAT_T(libraryPath, sizeof(libraryPath), libPathFromCfg); - } - } - - // create the java.library.path option ... - // autogenerate it, and append the part from the jvm options file, - // if it is specified there - STRCPY_T(libraryPathOpt, sizeof(libraryPathOpt), "-Djava.library.path="); - STRCAT_T(libraryPathOpt, sizeof(libraryPathOpt), libraryPath); - - - // ### create and set all JVM options ### - const char* strOptions[64]; - size_t numOpts = 0; - - strOptions[numOpts++] = classPathOpt; - strOptions[numOpts++] = libraryPathOpt; - - static const char* const JCPVAL = "-Djava.class.path="; - static const char* const JLPVAL = "-Djava.library.path="; - const size_t JCPVAL_size = strlen(JCPVAL); - const size_t JLPVAL_size = strlen(JCPVAL); - - if (jvmProps != NULL) { - // ### add string options from the JVM config file with property name "jvm.option.x" ### - int i; - for (i = 0; i < jvmProps->size; ++i) { - if (strcmp(jvmProps->keys[i], "jvm.option.x") != 0) - continue; - - const char* const val = jvmProps->values[i]; - const size_t val_size = strlen(val); - // ignore "-Djava.class.path=..." - // and "-Djava.library.path=..." options - if (strncmp(val, JCPVAL, minSize(val_size, JCPVAL_size)) != 0 && - strncmp(val, JLPVAL, minSize(val_size, JLPVAL_size)) != 0) { - strOptions[numOpts++] = val; - } - } - } else { - // ### ... or set default ones, if the JVM config file was not found ### - simpleLog_logL(LOG_LEVEL_WARNING, "JVM: properties file ("JVM_PROPERTIES_FILE") not found; using default options."); - - strOptions[numOpts++] = "-Xms64M"; - strOptions[numOpts++] = "-Xmx512M"; - strOptions[numOpts++] = "-Xss512K"; - strOptions[numOpts++] = "-Xoss400K"; - - #if defined DEBUG - strOptions[numOpts++] = "-Xcheck:jni"; - strOptions[numOpts++] = "-verbose:jni"; - strOptions[numOpts++] = "-XX:+UnlockDiagnosticVMOptions"; - strOptions[numOpts++] = "-XX:+LogVMOutput"; - - strOptions[numOpts++] = "-Xdebug"; - strOptions[numOpts++] = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=7777"; - // disable JIT (required for debugging under the classical VM) - strOptions[numOpts++] = "-Djava.compiler=NONE"; - // disable old JDB - strOptions[numOpts++] = "-Xnoagent"; - #endif // defined DEBUG - } - - vm_args->options = (struct JavaVMOption*) calloc(numOpts, sizeof(struct JavaVMOption)); - vm_args->nOptions = 0; - - // fill strOptions into the JVM options - simpleLog_logL(LOG_LEVEL_INFO, "JVM: options:", numOpts); - char dd_rw[2048] = {'\0'}; - callback->DataDirs_locatePath(interfaceId, dd_rw, sizeof(dd_rw), "", true, true, true, false); - size_t i; - - for (i = 0; i < numOpts; ++i) { - char* tmpOptionString = util_allocStrReplaceStr(strOptions[i], "${home-dir}", dd_rw); - - // do not add empty options - if (tmpOptionString == NULL) - continue; - - if (strlen(tmpOptionString) == 0) { - free(tmpOptionString); - tmpOptionString = NULL; - continue; - } - - vm_args->options[vm_args->nOptions ].optionString = tmpOptionString; - vm_args->options[vm_args->nOptions++].extraInfo = NULL; - - simpleLog_logL(LOG_LEVEL_INFO, "JVM option %ul: %s", vm_args->nOptions - 1, tmpOptionString); - } - - simpleLog_logL(LOG_LEVEL_INFO, ""); - return true; -} - - - -static JNIEnv* java_reattachCurrentThread(JavaVM* jvm) -{ - simpleLog_logL(LOG_LEVEL_DEBUG, "Reattaching current thread..."); - - JNIEnv* env = NULL; - - // const jint res = (*jvm)->AttachCurrentThreadAsDaemon(jvm, (void**) &env, NULL); - const jint res = (*jvm)->AttachCurrentThread(jvm, (void**) &env, NULL); - - if (res != 0) { - env = NULL; - simpleLog_logL(LOG_LEVEL_ERROR, "Failed attaching JVM to current thread(2): %i - %s", res, jniUtil_getJniRetValDescription(res)); - } - - return env; -} - -static JNIEnv* java_getJNIEnv(bool preload) -{ - if (g_jvm != NULL) - return java_reattachCurrentThread(g_jvm); - - assert(preload); - simpleLog_logL(LOG_LEVEL_INFO, "Creating the JVM."); - - JNIEnv* ret = NULL; - JNIEnv* env = NULL; - JavaVM* jvm = NULL; - - struct JavaVMInitArgs vm_args; - memset(&vm_args, 0, sizeof(vm_args)); - - jint res = 0; - - if (!java_createJavaVMInitArgs(&vm_args, &jvmCfgProps)) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed initializing JVM init-arguments."); - goto end; - } - - // Looking for existing JVMs might be problematic: they could - // have been initialized with other JVM-arguments then we need. - // But as we can not use DestroyJavaVM (it makes creating a new - // one for the same process impossible, a (SUN?) JVM limitation) - // we have to do this anyway to support /aireload and /aicontrol - // for Java Skirmish AIs. - // - simpleLog_logL(LOG_LEVEL_INFO, "looking for existing JVMs ..."); - jsize numJVMsFound = 0; - - // grab the first Java VM that has been created - if ((res = JNI_GetCreatedJavaVMs_f(&jvm, 1, &numJVMsFound)) != 0) { - jvm = NULL; - simpleLog_logL(LOG_LEVEL_ERROR, "Failed fetching list of running JVMs: %i - %s", res, jniUtil_getJniRetValDescription(res)); - goto end; - } - - simpleLog_logL(LOG_LEVEL_INFO, "number of existing JVMs: %i", numJVMsFound); - - if (numJVMsFound > 0) { - simpleLog_logL(LOG_LEVEL_INFO, "using an already running JVM."); - } else { - simpleLog_logL(LOG_LEVEL_INFO, "creating JVM..."); - - if ((res = JNI_CreateJavaVM_f(&jvm, (void**) &env, &vm_args)) != 0 || (*env)->ExceptionCheck(env)) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed to create Java VM: %i - %s", res, jniUtil_getJniRetValDescription(res)); - goto end; - } - } - - // free the JavaVMInitArgs content - jint i; - for (i = 0; i < vm_args.nOptions; ++i) { - FREE(vm_args.options[i].optionString); - } - FREE(vm_args.options); - - //res = (*jvm)->AttachCurrentThreadAsDaemon(jvm, (void**) &env, NULL); - res = (*jvm)->AttachCurrentThread(jvm, (void**) &env, NULL); - - if (res < 0 || (*env)->ExceptionCheck(env)) { - if ((*env)->ExceptionCheck(env)) - (*env)->ExceptionDescribe(env); - - simpleLog_logL(LOG_LEVEL_ERROR, "Failed to attach JVM to current thread: %i - %s", res, jniUtil_getJniRetValDescription(res)); - goto end; - } - -end: - if (env == NULL || jvm == NULL || (*env)->ExceptionCheck(env) || res != 0) { - simpleLog_logL(LOG_LEVEL_ERROR, "JVM: Failed creating."); - - if (env != NULL && (*env)->ExceptionCheck(env)) - (*env)->ExceptionDescribe(env); - - if (jvm != NULL) { - // never destroy the JVM, doing so prevents it from being created again for the same thread - // res = (*jvm)->DestroyJavaVM(jvm); - } - - g_jvm = NULL; - ret = NULL; - } else { - g_jvm = jvm; - ret = env; - } - - return ret; -} - - -bool java_unloadJNIEnv() -{ - if (g_jvm == NULL) - return true; - - simpleLog_logL(LOG_LEVEL_INFO, "JVM: Unloading ..."); - - #if 0 - // JNIEnv* jniEnv = java_getJNIEnv(false); - - // We have to be the ONLY running thread (native and Java) - // this may not help, but will not hurt either - // - // // jint res = (*g_jvm)->AttachCurrentThreadAsDaemon(g_jvm, (void**) &g_jniEnv, NULL); - // jint res = jvm->AttachCurrentThread((void**) &jniEnv, NULL); - #endif - - #if 0 - if (res < 0 || (*g_jniEnv)->ExceptionCheck(g_jniEnv)) { - if ((*g_jniEnv)->ExceptionCheck(g_jniEnv)) - (*g_jniEnv)->ExceptionDescribe(g_jniEnv); - - simpleLog_logL(LOG_LEVEL_ERROR, "JVM: Can not Attach to the current thread: %i - %s", res, jniUtil_getJniRetValDescription(res)); - return false; - } - #endif - - - const jint res = (*g_jvm)->DetachCurrentThread(g_jvm); - - if (res != 0) { - simpleLog_logL(LOG_LEVEL_ERROR, "JVM: Failed detaching current thread: %i - %s", res, jniUtil_getJniRetValDescription(res)); - return false; - } - - // never destroy the JVM because then it can not be created again - // in the same thread; will always fail with return value -1 (see - // java_getJNIEnv) - #if 0 - if ((res = (*g_jvm)->DestroyJavaVM(g_jvm)) != 0) { - simpleLog_logL(LOG_LEVEL_ERROR, "JVM: Failed destroying: %i - %s", res, jniUtil_getJniRetValDescription(res)); - return false; - } - - simpleLog_logL(LOG_LEVEL_NOTICE, "JVM: Successfully destroyed"); - g_jvm = NULL; - #endif - - java_establishSpringEnv(); - return true; -} - - -bool java_initStatic(int _interfaceId, const struct SAIInterfaceCallback* _callback) -{ - interfaceId = _interfaceId; - callback = _callback; - - // Read the jvm properties config file - java_readJvmCfgFile(&jvmCfgProps); - - size_t t; - for (t = 0; t < maxSkirmishAIs; ++t) { - skirmishAIId_skirmishAiImpl[t] = 999999; - } - - size_t sai; - for (sai = 0; sai < maxSkirmishAIs; ++sai) { - jAIClassNames[sai] = NULL; - jAIInstances[sai] = NULL; - jAIClassLoaders[sai] = NULL; - } - - // dynamically load the JVM - char jreLocationFile[2048]; - const bool located = callback->DataDirs_locatePath(interfaceId, jreLocationFile, sizeof(jreLocationFile), JRE_LOCATION_FILE, false, false, false, false); - char jrePath[1024]; - char jvmLibPath[1024]; - - if (!GetJREPath(jrePath, sizeof(jrePath), located ? jreLocationFile : NULL, NULL)) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed locating a JRE installation, you may specify the JAVA_HOME env var."); - return false; - } - - simpleLog_logL(LOG_LEVEL_NOTICE, "Using JRE (can be changed with JAVA_HOME): %s", jrePath); - -#if defined __arch64__ - static const char* defJvmType = "server"; -#else - static const char* defJvmType = "client"; -#endif - const char* jvmType = java_getValueByKey(&jvmCfgProps, "jvm.type"); - - if (jvmType == NULL) - jvmType = defJvmType; - - if (!GetJVMPath(jrePath, jvmType, jvmLibPath, sizeof(jvmLibPath), NULL)) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed locating the %s version of the JVM, please contact spring devs.", jvmType); - return false; - } - - if (!sharedLib_isLoaded(jvmSharedLib = sharedLib_load(jvmLibPath))) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed to load the JVM at \"%s\".", jvmLibPath); - return false; - } - - simpleLog_logL(LOG_LEVEL_NOTICE, "Successfully loaded the JVM shared library at \"%s\".", jvmLibPath); - - if ((JNI_GetDefaultJavaVMInitArgs_f = (JNI_GetDefaultJavaVMInitArgs_t*) sharedLib_findAddress(jvmSharedLib, "JNI_GetDefaultJavaVMInitArgs")) == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed to load the JVM, function \"%s\" not exported.", "JNI_GetDefaultJavaVMInitArgs"); - return false; - } - - if ((JNI_CreateJavaVM_f = (JNI_CreateJavaVM_t*) sharedLib_findAddress(jvmSharedLib, "JNI_CreateJavaVM")) == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed to load the JVM, function \"%s\" not exported.", "JNI_CreateJavaVM"); - return false; - } - - if ((JNI_GetCreatedJavaVMs_f = (JNI_GetCreatedJavaVMs_t*) sharedLib_findAddress(jvmSharedLib, "JNI_GetCreatedJavaVMs")) == NULL) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed to load the JVM, function \"%s\" not exported.", "JNI_GetCreatedJavaVMs"); - return false; - } - - java_establishJavaEnv(); - JNIEnv* env = java_getJNIEnv(true); - const bool loaded = (env != NULL); - const bool inited = (loaded && eventsJniBridge_initStatic(env, maxSkirmishAIs) == 0); - java_establishSpringEnv(); - - return inited; -} - -bool java_releaseStatic() -{ - sharedLib_unload(jvmSharedLib); - jvmSharedLib = NULL; - - FREE(jvmCfgProps.keys); - FREE(jvmCfgProps.values); - return true; -} - - - -static jobject java_createAICallback(JNIEnv* env, const struct SSkirmishAICallback* aiCallback, int skirmishAIId) { - (void) aiCallback; - - // initialize the AI Callback class, if not yet done - if (g_cls_aiCallback == NULL) { - // get the AI Callback class - if ((g_cls_aiCallback = jniUtil_findClass(env, CLS_AI_CALLBACK)) == NULL) - return NULL; - if ((g_cls_aiCallback = jniUtil_makeGlobalRef(env, g_cls_aiCallback, CLS_AI_CALLBACK)) == NULL) - return NULL; - // get (int skirmishAIId) constructor - if ((g_m_aiCallback_ctor_I = jniUtil_getMethodID(env, g_cls_aiCallback, "", "(I)V")) == NULL) - return NULL; - } - - #if 1 - // reuse callback if reloading - // this should be safe since the callback objects created in java_skirmishAI_init are not - // broken by java_skirmishAI_handleEvent, which also calls java_reattachCurrentThread and - // mightget a different env-pointer back - if (jAICallBacks[skirmishAIId] != NULL) - return jAICallBacks[skirmishAIId]; - #endif - - jobject o_clb = (*env)->NewObject(env, g_cls_aiCallback, g_m_aiCallback_ctor_I, skirmishAIId); - - if (jniUtil_checkException(env, "Failed creating Java AI Callback instance")) - return NULL; - - // return (jAICallBacks[skirmishAIId] = jniUtil_makeGlobalRef(env, o_clb, "AI callback instance")); - return (jAICallBacks[skirmishAIId] = o_clb); -} - - - -static bool java_loadSkirmishAI( - JNIEnv* env, - const char* shortName, - const char* version, - const char* className, - jobject* o_ai, - jobject* o_aiClassLoader -) { - #if 0 - // convert className from "com.myai.AI" to "com/myai/AI" - const size_t classNameP_sizeMax = strlen(className) + 1; - char classNameP[classNameP_sizeMax]; - STRCPY_T(classNameP, classNameP_sizeMax, className); - util_strReplaceChar(classNameP, '.', '/'); - #endif - - // get the AIs private class-loader - jobject o_global_aiClassLoader = java_createAIClassLoader(env, shortName, version); - - if (o_global_aiClassLoader == NULL) - return false; - - *o_aiClassLoader = o_global_aiClassLoader; - - // get the AI interface (from AIInterface.jar) - if (g_cls_ai_int == NULL) { - if ((g_cls_ai_int = jniUtil_findClass(env, INT_AI)) == NULL) - return false; - if ((g_cls_ai_int = jniUtil_makeGlobalRef(env, g_cls_ai_int, "AI interface class")) == NULL) - return false; - } - - // get the AI implementation class (from SkirmishAI.jar) - jclass cls_ai = jniUtil_findClassThroughLoader(env, o_global_aiClassLoader, className); - - if (cls_ai == NULL) - return false; - - const bool implementsAIInt = (bool) (*env)->IsAssignableFrom(env, cls_ai, g_cls_ai_int); - - if (!implementsAIInt || (*env)->ExceptionCheck(env)) { - simpleLog_logL(LOG_LEVEL_ERROR, "AI class not assignable from interface "INT_AI": %s", className); - simpleLog_logL(LOG_LEVEL_ERROR, "possible reasons (this list could be incomplete):"); - simpleLog_logL(LOG_LEVEL_ERROR, "* "INT_AI" interface not implemented"); - simpleLog_logL(LOG_LEVEL_ERROR, "* The AI is not compiled for the Java AI Interface version in use"); - - if (implementsAIInt) - (*env)->ExceptionDescribe(env); - - return false; - } - - - // get factory no-arg ctor - jmethodID m_ai_ctor = jniUtil_getMethodID(env, cls_ai, "", "()V"); - - if (m_ai_ctor == NULL) - return false; - - - // get AI instance - jobject o_local_ai = (*env)->NewObject(env, cls_ai, m_ai_ctor); - - if (o_local_ai == NULL || (*env)->ExceptionCheck(env)) { - simpleLog_logL(LOG_LEVEL_ERROR, "Failed fetching AI instance for class: %s", className); - - if (o_local_ai != NULL) - (*env)->ExceptionDescribe(env); - - return false; - } - - // make the AI a global reference, so it will not be garbage collected even after this method returns - *o_ai = jniUtil_makeGlobalRef(env, o_local_ai, "AI instance"); - return true; -} - - -bool java_initSkirmishAIClass( - const char* const shortName, - const char* const version, - const char* const className, - int skirmishAIId -) { - bool success = false; - - // see if an AI for className is instantiated already - size_t sai; - size_t firstFree = numSkirmishAIs; - - for (sai = 0; sai < numSkirmishAIs; ++sai) { - if (jAIClassNames[sai] == NULL) { - firstFree = sai; - break; - } - } - - // sai is now either the instantiated one, or a free one - // instantiate AI (if not already instantiated) - assert(sai < maxSkirmishAIs); - - if (jAIClassNames[sai] == NULL) { - sai = firstFree; - java_establishJavaEnv(); - JNIEnv* env = java_getJNIEnv(false); - - jobject instance = NULL; - jobject classLoader = NULL; - - success = java_loadSkirmishAI(env, shortName, version, className, &instance, &classLoader); - java_establishSpringEnv(); - - if (success) { - jAIInstances[sai] = instance; - jAIClassLoaders[sai] = classLoader; - jAIClassNames[sai] = util_allocStrCpy(className); - - numSkirmishAIs += (firstFree == numSkirmishAIs); - } else { - simpleLog_logL(LOG_LEVEL_ERROR, "Class loading failed for class: %s", className); - } - } else { - success = true; - } - - if (success) - skirmishAIId_skirmishAiImpl[skirmishAIId] = sai; - - return success; -} - -bool java_releaseSkirmishAIClass(const char* className) -{ - // see if an AI for className is instantiated - size_t sai; - for (sai = 0; sai < numSkirmishAIs; ++sai) { - if (jAIClassNames[sai] == NULL) - continue; - if (strcmp(jAIClassNames[sai], className) == 0) - break; - } - - // sai is now either the instantiated one, or a free one - // release AI (if its instance was found) - assert(sai < maxSkirmishAIs); - - if (jAIClassNames[sai] == NULL) - return false; - - java_establishJavaEnv(); - JNIEnv* env = java_getJNIEnv(false); - - - // delete the AI class-loader global reference, - // so it will be garbage collected - bool successPart = jniUtil_deleteGlobalRef(env, jAIClassLoaders[sai], "AI class-loader"); - bool success = successPart; - - // delete the AI global reference, - // so it will be garbage collected - successPart = jniUtil_deleteGlobalRef(env, jAIInstances[sai], "AI instance"); - success = success && successPart; - - java_establishSpringEnv(); - - if (success) { - jAIClassLoaders[sai] = NULL; - jAIInstances[sai] = NULL; - - FREE(jAIClassNames[sai]); - - // if it is the last implementation - numSkirmishAIs -= ((sai + 1) == numSkirmishAIs); - } - - return success; -} - -bool java_releaseAllSkirmishAIClasses() -{ - bool success = true; - - const char* className = ""; - size_t sai; - - for (sai = 0; sai < numSkirmishAIs; ++sai) { - if ((className = jAIClassNames[sai]) == NULL) - continue; - - success = success && java_releaseSkirmishAIClass(className); - } - - return success; -} - - - -int java_skirmishAI_init(int skirmishAIId, const struct SSkirmishAICallback* aiCallback) -{ - int res = -1; - - java_establishJavaEnv(); - - JNIEnv* env = java_getJNIEnv(false); - jobject global_javaAICallback = java_createAICallback(env, aiCallback, skirmishAIId); - - if (global_javaAICallback != NULL) - res = eventsJniBridge_initAI(env, skirmishAIId, global_javaAICallback); - - java_establishSpringEnv(); - return res; -} - -int java_skirmishAI_release(int skirmishAIId) -{ - return 0; -} - -int java_skirmishAI_handleEvent(int skirmishAIId, int topic, const void* data) -{ - java_establishJavaEnv(); - - JNIEnv* env = java_getJNIEnv(false); - const size_t sai = skirmishAIId_skirmishAiImpl[skirmishAIId]; - jobject aiInstance = jAIInstances[sai]; - const int res = eventsJniBridge_handleEvent(env, aiInstance, skirmishAIId, topic, data); - - java_establishSpringEnv(); - return res; -} diff --git a/AI/Interfaces/Java/src/main/native/JavaBridge.h b/AI/Interfaces/Java/src/main/native/JavaBridge.h deleted file mode 100644 index d742f47ef38..00000000000 --- a/AI/Interfaces/Java/src/main/native/JavaBridge.h +++ /dev/null @@ -1,73 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#ifndef _JAVA_BRIDGE_H -#define _JAVA_BRIDGE_H - -#define JVM_PROPERTIES_FILE "jvm.properties" - -#define PKG_AI "com/springrts/ai/" -#define INT_AI PKG_AI"AI" -#define CLS_AI_CALLBACK PKG_AI"JniAICallback" - -// define path entry delimiter, used eg for the java class-path -#ifdef _WIN32 -#define ENTRY_DELIM ";" -#else -#define ENTRY_DELIM ":" -#endif -#define PATH_DELIM "/" - -#ifdef __cplusplus -extern "C" { -#endif - -#include // bool, true, false - -struct SAIInterfaceCallback; -struct SSkirmishAICallback; - -bool java_unloadJNIEnv(); - -bool java_initStatic(int interfaceId, const struct SAIInterfaceCallback* callback); -bool java_releaseStatic(); - -/** - * Instantiates an instance of the specified className. - * - * @param shortName further specifies the the AI to load - * @param version further specifies the the AI to load - * @param className fully qualified name of a Java class that implements - * interface com.springrts.ai.AI, eg: - * "com.myai.AI" - * @param teamId The team that will be using this AI. - * Multiple teams may use the same AI implementation. - * @return true, if the AI implementation is now loaded - */ -bool java_initSkirmishAIClass( - const char* const shortName, - const char* const version, - const char* const className, - int teamId -); - -/** - * Release the loaded AI specified through a class name. - * - * @param className fully qualified name of a Java class that implements - * interface com.springrts.ai.AI, eg: - * "com.myai.AI" - * @return true, if the AI implementation was loaded and is now - * successfully unloaded - */ -bool java_releaseSkirmishAIClass(const char* className); -bool java_releaseAllSkirmishAIClasses(); - -int java_skirmishAI_init(int teamId, const struct SSkirmishAICallback* callback); -int java_skirmishAI_release(int teamId); -int java_skirmishAI_handleEvent(int teamId, int topic, const void* data); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _JAVA_BRIDGE_H diff --git a/AI/Interfaces/Java/src/main/native/JniUtil.c b/AI/Interfaces/Java/src/main/native/JniUtil.c deleted file mode 100644 index 909afc70bd3..00000000000 --- a/AI/Interfaces/Java/src/main/native/JniUtil.c +++ /dev/null @@ -1,288 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#include "JniUtil.h" - -#include "CUtils/SimpleLog.h" - - -// JNI global vars -static jclass g_cls_url = NULL; -static jmethodID g_m_url_ctor = NULL; - -static jclass g_cls_urlClassLoader = NULL; -static jmethodID g_m_urlClassLoader_ctor = NULL; -static jmethodID g_m_urlClassLoader_findClass = NULL; - - -const char* jniUtil_getJniRetValDescription(const jint retVal) { - - switch (retVal) { - case JNI_OK: { return "JNI_OK - success"; break; } - case JNI_ERR: { return "JNI_ERR - unknown error"; break; } - case JNI_EDETACHED: { return "JNI_EDETACHED - thread detached from the VM"; break; } - case JNI_EVERSION: { return "JNI_EVERSION - JNI version error"; break; } -#ifdef JNI_ENOMEM - case JNI_ENOMEM: { return "JNI_ENOMEM - not enough (contiguous) memory"; break; } -#endif // JNI_ENOMEM -#ifdef JNI_EEXIST - case JNI_EEXIST: { return "JNI_EEXIST - VM already created"; break; } -#endif // JNI_EEXIST -#ifdef JNI_EINVAL - case JNI_EINVAL: { return "JNI_EINVAL - invalid arguments"; break; } -#endif // JNI_EINVAL - default: { return "UNKNOWN - unknown/invalid JNI return value"; break; } - } -} - -bool jniUtil_checkException(JNIEnv* env, const char* const errorMsg) { - - if ((*env)->ExceptionCheck(env)) { - simpleLog_logL(LOG_LEVEL_ERROR, errorMsg); - (*env)->ExceptionDescribe(env); - return true; - } - - return false; -} - -jclass jniUtil_findClass(JNIEnv* env, const char* const className) { - - jclass res = NULL; - - res = (*env)->FindClass(env, className); - const bool hasException = (*env)->ExceptionCheck(env); - if (res == NULL || hasException) { - simpleLog_logL(LOG_LEVEL_ERROR, "Class not found: \"%s\"", className); - if (hasException) { - (*env)->ExceptionDescribe(env); - } - res = NULL; - } - - return res; -} - -jobject jniUtil_makeGlobalRef(JNIEnv* env, jobject localObject, const char* objDesc) { - - jobject res = NULL; - - // Make the local class a global reference, - // so it will not be garbage collected, - // even after this method returned, - // but only if explicitly deleted with DeleteGlobalRef - res = (*env)->NewGlobalRef(env, localObject); - if ((*env)->ExceptionCheck(env)) { - simpleLog_logL(LOG_LEVEL_ERROR, - "Failed to make %s a global reference.", - ((objDesc == NULL) ? "" : objDesc)); - (*env)->ExceptionDescribe(env); - res = NULL; - } - - return res; -} - -bool jniUtil_deleteGlobalRef(JNIEnv* env, jobject globalObject, - const char* objDesc) { - - // delete the AI class-loader global reference, - // so it will be garbage collected - (*env)->DeleteGlobalRef(env, globalObject); - if ((*env)->ExceptionCheck(env)) { - simpleLog_logL(LOG_LEVEL_ERROR, - "Failed to delete global reference %s.", - ((objDesc == NULL) ? "" : objDesc)); - (*env)->ExceptionDescribe(env); - return false; - } - - return true; -} - -jmethodID jniUtil_getMethodID(JNIEnv* env, jclass cls, - const char* const name, const char* const signature) { - - jmethodID res = NULL; - - res = (*env)->GetMethodID(env, cls, name, signature); - const bool hasException = (*env)->ExceptionCheck(env); - if (res == NULL || hasException) { - simpleLog_logL(LOG_LEVEL_ERROR, "Method not found: %s(%s)", - name, signature); - if (hasException) { - (*env)->ExceptionDescribe(env); - } - res = NULL; - } - - return res; -} - -jmethodID jniUtil_getStaticMethodID(JNIEnv* env, jclass cls, - const char* const name, const char* const signature) { - - jmethodID res = NULL; - - res = (*env)->GetStaticMethodID(env, cls, name, signature); - const bool hasException = (*env)->ExceptionCheck(env); - if (res == NULL || hasException) { - simpleLog_logL(LOG_LEVEL_ERROR, "Method not found: %s(%s)", - name, signature); - if (hasException) { - (*env)->ExceptionDescribe(env); - } - res = NULL; - } - - return res; -} - - -static bool jniUtil_initURLClass(JNIEnv* env) { - - if (g_m_url_ctor == NULL) { - // get the URL class - static const char* const fcCls = "java/net/URL"; - - g_cls_url = jniUtil_findClass(env, fcCls); - if (g_cls_url == NULL) return false; - - g_cls_url = jniUtil_makeGlobalRef(env, g_cls_url, fcCls); - if (g_cls_url == NULL) return false; - - // get (String) constructor - g_m_url_ctor = jniUtil_getMethodID(env, g_cls_url, - "", "(Ljava/lang/String;)V"); - if (g_m_url_ctor == NULL) return false; - } - - return true; -} -jobject jniUtil_createURLObject(JNIEnv* env, const char* const url) { - - jobject jurl = NULL; - - bool ok = true; - if (g_cls_url == NULL) { - ok = jniUtil_initURLClass(env); - } - - if (ok) { - jstring jstrUrl = (*env)->NewStringUTF(env, url); - if (jniUtil_checkException(env, "Failed creating Java String.")) { jstrUrl = NULL; } - if (jstrUrl != NULL) { - jurl = (*env)->NewObject(env, g_cls_url, g_m_url_ctor, jstrUrl); - if (jniUtil_checkException(env, "Failed creating Java URL.")) { jurl = NULL; } - } - } else { - simpleLog_logL(LOG_LEVEL_ERROR, - "Failed creating Java URL; URL class not initialized."); - } - - return jurl; -} -jobjectArray jniUtil_createURLArray(JNIEnv* env, size_t size) { - - jobjectArray jurlArr = NULL; - - bool ok = true; - if (g_cls_url == NULL) { - ok = jniUtil_initURLClass(env); - } - - if (ok) { - jurlArr = (*env)->NewObjectArray(env, size, g_cls_url, NULL); - if (jniUtil_checkException(env, "Failed creating URL[].")) { jurlArr = NULL; } - } else { - simpleLog_logL(LOG_LEVEL_ERROR, - "Failed creating Java URL[]; URL class not initialized."); - } - - return jurlArr; -} -bool jniUtil_insertURLIntoArray(JNIEnv* env, jobjectArray arr, size_t index, jobject url) { - - bool ok = true; - - (*env)->SetObjectArrayElement(env, arr, index, url); - if (jniUtil_checkException(env, "Failed inserting Java URL into array.")) { ok = false; } - - return ok; -} - -static bool jniUtil_initURLClassLoaderClass(JNIEnv* env) { - - if (g_m_urlClassLoader_findClass == NULL) { - // get the URLClassLoader class - static const char* const fcCls = "java/net/URLClassLoader"; - - g_cls_urlClassLoader = jniUtil_findClass(env, fcCls); - if (g_cls_urlClassLoader == NULL) return false; - - g_cls_urlClassLoader = - jniUtil_makeGlobalRef(env, g_cls_urlClassLoader, fcCls); - if (g_cls_urlClassLoader == NULL) return false; - - // get (URL[]) constructor - g_m_urlClassLoader_ctor = jniUtil_getMethodID(env, - g_cls_urlClassLoader, "", "([Ljava/net/URL;)V"); - if (g_m_urlClassLoader_ctor == NULL) return false; - - // get the findClass(String) method - g_m_urlClassLoader_findClass = jniUtil_getMethodID(env, - g_cls_urlClassLoader, "findClass", - "(Ljava/lang/String;)Ljava/lang/Class;"); - if (g_m_urlClassLoader_findClass == NULL) return false; - } - - return true; -} -jobject jniUtil_createURLClassLoader(JNIEnv* env, jobject urlArray) { - - jobject classLoader = NULL; - - bool ok = true; - if (g_m_urlClassLoader_ctor == NULL) { - ok = jniUtil_initURLClassLoaderClass(env); - } - - if (ok) { - classLoader = (*env)->NewObject(env, g_cls_urlClassLoader, g_m_urlClassLoader_ctor, urlArray); - if (jniUtil_checkException(env, "Failed creating class-loader.")) { return NULL; } - } else { - simpleLog_logL(LOG_LEVEL_ERROR, - "Failed creating class-loader; class-loader class not initialized."); - } - - return classLoader; -} -jclass jniUtil_findClassThroughLoader(JNIEnv* env, jobject classLoader, const char* const className) { - - jclass cls = NULL; - - bool ok = true; - if (g_m_urlClassLoader_findClass == NULL) { - ok = jniUtil_initURLClassLoaderClass(env); - } - - if (ok) { - //cls = (*env)->FindClass(env, classNameP); - jstring jstr_className = (*env)->NewStringUTF(env, className); - cls = (*env)->CallObjectMethod(env, classLoader, g_m_urlClassLoader_findClass, jstr_className); - const bool hasException = (*env)->ExceptionCheck(env); - if (cls == NULL || hasException) { - simpleLog_logL(LOG_LEVEL_ERROR, - "Class not found \"%s\"", className); - if (hasException) { - (*env)->ExceptionDescribe(env); - } - cls = NULL; - } - } else { - simpleLog_logL(LOG_LEVEL_ERROR, - "Failed finding class; class-loader class not initialized."); - } - - return cls; -} - diff --git a/AI/Interfaces/Java/src/main/native/JniUtil.h b/AI/Interfaces/Java/src/main/native/JniUtil.h deleted file mode 100644 index 336f2fc4f1e..00000000000 --- a/AI/Interfaces/Java/src/main/native/JniUtil.h +++ /dev/null @@ -1,80 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#ifndef _JNI_UTIL_H -#define _JNI_UTIL_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include // bool, true, false - -#include - -/** - * Takes a JNI function return value, and returns a short description for it. - * This can be used for getting a human readable string describing the - * return value of functions like AttachCurrentThread() and CreateJavaVM(). - * - * @return a short description for a JNI function return value - */ -const char* jniUtil_getJniRetValDescription(const jint retVal); - -/** - * Handles a possible JNI/Java exception. - * In case an exception is present, the supplied error message is written to - * the log file, and the whole exception info is written to stderr. - * - * @return true, if there was an exception - */ -bool jniUtil_checkException(JNIEnv* env, const char* const errorMsg); - -/** - * Tries to find a Java class. - * - * @return a local reference to the class if found, NULL otherwise - */ -jclass jniUtil_findClass(JNIEnv* env, const char* const className); - -/** - * Converts a local to a global reference. - * As jclass inherits from jobject, this can be used for jclass too. - * - * @return the global reference to localObject on success, NULL otherwise - */ -jobject jniUtil_makeGlobalRef(JNIEnv* env, jobject localObject, const char* objDesc); - -/** - * Deletes a global reference to an object. - * As jclass inherits from jobject, this can be used for jclass too. - * - * @return true on success, false if an error occurred - */ -bool jniUtil_deleteGlobalRef(JNIEnv* env, jobject globalObject, const char* objDesc); - -/** - * Retrieves a reference ID for calling a Java object method. - * - * @return the method ID on success, NULL otherwise - */ -jmethodID jniUtil_getMethodID(JNIEnv* env, jclass cls, const char* const name, const char* const signature); - -/** - * Retrieves a reference ID for calling a Java static method. - * - * @return the method ID on success, NULL otherwise - */ -jmethodID jniUtil_getStaticMethodID(JNIEnv* env, jclass cls, const char* const name, const char* const signature); - -jobject jniUtil_createURLObject(JNIEnv* env, const char* const url); -jobjectArray jniUtil_createURLArray(JNIEnv* env, size_t size); -bool jniUtil_insertURLIntoArray(JNIEnv* env, jobjectArray arr, size_t index, jobject url); - -jobject jniUtil_createURLClassLoader(JNIEnv* env, jobject urlArray); -jclass jniUtil_findClassThroughLoader(JNIEnv* env, jobject classLoader, const char* const className); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _JNI_UTIL_H diff --git a/AI/Interfaces/Java/src/main/native/JvmLocater.h b/AI/Interfaces/Java/src/main/native/JvmLocater.h deleted file mode 100644 index 5032991d6a0..00000000000 --- a/AI/Interfaces/Java/src/main/native/JvmLocater.h +++ /dev/null @@ -1,53 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#ifndef _JVM_LOCATER_H -#define _JVM_LOCATER_H - -#if !defined bool -#include -#endif -#if !defined size_t -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Returns the arch dir name, used eg here: - * .../jre/lib/${arch}/client/libjvm.so - * - * @return sparc, sparcv9, i386, amd64 or ia64 (windows only) - */ -const char* GetArchPath(); - -/* - * Given a JRE location and a JVM type, construct what the name the - * JVM shared library will be. - * - * @param jvmType "/", "\\", "client", "server" - * @param arch see GetArchPath(), use NULL for the default value - * @return true, if the JVM library was found, false otherwise. - */ -bool GetJVMPath(const char* jrePath, const char* jvmType, - char* jvmPath, size_t jvmPathSize, const char* arch); - -/** - * Find the path to a JRE install dir, using platform dependent means. - * - * @param path path of the JRE installation - * @param pathSize size of the path parameter - * @param configFile path to a simple text file containing only a path to the - * JRE installation to use, or NULL - * @param arch see GetArchPath(), use NULL for the default value - * @return true, if a JRE was found, false otherwise. - */ -bool GetJREPath(char* path, size_t pathSize, const char* configFile, - const char* arch); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _JVM_LOCATER_H diff --git a/AI/Interfaces/Java/src/main/native/JvmLocater_common.c b/AI/Interfaces/Java/src/main/native/JvmLocater_common.c deleted file mode 100644 index a85f9d87a95..00000000000 --- a/AI/Interfaces/Java/src/main/native/JvmLocater_common.c +++ /dev/null @@ -1,188 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#include -#include -#include -#include -#include - -#include "CUtils/Util.h" - -#include "JvmLocater.h" - -#define MAXPATHLEN 2048 -#define JRE_PATH_PROPERTY "jre.path" - -#include // for CHAR_BIT -#define CURRENT_DATA_MODEL (CHAR_BIT * sizeof(void*)) - -#include "CUtils/SimpleLog.h" -#include "System/MainDefines.h" -#include "System/SafeCStrings.h" - -// implemented in the OS specific files -const char* GetArchPath(); -bool GetJREPathFromBase(char* path, size_t pathSize, const char* basePath, - const char* arch); -bool GetJREPathOSSpecific(char* path, size_t pathSize, const char* arch); - -bool FileExists(const char* filePath) -{ - struct stat s; - return (stat(filePath, &s) == 0); -} - -//#define LOC_PROP_FILE -bool GetJREPathFromConfig(char* path, size_t pathSize, const char* configFile) -{ -#if defined LOC_PROP_FILE - // assume the config file is in properties file format - // and that the property JRE_PATH_PROPERTY contains - // the absolute path to the JRE to use - static const size_t props_sizeMax = 64; - - const char* props_keys[props_sizeMax]; - const char* props_values[props_sizeMax]; - - const size_t props_size = util_parsePropertiesFile(configFile, props_keys, - props_values, props_sizeMax); - - const char* jvmLocation = util_map_getValueByKey( - props_size, props_keys, props_values, - JRE_PATH_PROPERTY); - - if (jvmLocation == NULL) { - simpleLog_logL(LOG_LEVEL_DEBUG, "JRE not found in config file!"); - return false; - } else { - simpleLog_logL(LOG_LEVEL_NOTICE, "JRE found in config file!"); - STRCPY_T(path, pathSize, jvmLocation); - return true; - } -#else // defined LOC_PROP_FILE - // assume the config file is a plain text file containing nothing but - // the absolute path to the JRE to use in the first line - - bool found = false; - - FILE* cfp = fopen(configFile, "r"); - if (cfp == NULL) { - return found; - } - - // parse results - static const size_t line_sizeMax = 1024; - char line[line_sizeMax]; - if (fgets(line, line_sizeMax, cfp)) { - size_t line_size = strlen(line); - if (*(line+line_size-1) == '\n') { - // remove trailing '\n' - *(line+line_size-1) = '\0'; - line_size--; - } - - simpleLog_logL(LOG_LEVEL_NOTICE, - "Fetched JRE location from \"%s\"!", configFile); - - if (line_size > 0 && *line == '/') { - *(line+line_size-1) = '\0'; // remove trailing '/' - } - STRCPY_T(path, pathSize, line); - found = true; - } - fclose(cfp); - - return found; -#endif // defined LOC_PROP_FILE -} - - -bool GetJREPathFromEnvVars(char* path, size_t pathSize, const char* arch) -{ - bool found = false; - - static const size_t possLoc_sizeMax = 32; - char* possLoc[possLoc_sizeMax]; - size_t possLoc_i = 0; - - possLoc[possLoc_i++] = util_allocStrCpy("JAVA_HOME"); - possLoc[possLoc_i++] = util_allocStrCpy("JDK_HOME"); - possLoc[possLoc_i++] = util_allocStrCpy("JRE_HOME"); - - size_t l; - for (l=0; l < possLoc_i; ++l) { - const char* envPath = getenv(possLoc[l]); - if (envPath != NULL) { - found = GetJREPathFromBase(path, pathSize, envPath, arch); - if (found) { - simpleLog_logL(LOG_LEVEL_NOTICE, "JRE found in env var \"%s\"!", possLoc[l]); - goto locSearchEnd; - } else { - simpleLog_logL(LOG_LEVEL_WARNING, "Unusable JRE from env var \"%s\"=\"%s\"!", possLoc[l], envPath); - } - } - } - locSearchEnd: - - // cleanup - for (l=0; l < possLoc_i; ++l) { - free(possLoc[l]); - possLoc[l] = NULL; - } - - return found; -} - - - -bool GetJREPath(char* path, size_t pathSize, const char* configFile, - const char* arch) -{ - bool found = false; - - if (arch == NULL) { - arch = GetArchPath(); - } - - // check if a JRE location is specified in the config file - if (!found && configFile != NULL) { - found = GetJREPathFromConfig(path, pathSize, configFile); - } - - // check if a JRE is specified in an ENV var (eg. JAVA_HOME) - if (!found) { - found = GetJREPathFromEnvVars(path, pathSize, arch); - } - - // check if a JRE is located in a common location - if (!found) { - found = GetJREPathOSSpecific(path, pathSize, arch); - } - - return found; -} - -int main(int argc, const char* argv[]) { - - //simpleLog_init(NULL, false, LOG_LEVEL_DEBUG, false); - - static const size_t path_sizeMax = 1024; - char path[path_sizeMax]; - bool found = GetJREPath(path, path_sizeMax, NULL, NULL); - if (found) { - printf("JRE found: %s\n", path); - - static const size_t jvmPath_sizeMax = 1024; - char jvmPath[jvmPath_sizeMax]; - bool jvmFound = GetJVMPath(path, "client", jvmPath, jvmPath_sizeMax, NULL); - if (jvmFound) { - printf("JVM found: %s\n", jvmPath); - } else { - printf("JVM not found.\n"); - } - } else { - printf("JRE not found.\n"); - } - - return 0; -} diff --git a/AI/Interfaces/Java/src/main/native/JvmLocater_common.h b/AI/Interfaces/Java/src/main/native/JvmLocater_common.h deleted file mode 100644 index 45d81c2b9ac..00000000000 --- a/AI/Interfaces/Java/src/main/native/JvmLocater_common.h +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#ifndef _JVM_LOCATER_COMMON_H -#define _JVM_LOCATER_COMMON_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "JvmLocater.h" - -#include -#include -#include -#include -#include -#include // for CHAR_BIT - -#include "CUtils/Util.h" -#include "CUtils/SimpleLog.h" - -#define MAXPATHLEN 2048 -#define JRE_PATH_PROPERTY "jre.path" -#define CURRENT_DATA_MODEL (CHAR_BIT * sizeof(void*)) - - -bool FileExists(const char* filePath); - -bool GetJREPathFromEnvVars(char* path, size_t pathSize, const char* arch); - -bool GetJREPath(char* path, size_t pathSize, const char* configFile, - const char* arch); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _JVM_LOCATER_COMMON_H diff --git a/AI/Interfaces/Java/src/main/native/JvmLocater_linux.c b/AI/Interfaces/Java/src/main/native/JvmLocater_linux.c deleted file mode 100644 index ef1896be34b..00000000000 --- a/AI/Interfaces/Java/src/main/native/JvmLocater_linux.c +++ /dev/null @@ -1,266 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#if !defined _WIN32 - -#include "JvmLocater_common.h" - -#include "System/MainDefines.h" -#include "System/SafeCStrings.h" - -#include - - -#if defined APPLE -#define JVM_LIB "libjvm.dylib" -#else -#define JVM_LIB "libjvm.so" -#endif - -#if defined APPLE -#define JAVA_LIB "libjava.dylib" -#else -#define JAVA_LIB "libjava.so" -#endif - -#ifdef SPARC -# define LIBARCH32NAME "sparc" -# define LIBARCH64NAME "sparcv9" -#else // not SPARC -> LINUX or APPLE -# define LIBARCH32NAME "i386" -# define LIBARCH64NAME "amd64" -#endif // SPARC -#if defined __arch64__ -# define LIBARCHNAME LIBARCH64NAME -#else // defined __arch64__ -# define LIBARCHNAME LIBARCH32NAME -#endif // defined __arch64__ -//LIBARCH32 solaris only: sparc or i386 -//LIBARCH64 solaris only: sparcv9 or amd64 -//LIBARCH sparc, sparcv9, i386, amd64, or ia64 // last one is windows only - - -const char* GetArchPath() -{ - switch(CURRENT_DATA_MODEL) { -#ifdef DUAL_MODE - case 32: - return LIBARCH32NAME; - case 64: - return LIBARCH64NAME; -#endif // DUAL_MODE - default: - return LIBARCHNAME; - } -} - -/* - * On Solaris VM choosing is done by the launcher (java.c). - */ -bool GetJVMPath(const char* jrePath, const char* jvmType, - char* jvmPath, size_t jvmPathSize, const char* arch) -{ - if (arch == NULL) { - arch = GetArchPath(); - } - - if (*jvmType == '/') { - SNPRINTF(jvmPath, jvmPathSize, "%s/"JVM_LIB, jvmType); - } else { - SNPRINTF(jvmPath, jvmPathSize, "%s/lib/%s/%s/"JVM_LIB, jrePath, arch, - jvmType); - } - - return FileExists(jvmPath); -} - - -static bool CheckIfJREPath(const char* path, const char* arch) -{ - bool found = false; - - if (path != NULL) { - char libJava[MAXPATHLEN]; - - // Is path a JRE path? - SNPRINTF(libJava, MAXPATHLEN, "%s/lib/%s/"JAVA_LIB, path, arch); - if (access(libJava, F_OK) == 0) { - found = true; - } - } - - return found; -} - -bool GetJREPathFromBase(char* path, size_t pathSize, const char* basePath, - const char* arch) -{ - bool found = false; - - if (basePath != NULL) { - char jrePath[MAXPATHLEN]; - - // Is basePath a JRE path? - STRCPY_T(jrePath, MAXPATHLEN, basePath); - if (CheckIfJREPath(jrePath, arch)) { - STRCPY_T(path, pathSize, basePath); - found = true; - } - - // Is basePath/jre a JRE path? - STRCAT_T(jrePath, MAXPATHLEN, "/jre"); - if (CheckIfJREPath(jrePath, arch)) { - STRCPY_T(path, pathSize, jrePath); - found = true; - } - } - - return found; -} - -static size_t ExecFileSystemGlob(char** pathHits, size_t pathHits_sizeMax, - const char* globPattern) -{ - size_t pathHits_size = 0; - - // assemble the command - static const size_t cmd_sizeMax = 512; - char cmd[cmd_sizeMax]; - SNPRINTF(cmd, cmd_sizeMax, "find %s/ -maxdepth 0 2> /dev/null", globPattern); - - // execute - FILE* cmd_fp = popen(cmd, "r"); - if (cmd_fp == NULL) { - return pathHits_size; - } - - // parse results - static const size_t line_sizeMax = 512; - char line[line_sizeMax]; - while (fgets(line, line_sizeMax, cmd_fp) && (pathHits_size < pathHits_sizeMax)) { - size_t line_size = strlen(line); - if (*(line+line_size-1) == '\n') { - // remove trailing '\n' - *(line+line_size-1) = '\0'; - line_size--; - } - - simpleLog_logL(LOG_LEVEL_DEBUG, - "glob-hit \"%s\"!", line); - - if (line_size > 0 && *line == '/') { - *(line+line_size-1) = '\0'; // remove trailing '/' - pathHits[pathHits_size++] = util_allocStrCpy(line); - } - } - pclose(cmd_fp); - - return pathHits_size; -} -static bool GetJREPathInCommonLocations(char* path, size_t pathSize, const char* arch) -{ - bool found = false; - - static const size_t possLoc_sizeMax = 32; - char* possLoc[possLoc_sizeMax]; - size_t possLoc_i = 0; - - possLoc[possLoc_i++] = util_allocStrCpy("/usr/local/jdk*"); - possLoc[possLoc_i++] = util_allocStrCpy("/usr/lib/jvm/default-java"); - possLoc[possLoc_i++] = util_allocStrCpy("/usr/lib/jvm/java-?-sun"); - possLoc[possLoc_i++] = util_allocStrCpy("/usr/lib/jvm/java-?-*"); - possLoc[possLoc_i++] = util_allocStrCpy("~/jdk*"); - possLoc[possLoc_i++] = util_allocStrCpy("~/bin/jdk*"); - possLoc[possLoc_i++] = util_allocStrCpy("~/jre*"); - possLoc[possLoc_i++] = util_allocStrCpy("~/bin/jre*"); - - static const size_t globHits_sizeMax = 32; - char* globHits[globHits_sizeMax]; - size_t l, g; - for (l=0; l < possLoc_i; ++l) { - const size_t globHits_size = ExecFileSystemGlob(globHits, globHits_sizeMax, possLoc[l]); - for (g=0; g < globHits_size; ++g) { - found = GetJREPathFromBase(path, pathSize, globHits[g], arch); - if (found) { - simpleLog_logL(LOG_LEVEL_NOTICE, - "JRE found common location env var \"%s\"!", - possLoc[l]); - goto locSearchEnd; - } - } - } - locSearchEnd: - - // cleanup - for (l=0; l < possLoc_i; ++l) { - free(possLoc[l]); - possLoc[l] = NULL; - } - - return found; -} - -static bool GetJREPathWhichJava(char* path, size_t pathSize, const char* arch) -{ - static const char* suf = "/bin/java"; - const size_t suf_size = strlen(suf); - - bool found = false; - - // execute - FILE* cmd_fp = popen("which java | sed 's/[\\n\\r]/K/g'", "r"); - if (cmd_fp == NULL) { - return found; - } - - // parse results - static const size_t line_sizeMax = 512; - char line[line_sizeMax]; - if (fgets(line, line_sizeMax, cmd_fp)) { - if (*line == '/') { // -> absolute path - size_t line_size = strlen(line); - if (*(line+line_size-1) == '\n') { - // remove trailing '\n' - *(line+line_size-1) = '\0'; - line_size--; - } - - simpleLog_logL(LOG_LEVEL_DEBUG, - "which line \"%s\"!", line); - - if (line_size > suf_size - && strcmp(line+(line_size-suf_size), suf) == 0) { - // line ends with suf - simpleLog_logL(LOG_LEVEL_NOTICE, - "JRE found with `which java`!"); - // remove suf - *(line+(line_size-suf_size)) = '\0'; - found = GetJREPathFromBase(path, pathSize, line, arch); - } - } - } - pclose(cmd_fp); - - return found; -} - -/* - * Find path to JRE based on .exe's location or registry settings. - */ -bool GetJREPathOSSpecific(char* path, size_t pathSize, const char* arch) -{ - bool found = false; - - // check if a JRE is located in a common location - if (!found) { - found = GetJREPathInCommonLocations(path, pathSize, arch); - } - - // check if a JRE is located in a common location - if (!found) { - found = GetJREPathWhichJava(path, pathSize, arch); - } - - return found; -} - -#endif // !defined _WIN32 diff --git a/AI/Interfaces/Java/src/main/native/JvmLocater_windows.c b/AI/Interfaces/Java/src/main/native/JvmLocater_windows.c deleted file mode 100644 index 6bb5367f2b6..00000000000 --- a/AI/Interfaces/Java/src/main/native/JvmLocater_windows.c +++ /dev/null @@ -1,181 +0,0 @@ -/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ - -#if defined _WIN32 - -#include "JvmLocater_common.h" - -#include "System/MainDefines.h" -#include "System/SafeCStrings.h" - -#include -#include -#include - - -#define JVM_LIB "jvm.dll" - -#define JAVA_LIB "java.dll" - -/* - * Returns the arch path, to get the current arch use the - * macro GetArch, nbits here is ignored for now. - */ -const char* GetArchPath() -{ -#ifdef _M_AMD64 - return "amd64"; -#elif defined(_M_IA64) - return "ia64"; -#else - return "i386"; -#endif -} - -/* - * Given a JRE location and a JVM type, construct what the name the - * JVM shared library will be. Return true, if such a library - * exists, false otherwise. - */ -bool GetJVMPath(const char* jrePath, const char* jvmType, - char* jvmPath, size_t jvmPathSize, const char* arch) -{ - if (arch == NULL) { - arch = GetArchPath(); - } - - if ((*jvmType == '/') || (*jvmType == '\\')) { - SNPRINTF(jvmPath, jvmPathSize, "%s\\"JVM_LIB, jvmType); - } else { - SNPRINTF(jvmPath, jvmPathSize, "%s\\bin\\%s\\"JVM_LIB, jrePath, - jvmType); - } - - return FileExists(jvmPath); -} - -static bool CheckIfJREPath(const char* path, const char* arch) -{ - bool found = false; - - if (path != NULL) { - char libJava[MAXPATHLEN]; - - // Is path a JRE path? - SNPRINTF(libJava, MAXPATHLEN, "%s\\bin\\"JAVA_LIB, path); - if (FileExists(libJava)) { - found = true; - } - } - - return found; -} - -bool GetJREPathFromBase(char* path, size_t pathSize, const char* basePath, - const char* arch) -{ - bool found = false; - - if (basePath != NULL) { - //if (GetApplicationHome(path, pathSize)) { - char jrePath[MAXPATHLEN]; - - // Is basePath a JRE path? - STRCPY_T(jrePath, MAXPATHLEN, basePath); - if (CheckIfJREPath(jrePath, arch)) { - STRCPY_T(path, pathSize, basePath); - found = true; - } - - // Is basePath/jre a JRE path? - STRCAT_T(jrePath, MAXPATHLEN, "\\jre"); - if (CheckIfJREPath(jrePath, arch)) { - STRCPY_T(path, pathSize, jrePath); - found = true; - } - } - - return found; -} - -/* - * Helpers to look in the registry for a public JRE. - */ - -/* Same for 1.5.0, 1.5.1, 1.5.2 etc. */ -#define JRE_REG_KEY "Software\\JavaSoft\\Java Runtime Environment" - -static bool GetStringFromRegistry(HKEY key, const char* name, char* buf, - size_t bufSize) -{ - DWORD type, size; - - if (RegQueryValueEx(key, name, 0, &type, 0, &size) == 0 - && type == REG_SZ - && (size < bufSize)) { - if (RegQueryValueEx(key, name, 0, 0, (LPBYTE)buf, &size) == 0) { - return true; - } - } - return false; -} - -static bool GetJREPathFromRegistry(char* path, size_t pathSize, const char* arch) -{ - HKEY key, subkey; - char version[MAXPATHLEN]; - - /* - * Note: There is a very similar implementation of the following - * registry reading code in the Windows java control panel (javacp.cpl). - * If there are bugs here, a similar bug probably exists there. Hence, - * changes here require inspection there. - */ - - // Find the current version of the JRE - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_REG_KEY, 0, KEY_READ, &key) != 0) { - return false; - } - - if (!GetStringFromRegistry(key, "CurrentVersion", - version, sizeof(version))) { - RegCloseKey(key); - return false; - } - - /*if (strcmp(version, wantedVersion) != 0) { - RegCloseKey(key); - return false; - }*/ - - // Find directory where the current version is installed. - if (RegOpenKeyEx(key, version, 0, KEY_READ, &subkey) != 0) { - RegCloseKey(key); - return false; - } - - if (!GetStringFromRegistry(subkey, "JavaHome", path, pathSize)) { - RegCloseKey(key); - RegCloseKey(subkey); - return false; - } - - RegCloseKey(key); - RegCloseKey(subkey); - - simpleLog_logL(LOG_LEVEL_NOTICE, "JRE found in registry!"); - return true; -} - -bool GetJREPathOSSpecific(char* path, size_t pathSize, const char* arch) -{ - bool found = false; - - // check if a JRE is specified in the registry - if (!found) { - found = GetJREPathFromRegistry(path, pathSize, arch); - } - - return found; -} - -#endif // defined _WIN32 diff --git a/AI/Skirmish/NullJavaAI/CMakeLists.txt b/AI/Skirmish/NullJavaAI/CMakeLists.txt deleted file mode 100644 index ffac49c05b4..00000000000 --- a/AI/Skirmish/NullJavaAI/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -### Generic Java Skirmish AI config -# - -configure_java_skirmish_ai("") diff --git a/AI/Skirmish/NullJavaAI/VERSION b/AI/Skirmish/NullJavaAI/VERSION deleted file mode 100644 index ceab6e11ece..00000000000 --- a/AI/Skirmish/NullJavaAI/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.1 \ No newline at end of file diff --git a/AI/Skirmish/NullJavaAI/bin/ant.dependent.properties b/AI/Skirmish/NullJavaAI/bin/ant.dependent.properties deleted file mode 100644 index 559cacc4e54..00000000000 --- a/AI/Skirmish/NullJavaAI/bin/ant.dependent.properties +++ /dev/null @@ -1,36 +0,0 @@ -# properties file for spring Java Skirmish AIs -# This is used when you do not use the spring repository for compiling. -# -# Paths are relative to the project home (which is ../ from this file). -# All values are optional, and listed here with their defaults. -# -# The default assumes that you have the spring source, -# and do a spring in-source build as it is the default with CMake and SCons, -# and as the buildbot does it. -# -# build-dir: ${spring.home}/AI/Skirmish/${ai.name}/ -# install-dir: ${spring.home}/dist/AI/Skirmish/${ai.name}/${ai.version}/ -# -# This file is loaded from within build.xml, -# but only if no "jlibs-interface/" dir is present. -# - -;spring.home=../../.. - -# This is used only in the next property -;build.home=${spring.home} -# Where jar files will be built -;build.dir=${build.home}/AI/Skirmish/${skirmish.ai.name} - -# This is used only in the next property -;dist.home=${spring.home}/dist -# Where jar files will be installed to -;dist.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version} -# Where HTML JavaDoc files will be generated -;doc.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version}/doc/jdoc - -# The following two are needed for compiling (to create the classpath) -# * Here we look for ./jlib/*.jar recursively -;ai.interface.src.home=${spring.home}/AI/Interfaces/Java -# * Here we look for AIInterface.jar -;ai.interface.build.home=${build.home}/AI/Interfaces/Java diff --git a/AI/Skirmish/NullJavaAI/bin/ant.independent.properties b/AI/Skirmish/NullJavaAI/bin/ant.independent.properties deleted file mode 100644 index 129a1589a21..00000000000 --- a/AI/Skirmish/NullJavaAI/bin/ant.independent.properties +++ /dev/null @@ -1,29 +0,0 @@ -# properties file for spring Java Skirmish AIs -# This is used when you do not use the spring repository for compiling. -# -# Paths are relative to the project home (which is ../ from this file). -# All values are optional, and listed here with their defaults. -# -# For the project, you do not need the spring sources, -# but you will need the "jlibs-interface/" instead, which contains -# the Java AI Interfaces jlibs plus its binary and source jar. -# -# build-dir: build/ -# install-dir: dist/ -# -# This file is loaded from within build.xml, -# but only if a "jlibs-interface/" dir is present. -# - -# This is used only in the next property -;build.home=build -# Where jar files will be built -;build.dir=${build.home} - -# This is used only in the next property. -# You will want to set dist.home to your spring install dir. -;dist.home=dist -# Where jar files will be installed to -;dist.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version} -# Where HTML JavaDoc files will be generated -;doc.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version}/doc/jdoc diff --git a/AI/Skirmish/NullJavaAI/bin/build.xml b/AI/Skirmish/NullJavaAI/bin/build.xml deleted file mode 100644 index 8d3b185b6bf..00000000000 --- a/AI/Skirmish/NullJavaAI/bin/build.xml +++ /dev/null @@ -1,279 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . -File not found: ${ai.interface.jar} -Please make sure to compile the Java AI Interface -before trying to compile this AI, or request -an independent version of this project from -wherever you got this AI from. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Successfully bumped ${skirmish.ai.name} version from ${skirmish.ai.version} to ${skirmish.ai.version.new}. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . -Please specify either home.new or name.new, for example: - ant create-independent -Dhome.new=~/projects/SpringSkirmishAIs/ -or - ant create-independent -Dname.new=MyJavaAI - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Spring source independant Java Skirmish AI project copied to: - ${project.dir.new} - -You may want to change your java source package structure -and the data/AIInto.lua file for the new project. - - - - - - - - - - - - - - - - - diff --git a/AI/Skirmish/NullJavaAI/data/AIInfo.lua b/AI/Skirmish/NullJavaAI/data/AIInfo.lua deleted file mode 100644 index 75f19a8632b..00000000000 --- a/AI/Skirmish/NullJavaAI/data/AIInfo.lua +++ /dev/null @@ -1,53 +0,0 @@ --- --- Info Definition Table format --- --- --- These keywords must be lowercase for LuaParser to read them. --- --- key: user defined or one of the SKIRMISH_AI_PROPERTY_* defines in --- SSkirmishAILibrary.h --- value: the value of the property --- desc: the description (could be used as a tooltip) --- --- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local infos = { - { - key = 'shortName', - value = 'NullJavaAI', - desc = 'machine conform name.', - }, - { - key = 'version', - value = '0.1', -- AI version - !This comment is used for parsing! - }, - { - key = 'className', - value = 'nulljavaai.NullJavaAI', - desc = 'fully qualified name of a class that implements interface com.springrts.ai.AI', - }, - { - key = 'name', - value = 'low-level Java test Skirmish AI', - desc = 'human readable name.', - }, - { - key = 'loadSupported', - value = 'no', - desc = 'whether this AI supports loading or not', - }, - { - key = 'interfaceShortName', - value = 'Java', -- AI Interface name - !This comment is used for parsing! - desc = 'the shortName of the AI interface this AI needs', - }, - { - key = 'interfaceVersion', - value = '0.1', -- AI Interface version - !This comment is used for parsing! - desc = 'the minimum version of the AI interface required by this AI', - }, -} - -return infos diff --git a/AI/Skirmish/NullJavaAI/data/AIOptions.lua b/AI/Skirmish/NullJavaAI/data/AIOptions.lua deleted file mode 100644 index d435d62e964..00000000000 --- a/AI/Skirmish/NullJavaAI/data/AIOptions.lua +++ /dev/null @@ -1,15 +0,0 @@ --- --- Custom Options Definition Table format --- --- A detailed example of how this format works can be found --- in the spring source under: --- AI/Skirmish/NullAI/data/AIOptions.lua --- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local options = { -} - -return options - diff --git a/AI/Skirmish/NullJavaAI/manifest.mf b/AI/Skirmish/NullJavaAI/manifest.mf deleted file mode 100755 index 59499bce4a2..00000000000 --- a/AI/Skirmish/NullJavaAI/manifest.mf +++ /dev/null @@ -1,2 +0,0 @@ -Manifest-Version: 1.0 - diff --git a/AI/Skirmish/NullJavaAI/src/nulljavaai/NullJavaAI.java b/AI/Skirmish/NullJavaAI/src/nulljavaai/NullJavaAI.java deleted file mode 100644 index 41c42c6c235..00000000000 --- a/AI/Skirmish/NullJavaAI/src/nulljavaai/NullJavaAI.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - Copyright (c) 2008 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package nulljavaai; - - -import com.springrts.ai.*; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.logging.*; - -/** - * Serves as Interface for a Java Skirmish AIs for the Spring engine. - * - * @author hoijui - * @version 0.1 - */ -public class NullJavaAI extends AbstractAI implements AI { - - private int skirmishAIId = -1; - private AICallback clb = null; - private String myLogFile = null; - private Logger log = null; - private int frame = -1; - - private static class MyCustomLogFormatter extends Formatter { - - private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS dd.MM.yyyy"); - - public String format(LogRecord record) { - - // Create a StringBuffer to contain the formatted record - // start with the date. - StringBuffer sb = new StringBuffer(); - - // Get the date from the LogRecord and add it to the buffer - Date date = new Date(record.getMillis()); - sb.append(dateFormat.format(date)); - sb.append(" "); - - // Get the level name and add it to the buffer - sb.append(record.getLevel().getName()); - sb.append(": "); - - // Get the formatted message (includes localization - // and substitution of parameters) and add it to the buffer - sb.append(formatMessage(record)); - sb.append("\n"); - - return sb.toString(); - } - } - - public static boolean isDebugging() { - return true; - } - - public NullJavaAI() {} - - - @Override - public int init(int skirmishAIId, AICallback callback) { - - int ret = -1; - - this.clb = callback; - - // initialize the log - try { - int teamId = clb.SkirmishAI_getTeamId(); - myLogFile = callback.DataDirs_locatePath("log-team-" + teamId + "-" + skirmishAIId + ".txt", true, true, false, false); - FileHandler fileLogger = new FileHandler(myLogFile, false); - fileLogger.setFormatter(new MyCustomLogFormatter()); - fileLogger.setLevel(Level.ALL); - log = Logger.getLogger("nulljavaai"); - if (isDebugging()) { - log.setLevel(Level.ALL); - } else { - log.setLevel(Level.INFO); - } - log.addHandler(fileLogger); - } catch (Exception ex) { - System.out.println("NullJavaAI: Failed initializing the logger!"); - ex.printStackTrace(); - ret = -2; - } - - try { - int teamId = clb.SkirmishAI_getTeamId(); - log.info("initializing team " + teamId + ", id " + skirmishAIId); - - int numInfo = callback.SkirmishAI_Info_getSize(); - log.info("info (items: " + numInfo + ") ..."); - for (int i = 0; i < numInfo; i++) { - String key = callback.SkirmishAI_Info_getKey(i); - String value = callback.SkirmishAI_Info_getValue(i); - log.info(key + " = " + value); - } - - int numOptions = callback.SkirmishAI_OptionValues_getSize(); - log.info("options (items: " + numOptions + ") ..."); - for (int i = 0; i < numOptions; i++) { - String key = callback.SkirmishAI_OptionValues_getKey(i); - String value = callback.SkirmishAI_OptionValues_getValue(i); - log.info(key + " = " + value); - } - - ret = 0; - } catch (Exception ex) { - log.log(Level.SEVERE, "Failed initializing", ex); - log.log(Level.SEVERE, "msg: " + ex.getMessage()); - StackTraceElement[] stackTrace = ex.getStackTrace(); - for (int i = 0; i < stackTrace.length; i++) { - log.log(Level.SEVERE, "ste: " + stackTrace[i].toString()); - } - ret = -3; - } - - { - int numOptions = clb.SkirmishAI_OptionValues_getSize(); - log.info("sizeOptions: " + numOptions); - log.info("options:"); -// Pointer[] pKeys = evt.optionKeys.getPointerArray(0L, evt.sizeOptions); -// Pointer[] pValues = evt.optionValues.getPointerArray(0L, evt.sizeOptions); -// Properties options = new Properties(); -// for (int i = 0; i < evt.sizeOptions; i++) { -// options.setProperty(pKeys[i].getString(0L), pValues[i].getString(0L)); -// } - for (int i = 0; i < numOptions; i++) { - String key = clb.SkirmishAI_OptionValues_getKey(i); - String value = clb.SkirmishAI_OptionValues_getValue(i); - log.info(key + " = " + value); - } - log.info("stored"); - } - - return ret; - } - - @Override - public int update(int frame) { - - try { - log.finer("update event ..."); - log.finer("frame: " + frame); - } catch (Exception ex) { - log.log(Level.WARNING, "Failed handling event", ex); - return -1; - } - - return 0; - } - - @Override - public int release(int reason) { - - int ret = -1; - - try { - int teamId = clb.SkirmishAI_getTeamId(); - log.info("releasing team " + teamId + ", id " + skirmishAIId); - - ret = 0; - } catch (Exception ex) { - log.log(Level.WARNING, "Failed releasing", ex); - ret = -2; - } - - return ret; - } -} diff --git a/AI/Skirmish/NullOOJavaAI/CMakeLists.txt b/AI/Skirmish/NullOOJavaAI/CMakeLists.txt deleted file mode 100644 index 195bb8f6313..00000000000 --- a/AI/Skirmish/NullOOJavaAI/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -### Generic Java Skirmish AI config -# - -configure_java_skirmish_ai("JavaOO") diff --git a/AI/Skirmish/NullOOJavaAI/VERSION b/AI/Skirmish/NullOOJavaAI/VERSION deleted file mode 100644 index ceab6e11ece..00000000000 --- a/AI/Skirmish/NullOOJavaAI/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.1 \ No newline at end of file diff --git a/AI/Skirmish/NullOOJavaAI/bin/ant.dependent.properties b/AI/Skirmish/NullOOJavaAI/bin/ant.dependent.properties deleted file mode 100644 index 71674185fe3..00000000000 --- a/AI/Skirmish/NullOOJavaAI/bin/ant.dependent.properties +++ /dev/null @@ -1,40 +0,0 @@ -# properties file for spring Java Skirmish AIs -# This is used when you do not use the spring repository for compiling. -# -# Paths are relative to the project home (which is ../ from this file). -# All values are optional, and listed here with their defaults. -# -# The default assumes that you have the spring source, -# and do a spring in-source build as it is the default with CMake and SCons, -# and as the buildbot does it. -# -# build-dir: ${spring.home}/AI/Skirmish/${ai.name}/ -# install-dir: ${spring.home}/dist/AI/Skirmish/${ai.name}/${ai.version}/ -# -# This file is loaded from within build.xml, -# but only if "Java-AIInterface/" and "JavaOO-AIWrapper/" dirs are not present. -# - -;spring.home=../../.. - -# This is used only in the next property -;build.home=${spring.home} -# Where jar files will be built -;build.dir=${build.home}/AI/Skirmish/${skirmish.ai.name} - -# This is used only in the next property -;dist.home=${spring.home}/dist -# Where jar files will be installed to -;dist.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version} -# Where HTML JavaDoc files will be generated -;doc.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version}/doc/jdoc - -# The following four are needed for compiling (to create the classpath) -# * Here we look for ./data/jlib/*.jar recursively -;ai.interface.src.home=${spring.home}/AI/Interfaces/Java -# * Here we look for AIInterface.jar -;ai.interface.build.home=${build.home}/AI/Interfaces/Java -# * Here we look for ./jlib/*.jar recursively -;ai.wrapper.oo.src.home=${spring.home}/AI/Wrappers/JavaOO -# * Here we look for JavaOO-AIWrapper.jar -;ai.wrapper.oo.build.home=${build.home}/AI/Wrappers/JavaOO diff --git a/AI/Skirmish/NullOOJavaAI/bin/ant.independent.properties b/AI/Skirmish/NullOOJavaAI/bin/ant.independent.properties deleted file mode 100644 index 4f5648f2935..00000000000 --- a/AI/Skirmish/NullOOJavaAI/bin/ant.independent.properties +++ /dev/null @@ -1,30 +0,0 @@ -# properties file for spring Java Skirmish AIs -# This is used when you do not use the spring repository for compiling. -# -# Paths are relative to the project home (which is ../ from this file). -# All values are optional, and listed here with their defaults. -# -# For the project, you do not need the spring sources, -# but you will need the "Java-AIInterface/" and "JavaOO-AIWrapper/" dirs -# instead, which contain the Java AI Interfaces jlibs plus its binary -# and source jar, and the Java OO Wrappers equal counterparts. -# -# build-dir: build/ -# install-dir: dist/ -# -# This file is loaded from within build.xml, -# but only if "Java-AIInterface/" and "JavaOO-AIWrapper/" dirs are present. -# - -# This is used only in the next property -;build.home=build -# Where jar files will be built -;build.dir=${build.home} - -# This is used only in the next property. -# You will want to set dist.home to your spring install dir. -;dist.home=dist -# Where jar files will be installed to -;dist.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version} -# Where HTML JavaDoc files will be generated -;doc.dir=${dist.home}/AI/Skirmish/${skirmish.ai.name}/${skirmish.ai.version}/doc/jdoc diff --git a/AI/Skirmish/NullOOJavaAI/bin/build.xml b/AI/Skirmish/NullOOJavaAI/bin/build.xml deleted file mode 100644 index 32b0b4783eb..00000000000 --- a/AI/Skirmish/NullOOJavaAI/bin/build.xml +++ /dev/null @@ -1,342 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . -File not found: ${ai.interface.build.home}/AIInterface.jar -Please make sure to compile the Java AI Interface -before trying to compile this AI, or request -an independent version of this project from -wherever you got this AI. - - - - . -File not found: ${ai.wrapper.oo.build.home}/JavaOO-AIWrapper.jar -Please make sure to compile the Java OO AI Wrapper -before trying to compile this AI, or request -an independent version of this project from -wherever you got this AI from. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Successfully bumped ${skirmish.ai.name} version from ${skirmish.ai.version} to ${skirmish.ai.version.new}. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . -Please specify either home.new or name.new, for example: - ant create-independent -Dhome.new=~/projects/SpringSkirmishAIs/ -or - ant create-independent -Dname.new=MyJavaAI - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Spring source independant Java Skirmish AI project copied to: - ${project.dir.new} - -You may want to change your java source package structure -and the data/AIInto.lua file for the new project. - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AI/Skirmish/NullOOJavaAI/data/AIInfo.lua b/AI/Skirmish/NullOOJavaAI/data/AIInfo.lua deleted file mode 100644 index 91420c5e704..00000000000 --- a/AI/Skirmish/NullOOJavaAI/data/AIInfo.lua +++ /dev/null @@ -1,53 +0,0 @@ --- --- Info Definition Table format --- --- --- These keywords must be lowercase for LuaParser to read them. --- --- key: user defined or one of the SKIRMISH_AI_PROPERTY_* defines in --- SSkirmishAILibrary.h --- value: the value of the property --- desc: the description (could be used as a tooltip) --- --- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local infos = { - { - key = 'shortName', - value = 'NullOOJavaAI', - desc = 'machine conform name.', - }, - { - key = 'version', - value = '0.1', -- AI version - !This comment is used for parsing! - }, - { - key = 'className', - value = 'nulloojavaai.NullOOJavaAI', - desc = 'fully qualified name of a class that implements interface com.springrts.ai.AI', - }, - { - key = 'name', - value = 'high-level Java stub Skirmish AI', - desc = 'human readable name.', - }, - { - key = 'loadSupported', - value = 'no', - desc = 'whether this AI supports loading or not', - }, - { - key = 'interfaceShortName', - value = 'Java', -- AI Interface name - !This comment is used for parsing! - desc = 'the shortName of the AI interface this AI needs', - }, - { - key = 'interfaceVersion', - value = '0.1', -- AI Interface version - !This comment is used for parsing! - desc = 'the minimum version of the AI interface required by this AI', - }, -} - -return infos diff --git a/AI/Skirmish/NullOOJavaAI/data/AIOptions.lua b/AI/Skirmish/NullOOJavaAI/data/AIOptions.lua deleted file mode 100644 index d435d62e964..00000000000 --- a/AI/Skirmish/NullOOJavaAI/data/AIOptions.lua +++ /dev/null @@ -1,15 +0,0 @@ --- --- Custom Options Definition Table format --- --- A detailed example of how this format works can be found --- in the spring source under: --- AI/Skirmish/NullAI/data/AIOptions.lua --- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- - -local options = { -} - -return options - diff --git a/AI/Skirmish/NullOOJavaAI/manifest.mf b/AI/Skirmish/NullOOJavaAI/manifest.mf deleted file mode 100755 index 59499bce4a2..00000000000 --- a/AI/Skirmish/NullOOJavaAI/manifest.mf +++ /dev/null @@ -1,2 +0,0 @@ -Manifest-Version: 1.0 - diff --git a/AI/Skirmish/NullOOJavaAI/src/main/java/nulloojavaai/NullOOJavaAI.java b/AI/Skirmish/NullOOJavaAI/src/main/java/nulloojavaai/NullOOJavaAI.java deleted file mode 100644 index 9ffabe1eae6..00000000000 --- a/AI/Skirmish/NullOOJavaAI/src/main/java/nulloojavaai/NullOOJavaAI.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - Copyright (c) 2008 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package nulloojavaai; - - -import com.springrts.ai.AI; -import com.springrts.ai.oo.AIFloat3; -import com.springrts.ai.oo.OOAI; -import com.springrts.ai.oo.clb.*; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; -import java.util.List; -import java.util.logging.*; - -/** - * Serves as Interface for a Java Skirmish AIs for the Spring engine. - * - * @author hoijui - */ -public class NullOOJavaAI extends OOAI implements AI { - - private static class MyCustomLogFormatter extends Formatter { - - private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSS dd.MM.yyyy"); - - public String format(LogRecord record) { - - // Create a StringBuffer to contain the formatted record - // start with the date. - StringBuffer sb = new StringBuffer(); - - // Get the date from the LogRecord and add it to the buffer - Date date = new Date(record.getMillis()); - sb.append(dateFormat.format(date)); - sb.append(" "); - - // Get the level name and add it to the buffer - sb.append(record.getLevel().getName()); - sb.append(": "); - - // Get the formatted message (includes localization - // and substitution of parameters) and add it to the buffer - sb.append(formatMessage(record)); - sb.append("\n"); - - return sb.toString(); - } - } - - private static void logProperties(Logger log, Level level, Properties props) { - - log.log(level, "properties (items: " + props.size() + "):"); - for (String key : props.stringPropertyNames()) { - log.log(level, key + " = " + props.getProperty(key)); - } - } - - private int skirmishAIId = -1; - private int teamId = -1; - private Properties info = null; - private Properties optionValues = null; - private OOAICallback clb = null; - private String myLogFile = null; - private Logger log = null; - - private static final int DEFAULT_ZONE = 0; - - - public NullOOJavaAI() {} - - private int sendTextMsg(String msg) { - - try { - clb.getGame().sendTextMessage("/say " + msg, DEFAULT_ZONE); - } catch (Exception ex) { - ex.printStackTrace(); - return 1; - } - - return 0; - } - public boolean isDebugging() { - return true; - } - - @Override - public int init(int skirmishAIId, OOAICallback callback) { - - int ret = -1; - - this.skirmishAIId = skirmishAIId; - this.clb = callback; - - this.teamId = clb.getSkirmishAI().getTeamId(); - - info = new Properties(); - Info inf = clb.getSkirmishAI().getInfo(); - int numInfo = inf.getSize(); - for (int i = 0; i < numInfo; i++) { - String key = inf.getKey(i); - String value = inf.getValue(i); - info.setProperty(key, value); - } - - optionValues = new Properties(); - OptionValues opVals = clb.getSkirmishAI().getOptionValues(); - int numOpVals = opVals.getSize(); - for (int i = 0; i < numOpVals; i++) { - String key = opVals.getKey(i); - String value = opVals.getValue(i); - optionValues.setProperty(key, value); - } - - // initialize the log - try { - myLogFile = callback.getDataDirs().locatePath("log-team-" + teamId + ".txt", true, true, false, false); - FileHandler fileLogger = new FileHandler(myLogFile, false); - fileLogger.setFormatter(new MyCustomLogFormatter()); - fileLogger.setLevel(Level.ALL); - log = Logger.getLogger("nulloojavaai"); - log.addHandler(fileLogger); - if (isDebugging()) { - log.setLevel(Level.ALL); - } else { - log.setLevel(Level.INFO); - } - } catch (Exception ex) { - System.out.println("NullOOJavaAI: Failed initializing the logger!"); - ex.printStackTrace(); - ret = -2; - } - - try { - log.info("initializing team " + teamId); - - log.log(Level.FINE, "info:"); - logProperties(log, Level.FINE, info); - - log.log(Level.FINE, "options:"); - logProperties(log, Level.FINE, optionValues); - - ret = 0; - } catch (Exception ex) { - log.log(Level.SEVERE, "Failed initializing", ex); - ret = -3; - } - - return ret; - } - - @Override - public int release(int reason) { - return 0; // signaling: OK - } - - @Override - public int update(int frame) { - - if (frame % 300 == 0) { - sendTextMsg("listing resources ..."); - List resources = clb.getResources(); - for (Resource resource : resources) { - sendTextMsg("Resource " + resource.getName() + " optimum: " - + resource.getOptimum()); - sendTextMsg("Resource " + resource.getName() + " current: " - + clb.getEconomy().getCurrent(resource)); - sendTextMsg("Resource " + resource.getName() + " income: " - + clb.getEconomy().getIncome(resource)); - sendTextMsg("Resource " + resource.getName() + " storage: " - + clb.getEconomy().getStorage(resource)); - sendTextMsg("Resource " + resource.getName() + " usage: " - + clb.getEconomy().getUsage(resource)); - } - } - - return 0; // signaling: OK - } - - @Override - public int message(int player, String message) { - return 0; // signaling: OK - } - - @Override - public int unitCreated(Unit unit, Unit builder) { - - int ret = sendTextMsg("unitCreated: " + unit.toString()); - sendTextMsg("unitCreated def: " + unit.getDef().getName()); - List buildOptions = unit.getDef().getBuildOptions(); - for (UnitDef unitDef : buildOptions) { - sendTextMsg("\tbuildOption x: " + unitDef.getName() + "\t" + unitDef.getHumanName() + "\t" + unitDef.toString() + "\t" + unitDef.hashCode()); - } - - return ret; - } - - @Override - public int unitFinished(Unit unit) { - return 0; // signaling: OK - } - - @Override - public int unitIdle(Unit unit) { - return 0; // signaling: OK - } - - @Override - public int unitMoveFailed(Unit unit) { - return 0; // signaling: OK - } - - @Override - public int unitDamaged(Unit unit, Unit attacker, float damage, AIFloat3 dir, WeaponDef weaponDef, boolean paralyzed) { - return 0; // signaling: OK - } - - @Override - public int unitDestroyed(Unit unit, Unit attacker) { - return 0; // signaling: OK - } - - @Override - public int unitGiven(Unit unit, int oldTeamId, int newTeamId) { - return 0; // signaling: OK - } - - @Override - public int unitCaptured(Unit unit, int oldTeamId, int newTeamId) { - return 0; // signaling: OK - } - - @Override - public int enemyEnterLOS(Unit enemy) { - return 0; // signaling: OK - } - - @Override - public int enemyLeaveLOS(Unit enemy) { - return 0; // signaling: OK - } - - @Override - public int enemyEnterRadar(Unit enemy) { - return 0; // signaling: OK - } - - @Override - public int enemyLeaveRadar(Unit enemy) { - return 0; // signaling: OK - } - - @Override - public int enemyDamaged(Unit enemy, Unit attacker, float damage, AIFloat3 dir, WeaponDef weaponDef, boolean paralyzed) { - return 0; // signaling: OK - } - - @Override - public int enemyDestroyed(Unit enemy, Unit attacker) { - return 0; // signaling: OK - } - - @Override - public int weaponFired(Unit unit, WeaponDef weaponDef) { - return 0; // signaling: OK - } - - @Override - public int playerCommand(java.util.List units, int commandTopicId, int playerId) { - return 0; // signaling: OK - } - - @Override - public int commandFinished(Unit unit, int commandId, int commandTopicId) { - return 0; // signaling: OK - } - - @Override - public int seismicPing(AIFloat3 pos, float strength) { - return 0; // signaling: OK - } - - @Override - public int load(String file) { - return 0; // signaling: OK - } - - @Override - public int save(String file) { - return 0; // signaling: OK - } - - @Override - public int enemyCreated(Unit enemy) { - return 0; // signaling: OK - } - - @Override - public int enemyFinished(Unit enemy) { - return 0; // signaling: OK - } - -} diff --git a/AI/Wrappers/JavaOO/CMakeLists.txt b/AI/Wrappers/JavaOO/CMakeLists.txt deleted file mode 100644 index da45a64c6e6..00000000000 --- a/AI/Wrappers/JavaOO/CMakeLists.txt +++ /dev/null @@ -1,379 +0,0 @@ -### Java OO AI Wrapper -# -# Global variables set in this file: -# * BUILD_JavaOO_AIWRAPPER -# - -#enable_language(Java) - -# includes rts/build/cmake/UtilJava.cmake -include(UtilJava) - - -set(myName "JavaOO") - - -# Check if the user wants to compile the wrapper -if ("${AI_TYPES}" STREQUAL "ALL" OR "${AI_TYPES}" STREQUAL "JAVA") - set(AIWRAPPERS_JAVA TRUE) -else ("${AI_TYPES}" STREQUAL "ALL" OR "${AI_TYPES}" STREQUAL "JAVA") - set(AIWRAPPERS_JAVA FALSE) -endif ("${AI_TYPES}" STREQUAL "ALL" OR "${AI_TYPES}" STREQUAL "JAVA") - - -# Check dependencies of the wrapper are met -if (AIWRAPPERS_JAVA AND BUILD_Java_AIINTERFACE AND AWK_FOUND AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - set_global(BUILD_${myName}_AIWRAPPER TRUE) -else (AIWRAPPERS_JAVA AND BUILD_Java_AIINTERFACE AND AWK_FOUND AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - set_global(BUILD_${myName}_AIWRAPPER FALSE) - message("warning: Java OO AI Wrapper will not be built!") -endif (AIWRAPPERS_JAVA AND BUILD_Java_AIINTERFACE AND AWK_FOUND AND NOT myName MATCHES "${AI_EXCLUDE_REGEX}") - - -# Build -if (BUILD_${myName}_AIWRAPPER) - set(myDir "${CMAKE_CURRENT_SOURCE_DIR}") - get_last_path_part(dirName ${myDir}) - set(myName "${dirName}") - set(myTarget "${myName}-AIWrapper") - set(myGenTarget "${myTarget}-generateSources") - set(myJavaTarget "${myTarget}-java") - set(myPomTarget "${myTarget}-pom") - set(mySourceDirRel "src/main/java") - make_absolute(mySourceDir "${myDir}" "${mySourceDirRel}") - - ai_wrapper_message(STATUS "Found AI Wrapper: ${myName}") - - - # Build library - set(myPkgFirstPart "com") - set(myParentPkg "${myPkgFirstPart}/springrts/ai") - set(myPkg "${myParentPkg}/oo") - set(myBinDir "${myDir}/bin") - set(commonAwkScriptsDir "${CMAKE_SOURCE_DIR}/AI/Wrappers/CUtils/bin") - set(myBuildDir "${CMAKE_CURRENT_BINARY_DIR}") - set(myGeneratedSourceDir "${myBuildDir}/src-generated/main/java") - set(myJavaBuildDir "${myBuildDir}/classes") - set(myJarFile "${myName}-AIWrapper") - set(myBinJarFile "${myJarFile}.jar") - set(mySrcJarFile "${myJarFile}-src.jar") - set(myJLibDir "${myDir}/jlib") - find_java_lib(vecmath_jar "vecmath" "${myJLibDir}") - set(myJLibs "${vecmath_jar}") - set(jAiIntJavaSourceDir "${JAVA_SRC_DIR_Java_AIINTERFACE}") - set(jAiIntJavaGeneratedSourceDir "${JAVA_GEN_SRC_DIR_Java_AIINTERFACE}") - set(myClassPath "${myJLibs}${PATH_DELIM_H}${CLASSPATH_Java_AIINTERFACE}") - - set_global(${myName}_AIWRAPPER_JAR_BIN "${myBuildDir}/${myBinJarFile}") - set_global(${myName}_AIWRAPPER_JAR_SRC "${myBuildDir}/${mySrcJarFile}") - set_global(${myName}_AIWRAPPER_JAR_CLASSPATH "${myJLibs}${PATH_DELIM_H}${${myName}_AIWRAPPER_JAR_BIN}") - set_global(${myName}_AIWRAPPER_TARGET "${myTarget}") - set_global(SOURCE_ROOT_${myName}_AIWRAPPER "${myDir}") - set_global(BUILD_ROOT_${myName}_AIWRAPPER "${CMAKE_CURRENT_BINARY_DIR}") - - # Locate the manifest file - find_manifest_file("${myDir}" myManifestFile) - if (myManifestFile) - set(myBinJarArgs "cmf" "${myManifestFile}") - else (myManifestFile) - set(myBinJarArgs "cf") - endif (myManifestFile) - - # remove all generated sources from build dir, if it exists - # (required for build dirs of git:master from before 21. September 2010) - file(REMOVE_RECURSE "${myGeneratedSourceDir}/${myPkg}") - - - # Generate sources - # ---------------- - - set(commonAwkScriptArgs - "-v" "INTERFACE_SOURCE_DIR=${jAiIntJavaSourceDir}" - "-v" "INTERFACE_GENERATED_SOURCE_DIR=${jAiIntJavaGeneratedSourceDir}" - "-v" "JAVA_GENERATED_SOURCE_DIR=${myGeneratedSourceDir}" - "-f" "${commonAwkScriptsDir}/common.awk" - "-f" "${commonAwkScriptsDir}/commonDoc.awk" - ) - - set(mySources - "${mySourceDir}/${myPkg}/AIEvent.java" - "${mySourceDir}/${myPkg}/AIFloat3.java" - "${mySourceDir}/${myPkg}/AIException.java" - "${mySourceDir}/${myPkg}/CallbackAIException.java" - "${mySourceDir}/${myPkg}/EventAIException.java" - ) - - set(myGenClbClasses - "Cheats" - "CommandDescription" - "Command" - "Damage" - "DataDirs" - "Debug" - "Drawer" - "Economy" - "Engine" - "FeatureDef" - "Feature" - "Figure" - "FlankingBonus" - "Game" - "GraphDrawer" - "GraphLine" - "Group" - "Info" - "Line" - "Log" - "Lua" - "Map" - "Mod" - "MoveData" - "OOAICallback" - "OptionValues" - "OrderPreview" - "Pathing" - "PathDrawer" - "Point" - "Resource" - "Roots" - "Shield" - "SkirmishAI" - "Team" - "OverlayTexture" - "UnitDef" - "Unit" - "Version" - "WeaponDef" - "WeaponMount" - "Weapon" - ) - set(myGeneratedCallbackSources ) - foreach (className ${myGenClbClasses}) - list(APPEND myGeneratedCallbackSources - "${myGeneratedSourceDir}/${myPkg}/clb/${className}.java" - "${myGeneratedSourceDir}/${myPkg}/clb/Abstract${className}.java" - "${myGeneratedSourceDir}/${myPkg}/clb/Stub${className}.java" - ) - if ("${className}" STREQUAL "CommandDescription") - list(APPEND myGeneratedCallbackSources - "${myGeneratedSourceDir}/${myPkg}/clb/WrappGroupSupportedCommand.java" - "${myGeneratedSourceDir}/${myPkg}/clb/WrappUnitSupportedCommand.java" - ) - elseif ("${className}" STREQUAL "Command") - list(APPEND myGeneratedCallbackSources - "${myGeneratedSourceDir}/${myPkg}/clb/WrappCurrentCommand.java" - ) - else () - list(APPEND myGeneratedCallbackSources - "${myGeneratedSourceDir}/${myPkg}/clb/Wrapp${className}.java" - ) - endif () - endforeach (className) - - set(myGeneratedEventSources - "${myGeneratedSourceDir}/${myPkg}/AbstractOOAI.java" - "${myGeneratedSourceDir}/${myPkg}/IOOAI.java" - "${myGeneratedSourceDir}/${myPkg}/OOAI.java" - "${myGeneratedSourceDir}/${myPkg}/IOOEventAI.java" - "${myGeneratedSourceDir}/${myPkg}/OOEventAI.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitLifeStateAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitTeamChangeAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/LoadSaveAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/CommandFinishedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyCreatedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyDamagedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyDestroyedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyFinishedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyEnterLOSAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyEnterRadarAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyLeaveLOSAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/EnemyLeaveRadarAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/InitAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/LoadAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/MessageAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/LuaMessageAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/PlayerCommandAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/ReleaseAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/SaveAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/SeismicPingAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitCapturedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitCreatedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitDamagedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitDestroyedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitFinishedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitGivenAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitIdleAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UnitMoveFailedAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/UpdateAIEvent.java" - "${myGeneratedSourceDir}/${myPkg}/evt/WeaponFiredAIEvent.java" - ) - - set(myGeneratedSources - ${myGeneratedCallbackSources} - ${myGeneratedEventSources} - ) - set_source_files_properties(${myGeneratedSources} PROPERTIES GENERATED TRUE) - - set(jAiIntJavaGeneratedSources - "${jAiIntJavaGeneratedSourceDir}/${myParentPkg}/AI.java" - "${jAiIntJavaGeneratedSourceDir}/${myParentPkg}/AICallback.java" - ) - set_source_files_properties(${jAiIntJavaGeneratedSources} PROPERTIES GENERATED TRUE) - - - # Assemble project generated targets (and their libraries) we depend on - set(myDependTargets "${Java_AIINTERFACE_TARGET}") - set(myDependLibFiles "${Java_AIINTERFACE_JAR_BIN}") - set_source_files_properties(${myDependLibFiles} PROPERTIES GENERATED TRUE) - - add_custom_target(${myJavaTarget} - DEPENDS - "${myBuildDir}/${myBinJarFile}" - "${myBuildDir}/${mySrcJarFile}") - add_dependencies(${myJavaTarget} ${myDependTargets}) - - - # generate sources: callback - add_custom_command( - OUTPUT - ${myGeneratedCallbackSources} - COMMAND "${CMAKE_COMMAND}" - "-E" "remove_directory" "${myGeneratedSourceDir}/${myPkg}/clb" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myGeneratedSourceDir}/${myPkg}/clb" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${commonAwkScriptsDir}/commonOOCallback.awk" - "-f" "${myBinDir}/wrappCallback.awk" - "${jAiIntJavaGeneratedSourceDir}/${myParentPkg}/AICallback.java" - DEPENDS - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${commonAwkScriptsDir}/commonOOCallback.awk" - "${myBinDir}/wrappCallback.awk" - # Handled through a target level dependency, see below - #"${jAiIntJavaGeneratedSourceDir}/${myParentPkg}/AICallback.java" - WORKING_DIRECTORY - "${myBinDir}" - COMMENT - " ${myTarget}: Generating callback sources" VERBATIM - ) - - # generate sources: events - add_custom_command( - OUTPUT - ${myGeneratedEventSources} - COMMAND "${CMAKE_COMMAND}" - "-E" "remove_directory" "${myGeneratedSourceDir}/${myPkg}/evt" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myGeneratedSourceDir}/${myPkg}/evt" - COMMAND "${AWK_BIN}" - ${commonAwkScriptArgs} - "-f" "${myBinDir}/wrappEvents.awk" - "${jAiIntJavaGeneratedSourceDir}/${myParentPkg}/AI.java" - DEPENDS - "${commonAwkScriptsDir}/common.awk" - "${commonAwkScriptsDir}/commonDoc.awk" - "${myBinDir}/wrappEvents.awk" - "${jAiIntJavaGeneratedSourceDir}/${myParentPkg}/AI.java" - WORKING_DIRECTORY - "${myBinDir}" - COMMENT - " ${myTarget}: Generating event sources" VERBATIM - ) - - add_custom_target(${myGenTarget} DEPENDS ${myGeneratedSources}) - add_dependencies(${myGenTarget} ${Java_AIINTERFACE_TARGET_GENERATE_SOURCES}) # for AICallback.java - add_dependencies(generateSources ${myGenTarget}) - - - # Build the jars - # -------------- - - # Write list of source files to an arg-file - set(mySrcArgFile "${CMAKE_CURRENT_BINARY_DIR}/sourceFiles.txt") - if (EXISTS "${mySrcArgFile}") - file(REMOVE "${mySrcArgFile}") - endif (EXISTS "${mySrcArgFile}") - foreach (srcFile ${mySources} ${myGeneratedSources}) - file(APPEND "${mySrcArgFile}" "\"${srcFile}\"\n") - endforeach (srcFile) - - # compile and pack library - add_custom_command( - OUTPUT - "${myBuildDir}/${myBinJarFile}" - COMMAND "${CMAKE_COMMAND}" - "-E" "remove_directory" "${myJavaBuildDir}" - COMMAND "${CMAKE_COMMAND}" - "-E" "make_directory" "${myJavaBuildDir}" - COMMAND "${Java_JAVAC_EXECUTABLE}" - "${JAVA_COMPILE_FLAG_CONDITIONAL}" - "-Xlint:deprecation" - "-cp" "${myClassPath}" - "-d" "${myJavaBuildDir}" - "@${mySrcArgFile}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - ${myBinJarArgs} "${myBuildDir}/${myBinJarFile}" - "-C" "${myJavaBuildDir}" "${myPkgFirstPart}" - DEPENDS - ${myDependLibFiles} - ${mySources} - ${myGeneratedSources} - WORKING_DIRECTORY - "${myBinDir}" - COMMENT - " ${myTarget}: Compiling sources and packing library ${myBinJarFile}" VERBATIM - ) - - # pack sources - add_custom_command( - OUTPUT - "${myBuildDir}/${mySrcJarFile}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "cf" "${${myName}_AIWRAPPER_JAR_SRC}" - "-C" "${mySourceDir}" "${myPkgFirstPart}" - COMMAND "${Java_JAR_EXECUTABLE}" ARGS - "uf" "${${myName}_AIWRAPPER_JAR_SRC}" - "-C" "${myGeneratedSourceDir}" "${myPkgFirstPart}" - DEPENDS - ${myJavaSources} - ${myJavaGeneratedSources} - WORKING_DIRECTORY - "${myBuildDir}" - COMMENT - " ${myTarget}: Creating sources archive ${mySrcJarFile}" VERBATIM - ) - - # This sets the version in pom.xml - # as we have no separate version for the wrapper, - # we use the one from the interface - set(myMavenProperties "-Dmy.version=${Java_AIINTERFACE_VERS}") - add_custom_command( - OUTPUT - "${myBuildDir}/pom-generated.xml" - COMMAND "${CMAKE_COMMAND}" - "-Dfile.in=${myDir}/pom.xml" - "-Dfile.out=${myBuildDir}/pom-generated.xml" - ${myMavenProperties} - "-P" "${CMAKE_MODULES_SPRING}/ConfigureFile.cmake" - DEPENDS - "${myDir}/pom.xml" - WORKING_DIRECTORY - "${myDir}" - COMMENT - " ${myTarget}: Configure pom.xml" VERBATIM - ) - set_source_files_properties("${myBuildDir}/pom-generated.xml" PROPERTIES GENERATED TRUE) - - add_custom_target(${myPomTarget} - DEPENDS - "${myBuildDir}/pom-generated.xml") - - add_custom_target(${myTarget} ALL) - - add_dependencies(${myTarget} ${myJavaTarget}) - -endif (BUILD_${myName}_AIWRAPPER) diff --git a/AI/Wrappers/JavaOO/bin/ant.properties b/AI/Wrappers/JavaOO/bin/ant.properties deleted file mode 100644 index 0807d79b8a8..00000000000 --- a/AI/Wrappers/JavaOO/bin/ant.properties +++ /dev/null @@ -1,26 +0,0 @@ -# Paths are relative to the project home (which is ../ from this file). -# All values are optional. - -;spring.home=../../.. - -# specify Java-AIInterface dirs -;spring.ai.interface.src.home=${spring.home}/AI/Interfaces/Java -;spring.ai.interface.src.dir=${spring.ai.interface.src.home}/src/main/java -;spring.ai.interface.build.home=${build.home}/AI/Interfaces/Java -;spring.ai.interface.build.dir=${spring.ai.interface.build.home}/src-generated/main/java - -# This is used only in the next property -;build.home=${spring.home}/build -# Where jar files will be built -;build.dir=${build.home}/AI/Wrappers/${wrapper.name} - -# Where generated sources shall be created in -;src.generated=${build.dir}/src-generated/main -;src.generated.java=${src.generated}/java - -# This is used only in the next property -;dist.home=${spring.home}/dist -# Where jar files will be installed to -;dist.dir=${dist.home}/AI/Wrappers/${wrapper.name} -# Where HTML JavaDoc files will be generated -;doc.dir=${dist.home}/AI/Wrappers/${wrapper.name}/doc/jdoc diff --git a/AI/Wrappers/JavaOO/bin/build.xml b/AI/Wrappers/JavaOO/bin/build.xml deleted file mode 100644 index 71e836bbb7a..00000000000 --- a/AI/Wrappers/JavaOO/bin/build.xml +++ /dev/null @@ -1,211 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AI/Wrappers/JavaOO/bin/wrappCallback.awk b/AI/Wrappers/JavaOO/bin/wrappCallback.awk deleted file mode 100755 index 7824eb30137..00000000000 --- a/AI/Wrappers/JavaOO/bin/wrappCallback.awk +++ /dev/null @@ -1,1241 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates Java classes in OO style to wrap the C style -# JNI based AI Callback wrapper. -# In other words, the output of this file wraps: -# com/springrts/ai/AICallback.java -# which wraps: -# rts/ExternalAI/Interface/SSkirmishAICallback.h -# and -# rts/ExternalAI/Interface/AISCommands.h -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# * commonOOCallback.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR : the generated sources root dir -# * JAVA_GENERATED_SOURCE_DIR : the generated java sources root dir -# * INTERFACE_SOURCE_DIR : the Java AI Interfaces static source files root dir -# * INTERFACE_GENERATED_SOURCE_DIR : the Java AI Interfaces generated source files root dir -# -# usage: -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -f commonOOCallback.awk -# awk -f thisScript.awk -f common.awk -f commonDoc.awk -f commonOOCallback.awk \ -# -v 'GENERATED_SOURCE_DIR=/tmp/build/AI/Interfaces/Java/src-generated' -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "(\\()|(\\);)"; - IGNORECASE = 0; - - # Used by other scripts - JAVA_MODE = 1; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!JAVA_GENERATED_SOURCE_DIR) { - JAVA_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/java"; - } - if (!INTERFACE_SOURCE_DIR) { - INTERFACE_SOURCE_DIR = "../../../Interfaces/Java/src/main/java"; - } - if (!INTERFACE_GENERATED_SOURCE_DIR) { - INTERFACE_GENERATED_SOURCE_DIR = "../../../Interfaces/Java/src-generated/main/java"; - } - - myMainPkgA = "com.springrts.ai"; - myParentPkgA = myMainPkgA ".oo"; - myPkgA = myParentPkgA ".clb"; - myPkgD = convertJavaNameFormAToD(myPkgA); - myClassVar = "ooClb"; - myWrapClass = "AICallback"; - myWrapVar = "innerCallback"; - - myBufferedClasses["UnitDef"] = 1; - myBufferedClasses["WeaponDef"] = 1; - myBufferedClasses["FeatureDef"] = 1; - - retParamName = "__retVal"; -} - -function createJavaFileName(clsName_c) { - return JAVA_GENERATED_SOURCE_DIR "/" myPkgD "/" clsName_c ".java"; -} - - -function printHeader(outFile_h, javaPkg_h, javaClassName_h, isInterface_h, - implementsInterface_h, isJniBound_h, isAbstract_h, implementsClass_h) { - - if (isInterface_h) { - classOrInterface_h = "interface"; - } else if (isAbstract_h) { - classOrInterface_h = "abstract class"; - } else { - classOrInterface_h = "class"; - } - - extensionsPart_h = ""; - if (isInterface_h) { - extensionsPart_h = " extends Comparable<" javaClassName_h ">"; - } else if (isAbstract_h) { - extensionsPart_h = " implements " implementsInterface_h ""; - } else { - extensionsPart_h = " extends " implementsClass_h " implements " implementsInterface_h; - } - - printCommentsHeader(outFile_h); - print("") >> outFile_h; - print("package " javaPkg_h ";") >> outFile_h; - print("") >> outFile_h; - print("") >> outFile_h; - print("import " myParentPkgA ".CallbackAIException;") >> outFile_h; - print("import " myParentPkgA ".AIFloat3;") >> outFile_h; - if (isJniBound_h) { - print("import " myMainPkgA ".AICallback;") >> outFile_h; - print("import " myMainPkgA ".Util;") >> outFile_h; - } - print("") >> outFile_h; - print("/**") >> outFile_h; - print(" * @author AWK wrapper script") >> outFile_h; - print(" * @version GENERATED") >> outFile_h; - print(" */") >> outFile_h; - print("public " classOrInterface_h " " javaClassName_h extensionsPart_h " {") >> outFile_h; - print("") >> outFile_h; -} - - -function getNullTypeValue(fRet_ntv) { - - if (fRet_ntv == "void") { - return ""; - } else if (fRet_ntv == "String") { - return "\"\""; - } else if (fRet_ntv == "AIFloat3") { - #return "new AIFloat3(0.0f, 0.0f, 0.0f)"; - return "null"; - } else if (fRet_ntv == "java.awt.Color") { - #return "java.awt.Color.BLACK"; - return "null"; - } else if (startsWithCapital(fRet_ntv)) { - # must be a class - return "null"; - } else if (match(fRet_ntv, /^java.util.List/)) { - return "null"; - } else if (match(fRet_ntv, /^java.util.Map/)) { - return "null"; - } else if (fRet_ntv == "boolean") { - return "false"; - } else { - return "0"; - } -} -function printTripleFunc(fRet_tr, fName_tr, fParams_tr, thrownExceptions_tr, outFile_int_tr, outFile_stb_tr, outFile_jni_tr, printIntAndStb_tr, noOverride_tr, isDeprecated_tr) { - - _funcHdr_tr = "public " fRet_tr " " fName_tr "(" fParams_tr ")"; - if (thrownExceptions_tr != "") { - _funcHdr_tr = _funcHdr_tr " throws " thrownExceptions_tr; - } - - if (printIntAndStb_tr) { - print("\t" _funcHdr_tr ";") >> outFile_int_tr; - print("") >> outFile_int_tr; - - isSimpleGetter_tr = ((fRet_tr != "void") && (fParams_tr == "") && match(fName_tr, /^(get|is)/)); - if ((fName_tr == "isEnabled") && match(outFile_int_tr, /Cheats\.java$/)) { - # an exception, because this has a setter anyway - isSimpleGetter_tr = 0; - } - nullTypeValue_tr = getNullTypeValue(fRet_tr); - if (isSimpleGetter_tr) { - # create an additional private member and setter - propName_tr = fName_tr; - sub(/^get/, "", propName_tr); - propName_tr = lowerize(propName_tr); - fSetterName_tr = fName_tr; - sub(/^(get|is)/, "set", fSetterName_tr); - print("\t" "public void " fSetterName_tr "(" fRet_tr " " propName_tr ")" " {") >> outFile_stb_tr; - print("\t\t" "this." propName_tr " = " propName_tr ";") >> outFile_stb_tr; - print("\t" "}") >> outFile_stb_tr; - print("\t" "private " fRet_tr " " propName_tr " = " nullTypeValue_tr ";") >> outFile_stb_tr; - if (isDeprecated_tr) { - # this prevents javac from outputting a warning - print("\t" "/** @deprecated */") >> outFile_stb_tr; - } - print("\t" "@Override") >> outFile_stb_tr; - print("\t" _funcHdr_tr " {") >> outFile_stb_tr; - print("\t\t" "return " propName_tr ";") >> outFile_stb_tr; - } else { - print("\t" "@Override") >> outFile_stb_tr; - print("\t" _funcHdr_tr " {") >> outFile_stb_tr; - # simply return a null like value - if (fRet_tr == "void") { - # return nothing - } else { - print("\t\t" "return " nullTypeValue_tr ";") >> outFile_stb_tr; - } - } - print("\t" "}") >> outFile_stb_tr; - print("") >> outFile_stb_tr; - } - - if (!noOverride_tr) { - print("\t" "@Override") >> outFile_jni_tr; - } - print("\t" _funcHdr_tr " {") >> outFile_jni_tr; - print("") >> outFile_jni_tr; -} - - -function printClasses() { - - # look for AVAILABLE indicators - for (_memberId in cls_memberId_metaComment) { - if (match(cls_memberId_metaComment[_memberId], /AVAILABLE:/)) { - _availCls = cls_memberId_metaComment[_memberId]; - sub(/^.*AVAILABLE:/, "", _availCls); - sub(/[ \t].*$/, "", _availCls); - clsAvailInd_memberId_cls[_memberId] = _availCls; - } - } - - c_size_cs = cls_id_name["*"]; - for (c=0; c < c_size_cs; c++) { - cls_cs = cls_id_name[c]; - anc_size_cs = cls_name_implIds[cls_cs ",*"]; - - printIntAndStb_cs = 1; - for (a=0; a < anc_size_cs; a++) { - implId_cs = cls_name_implIds[cls_cs "," a]; - printClass(implId_cs, cls_cs, printIntAndStb_cs); - # only print interface and stub when printing the first impl-class - printIntAndStb_cs = 0; - } - } -} - - -function printClass(implId_c, clsName_c, printIntAndStb_c) { - - implCls_c = implId_c; - sub(/^.*,/, "", implCls_c); - - clsName_int_c = clsName_c; - clsName_abs_c = "Abstract" clsName_int_c; - clsName_stb_c = "Stub" clsName_int_c; - _fullClsName = cls_implId_fullClsName[implId_c]; - if (_fullClsName != clsName_c) { - lastAncName_c = implId_c; - sub(/,[^,]*$/, "", lastAncName_c); # remove class name - sub(/^.*,/, "", lastAncName_c); # remove pre last ancestor name - noInterfaceIndices_c = lowerize(lastAncName_c) "Id"; - } else { - noInterfaceIndices_c = 0; - } - clsName_jni_c = "Wrapp" _fullClsName; - - if (printIntAndStb_c) { - outFile_int_c = createJavaFileName(clsName_int_c); - outFile_abs_c = createJavaFileName(clsName_abs_c); - outFile_stb_c = createJavaFileName(clsName_stb_c); - } - outFile_jni_c = createJavaFileName(clsName_jni_c); - - if (printIntAndStb_c) { - printHeader(outFile_int_c, myPkgA, clsName_int_c, 1, 0, 0, 0, 0); - printHeader(outFile_abs_c, myPkgA, clsName_abs_c, 0, clsName_int_c, 0, 1, 0); - printHeader(outFile_stb_c, myPkgA, clsName_stb_c, 0, clsName_int_c, 0, 0, clsName_abs_c); - } - printHeader( outFile_jni_c, myPkgA, clsName_jni_c, 0, clsName_int_c, 1, 0, clsName_abs_c); - - # prepare additional indices names - addInds_size_c = split(cls_implId_indicesArgs[implId_c], addInds_c, ","); - for (ai=1; ai <= addInds_size_c; ai++) { - sub(/int /, "", addInds_c[ai]); - addInds_c[ai] = trim(addInds_c[ai]); - } - - myInnerClb = myClassVar ".getInnerCallback()"; - - - # print private vars - print("\t" "private " myWrapClass " " myWrapVar " = null;") >> outFile_jni_c; - # print additionalVars - for (ai=1; ai <= addInds_size_c; ai++) { - print("\t" "private int " addInds_c[ai] " = -1;") >> outFile_jni_c; - } - print("") >> outFile_jni_c; - - - # print constructor - ctorParams = myWrapClass " " myWrapVar; - addIndPars_c = ""; - for (ai=1; ai <= addInds_size_c; ai++) { - addIndPars_c = addIndPars_c ", int " addInds_c[ai]; - } - ctorParams = ctorParams addIndPars_c; - ctorParamsNoTypes = removeParamTypes(ctorParams); - sub(/^, /, "", addIndPars_c); - addIndParsNoTypes_c = removeParamTypes(addIndPars_c); - condAddIndPars_c = (addIndPars_c == "") ? "" : ", "; - print("\t" "public " clsName_jni_c "(" ctorParams ") {") >> outFile_jni_c; - print("") >> outFile_jni_c; - print("\t\t" "this." myWrapVar " = " myWrapVar ";") >> outFile_jni_c; - # init additionalVars - for (ai=1; ai <= addInds_size_c; ai++) { - addIndName = addInds_c[ai]; - print("\t\t" "this." addIndName " = " addIndName ";") >> outFile_jni_c; - } - print("\t" "}") >> outFile_jni_c; - print("") >> outFile_jni_c; - - - # print additional vars fetchers - for (ai=1; ai <= addInds_size_c; ai++) { - addIndName = addInds_c[ai]; - addIndNameCap = capitalize(addIndName); - - printIntAndStb_tmp_c = printIntAndStb_c; - _noOverride = 0; - if ((noInterfaceIndices_c != 0) && (addIndName == noInterfaceIndices_c)) { - printIntAndStb_tmp_c = 0; - _noOverride = 1; - } - - # Print the direct fetcher function, eg. "int getUnitId()" - _fRet = "int"; - _fName = "get" addIndNameCap; - _fParams = ""; - _fExceps = ""; - _fIsDeprecated = 0; - printTripleFunc(_fRet, _fName, _fParams, _fExceps, outFile_int_c, outFile_stb_c, outFile_jni_c, printIntAndStb_tmp_c, _noOverride, _fIsDeprecated); - print("\t\t" "return " addIndName ";") >> outFile_jni_c; - print("\t" "}") >> outFile_jni_c; - print("") >> outFile_jni_c; - - # Print the OO entity fetcher function if applicable, eg. "Unit getUnit()" - addIndNameCapOO = addIndNameCap; - _hadId = sub(/Id$/, "", addIndNameCapOO); - if (_hadId && (addIndNameCapOO in cls_name_id) && (addIndNameCapOO != clsName_int_c)) { - _refObj = addIndNameCapOO; # example: Unit - _implId = implId_m "," _refObj; - if (_implId in cls_implId_fullClsName) { - _fullClsName = cls_implId_fullClsName[_implId]; - } else if (cls_name_implIds[_refObj ",*"] == 1) { - _fullClsName = cls_name_implIds[_refObj ",0"]; - _fullClsName = cls_implId_fullClsName[_fullClsName]; - } else { - print("ERROR: failed finding the full class name for: " _refObj); - exit(1); - } - - _wrappGetInst_params = myWrapVar; - for (aij=1; aij <= ai; aij++) { - _wrappGetInst_params = _wrappGetInst_params ", " addInds_c[aij]; - } - - _fRet = addIndNameCapOO; - _fName = "get" addIndNameCapOO; - _fParams = ""; - _fExceps = ""; - _fIsDeprecated = 0; - printTripleFunc(_fRet, _fName, _fParams, _fExceps, outFile_int_c, outFile_stb_c, outFile_jni_c, printIntAndStb_tmp_c, _noOverride, _fIsDeprecated); - print("\t\t" "return Wrapp" _fullClsName ".getInstance(" _wrappGetInst_params ");") >> outFile_jni_c; - print("\t" "}") >> outFile_jni_c; - print("") >> outFile_jni_c; - } - } - - # print static instance fetcher method - { - clsIsBuffered_c = isBufferedClass(clsName_c); - _isAvailableMethod = ""; - for (_memId in clsAvailInd_memberId_cls) { - if (clsAvailInd_memberId_cls[_memId] == clsName_c) { - _isAvailableMethod = _memId; - gsub(/,/, "_", _isAvailableMethod); - } - } - - if (clsIsBuffered_c) { - print("\t" "private static java.util.Map _buffer_instances = new java.util.HashMap();") >> outFile_jni_c; - print("") >> outFile_jni_c; - } - print("\t" "public static " clsName_c " getInstance(" ctorParams ") {") >> outFile_jni_c; - print("") >> outFile_jni_c; - lastParamName = ctorParamsNoTypes; - sub(/^.*,[ \t]*/, "", lastParamName); - if (match(lastParamName, /^[^ \t]+Id$/)) { - # id's < 0 are invalid, return null - print("\t\t" "if (" lastParamName " < 0) {") >> outFile_jni_c; - print("\t\t\t" "return null;") >> outFile_jni_c; - print("\t\t" "}") >> outFile_jni_c; - print("") >> outFile_jni_c; - } - print("\t\t" clsName_c " _ret = null;") >> outFile_jni_c; - if (_isAvailableMethod == "") { - print("\t\t" "_ret = new " clsName_jni_c "(" ctorParamsNoTypes ");") >> outFile_jni_c; - } else { - print("\t\t" "boolean isAvailable = " myWrapVar "." _isAvailableMethod "(" addIndParsNoTypes_c ");") >> outFile_jni_c; - print("\t\t" "if (isAvailable) {") >> outFile_jni_c; - print("\t\t\t" "_ret = new " clsName_jni_c "(" ctorParamsNoTypes ");") >> outFile_jni_c; - print("\t\t" "}") >> outFile_jni_c; - } - if (clsIsBuffered_c) { - if (_isAvailableMethod == "") { - print("\t\t" "{") >> outFile_jni_c; - } else { - print("\t\t" "if (_ret != null) {") >> outFile_jni_c; - } - print("\t\t\t" "Integer indexHash = _ret.hashCode();") >> outFile_jni_c; - print("\t\t\t" "if (_buffer_instances.containsKey(indexHash)) {") >> outFile_jni_c; - print("\t\t\t\t" "_ret = _buffer_instances.get(indexHash);") >> outFile_jni_c; - print("\t\t\t" "} else {") >> outFile_jni_c; - print("\t\t\t\t" "_buffer_instances.put(indexHash, _ret);") >> outFile_jni_c; - print("\t\t\t" "}") >> outFile_jni_c; - print("\t\t" "}") >> outFile_jni_c; - } - print("\t\t" "return _ret;") >> outFile_jni_c; - print("\t" "}") >> outFile_jni_c; - print("") >> outFile_jni_c; - } - - - if (printIntAndStb_c) { - # print compareTo(other) method - { - print("\t" "@Override") >> outFile_abs_c; - print("\t" "public int compareTo(" clsName_c " other) {") >> outFile_abs_c; - print("\t\t" "final int BEFORE = -1;") >> outFile_abs_c; - print("\t\t" "final int EQUAL = 0;") >> outFile_abs_c; - print("\t\t" "final int AFTER = 1;") >> outFile_abs_c; - print("") >> outFile_abs_c; - print("\t\t" "if (this == other) return EQUAL;") >> outFile_abs_c; - print("") >> outFile_abs_c; - - if (isClbRootCls) { - print("\t\t" "if (this.skirmishAIId < other.skirmishAIId) return BEFORE;") >> outFile_abs_c; - print("\t\t" "if (this.skirmishAIId > other.skirmishAIId) return AFTER;") >> outFile_abs_c; - print("\t\t" "return EQUAL;") >> outFile_abs_c; - } else { - for (ai=1; ai <= addInds_size_c; ai++) { - addIndName = addInds_c[ai]; - if ((noInterfaceIndices_c == 0) || (addIndName != noInterfaceIndices_c)) { - print("\t\t" "if (this.get" capitalize(addIndName) "() < other.get" capitalize(addIndName) "()) return BEFORE;") >> outFile_abs_c; - print("\t\t" "if (this.get" capitalize(addIndName) "() > other.get" capitalize(addIndName) "()) return AFTER;") >> outFile_abs_c; - } - } - print("\t\t" "return 0;") >> outFile_abs_c; - } - print("\t" "}") >> outFile_abs_c; - print("") >> outFile_abs_c; - } - - - # print equals(other) method - if (!isClbRootCls) { - print("\t" "@Override") >> outFile_abs_c; - print("\t" "public boolean equals(Object otherObject) {") >> outFile_abs_c; - print("") >> outFile_abs_c; - print("\t\t" "if (this == otherObject) return true;") >> outFile_abs_c; - print("\t\t" "if (!(otherObject instanceof " clsName_c ")) return false;") >> outFile_abs_c; - print("\t\t" clsName_c " other = (" clsName_c ") otherObject;") >> outFile_abs_c; - print("") >> outFile_abs_c; - - #if (isClbRootCls) { - # print("\t\t" "if (this.skirmishAIId != other.skirmishAIId) return false;") >> outFile_abs_c; - # print("\t\t" "return true;") >> outFile_abs_c; - #} - #else - { - for (ai=1; ai <= addInds_size_c; ai++) { - addIndName = addInds_c[ai]; - if ((noInterfaceIndices_c == 0) || (addIndName != noInterfaceIndices_c)) { - print("\t\t" "if (this.get" capitalize(addIndName) "() != other.get" capitalize(addIndName) "()) return false;") >> outFile_abs_c; - } - } - print("\t\t" "return true;") >> outFile_abs_c; - } - print("\t" "}") >> outFile_abs_c; - print("") >> outFile_abs_c; - } - - - # print hashCode() method - if (!isClbRootCls) { - print("\t" "@Override") >> outFile_abs_c; - print("\t" "public int hashCode() {") >> outFile_abs_c; - print("") >> outFile_abs_c; - - if (isClbRootCls) { - print("\t\t" "int _res = 0;") >> outFile_abs_c; - print("") >> outFile_abs_c; - print("\t\t" "_res += this.skirmishAIId * 10E8;") >> outFile_abs_c; - } else { - print("\t\t" "int _res = 23;") >> outFile_abs_c; - print("") >> outFile_abs_c; - # NOTE: This could go wrong if we have more then 7 additional indices - # see 10E" (7-ai) below - # the conversion to int is nessesarry, - # as otherwise it would be a double, - # which would be higher then max int, - # and most hashes would end up being max int, - # when converted from double to int - for (ai=1; ai <= addInds_size_c; ai++) { - addIndName = addInds_c[ai]; - if ((noInterfaceIndices_c == 0) || (addIndName != noInterfaceIndices_c)) { - print("\t\t" "_res += this.get" capitalize(addIndName) "() * (int) (10E" (7-ai) ");") >> outFile_abs_c; - } - } - } - print("") >> outFile_abs_c; - print("\t\t" "return _res;") >> outFile_abs_c; - print("\t" "}") >> outFile_abs_c; - print("") >> outFile_abs_c; - } - - - # print toString() method - { - print("\t" "@Override") >> outFile_abs_c; - print("\t" "public String toString() {") >> outFile_abs_c; - print("") >> outFile_abs_c; - print("\t\t" "String _res = this.getClass().toString();") >> outFile_abs_c; - print("") >> outFile_abs_c; - - #if (isClbRootCls) { # NO FOLD - # print("\t\t" "_res = _res + \"(skirmishAIId=\" + this.skirmishAIId + \", \";") >> outFile_abs_c; - #} else { # NO FOLD - # print("\t\t" "_res = _res + \"(clbHash=\" + this." myWrapVar ".hashCode() + \", \";") >> outFile_abs_c; - # print("\t\t" "_res = _res + \"skirmishAIId=\" + this." myWrapVar ".SkirmishAI_getSkirmishAIId() + \", \";") >> outFile_abs_c; - for (ai=1; ai <= addInds_size_c; ai++) { - addIndName = addInds_c[ai]; - if ((noInterfaceIndices_c == 0) || (addIndName != noInterfaceIndices_c)) { - print("\t\t" "_res = _res + \"" addIndName "=\" + this.get" capitalize(addIndName) "() + \", \";") >> outFile_abs_c; - } - } - #} # NO FOLD - print("\t\t" "_res = _res + \")\";") >> outFile_abs_c; - print("") >> outFile_abs_c; - print("\t\t" "return _res;") >> outFile_abs_c; - print("\t" "}") >> outFile_abs_c; - print("") >> outFile_abs_c; - } - } - - # make these available in called functions - implId_c_ = implId_c; - clsName_c_ = clsName_c; - printIntAndStb_c_ = printIntAndStb_c; - - # print member functions - members_size = cls_name_members[clsName_int_c ",*"]; - for (m=0; m < members_size; m++) { - memName_c = cls_name_members[clsName_int_c "," m]; - fullName_c = implId_c "," memName_c; - gsub(/,/, "_", fullName_c); - if (doWrappMember(fullName_c)) { - printMember(fullName_c, memName_c, addInds_size_c); - } else { - print("JavaOO-AIWrapper: NOTE: intentionally not wrapped: " fullName_c); - } - } - - - # finnish up - if (printIntAndStb_c) { - print("}") >> outFile_int_c; - print("") >> outFile_int_c; - close(outFile_int_c); - - print("}") >> outFile_abs_c; - print("") >> outFile_abs_c; - close(outFile_abs_c); - - print("}") >> outFile_stb_c; - print("") >> outFile_stb_c; - close(outFile_stb_c); - } - print("}") >> outFile_jni_c; - print("") >> outFile_jni_c; - close(outFile_jni_c); -} - - -function isRetParamName(paramName_rp) { - return (match(paramName_rp, /_out(_|$)/) || match(paramName_rp, /(^|_)?ret_/)); -} - - -function printMember(fullName_m, memName_m, additionalIndices_m) { - - # use some vars from the printClass function (which called us) - implId_m = implId_c_; - clsName_m = clsName_c_; - printIntAndStb_m = printIntAndStb_c_; - implCls_m = implCls_c; - clsName_int_m = clsName_int_c; - clsName_stb_m = clsName_stb_c; - clsName_jni_m = clsName_jni_c; - outFile_int_m = outFile_int_c; - outFile_stb_m = outFile_stb_c; - outFile_jni_m = outFile_jni_c; - addInds_size_m = addInds_size_c; - for (ai=1; ai <= addInds_size_m; ai++) { - addInds_m[ai] = addInds_c[ai]; - } - - indent_m = "\t"; - memId_m = clsName_m "," memName_m; - retType = cls_memberId_retType[memId_m]; # this may be changed - retType_int = retType; # this is a const var - params = cls_memberId_params[memId_m]; - isFetcher = cls_memberId_isFetcher[memId_m]; - metaComment = cls_memberId_metaComment[memId_m]; - memName = fullName_m; - sub(/^.*_/, "", memName); - functionName_m = fullName_m; - sub(/^[^_]+_/, "", functionName_m); - - if (memId_m in clsAvailInd_memberId_cls) { - return; - } - - isVoid_int_m = (retType_int == "void"); - - retVar_int_m = "_ret_int"; # this is a const var - retVar_out_m = retVar_int_m; # this may be changed - declaredVarsCode = ""; - conversionCode_pre = ""; - conversionCode_post = ""; - thrownExceptions = ""; - ommitMainCall = 0; - - if (!isVoid_int_m) { - declaredVarsCode = "\t\t" retType_int " " retVar_int_m ";" "\n" declaredVarsCode; - } - - - # Rewrite meta comment - if (match(metaComment, /FETCHER:MULTI:IDs:/)) { - # convert this: FETCHER:MULTI:IDs:Group:groupIds - # to this: ARRAY:groupIds->Group - _mc_pre = metaComment; - sub(/FETCHER:MULTI:IDs:.*$/, "", _mc_pre); - _mc_fet = metaComment; - sub(/^.*FETCHER:MULTI:IDs:/, "", _mc_fet); - sub(/[ \t].*$/, "", _mc_fet); - _mc_post = metaComment; - sub(/^.*FETCHER:MULTI:IDs:[^ \t]*/, "", _mc_post); - - _refObj = _mc_fet; - sub(/:.*$/, "", _refObj); - _refPaNa = _mc_fet; - sub(/^.*:/, "", _refPaNa); - - _mc_newArr = "ARRAY:" _refPaNa "->" _refObj; - metaComment = _mc_pre _mc_newArr _mc_post; - } - if (match(metaComment, /FETCHER:MULTI:NUM:/)) { - # convert this: FETCHER:MULTI:NUM:Resource - # to this: ARRAY:RETURN_SIZE->Resource - sub(/FETCHER:MULTI:NUM:/, "ARRAY:RETURN_SIZE->", metaComment); - } - if (match(metaComment, /REF:MULTI:/)) { - # convert this: REF:MULTI:unitDefIds->UnitDef - # to this: ARRAY:unitDefIds->UnitDef - sub(/REF:MULTI:/, "ARRAY:", metaComment); - } - - # remove additional indices from the outer params - for (ai=1; ai <= addInds_size_m; ai++) { - _removed = sub(/[^,]+(, )?/, "", params); - if (!_removed && !part_isStatic(memName_m, metaComment)) { - addIndName = addInds_m[ai]; - print("ERROR: failed removing additional indices " addIndName " from method " memName_m " in class " clsName_int_m); - exit(1); - } - } - - innerParams = removeParamTypes(params); - - # add additional indices fetcher calls to inner params - addInnerParams = ""; - addInds_real_size_m = addInds_size_m; - if (part_isStatic(memName_m, metaComment)) { - addInds_real_size_m--; - } - for (ai=1; ai <= addInds_real_size_m; ai++) { - addIndName = addInds_m[ai]; - _condComma = ""; - if (addInnerParams != "") { - _condComma = ", "; - } - addInnerParams = addInnerParams _condComma "this.get" capitalize(addIndName) "()"; - } - _condComma = ""; - if ((addInnerParams != "") && (innerParams != "")) { - _condComma = ", "; - } - innerParams = addInnerParams _condComma innerParams; - - - # convert param types - paramNames_size = split(innerParams, paramNames, ", "); - for (prm = 1; prm <= paramNames_size; prm++) { - paNa = paramNames[prm]; - if (!isRetParamName(paNa)) { - if (match(paNa, /_posF3/)) { - # convert float[3] to AIFloat3 - paNaNew = paNa; - sub(/_posF3/, "", paNaNew); - sub("float\\[\\] " paNa, "AIFloat3 " paNaNew, params); - conversionCode_pre = conversionCode_pre "\t\t" "float[] " paNa " = " paNaNew ".toFloatArray();" "\n"; - } else if (match(paNa, /_colorS3/)) { - # convert short[3] to java.awt.Color - paNaNew = paNa; - sub(/_colorS3/, "", paNaNew); - sub("short\\[\\] " paNa, "java.awt.Color " paNaNew, params); - conversionCode_pre = conversionCode_pre "\t\t" "short[] " paNa " = Util.toShort3Array(" paNaNew ");" "\n"; - } - } - } - - # convert an error return int value to an Exception - # "error-return:0=OK" - if (part_isErrorReturn(metaComment) && retType == "int") { - errorRetValueOk_m = part_getErrorReturnValueOk(metaComment); - - conversionCode_post = conversionCode_post "\t\t" "if (" retVar_out_m " != " errorRetValueOk_m ") {" "\n"; - conversionCode_post = conversionCode_post "\t\t\t" "throw new CallbackAIException(\"" memName_m "\", " retVar_out_m ");" "\n"; - conversionCode_post = conversionCode_post "\t\t" "}" "\n"; - thrownExceptions = thrownExceptions ", CallbackAIException" thrownExceptions; - - retType = "void"; - } - - # convert out params to return values - paramTypeNames_size = split(params, paramTypeNames, ", "); - hasRetParam = 0; - for (prm = 1; prm <= paramTypeNames_size; prm++) { - paNa = extractParamName(paramTypeNames[prm]); - if (isRetParamName(paNa)) { - if (retType == "void") { - paTy = extractParamType(paramTypeNames[prm]); - hasRetParam = 1; - if (match(paNa, /_posF3/)) { - # convert float[3] to AIFloat3 - retParamType = "AIFloat3"; - retVar_out_m = "_ret"; - conversionCode_pre = conversionCode_pre "\t\t" "float[] " paNa " = new float[3];" "\n"; - conversionCode_post = conversionCode_post "\t\t" retVar_out_m " = new AIFloat3(" paNa "[0], " paNa "[1]," paNa "[2]);" "\n"; - declaredVarsCode = "\t\t" retParamType " " retVar_out_m ";" "\n" declaredVarsCode; - sub("(, )?float\\[\\] " paNa, "", params); - retType = retParamType; - } else if (match(paNa, /_colorS3/)) { - retParamType = "java.awt.Color"; - retVar_out_m = "_ret"; - conversionCode_pre = conversionCode_pre "\t\t" "short[] " paNa " = new short[3];" "\n"; - conversionCode_post = conversionCode_post "\t\t" retVar_out_m " = Util.toColor(" paNa ");" "\n"; - declaredVarsCode = "\t\t" retParamType " " retVar_out_m ";" "\n" declaredVarsCode; - sub("(, )?short\\[\\] " paNa, "", params); - retType = retParamType; - } else if (match(paTy, /StringBuffer/)) { - retParamType = "String"; - retVar_out_m = "_ret"; - conversionCode_pre = conversionCode_pre "\t\t" "StringBuffer " paNa " = new StringBuffer();" "\n"; - conversionCode_post = conversionCode_post "\t\t" retParamType " " retVar_out_m " = " paNa ".toString();" "\n"; - sub("(, )?StringBuffer " paNa, "", params); - retType = retParamType; - } else { - print("FAILED converting return param: " paramTypeNames[prm] " / " fullName_m); - exit(1); - } - } else { - print("FAILED converting return param: return type should be \"void\", but is \"" retType "\""); - exit(1); - } - } - } - - # REF: - refObjs_size_m = split(metaComment, refObjs_m, "REF:"); - for (ro=2; ro <= refObjs_size_m; ro++) { - _ref = refObjs_m[ro]; - sub(/[ \t].*$/, "", _ref); # remove parts after this REF part - _isMulti = match(_ref, /MULTI:/); - _isReturn = match(_ref, /RETURN->/); - - if (!_isMulti && !_isReturn) { - # convert single param reference - _refRel = _ref; - sub(/^.*:/, "", _refRel); - _paNa = _refRel; # example: resourceId - sub(/->.*$/, "", _paNa); - _refObj = _refRel; # example: Resource - sub(/^.*->/, "", _refObj); - _paNaNew = _paNa; - if (!sub(/Id$/, "", _paNaNew)) { - _paNaNew = "oo_" _paNaNew; - } - - if (_refObj == "Team" || _refObj == "FigureGroup" || _refObj == "Path") { - print("note: ignoring meta comment: REF:" _ref); - } else { - _paNa_found = sub("int " _paNa, _refObj " " _paNaNew, params); - # it may not be found if it is an output parameter - if (_paNa_found) { - conversionCode_pre = conversionCode_pre "\t\t" "int " _paNa " = " _paNaNew ".get" _refObj "Id();" "\n"; - } - } - } else if (!_isMulti && _isReturn) { - _refObj = _ref; # example: Resource - sub(/^.*->/, "", _refObj); - - if (_refObj == "Team" || _refObj == "FigureGroup" || _refObj == "Path") { - print("note: ignoring meta comment: REF:" _ref); - continue; - } - - _implId = implId_m "," _refObj; - if (_implId in cls_implId_fullClsName) { - _fullClsName = cls_implId_fullClsName[_implId]; - } else if (cls_name_implIds[_refObj ",*"] == 1) { - _fullClsName = cls_name_implIds[_refObj ",0"]; - _fullClsName = cls_implId_fullClsName[_fullClsName]; - } else { - print("ERROR: failed finding the full class name for: " _refObj); - exit(1); - } - - _retVar_out_new = retVar_out_m "_out"; - _wrappGetInst_params = myWrapVar; - _hasRetInd = 0; - _inPa_size = split(innerParams, _, ","); - if (retType != "void" && (_inPa_size == addInds_size_m || _inPa_size == 0)) { - _hasRetInd = 1; - } - for (ai=1; ai <= (addInds_size_m-_hasRetInd); ai++) { - # Very hacky! too unmotivated for proper fix, sorry. - # proper fix would involve getting the parent of the wrapped - # class and using its additional indices - if ((functionName_m != "UnitDef_WeaponMount_getWeaponDef") && (functionName_m != "Unit_Weapon_getDef")) { - _wrappGetInst_params = _wrappGetInst_params ", " addInds_m[ai]; - } - } - if (retType != "void") { - _wrappGetInst_params = _wrappGetInst_params ", " retVar_out_m; - } else { - ommitMainCall = 1; - } - conversionCode_post = conversionCode_post "\t\t" _retVar_out_new " = Wrapp" _fullClsName ".getInstance(" _wrappGetInst_params ");" "\n"; - declaredVarsCode = "\t\t" _refObj " " _retVar_out_new ";" "\n" declaredVarsCode; - retVar_out_m = _retVar_out_new; - retType = _refObj; - } else { - print("WARNING: unsupported: REF:" _ref); - } - } - - - isMap = part_isMap(fullName_m, metaComment); - if (isMap) { - - _isFetching = 1; - _isRetSize = 0; - _isObj = 0; - _mapVar_size = "_size"; - _mapVar_keys = "keys"; - _mapVar_values = "values"; - _mapType_key = "String"; - _mapType_value = "String"; - _mapType_oo_key = "String"; - _mapType_oo_value = "String"; - _mapVar_oo = "_map"; - _mapType_int = "java.util.Map<" _mapType_oo_key ", " _mapType_oo_value ">"; - _mapType_impl = "java.util.HashMap<" _mapType_oo_key ", " _mapType_oo_value ">"; - - sub("(, )?" _mapType_key "\\[\\] " _mapVar_keys, "", params); - sub("(, )?" _mapType_value "\\[\\] " _mapVar_values, "", params); - sub(/, $/ , "", params); - - declaredVarsCode = "\t\t" "int " _mapVar_size ";" "\n" declaredVarsCode; - if (_isFetching) { - declaredVarsCode = "\t\t" _mapType_int " " _mapVar_oo ";" "\n" declaredVarsCode; - } - if (!_isRetSize) { - declaredVarsCode = "\t\t" _mapType_key "[] " _mapVar_keys ";" "\n" declaredVarsCode; - declaredVarsCode = "\t\t" _mapType_value "[] " _mapVar_values ";" "\n" declaredVarsCode; - if (_isFetching) { - conversionCode_pre = conversionCode_pre "\t\t" _mapVar_keys " = null;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _mapVar_values " = null;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _mapVar_size " = " myWrapVar "." functionName_m "(" innerParams ");" "\n"; - } else { - #conversionCode_pre = conversionCode_pre "\t\t" _arraySizeVar " = " _arrayListVar ".size();" "\n"; - #conversionCode_pre = conversionCode_pre "\t\t" "int _size = " _arraySizeVar ";" "\n"; - } - } - - if (_isRetSize) { - #conversionCode_post = conversionCode_post "\t\t" _arraySizeVar " = " retVar_out_m ";" "\n"; - #_arraySizeMaxPaNa = _arraySizeVar; - } else { - conversionCode_pre = conversionCode_pre "\t\t" _mapVar_keys " = new " _mapType_key "[" _mapVar_size "];" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _mapVar_values " = new " _mapType_value "[" _mapVar_size "];" "\n"; - } - - if (_isFetching) { - # convert to a HashMap - conversionCode_post = conversionCode_post "\t\t" _mapVar_oo " = new " _mapType_impl "();" "\n"; - conversionCode_post = conversionCode_post "\t\t" "for (int i=0; i < " _mapVar_size "; i++) {" "\n"; -# if (_isObj) { -# if (_isRetSize) { - conversionCode_post = conversionCode_post "\t\t\t" _mapVar_oo ".put(" _mapVar_keys "[i], " _mapVar_values "[i]);" "\n"; -# } else { - #conversionCode_post = conversionCode_post "\t\t\t" _mapVar_oo ".put(" myPkgA ".Wrapp" _refObj ".getInstance(" myWrapVar _addWrappVars ", " _arrayPaNa "[i]));" "\n"; -# } -# } else if (_isNative) { - #conversionCode_post = conversionCode_post "\t\t\t" _arrayListVar ".add(" _arrayPaNa "[i]);" "\n"; -# } - conversionCode_post = conversionCode_post "\t\t" "}" "\n"; - - retParamType = _mapType_int; - retVar_out_m = _mapVar_oo; - retType = retParamType; - } else { - # convert from a HashMap - } - } - - - isArray = part_isArray(fullName_m, metaComment); - if (isArray) { - _refObj = ""; - _arrayPaNa = metaComment; - _addWrappVars = ""; - sub(/^.*ARRAY:/, "", _arrayPaNa); - sub(/[ \t].*$/, "", _arrayPaNa); - if (match(_arrayPaNa, /->/)) { - _refObj = _arrayPaNa; - sub(/->.*$/, "", _arrayPaNa); - sub(/^.*->/, "", _refObj); - _refObjInt = _refObj; - - if (match(_refObj, /-/)) { - sub(/-.*$/, "", _refObj); - sub(/^.*-/, "", _refObjInt); - } - _implId = implId_m "," _refObj; - if (_implId in cls_implId_fullClsName) { - _fullClsName = cls_implId_fullClsName[_implId]; - } else if ((myRootClass "," _refObj) in cls_implId_fullClsName) { - _implId = myRootClass "," _refObj; - _fullClsName = cls_implId_fullClsName[_implId]; - } else { - print("ERROR: failed to find the full class name for " _refObj " in " fullName_m); - exit(1); - } - _refObj = _fullClsName; - _addWrappVars = cls_implId_indicesArgs[_implId]; - sub(/(,)?[^,]*$/, "", _addWrappVars); # remove last index - _addWrappVars = trim(removeParamTypes(_addWrappVars)); - if (_addWrappVars != "") { - _addWrappVars = ", " _addWrappVars; - } - } - - _isF3 = match(_arrayPaNa, /_AposF3/); - _isObj = (_refObj != ""); - _isNative = (!_refObj && !_isObjc); - - _isRetSize = 0; - if (_isObj) { - _isRetSize = (_arrayPaNa == "RETURN_SIZE"); - } - - _arrayType = params; - sub("\\[\\][ \t]" _arrayPaNa ".*$", "", _arrayType); - sub("^.*[ \t]", "", _arrayType); - _arraySizeMaxPaNa = _arrayPaNa "_sizeMax"; - _arraySizeVar = _arrayPaNa "_size"; - _arraySizeRaw = _arrayPaNa "_raw_size"; - - _arrayListVar = _arrayPaNa "_list"; - if (_isF3) { - _arrListGenType = "AIFloat3"; - } else if (_isObj) { - _arrListGenType = _refObjInt; - } else if (_isNative) { - _arrListGenType = convertJavaBuiltinTypeToClass(_arrayType); - } - _arrListType = "java.util.List<" _arrListGenType ">"; - _arrListImplType = "java.util.ArrayList<" _arrListGenType ">"; - - _isFetching = sub("(, )?int " _arraySizeMaxPaNa, "", params); - if (_isRetSize) { - _isFetching = 1; - } else { - if (!_isFetching && !_isRetSize) { - _isNonFetcher = sub("(, )?int " _arraySizeVar, "", params); - if (!_isNonFetcher) { - print("ERROR: neither propper fetcher nor supplier ARRAY syntax in function: " fullName_m); - exit(1); - } - } - if (_isFetching) { - sub(_arrayType "\\[\\] " _arrayPaNa, "", params); - } else { - sub(_arrayType "\\[\\] " _arrayPaNa, _arrListType " " _arrayListVar, params); - } - sub(/^, /, "", params); - sub(/, $/, "", params); - } - - declaredVarsCode = "\t\t" "int " _arraySizeVar ";" "\n" declaredVarsCode; - if (_isFetching) { - declaredVarsCode = "\t\t" _arrListType " " _arrayListVar ";" "\n" declaredVarsCode; - } - if (!_isRetSize) { - declaredVarsCode = "\t\t" _arrayType "[] " _arrayPaNa ";" "\n" declaredVarsCode; - declaredVarsCode = "\t\t" "int " _arraySizeRaw ";" "\n" declaredVarsCode; - if (_isFetching) { - declaredVarsCode = "\t\t" "int " _arraySizeMaxPaNa ";" "\n" declaredVarsCode; - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeMaxPaNa " = Integer.MAX_VALUE;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _arrayPaNa " = null;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeVar " = " myWrapVar "." functionName_m "(" innerParams ");" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeMaxPaNa " = " _arraySizeVar ";" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeRaw " = " _arraySizeVar ";" "\n"; - if (_isF3) { - conversionCode_pre = conversionCode_pre "\t\t" "if (" _arraySizeVar " % 3 != 0) {" "\n"; - conversionCode_pre = conversionCode_pre "\t\t\t" "throw new RuntimeException(\"returned AIFloat3 array has incorrect size (\" + " _arraySizeVar "+ \"), should be a multiple of 3.\");" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" "}" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeVar " /= 3;" "\n"; - } - } else { - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeVar " = " _arrayListVar ".size();" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" "int _size = " _arraySizeVar ";" "\n"; - if (_isF3) { - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeVar " *= 3;" "\n"; - } - conversionCode_pre = conversionCode_pre "\t\t" _arraySizeRaw " = " _arraySizeVar ";" "\n"; - } - } - - if (_isRetSize) { - conversionCode_post = conversionCode_post "\t\t" _arraySizeVar " = " retVar_out_m ";" "\n"; - _arraySizeMaxPaNa = _arraySizeVar; - } else { - conversionCode_pre = conversionCode_pre "\t\t" _arrayPaNa " = new " _arrayType "[" _arraySizeRaw "];" "\n"; - } - - if (_isFetching) { - # convert to an ArrayList - conversionCode_post = conversionCode_post "\t\t" _arrayListVar " = new " _arrListImplType "(" _arraySizeVar ");" "\n"; - conversionCode_post = conversionCode_post "\t\t" "for (int i=0; i < " _arraySizeMaxPaNa "; i++) {" "\n"; - if (_isF3) { - conversionCode_post = conversionCode_post "\t\t\t" _arrayListVar ".add(new AIFloat3(" _arrayPaNa "[i], " _arrayPaNa "[++i], " _arrayPaNa "[++i]));" "\n"; - } else if (_isObj) { - if (_isRetSize) { - conversionCode_post = conversionCode_post "\t\t\t" _arrayListVar ".add(" myPkgA ".Wrapp" _refObj ".getInstance(" myWrapVar _addWrappVars ", i));" "\n"; - } else { - conversionCode_post = conversionCode_post "\t\t\t" _arrayListVar ".add(" myPkgA ".Wrapp" _refObj ".getInstance(" myWrapVar _addWrappVars ", " _arrayPaNa "[i]));" "\n"; - } - } else if (_isNative) { - conversionCode_post = conversionCode_post "\t\t\t" _arrayListVar ".add(" _arrayPaNa "[i]);" "\n"; - } - conversionCode_post = conversionCode_post "\t\t" "}" "\n"; - - retParamType = _arrListType; - retVar_out_m = _arrayListVar; - retType = retParamType; - } else { - # convert from an ArrayList - conversionCode_pre = conversionCode_pre "\t\t" "for (int i=0; i < _size; i++) {" "\n"; - if (_isF3) { - conversionCode_pre = conversionCode_pre "\t\t\t" "int arrInd = i*3;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t\t" "AIFloat3 aif3 = " _arrayListVar ".get(i);" "\n"; - conversionCode_pre = conversionCode_pre "\t\t\t" _arrayPaNa "[arrInd] = aif3.x;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t\t" _arrayPaNa "[arrInd+1] = aif3.y;" "\n"; - conversionCode_pre = conversionCode_pre "\t\t\t" _arrayPaNa "[arrInd+2] = aif3.z;" "\n"; - } else if (_isObj) { - conversionCode_pre = conversionCode_pre "\t\t\t" _arrayPaNa "[i] = " _arrayListVar ".get(i).get" _refObj "Id();" "\n"; - } else if (_isNative) { - conversionCode_pre = conversionCode_pre "\t\t\t" _arrayPaNa "[i] = " _arrayListVar ".get(i);" "\n"; - } - conversionCode_pre = conversionCode_pre "\t\t" "}" "\n"; - } - } - - firstLineEnd = ";"; - mod_m = ""; - if (!isInterface_m) { - firstLineEnd = " {"; - mod_m = "public "; - } - - sub(/^, /, "", thrownExceptions); - - print("") >> outFile_jni_m; - - isBuffered_m = !isVoid_m && isBufferedFunc(fullName_m) && (params == ""); - if (!isInterface_m && isBuffered_m) { - print(indent_m retType " _buffer_" memName ";") >> outFile_jni_m; - print(indent_m "boolean _buffer_isInitialized_" memName " = false;") >> outFile_jni_m; - } - - # print method doc comment - fullName_doc_m = fullName_m; - sub(/^[^_]*_/, "", fullName_doc_m); # remove OOAICallback_ - if (printIntAndStb_m) { - printFunctionComment_Common(outFile_int_m, funcDocComment, fullName_doc_m, indent_m); - printFunctionComment_Common(outFile_stb_m, funcDocComment, fullName_doc_m, indent_m); - } - printFunctionComment_Common(outFile_jni_m, funcDocComment, fullName_doc_m, indent_m); - - _fNoOverride = 0; - commentText = getFunctionComment_Common(funcDocComment, fullName_doc_m); - _fIsDeprecated = match(commentText, /@deprecated/); - printTripleFunc(retType, memName, params, thrownExceptions, outFile_int_m, outFile_stb_m, outFile_jni_m, printIntAndStb_m, _fNoOverride, _fIsDeprecated); - - isVoid_m = (retType == "void"); - - if (!isInterface_m) { - condRet_int_m = isVoid_int_m ? "" : retVar_int_m " = "; - indent_m = indent_m "\t"; - - if (isBuffered_m) { - print(indent_m "if (!_buffer_isInitialized_" memName ") {") >> outFile_jni_m; - indent_m = indent_m "\t"; - } - if (declaredVarsCode != "") { - print(declaredVarsCode) >> outFile_jni_m; - } - if (conversionCode_pre != "") { - print(conversionCode_pre) >> outFile_jni_m; - } - if (!ommitMainCall) { - print(indent_m condRet_int_m myWrapVar "." functionName_m "(" innerParams ");") >> outFile_jni_m; - } - if (conversionCode_post != "") { - print(conversionCode_post) >> outFile_jni_m; - } - if (isBuffered_m) { - print(indent_m "_buffer_" memName " = " retVar_out_m ";") >> outFile_jni_m; - print(indent_m "_buffer_isInitialized_" memName " = true;") >> outFile_jni_m; - sub(/\t/, "", indent_m); - print(indent_m "}") >> outFile_jni_m; - print("") >> outFile_jni_m; - retVar_out_m = "_buffer_" memName; - } - if (!isVoid_m) { - print(indent_m "return " retVar_out_m ";") >> outFile_jni_m; - } - sub(/\t/, "", indent_m); - print(indent_m "}") >> outFile_jni_m; - } -} - - -function doWrappMember(fullName_dwm) { - - doWrapp_dwm = 1; - - return doWrapp_dwm; -} - -# Used by the common OO AWK script -function doWrappOO(funcFullName_dw, params_dw, metaComment_dw) { - - doWrapp_dw = 1; - - #doWrapp_dw = doWrapp_dw && !match(funcFullName_dw, /Lua_callRules/) && !match(funcFullName_dw, /Lua_callUI/); - - return doWrapp_dw; -} - -function wrappFunctionDef(funcDef, commentEolTot) { - - size_funcParts = split(funcDef, funcParts, "(\\()|(\\);)"); - # because the empty part after ");" would count as part as well - size_funcParts--; - - fullName = funcParts[1]; - fullName = trim(fullName); - sub(/.*[ \t]+/, "", fullName); - - retType = funcParts[1]; - sub(/[ \t]*public/, "", retType); - sub(fullName, "", retType); - retType = trim(retType); - - params = funcParts[2]; - - wrappFunctionPlusMeta(retType, fullName, params, commentEolTot); -} - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return isMultiLineFunc != 1; -} - - -# grab callback functions info -# 2nd, 3rd, ... line of a function definition -{ - if (isMultiLineFunc) { # function is defined on one single line - funcIntermLine = $0; - # separate possible comment at end of line: // fu bar - commentEol = funcIntermLine; - if (sub(/.*\/\//, "", commentEol)) { - commentEolTot = commentEolTot commentEol; - } - sub(/[ \t]*\/\/.*$/, "", funcIntermLine); - funcIntermLine = trim(funcIntermLine); - funcSoFar = funcSoFar " " funcIntermLine; - if (match(funcSoFar, /;$/)) { - # function ends in this line - wrappFunctionDef(funcSoFar, commentEolTot); - isMultiLineFunc = 0; - } - } -} -# 1st line of a function definition -/\tpublic .*\);/ { - - funcStartLine = $0; - # separate possible comment at end of line: // foo bar - commentEolTot = ""; - commentEol = funcStartLine; - if (sub(/.*\/\//, "", commentEol)) { - commentEolTot = commentEolTot commentEol; - } - # remove possible comment at end of line: // foo bar - sub(/\/\/.*$/, "", funcStartLine); - funcStartLine = trim(funcStartLine); - if (match(funcStartLine, /;$/)) { - # function ends in this line - wrappFunctionDef(funcStartLine, commentEolTot); - } else { - funcSoFar = funcStartLine; - isMultiLineFunc = 1; - } -} - - - -END { - # finalize things - store_everything(); - printClasses(); -} diff --git a/AI/Wrappers/JavaOO/bin/wrappEvents.awk b/AI/Wrappers/JavaOO/bin/wrappEvents.awk deleted file mode 100755 index d044b135740..00000000000 --- a/AI/Wrappers/JavaOO/bin/wrappEvents.awk +++ /dev/null @@ -1,627 +0,0 @@ -#!/usr/bin/awk -f -# -# This awk script creates a java class in OO style to wrap the C style -# JNI based AI Events wrapper interface. -# In other words, the output of this file wraps: -# com/springrts/ai/AI.java -# which wraps: -# rts/ExternalAI/Interface/AISEvents.h -# -# This script uses functions from the following files: -# * common.awk -# * commonDoc.awk -# * commonOOCallback.awk -# Variables that can be set on the command-line (with -v): -# * GENERATED_SOURCE_DIR : the generated sources root dir -# * JAVA_GENERATED_SOURCE_DIR : the generated java sources root dir -# * INTERFACE_SOURCE_DIR : the Java AI Interfaces static source files root dir -# * INTERFACE_GENERATED_SOURCE_DIR : the Java AI Interfaces generated source files root dir -# - -BEGIN { - # initialize things - - # define the field splitter(-regex) - FS = "(\\()|(\\);)"; - IGNORECASE = 0; - - # Used by other scripts - JAVA_MODE = 1; - - # These vars can be assigned externally, see file header. - # Set the default values if they were not supplied on the command line. - if (!GENERATED_SOURCE_DIR) { - GENERATED_SOURCE_DIR = "../src-generated/main"; - } - if (!JAVA_GENERATED_SOURCE_DIR) { - JAVA_GENERATED_SOURCE_DIR = GENERATED_SOURCE_DIR "/java"; - } - if (!INTERFACE_SOURCE_DIR) { - INTERFACE_SOURCE_DIR = "../../../Interfaces/Java/src/main/java"; - } - if (!INTERFACE_GENERATED_SOURCE_DIR) { - INTERFACE_GENERATED_SOURCE_DIR = "../../../Interfaces/Java/src-generated/main/java"; - } - - javaSrcRoot = "../src/main/java"; - - myParentPkgA = "com.springrts.ai"; - myMainPkgA = myParentPkgA ".oo"; - myPkgClbA = myMainPkgA ".clb"; - myPkgEvtA = myMainPkgA ".evt"; - myMainPkgD = convertJavaNameFormAToD(myMainPkgA); - myPkgEvtD = convertJavaNameFormAToD(myPkgEvtA); - - aiFloat3Class = "AIFloat3"; - - myOOAIClass = "OOAI"; - myOOAIInterface = "I" myOOAIClass; - myOOAIAbstractClass = "AbstractOOAI"; - myOOEventAIClass = "OOEventAI"; - myOOEventAIInterface = "I" myOOEventAIClass; - myOOAIFile = JAVA_GENERATED_SOURCE_DIR "/" myMainPkgD "/" myOOAIClass ".java"; - myOOAIInterfaceFile = JAVA_GENERATED_SOURCE_DIR "/" myMainPkgD "/" myOOAIInterface ".java"; - myOOAIAbstractFile = JAVA_GENERATED_SOURCE_DIR "/" myMainPkgD "/" myOOAIAbstractClass ".java"; - myOOEventAIFile = JAVA_GENERATED_SOURCE_DIR "/" myMainPkgD "/" myOOEventAIClass ".java"; - myOOEventAIInterfaceFile = JAVA_GENERATED_SOURCE_DIR "/" myMainPkgD "/" myOOEventAIInterface ".java"; - - printOOAIHeader(myOOAIFile, myOOAIClass); - printOOAIHeader(myOOAIInterfaceFile, myOOAIInterface); - printOOAIHeader(myOOAIAbstractFile, myOOAIAbstractClass); - printOOEventAIHeader(myOOEventAIFile); - printOOEventAIHeader(myOOEventAIInterfaceFile); - - ind_evt = 0; -} - - - -function printOOAIHeader(outFile, clsName) { - - printCommentsHeader(outFile); - print("") >> outFile; - print("package " myMainPkgA ";") >> outFile; - print("") >> outFile; - print("") >> outFile; - if (clsName != myOOAIInterface) { - print("import " myParentPkgA ".AI;") >> outFile; - } - if (clsName == myOOAIClass) { - print("import " myParentPkgA ".AICallback;") >> outFile; - print("import " myMainPkgA ".clb.WrappOOAICallback;") >> outFile; - print("import " myMainPkgA ".clb.WrappUnit;") >> outFile; - print("import " myMainPkgA ".clb.WrappWeaponDef;") >> outFile; - } - print("import " myMainPkgA ".AIFloat3;") >> outFile; - print("import " myMainPkgA ".clb.OOAICallback;") >> outFile; - print("import " myMainPkgA ".clb.Unit;") >> outFile; - print("import " myMainPkgA ".clb.WeaponDef;") >> outFile; - print("") >> outFile; - print("/**") >> outFile; - print(" * TODO: Add description here") >> outFile; - print(" *") >> outFile; - print(" * @author hoijui") >> outFile; - print(" * @version GENERATED") >> outFile; - print(" */") >> outFile; - - _type = "abstract class"; - _extends = ""; - _implements = " implements " myOOAIInterface ", AI"; - if (clsName == myOOAIAbstractClass) { - _extends = " extends " myOOAIClass; - } - if (clsName == myOOAIInterface) { - _type = "interface"; - _implements = ""; - } - print("public " _type " " clsName _extends _implements " {") >> outFile; - print("") >> outFile; - - if (clsName == myOOAIClass) { - print("\t" "private AICallback clb = null;") >> outFile; - print("\t" "private OOAICallback clbOO = null;") >> outFile; - print("") >> outFile; - } -} -function printOOAIEnd(outFile) { - - print("}") >> outFile; - print("") >> outFile; -} - -function printOOEventAIHeader(outFile) { - - printCommentsHeader(outFile); - print("") >> outFile; - print("package " myMainPkgA ";") >> outFile; - print("") >> outFile; - print("") >> outFile; - print("import " myParentPkgA ".AI;") >> outFile; - print("import " myMainPkgA "." myOOAIClass ";") >> outFile; - print("import " myPkgEvtA ".*;") >> outFile; - print("import " myPkgClbA ".*;") >> outFile; - print("") >> outFile; - print("/**") >> outFile; - print(" * TODO: Add description here") >> outFile; - print(" *") >> outFile; - print(" * @author hoijui") >> outFile; - print(" * @version GENERATED") >> outFile; - print(" */") >> outFile; - if (outFile == myOOEventAIFile) { - print("public abstract class " myOOEventAIClass " extends " myOOAIClass " implements " myOOEventAIInterface ", AI {") >> outFile; - } else { - print("public interface " myOOEventAIInterface " {") >> outFile; - } - print("") >> outFile; - - print("\t" "/**") >> outFile; - print("\t" " * TODO: Add description here") >> outFile; - print("\t" " *") >> outFile; - print("\t" " * @param event the AI event to handle, sent by the engine") >> outFile; - print("\t" " * @throws AIException") >> outFile; - print("\t" " */") >> outFile; - _modifyer = ""; - if (outFile == myOOEventAIFile) { - _modifyer = " abstract"; - } - print("\t" "public" _modifyer " void handleEvent(AIEvent event) throws EventAIException;") >> outFile; - print("") >> outFile; -} -function printOOEventAIEnd(outFile) { - - print("}") >> outFile; - print("") >> outFile; -} - - -function convertJavaSimpleTypeToOO(paType_sto, paName_sto, - paTypeNew_sto, paNameNew_sto, convPre_sto, convPost_sto) { - - _change = 1; - - # uses this global vars: - # - paramTypeNew - # - paramNameNew - # - conversionCode_pre - # - conversionCode_post - - paramTypeNew = paType_sto; - paramNameNew = paName_sto; - - if (match(paName_sto, /_posF3/)) { - # convert float[3] to AIFloat3 - sub(/_posF3/, "", paramNameNew); - paramTypeNew = "AIFloat3"; - conversionCode_pre = conversionCode_pre "\t\t" paramTypeNew " " paramNameNew " = new " paramTypeNew "(" paName_sto ");" "\n"; - #conversionCode_pre = conversionCode_pre "\t\t" paType_sto " " paName_sto " = " paNameNew_sto ".toFloatArray();" "\n"; - } else if (match(paName_sto, /_colorS3/)) { - # convert short[3] to java.awt.Color - sub(/_colorS3/, "", paramNameNew); - paramTypeNew = "java.awt.Color"; - conversionCode_pre = conversionCode_pre "\t\t" paramTypeNew " " paramNameNew " = Util.toColor(" paName_sto ");" "\n"; - #conversionCode_pre = conversionCode_pre "\t\t" paType_sto " " paName_sto " = Util.toShort3Array(" paNameNew_sto ");" "\n"; - } else if ((paType_sto == "int") && match(paName_sto, /(unit|builder|attacker|enemy)(Id)?$/)) { - # convert int to Unit - sub(/Id$/, "", paramNameNew); - paramNameNew = "oo_" paramNameNew; - paramTypeNew = "Unit"; - conversionCode_pre = conversionCode_pre "\t\t" paramTypeNew " " paramNameNew " = Wrapp" paramTypeNew ".getInstance(this.clb, " paName_sto ");" "\n"; - } else if ((paType_sto == "int[]") && match(paName_sto, /unit(s|Ids)$/)) { - # convert int[] to List - sub(/(Id)?s$/, "s", paramNameNew); - paramNameNew = "oo_" paramNameNew; - paramTypeNew = "java.util.List"; - conversionCode_pre = conversionCode_pre "\t\t" paramTypeNew " " paramNameNew " = new java.util.ArrayList();" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" "for (int u=0; u < " paName_sto ".length; u++) {" "\n"; - conversionCode_pre = conversionCode_pre "\t\t\t" paramNameNew ".add(WrappUnit.getInstance(this.clb, " paName_sto "[u]));" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" "}" "\n"; - } else if ((paType_sto == "int") && match(paName_sto, /(weaponDef)(Id)?$/)) { - # convert int to WeaponDef - sub(/Id$/, "", paramNameNew); - paramNameNew = "oo_" paramNameNew; - paramTypeNew = "WeaponDef"; - conversionCode_pre = conversionCode_pre "\t\t" paramTypeNew " " paramNameNew " = Wrapp" paramTypeNew ".getInstance(this.clb, " paName_sto ");" "\n"; - } else if (paType_sto == "AICallback") { - # convert AICallback to OOAICallback - paramNameNew = "oo_" paramNameNew; - paramTypeNew = "OOAICallback"; - conversionCode_pre = conversionCode_pre "\t\t" "this.clb = " paName_sto ";" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" "this.clbOO = Wrapp" paramTypeNew ".getInstance(" paName_sto ");" "\n"; - conversionCode_pre = conversionCode_pre "\t\t" paramTypeNew " " paramNameNew " = this.clbOO;" "\n"; - } else { - _change = 0; - } - - return _change; -} - - -function printEventsOO() { - - # agarra te los event interfaces - for (e=0; e < evts_size; e++) { - meta_es = evts_meta[e]; - - interfList_size_es = 0; - if (match(meta_es, /INTERFACES:/)) { - interfMeta_es = meta_es; - sub(/^.*INTERFACES:/, "", interfMeta_es); - sub(/[ \t].*$/, "", interfMeta_es); - interfList_size_es = split(interfMeta_es, interfList_es, /\),/); - - for (i=1; i <= interfList_size_es; i++) { - _intName = interfList_es[i]; - sub(/\(.*$/, "", _intName); - _intParams = interfList_es[i]; - sub(/^.*\(/, "", _intParams); - sub(/\)$/, "", _intParams); - - if (!(_intName in int_names)) { - int_names[_intName] = _intParams; - } - evts_intNames[e "," (i-1)] = _intName; - evts_intParams[e "," (i-1)] = _intParams; - } - } - evts_intNames[e ",*"] = interfList_size_es; - } - - # print the event classes - for (e=0; e < evts_size; e++) { - printEventOO(e); - } - - # print the event interfaces - for (intName in int_names) { - printOOEventInterface(intName); - } -} - -function printEventOO(ind_evt_em) { - - retType_em = evts_retType[ind_evt_em]; - name_em = evts_name[ind_evt_em]; - params_em = evts_params[ind_evt_em]; - meta_em = evts_meta[ind_evt_em]; - - paramsList_size_em = split(params_em, paramsList_em, ", "); - - conversionCode_pre = ""; - conversionCode_post = ""; - ooParams_em = ""; - - for (p=1; p <= paramsList_size_em; p++) { - _param = paramsList_em[p]; - _paramType = _param; - sub(/ [^ ]*$/, "", _paramType); - _paramName = _param; - sub(/^[^ ]* /, "", _paramName); - - paramTypeNew = ""; - paramNameNew = ""; - convertJavaSimpleTypeToOO(_paramType, _paramName); - - if (!match(_paramName, /_size$/)) { - ooParams_em = ooParams_em ", " paramTypeNew " " paramNameNew; - } - } - sub(/^, /, "", ooParams_em); - - _equalMethod = (ooParams_em == params_em); - _isVoid = (retType_em == "void"); - if (_isVoid) { - _condRet = ""; - } else { - _condRet = "_ret = "; - } - - print("") >> myOOAIFile; - - if (!_equalMethod) { - ooParamNames_em = removeParamTypes(ooParams_em); - print("\t" "@Override") >> myOOAIFile; - print("\t" "public final " retType_em " " name_em "(" params_em ") {") >> myOOAIFile; - print("") >> myOOAIFile; - - if (!_isVoid) { - print("\t\t" retType_em " _ret;") >> myOOAIFile; - print("") >> myOOAIFile; - } - if (conversionCode_pre != "") { - print(conversionCode_pre) >> myOOAIFile; - } - - print("\t\t" _condRet "this." name_em "(" ooParamNames_em ");") >> myOOAIFile; - - if (conversionCode_post != "") { - print(conversionCode_post) >> myOOAIFile; - } - if (!_isVoid) { - print("") >> myOOAIFile; - print("\t\t" "return _ret;") >> myOOAIFile; - } - - print("\t" "}") >> myOOAIFile; - } - - printFunctionComment_Common(myOOAIFile, evts_docComment, ind_evt_em, "\t"); - print("\t" "@Override") >> myOOAIFile; - if (retType_em == "int") { - print("\t" "public " retType_em " " name_em "(" ooParams_em ") { return 0; }") >> myOOAIFile; - } else { - print("Warning: No default return value given for event return-type " retType_em); - print("\t" "public abstract " retType_em " " name_em "(" ooParams_em ");") >> myOOAIFile; - } - - ooParamsCleaned_em = ooParams_em; - gsub(/ oo_/, " ", ooParamsCleaned_em); - - print("") >> myOOAIInterfaceFile; - printFunctionComment_Common(myOOAIInterfaceFile, evts_docComment, ind_evt_em, "\t"); - print("\t" "public " retType_em " " name_em "(" ooParamsCleaned_em ");") >> myOOAIInterfaceFile; - - print("") >> myOOAIAbstractFile; - printFunctionComment_Common(myOOAIAbstractFile, evts_docComment, ind_evt_em, "\t"); - print("\t" "@Override") >> myOOAIAbstractFile; - print("\t" "public " retType_em " " name_em "(" ooParamsCleaned_em ") {") >> myOOAIAbstractFile; - print("\t\t" "return 0; // signaling: OK") >> myOOAIAbstractFile; - print("\t" "}") >> myOOAIAbstractFile; - - printOOEventWrapper(retType_em, name_em, ooParamsCleaned_em, meta_em, ind_evt_em); -} - -function printOOEventWrapper(retType_ei, mthName_ei, ooParams_ei, meta_ei, ind_evt_ei) { - - outFile = myOOEventAIFile; - ooParamsNoTypes_ei = removeParamTypes(ooParams_ei); - evtName_ei = capitalize(mthName_ei) "AIEvent"; - - print("\t" "@Override") >> outFile; - print("\t" "public final " retType_ei " " mthName_ei "(" ooParams_ei ") {") >> outFile; - print("") >> outFile; - print("\t\t" "AIEvent evt = new " evtName_ei "(" ooParamsNoTypes_ei ");") >> outFile; - print("\t\t" "try {") >> outFile; - print("\t\t\t" "this.handleEvent(evt);") >> outFile; - print("\t\t\t" "return 0; // everything OK") >> outFile; - print("\t\t" "} catch (EventAIException ex) {") >> outFile; - print("\t\t\t" "return ex.getErrorNumber();") >> outFile; - print("\t\t" "}") >> outFile; - print("\t" "}") >> outFile; - print("") >> outFile; - - printOOEventClass(retType_ei, evtName_ei, ooParams_ei, meta_ei, ind_evt_ei); -} - -function printOOEventClass(retType_ec, evtName_ec, ooParams_ec, meta_ec, ind_evt_ec) { - - outFile = JAVA_GENERATED_SOURCE_DIR "/" myPkgEvtD "/" evtName_ec ".java"; - - ooParamsList_size_ec = split(ooParams_ec, ooParamsList_ec, ", "); - int_size_ec = evts_intNames[ind_evt_ec ",*"]; - - # list up interface parameters - # clear arrays - split("", intParams_toPrint_ec); - split("", myIntParams_intParams_ec); - split("", myIntParams_int_ec); - for (_ii=0; _ii < int_size_ec; _ii++) { - _name = evts_intNames[ind_evt_ec "," _ii]; - _myIntParams = evts_intParams[ind_evt_ec "," _ii]; - _intParams = int_names[_name]; - - _myIntParamsList_size = split(_myIntParams, _myIntParamsList, ","); - _intParamsList_size = split(_intParams, _intParamsList, ","); - - for (_p=1; _p <= _intParamsList_size; _p++) { - _myIntParam = _myIntParamsList[_p]; - _intParam = _intParamsList[_p]; - - intParams_toPrint_ec[_intParam] = 1; - myIntParams_int_ec[_myIntParam] = _name; - if (_myIntParam != _intParam) { - myIntParams_intParams_ec[_myIntParam] = _intParam; - } - } - } - - _addIntLst = ""; - for (i=0; i < int_size_ec; i++) { - _addIntLst = _addIntLst ", " evts_intNames[ind_evt_ec "," i] "AIEvent"; - } - - # print comments header - printCommentsHeader(outFile); - print("") >> outFile; - - print("package " myPkgEvtA ";") >> outFile; - print("") >> outFile; - print("") >> outFile; - - # print imports - print("import " myMainPkgA ".AIEvent;") >> outFile; - print("import " myMainPkgA ".AIFloat3;") >> outFile; - print("import " myPkgClbA ".*;") >> outFile; - print("") >> outFile; - - # print class header - printFunctionComment_Common(outFile, evts_docComment, ind_evt_ec, ""); - print("public class " evtName_ec " implements AIEvent" _addIntLst " {") >> outFile; - print("") >> outFile; - - # print member vars - for (_p=1; _p <= ooParamsList_size_ec; _p++) { - print("\t" "private " ooParamsList_ec[_p] ";") >> outFile; - } - print("") >> outFile; - - # print constructor - print("\t" "public " evtName_ec "(" ooParams_ec ") {") >> outFile; - print("") >> outFile; - for (_p=1; _p <= ooParamsList_size_ec; _p++) { - _name = extractParamName(ooParamsList_ec[_p]); - print("\t\t" "this." _name " = " _name ";") >> outFile; - } - print("\t" "}") >> outFile; - print("") >> outFile; - - # print member getters - for (_p=1; _p <= ooParamsList_size_ec; _p++) { - _type = extractParamType(ooParamsList_ec[_p]); - _name = extractParamName(ooParamsList_ec[_p]); - - # save the type for later writing of interfaces, - # in case it is a ninterface param - if (_name in intParams_toPrint_ec) { - _intName = _name; - if (_name in myIntParams_intParams_ec) { - _intName = myIntParams_intParams_ec[_name]; - } - _int = myIntParams_int_ec[_name]; - - int_name_param_type[_int "," _intName] = _type; - # hacky - int_name_param_type[_int "," _name] = _type; - } - - # print out @Override if this is an interface member - if (_name in intParams_toPrint_ec && intParams_toPrint_ec[_name] == 1) { - print("\t" "@Override") >> outFile; - intParams_toPrint_ec[_name] = 0; - } - - print("\t" "public " _type " get" capitalize(_name) "() {") >> outFile; - print("\t\t" "return this." _name ";") >> outFile; - print("\t" "}") >> outFile; - - # print out another getter if the interface param name is different - if (_name in myIntParams_intParams_ec) { - _intName = myIntParams_intParams_ec[_name]; - intParams_toPrint_ec[_intName] = 0; - - print("\t" "@Override") >> outFile; - print("\t" "public " _type " get" capitalize(_intName) "() {") >> outFile; - print("\t\t" "return this.get" capitalize(_name) "();") >> outFile; - print("\t" "}") >> outFile; - } - - print("") >> outFile; - } - - print("}") >> outFile; - - close(outFile); -} - -function printOOEventInterface(int_name_ei) { - - outFile = JAVA_GENERATED_SOURCE_DIR "/" myPkgEvtD "/" int_name_ei "AIEvent.java"; - - int_params_ei = int_names[int_name_ei]; - - int_paramsList_size_ei = split(int_params_ei, int_paramsList_ei, ","); - int_size_ei = evts_intNames[ind_evt_ec ",*"]; - - _addIntLst = ""; - for (i=0; i < int_size_ei; i++) { - _addIntLst = _addIntLst ", " evts_intNames[ind_evt_ec "," i] "AIEvent"; - } - - # print comments header - printCommentsHeader(outFile); - print("") >> outFile; - - print("package " myPkgEvtA ";") >> outFile; - print("") >> outFile; - print("") >> outFile; - - # print imports - print("import " myMainPkgA ".AIEvent;") >> outFile; - print("import " myMainPkgA ".AIFloat3;") >> outFile; - print("import " myPkgClbA ".*;") >> outFile; - print("") >> outFile; - - # print class header - print("public interface " int_name_ei "AIEvent extends AIEvent {") >> outFile; - print("") >> outFile; - - # print getters - for (_p=1; _p <= int_paramsList_size_ei; _p++) { - _name = int_paramsList_ei[_p]; - _type = int_name_param_type[int_name_ei "," _name]; - - print("\t" "public " _type " get" capitalize(_name) "();") >> outFile; - } - print("") >> outFile; - - print("}") >> outFile; -} - - - -# This function has to return true (1) if a doc comment (eg: /** foo bar */) -# can be deleted. -# If there is no special condition you want to apply, -# it should always return true (1), -# cause there are additional mechanism to prevent accidental deleting. -# see: commonDoc.awk -function canDeleteDocumentation() { - return 1; -} - -################################################################################ -### BEGIN: parsing and saving the event methods - -# beginning of struct S*Event -/^\tpublic .+\);/ { - - _head = $1; - _params = $2; - _tail = $3; - - _retType = _head; - sub(/^\tpublic /, "", _retType); # remove pre - sub(/ .*$/, "", _retType); # remove post - - _name = _head; - sub(/^\tpublic [^ ]+ /, "", _name); # remove pre - - _meta = $0; - _hasMeta = sub(/.*\);[ \t]*\/\/[ \t]*/, "", _meta); # remove pre - if (!_hasMeta) { - _meta = ""; - } - - evts_retType[ind_evt] = _retType; - evts_name[ind_evt] = _name; - evts_params[ind_evt] = _params; - evts_meta[ind_evt] = _meta; - storeDocLines(evts_docComment, ind_evt); -#print(_retType " " _name "(" _params ") // " _meta); - ind_evt++; -} - -### END: parsing and saving the event methods -################################################################################ - - - - -END { - # finalize things - - evts_size = ind_evt; - - printEventsOO(); - - printOOAIEnd(myOOAIFile); - printOOAIEnd(myOOAIInterfaceFile); - printOOAIEnd(myOOAIAbstractFile); - printOOEventAIEnd(myOOEventAIFile); - printOOEventAIEnd(myOOEventAIInterfaceFile); - - close(myOOAIFile); - close(myOOAIInterfaceFile); - close(myOOAIAbstractFile); - close(myOOEventAIFile); - close(myOOEventAIInterfaceFile); -} diff --git a/AI/Wrappers/JavaOO/jlib/vecmath-src.jar b/AI/Wrappers/JavaOO/jlib/vecmath-src.jar deleted file mode 100644 index 4f66594635f..00000000000 Binary files a/AI/Wrappers/JavaOO/jlib/vecmath-src.jar and /dev/null differ diff --git a/AI/Wrappers/JavaOO/jlib/vecmath.jar b/AI/Wrappers/JavaOO/jlib/vecmath.jar deleted file mode 100755 index 75b8ac577b0..00000000000 Binary files a/AI/Wrappers/JavaOO/jlib/vecmath.jar and /dev/null differ diff --git a/AI/Wrappers/JavaOO/pom.xml b/AI/Wrappers/JavaOO/pom.xml deleted file mode 100644 index cd552ebf475..00000000000 --- a/AI/Wrappers/JavaOO/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - 4.0.0 - - - - - - 0.1 - - - - com.springrts - common-spring - 1.0 - ../../../rts/build/maven/support/common/spring/pom.xml - - - com.springrts - ai-wrapper-javaoo - ${my.version} - - jar - - Java OO AI Wrapper - Java Object Oriented Artificial Intelligence interface wrapper for the Spring RTS engine - https://springrts.com/wiki/AIWrapper:JavaOO - 2008 - - - - - scm:git:git://github.com/spring/spring.git - scm:git:git@github.com:spring/spring.git - http://github.com/spring/spring/tree/master/AI/Wrappers/JavaOO/ - - - - - - - com.springrts - ai-interface-java - ${my.version} - - - - java3d - vecmath - 1.3.1 - - - - - diff --git a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIEvent.java b/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIEvent.java deleted file mode 100644 index 796112ef8a1..00000000000 --- a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (c) 2008 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package com.springrts.ai.oo; - -/** - * An AI event is sent form the engine to Java Skirmish AIs. - * - * @author hoijui - * @version 0.1 - */ -public interface AIEvent { - -} diff --git a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIException.java b/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIException.java deleted file mode 100644 index 2c3a9ddb927..00000000000 --- a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright (c) 2009 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package com.springrts.ai.oo; - -/** - * Common base interface for AI related Exceptions. - * - * @author hoijui - * @version 0.1 - */ -public interface AIException { - - /** - * Returns the error associated with this Exception. - * This is used to send over low-level language interfaces, - * for example C, where exceptions are not supported. - * @return should be != 0, as this value is reserved for the no-error state - */ - public int getErrorNumber(); -} diff --git a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIFloat3.java b/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIFloat3.java deleted file mode 100644 index 7865eac461c..00000000000 --- a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/AIFloat3.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright (c) 2008 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package com.springrts.ai.oo; - - -import javax.vecmath.Tuple3d; -import javax.vecmath.Tuple3f; -import javax.vecmath.Vector3d; -import javax.vecmath.Vector3f; -import java.awt.Color; - -/** - * Represents a position on the map. - * - * @author hoijui.quaero@gmail.com - * @version 0.1 - */ -public class AIFloat3 extends Vector3f { - - public AIFloat3() { - super(0.0f, 0.0f, 0.0f); - } - public AIFloat3(float x, float y, float z) { - super(x, y, z); - } - public AIFloat3(float[] xyz) { - super(xyz); - } - public AIFloat3(AIFloat3 other) { - super(other); - } - public AIFloat3(Tuple3d tub3d) { - super(tub3d); - } - public AIFloat3(Tuple3f tub3f) { - super(tub3f); - } - public AIFloat3(Vector3d vec3d) { - super(vec3d); - } - public AIFloat3(Vector3f vec3f) { - super(vec3f); - } - public AIFloat3(Color color) { - - this.x = color.getRed() / 255.0F; - this.y = color.getGreen() / 255.0F; - this.z = color.getBlue() / 255.0F; - } - - public Color toColor() { - return new Color(x, y, z); - } - @Override - public String toString() { - return "(" + this.x + ", " + this.y + ", " + this.z + ")"; - } - public float[] toFloatArray() { - - float[] floatArr = new float[3]; - loadInto(floatArr); - return floatArr; - } - public void loadInto(float[] xyz) { - - xyz[0] = x; - xyz[1] = y; - xyz[2] = z; - } - - @Override - public int hashCode() { - - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Float.floatToIntBits(x); - result = prime * result + Float.floatToIntBits(y); - result = prime * result + Float.floatToIntBits(z); - return result; - } - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } else if (!super.equals(obj)) { - return false; - } else if (getClass() != obj.getClass()) { - return false; - } - - AIFloat3 other = (AIFloat3) obj; - if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) { - return false; - } else if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) { - return false; - } else if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z)) { - return false; - } else { - return true; - } - } -} diff --git a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/CallbackAIException.java b/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/CallbackAIException.java deleted file mode 100644 index 309663ef976..00000000000 --- a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/CallbackAIException.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright (c) 2009 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package com.springrts.ai.oo; - -/** - * An exception of this type may be thrown while from an AI callback method. - * - * @author hoijui - */ -public class CallbackAIException extends RuntimeException implements AIException { - - private String methodName; - private int errorNumber; - - public CallbackAIException(String methodName, int errorNumber) { - super("Error calling method \"" + methodName + "\": " + errorNumber); - - this.methodName = methodName; - this.errorNumber = errorNumber; - } - public CallbackAIException(String methodName, int errorNumber, Throwable cause) { - super("Error calling method \"" + methodName + "\": " + errorNumber, cause); - - this.methodName = methodName; - this.errorNumber = errorNumber; - } - - /** - * Returns the name of the method in which the exception occurred. - */ - public String getMethodName() { - return methodName; - } - - /** - * Returns the error number that will be sent to the engine, - * and consequently appear in the engines main log file. - * @return should be != 0, as this value is reserved for the no-error state - */ - @Override - public int getErrorNumber() { - return errorNumber; - } -} diff --git a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/EventAIException.java b/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/EventAIException.java deleted file mode 100644 index 8486a33f23f..00000000000 --- a/AI/Wrappers/JavaOO/src/main/java/com/springrts/ai/oo/EventAIException.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright (c) 2009 Robin Vobruba - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -package com.springrts.ai.oo; - -/** - * An exception of this type may be thrown while handling an AI event. - * - * @author hoijui - * @version 0.1 - */ -public class EventAIException extends Exception implements AIException { - - public static final int DEFAULT_ERROR_NUMBER = 10; - - private int errorNumber; - - public EventAIException() { - super(); - - this.errorNumber = DEFAULT_ERROR_NUMBER; - } - public EventAIException(int errorNumber) { - super(); - - this.errorNumber = errorNumber; - } - - public EventAIException(String message) { - super(message); - - this.errorNumber = DEFAULT_ERROR_NUMBER; - } - public EventAIException(String message, int errorNumber) { - super(message); - - this.errorNumber = errorNumber; - } - - public EventAIException(String message, Throwable cause) { - super(message, cause); - - this.errorNumber = DEFAULT_ERROR_NUMBER; - } - public EventAIException(String message, Throwable cause, int errorNumber) { - super(message, cause); - - this.errorNumber = errorNumber; - } - - public EventAIException(Throwable cause) { - super(cause); - - this.errorNumber = DEFAULT_ERROR_NUMBER; - } - public EventAIException(Throwable cause, int errorNumber) { - super(cause); - - this.errorNumber = errorNumber; - } - - /** - * Returns the error number that will be sent to the engine, - * and consequently appear in the engines main log file. - * @return should be != 0, as this value is reserved for the no-error state - */ - @Override - public int getErrorNumber() { - return errorNumber; - } -} diff --git a/CMakeLists.txt b/CMakeLists.txt index d016d27287c..243ef8cb697 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -73,11 +73,6 @@ else() set(DEBUG_BUILD FALSE) endif() -if(DEBUG_BUILD) - set(JAVA_COMPILE_FLAG_CONDITIONAL "-g:lines,source,vars") -else() - set(JAVA_COMPILE_FLAG_CONDITIONAL "-g:lines,source") -endif() # By default, the libraries that don't explicitly specify SHARED/STATIC are build statically. # See https://cmake.org/cmake/help/latest/variable/BUILD_SHARED_LIBS.html @@ -211,7 +206,7 @@ endif (UNIX AND NOT MINGW) # (next two are relative to CMAKE_INSTALL_PREFIX) set(AI_LIBS_DIR "${DATADIR}" CACHE STRING "Where to install Skirmish AI libraries") set(AI_DATA_DIR "${AI_LIBS_DIR}" CACHE STRING "Where to install Skirmish AI additional files (eg. configuration)") -set(AI_TYPES "NATIVE" CACHE STRING "Which AI Interfaces (and Skirmish AIs using them) to build [ALL|NATIVE|JAVA|NONE]") +set(AI_TYPES "NATIVE" CACHE STRING "Which AI Interfaces (and Skirmish AIs using them) to build [ALL|NATIVE|NONE]") ## DataDirs set(BUILTIN_DATADIRS "") diff --git a/rts/build/cmake/UtilJava.cmake b/rts/build/cmake/UtilJava.cmake deleted file mode 100644 index 71874cc4966..00000000000 --- a/rts/build/cmake/UtilJava.cmake +++ /dev/null @@ -1,101 +0,0 @@ -# This file is part of the Spring engine (GPL v2 or later), see LICENSE.html - -# -# Spring Java related CMake utilities -# ----------------------------------- -# -# Variables set in this file: -# * JAVA_GLOBAL_LIBS_DIRS -# -# Functions and macros defined in this file: -# * find_java_lib -# * get_first_sub_dir_name -# * create_classpath -# * concat_classpaths -# * find_manifest_file -# - - -if (CMAKE_HOST_WIN32) - set(JAVA_GLOBAL_LIBS_DIRS "${MINGWLIBS}") -else (CMAKE_HOST_WIN32) - set(JAVA_GLOBAL_LIBS_DIRS "/usr/share/java" "/usr/local/share/java") -endif (CMAKE_HOST_WIN32) -make_global(JAVA_GLOBAL_LIBS_DIRS) - - -# Looks for a Java library (Jar file) in system wide search paths and in -# additional dirs supplied as argument. -macro (find_java_lib path_var libName additionalSearchDirs) - find_file(${path_var} "${libName}.jar" - PATHS ${additionalSearchDirs} ${JAVA_GLOBAL_LIBS_DIRS} - DOC "Path to the Java library ${libName}.jar" - NO_DEFAULT_PATH - NO_CMAKE_FIND_ROOT_PATH - ) - if (NOT ${path_var}) - message(SEND_ERROR "${libName}.jar not found!") - else (NOT ${path_var}) - ai_message(STATUS "Found ${libName}.jar: ${${path_var}}") - endif (NOT ${path_var}) -endmacro (find_java_lib path_var libName additionalSearchDirs) - - -# Returns the name of the first sub-dir (in alphabetical descending order) -# under dir. -macro (get_first_sub_dir_name name_var dir) - file(GLOB dirContent RELATIVE "${dir}" "${dir}/*") - foreach (dirPart ${dirContent}) - if (IS_DIRECTORY "${dir}/${dirPart}") - set(${name_var} ${dirPart}) - break() - endif (IS_DIRECTORY "${dir}/${dirPart}") - endforeach (dirPart) -endmacro (get_first_sub_dir_name name_var dir) - - -# Recursively lists all JAR files in a given directory -# and concatenates them in a Java Classpath compatible way into a single string. -macro (create_classpath classPath_var dir) - file(GLOB_RECURSE ${classPath_var} FOLLOW_SYMLINKS "${dir}/*.jar") - # Make sure we use the correct path delimiter for the compiling system - string(REPLACE ";" "${PATH_DELIM_H}" ${classPath_var} "${${classPath_var}}") -endmacro (create_classpath classPath_var dir) - - -# Concatenates an arbitrary number of Java ClassPaths (may be empty). -function (concat_classpaths resultingCP_var) - set(${resultingCP_var} "") - foreach (cpPart ${ARGN}) - set(${resultingCP_var} "${${resultingCP_var}}${cpPart}${PATH_DELIM_H}") - endforeach (cpPart) - string(REGEX REPLACE "${PATH_DELIM_H}\$" "" ${resultingCP_var} "${${resultingCP_var}}") - set(${resultingCP_var} "${${resultingCP_var}}" PARENT_SCOPE) -endfunction (concat_classpaths) - -# Look for a manifest.mf file in a few specific sub-dirs. -# This could be done with a simple find_file call, -# but that strangely does not find the file under win32, -# so we use this workaround -function (find_manifest_file srcDir result_var) - set(manifestSubdirs - "/src/main/resources/META-INF/" - "/src/" - "/") - set(${result_var} "${result_var}-NOTFOUND") - if (CMAKE_HOST_WIN32) - foreach(subDir_var ${manifestSubdirs}) - if (EXISTS "${srcDir}${subDir_var}manifest.mf") - set(${result_var} "${srcDir}${subDir_var}manifest.mf") - break() - endif (EXISTS "${srcDir}${subDir_var}manifest.mf") - endforeach(subDir_var) - else (CMAKE_HOST_WIN32) - find_file(${result_var} - NAMES "manifest.mf" "MANIFEST.MF" - PATHS "${srcDir}" - PATH_SUFFIXES ${manifestSubdirs} - NO_DEFAULT_PATH) - endif (CMAKE_HOST_WIN32) - set(${result_var} ${${result_var}} PARENT_SCOPE) -endfunction (find_manifest_file)