Import source

initial
Nicolas Hake 2009-05-08 15:28:41 +02:00
commit 0f050f0343
570 changed files with 252179 additions and 0 deletions

1201
Makefile.am 100644

File diff suppressed because it is too large Load Diff

3936
Makefile.in 100644

File diff suppressed because it is too large Load Diff

31
README.linux.txt 100644
View File

@ -0,0 +1,31 @@
Requirements
============
To build on Linux you need the following packages (Debian names given):
build-essential gcc-4.1 g++-4.1
automake autoconf
libx11-dev libxxf86vm-dev libxpm-dev libgl1-mesa-dev libpng12-dev libssl-dev
libsdl1.2-dev libsdl-mixer1.2-dev libssl-dev libgtk2.0-dev libjpeg62-dev
Build
=====
Open a shell, cd into the source directory, and run:
./configure 'CXX=g++-4.1' && make
If you want a debug build, pass --enable-debug to configure, for the developer mode
--with-gtk. Other options are listed by ./configure --help.
On subsequent build runs, you only have to execute make.
If you want to edit the build files, pass --enable-maintainer-mode to configure.
When you do that, make will automatically update the build system.
The following additional arguments to configure are currently used for release builds:
'--with-gtk' '--with-internal-libpng' '--without-internal-libjpeg' \
'CFLAGS=-Os -g -finline-functions -ffast-math -DBIG_C4INCLUDE' \
'CXXFLAGS=-Os -g -finline-functions -ffast-math -DBIG_C4INCLUDE' \
'OPENSSL_LIBS=/usr/lib/libcrypto.a -ldl'

19
README.mac.txt 100644
View File

@ -0,0 +1,19 @@
Requirements
============
OSX 10.4 or higher
an Intel mac
xcode
Build
=====
Launch xcode and load the project. Select the desired configuration and build.
It should be pretty straight forward, hopefully.
NoNetwork
=========
If you are using the public source package, will be able to build
the "NoNetwork" configurations only.

75
README.windows.txt 100644
View File

@ -0,0 +1,75 @@
Requirements
============
You can build on Windows using either:
* vc6 (Microsoft Visual C++ 6.0)
plus PlatformSDK 2003
plus DXSDK 8.1
* vc7 (Microsoft Visual C++ 2003)
you might have to set the correct DXSDK include and library directories
professional edition required to compile resources
* vc9 (Microsoft Visual C++ 2008)
you might have to set the correct DXSDK include and library directories
professional edition required to compile resources
* MinGW
plus MSYS (or any other shell that can run configure and make)
plus DXSDK 9 (if you want DirectX support)
this is currently only tested by crosscompiling from Linux.
only g++-4.1 and older can compile clonk, g++-4.2 and newer are incompatible.
NoNetwork
=========
If you are using the public source package, will be able to build
the "NoNetwork" configurations only.
Notes for MinGW
===============
To build using MinGW, you need from http://www.mingw.org/:
* MinGW-5.1.3.exe (or newer)
* MSYS-1.0.10.exe
With MinGW-*.exe, install from the "current" distribution the MinGW base tools
and g++, the C++ compiler. Then install msys.
If you want to edit the build files (for example for a new source file), you
need the MSYS DTK, Autoconf 2.6x and Automake 1.10.x. You might need to build
the last two from source.
If you want DirectX support, get a DirectX 9 SDK from Microsoft. Copy the
contents of it's include dir to the include dir of your MinGW installation,
and pass --with-directx to configure below.
Open a shell (the MSYS one under windows), cd to this directory, and execute:
./configure && make
If you want a debugbuild, pass --enable-debug to configure. Other options are
listed by configure --help.
If you get an error like "directx/dxfile.h:240: stray '\32' in program", then
delete that char from that file (Whyever someone would want an ASCII 32 in a
header is beyond me). Some editors (SciTE for example) display such unusual
characters instead of representing them with space.
On subsequent build runs, you only have to execute make.
If you want to edit the build files, pass --enable-maintainer-mode to configure.
When you do that, make will automatically update the build system.
If you want to separate the source directory and the output files, you can call
configure from another directory. You can call configure by it's relative path,
but using the full path helps gdb find the source files. Example:
mkdir build
cd build
/path/to/clonksource/configure --with-directx CXXFLAGS='-Os'
make

937
aclocal.m4 vendored 100644
View File

@ -0,0 +1,937 @@
# generated automatically by aclocal 1.10.1 -*- Autoconf -*-
# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
# 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
m4_ifndef([AC_AUTOCONF_VERSION],
[m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
m4_if(AC_AUTOCONF_VERSION, [2.63],,
[m4_warning([this file was generated for autoconf 2.63.
You have another version of autoconf. It may work, but is not guaranteed to.
If you have problems, you may need to regenerate the build system entirely.
To do so, use the procedure documented by the package, typically `autoreconf'.])])
# Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_AUTOMAKE_VERSION(VERSION)
# ----------------------------
# Automake X.Y traces this macro to ensure aclocal.m4 has been
# generated from the m4 files accompanying Automake X.Y.
# (This private macro should not be called outside this file.)
AC_DEFUN([AM_AUTOMAKE_VERSION],
[am__api_version='1.10'
dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
dnl require some minimum version. Point them to the right macro.
m4_if([$1], [1.10.1], [],
[AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
])
# _AM_AUTOCONF_VERSION(VERSION)
# -----------------------------
# aclocal traces this macro to find the Autoconf version.
# This is a private macro too. Using m4_define simplifies
# the logic in aclocal, which can simply ignore this definition.
m4_define([_AM_AUTOCONF_VERSION], [])
# AM_SET_CURRENT_AUTOMAKE_VERSION
# -------------------------------
# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
# This function is AC_REQUIREd by AC_INIT_AUTOMAKE.
AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
[AM_AUTOMAKE_VERSION([1.10.1])dnl
m4_ifndef([AC_AUTOCONF_VERSION],
[m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
_AM_AUTOCONF_VERSION(AC_AUTOCONF_VERSION)])
# AM_AUX_DIR_EXPAND -*- Autoconf -*-
# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to
# `$srcdir', `$srcdir/..', or `$srcdir/../..'.
#
# Of course, Automake must honor this variable whenever it calls a
# tool from the auxiliary directory. The problem is that $srcdir (and
# therefore $ac_aux_dir as well) can be either absolute or relative,
# depending on how configure is run. This is pretty annoying, since
# it makes $ac_aux_dir quite unusable in subdirectories: in the top
# source directory, any form will work fine, but in subdirectories a
# relative path needs to be adjusted first.
#
# $ac_aux_dir/missing
# fails when called from a subdirectory if $ac_aux_dir is relative
# $top_srcdir/$ac_aux_dir/missing
# fails if $ac_aux_dir is absolute,
# fails when called from a subdirectory in a VPATH build with
# a relative $ac_aux_dir
#
# The reason of the latter failure is that $top_srcdir and $ac_aux_dir
# are both prefixed by $srcdir. In an in-source build this is usually
# harmless because $srcdir is `.', but things will broke when you
# start a VPATH build or use an absolute $srcdir.
#
# So we could use something similar to $top_srcdir/$ac_aux_dir/missing,
# iff we strip the leading $srcdir from $ac_aux_dir. That would be:
# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"`
# and then we would define $MISSING as
# MISSING="\${SHELL} $am_aux_dir/missing"
# This will work as long as MISSING is not called from configure, because
# unfortunately $(top_srcdir) has no meaning in configure.
# However there are other variables, like CC, which are often used in
# configure, and could therefore not use this "fixed" $ac_aux_dir.
#
# Another solution, used here, is to always expand $ac_aux_dir to an
# absolute PATH. The drawback is that using absolute paths prevent a
# configured tree to be moved without reconfiguration.
AC_DEFUN([AM_AUX_DIR_EXPAND],
[dnl Rely on autoconf to set up CDPATH properly.
AC_PREREQ([2.50])dnl
# expand $ac_aux_dir to an absolute path
am_aux_dir=`cd $ac_aux_dir && pwd`
])
# AM_CONDITIONAL -*- Autoconf -*-
# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 8
# AM_CONDITIONAL(NAME, SHELL-CONDITION)
# -------------------------------------
# Define a conditional.
AC_DEFUN([AM_CONDITIONAL],
[AC_PREREQ(2.52)dnl
ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])],
[$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl
AC_SUBST([$1_TRUE])dnl
AC_SUBST([$1_FALSE])dnl
_AM_SUBST_NOTMAKE([$1_TRUE])dnl
_AM_SUBST_NOTMAKE([$1_FALSE])dnl
if $2; then
$1_TRUE=
$1_FALSE='#'
else
$1_TRUE='#'
$1_FALSE=
fi
AC_CONFIG_COMMANDS_PRE(
[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then
AC_MSG_ERROR([[conditional "$1" was never defined.
Usually this means the macro was only invoked conditionally.]])
fi])])
# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 9
# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be
# written in clear, in which case automake, when reading aclocal.m4,
# will think it sees a *use*, and therefore will trigger all it's
# C support machinery. Also note that it means that autoscan, seeing
# CC etc. in the Makefile, will ask for an AC_PROG_CC use...
# _AM_DEPENDENCIES(NAME)
# ----------------------
# See how the compiler implements dependency checking.
# NAME is "CC", "CXX", "GCJ", or "OBJC".
# We try a few techniques and use that to set a single cache variable.
#
# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was
# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular
# dependency, and given that the user is not expected to run this macro,
# just rely on AC_PROG_CC.
AC_DEFUN([_AM_DEPENDENCIES],
[AC_REQUIRE([AM_SET_DEPDIR])dnl
AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl
AC_REQUIRE([AM_MAKE_INCLUDE])dnl
AC_REQUIRE([AM_DEP_TRACK])dnl
ifelse([$1], CC, [depcc="$CC" am_compiler_list=],
[$1], CXX, [depcc="$CXX" am_compiler_list=],
[$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'],
[$1], UPC, [depcc="$UPC" am_compiler_list=],
[$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'],
[depcc="$$1" am_compiler_list=])
AC_CACHE_CHECK([dependency style of $depcc],
[am_cv_$1_dependencies_compiler_type],
[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
# We make a subdir and do the tests there. Otherwise we can end up
# making bogus files that we don't know about and never remove. For
# instance it was reported that on HP-UX the gcc test will end up
# making a dummy file named `D' -- because `-MD' means `put the output
# in D'.
mkdir conftest.dir
# Copy depcomp to subdir because otherwise we won't find it if we're
# using a relative directory.
cp "$am_depcomp" conftest.dir
cd conftest.dir
# We will build objects and dependencies in a subdirectory because
# it helps to detect inapplicable dependency modes. For instance
# both Tru64's cc and ICC support -MD to output dependencies as a
# side effect of compilation, but ICC will put the dependencies in
# the current directory while Tru64 will put them in the object
# directory.
mkdir sub
am_cv_$1_dependencies_compiler_type=none
if test "$am_compiler_list" = ""; then
am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp`
fi
for depmode in $am_compiler_list; do
# Setup a source with many dependencies, because some compilers
# like to wrap large dependency lists on column 80 (with \), and
# we should not choose a depcomp mode which is confused by this.
#
# We need to recreate these files for each test, as the compiler may
# overwrite some of them when testing with obscure command lines.
# This happens at least with the AIX C compiler.
: > sub/conftest.c
for i in 1 2 3 4 5 6; do
echo '#include "conftst'$i'.h"' >> sub/conftest.c
# Using `: > sub/conftst$i.h' creates only sub/conftst1.h with
# Solaris 8's {/usr,}/bin/sh.
touch sub/conftst$i.h
done
echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
case $depmode in
nosideeffect)
# after this tag, mechanisms are not by side-effect, so they'll
# only be used when explicitly requested
if test "x$enable_dependency_tracking" = xyes; then
continue
else
break
fi
;;
none) break ;;
esac
# We check with `-c' and `-o' for the sake of the "dashmstdout"
# mode. It turns out that the SunPro C++ compiler does not properly
# handle `-M -o', and we need to detect this.
if depmode=$depmode \
source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \
depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
$SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
>/dev/null 2>conftest.err &&
grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
${MAKE-make} -s -f confmf > /dev/null 2>&1; then
# icc doesn't choke on unknown options, it will just issue warnings
# or remarks (even with -Werror). So we grep stderr for any message
# that says an option was ignored or not supported.
# When given -MP, icc 7.0 and 7.1 complain thusly:
# icc: Command line warning: ignoring option '-M'; no argument required
# The diagnosis changed in icc 8.0:
# icc: Command line remark: option '-MP' not supported
if (grep 'ignoring option' conftest.err ||
grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
am_cv_$1_dependencies_compiler_type=$depmode
break
fi
fi
done
cd ..
rm -rf conftest.dir
else
am_cv_$1_dependencies_compiler_type=none
fi
])
AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type])
AM_CONDITIONAL([am__fastdep$1], [
test "x$enable_dependency_tracking" != xno \
&& test "$am_cv_$1_dependencies_compiler_type" = gcc3])
])
# AM_SET_DEPDIR
# -------------
# Choose a directory name for dependency files.
# This macro is AC_REQUIREd in _AM_DEPENDENCIES
AC_DEFUN([AM_SET_DEPDIR],
[AC_REQUIRE([AM_SET_LEADING_DOT])dnl
AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl
])
# AM_DEP_TRACK
# ------------
AC_DEFUN([AM_DEP_TRACK],
[AC_ARG_ENABLE(dependency-tracking,
[ --disable-dependency-tracking speeds up one-time build
--enable-dependency-tracking do not reject slow dependency extractors])
if test "x$enable_dependency_tracking" != xno; then
am_depcomp="$ac_aux_dir/depcomp"
AMDEPBACKSLASH='\'
fi
AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno])
AC_SUBST([AMDEPBACKSLASH])dnl
_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl
])
# Generate code to set up dependency tracking. -*- Autoconf -*-
# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
#serial 3
# _AM_OUTPUT_DEPENDENCY_COMMANDS
# ------------------------------
AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS],
[for mf in $CONFIG_FILES; do
# Strip MF so we end up with the name of the file.
mf=`echo "$mf" | sed -e 's/:.*$//'`
# Check whether this is an Automake generated Makefile or not.
# We used to match only the files named `Makefile.in', but
# some people rename them; so instead we look at the file content.
# Grep'ing the first line is not enough: some people post-process
# each Makefile.in and add a new line on top of each file to say so.
# Grep'ing the whole file is not good either: AIX grep has a line
# limit of 2048, but all sed's we know have understand at least 4000.
if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then
dirpart=`AS_DIRNAME("$mf")`
else
continue
fi
# Extract the definition of DEPDIR, am__include, and am__quote
# from the Makefile without running `make'.
DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
test -z "$DEPDIR" && continue
am__include=`sed -n 's/^am__include = //p' < "$mf"`
test -z "am__include" && continue
am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
# When using ansi2knr, U may be empty or an underscore; expand it
U=`sed -n 's/^U = //p' < "$mf"`
# Find all dependency output files, they are included files with
# $(DEPDIR) in their names. We invoke sed twice because it is the
# simplest approach to changing $(DEPDIR) to its actual value in the
# expansion.
for file in `sed -n "
s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
# Make sure the directory exists.
test -f "$dirpart/$file" && continue
fdir=`AS_DIRNAME(["$file"])`
AS_MKDIR_P([$dirpart/$fdir])
# echo "creating $dirpart/$file"
echo '# dummy' > "$dirpart/$file"
done
done
])# _AM_OUTPUT_DEPENDENCY_COMMANDS
# AM_OUTPUT_DEPENDENCY_COMMANDS
# -----------------------------
# This macro should only be invoked once -- use via AC_REQUIRE.
#
# This code is only required when automatic dependency tracking
# is enabled. FIXME. This creates each `.P' file that we will
# need in order to bootstrap the dependency handling code.
AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
[AC_CONFIG_COMMANDS([depfiles],
[test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS],
[AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"])
])
# Do all the work for Automake. -*- Autoconf -*-
# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
# 2005, 2006, 2008 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 13
# This macro actually does too much. Some checks are only needed if
# your package does certain things. But this isn't really a big deal.
# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
# AM_INIT_AUTOMAKE([OPTIONS])
# -----------------------------------------------
# The call with PACKAGE and VERSION arguments is the old style
# call (pre autoconf-2.50), which is being phased out. PACKAGE
# and VERSION should now be passed to AC_INIT and removed from
# the call to AM_INIT_AUTOMAKE.
# We support both call styles for the transition. After
# the next Automake release, Autoconf can make the AC_INIT
# arguments mandatory, and then we can depend on a new Autoconf
# release and drop the old call support.
AC_DEFUN([AM_INIT_AUTOMAKE],
[AC_PREREQ([2.60])dnl
dnl Autoconf wants to disallow AM_ names. We explicitly allow
dnl the ones we care about.
m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl
AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl
AC_REQUIRE([AC_PROG_INSTALL])dnl
if test "`cd $srcdir && pwd`" != "`pwd`"; then
# Use -I$(srcdir) only when $(srcdir) != ., so that make's output
# is not polluted with repeated "-I."
AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl
# test to see if srcdir already configured
if test -f $srcdir/config.status; then
AC_MSG_ERROR([source directory already configured; run "make distclean" there first])
fi
fi
# test whether we have cygpath
if test -z "$CYGPATH_W"; then
if (cygpath --version) >/dev/null 2>/dev/null; then
CYGPATH_W='cygpath -w'
else
CYGPATH_W=echo
fi
fi
AC_SUBST([CYGPATH_W])
# Define the identity of the package.
dnl Distinguish between old-style and new-style calls.
m4_ifval([$2],
[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl
AC_SUBST([PACKAGE], [$1])dnl
AC_SUBST([VERSION], [$2])],
[_AM_SET_OPTIONS([$1])dnl
dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT.
m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,,
[m4_fatal([AC_INIT should be called with package and version arguments])])dnl
AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl
AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl
_AM_IF_OPTION([no-define],,
[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package])
AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl
# Some tools Automake needs.
AC_REQUIRE([AM_SANITY_CHECK])dnl
AC_REQUIRE([AC_ARG_PROGRAM])dnl
AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version})
AM_MISSING_PROG(AUTOCONF, autoconf)
AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version})
AM_MISSING_PROG(AUTOHEADER, autoheader)
AM_MISSING_PROG(MAKEINFO, makeinfo)
AM_PROG_INSTALL_SH
AM_PROG_INSTALL_STRIP
AC_REQUIRE([AM_PROG_MKDIR_P])dnl
# We need awk for the "check" target. The system "awk" is bad on
# some platforms.
AC_REQUIRE([AC_PROG_AWK])dnl
AC_REQUIRE([AC_PROG_MAKE_SET])dnl
AC_REQUIRE([AM_SET_LEADING_DOT])dnl
_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
[_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
[_AM_PROG_TAR([v7])])])
_AM_IF_OPTION([no-dependencies],,
[AC_PROVIDE_IFELSE([AC_PROG_CC],
[_AM_DEPENDENCIES(CC)],
[define([AC_PROG_CC],
defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl
AC_PROVIDE_IFELSE([AC_PROG_CXX],
[_AM_DEPENDENCIES(CXX)],
[define([AC_PROG_CXX],
defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl
AC_PROVIDE_IFELSE([AC_PROG_OBJC],
[_AM_DEPENDENCIES(OBJC)],
[define([AC_PROG_OBJC],
defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl
])
])
# When config.status generates a header, we must update the stamp-h file.
# This file resides in the same directory as the config header
# that is generated. The stamp files are numbered to have different names.
# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the
# loop where config.status creates the headers, so we can generate
# our stamp files there.
AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK],
[# Compute $1's index in $config_headers.
_am_arg=$1
_am_stamp_count=1
for _am_header in $config_headers :; do
case $_am_header in
$_am_arg | $_am_arg:* )
break ;;
* )
_am_stamp_count=`expr $_am_stamp_count + 1` ;;
esac
done
echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count])
# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_PROG_INSTALL_SH
# ------------------
# Define $install_sh.
AC_DEFUN([AM_PROG_INSTALL_SH],
[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"}
AC_SUBST(install_sh)])
# Copyright (C) 2003, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 2
# Check whether the underlying file-system supports filenames
# with a leading dot. For instance MS-DOS doesn't.
AC_DEFUN([AM_SET_LEADING_DOT],
[rm -rf .tst 2>/dev/null
mkdir .tst 2>/dev/null
if test -d .tst; then
am__leading_dot=.
else
am__leading_dot=_
fi
rmdir .tst 2>/dev/null
AC_SUBST([am__leading_dot])])
# Add --enable-maintainer-mode option to configure. -*- Autoconf -*-
# From Jim Meyering
# Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 4
AC_DEFUN([AM_MAINTAINER_MODE],
[AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles])
dnl maintainer-mode is disabled by default
AC_ARG_ENABLE(maintainer-mode,
[ --enable-maintainer-mode enable make rules and dependencies not useful
(and sometimes confusing) to the casual installer],
USE_MAINTAINER_MODE=$enableval,
USE_MAINTAINER_MODE=no)
AC_MSG_RESULT([$USE_MAINTAINER_MODE])
AM_CONDITIONAL(MAINTAINER_MODE, [test $USE_MAINTAINER_MODE = yes])
MAINT=$MAINTAINER_MODE_TRUE
AC_SUBST(MAINT)dnl
]
)
AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE])
# Check to see how 'make' treats includes. -*- Autoconf -*-
# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 3
# AM_MAKE_INCLUDE()
# -----------------
# Check to see how make treats includes.
AC_DEFUN([AM_MAKE_INCLUDE],
[am_make=${MAKE-make}
cat > confinc << 'END'
am__doit:
@echo done
.PHONY: am__doit
END
# If we don't find an include directive, just comment out the code.
AC_MSG_CHECKING([for style of include used by $am_make])
am__include="#"
am__quote=
_am_result=none
# First try GNU make style include.
echo "include confinc" > confmf
# We grep out `Entering directory' and `Leaving directory'
# messages which can occur if `w' ends up in MAKEFLAGS.
# In particular we don't look at `^make:' because GNU make might
# be invoked under some other name (usually "gmake"), in which
# case it prints its new name instead of `make'.
if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then
am__include=include
am__quote=
_am_result=GNU
fi
# Now try BSD make style include.
if test "$am__include" = "#"; then
echo '.include "confinc"' > confmf
if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then
am__include=.include
am__quote="\""
_am_result=BSD
fi
fi
AC_SUBST([am__include])
AC_SUBST([am__quote])
AC_MSG_RESULT([$_am_result])
rm -f confinc confmf
])
# Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 5
# AM_PROG_CC_C_O
# --------------
# Like AC_PROG_CC_C_O, but changed for automake.
AC_DEFUN([AM_PROG_CC_C_O],
[AC_REQUIRE([AC_PROG_CC_C_O])dnl
AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
AC_REQUIRE_AUX_FILE([compile])dnl
# FIXME: we rely on the cache variable name because
# there is no other way.
set dummy $CC
ac_cc=`echo $[2] | sed ['s/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/']`
if eval "test \"`echo '$ac_cv_prog_cc_'${ac_cc}_c_o`\" != yes"; then
# Losing compiler, so override with the script.
# FIXME: It is wrong to rewrite CC.
# But if we don't then we get into trouble of one sort or another.
# A longer-term fix would be to have automake use am__CC in this case,
# and then we could set am__CC="\$(top_srcdir)/compile \$(CC)"
CC="$am_aux_dir/compile $CC"
fi
dnl Make sure AC_PROG_CC is never called again, or it will override our
dnl setting of CC.
m4_define([AC_PROG_CC],
[m4_fatal([AC_PROG_CC cannot be called after AM_PROG_CC_C_O])])
])
# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*-
# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 5
# AM_MISSING_PROG(NAME, PROGRAM)
# ------------------------------
AC_DEFUN([AM_MISSING_PROG],
[AC_REQUIRE([AM_MISSING_HAS_RUN])
$1=${$1-"${am_missing_run}$2"}
AC_SUBST($1)])
# AM_MISSING_HAS_RUN
# ------------------
# Define MISSING if not defined so far and test if it supports --run.
# If it does, set am_missing_run to use it, otherwise, to nothing.
AC_DEFUN([AM_MISSING_HAS_RUN],
[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
AC_REQUIRE_AUX_FILE([missing])dnl
test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing"
# Use eval to expand $SHELL
if eval "$MISSING --run true"; then
am_missing_run="$MISSING --run "
else
am_missing_run=
AC_MSG_WARN([`missing' script is too old or missing])
fi
])
# Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_PROG_MKDIR_P
# ---------------
# Check for `mkdir -p'.
AC_DEFUN([AM_PROG_MKDIR_P],
[AC_PREREQ([2.60])dnl
AC_REQUIRE([AC_PROG_MKDIR_P])dnl
dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P,
dnl while keeping a definition of mkdir_p for backward compatibility.
dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile.
dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of
dnl Makefile.ins that do not define MKDIR_P, so we do our own
dnl adjustment using top_builddir (which is defined more often than
dnl MKDIR_P).
AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl
case $mkdir_p in
[[\\/$]]* | ?:[[\\/]]*) ;;
*/*) mkdir_p="\$(top_builddir)/$mkdir_p" ;;
esac
])
# Helper functions for option handling. -*- Autoconf -*-
# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 3
# _AM_MANGLE_OPTION(NAME)
# -----------------------
AC_DEFUN([_AM_MANGLE_OPTION],
[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])])
# _AM_SET_OPTION(NAME)
# ------------------------------
# Set option NAME. Presently that only means defining a flag for this option.
AC_DEFUN([_AM_SET_OPTION],
[m4_define(_AM_MANGLE_OPTION([$1]), 1)])
# _AM_SET_OPTIONS(OPTIONS)
# ----------------------------------
# OPTIONS is a space-separated list of Automake options.
AC_DEFUN([_AM_SET_OPTIONS],
[AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET])
# -------------------------------------------
# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
AC_DEFUN([_AM_IF_OPTION],
[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
# Check to make sure that the build environment is sane. -*- Autoconf -*-
# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005
# Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 4
# AM_SANITY_CHECK
# ---------------
AC_DEFUN([AM_SANITY_CHECK],
[AC_MSG_CHECKING([whether build environment is sane])
# Just in case
sleep 1
echo timestamp > conftest.file
# Do `set' in a subshell so we don't clobber the current shell's
# arguments. Must try -L first in case configure is actually a
# symlink; some systems play weird games with the mod time of symlinks
# (eg FreeBSD returns the mod time of the symlink's containing
# directory).
if (
set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
if test "$[*]" = "X"; then
# -L didn't work.
set X `ls -t $srcdir/configure conftest.file`
fi
rm -f conftest.file
if test "$[*]" != "X $srcdir/configure conftest.file" \
&& test "$[*]" != "X conftest.file $srcdir/configure"; then
# If neither matched, then we have a broken ls. This can happen
# if, for instance, CONFIG_SHELL is bash and it inherits a
# broken ls alias from the environment. This has actually
# happened. Such a system could not be considered "sane".
AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken
alias in your environment])
fi
test "$[2]" = conftest.file
)
then
# Ok.
:
else
AC_MSG_ERROR([newly created file is older than distributed files!
Check your system clock])
fi
AC_MSG_RESULT(yes)])
# Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_PROG_INSTALL_STRIP
# ---------------------
# One issue with vendor `install' (even GNU) is that you can't
# specify the program used to strip binaries. This is especially
# annoying in cross-compiling environments, where the build's strip
# is unlikely to handle the host's binaries.
# Fortunately install-sh will honor a STRIPPROG variable, so we
# always use install-sh in `make install-strip', and initialize
# STRIPPROG with the value of the STRIP variable (set by the user).
AC_DEFUN([AM_PROG_INSTALL_STRIP],
[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
# Installed binaries are usually stripped using `strip' when the user
# run `make install-strip'. However `strip' might not be the right
# tool to use in cross-compilation environments, therefore Automake
# will honor the `STRIP' environment variable to overrule this program.
dnl Don't test for $cross_compiling = yes, because it might be `maybe'.
if test "$cross_compiling" != no; then
AC_CHECK_TOOL([STRIP], [strip], :)
fi
INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
AC_SUBST([INSTALL_STRIP_PROGRAM])])
# Copyright (C) 2006 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# _AM_SUBST_NOTMAKE(VARIABLE)
# ---------------------------
# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in.
# This macro is traced by Automake.
AC_DEFUN([_AM_SUBST_NOTMAKE])
# Check how to create a tarball. -*- Autoconf -*-
# Copyright (C) 2004, 2005 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# serial 2
# _AM_PROG_TAR(FORMAT)
# --------------------
# Check how to create a tarball in format FORMAT.
# FORMAT should be one of `v7', `ustar', or `pax'.
#
# Substitute a variable $(am__tar) that is a command
# writing to stdout a FORMAT-tarball containing the directory
# $tardir.
# tardir=directory && $(am__tar) > result.tar
#
# Substitute a variable $(am__untar) that extract such
# a tarball read from stdin.
# $(am__untar) < result.tar
AC_DEFUN([_AM_PROG_TAR],
[# Always define AMTAR for backward compatibility.
AM_MISSING_PROG([AMTAR], [tar])
m4_if([$1], [v7],
[am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'],
[m4_case([$1], [ustar],, [pax],,
[m4_fatal([Unknown tar format])])
AC_MSG_CHECKING([how to create a $1 tar archive])
# Loop over all known methods to create a tar archive until one works.
_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none'
_am_tools=${am_cv_prog_tar_$1-$_am_tools}
# Do not fold the above two line into one, because Tru64 sh and
# Solaris sh will not grok spaces in the rhs of `-'.
for _am_tool in $_am_tools
do
case $_am_tool in
gnutar)
for _am_tar in tar gnutar gtar;
do
AM_RUN_LOG([$_am_tar --version]) && break
done
am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"'
am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"'
am__untar="$_am_tar -xf -"
;;
plaintar)
# Must skip GNU tar: if it does not support --format= it doesn't create
# ustar tarball either.
(tar --version) >/dev/null 2>&1 && continue
am__tar='tar chf - "$$tardir"'
am__tar_='tar chf - "$tardir"'
am__untar='tar xf -'
;;
pax)
am__tar='pax -L -x $1 -w "$$tardir"'
am__tar_='pax -L -x $1 -w "$tardir"'
am__untar='pax -r'
;;
cpio)
am__tar='find "$$tardir" -print | cpio -o -H $1 -L'
am__tar_='find "$tardir" -print | cpio -o -H $1 -L'
am__untar='cpio -i -H $1 -d'
;;
none)
am__tar=false
am__tar_=false
am__untar=false
;;
esac
# If the value was cached, stop now. We just wanted to have am__tar
# and am__untar set.
test -n "${am_cv_prog_tar_$1}" && break
# tar/untar a dummy directory, and stop if the command works
rm -rf conftest.dir
mkdir conftest.dir
echo GrepMe > conftest.dir/file
AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar])
rm -rf conftest.dir
if test -s conftest.tar; then
AM_RUN_LOG([$am__untar <conftest.tar])
grep GrepMe conftest.dir/file >/dev/null 2>&1 && break
fi
done
rm -rf conftest.dir
AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool])
AC_MSG_RESULT([$am_cv_prog_tar_$1])])
AC_SUBST([am__tar])
AC_SUBST([am__untar])
]) # _AM_PROG_TAR
m4_include([autotools/acx_iconv.m4])
m4_include([autotools/acx_pthread.m4])
m4_include([autotools/pkg.m4])
m4_include([autotools/reftotemp.m4])
m4_include([autotools/sdl.m4])
m4_include([autotools/vl_lib_readline.m4])

View File

@ -0,0 +1,75 @@
dnl Copyright (C) 2000-2002 Free Software Foundation, Inc.
dnl This file is free software; the Free Software Foundation
dnl gives unlimited permission to copy and/or distribute it,
dnl with or without modifications, as long as this notice is preserved.
dnl From Bruno Haible.
dnl Modified for Clonk to not do all that weird stuff
AC_DEFUN([_AX_ICONV_LINK],
[
dnl Some systems have iconv in libc, some have it in libiconv (OSF/1 and
dnl those with the standalone portable GNU libiconv installed).
dnl Search for libiconv and define LIBICONV and INCICONV
dnl accordingly.
AC_CACHE_CHECK(for iconv, ax_cv_func_iconv, [
ax_cv_func_iconv="no, consider installing GNU libiconv"
ax_cv_lib_iconv=no
LIBICONV=""
AC_TRY_LINK([#include <stdlib.h>
#include <iconv.h>],
[iconv_t cd = iconv_open("","");
iconv(cd,NULL,NULL,NULL,NULL);
iconv_close(cd);],
ax_cv_func_iconv=yes)
if test "$ax_cv_func_iconv" != yes; then
ax_save_LIBS="$LIBS"
LIBS="$LIBS -liconv"
AC_TRY_LINK([#include <stdlib.h>
#include <iconv.h>],
[iconv_t cd = iconv_open("","");
iconv(cd,NULL,NULL,NULL,NULL);
iconv_close(cd);],
ax_cv_lib_iconv=yes
ax_cv_func_iconv=yes
LIBICONV=-liconv)
LIBS="$ax_save_LIBS"
fi
])
if test "$ax_cv_func_iconv" = yes; then
AC_DEFINE(HAVE_ICONV, 1, [Define if you have the iconv() function.])
fi
if test "$ax_cv_lib_iconv" = yes; then
AC_MSG_CHECKING([how to link with libiconv])
AC_MSG_RESULT([-liconv])
fi
AC_SUBST(LIBICONV)
])
AC_DEFUN([AX_ICONV],
[
_AX_ICONV_LINK
if test "$ax_cv_func_iconv" = yes; then
AC_MSG_CHECKING([for iconv declaration])
AC_CACHE_VAL(ax_cv_proto_iconv, [
AC_TRY_COMPILE([
#include <stdlib.h>
#include <iconv.h>
extern
#ifdef __cplusplus
"C"
#endif
#if defined(__STDC__) || defined(__cplusplus)
size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
#else
size_t iconv();
#endif
], [], ax_cv_proto_iconv_arg1="", ax_cv_proto_iconv_arg1="const")])
AC_MSG_RESULT([extern size_t iconv (iconv_t cd, $ax_cv_proto_iconv_arg1 char * * inbuf, size_t * inbytesleft, char * * outbuf, size_t * outbytesleft);])
AC_DEFINE_UNQUOTED(ICONV_CONST, $ax_cv_proto_iconv_arg1,
[Define as const if the declaration of iconv() needs const.])
fi
])

View File

@ -0,0 +1,238 @@
dnl @synopsis ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
dnl
dnl @summary figure out how to build C programs using POSIX threads
dnl
dnl This macro figures out how to build C programs using POSIX threads.
dnl It sets the PTHREAD_LIBS output variable to the threads library and
dnl linker flags, and the PTHREAD_CFLAGS output variable to any special
dnl C compiler flags that are needed. (The user can also force certain
dnl compiler flags/libs to be tested by setting these environment
dnl variables.)
dnl
dnl Also sets PTHREAD_CC to any special C compiler that is needed for
dnl multi-threaded programs (defaults to the value of CC otherwise).
dnl (This is necessary on AIX to use the special cc_r compiler alias.)
dnl
dnl NOTE: You are assumed to not only compile your program with these
dnl flags, but also link it with them as well. e.g. you should link
dnl with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS
dnl $LIBS
dnl
dnl If you are only building threads programs, you may wish to use
dnl these variables in your default LIBS, CFLAGS, and CC:
dnl
dnl LIBS="$PTHREAD_LIBS $LIBS"
dnl CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
dnl CC="$PTHREAD_CC"
dnl
dnl In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute
dnl constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to
dnl that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
dnl
dnl ACTION-IF-FOUND is a list of shell commands to run if a threads
dnl library is found, and ACTION-IF-NOT-FOUND is a list of commands to
dnl run it if it is not found. If ACTION-IF-FOUND is not specified, the
dnl default action will define HAVE_PTHREAD.
dnl
dnl Please let the authors know if this macro fails on any platform, or
dnl if you have any other suggestions or comments. This macro was based
dnl on work by SGJ on autoconf scripts for FFTW (www.fftw.org) (with
dnl help from M. Frigo), as well as ac_pthread and hb_pthread macros
dnl posted by Alejandro Forero Cuervo to the autoconf macro repository.
dnl We are also grateful for the helpful feedback of numerous users.
dnl
dnl @category InstalledPackages
dnl @author Steven G. Johnson <stevenj@alum.mit.edu>
dnl @version 2005-06-15
dnl @license GPLWithACException
AC_DEFUN([ACX_PTHREAD], [
AC_REQUIRE([AC_CANONICAL_HOST])
AC_LANG_SAVE
AC_LANG_C
acx_pthread_ok=no
# We used to check for pthread.h first, but this fails if pthread.h
# requires special compiler flags (e.g. on True64 or Sequent).
# It gets checked for in the link test anyway.
# First of all, check if the user has set any of the PTHREAD_LIBS,
# etcetera environment variables, and if threads linking works using
# them:
if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes)
AC_MSG_RESULT($acx_pthread_ok)
if test x"$acx_pthread_ok" = xno; then
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
fi
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
fi
# We must check for the threads library under a number of different
# names; the ordering is very important because some systems
# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
# libraries is broken (non-POSIX).
# Create a list of thread flags to try. Items starting with a "-" are
# C compiler flags, and other items are library names, except for "none"
# which indicates that we try without any flags at all, and "pthread-config"
# which is a program returning the flags for the Pth emulation library.
acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
# The ordering *is* (sometimes) important. Some notes on the
# individual items follow:
# pthreads: AIX (must check this before -lpthread)
# none: in case threads are in libc; should be tried before -Kthread and
# other compiler flags to prevent continual compiler warnings
# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
# -pthreads: Solaris/gcc
# -mthreads: Mingw32/gcc, Lynx/gcc
# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
# doesn't hurt to check since this sometimes defines pthreads too;
# also defines -D_REENTRANT)
# ... -mt is also the pthreads flag for HP/aCC
# pthread: Linux, etcetera
# --thread-safe: KAI C++
# pthread-config: use pthread-config program (for GNU Pth library)
case "${host_cpu}-${host_os}" in
*solaris*)
# On Solaris (at least, for some versions), libc contains stubbed
# (non-functional) versions of the pthreads routines, so link-based
# tests will erroneously succeed. (We need to link with -pthreads/-mt/
# -lpthread.) (The stubs are missing pthread_cleanup_push, or rather
# a function called by this macro, so we could check for that, but
# who knows whether they'll stub that too in a future libc.) So,
# we'll just look for -pthreads and -lpthread first:
acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags"
;;
esac
if test x"$acx_pthread_ok" = xno; then
for flag in $acx_pthread_flags; do
case $flag in
none)
AC_MSG_CHECKING([whether pthreads work without any flags])
;;
-*)
AC_MSG_CHECKING([whether pthreads work with $flag])
PTHREAD_CFLAGS="$flag"
;;
pthread-config)
AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no)
if test x"$acx_pthread_config" = xno; then continue; fi
PTHREAD_CFLAGS="`pthread-config --cflags`"
PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
;;
*)
AC_MSG_CHECKING([for the pthreads library -l$flag])
PTHREAD_LIBS="-l$flag"
;;
esac
save_LIBS="$LIBS"
save_CFLAGS="$CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Check for various functions. We must include pthread.h,
# since some functions may be macros. (On the Sequent, we
# need a special flag -Kthread to make this header compile.)
# We check for pthread_join because it is in -lpthread on IRIX
# while pthread_create is in libc. We check for pthread_attr_init
# due to DEC craziness with -lpthreads. We check for
# pthread_cleanup_push because it is one of the few pthread
# functions on Solaris that doesn't have a non-functional libc stub.
# We try pthread_create on general principles.
AC_TRY_LINK([#include <pthread.h>],
[pthread_t th; pthread_join(th, 0);
pthread_attr_init(0); pthread_cleanup_push(0, 0);
pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
[acx_pthread_ok=yes])
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
AC_MSG_RESULT($acx_pthread_ok)
if test "x$acx_pthread_ok" = xyes; then
break;
fi
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
done
fi
# Various other checks:
if test "x$acx_pthread_ok" = xyes; then
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
AC_MSG_CHECKING([for joinable pthread attribute])
attr_name=unknown
for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;],
[attr_name=$attr; break])
done
AC_MSG_RESULT($attr_name)
if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
[Define to necessary symbol if this constant
uses a non-standard name on your system.])
fi
AC_MSG_CHECKING([if more special flags are required for pthreads])
flag=no
case "${host_cpu}-${host_os}" in
*-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
*solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
esac
AC_MSG_RESULT(${flag})
if test "x$flag" != xno; then
PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
fi
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
# More AIX lossage: must compile with cc_r
AC_CHECK_PROG(PTHREAD_CC, cc_r, cc_r, ${CC})
else
PTHREAD_CC="$CC"
fi
AC_SUBST(PTHREAD_LIBS)
AC_SUBST(PTHREAD_CFLAGS)
AC_SUBST(PTHREAD_CC)
# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
if test x"$acx_pthread_ok" = xyes; then
ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
:
else
acx_pthread_ok=no
$2
fi
AC_LANG_RESTORE
])dnl ACX_PTHREAD

142
autotools/compile 100644
View File

@ -0,0 +1,142 @@
#! /bin/sh
# Wrapper for compilers which do not understand `-c -o'.
scriptversion=2005-05-14.22
# Copyright (C) 1999, 2000, 2003, 2004, 2005 Free Software Foundation, Inc.
# Written by Tom Tromey <tromey@cygnus.com>.
#
# 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, 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
case $1 in
'')
echo "$0: No command. Try \`$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: compile [--help] [--version] PROGRAM [ARGS]
Wrapper for compilers which do not understand `-c -o'.
Remove `-o dest.o' from ARGS, run PROGRAM with the remaining
arguments, and rename the output as expected.
If you are trying to build a whole package this is not the
right script to run: please start by reading the file `INSTALL'.
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "compile $scriptversion"
exit $?
;;
esac
ofile=
cfile=
eat=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as `compile cc -o foo foo.c'.
# So we strip `-o arg' only if arg is an object.
eat=1
case $2 in
*.o | *.obj)
ofile=$2
;;
*)
set x "$@" -o "$2"
shift
;;
esac
;;
*.c)
cfile=$1
set x "$@" "$1"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -z "$ofile" || test -z "$cfile"; then
# If no `-o' option was seen then we might have been invoked from a
# pattern rule where we don't need one. That is ok -- this is a
# normal compilation that the losing compiler can handle. If no
# `.c' file was seen then we are probably linking. That is also
# ok.
exec "$@"
fi
# Name of file we expect compiler to create.
cofile=`echo "$cfile" | sed -e 's|^.*/||' -e 's/\.c$/.o/'`
# Create the lock directory.
# Note: use `[/.-]' here to ensure that we don't use the same name
# that we are using for the .o file. Also, base the name on the expected
# object file name, since that is what matters with a parallel build.
lockdir=`echo "$cofile" | sed -e 's|[/.-]|_|g'`.d
while true; do
if mkdir "$lockdir" >/dev/null 2>&1; then
break
fi
sleep 1
done
# FIXME: race condition here if user kills between mkdir and trap.
trap "rmdir '$lockdir'; exit 1" 1 2 15
# Run the compile.
"$@"
ret=$?
if test -f "$cofile"; then
mv "$cofile" "$ofile"
elif test -f "${cofile}bj"; then
mv "${cofile}bj" "$ofile"
fi
rmdir "$lockdir"
exit $ret
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:

1526
autotools/config.guess vendored 100644

File diff suppressed because it is too large Load Diff

1658
autotools/config.sub vendored 100644

File diff suppressed because it is too large Load Diff

589
autotools/depcomp 100644
View File

@ -0,0 +1,589 @@
#! /bin/sh
# depcomp - compile a program generating dependencies as side-effects
scriptversion=2007-03-29.01
# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007 Free Software
# Foundation, Inc.
# 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, 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
case $1 in
'')
echo "$0: No command. Try \`$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: depcomp [--help] [--version] PROGRAM [ARGS]
Run PROGRAMS ARGS to compile a file, generating dependencies
as side-effects.
Environment variables:
depmode Dependency tracking mode.
source Source file read by `PROGRAMS ARGS'.
object Object file output by `PROGRAMS ARGS'.
DEPDIR directory where to store dependencies.
depfile Dependency file to output.
tmpdepfile Temporary file to use when outputing dependencies.
libtool Whether libtool is used (yes/no).
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "depcomp $scriptversion"
exit $?
;;
esac
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
echo "depcomp: Variables source, object and depmode must be set" 1>&2
exit 1
fi
# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
depfile=${depfile-`echo "$object" |
sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
rm -f "$tmpdepfile"
# Some modes work just like other modes, but use different flags. We
# parameterize here, but still list the modes in the big case below,
# to make depend.m4 easier to write. Note that we *cannot* use a case
# here, because this file can only contain one case statement.
if test "$depmode" = hp; then
# HP compiler uses -M and no extra arg.
gccflag=-M
depmode=gcc
fi
if test "$depmode" = dashXmstdout; then
# This is just like dashmstdout with a different argument.
dashmflag=-xM
depmode=dashmstdout
fi
case "$depmode" in
gcc3)
## gcc 3 implements dependency tracking that does exactly what
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
## it if -MD -MP comes after the -MF stuff. Hmm.
## Unfortunately, FreeBSD c89 acceptance of flags depends upon
## the command line argument order; so add the flags where they
## appear in depend2.am. Note that the slowdown incurred here
## affects only configure: in makefiles, %FASTDEP% shortcuts this.
for arg
do
case $arg in
-c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
*) set fnord "$@" "$arg" ;;
esac
shift # fnord
shift # $arg
done
"$@"
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
mv "$tmpdepfile" "$depfile"
;;
gcc)
## There are various ways to get dependency output from gcc. Here's
## why we pick this rather obscure method:
## - Don't want to use -MD because we'd like the dependencies to end
## up in a subdir. Having to rename by hand is ugly.
## (We might end up doing this anyway to support other compilers.)
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
## -MM, not -M (despite what the docs say).
## - Using -M directly means running the compiler twice (even worse
## than renaming).
if test -z "$gccflag"; then
gccflag=-MD,
fi
"$@" -Wp,"$gccflag$tmpdepfile"
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
## The second -e expression handles DOS-style file names with drive letters.
sed -e 's/^[^:]*: / /' \
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
## This next piece of magic avoids the `deleted header file' problem.
## The problem is that when a header file which appears in a .P file
## is deleted, the dependency causes make to die (because there is
## typically no way to rebuild the header). We avoid this by adding
## dummy dependencies for each header file. Too bad gcc doesn't do
## this for us directly.
tr ' ' '
' < "$tmpdepfile" |
## Some versions of gcc put a space before the `:'. On the theory
## that the space means something, we add a space to the output as
## well.
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
sgi)
if test "$libtool" = yes; then
"$@" "-Wp,-MDupdate,$tmpdepfile"
else
"$@" -MDupdate "$tmpdepfile"
fi
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
echo "$object : \\" > "$depfile"
# Clip off the initial element (the dependent). Don't try to be
# clever and replace this with sed code, as IRIX sed won't handle
# lines with more than a fixed number of characters (4096 in
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
# the IRIX cc adds comments like `#:fec' to the end of the
# dependency line.
tr ' ' '
' < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
tr '
' ' ' >> $depfile
echo >> $depfile
# The second pass generates a dummy entry for each header file.
tr ' ' '
' < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
>> $depfile
else
# The sourcefile does not contain any dependencies, so just
# store a dummy comment line, to avoid errors with the Makefile
# "include basename.Plo" scheme.
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile"
;;
aix)
# The C for AIX Compiler uses -M and outputs the dependencies
# in a .u file. In older versions, this file always lives in the
# current directory. Also, the AIX compiler puts `$object:' at the
# start of each line; $object doesn't have directory information.
# Version 6 uses the directory in both cases.
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
test "x$dir" = "x$object" && dir=
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.u
tmpdepfile2=$base.u
tmpdepfile3=$dir.libs/$base.u
"$@" -Wc,-M
else
tmpdepfile1=$dir$base.u
tmpdepfile2=$dir$base.u
tmpdepfile3=$dir$base.u
"$@" -M
fi
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
# Each line is of the form `foo.o: dependent.h'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
# That's a tab and a space in the [].
sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
else
# The sourcefile does not contain any dependencies, so just
# store a dummy comment line, to avoid errors with the Makefile
# "include basename.Plo" scheme.
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile"
;;
icc)
# Intel's C compiler understands `-MD -MF file'. However on
# icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
# ICC 7.0 will fill foo.d with something like
# foo.o: sub/foo.c
# foo.o: sub/foo.h
# which is wrong. We want:
# sub/foo.o: sub/foo.c
# sub/foo.o: sub/foo.h
# sub/foo.c:
# sub/foo.h:
# ICC 7.1 will output
# foo.o: sub/foo.c sub/foo.h
# and will wrap long lines using \ :
# foo.o: sub/foo.c ... \
# sub/foo.h ... \
# ...
"$@" -MD -MF "$tmpdepfile"
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each line is of the form `foo.o: dependent.h',
# or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp2)
# The "hp" stanza above does not work with aCC (C++) and HP's ia64
# compilers, which have integrated preprocessors. The correct option
# to use with these is +Maked; it writes dependencies to a file named
# 'foo.d', which lands next to the object file, wherever that
# happens to be.
# Much of this is similar to the tru64 case; see comments there.
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
test "x$dir" = "x$object" && dir=
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir.libs/$base.d
"$@" -Wc,+Maked
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
"$@" +Maked
fi
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile1" "$tmpdepfile2"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile"
# Add `dependent.h:' lines.
sed -ne '2,${; s/^ *//; s/ \\*$//; s/$/:/; p;}' "$tmpdepfile" >> "$depfile"
else
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile" "$tmpdepfile2"
;;
tru64)
# The Tru64 compiler uses -MD to generate dependencies as a side
# effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
# dependencies in `foo.d' instead, so we check for that too.
# Subdirectories are respected.
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
test "x$dir" = "x$object" && dir=
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
if test "$libtool" = yes; then
# With Tru64 cc, shared objects can also be used to make a
# static library. This mechanism is used in libtool 1.4 series to
# handle both shared and static libraries in a single compilation.
# With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d.
#
# With libtool 1.5 this exception was removed, and libtool now
# generates 2 separate objects for the 2 libraries. These two
# compilations output dependencies in $dir.libs/$base.o.d and
# in $dir$base.o.d. We have to check for both files, because
# one of the two compilations can be disabled. We should prefer
# $dir$base.o.d over $dir.libs/$base.o.d because the latter is
# automatically cleaned when .libs/ is deleted, while ignoring
# the former would cause a distcleancheck panic.
tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4
tmpdepfile2=$dir$base.o.d # libtool 1.5
tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5
tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504
"$@" -Wc,-MD
else
tmpdepfile1=$dir$base.o.d
tmpdepfile2=$dir$base.d
tmpdepfile3=$dir$base.d
tmpdepfile4=$dir$base.d
"$@" -MD
fi
stat=$?
if test $stat -eq 0; then :
else
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
# That's a tab and a space in the [].
sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
else
echo "#dummy" > "$depfile"
fi
rm -f "$tmpdepfile"
;;
#nosideeffect)
# This comment above is used by automake to tell side-effect
# dependency tracking mechanisms from slower ones.
dashmstdout)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test $1 != '--mode=compile'; do
shift
done
shift
fi
# Remove `-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
test -z "$dashmflag" && dashmflag=-M
# Require at least two characters before searching for `:'
# in the target name. This is to cope with DOS-style filenames:
# a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
"$@" $dashmflag |
sed 's:^[ ]*[^: ][^:][^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
tr ' ' '
' < "$tmpdepfile" | \
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
dashXmstdout)
# This case only exists to satisfy depend.m4. It is never actually
# run, as this mode is specially recognized in the preamble.
exit 1
;;
makedepend)
"$@" || exit $?
# Remove any Libtool call
if test "$libtool" = yes; then
while test $1 != '--mode=compile'; do
shift
done
shift
fi
# X makedepend
shift
cleared=no
for arg in "$@"; do
case $cleared in
no)
set ""; shift
cleared=yes ;;
esac
case "$arg" in
-D*|-I*)
set fnord "$@" "$arg"; shift ;;
# Strip any option that makedepend may not understand. Remove
# the object too, otherwise makedepend will parse it as a source file.
-*|$object)
;;
*)
set fnord "$@" "$arg"; shift ;;
esac
done
obj_suffix="`echo $object | sed 's/^.*\././'`"
touch "$tmpdepfile"
${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
sed '1,2d' "$tmpdepfile" | tr ' ' '
' | \
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile" "$tmpdepfile".bak
;;
cpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test $1 != '--mode=compile'; do
shift
done
shift
fi
# Remove `-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
"$@" -E |
sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
sed '$ s: \\$::' > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
cat < "$tmpdepfile" >> "$depfile"
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvisualcpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o,
# because we must use -o when running libtool.
"$@" || exit $?
IFS=" "
for arg
do
case "$arg" in
"-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
set fnord "$@"
shift
shift
;;
*)
set fnord "$@" "$arg"
shift
shift
;;
esac
done
"$@" -E |
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
. "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile"
echo " " >> "$depfile"
. "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
rm -f "$tmpdepfile"
;;
none)
exec "$@"
;;
*)
echo "Unknown depmode $depmode" 1>&2
exit 1
;;
esac
exit 0
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:

View File

@ -0,0 +1,519 @@
#!/bin/sh
# install - install a program, script, or datafile
scriptversion=2006-12-25.00
# This originates from X11R5 (mit/util/scripts/install.sh), which was
# later released in X11R6 (xc/config/util/install.sh) with the
# following copyright and license.
#
# Copyright (C) 1994 X Consortium
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of the X Consortium shall not
# be used in advertising or otherwise to promote the sale, use or other deal-
# ings in this Software without prior written authorization from the X Consor-
# tium.
#
#
# FSF changes to this file are in the public domain.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.
nl='
'
IFS=" "" $nl"
# set DOITPROG to echo to test this script
# Don't use :- since 4.3BSD and earlier shells don't like it.
doit=${DOITPROG-}
if test -z "$doit"; then
doit_exec=exec
else
doit_exec=$doit
fi
# Put in absolute file names if you don't have them in your path;
# or use environment vars.
chgrpprog=${CHGRPPROG-chgrp}
chmodprog=${CHMODPROG-chmod}
chownprog=${CHOWNPROG-chown}
cmpprog=${CMPPROG-cmp}
cpprog=${CPPROG-cp}
mkdirprog=${MKDIRPROG-mkdir}
mvprog=${MVPROG-mv}
rmprog=${RMPROG-rm}
stripprog=${STRIPPROG-strip}
posix_glob='?'
initialize_posix_glob='
test "$posix_glob" != "?" || {
if (set -f) 2>/dev/null; then
posix_glob=
else
posix_glob=:
fi
}
'
posix_mkdir=
# Desired mode of installed file.
mode=0755
chgrpcmd=
chmodcmd=$chmodprog
chowncmd=
mvcmd=$mvprog
rmcmd="$rmprog -f"
stripcmd=
src=
dst=
dir_arg=
dst_arg=
copy_on_change=false
no_target_directory=
usage="\
Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
or: $0 [OPTION]... SRCFILES... DIRECTORY
or: $0 [OPTION]... -t DIRECTORY SRCFILES...
or: $0 [OPTION]... -d DIRECTORIES...
In the 1st form, copy SRCFILE to DSTFILE.
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
In the 4th, create DIRECTORIES.
Options:
--help display this help and exit.
--version display version info and exit.
-c (ignored)
-C install only if different (preserve the last data modification time)
-d create directories instead of installing files.
-g GROUP $chgrpprog installed files to GROUP.
-m MODE $chmodprog installed files to MODE.
-o USER $chownprog installed files to USER.
-s $stripprog installed files.
-t DIRECTORY install into DIRECTORY.
-T report an error if DSTFILE is a directory.
Environment variables override the default commands:
CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
RMPROG STRIPPROG
"
while test $# -ne 0; do
case $1 in
-c) ;;
-C) copy_on_change=true;;
-d) dir_arg=true;;
-g) chgrpcmd="$chgrpprog $2"
shift;;
--help) echo "$usage"; exit $?;;
-m) mode=$2
case $mode in
*' '* | *' '* | *'
'* | *'*'* | *'?'* | *'['*)
echo "$0: invalid mode: $mode" >&2
exit 1;;
esac
shift;;
-o) chowncmd="$chownprog $2"
shift;;
-s) stripcmd=$stripprog;;
-t) dst_arg=$2
shift;;
-T) no_target_directory=true;;
--version) echo "$0 $scriptversion"; exit $?;;
--) shift
break;;
-*) echo "$0: invalid option: $1" >&2
exit 1;;
*) break;;
esac
shift
done
if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
# When -d is used, all remaining arguments are directories to create.
# When -t is used, the destination is already specified.
# Otherwise, the last argument is the destination. Remove it from $@.
for arg
do
if test -n "$dst_arg"; then
# $@ is not empty: it contains at least $arg.
set fnord "$@" "$dst_arg"
shift # fnord
fi
shift # arg
dst_arg=$arg
done
fi
if test $# -eq 0; then
if test -z "$dir_arg"; then
echo "$0: no input file specified." >&2
exit 1
fi
# It's OK to call `install-sh -d' without argument.
# This can happen when creating conditional directories.
exit 0
fi
if test -z "$dir_arg"; then
trap '(exit $?); exit' 1 2 13 15
# Set umask so as not to create temps with too-generous modes.
# However, 'strip' requires both read and write access to temps.
case $mode in
# Optimize common cases.
*644) cp_umask=133;;
*755) cp_umask=22;;
*[0-7])
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw='% 200'
fi
cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
*)
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw=,u+rw
fi
cp_umask=$mode$u_plus_rw;;
esac
fi
for src
do
# Protect names starting with `-'.
case $src in
-*) src=./$src;;
esac
if test -n "$dir_arg"; then
dst=$src
dstdir=$dst
test -d "$dstdir"
dstdir_status=$?
else
# Waiting for this to be detected by the "$cpprog $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if test ! -f "$src" && test ! -d "$src"; then
echo "$0: $src does not exist." >&2
exit 1
fi
if test -z "$dst_arg"; then
echo "$0: no destination specified." >&2
exit 1
fi
dst=$dst_arg
# Protect names starting with `-'.
case $dst in
-*) dst=./$dst;;
esac
# If destination is a directory, append the input filename; won't work
# if double slashes aren't ignored.
if test -d "$dst"; then
if test -n "$no_target_directory"; then
echo "$0: $dst_arg: Is a directory" >&2
exit 1
fi
dstdir=$dst
dst=$dstdir/`basename "$src"`
dstdir_status=0
else
# Prefer dirname, but fall back on a substitute if dirname fails.
dstdir=`
(dirname "$dst") 2>/dev/null ||
expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
X"$dst" : 'X\(//\)[^/]' \| \
X"$dst" : 'X\(//\)$' \| \
X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
echo X"$dst" |
sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
s//\1/
q
}
/^X\(\/\/\)[^/].*/{
s//\1/
q
}
/^X\(\/\/\)$/{
s//\1/
q
}
/^X\(\/\).*/{
s//\1/
q
}
s/.*/./; q'
`
test -d "$dstdir"
dstdir_status=$?
fi
fi
obsolete_mkdir_used=false
if test $dstdir_status != 0; then
case $posix_mkdir in
'')
# Create intermediate dirs using mode 755 as modified by the umask.
# This is like FreeBSD 'install' as of 1997-10-28.
umask=`umask`
case $stripcmd.$umask in
# Optimize common cases.
*[2367][2367]) mkdir_umask=$umask;;
.*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
*[0-7])
mkdir_umask=`expr $umask + 22 \
- $umask % 100 % 40 + $umask % 20 \
- $umask % 10 % 4 + $umask % 2
`;;
*) mkdir_umask=$umask,go-w;;
esac
# With -d, create the new directory with the user-specified mode.
# Otherwise, rely on $mkdir_umask.
if test -n "$dir_arg"; then
mkdir_mode=-m$mode
else
mkdir_mode=
fi
posix_mkdir=false
case $umask in
*[123567][0-7][0-7])
# POSIX mkdir -p sets u+wx bits regardless of umask, which
# is incompatible with FreeBSD 'install' when (umask & 300) != 0.
;;
*)
tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
if (umask $mkdir_umask &&
exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
then
if test -z "$dir_arg" || {
# Check for POSIX incompatibilities with -m.
# HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
# other-writeable bit of parent directory when it shouldn't.
# FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
ls_ld_tmpdir=`ls -ld "$tmpdir"`
case $ls_ld_tmpdir in
d????-?r-*) different_mode=700;;
d????-?--*) different_mode=755;;
*) false;;
esac &&
$mkdirprog -m$different_mode -p -- "$tmpdir" && {
ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
}
}
then posix_mkdir=:
fi
rmdir "$tmpdir/d" "$tmpdir"
else
# Remove any dirs left behind by ancient mkdir implementations.
rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
fi
trap '' 0;;
esac;;
esac
if
$posix_mkdir && (
umask $mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
)
then :
else
# The umask is ridiculous, or mkdir does not conform to POSIX,
# or it failed possibly due to a race condition. Create the
# directory the slow way, step by step, checking for races as we go.
case $dstdir in
/*) prefix='/';;
-*) prefix='./';;
*) prefix='';;
esac
eval "$initialize_posix_glob"
oIFS=$IFS
IFS=/
$posix_glob set -f
set fnord $dstdir
shift
$posix_glob set +f
IFS=$oIFS
prefixes=
for d
do
test -z "$d" && continue
prefix=$prefix$d
if test -d "$prefix"; then
prefixes=
else
if $posix_mkdir; then
(umask=$mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
# Don't fail if two instances are running concurrently.
test -d "$prefix" || exit 1
else
case $prefix in
*\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
*) qprefix=$prefix;;
esac
prefixes="$prefixes '$qprefix'"
fi
fi
prefix=$prefix/
done
if test -n "$prefixes"; then
# Don't fail if two instances are running concurrently.
(umask $mkdir_umask &&
eval "\$doit_exec \$mkdirprog $prefixes") ||
test -d "$dstdir" || exit 1
obsolete_mkdir_used=true
fi
fi
fi
if test -n "$dir_arg"; then
{ test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
{ test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
else
# Make a couple of temp file names in the proper directory.
dsttmp=$dstdir/_inst.$$_
rmtmp=$dstdir/_rm.$$_
# Trap to clean up those temp files at exit.
trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
# Copy the file name to the temp name.
(umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
# and set any options; do chmod last to preserve setuid bits.
#
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $cpprog $src $dsttmp" command.
#
{ test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
{ test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
{ test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
# If -C, don't bother to copy if it wouldn't change the file.
if $copy_on_change &&
old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` &&
new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
eval "$initialize_posix_glob" &&
$posix_glob set -f &&
set X $old && old=:$2:$4:$5:$6 &&
set X $new && new=:$2:$4:$5:$6 &&
$posix_glob set +f &&
test "$old" = "$new" &&
$cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
then
rm -f "$dsttmp"
else
# Rename the file to the real destination.
$doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
# The rename failed, perhaps because mv can't rename something else
# to itself, or perhaps because mv is so ancient that it does not
# support -f.
{
# Now remove or move aside any old file at destination location.
# We try this two ways since rm can't unlink itself on some
# systems and the destination file might be busy for other
# reasons. In this case, the final cleanup might fail but the new
# file should still install successfully.
{
test ! -f "$dst" ||
$doit $rmcmd -f "$dst" 2>/dev/null ||
{ $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
{ $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
} ||
{ echo "$0: cannot unlink or rename $dst" >&2
(exit 1); exit 1
}
} &&
# Now rename the file to the real destination.
$doit $mvcmd "$dsttmp" "$dst"
}
fi || exit 1
trap '' 0
fi
done
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:

367
autotools/missing 100644
View File

@ -0,0 +1,367 @@
#! /bin/sh
# Common stub for a few missing GNU programs while installing.
scriptversion=2006-05-10.23
# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006
# Free Software Foundation, Inc.
# Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
# 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, 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
if test $# -eq 0; then
echo 1>&2 "Try \`$0 --help' for more information"
exit 1
fi
run=:
sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p'
sed_minuso='s/.* -o \([^ ]*\).*/\1/p'
# In the cases where this matters, `missing' is being run in the
# srcdir already.
if test -f configure.ac; then
configure_ac=configure.ac
else
configure_ac=configure.in
fi
msg="missing on your system"
case $1 in
--run)
# Try to run requested program, and just exit if it succeeds.
run=
shift
"$@" && exit 0
# Exit code 63 means version mismatch. This often happens
# when the user try to use an ancient version of a tool on
# a file that requires a minimum version. In this case we
# we should proceed has if the program had been absent, or
# if --run hadn't been passed.
if test $? = 63; then
run=:
msg="probably too old"
fi
;;
-h|--h|--he|--hel|--help)
echo "\
$0 [OPTION]... PROGRAM [ARGUMENT]...
Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
error status if there is no known handling for PROGRAM.
Options:
-h, --help display this help and exit
-v, --version output version information and exit
--run try to run the given command, and emulate it if it fails
Supported PROGRAM values:
aclocal touch file \`aclocal.m4'
autoconf touch file \`configure'
autoheader touch file \`config.h.in'
autom4te touch the output file, or create a stub one
automake touch all \`Makefile.in' files
bison create \`y.tab.[ch]', if possible, from existing .[ch]
flex create \`lex.yy.c', if possible, from existing .c
help2man touch the output file
lex create \`lex.yy.c', if possible, from existing .c
makeinfo touch the output file
tar try tar, gnutar, gtar, then tar without non-portable flags
yacc create \`y.tab.[ch]', if possible, from existing .[ch]
Send bug reports to <bug-automake@gnu.org>."
exit $?
;;
-v|--v|--ve|--ver|--vers|--versi|--versio|--version)
echo "missing $scriptversion (GNU Automake)"
exit $?
;;
-*)
echo 1>&2 "$0: Unknown \`$1' option"
echo 1>&2 "Try \`$0 --help' for more information"
exit 1
;;
esac
# Now exit if we have it, but it failed. Also exit now if we
# don't have it and --version was passed (most likely to detect
# the program).
case $1 in
lex|yacc)
# Not GNU programs, they don't have --version.
;;
tar)
if test -n "$run"; then
echo 1>&2 "ERROR: \`tar' requires --run"
exit 1
elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
exit 1
fi
;;
*)
if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
# We have it, but it failed.
exit 1
elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
# Could not run --version or --help. This is probably someone
# running `$TOOL --version' or `$TOOL --help' to check whether
# $TOOL exists and not knowing $TOOL uses missing.
exit 1
fi
;;
esac
# If it does not exist, or fails to run (possibly an outdated version),
# try to emulate it.
case $1 in
aclocal*)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`acinclude.m4' or \`${configure_ac}'. You might want
to install the \`Automake' and \`Perl' packages. Grab them from
any GNU archive site."
touch aclocal.m4
;;
autoconf)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`${configure_ac}'. You might want to install the
\`Autoconf' and \`GNU m4' packages. Grab them from any GNU
archive site."
touch configure
;;
autoheader)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`acconfig.h' or \`${configure_ac}'. You might want
to install the \`Autoconf' and \`GNU m4' packages. Grab them
from any GNU archive site."
files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
test -z "$files" && files="config.h"
touch_files=
for f in $files; do
case $f in
*:*) touch_files="$touch_files "`echo "$f" |
sed -e 's/^[^:]*://' -e 's/:.*//'`;;
*) touch_files="$touch_files $f.in";;
esac
done
touch $touch_files
;;
automake*)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
You might want to install the \`Automake' and \`Perl' packages.
Grab them from any GNU archive site."
find . -type f -name Makefile.am -print |
sed 's/\.am$/.in/' |
while read f; do touch "$f"; done
;;
autom4te)
echo 1>&2 "\
WARNING: \`$1' is needed, but is $msg.
You might have modified some files without having the
proper tools for further handling them.
You can get \`$1' as part of \`Autoconf' from any GNU
archive site."
file=`echo "$*" | sed -n "$sed_output"`
test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
if test -f "$file"; then
touch $file
else
test -z "$file" || exec >$file
echo "#! /bin/sh"
echo "# Created by GNU Automake missing as a replacement of"
echo "# $ $@"
echo "exit 0"
chmod +x $file
exit 1
fi
;;
bison|yacc)
echo 1>&2 "\
WARNING: \`$1' $msg. You should only need it if
you modified a \`.y' file. You may need the \`Bison' package
in order for those modifications to take effect. You can get
\`Bison' from any GNU archive site."
rm -f y.tab.c y.tab.h
if test $# -ne 1; then
eval LASTARG="\${$#}"
case $LASTARG in
*.y)
SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
if test -f "$SRCFILE"; then
cp "$SRCFILE" y.tab.c
fi
SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
if test -f "$SRCFILE"; then
cp "$SRCFILE" y.tab.h
fi
;;
esac
fi
if test ! -f y.tab.h; then
echo >y.tab.h
fi
if test ! -f y.tab.c; then
echo 'main() { return 0; }' >y.tab.c
fi
;;
lex|flex)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified a \`.l' file. You may need the \`Flex' package
in order for those modifications to take effect. You can get
\`Flex' from any GNU archive site."
rm -f lex.yy.c
if test $# -ne 1; then
eval LASTARG="\${$#}"
case $LASTARG in
*.l)
SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
if test -f "$SRCFILE"; then
cp "$SRCFILE" lex.yy.c
fi
;;
esac
fi
if test ! -f lex.yy.c; then
echo 'main() { return 0; }' >lex.yy.c
fi
;;
help2man)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified a dependency of a manual page. You may need the
\`Help2man' package in order for those modifications to take
effect. You can get \`Help2man' from any GNU archive site."
file=`echo "$*" | sed -n "$sed_output"`
test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
if test -f "$file"; then
touch $file
else
test -z "$file" || exec >$file
echo ".ab help2man is required to generate this page"
exit 1
fi
;;
makeinfo)
echo 1>&2 "\
WARNING: \`$1' is $msg. You should only need it if
you modified a \`.texi' or \`.texinfo' file, or any other file
indirectly affecting the aspect of the manual. The spurious
call might also be the consequence of using a buggy \`make' (AIX,
DU, IRIX). You might want to install the \`Texinfo' package or
the \`GNU make' package. Grab either from any GNU archive site."
# The file to touch is that specified with -o ...
file=`echo "$*" | sed -n "$sed_output"`
test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
if test -z "$file"; then
# ... or it is the one specified with @setfilename ...
infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
file=`sed -n '
/^@setfilename/{
s/.* \([^ ]*\) *$/\1/
p
q
}' $infile`
# ... or it is derived from the source name (dir/f.texi becomes f.info)
test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info
fi
# If the file does not exist, the user really needs makeinfo;
# let's fail without touching anything.
test -f $file || exit 1
touch $file
;;
tar)
shift
# We have already tried tar in the generic part.
# Look for gnutar/gtar before invocation to avoid ugly error
# messages.
if (gnutar --version > /dev/null 2>&1); then
gnutar "$@" && exit 0
fi
if (gtar --version > /dev/null 2>&1); then
gtar "$@" && exit 0
fi
firstarg="$1"
if shift; then
case $firstarg in
*o*)
firstarg=`echo "$firstarg" | sed s/o//`
tar "$firstarg" "$@" && exit 0
;;
esac
case $firstarg in
*h*)
firstarg=`echo "$firstarg" | sed s/h//`
tar "$firstarg" "$@" && exit 0
;;
esac
fi
echo 1>&2 "\
WARNING: I can't seem to be able to run \`tar' with the given arguments.
You may want to install GNU tar or Free paxutils, or check the
command line arguments."
exit 1
;;
*)
echo 1>&2 "\
WARNING: \`$1' is needed, and is $msg.
You might have modified some files without having the
proper tools for further handling them. Check the \`README' file,
it often tells you about the needed prerequisites for installing
this package. You may also peek at any GNU archive site, in case
some other package would contain this missing \`$1' program."
exit 1
;;
esac
exit 0
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-end: "$"
# End:

157
autotools/pkg.m4 100644
View File

@ -0,0 +1,157 @@
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
#
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# PKG_PROG_PKG_CONFIG([MIN-VERSION])
# ----------------------------------
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
_pkg_min_version=m4_default([$1], [0.9.0])
AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
PKG_CONFIG=""
fi
fi[]dnl
])# PKG_PROG_PKG_CONFIG
# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# Check to see whether a particular set of modules exists. Similar
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
#
#
# Similar to PKG_CHECK_MODULES, make sure that the first instance of
# this or PKG_CHECK_MODULES is called, or make sure to call
# PKG_CHECK_EXISTS manually
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
m4_ifval([$2], [$2], [:])
m4_ifvaln([$3], [else
$3])dnl
fi])
# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
# ---------------------------------------------
m4_define([_PKG_CONFIG],
[if test -n "$PKG_CONFIG"; then
if test -n "$$1"; then
pkg_cv_[]$1="$$1"
else
PKG_CHECK_EXISTS([$3],
[pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
[pkg_failed=yes])
fi
else
pkg_failed=untried
fi[]dnl
])# _PKG_CONFIG
# _PKG_SHORT_ERRORS_SUPPORTED
# -----------------------------
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
_pkg_short_errors_supported=yes
else
_pkg_short_errors_supported=no
fi[]dnl
])# _PKG_SHORT_ERRORS_SUPPORTED
# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
# [ACTION-IF-NOT-FOUND])
#
#
# Note that if there is a possibility the first call to
# PKG_CHECK_MODULES might not happen, you should be sure to include an
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
#
#
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
pkg_failed=no
AC_MSG_CHECKING([for $1])
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])
if test $pkg_failed = yes; then
_PKG_SHORT_ERRORS_SUPPORTED
if test $_pkg_short_errors_supported = yes; then
$1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"`
else
$1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
fi
# Put the nasty error message in config.log where it belongs
echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
ifelse([$4], , [AC_MSG_ERROR(dnl
[Package requirements ($2) were not met:
$$1_PKG_ERRORS
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
_PKG_TEXT
])],
[AC_MSG_RESULT([no])
$4])
elif test $pkg_failed = untried; then
ifelse([$4], , [AC_MSG_FAILURE(dnl
[The pkg-config script could not be found or is too old. Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.
_PKG_TEXT
To get pkg-config, see <http://pkg-config.freedesktop.org/>.])],
[$4])
else
$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
AC_MSG_RESULT([yes])
ifelse([$3], , :, [$3])
fi[]dnl
])# PKG_CHECK_MODULES

View File

@ -0,0 +1,23 @@
dnl Copyright (C) 2009 Günther Brammer
AC_DEFUN([AX_PROG_CXX_REFTOTEMP],
[
AC_LANG_ASSERT([C++])
AC_CACHE_CHECK([wether the C++ compiler is friendly], [ax_cv_reftotemp], [
AC_COMPILE_IFELSE([
struct Foo {
operator Foo & () { return *this; }
};
#ifdef __GXX_EXPERIMENTAL_CXX0X__
void frobnicate(Foo &&) { }
#else
void frobnicate(Foo &) { }
#endif
int main () {
frobnicate (Foo());
}
], [ax_cv_reftotemp=yes], [ax_cv_reftotemp=no])])
if test $ax_cv_reftotemp = no; then
AC_MSG_ERROR([The C++ compiler won't be able to compile Clonk. Try 'CXX=g++-4.1'.])
fi[]dnl
])# AX_PROG_CXX_REFTOTEMP

181
autotools/sdl.m4 100644
View File

@ -0,0 +1,181 @@
# Configure paths for SDL
# Sam Lantinga 9/21/99
# stolen from Manish Singh
# stolen back from Frank Belew
# stolen from Manish Singh
# Shamelessly stolen from Owen Taylor
dnl AM_PATH_SDL([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
dnl Test for SDL, and define SDL_CFLAGS and SDL_LIBS
dnl
AC_DEFUN([AM_PATH_SDL],
[dnl
dnl Get the cflags and libraries from the sdl-config script
dnl
AC_ARG_WITH(sdl-prefix,[ --with-sdl-prefix=PFX Prefix where SDL is installed (optional)],
sdl_prefix="$withval", sdl_prefix="")
AC_ARG_WITH(sdl-exec-prefix,[ --with-sdl-exec-prefix=PFX Exec prefix where SDL is installed (optional)],
sdl_exec_prefix="$withval", sdl_exec_prefix="")
AC_ARG_ENABLE(sdltest, [ --disable-sdltest Do not try to compile and run a test SDL program],
, enable_sdltest=yes)
if test x$sdl_exec_prefix != x ; then
sdl_args="$sdl_args --exec-prefix=$sdl_exec_prefix"
if test x${SDL_CONFIG+set} != xset ; then
SDL_CONFIG=$sdl_exec_prefix/bin/sdl-config
fi
fi
if test x$sdl_prefix != x ; then
sdl_args="$sdl_args --prefix=$sdl_prefix"
if test x${SDL_CONFIG+set} != xset ; then
SDL_CONFIG=$sdl_prefix/bin/sdl-config
fi
fi
if test "x$prefix" != xNONE; then
PATH="$prefix/bin:$prefix/usr/bin:$PATH"
fi
AC_PATH_PROG(SDL_CONFIG, sdl-config, no, [$PATH])
min_sdl_version=ifelse([$1], ,0.11.0,$1)
AC_MSG_CHECKING(for SDL - version >= $min_sdl_version)
no_sdl=""
if test "$SDL_CONFIG" = "no" ; then
no_sdl=yes
else
SDL_CFLAGS=`$SDL_CONFIG $sdlconf_args --cflags`
SDL_LIBS=`$SDL_CONFIG $sdlconf_args --libs`
sdl_major_version=`$SDL_CONFIG $sdl_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
sdl_minor_version=`$SDL_CONFIG $sdl_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
sdl_micro_version=`$SDL_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
if test "x$enable_sdltest" = "xyes" ; then
ac_save_CFLAGS="$CFLAGS"
ac_save_CXXFLAGS="$CXXFLAGS"
ac_save_LIBS="$LIBS"
CFLAGS="$CFLAGS $SDL_CFLAGS"
CXXFLAGS="$CXXFLAGS $SDL_CFLAGS"
LIBS="$LIBS $SDL_LIBS"
dnl
dnl Now check if the installed SDL is sufficiently new. (Also sanity
dnl checks the results of sdl-config to some extent
dnl
rm -f conf.sdltest
AC_TRY_RUN([
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
char*
my_strdup (char *str)
{
char *new_str;
if (str)
{
new_str = (char *)malloc ((strlen (str) + 1) * sizeof(char));
strcpy (new_str, str);
}
else
new_str = NULL;
return new_str;
}
int main (int argc, char *argv[])
{
int major, minor, micro;
char *tmp_version;
/* This hangs on some systems (?)
system ("touch conf.sdltest");
*/
{ FILE *fp = fopen("conf.sdltest", "a"); if ( fp ) fclose(fp); }
/* HP/UX 9 (%@#!) writes to sscanf strings */
tmp_version = my_strdup("$min_sdl_version");
if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, &micro) != 3) {
printf("%s, bad version string\n", "$min_sdl_version");
exit(1);
}
if (($sdl_major_version > major) ||
(($sdl_major_version == major) && ($sdl_minor_version > minor)) ||
(($sdl_major_version == major) && ($sdl_minor_version == minor) && ($sdl_micro_version >= micro)))
{
return 0;
}
else
{
printf("\n*** 'sdl-config --version' returned %d.%d.%d, but the minimum version\n", $sdl_major_version, $sdl_minor_version, $sdl_micro_version);
printf("*** of SDL required is %d.%d.%d. If sdl-config is correct, then it is\n", major, minor, micro);
printf("*** best to upgrade to the required version.\n");
printf("*** If sdl-config was wrong, set the environment variable SDL_CONFIG\n");
printf("*** to point to the correct copy of sdl-config, and remove the file\n");
printf("*** config.cache before re-running configure\n");
return 1;
}
}
],, no_sdl=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"])
CFLAGS="$ac_save_CFLAGS"
CXXFLAGS="$ac_save_CXXFLAGS"
LIBS="$ac_save_LIBS"
fi
fi
if test "x$no_sdl" = x ; then
AC_MSG_RESULT(yes)
ifelse([$2], , :, [$2])
else
AC_MSG_RESULT(no)
if test "$SDL_CONFIG" = "no" ; then
echo "*** The sdl-config script installed by SDL could not be found"
echo "*** If SDL was installed in PREFIX, make sure PREFIX/bin is in"
echo "*** your path, or set the SDL_CONFIG environment variable to the"
echo "*** full path to sdl-config."
else
if test -f conf.sdltest ; then
:
else
echo "*** Could not run SDL test program, checking why..."
CFLAGS="$CFLAGS $SDL_CFLAGS"
CXXFLAGS="$CXXFLAGS $SDL_CFLAGS"
LIBS="$LIBS $SDL_LIBS"
AC_TRY_LINK([
#include <stdio.h>
#include "SDL.h"
int main(int argc, char *argv[])
{ return 0; }
#undef main
#define main K_and_R_C_main
], [ return 0; ],
[ echo "*** The test program compiled, but did not run. This usually means"
echo "*** that the run-time linker is not finding SDL or finding the wrong"
echo "*** version of SDL. If it is not finding SDL, you'll need to set your"
echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
echo "*** to the installed location Also, make sure you have run ldconfig if that"
echo "*** is required on your system"
echo "***"
echo "*** If you have an old version installed, it is best to remove it, although"
echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"],
[ echo "*** The test program failed to compile or link. See the file config.log for the"
echo "*** exact error that occured. This usually means SDL was incorrectly installed"
echo "*** or that you have moved SDL since it was installed. In the latter case, you"
echo "*** may want to edit the sdl-config script: $SDL_CONFIG" ])
CFLAGS="$ac_save_CFLAGS"
CXXFLAGS="$ac_save_CXXFLAGS"
LIBS="$ac_save_LIBS"
fi
fi
SDL_CFLAGS=""
SDL_LIBS=""
ifelse([$3], , :, [$3])
fi
AC_SUBST(SDL_CFLAGS)
AC_SUBST(SDL_LIBS)
rm -f conf.sdltest
])

View File

@ -0,0 +1,93 @@
dnl @synopsis VL_LIB_READLINE
dnl
dnl Searches for a readline compatible library. If found, defines
dnl `HAVE_LIBREADLINE'. If the found library has the `add_history'
dnl function, sets also `HAVE_READLINE_HISTORY'. Also checks for the
dnl locations of the necessary include files and sets `HAVE_READLINE_H'
dnl or `HAVE_READLINE_READLINE_H' and `HAVE_READLINE_HISTORY_H' or
dnl 'HAVE_HISTORY_H' if the corresponding include files exists.
dnl
dnl The libraries that may be readline compatible are `libedit',
dnl `libeditline' and `libreadline'. Sometimes we need to link a
dnl termcap library for readline to work, this macro tests these cases
dnl too by trying to link with `libtermcap', `libcurses' or
dnl `libncurses' before giving up.
dnl
dnl Here is an example of how to use the information provided by this
dnl macro to perform the necessary includes or declarations in a C
dnl file:
dnl
dnl #ifdef HAVE_LIBREADLINE
dnl # if defined(HAVE_READLINE_READLINE_H)
dnl # include <readline/readline.h>
dnl # elif defined(HAVE_READLINE_H)
dnl # include <readline.h>
dnl # else /* !defined(HAVE_READLINE_H) */
dnl extern char *readline ();
dnl # endif /* !defined(HAVE_READLINE_H) */
dnl char *cmdline = NULL;
dnl #else /* !defined(HAVE_READLINE_READLINE_H) */
dnl /* no readline */
dnl #endif /* HAVE_LIBREADLINE */
dnl
dnl #ifdef HAVE_READLINE_HISTORY
dnl # if defined(HAVE_READLINE_HISTORY_H)
dnl # include <readline/history.h>
dnl # elif defined(HAVE_HISTORY_H)
dnl # include <history.h>
dnl # else /* !defined(HAVE_HISTORY_H) */
dnl extern void add_history ();
dnl extern int write_history ();
dnl extern int read_history ();
dnl # endif /* defined(HAVE_READLINE_HISTORY_H) */
dnl /* no history */
dnl #endif /* HAVE_READLINE_HISTORY */
dnl
dnl @category InstalledPackages
dnl @author Ville Laurikari <vl@iki.fi>
dnl @version 2002-04-04
dnl @license AllPermissive
AC_DEFUN([VL_LIB_READLINE], [
AC_CACHE_CHECK([for a readline compatible library],
vl_cv_lib_readline, [
ORIG_LIBS="$LIBS"
for readline_lib in readline edit editline; do
for termcap_lib in "" termcap curses ncurses; do
if test -z "$termcap_lib"; then
TRY_LIB="-l$readline_lib"
else
TRY_LIB="-l$readline_lib -l$termcap_lib"
fi
LIBS="$ORIG_LIBS $TRY_LIB"
AC_TRY_LINK_FUNC(readline, vl_cv_lib_readline="$TRY_LIB")
if test -n "$vl_cv_lib_readline"; then
break
fi
done
if test -n "$vl_cv_lib_readline"; then
break
fi
done
if test -z "$vl_cv_lib_readline"; then
vl_cv_lib_readline="no"
LIBS="$ORIG_LIBS"
fi
])
if test "$vl_cv_lib_readline" != "no"; then
AC_DEFINE(HAVE_LIBREADLINE, 1,
[Define if you have a readline compatible library])
AC_CHECK_HEADERS(readline.h readline/readline.h)
AC_CACHE_CHECK([whether readline supports history],
vl_cv_lib_readline_history, [
vl_cv_lib_readline_history="no"
AC_TRY_LINK_FUNC(add_history, vl_cv_lib_readline_history="yes")
])
if test "$vl_cv_lib_readline_history" = "yes"; then
AC_DEFINE(HAVE_READLINE_HISTORY, 1,
[Define if your readline library has \`add_history'])
AC_CHECK_HEADERS(history.h readline/history.h)
fi
fi
])dnl

1
build_tag 100644
View File

@ -0,0 +1 @@
300

37
clonk.anjuta 100644
View File

@ -0,0 +1,37 @@
<?xml version="1.0"?>
<anjuta>
<plugin name="Automake Project Manager"
url="http://anjuta.org/plugins/"
mandatory="yes">
<require group="Anjuta Plugin"
attribute="Interfaces"
value="IAnjutaProjectManager"/>
<require group="Project"
attribute="Supported-Project-Types"
value="automake"/>
</plugin>
<plugin name="Symbol Browser"
url="http://anjuta.org/plugins/"
mandatory="yes">
<require group="Anjuta Plugin"
attribute="Location"
value="anjuta-symbol-browser:SymbolBrowserPlugin"/>
</plugin>
<plugin name="Make Build System"
url="http://anjuta.org/plugins/"
mandatory="yes">
<require group="Anjuta Plugin"
attribute="Interfaces"
value="IAnjutaBuildable"/>
<require group="Build"
attribute="Supported-Build-Types"
value="make"/>
</plugin>
<plugin name="Debug Manager"
url="http://anjuta.org/plugins/"
mandatory="no">
<require group="Anjuta Plugin"
attribute="Interfaces"
value="IAnjutaDebuggerManager"/>
</plugin>
</anjuta>

65
clonk.vc9.sln 100644
View File

@ -0,0 +1,65 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "engine", "engine\engine.vc9.vcproj", "{F0044558-503E-4793-9BD2-CF6BFF7D7545}"
ProjectSection(ProjectDependencies) = postProject
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91} = {36C4BD18-A442-41BD-9B5B-2E7FD4983B91}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Standard", "standard\Standard.vc9.vcproj", "{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "c4group", "group\c4group.vc9.vcproj", "{C2E2343A-C3D6-4D49-9336-7C1264D5C945}"
ProjectSection(ProjectDependencies) = postProject
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91} = {36C4BD18-A442-41BD-9B5B-2E7FD4983B91}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
c4group Debug|Win32 = c4group Debug|Win32
c4group Release|Win32 = c4group Release|Win32
Engine Debug Console|Win32 = Engine Debug Console|Win32
Engine Debug|Win32 = Engine Debug|Win32
Engine Release (Debug)|Win32 = Engine Release (Debug)|Win32
Engine Release Console|Win32 = Engine Release Console|Win32
Engine Release|Win32 = Engine Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.c4group Debug|Win32.ActiveCfg = Engine Debug|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.c4group Release|Win32.ActiveCfg = Engine Release|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Debug Console|Win32.ActiveCfg = Engine Debug Console|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Debug Console|Win32.Build.0 = Engine Debug Console|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Debug|Win32.ActiveCfg = Engine Debug|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Debug|Win32.Build.0 = Engine Debug|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Release (Debug)|Win32.ActiveCfg = Engine Release (Debug)|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Release (Debug)|Win32.Build.0 = Engine Release (Debug)|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Release Console|Win32.ActiveCfg = Engine Release Console|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Release Console|Win32.Build.0 = Engine Release Console|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Release|Win32.ActiveCfg = Engine Release|Win32
{F0044558-503E-4793-9BD2-CF6BFF7D7545}.Engine Release|Win32.Build.0 = Engine Release|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.c4group Debug|Win32.ActiveCfg = c4group Debug|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.c4group Debug|Win32.Build.0 = c4group Debug|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.c4group Release|Win32.ActiveCfg = c4group Release|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.c4group Release|Win32.Build.0 = c4group Release|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Debug Console|Win32.ActiveCfg = Engine Debug Console|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Debug Console|Win32.Build.0 = Engine Debug Console|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Debug|Win32.ActiveCfg = Engine Debug|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Debug|Win32.Build.0 = Engine Debug|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Release (Debug)|Win32.ActiveCfg = Engine Release (Debug)|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Release (Debug)|Win32.Build.0 = Engine Release (Debug)|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Release Console|Win32.ActiveCfg = Engine Release Console|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Release Console|Win32.Build.0 = Engine Release Console|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Release|Win32.ActiveCfg = Engine Release|Win32
{36C4BD18-A442-41BD-9B5B-2E7FD4983B91}.Engine Release|Win32.Build.0 = Engine Release|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.c4group Debug|Win32.ActiveCfg = c4group Debug|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.c4group Debug|Win32.Build.0 = c4group Debug|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.c4group Release|Win32.ActiveCfg = c4group Release|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.c4group Release|Win32.Build.0 = c4group Release|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.Engine Debug Console|Win32.ActiveCfg = c4group Release|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.Engine Debug|Win32.ActiveCfg = c4group Debug|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.Engine Release (Debug)|Win32.ActiveCfg = c4group Release|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.Engine Release Console|Win32.ActiveCfg = c4group Release|Win32
{C2E2343A-C3D6-4D49-9336-7C1264D5C945}.Engine Release|Win32.ActiveCfg = c4group Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

182
config.h.in 100644
View File

@ -0,0 +1,182 @@
/* config.h.in. Generated from configure.ac by autoheader. */
/* Activate DebugRecs */
#undef DEBUGREC
/* Define to 1 if you have the <direct.h> header file. */
#undef HAVE_DIRECT_H
/* Define to 1 if you have the <execinfo.h> header file. */
#undef HAVE_EXECINFO_H
/* Define to 1 if you have FreeType2. */
#undef HAVE_FREETYPE
/* Define to 1 if you have the <history.h> header file. */
#undef HAVE_HISTORY_H
/* Define if you have the iconv() function. */
#undef HAVE_ICONV
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the <io.h> header file. */
#undef HAVE_IO_H
/* Define to 1 if you have the <langinfo.h> header file. */
#undef HAVE_LANGINFO_H
/* Define if you have a readline compatible library */
#undef HAVE_LIBREADLINE
/* Define to 1 if you have SDL_mixer. */
#undef HAVE_LIBSDL_MIXER
/* Define to 1 if you have the <locale.h> header file. */
#undef HAVE_LOCALE_H
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the <multimon.h> header file. */
#undef HAVE_MULTIMON_H
/* Define to 1 if you have the <poll.h> header file. */
#undef HAVE_POLL_H
/* Define if you have POSIX threads libraries and header files. */
#undef HAVE_PTHREAD
/* Define to 1 if you have the <readline.h> header file. */
#undef HAVE_READLINE_H
/* Define if your readline library has \`add_history' */
#undef HAVE_READLINE_HISTORY
/* Define to 1 if you have the <readline/history.h> header file. */
#undef HAVE_READLINE_HISTORY_H
/* Define to 1 if you have the <readline/readline.h> header file. */
#undef HAVE_READLINE_READLINE_H
/* Define to 1 if you have SDL. */
#undef HAVE_SDL
/* Define to 1 if you have the <share.h> header file. */
#undef HAVE_SHARE_H
/* Define to 1 if you have the <signal.h> header file. */
#undef HAVE_SIGNAL_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* inotify reachable using syscall */
#undef HAVE_SYSCALL_INOTIFY
/* Define to 1 if you have the <sys/inotify.h> header file. */
#undef HAVE_SYS_INOTIFY_H
/* Define to 1 if you have the <sys/socket.h> header file. */
#undef HAVE_SYS_SOCKET_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/syscall.h> header file. */
#undef HAVE_SYS_SYSCALL_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if you have the `vasprintf' function. */
#undef HAVE_VASPRINTF
/* Define to 1 if you have the <X11/extensions/xf86vmode.h> header file. */
#undef HAVE_X11_EXTENSIONS_XF86VMODE_H
/* Define to 1 if you have the <X11/extensions/Xrandr.h> header file. */
#undef HAVE_X11_EXTENSIONS_XRANDR_H
/* Define to 1 if you have the <X11/keysym.h> header file. */
#undef HAVE_X11_KEYSYM_H
/* Define to 1 if you have the <X11/xpm.h> header file. */
#undef HAVE_X11_XPM_H
/* Define as const if the declaration of iconv() needs const. */
#undef ICONV_CONST
/* compile without debug options */
#undef NDEBUG
/* Define to 1 if your C compiler doesn't accept -c and -o together. */
#undef NO_MINUS_C_MINUS_O
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define to necessary symbol if this constant uses a non-standard name on
your system. */
#undef PTHREAD_CREATE_JOINABLE
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* dedicated server mode */
#undef USE_CONSOLE
/* DirectX graphics */
#undef USE_DIRECTX
/* Wether FMOD shall be used */
#undef USE_FMOD
/* OpenGL graphics */
#undef USE_GL
/* MP3 music */
#undef USE_MP3
/* Define to 1 if SDL is used for the main loop */
#undef USE_SDL_MAINLOOP
/* Define to 1 if the X Window System is used */
#undef USE_X11
/* Developer mode */
#undef WITH_DEVELOPER_MODE
/* Glib */
#undef WITH_GLIB
/* Define to 1 if the X Window System is missing or not being used. */
#undef X_DISPLAY_MISSING
/* compile with debug options */
#undef _DEBUG

11610
configure vendored 100644

File diff suppressed because it is too large Load Diff

340
configure.ac 100644
View File

@ -0,0 +1,340 @@
dnl Copyright (c) 2005-2009, RedWolf Design GmbH, http://www.clonk.de
dnl Permission to use, copy, modify, and/or distribute this software for any
dnl purpose with or without fee is hereby granted, provided that the above
dnl copyright notice and this permission notice appear in all copies.
dnl THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
dnl WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
dnl MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
dnl ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
dnl WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
dnl ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
dnl OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
dnl Process this file with autoconf to produce a configure script.
AC_PREREQ(2.59)
AC_INIT(clonk, m4_format([[[%s.%s.%s.%s]]], m4_include(version)))
AC_COPYRIGHT([©2005, 2006, 2007 Günther Brammer])
AC_CONFIG_SRCDIR([engine/src/C4Map.cpp])
AC_CONFIG_AUX_DIR([autotools])
AC_CONFIG_HEADER([config.h])
AC_CONFIG_FILES([Makefile])
AC_CANONICAL_HOST
dnl foreign to tell automake to shut up,
dnl no-dist because we do not need dist
dnl and subdir-objects because it makes the Makefile smaller.
dnl no-define because PACKAGE and VERSION are not used
AM_INIT_AUTOMAKE([foreign subdir-objects nostdinc no-dist no-define 1.10])
dnl The new every random file in the repos policy
AM_MAINTAINER_MODE
AC_PROG_CXX
AC_LANG([C++])
AX_PROG_CXX_REFTOTEMP
AC_PROG_CC
AM_PROG_CC_C_O
AC_PROG_RANLIB
# The wonders of code stolen from docs.
case $host in
*-*-mingw32* | *-*-cygwin* | *-*-windows*)
win32=true; osx=false;;
*-*-darwin*)
win32=false; osx=true;;
*)
win32=false; osx=false;;
esac
# Detect Wine. Unfortunately, at the moment winegcc does not meet the demands
AC_CHECK_HEADER([windows.h], [win32=true], [], [[ ]])
AM_CONDITIONAL(WIN32, [test $win32 = true])
# various used headers
dnl the whitespace is there to prevent AC_INCLUDES_DEFAULT
AC_CHECK_HEADERS([stdint.h unistd.h poll.h sys/stat.h sys/types.h locale.h sys/socket.h signal.h langinfo.h execinfo.h sys/inotify.h sys/syscall.h], , , [[ ]])
# Mingw does not ship with multimon.h
AC_CHECK_HEADERS([multimon.h io.h direct.h share.h], [], [], [[#include <windows.h>]])
# iconv
AX_ICONV
# vasprintf is a GNU extension
AC_CHECK_FUNCS(vasprintf)
AC_ARG_ENABLE([debug],
[AC_HELP_STRING([--enable-debug], [debugging options [default=no]])],
, [enable_debug=no])
if test $enable_debug = yes; then
AC_DEFINE([_DEBUG], 1, [compile with debug options])
else
AC_DEFINE([NDEBUG], 1, [compile without debug options])
fi
AC_ARG_ENABLE([debugrec],
[AC_HELP_STRING([--enable-debugrec], [write additional debug control to records [default=no]])],
, [enable_debugrec=no])
if test $enable_debugrec = yes; then
AC_DEFINE([DEBUGREC], 1, [Activate DebugRecs])
fi
AC_ARG_ENABLE([console],
[AC_HELP_STRING([--enable-console],[compile as pure console application [default=no]])],
, [enable_console=no])
AC_ARG_ENABLE([sound],
[AC_HELP_STRING([--enable-sound],[compile with sound support [default=yes]])],
, [if test $enable_console = yes; then enable_sound=no; else enable_sound=yes; fi])
AC_ARG_WITH([gtk],
[AC_HELP_STRING([--with-gtk], [Use gtk for the developer mode [default=no]])],
, [with_gtk=no])
if test $with_gtk = yes; then
PKG_CHECK_MODULES(GTK, glib-2.0 >= 2.4 gtk+-2.0 >= 2.4)
AC_DEFINE([WITH_GLIB], 1, [Glib])
AC_DEFINE([WITH_DEVELOPER_MODE], 1, [Developer mode])
DEVELOPER_MODE=true
fi
AM_CONDITIONAL(DEVELOPER_MODE, [test $with_gtk = yes])
AC_ARG_WITH([sdl],
AS_HELP_STRING([--with-sdl], [Use SDL @<:@default=yes (no for win32)@:>@]),
, [if test $win32 = true; then with_sdl=no; else if test $enable_console = yes; then with_sdl=no; else with_sdl=yes; fi fi])
if test $with_sdl = yes; then
# Check for SDL
SDL_VERSION=1.2.0
AM_PATH_SDL($SDL_VERSION,
[AC_DEFINE(HAVE_SDL, 1, [Define to 1 if you have SDL.])],
[AC_MSG_ERROR([libSDL not found.])])
AC_SUBST(SDL_CFLAGS)
AC_SUBST(SDL_LIBS)
if test $enable_sound = yes; then
# Check for SDL_mixer library
AC_CHECK_LIB(SDL_mixer, Mix_OpenAudio,
[AC_DEFINE(HAVE_LIBSDL_MIXER,1,[Define to 1 if you have SDL_mixer.])
SDL_LIBS="-lSDL_mixer $SDL_LIBS"],
[AC_MSG_ERROR([SDL_mixer not found.])],
[$SDL_LIBS])
fi
AC_ARG_ENABLE(sdlmainloop,
[AC_HELP_STRING([--enable-sdlmainloop],[use SDL instead of X11 or Win32 [default=no]])],
, [if test $osx = true; then enable_sdlmainloop=yes; else enable_sdlmainloop=no; fi ])
fi
if test $enable_sdlmainloop = yes; then
with_x=no
AC_DEFINE(USE_SDL_MAINLOOP, 1, [Define to 1 if SDL is used for the main loop])
fi
AM_CONDITIONAL(SDL_MAIN_LOOP, [test $enable_sdlmainloop = yes])
if test $enable_sound = yes; then
AC_ARG_ENABLE([mp3],
[AC_HELP_STRING([--enable-mp3],[enable mp3 support [default=no]])],
, [enable_mp3=no])
if test $enable_mp3 = yes; then
AC_DEFINE([USE_MP3], 1, [MP3 music])
fi
fi
if test $enable_console = no; then
if test $win32 = true; then
AC_SUBST(WINDOWS_CFLAGS, "-mwindows")
fi
else
# console mode
AC_DEFINE([USE_CONSOLE], 1, [dedicated server mode])
with_x=no
enable_sdlmainloop=no
VL_LIB_READLINE
fi
# Check for libjpeg
AC_ARG_WITH([internal-libjpeg],
[AC_HELP_STRING([--with-internal-libjpeg], [Use the included copy of libjpeg [default=no]])])
if test "$with_internal_libjpeg" != yes; then
AC_CHECK_LIB(jpeg, jpeg_read_header, [
CLONK_LIBS="-ljpeg $CLONK_LIBS"
with_internal_libjpeg=no
], [
if test "$with_internal_libjpeg" = no; then
AC_MSG_ERROR([libjpeg not found.])
else
with_internal_libjpeg=yes
fi
])
fi
if test "$with_internal_libjpeg" = yes; then
INCLUDES="$INCLUDES -I\$(top_srcdir)/standard/jpeglib"
fi
AM_CONDITIONAL(INTERNAL_JPEG, [test $with_internal_libjpeg = yes])
# Check for libpng
AC_ARG_WITH([internal-libpng],
[AC_HELP_STRING([--with-internal-libpng], [Use the included copy of libpng [default=no]])])
if test "$with_internal_libpng" != yes; then
AC_CHECK_LIB(png, png_read_image, [
CLONK_LIBS="-lpng $CLONK_LIBS"
with_internal_libpng=no
], [
if test "$with_internal_libpng" = no; then
AC_MSG_ERROR([libpng not found.])
else
with_internal_libpng=yes
fi
], [-lz])
fi
if test "$with_internal_libpng" = yes; then
INCLUDES="$INCLUDES -I\$(top_srcdir)/standard/lpng121"
fi
AM_CONDITIONAL(INTERNAL_PNG, [test $with_internal_libpng = yes])
# Check for libfreetype
AC_ARG_WITH([internal-libfreetype],
[AC_HELP_STRING([--with-internal-libfreetype], [Use the included copy of libfreetype [default=no]])])
if test "$with_internal_libfreetype" != yes && test $enable_console = no; then
if test "$cross_compiling" = no; then
AC_CHECK_PROG(FREETYPE_CONFIG, freetype-config, freetype-config)
fi
if test $FREETYPE_CONFIG; then
AC_SUBST(FREETYPE_CFLAGS, [`$FREETYPE_CONFIG --cflags`])
AC_SUBST(FREETYPE_LIBS, [`$FREETYPE_CONFIG --libs`])
with_internal_libfreetype=no
else
if test "$with_internal_libfreetype" = no; then
AC_MSG_ERROR([libfreetype not found.])
else
with_internal_libfreetype=yes
fi
fi
fi
if test "$with_internal_libfreetype" = yes; then
INCLUDES="$INCLUDES -I\$(top_srcdir)/standard/freetype2"
fi
AM_CONDITIONAL(INTERNAL_FREETYPE, [test $with_internal_libfreetype = yes])
if test "$with_internal_libfreetype" = yes || test $enable_console = no; then
AC_DEFINE(HAVE_FREETYPE, 1, [Define to 1 if you have FreeType2.])
fi
AC_SUBST(INCLUDES)
# X11, Xpm, Xrandr
AC_PATH_XTRA
if test $have_x = yes; then
AC_DEFINE(USE_X11, 1, [Define to 1 if the X Window System is used])
CLONK_LIBS="$X_LIBS $CLONK_LIBS"
AC_CHECK_HEADERS([X11/keysym.h X11/extensions/xf86vmode.h X11/xpm.h X11/extensions/Xrandr.h], ,
[AC_MSG_ERROR([A required X11 header was not found.])], [[#include <X11/Xlib.h>]])
AC_CHECK_LIB(X11, XOpenDisplay, [CLONK_LIBS="-lX11 $CLONK_LIBS"],
[AC_MSG_ERROR([libX11 not found.])], [$X_LIBS])
AC_CHECK_LIB(Xpm, XpmCreatePixmapFromData, [CLONK_LIBS="-lXpm $CLONK_LIBS"],
[AC_MSG_ERROR([libXpm not found.])], [$X_LIBS])
AC_CHECK_LIB(Xxf86vm, XF86VidModeQueryVersion, [CLONK_LIBS="-lXxf86vm $CLONK_LIBS"],
[AC_MSG_ERROR([XF86VidMode not found.])], [$X_LIBS])
AC_CHECK_LIB(Xrandr, XRRQueryExtension, [CLONK_LIBS="-lXrandr $CLONK_LIBS"],
[AC_MSG_ERROR([libXrandr not found.])], [$X_LIBS])
fi
# OpenGL
AC_ARG_WITH([gl],
[AC_HELP_STRING([--with-gl],[compile with opengl support [default=yes]])],
, [if test $enable_console = yes; then with_gl=no; else with_gl=yes; fi])
if test $with_gl = yes; then
if test $osx = true; then
CLONK_LIBS="-framework OpenGL $CLONK_LIBS"
elif test $win32 = true; then
AC_CHECK_LIB(opengl32, main, [CLONK_LIBS="-lopengl32 $CLONK_LIBS"],
[AC_MSG_ERROR([opengl32 not found.])])
AC_CHECK_LIB(glu32, main, [CLONK_LIBS="-lglu32 $CLONK_LIBS"],
[AC_MSG_ERROR([glu32 not found.])])
else
AC_CHECK_LIB(GL, glBegin, [CLONK_LIBS="-lGL $CLONK_LIBS"],
[AC_MSG_ERROR([libGL not found.])])
AC_CHECK_LIB(GLU, gluOrtho2D, [CLONK_LIBS="-lGLU $CLONK_LIBS"],
[AC_MSG_ERROR([libGLU not found.])])
fi
AC_DEFINE([USE_GL], 1, [OpenGL graphics])
fi
# DirectX
AC_ARG_WITH([directx],
[AC_HELP_STRING([--with-directx],[compile with directx support [default=no]])],
, [with_directx="no"])
if test "$with_directx" = yes; then
AC_CHECK_LIB(d3d9, main, [CLONK_LIBS="-ld3d9 $CLONK_LIBS"],
[AC_MSG_ERROR([d3d9 not found.])])
AC_DEFINE([USE_DIRECTX], 1, [DirectX graphics])
fi
if test $win32 = false; then
# OpenSSL
AC_CHECK_LIB(crypto, BIO_new, [OPENSSL_LIBS="-lcrypto"],
[AC_MSG_ERROR([libcrypto (OpenSSL) not found.])])
# pthread
ACX_PTHREAD( , [AC_MSG_ERROR([No pthread support.])])
AC_SUBST(PTHREAD_LIBS)
AC_SUBST(PTHREAD_CFLAGS)
# inotify syscall workaround
AC_CHECK_DECL(SYS_inotify_init,
AC_DEFINE([HAVE_SYSCALL_INOTIFY], 1, [inotify reachable using syscall]),,
[#include <sys/syscall.h>])
# FMod is used for windows only
AM_CONDITIONAL(USE_FMOD, false)
else
# Link openssl statically, always
OPENSSL_LIBS='$(srcdir)/standard/openssl/libcrypto.a'
# Windows
for WIN32LIB in gdi32 comdlg32 winmm ws2_32 vfw32
do
AC_CHECK_LIB([$WIN32LIB], main, [CLONK_LIBS="-l$WIN32LIB $CLONK_LIBS"], [AC_MSG_ERROR([$WIN32LIB not found.])])
done
# FMod (Library comes with standard)
if test "$enable_sound" = yes; then
AC_DEFINE([USE_FMOD], 1, [Wether FMOD shall be used])
fi
AM_CONDITIONAL(USE_FMOD, test "$enable_sound" = yes)
# windres (check needed for crosscompilation)
AC_CHECK_TOOL(WINDRES, windres, no)
if test $WINDRES = no; then
AC_MSG_ERROR([windres not found.])
fi
fi
AC_SUBST(CLONK_LIBS)
AC_SUBST(OPENSSL_LIBS)
# precompiled headers and -Wextra
AC_MSG_CHECKING([whether we are using a GNU C++ compiler version 4.1 or newer])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [[#if defined(__GNUC__) && (((__GNUC__ >= 4) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ > 4))
// all ok
#else
choke me
#endif
]])], RECENT_GCC="yes", RECENT_GCC="no")
AC_MSG_RESULT([$RECENT_GCC])
AM_CONDITIONAL(RECENT_GCC, [test $RECENT_GCC = yes])
AC_OUTPUT
echo "Configuration:
Debug: $enable_debug
Debugrec: $enable_debugrec
Pure console: $enable_console
DirectX: $with_directx
OpenGL: $with_gl
Sound: $enable_sound
GTK+: $with_gtk
X11: $have_x"
if test "$enable_sdlmainloop" = yes; then echo " SDL: mainloop";
else echo " SDL: $with_sdl"; fi
if test "$with_internal_libjpeg" = yes; then echo " libjpeg: internal";
else echo " libjpeg: external"; fi
if test "$with_internal_libpng" = yes; then echo " libpng: internal";
else echo " libpng: external"; fi
if test "$with_internal_libfreetype" = yes; then echo " freetype: internal";
else if test $FREETYPE_CONFIG; then echo " freetype: external";
else echo " freetype: no"; fi fi

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// an associated list
// used by C4AulScriptEngine, as virtual function table and include/dependency list
#ifndef INC_C4AList
#define INC_C4AList
#define C4AListChunkSize 128 // number of table entries for each chunk
// table entry
struct C4AListEntry
{
C4ID Var; void *Val;
C4AListEntry *next(); // get entry after the given one
};
// bunch of table entries
struct C4AListChunk
{
C4AListEntry Entries[C4AListChunkSize]; // table entries
void *Stop; // stop entry; should always be NULL
C4AListChunk *Next; // next chunk
};
// associative list
class C4AList
{
protected:
C4AListChunk *Table, *CurrC; // first/last table chunk
int CCount; // number of entries in current chunk
C4AListEntry *Curr; // next available entry to be used
void Grow(); // append chunk
public:
C4AList(); // constructor
~C4AList(); // destructor
void Clear(); // clear the list
C4AListEntry *push(C4ID Var = 0, void *pVal = NULL); // push var/value pair to end of list
};
#endif

View File

@ -0,0 +1,128 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#ifndef INC_C4Application
#define INC_C4Application
#include <C4ConfigShareware.h>
#include <C4Group.h>
#include <C4MusicSystem.h>
#include <C4SoundSystem.h>
#include <C4Components.h>
#include <C4InteractiveThread.h>
#include <C4Network2IRC.h>
#include <StdWindow.h>
class CStdDDraw;
class C4ApplicationGameTimer;
/* Main class to initialize configuration and execute the game */
class C4Application: public CStdApp
{
private:
// if set, this mission will be launched next
StdCopyStrBuf NextMission;
public:
C4Application();
~C4Application();
// set by ParseCommandLine
bool isFullScreen;
// set by ParseCommandLine, if neither scenario nor direct join adress has been specified
bool UseStartupDialog;
// set by ParseCommandLine, for installing registration keys
StdStrBuf IncomingKeyfile;
// set by ParseCommandLine, for manually applying downloaded update packs
StdStrBuf IncomingUpdate;
// set by ParseCommandLine, for manually invoking an update check by command line or url
bool CheckForUpdates;
// set by ParseCommandLine, only pertains to this program start - independent of Config.Startup.NoSplash
bool NoSplash;
// Flag for launching editor on quit
bool launchEditor;
// Flag for restarting the engine at the end
bool restartAtEnd;
// main System.c4g in working folder
C4Group SystemGroup;
C4MusicSystem MusicSystem;
C4SoundSystem SoundSystem;
C4GamePadControl * pGamePadControl;
// Thread for interactive processes (automatically starts as needed)
C4InteractiveThread InteractiveThread;
// IRC client for global chat
C4Network2IRCClient IRCClient;
// Tick timing
class CStdDDraw *DDraw;
void Clear();
void GameTick();
void Draw();
// System.c4g helper funcs
bool OpenSystemGroup() { return SystemGroup.IsOpen() || SystemGroup.Open(C4CFN_System); }
void CloseSystemGroup() { SystemGroup.Close(); }
void SetGameTickDelay(int iDelay);
virtual void OnResolutionChanged(unsigned int iXRes, unsigned int iYRes);
bool SetGameFont(const char *szFontFace, int32_t iFontSize);
void NextTick();
protected:
enum State { C4AS_None, C4AS_PreInit, C4AS_Startup, C4AS_StartGame, C4AS_Game, C4AS_Quit, } AppState;
C4ApplicationGameTimer *pGameTimer;
protected:
virtual bool DoInit();
bool OpenGame();
bool PreInit();
static BOOL ProcessCallback(const char *szMessage, int iProcess);
virtual void OnCommand(const char *szCmd);
public:
virtual void Quit();
void QuitGame(); // quit game only, but restart application if in fullscreen startup menu mode
void Activate(); // activate app to gain full focus in OS
void SetNextMission(const char *szMissionFilename);
};
extern C4Application Application;
class C4ApplicationGameTimer : public CStdMultimediaTimerProc
{
public:
C4ApplicationGameTimer();
private:
unsigned int iLastGameTick, iGameTickDelay;
bool fRecursing;
public:
void SetGameTickDelay(uint32_t iDelay);
virtual bool Execute(int iTimeout, pollfd *);
};
class C4ApplicationSec1Timer : protected CStdTimerProc
{
public:
C4ApplicationSec1Timer() : CStdTimerProc(1000) { }
virtual void OnSec1Timer() = 0;
private:
virtual bool Execute(int, pollfd *)
{
if(CheckAndReset())
OnSec1Timer();
return true;
}
};
#endif

572
engine/inc/C4Aul.h 100644
View File

@ -0,0 +1,572 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// C4Aul script engine CP conversion
// (cut C4Aul of classes/structs and put everything in namespace C4Aul instead?)
// drop uncompiled scripts when not in developer mode
// -> build string table
// -> clear the string table in UnLink? ReLink won't happen to be called in player mode anyway
#ifndef INC_C4Aul
#define INC_C4Aul
#include <C4AList.h>
#include <C4ValueList.h>
#include <C4ValueMap.h>
#include <C4Id.h>
#include <C4Script.h>
#include <C4StringTable.h>
// debug mode?
#ifdef _DEBUG
#define C4AUL_DEBUG
#endif
// class predefs
class C4AulError;
class C4AulFunc;
class C4AulScriptFunc;
class C4AulDefFunc;
class C4AulScript;
class C4AulScriptEngine;
struct C4AulContext;
struct C4AulBCC;
// consts
#define C4AUL_MAX_String 1024// max string length
#define C4AUL_MAX_Identifier 100 // max length of function identifiers
#define C4AUL_MAX_Par 10 // max number of parameters
#define C4AUL_MAX_Var 10 // max number of func local vars
#define C4AUL_ControlMethod_None 0
#define C4AUL_ControlMethod_Classic 1
#define C4AUL_ControlMethod_JumpAndRun 2
#define C4AUL_ControlMethod_All 3
// generic C4Aul error class
class C4AulError
{
protected:
StdStrBuf sMessage;
public:
C4AulError();
C4AulError(const C4AulError& Error) { sMessage.Copy(Error.sMessage); } // copy - constructor
virtual ~C4AulError() { } // destructor
virtual void show(); // present error message
};
// parse error
class C4AulParseError : public C4AulError
{
public:
C4AulParseError(C4AulScript *pScript, const char *pMsg, const char *pIdtf = NULL, BOOL Warn = FALSE); // constructor
C4AulParseError(class C4AulParseState * state, const char *pMsg, const char *pIdtf = NULL, BOOL Warn = FALSE); // constructor
};
// execution error
class C4AulExecError : public C4AulError
{
C4Object *cObj;
public:
C4AulExecError(C4Object *pObj, const char *szError); // constructor
virtual void show(); // present error message
};
// function access
enum C4AulAccess
{
AA_PRIVATE,
AA_PROTECTED,
AA_PUBLIC,
AA_GLOBAL
};
struct C4AulParSet
{
C4Value Par[C4AUL_MAX_Par];
C4AulParSet() {} // standard-constructor
C4AulParSet(const C4Value &par0, const C4Value &par1 = C4Value(), const C4Value &par2 = C4Value(), const C4Value &par3 = C4Value(), const C4Value &par4 = C4Value(),
const C4Value &par5 = C4Value(), const C4Value &par6 = C4Value(), const C4Value &par7 = C4Value(), const C4Value &par8 = C4Value(), const C4Value &par9 = C4Value())
{
Par[0].Set(par0); Par[1].Set(par1); Par[2].Set(par2); Par[3].Set(par3); Par[4].Set(par4);
Par[5].Set(par5); Par[6].Set(par6); Par[7].Set(par7); Par[8].Set(par8); Par[9].Set(par9);
}
C4Value & operator[](int iIdx) { return Par[iIdx]; }
C4AulParSet * operator&() { return this; }
};
#define Copy2ParSet8(Pars, Vars) Pars[0].Set(Vars##0); Pars[1].Set(Vars##1); Pars[2].Set(Vars##2); Pars[3].Set(Vars##3); Pars[4].Set(Vars##4); Pars[5].Set(Vars##5); Pars[6].Set(Vars##6); Pars[7].Set(Vars##7);
#define Copy2ParSet9(Pars, Vars) Pars[0].Set(Vars##0); Pars[1].Set(Vars##1); Pars[2].Set(Vars##2); Pars[3].Set(Vars##3); Pars[4].Set(Vars##4); Pars[5].Set(Vars##5); Pars[6].Set(Vars##6); Pars[7].Set(Vars##7); Pars[8].Set(Vars##8);
#define Copy2ParSet10(Pars, Vars) Pars[0].Set(Vars##0); Pars[1].Set(Vars##1); Pars[2].Set(Vars##2); Pars[3].Set(Vars##3); Pars[4].Set(Vars##4); Pars[5].Set(Vars##5); Pars[6].Set(Vars##6); Pars[7].Set(Vars##7); Pars[8].Set(Vars##8); Pars[9].Set(Vars##9);
// byte code chunk type
// some special script functions defined hard-coded to reduce the exec context
enum C4AulBCCType
{
AB_ARRAYA_R, // array access
AB_ARRAYA_V, // not creating a reference
AB_VARN_R, // a named var
AB_VARN_V,
AB_PARN_R, // a named parameter
AB_PARN_V,
AB_LOCALN_R, // a named local
AB_LOCALN_V,
AB_GLOBALN_R, // a named global
AB_GLOBALN_V,
AB_VAR_R, // Var statement
AB_VAR_V,
AB_PAR_R, // Par statement
AB_PAR_V,
AB_FUNC, // function
// prefix
AB_Inc1, // ++
AB_Dec1, // --
AB_BitNot, // ~
AB_Not, // !
// +
AB_Neg, // -
// postfix (whithout second statement)
AB_Inc1_Postfix, // ++
AB_Dec1_Postfix, // --
// postfix
AB_Pow, // **
AB_Div, // /
AB_Mul, // *
AB_Mod, // %
AB_Sub, // -
AB_Sum, // +
AB_LeftShift, // <<
AB_RightShift, // >>
AB_LessThan, // <
AB_LessThanEqual, // <=
AB_GreaterThan, // >
AB_GreaterThanEqual, // >=
AB_EqualIdent, // old ==
AB_Equal, // new ==
AB_NotEqualIdent, // old !=
AB_NotEqual, // new !=
AB_SEqual, // S=, eq
AB_SNEqual, // ne
AB_BitAnd, // &
AB_BitXOr, // ^
AB_BitOr, // |
AB_And, // &&
AB_Or, // ||
AB_MulIt, // *=
AB_DivIt, // /=
AB_ModIt, // %=
AB_Inc, // +=
AB_Dec, // -=
AB_AndIt, // &=
AB_OrIt, // |=
AB_XOrIt, // ^=
AB_Set, // =
AB_CALL, // direct object call
AB_CALLFS, // failsafe direct call
AB_CALLNS, // direct object call: namespace operator
AB_STACK, // push nulls / pop
AB_INT, // constant: int
AB_BOOL, // constant: bool
AB_STRING, // constant: string
AB_C4ID, // constant: C4ID
AB_ARRAY, // semi-constant: array
AB_IVARN, // initialization of named var
AB_JUMP, // jump
AB_JUMPAND, // jump if zero, else pop the stack
AB_JUMPOR, // jump if not zero, else pop the stack
AB_CONDN, // conditional jump (negated, pops stack)
AB_FOREACH_NEXT, // foreach: next element
AB_RETURN, // return statement
AB_ERR, // parse error at this position
AB_EOFN, // end of function
AB_EOF, // end of file
};
// ** a definition of an operator
// there are two classes of operators, the postfix-operators (+,-,&,...) and the
// prefix-operators (mainly !,~,...).
struct C4ScriptOpDef
{
unsigned short Priority;
const char* Identifier;
C4AulBCCType Code;
BOOL Postfix;
BOOL RightAssociative; // right oder left-associative?
BOOL NoSecondStatement; // no second statement expected (++/-- postfix)
C4V_Type RetType; // type returned. ignored by C4V
C4V_Type Type1;
C4V_Type Type2;
};
extern C4ScriptOpDef C4ScriptOpMap[];
// byte code chunk
struct C4AulBCC
{
C4AulBCCType bccType; // chunk type
intptr_t bccX; // extra info (long for use with amd64)
const char *SPos;
};
// call context
struct C4AulContext
{
C4Object *Obj;
C4Def *Def;
struct C4AulScriptContext *Caller;
};
// execution context
struct C4AulScriptContext : public C4AulContext
{
C4Value *Return;
C4Value *Pars;
C4Value *Vars;
C4AulScriptFunc *Func;
bool TemporaryScript;
C4ValueList NumVars;
C4AulBCC *CPos;
time_t tTime; // initialized only by profiler if active
int ParCnt() const { return Vars - Pars; }
void dump(StdStrBuf Dump = StdStrBuf(""));
};
// base function class
class C4AulFunc
{
friend class C4AulScript;
friend class C4AulScriptEngine;
friend class C4AulFuncMap;
friend class C4AulParseState;
public:
C4AulFunc(C4AulScript *pOwner, const char *pName, bool bAtEnd = true); // constructor
virtual ~C4AulFunc(); // destructor
C4AulScript *Owner; // owner
char Name[C4AUL_MAX_Identifier]; // function name
protected:
C4AulFunc *Prev, *Next; // linked list members
C4AulFunc *MapNext; // map member
C4AulFunc *LinkedTo; // points to next linked function; destructor will destroy linked func, too
public:
C4AulFunc *OverloadedBy; // function by which this one is overloaded
virtual C4AulScriptFunc *SFunc() { return NULL; } // type check func...
// Wether this function should be visible to players
virtual bool GetPublic() { return false; }
virtual int GetParCount() { return C4AUL_MAX_Par; }
virtual C4V_Type* GetParType() { return 0; }
virtual C4V_Type GetRetType() { return C4V_Any; }
virtual C4Value Exec(C4AulContext *pCallerCtx, C4Value pPars[], bool fPassErrors=false) { return C4Value(); } // execute func (script call)
virtual C4Value Exec(C4Object *pObj=NULL, C4AulParSet *pPars = NULL, bool fPassErrors=false); // execute func (engine call)
virtual void UnLink() { OverloadedBy = NULL; }
C4AulFunc *GetLocalSFunc(const char *szIdtf); // find script function in own scope
protected:
void DestroyLinked(); // destroys linked functions
};
// script function class
class C4AulScriptFunc : public C4AulFunc
{
public:
C4AulFunc *OwnerOverloaded; // overloaded owner function; if present
C4AulScriptFunc *SFunc() { return this; } // type check func...
protected:
void ParseDesc(); // evaluate desc (i.e. get idImage and Condition
public:
C4AulAccess Access;
StdCopyStrBuf Desc; // full function description block, including image and condition
StdCopyStrBuf DescText; // short function description text (name of menu entry)
StdCopyStrBuf DescLong; // secondary function description
C4ID idImage; // associated image
int32_t iImagePhase; // Image phase
C4AulFunc *Condition; // func condition
int32_t ControlMethod; // 0 = all, 1 = Classic, 2 = Jump+Run
const char *Script; // script pos
C4AulBCC *Code; // code pos
C4ValueMapNames VarNamed; // list of named vars in this function
C4ValueMapNames ParNamed; // list of named pars in this function
C4V_Type ParType[C4AUL_MAX_Par]; // parameter types
bool bNewFormat; // new func format? [ func xyz(par abc) { ... } ]
bool bReturnRef; // return reference
C4AulScript *pOrgScript; // the orginal script (!= Owner if included or appended)
C4AulScriptFunc(C4AulScript *pOwner, const char *pName, bool bAtEnd = true) : C4AulFunc(pOwner, pName, bAtEnd),
idImage (C4ID_None), iImagePhase(0), Condition(NULL), ControlMethod(C4AUL_ControlMethod_All), OwnerOverloaded(NULL),
bReturnRef(false), tProfileTime(0)
{
for(int i = 0; i < C4AUL_MAX_Par; i++) ParType[i] = C4V_Any;
} // constructor
virtual void UnLink();
virtual bool GetPublic() { return true; }
virtual C4V_Type *GetParType() { return ParType; }
virtual C4V_Type GetRetType() { return bReturnRef ? C4V_pC4Value : C4V_Any; }
virtual C4Value Exec(C4AulContext *pCallerCtx, C4Value pPars[], bool fPassErrors=false); // execute func (script call, should not happen)
virtual C4Value Exec(C4Object *pObj=NULL, C4AulParSet *pPars = NULL, bool fPassErrors=false); // execute func (engine call)
void SetError(C4AulContext *ctx, const char *szMessage); // set error message
void CopyBody(C4AulScriptFunc &FromFunc); // copy script/code, etc from given func
StdStrBuf GetFullName(); // get a fully classified name (C4ID::Name) for debug output
time_t tProfileTime; // internally set by profiler
friend class C4AulScript;
};
// defined function class
class C4AulDefFunc : C4AulFunc
{
public:
C4ScriptFnDef* Def;
C4AulDefFunc(C4AulScript *pOwner, const char *pName, C4ScriptFnDef* pDef) : C4AulFunc(pOwner, pName) // constructor
{ Def = pDef; }
virtual bool GetPublic() { return !!Def->Public; }
virtual C4V_Type* GetParType() { return Def->ParType; }
virtual C4V_Type GetRetType() { return Def->RetType; }
virtual C4Value Exec(C4AulContext *pCallerCtx, C4Value pPars[], bool fPassErrors=false); // execute func (script call)
};
class C4AulFuncMap {
public:
C4AulFuncMap();
~C4AulFuncMap();
C4AulFunc * GetFunc(const char * Name, const C4AulScript * Owner, const C4AulFunc * After);
C4AulFunc * GetFirstFunc(const char * Name);
C4AulFunc * GetNextSNFunc(const C4AulFunc * After);
private:
C4AulFunc ** Funcs;
int FuncCnt;
int Capacity;
static unsigned int Hash(const char * Name);
protected:
void Add(C4AulFunc * func, bool bAtEnd = true);
void Remove(C4AulFunc * func);
friend class C4AulFunc;
};
// aul script state
enum C4AulScriptState
{
ASS_ERROR, // erroneous script
ASS_NONE, // nothing
ASS_PREPARSED, // function list built; CodeSize set
ASS_LINKED, // includes and appends resolved
ASS_PARSED // byte code generated
};
#ifdef C4ENGINE
// script profiler entry
class C4AulProfiler
{
private:
// map entry
struct Entry
{
C4AulScriptFunc *pFunc;
time_t tProfileTime;
bool operator < (const Entry &e2) const { return tProfileTime < e2.tProfileTime ; }
};
// items
std::vector<Entry> Times;
public:
void CollectEntry(C4AulScriptFunc *pFunc, time_t tProfileTime);
void Show();
static void Abort();
static void StartProfiling(C4AulScript *pScript);
static void StopProfiling();
};
#endif
// script class
class C4AulScript
{
// MSVC maybe needs this.
#ifdef _MSC_VER
friend class C4AulScript;
#endif
public:
C4AulScript(); // constructor
virtual ~C4AulScript(); // destructor
void Default(); // init
void Clear(); // remove script, byte code and children
void Reg2List(C4AulScriptEngine *pEngine, C4AulScript *pOwner); // reg to linked list
void Unreg(); // remove from list
virtual BOOL Delete() { return TRUE; } // allow deletion on pure class
protected:
C4AulFunc *Func0, *FuncL; // owned functions
C4AulScriptEngine *Engine; //owning engine
C4AulScript *Owner, *Prev, *Next, *Child0, *ChildL; // tree structure
StdStrBuf Script; // script
C4AulBCC *Code, *CPos; // compiled script (/pos)
C4AulScriptState State; // script state
int CodeSize; // current number of byte code chunks in Code
int CodeBufSize; // size of Code buffer
bool Preparsing; // set while preparse
bool Resolving; // set while include-resolving, to catch circular includes
C4AListEntry *Includes; // include list
C4AListEntry *Appends; // append list
// internal function used to find overloaded functions
C4AulFunc *GetOverloadedFunc(C4AulFunc *ByFunc);
C4AulFunc *GetFunc(const char *pIdtf); // get local function by name
void AddBCC(C4AulBCCType eType, intptr_t = 0, const char * SPos = 0); // add byte code chunk and advance
void ClearCode();
BOOL Preparse(); // preparse script; return if successfull
void ParseFn(C4AulScriptFunc *Fn, bool fExprOnly = false); // parse single script function
BOOL Parse(); // parse preparsed script; return if successfull
void ParseDescs(); // parse function descs
BOOL ResolveIncludes(C4DefList *rDefs); // resolve includes
BOOL ResolveAppends(C4DefList *rDefs); // resolve appends
bool IncludesResolved;
void AppendTo(C4AulScript &Scr, bool bHighPrio); // append to given script
void UnLink(); // reset to unlinked state
virtual void AfterLink(); // called after linking is completed; presearch common funcs here
virtual BOOL ReloadScript(const char *szPath); // reload given script
C4AulScript *FindFirstNonStrictScript(); // find first script that is not #strict
int GetCodePos() const { return CPos - Code; }
C4AulBCC *GetCodeByPos(int iPos) { return Code + iPos; }
public:
StdCopyStrBuf ScriptName; // script name
C4Def *Def; // owning def file
C4ValueMapNames LocalNamed;
enum Strict { NONSTRICT = 0, STRICT1 = 1, STRICT2 = 2, MAXSTRICT=STRICT2 };
enum Strict Strict; // new or even newer syntax?
bool Temporary; // set for DirectExec-scripts; do not parse those
const char *GetScript() const { return Script.getData(); }
C4AulFunc *GetFuncRecursive(const char *pIdtf); // search function by identifier, including global funcs
C4AulScriptFunc *GetSFunc(const char *pIdtf, C4AulAccess AccNeeded, BOOL fFailSafe = false); // get local sfunc, check access, check '~'-safety
C4AulScriptFunc *GetSFunc(const char *pIdtf); // get local script function by name
C4AulScriptFunc *GetSFunc(int iIndex, const char *szPattern = NULL); // get local script function by index
C4AulScriptFunc *GetSFuncWarn(const char *pIdtf, C4AulAccess AccNeeded, const char *WarnStr); // get function; return NULL and warn if not existant
void AddFunc(const char *pIdtf, C4ScriptFnDef* Def); // add def def func to table
public:
C4Value DirectExec(C4Object *pObj, const char *szScript, const char *szContext, bool fPassErrors = false, enum Strict Strict = MAXSTRICT); // directly parse uncompiled script (WARG! CYCLES!)
void ResetProfilerTimes(); // zero all profiler times of owned functions
void CollectProfilerTimes(class C4AulProfiler &rProfiler);
bool IsReady() { return State == ASS_PARSED; } // whether script calls may be done
// helper functions
void Warn(const char *pMsg, const char *pIdtf);
friend class C4AulParseError;
friend class C4AulFunc;
friend class C4AulScriptFunc;
friend class C4AulScriptEngine;
friend class C4AulParseState;
};
// holds all C4AulScripts
class C4AulScriptEngine : public C4AulScript
{
protected:
C4AList itbl; // include table
C4AList atbl; // append table
C4AulFuncMap FuncLookUp;
public:
int warnCnt, errCnt; // number of warnings/errors
int nonStrictCnt; // number of non-strict scripts
int lineCnt; // line count parsed
C4ValueList Global;
C4ValueMapNames GlobalNamedNames;
C4ValueMapData GlobalNamed;
C4StringTable Strings;
// global constants (such as "static const C4D_Structure = 2;")
// cannot share var lists, because it's so closely tied to the data lists
// constants are used by the Parser only, anyway, so it's not
// necessary to pollute the global var list here
C4ValueMapNames GlobalConstNames;
C4ValueMapData GlobalConsts;
C4AulScriptEngine(); // constructor
~C4AulScriptEngine(); // destructor
void Clear(); // clear data
void Link(C4DefList *rDefs); // link and parse all scripts
void ReLink(C4DefList *rDefs); // unlink + relink and parse all scripts
BOOL ReloadScript(const char *szScript, C4DefList *pDefs); // search script and reload + relink, if found
C4AulFunc * GetFirstFunc(const char * Name)
{ return FuncLookUp.GetFirstFunc(Name); }
C4AulFunc * GetFunc(const char * Name, const C4AulScript * Owner, const C4AulFunc * After)
{ return FuncLookUp.GetFunc(Name, Owner, After); }
C4AulFunc * GetNextSNFunc(const C4AulFunc * After)
{ return FuncLookUp.GetNextSNFunc(After); }
// For the list of functions in the PropertyDlg
C4AulFunc * GetFirstFunc() { return Func0; }
C4AulFunc * GetNextFunc(C4AulFunc * pFunc) { return pFunc->Next; }
void RegisterGlobalConstant(const char *szName, const C4Value &rValue); // creates a new constants or overwrites an old one
bool GetGlobalConstant(const char *szName, C4Value *pTargetValue); // check if a constant exists; assign value to pTargetValue if not NULL
BOOL DenumerateVariablePointers();
void UnLink(); // called when a script is being reloaded (clears string table)
// Compile scenario script data (without strings and constants)
void CompileFunc(StdCompiler *pComp);
friend class C4AulFunc;
friend class C4AulParseState;
};
#endif

View File

@ -0,0 +1,200 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2007-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// IRC client dialog
#ifndef INC_C4ChatDlg
#define INC_C4ChatDlg
#include "C4Gui.h"
#include "C4InteractiveThread.h"
#include "C4Network2IRC.h"
// a GUI control to chat in
class C4ChatControl : public C4GUI::Window, private C4InteractiveThread::Callback
{
private:
// one open channel or query
class ChatSheet : public C4GUI::Tabular::Sheet
{
public:
// one item in the nick list
class NickItem : public C4GUI::Window
{
private:
C4GUI::Icon *pStatusIcon; // status icon indicating channel status (e.g. operator)
C4GUI::Label *pNameLabel; // the nickname
bool fFlaggedExisting; // flagged for existance; used by user update func
int32_t iStatus;
public:
NickItem(class C4Network2IRCUser *pByUser);
protected:
virtual void UpdateOwnPos();
public:
const char *GetNick() const { return pNameLabel->GetText(); }
int32_t GetStatus() const { return iStatus; }
void Update(class C4Network2IRCUser *pByUser);
void SetFlaggedExisting(bool fToVal) { fFlaggedExisting = fToVal; }
bool IsFlaggedExisting() const { return fFlaggedExisting; }
static int32_t SortFunc(const C4GUI::Element *pEl1, const C4GUI::Element *pEl2, void *);
};
enum SheetType { CS_Server, CS_Channel, CS_Query };
private:
C4ChatControl *pChatControl;
C4GUI::TextWindow *pChatBox;
C4GUI::ListBox *pNickList;
C4GUI::WoodenLabel *pInputLbl;
C4GUI::Edit *pInputEdit;
int32_t iBackBufferIndex; // chat message history index
SheetType eType;
StdStrBuf sIdent;
bool fHasUnread;
StdStrBuf sChatTitle; // topic for channels; name+ident for queries; server name for server sheet
C4KeyBinding *pKeyHistoryUp, *pKeyHistoryDown; // keys used to scroll through chat history
public:
ChatSheet(C4ChatControl *pChatControl, const char *szTitle, const char *szIdent, SheetType eType);
virtual ~ChatSheet();
C4GUI::Edit *GetInputEdit() const { return pInputEdit; }
SheetType GetSheetType() const { return eType; }
const char *GetIdent() const { return sIdent.getData(); }
void SetIdent(const char *szToIdent) { sIdent.Copy(szToIdent); }
const char *GetChatTitle() const { return sChatTitle.getData(); }
void SetChatTitle(const char *szNewTitle) { sChatTitle.Copy(szNewTitle); }
void AddTextLine(const char *szText, uint32_t dwClr);
void DoError(const char *szError);
void Update(bool fLock);
void UpdateUsers(C4Network2IRCUser *pUsers);
void ResetUnread(); // mark messages as read
protected:
virtual void UpdateSize();
virtual void OnShown(bool fByUser);
virtual void UserClose(); // user pressed close button: Close queries, part channels, etc.
C4GUI::Edit::InputResult OnChatInput(C4GUI::Edit *edt, bool fPasting, bool fPastingMore);
bool KeyHistoryUpDown(bool fUp);
void OnNickDblClick(class C4GUI::Element *pEl);
private:
NickItem *GetNickItem(const char *szByNick);
NickItem *GetFirstNickItem() { return pNickList ? static_cast<NickItem *>(pNickList->GetFirst()) : NULL; }
NickItem *GetNextNickItem(NickItem *pPrev) { return static_cast<NickItem *>(pPrev->GetNext()); }
};
private:
C4GUI::Tabular *pTabMain, *pTabChats;
// login controls
C4GUI::Label *pLblLoginNick, *pLblLoginPass, *pLblLoginRealName, *pLblLoginChannel;
C4GUI::Edit *pEdtLoginNick, *pEdtLoginPass, *pEdtLoginRealName, *pEdtLoginChannel;
C4GUI::Button *pBtnLogin;
StdStrBuf sTitle;
C4GUI::BaseInputCallback *pTitleChangeBC;
C4Network2IRCClient *pIRCClient;
bool fInitialMessagesReceived; // set after initial update call, which fetches all messages. Subsequent calls fetch only unread messages
public:
C4ChatControl(C4Network2IRCClient *pIRC);
virtual ~C4ChatControl();
protected:
virtual void UpdateSize();
C4GUI::Edit::InputResult OnLoginDataEnter(C4GUI::Edit *edt, bool fPasting, bool fPastingMore); // advance focus when user presses enter in one of the login edits
void OnConnectBtn(C4GUI::Control *btn); // callback: connect button pressed
public:
virtual class C4GUI::Control *GetDefaultControl();
C4Network2IRCClient *getIRCClient() { return pIRCClient; }
void SetTitleChangeCB(C4GUI::BaseInputCallback *pNewCB);
virtual void OnShown(); // callback when shown
void UpdateShownPage();
void Update();
void UpdateTitle();
bool DlgEnter();
void OnSec1Timer() { Update(); } // timer proc
bool ProcessInput(const char *szInput, ChatSheet *pChatSheet); // process chat input - return false if no more pasting is to be done (i.e., on /quit or /part in channel)
const char *GetTitle() { return sTitle.getData(); }
void UserQueryQuit();
ChatSheet *OpenQuery(const char *szForNick, bool fSelect, const char *szIdentFallback);
private:
static bool IsServiceName(const char *szName);
ChatSheet *GetActiveChatSheet();
ChatSheet *GetSheetByTitle(const char *szTitle, C4ChatControl::ChatSheet::SheetType eType);
ChatSheet *GetSheetByIdent(const char *szIdent, C4ChatControl::ChatSheet::SheetType eType);
ChatSheet *GetServerSheet();
void ClearChatSheets();
// IRC event hook
virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) { if(pEventData == pIRCClient) Update(); }
};
// container dialog for the C4ChatControl
class C4ChatDlg : public C4GUI::Dialog
{
private:
static C4ChatDlg *pInstance;
class C4ChatControl *pChatCtrl;
C4GUI::Button *pBtnClose;
public:
C4ChatDlg();
virtual ~C4ChatDlg();
static C4ChatDlg *ShowChat();
static void StopChat();
static bool IsChatActive();
static bool IsChatEnabled();
static bool ToggleChat();
protected:
// default control to be set if unprocessed keyboard input has been detected
virtual class C4GUI::Control *GetDefaultControl();
// true for dialogs that should span the whole screen
// not just the mouse-viewport
virtual bool IsFreePlaceDialog() { return true; }
// true for dialogs that receive keyboard input even in shared mode
virtual bool IsExclusiveDialog() { return true; }
// for custom placement procedures; should call SetPos
virtual bool DoPlacement(C4GUI::Screen *pOnScreen, const C4Rect &rPreferredDlgRect);
virtual void OnClosed(bool fOK); // callback when dlg got closed
virtual void OnShown(); // callback when shown - should not delete the dialog
virtual void UpdateSize();
void OnExitBtn(C4GUI::Control *btn); // callback: exit button pressed
void OnChatTitleChange(const StdStrBuf &sNewTitle);
};
#endif // INC_C4ChatDlg

View File

@ -0,0 +1,177 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#ifndef C4CLIENT_H
#define C4CLIENT_H
#include "C4NetIO.h"
#include "C4PacketBase.h"
#include "C4InputValidation.h"
// special ids
const int32_t C4ClientIDUnknown = -1,
C4ClientIDHost = 0,
C4ClientIDStart = 1;
// client core difference levels
const int32_t C4ClientCoreDL_None = 0, // identical
C4ClientCoreDL_IDMatch = 1, // status change
C4ClientCoreDL_IDChange = 2, // identification changed (host only!)
C4ClientCoreDL_Different = 3; // really different
class C4ClientCore : public C4PacketBase
{
public:
C4ClientCore();
~C4ClientCore();
protected:
// identification
int32_t iID;
ValidatedStdCopyStrBuf<C4InVal::VAL_NameNoEmpty> Name, Nick;
ValidatedStdCopyStrBuf<C4InVal::VAL_NameAllowEmpty> CUID;
// version info
int iVersion[4];
// status
bool fActivated, fObserver;
public:
// status data
int32_t getID() const { return iID; }
bool isHost() const { return iID == C4ClientIDHost; }
bool isActivated() const { return fActivated; }
bool isObserver() const { return fObserver; }
void SetID(int32_t inID) { iID = inID; }
void SetName(const char *sznName) { Name.CopyValidated(sznName); }
void SetActivated(bool fnActivated) { fActivated = fnActivated; fObserver = false; }
void SetObserver(bool fnObserver) { fActivated &= !(fObserver = fnObserver); }
// misc
const char *getName() const { return Name.getData(); }
const char *getCUID() const { return CUID.getData(); }
const char *getNick() const { return Nick.getData(); }
bool isRegistered()const { return CUID.getLength()>0; }
// initialization
void SetLocal(int32_t iID, bool fnActivated, bool fnObserver);
void SetUnknown(int32_t iID);
int32_t getDiffLevel(const C4ClientCore &CCore2) const;
virtual void CompileFunc(StdCompiler *pComp);
};
class C4Client
{
friend class C4ClientList;
public:
C4Client();
C4Client(const C4ClientCore &Core);
~C4Client();
private:
C4ClientCore Core;
bool fLocal; // Local, NoSync
class C4Network2Client *pNetClient; // Local, NoSync
C4Client *pNext;
public:
const C4ClientCore &getCore() const { return Core; }
int32_t getID() const { return Core.getID(); }
bool isHost() const { return Core.isHost(); }
const char *getName() const { return Core.getName(); }
const char *getCUID() const { return Core.getCUID(); }
const char *getNick() const { return Core.getNick(); }
bool isActivated() const { return Core.isActivated(); }
bool isObserver() const { return Core.isObserver(); }
bool isRegistered()const { return Core.isRegistered(); }
bool isLocal() const { return fLocal; }
C4Network2Client *getNetClient() const { return pNetClient; }
void SetCore(const C4ClientCore &NewCore) { Core = NewCore; }
void SetID(int32_t iID) { Core.SetID(iID); }
void SetActivated(bool fnActivated);
void SetObserver() { Core.SetObserver(true); }
void SetLocal();
void UnlinkNetClient() { pNetClient = NULL; }
void Remove();
void CompileFunc(StdCompiler *pComp);
};
class C4ClientList
{
public:
C4ClientList();
~C4ClientList();
C4ClientList &operator = (const C4ClientList &List);
void Clear();
protected:
// client list
C4Client *pFirst;
// pointer to local client
C4Client *pLocal;
// network client list (may be NULL if network is not active)
class C4Network2ClientList *pNetClients;
void Add(C4Client *pClient);
public:
C4Client *getClient(const C4Client *pAfter = NULL) const { return pAfter ? pAfter->pNext : pFirst; }
C4Client *getLocal() const { return pLocal; }
C4Client *getClientByID(int32_t iID) const;
C4Client *getHost() const { return getClientByID(C4ClientIDHost); }
C4Client *getNextClientByID(int32_t iAfterID) const;
C4Client *getClientByName(const char *szName) const;
int32_t getClientCnt() const;
const C4ClientCore &getLocalCore() const { return getLocal()->getCore(); }
const char *getLocalName() const { return pLocal ? getLocalCore().getName() : "???"; }
int32_t getLocalID() const { return pLocal ? getLocalCore().getID() : C4ClientIDUnknown; }
bool Init(int32_t iLocalClientID = C4ClientIDHost);
void InitNetwork(class C4Network2ClientList *pNetClients);
void ClearNetwork();
bool Remove(C4Client *pClient, bool fTemporary = false);
C4Client *Add(const C4ClientCore &Core);
C4Client *AddLocal(int32_t iID, bool fActivated, bool fObserver);
void SetLocalID(int32_t iID);
void CtrlRemove(const C4Client *pClient, const char *szReason);
void RemoveRemote();
void CompileFunc(StdCompiler *pComp);
};
#endif // C4CLIENT_H

View File

@ -0,0 +1,145 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* The command stack controls an object's complex and independent behavior */
#ifndef INC_C4Command
#define INC_C4Command
#include "C4Value.h"
const int32_t C4CMD_None = 0,
C4CMD_Follow = 1,
C4CMD_MoveTo = 2,
C4CMD_Enter = 3,
C4CMD_Exit = 4,
C4CMD_Grab = 5,
C4CMD_Build = 6,
C4CMD_Throw = 7,
C4CMD_Chop = 8,
C4CMD_UnGrab = 9,
C4CMD_Jump = 10,
C4CMD_Wait = 11,
C4CMD_Get = 12,
C4CMD_Put = 13,
C4CMD_Drop = 14,
C4CMD_Dig = 15,
C4CMD_Activate = 16,
C4CMD_PushTo = 17,
C4CMD_Construct = 18,
C4CMD_Transfer = 19,
C4CMD_Attack = 20,
C4CMD_Context = 21,
C4CMD_Buy = 22,
C4CMD_Sell = 23,
C4CMD_Acquire = 24,
C4CMD_Energy = 25,
C4CMD_Retry = 26,
C4CMD_Home = 27,
C4CMD_Call = 28,
C4CMD_Take = 29, // carlo
C4CMD_Take2 = 30; // carlo
const int32_t C4CMD_First = C4CMD_Follow,
C4CMD_Last = C4CMD_Take2; // carlo
const int32_t C4CMD_Mode_SilentSub = 0, // subcommand; failure will cause base to fail (no message in case of failure)
C4CMD_Mode_Base = 1, // regular base command
C4CMD_Mode_SilentBase = 2, // silent base command (no message in case of failure)
C4CMD_Mode_Sub = 3; // subcommand; failure will cause base to fail
// MoveTo and Enter command options: Include push target
const int32_t C4CMD_MoveTo_NoPosAdjust = 1,
C4CMD_MoveTo_PushTarget = 2;
const int32_t C4CMD_Enter_PushTarget = 2;
const char *CommandName(int32_t iCommand);
const char* CommandNameID(int32_t iCommand);
int32_t CommandByName(const char *szCommand);
class C4Command
{
public:
C4Command();
~C4Command();
public:
C4Object *cObj;
int32_t Command;
C4Value Tx;
int32_t Ty;
C4Object *Target,*Target2;
int32_t Data;
int32_t UpdateInterval;
int32_t Evaluated,PathChecked,Finished;
int32_t Failures,Retries,Permit;
C4String *Text;
C4Command *Next;
int32_t iExec; // 0 = not executing, 1 = executing, 2 = executing, command should delete himself on finish
int32_t BaseMode; // 0: subcommand/unmarked base (if failing, base will fail, too); 1: base command; 2: silent base command
public:
void Set(int32_t iCommand, C4Object *pObj, C4Object *pTarget, C4Value iTx, int32_t iTy, C4Object *pTarget2, int32_t iData, int32_t iUpdateInterval, BOOL fEvaluated, int32_t iRetries, C4String *szText, int32_t iBaseMode);
void Clear();
void Execute();
void ClearPointers(C4Object *pObj);
void Default();
void EnumeratePointers();
void DenumeratePointers();
void CompileFunc(StdCompiler *pComp);
protected:
void Call();
void Home();
void Retry();
void Energy();
void Fail(const char *szFailMessage=0);
void Acquire();
void Sell();
void Buy();
void Attack();
void Transfer();
void Construct();
void Finish(BOOL fSuccess=FALSE, const char *szFailMessage=0);
void Follow();
void MoveTo();
void Enter();
void Exit();
void Grab();
void UnGrab();
void Throw();
void Chop();
void Build();
void Jump();
void Wait();
void Take();
void Take2();
bool GetTryEnter(); // at object pos during get-command: Try entering it
void Get();
void Put();
void Drop();
void Dig();
void Activate();
void PushTo();
void Context();
int32_t CallFailed();
BOOL JumpControl();
BOOL FlightControl();
BOOL InitEvaluation();
int32_t GetExpGain(); // get control counts gained by this command; 1EXP=5 ControlCounts
bool CheckMinimumCon (C4Object *pObj);
};
#endif

View File

@ -0,0 +1,60 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Holds a single text file component from a group */
#ifndef INC_C4ComponentHost
#define INC_C4ComponentHost
#include "C4GroupSet.h"
class C4ComponentHost
{
public:
C4ComponentHost();
virtual ~C4ComponentHost();
const char *GetFilePath() const { return FilePath; }
void Default();
void Clear();
void Open();
const char *GetData() { return Data.getData(); }
size_t GetDataSize() { return Data.getLength(); }
virtual void Close();
BOOL Load(const char *szName, C4Group &hGroup, const char *szFilename, const char *szLanguage=NULL);
BOOL Load(const char *szName, C4GroupSet &hGroupSet, const char *szFilename, const char *szLanguage=NULL);
BOOL LoadEx(const char *szName, C4Group &hGroup, const char *szFilename, const char *szLanguage=NULL);
BOOL LoadAppend(const char *szName, C4Group &hGroup, const char *szFilename, const char *szLanguage=NULL);
BOOL Set(const char *szData);
BOOL Save(C4Group &hGroup);
bool GetLanguageString(const char *szLanguage, class StdStrBuf &rTarget);
BOOL SetLanguageString(const char *szLanguage, const char *szString);
void TrimSpaces();
protected:
StdCopyStrBuf Data;
BOOL Modified;
char Name[_MAX_FNAME+1];
char Filename[_MAX_FNAME+1];
char FilePath[_MAX_PATH+1];
void CopyFilePathFromGroup(const C4Group &hGroup);
#ifdef _WIN32
HWND hDialog;
void InitDialog(HWND hDlg);
friend BOOL CALLBACK ComponentDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
#endif
};
#endif

View File

@ -0,0 +1,194 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Known component file names */
#ifndef INC_C4Components
#define INC_C4Components
//========================= Component File Names ============================================
#define C4CFN_Engine "Clonk.exe"
#define C4CFN_Editor "Editor.exe"
#define C4CFN_Material "Material.c4g"
#define C4CFN_Sound "Sound.c4g"
#define C4CFN_Graphics "Graphics.c4g"
#define C4CFN_System "System.c4g"
#define C4CFN_Music "Music.c4g"
#define C4CFN_Extra "Extra.c4g"
#define C4CFN_Languages "Language.c4g"
#define C4CFN_ScenarioSections "Sect*.c4g"
#define C4CFN_Objects "Objects.c4d"
#define C4CFN_Mouse "Mouse.c4f"
#define C4CFN_Keyboard "Keyboard.c4f"
#define C4CFN_Easy "Easy.c4f"
#define C4CFN_ScenarioCore "Scenario.txt"
#define C4CFN_FolderCore "Folder.txt"
#define C4CFN_PlayerInfoCore "Player.txt"
#define C4CFN_DefCore "DefCore.txt"
#define C4CFN_ObjectInfoCore "ObjectInfo.txt"
#define C4CFN_ParticleCore "Particle.txt"
#define C4CFN_LinkCore "Link.txt"
#define C4CFN_UpdateCore "AutoUpdate.txt"
#define C4CFN_UpdateEntries "GRPUP_Entries.txt"
#ifdef __x86_64
#define C4CFN_UpdateProgram "c4group64"
#else
#define C4CFN_UpdateProgram "c4group"
#endif
#define C4CFN_Map "Map.bmp"
#define C4CFN_Landscape "Landscape.bmp"
#define C4CFN_LandscapePNG "Landscape.png"
#define C4CFN_DiffLandscape "DiffLandscape.bmp"
#define C4CFN_Sky "Sky"
#define C4CFN_Script "Script.c|Script%s.c|C4Script%s.c"
#define C4CFN_ScriptStringTbl "StringTbl.txt|StringTbl%s.txt"
#define C4CFN_Info "Info.txt"
#define C4CFN_Author "Author.txt"
#define C4CFN_Version "Version.txt"
#define C4CFN_Game "Game.txt"
#define C4CFN_PXS "PXS.c4b"
#define C4CFN_MassMover "MassMover.c4b"
#define C4CFN_CtrlRec "CtrlRec.c4b"
#define C4CFN_CtrlRecText "CtrlRec.txt"
#define C4CFN_TexMap "TexMap.txt"
#define C4CFN_MatMap "MatMap.txt"
#define C4CFN_Title "Title%s.txt|Title.txt"
#define C4CFN_WriteTitle "Title.txt" // file that is generated if a title is set automatically
#define C4CFN_ScenarioTitle "Title.bmp"
#define C4CFN_ScenarioTitlePNG "Title.png"
#define C4CFN_ScenarioIcon "Icon.bmp"
#define C4CFN_IconPNG "Icon.png"
#define C4CFN_ScenarioObjects "Objects.txt"
#define C4CFN_ScenarioDesc "Desc%s.rtf"
#define C4CFN_DefGraphics "Graphics.bmp"
#define C4CFN_DefGraphicsPNG "Graphics.png"
#define C4CFN_ClrByOwnerPNG "Overlay.png"
#define C4CFN_DefGraphicsEx "Graphics*.bmp"
#define C4CFN_DefGraphicsExPNG "Graphics*.png"
#define C4CFN_DefGraphicsScaled "Graphics.*.bmp"
#define C4CFN_DefGraphicsScaledPNG "Graphics.*.png"
#define C4CFN_ClrByOwnerExPNG "Overlay*.png"
#define C4CFN_DefNames "Names%s.txt|Names.txt"
#define C4CFN_DefActMap "ActMap.txt"
#define C4CFN_DefDesc "Desc%s.txt"
#define C4CFN_BigIcon "BigIcon.png"
#define C4CFN_Portrait "Portrait.png"
#define C4CFN_PortraitOverlay "PortraitOverlay.png"
#define C4CFN_Portrait_Old "Portrait.bmp"
#define C4CFN_Portraits "Portrait*.*"
#define C4CFN_UpperBoard "UpperBoard"
#define C4CFN_Logo "Logo"
#define C4CFN_MoreMusic "MoreMusic.txt"
#define C4CFN_DynLandscape "Landscape.txt"
#define C4CFN_ClonkNames "ClonkNames%s.txt|ClonkNames.txt"
#define C4CFN_ClonkNameFiles "ClonkNames*.txt"
#define C4CFN_RankNames "Rank%s.txt|Rank.txt"
#define C4CFN_RankNameFiles "Rank*.txt"
#define C4CFN_RankFaces "Rank.bmp"
#define C4CFN_RankFacesPNG "Rank.png"
#define C4CFN_ClonkRank "Rank.png" // custom rank in info file: One rank image only
#define C4CFN_Strings "Strings.txt"
#define C4CFN_LeagueInfo "League.txt" // read by frontend only
#define C4CFN_FontDefs "Fonts.txt"
#define C4CFN_PlayerInfos "PlayerInfos.txt"
#define C4CFN_SavePlayerInfos "SavePlayerInfos.txt"
#define C4CFN_RecPlayerInfos "RecPlayerInfos.txt"
#define C4CFN_Teams "Teams.txt"
#define C4CFN_Parameters "Parameters.txt"
#define C4CFN_RoundResults "RoundResults.txt"
#define C4CFN_MapFolderData "FolderMap.txt"
#define C4CFN_MapFolderBG "FolderMap"
#define C4CFN_Language "Language*.txt"
#define C4CFN_KeyConfig "KeyConfig.txt"
#define C4CFN_Log "Clonk.log"
#define C4CFN_LogEx "Clonk%d.log" // created if regular logfile is in use
#define C4CFN_Intro "Clonk4.avi"
#define C4CFN_Names "Names.txt"
#define C4CFN_Titles "Title*.txt|Title.txt"
#define C4CFN_DefNameFiles "Names*.txt|Names.txt"
#define C4CFN_Splash "Splash.c4v"
#define C4CFN_TempMusic "~Music.tmp"
#define C4CFN_TempMusic2 "~Music2.tmp"
#define C4CFN_TempSky "~Sky.tmp"
#define C4CFN_TempMap "~Map.tmp"
#define C4CFN_TempLandscape "~Landscape.tmp"
#define C4CFN_TempLandscapePNG "~Landscape2.tmp"
#define C4CFN_TempPXS "~PXS.tmp"
#define C4CFN_TempTitle "~Title.tmp"
#define C4CFN_TempCtrlRec "~CtrlRec.tmp"
#define C4CFN_TempReSync "~ReSync.tmp"
#define C4CFN_TempPlayer "~plr.tmp"
#define C4CFN_TempRoundResults "~C4Results.tmp"
#define C4CFN_TempLeagueInfo "~league.tmp"
#define C4CFN_DefFiles "*.c4d"
#define C4CFN_PlayerFiles "*.c4p"
#define C4CFN_MaterialFiles "*.c4m"
#define C4CFN_ObjectInfoFiles "*.c4i"
#define C4CFN_MusicFiles "*.mid"
#define C4CFN_SoundFiles "*.wav|*.ogg"
#define C4CFN_PNGFiles "*.png"
#define C4CFN_BitmapFiles "*.bmp"
#define C4CFN_ScenarioFiles "*.c4s"
#define C4CFN_FolderFiles "*.c4f"
#define C4CFN_QueueFiles "*.c4q"
#define C4CFN_AnimationFiles "*.c4v"
#define C4CFN_KeyFiles "*.c4k"
#define C4CFN_ScriptFiles "*.c"
#define C4CFN_ImageFiles "*.png|*.bmp|*.jpeg|*.jpg"
#define C4CFN_FontFiles "*.fon|*.fnt|*.ttf|*.ttc|*.fot|*.otf"
//================================= File Load Sequences ================================================
// TODO: proper sorting of scaled def graphics (once we know what order we might load them in...)
#define C4FLS_Scenario "Loader*.bmp|Loader*.png|Loader*.jpeg|Loader*.jpg|Fonts.txt|Scenario.txt|Title*.txt|Info.txt|Desc*.rtf|Icon.png|Icon.bmp|Game.txt|StringTbl*.txt|Teams.txt|Parameters.txt|Info.txt|Sect*.c4g|Music.c4g|*.mid|*.wav|Desc*.rtf|Title.bmp|Title.png|*.c4d|Material.c4g|MatMap.txt|Landscape.bmp|Landscape.png|" C4CFN_DiffLandscape "|Sky.bmp|Sky.png|Sky.jpeg|Sky.jpg|PXS.c4b|MassMover.c4b|CtrlRec.c4b|Strings.txt|Objects.txt|RoundResults.txt|Author.txt|Version.txt|Names.txt|*.c4d|Script.c|Script*.c|System.c4g"
#define C4FLS_Section "Scenario.txt|Game.txt|Landscape.bmp|Landscape.png|Sky.bmp|Sky.png|Sky.jpeg|Sky.jpg|PXS.c4b|MassMover.c4b|CtrlRec.c4b|Strings.txt|Objects.txt"
#define C4FLS_SectionLandscape "Scenario.txt|Landscape.bmp|Landscape.png|PXS.c4b|MassMover.c4b"
#define C4FLS_SectionObjects "Strings.txt|Objects.txt"
#define C4FLS_Def "Particle.txt|DefCore.txt|Graphics.bmp|Graphics.png|Overlay.png|Graphics*.png|Overlay*.png|Portrait*.png|Portrait*.bmp|ActMap.txt|Script.c|Script*.c|C4Script.c|StringTbl*.txt|Names*.txt|Title*.txt|ClonkNames.txt|Rank.txt|Rank.bmp|Rank.png|Desc*.txt|Overlay.png|Title.bmp|Title.png|Icon.bmp|Author.txt|Version.txt|*.wav|*.c4d"
#define C4FLS_Player "Player.txt|Portrait.png|Portrait.bmp|*.c4i"
#define C4FLS_Object "ObjectInfo.txt|Portrait.png|Portrait.bmp"
#define C4FLS_Folder "Folder.txt|Title*.txt|Info.txt|Desc*.rtf|Title.png|Title.bmp|Icon.png|Icon.bmp|Author.txt|Version.txt|*.c4s|Loader*.bmp|Loader*.png|Loader*.jpeg|Loader*.jpg|FolderMap.txt|FolderMap.png"
#define C4FLS_Material "TexMap.txt|*.bmp|*.png|*.c4m"
#define C4FLS_Graphics "Loader*.bmp|Loader*.png|Loader*.jpeg|Loader*.jpg|FontEndeavour12.png|FontEndeavour24.png|FontEndeavour16.png|FontEndeavour10.png|Font*.png"\
"|*.pal|Control.png|Fire.png|Background.png|Flag.png|Crew.png|Score.png|Wealth.png|Player.png|Rank.png|Entry.png|Captain.png|Cursor.png|CursorSmall.png|CursorMedium.png|CursorLarge.png|SelectMark.png|MenuSymbol.png|Menu.png|Logo.png|Construction.png|Energy.png|Magic.png|Options.png|UpperBoard.png|Arrow.png|Exit.png|Hand.png|Gamepad.png|Build.png|EnergyBars.png|Liquid.png"\
"|GUICaption.png|GUIButton.png|GUIButtonDown.png|GUIButtonHighlight.png|GUIIcons.png|GUIIcons2.png|GUIScroll.png|GUIContext.png|GUISubmenu.png|GUICheckBox.png|GUIBigArrows.png|GUIProgress.png"\
"|StartupScenSelBG.*|StartupPlrSelBG.*|StartupPlrPropBG.*|StartupNetworkBG.*|StartupAboutBG.*|StartupBigButton.png|StartupBigButtonDown.png|StartupBookScroll.png|StartupContext.png|StartupScenSelIcons.png|StartupScenSelTitleOv.png|StartupPlrCtrlType.png|StartupDlgPaper.png|StartupOptionIcons.png|StartupTabClip.png|StartupNetGetRef.png"
#define C4FLS_Objects "Names*.txt|Desc*.txt|*.c4d"
#define C4FLS_Mouse "*.txt|*.rtf|Title.bmp|Title.png|Icon.bmp|Tutorial01.c4s|Tutorial02.c4s|Tutorial03.c4s|Objects.c4d"
#define C4FLS_Keyboard "*.txt|*.rtf|Title.bmp|Title.png|Icon.bmp|Tutorial01.c4s|Tutorial02.c4s|Tutorial03.c4s|Tutorial04.c4s|Tutorial05.c4s|Tutorial06.c4s|Tutorial07.c4s|Tutorial08.c4s|Tutorial09.c4s|Tutorial10.c4s"
#define C4FLS_Easy "*.txt|*.rtf|Title.bmp|Title.png|Icon.bmp|Goldmine.c4s|Monsterkill.c4s|Economy.c4s|Melee.c4s|Lake.c4s|Castle.c4s"
#define C4FLS_System "*.hlp|*.cnt|Language*.txt|*.fon|*.fnt|*.ttf|*.ttc|*.fot|*.otf|Fonts.txt|Alchem.c|StringTbl*.txt|*.c|Names.txt"
#define C4FLS_Music "Frontend.*|Credits.*"
// western foldermap hardcoded...
#define C4FLS_Western C4FLS_Folder "|ScenGCBase.png|ScenGC.png|ScenDMVBase.png|ScenDMV.png|ScenFSBase.png|ScenFS.png|ScenCTFBase.png|ScenCTF.png|ScenLHBase.png|ScenLH.png|ScenMCBase.png|ScenMC.png|ScenMWBase.png|ScenMW.png|ScenBRBase.png|ScenBR.png|ScenTHBase.png|ScenTH.png|ScenGRBase.png|ScenGR.png|ScenSTSBase.png|ScenSTS.png|ScenNWBase.png|ScenNW.png|AccLH.png|AccFS.png|AccGC.png|AccGR.png|AccMW.png|AccNW.png"
#endif

View File

@ -0,0 +1,348 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Game configuration as stored in registry */
#ifndef INC_C4Config
#define INC_C4Config
#include "C4Constants.h"
#include "C4InputValidation.h"
#include <list>
const char *CfgAtTempPath(const char *szFilename);
class C4ConfigGeneral
{
public:
enum { ConfigResetSafetyVal = 42 };
char Name[CFG_MaxString+1];
char Language[CFG_MaxString+1]; // entered by user in frontend options (may contain comma separated list or long language descriptions)
char LanguageEx[CFG_MaxString+1]; // full fallback list composed by frontend options (condensed comma separated list)
char Definitions[CFG_MaxString+1];
char Participants[CFG_MaxString+1];
int32_t AlwaysDebug; // if set: turns on debugmode whenever engine is started
char RXFontName[CFG_MaxString+1];
int32_t RXFontSize;
char ConfigUserPath[CFG_MaxString + 1];
StdStrBuf SaveGameFolder;
StdStrBuf SaveDemoFolder;
StdStrBuf ScreenshotFolder;
char MissionAccess[CFG_MaxString+1];
char UpdateEngine[CFG_MaxString+1];
char UpdateObjects[CFG_MaxString+1];
char UpdateMajor[CFG_MaxString+1];
int32_t FPS;
int32_t Record;
int32_t DefRec;
int32_t MMTimer; // use multimedia-timers
int32_t FairCrew; // don't use permanent crew physicals
int32_t FairCrewStrength, MaxFairCrewStrength; // strength of clonks in fair crew mode
int32_t MouseAScroll; // auto scroll strength
int32_t ScrollSmooth; // view movement smoothing
int32_t ConfigResetSafety; // safety value: If this value is screwed, the config got currupted and must be reset
// Determined at run-time
char ExePath[CFG_MaxString+1];
char TempPath[CFG_MaxString+1];
char UserDataPath[CFG_MaxString+1];
char SystemDataPath[CFG_MaxString+1];
char ScreenshotPath[CFG_MaxString+1];
char BetaCode[CFG_MaxString+1];
bool GamepadEnabled;
bool FirstStart;
bool UserPortraitsWritten; // set when default portraits have been copied to the UserPath (this is only done once)
// Additional paths to read data from (prioritized lower than UserDataPath/SystemDataPath)
typedef std::list<const char *> PathList;
PathList AdditionalDataPaths;
public:
static int GetLanguageSequence(const char *strSource, char *strTarget);
void DefaultLanguage();
BOOL CreateSaveFolder(const char *strDirectory, const char *strLanguageTitle);
void AdoptOldSettings();
void DeterminePaths(BOOL forceWorkingDirectory);
void CompileFunc(StdCompiler *pComp);
bool IsUTF8() { return SEqual(LoadResStr("IDS_LANG_CHARSET"), "UTF-8"); }
void AddAdditionalDataPath(const char *szPath);
void ClearAdditionalDataPaths();
~C4ConfigGeneral() { ClearAdditionalDataPaths(); }
private:
struct
{
char PlayerPath[CFG_MaxString+1];
} Adopt;
};
class C4ConfigDeveloper
{
public:
int32_t AutoFileReload;
#ifdef _WIN32
int32_t AutoEditScan;
#endif
int32_t AllErrorsFatal;
void CompileFunc(StdCompiler *pComp);
};
class C4ConfigGraphics
{
public:
int32_t SplitscreenDividers;
int32_t ShowPlayerInfoAlways;
int32_t ShowCommands;
int32_t ShowCommandKeys;
int32_t ShowPortraits;
int32_t AddNewCrewPortraits;
int32_t SaveDefaultPortraits;
int32_t ShowStartupMessages;
int32_t VerboseObjectLoading;
int32_t ColorAnimation;
int32_t SmokeLevel;
int32_t VideoModule;
int32_t MenuTransparency;
int32_t UpperBoard;
int32_t ShowClock;
int32_t ResX,ResY;
int32_t GuiResX,GuiResY;
int32_t ShowAllResolutions;
int32_t ShowCrewNames; // show player name above clonks?
int32_t ShowCrewCNames; // show clonk names above clonks?
int32_t BitDepth; // used bit depth for newgfx
int32_t NewGfxCfg; // some configuration settings for newgfx
int32_t NewGfxCfgGL; // some configuration settings for newgfx (OpenGL)
int32_t MsgBoard;
int32_t MsgBrdFadeDelay;
int32_t PXSGfx; // show PXS-graphics (instead of sole pixels)
int32_t Engine; // 0: D3D; 1: OpenGL;
int32_t BlitOff; // blit offset (percent)
int32_t BlitOffGL; // blit offset (percent) (OpenGL)
int32_t Gamma1, Gamma2, Gamma3; // gamma ramps
int32_t Currency; // default wealth symbolseb
int32_t RenderInactiveEM; // draw vieports even if inactive in CPEM
int32_t DisableGamma;
int32_t Monitor; // monitor index to play on
int32_t FireParticles; // draw extended fire particles if enabled (defualt on)
int32_t MaxRefreshDelay; // minimum time after which graphics should be refreshed (ms)
void CompileFunc(StdCompiler *pComp);
};
class C4ConfigSound
{
public:
int32_t RXSound;
int32_t RXMusic;
int32_t FEMusic;
int32_t FESamples;
int32_t FMMode;
int32_t Verbose; // show music files names
int32_t MusicVolume;
int32_t SoundVolume;
void CompileFunc(StdCompiler *pComp);
};
class C4ConfigNetwork
{
public:
int32_t ControlRate;
int32_t ControlPreSend;
int32_t Lobby;
int32_t NoRuntimeJoin;
int32_t NoReferenceRequest;
int32_t MaxResSearchRecursion;
char WorkPath[CFG_MaxString+1];
ValidatedStdCopyStrBuf<C4InVal::VAL_Comment> Comment;
int32_t MasterServerSignUp;
int32_t MasterServerActive;
int32_t MasterKeepPeriod;
int32_t MasterReferencePeriod;
int32_t LeagueServerSignUp;
int32_t UseAlternateServer;
int32_t SendPortraits;
int32_t PortTCP,PortUDP,PortDiscovery,PortRefServer;
int32_t ControlMode;
ValidatedStdCopyStrBuf<C4InVal::VAL_NameNoEmpty> LocalName;
ValidatedStdCopyStrBuf<C4InVal::VAL_NameAllowEmpty> Nick;
int32_t MaxLoadFileSize;
char LastPassword[CFG_MaxString+1];
char AlternateServerAddress[CFG_MaxString+1];
char UpdateServerAddress[CFG_MaxString+1];
char PuncherAddress[CFG_MaxString+1];
int32_t AutomaticUpdate;
int32_t LastUpdateTime;
int32_t AsyncMaxWait;
public:
void CompileFunc(StdCompiler *pComp);
const char *GetLeagueServerAddress();
};
class C4ConfigStartup
{
public:
// config for do-not-show-this-msg-again-messages
int32_t HideMsgGfxEngineChange;
int32_t HideMsgGfxBitDepthChange;
int32_t HideMsgMMTimerChange;
int32_t HideMsgStartDedicated;
int32_t HideMsgPlrTakeOver;
int32_t HideMsgPlrNoTakeOver;
int32_t HideMsgNoOfficialLeague;
int32_t HideMsgIRCDangerous;
int32_t NoSplash;
int32_t AlphabeticalSorting; // if set, Folder.txt-sorting is ignored in scenario selection
int32_t LastPortraitFolderIdx;
void CompileFunc(StdCompiler *pComp);
};
class C4ConfigLobby
{
public:
int32_t CountdownTime;
int32_t AllowPlayerSave; // whether save-to-disk function is enabled for player ressources
void CompileFunc(StdCompiler *pComp);
};
class C4ConfigIRC
{
public:
char Server[CFG_MaxString+1];
char Nick[CFG_MaxString+1];
char RealName[CFG_MaxString+1];
char Channel[CFG_MaxString+1];
void CompileFunc(StdCompiler *pComp);
int32_t AllowAllChannels;
};
class C4ConfigExplorer
{
public:
int32_t Mode;
int32_t Run;
char Definitions[CFG_MaxString+1];
char Engines[CFG_MaxString+1];
char EditorBitmap[CFG_MaxString+1];
char EditorPNG[CFG_MaxString+1];
char EditorMusic[CFG_MaxString+1];
char EditorRichText[CFG_MaxString+1];
char EditorScript[CFG_MaxString+1];
char EditorText[CFG_MaxString+1];
char EditorSound[CFG_MaxString+1];
char EditorZip[CFG_MaxString+1];
char EditorDefinition[CFG_MaxString+1];
char EditorHtml[CFG_MaxString+1];
char CommandLine[CFG_MaxString+1];
int32_t EditorUseShell;
int32_t Kindersicherung;
int32_t DontShowLanguageDisclaimer;
int32_t IDListSortColumn;
int32_t IDListViewMode;
int32_t LicenseAccepted;
char Reload[CFG_MaxString+1];
public:
void CompileFunc(StdCompiler *pComp);
};
const int C4ConfigMaxGamepads = 4;
class C4ConfigGamepad
{
public:
int32_t Button[C4MaxKey];
uint32_t AxisMin[6], AxisMax[6];
bool AxisCalibrated[6];
void CompileFunc(StdCompiler *pComp, bool fButtonsOnly=false);
void ResetButtons(); // reset all buttons to default
void Reset(); // reset all buttons and axis calibration to default
};
class C4ConfigControls
{
public:
int32_t GamepadGuiControl;
int32_t MouseAScroll; // auto scroll strength
int32_t Keyboard[C4MaxKeyboardSet][C4MaxKey];
void CompileFunc(StdCompiler *pComp, bool fKeysOnly=false);
void ResetKeys(); // reset all keys to default
};
class C4ConfigSecurity
{
public:
char KeyPath[CFG_MaxString + 1]; // absolute path; environment variables are stored and only expanded upon evaluation
int32_t WasRegistered;
void CompileFunc(StdCompiler *pComp);
};
class C4Config: protected CStdConfig
{
public:
C4Config();
~C4Config();
public:
C4ConfigGeneral General;
C4ConfigDeveloper Developer;
C4ConfigGraphics Graphics;
C4ConfigSound Sound;
C4ConfigNetwork Network;
C4ConfigLobby Lobby;
C4ConfigIRC IRC;
C4ConfigExplorer Explorer;
C4ConfigGamepad Gamepads[C4ConfigMaxGamepads];
C4ConfigControls Controls;
C4ConfigStartup Startup;
C4ConfigSecurity Security;
bool fConfigLoaded; // true if config has been successfully loaded
StdStrBuf ConfigFilename; // set for configs loaded from a nondefault config file
public:
const char* GetSubkeyPath(const char *strSubkey);
void Default();
BOOL Save();
BOOL Load(BOOL forceWorkingDirectory = TRUE, const char *szConfigFile = NULL);
BOOL Init();
BOOL Registered();
BOOL IsFreeFolder(const char *szFoldername, const char *szMaker);
const char *AtExePath(const char *szFilename);
const char *AtTempPath(const char *szFilename);
const char *AtNetworkPath(const char *szFilename);
const char *AtScreenshotPath(const char *szFilename);
const char *AtUserDataPath(const char *szFilename);
const char *AtUserDataRelativePath(const char *szFilename);
const char *AtSystemDataPath(const char *szFilename);
const char *AtSystemDataRelativePath(const char *szFilename);
const char *AtRelativePath(const char *szFilename); // Returns ASDRP or AUDRP depending on location
const char *AtDataReadPath(const char *szFilename, bool fPreferWorkdir = false);
const char *GetRegistrationData(const char* strField) { return ""; }
void ForceRelativePath(StdStrBuf *sFilename); // try AtRelativePath; force GetC4Filename if not possible
void CompileFunc(StdCompiler *pComp);
bool IsCorrupted() { return (General.ConfigResetSafety != C4ConfigGeneral::ConfigResetSafetyVal) || !Graphics.ResX; }
bool RemoveModule(const char *szPath, char *szModules);
bool IsModule(const char *szPath, char *szModules);
bool AddModule(const char *szPath, char *szModules);
static void ExpandEnvironmentVariables(char *strPath, int iMaxLen);
private:
const char *AtDataReadPathCore(const char *szFilename, bool fPreferWorkdir = false);
};
#ifndef BIG_C4INCLUDE
#include <C4ConfigShareware.h>
#endif
extern C4Config *pConfig; // Some cheap temporary hack to get to config in Engine + Frontend...
// This is so good - we can use it everywear!!!!
#endif // INC_C4Config

View File

@ -0,0 +1,231 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Handles engine execution in developer mode */
#ifndef INC_C4Console
#define INC_C4Console
#include "C4PropertyDlg.h"
#include "C4ToolsDlg.h"
#include "C4ObjectListDlg.h"
#include "C4EditCursor.h"
#include "C4Game.h"
#include <StdWindow.h>
#ifdef WITH_DEVELOPER_MODE
# include <gtk/gtkwidget.h>
#endif
const int C4CNS_ModePlay = 0,
C4CNS_ModeEdit = 1,
C4CNS_ModeDraw = 2;
#define IDM_NET_CLIENT1 10000
#define IDM_NET_CLIENT2 10100
#define IDM_PLAYER_QUIT1 10200
#define IDM_PLAYER_QUIT2 10300
#define IDM_VIEWPORT_NEW1 10400
#define IDM_VIEWPORT_NEW2 10500
#ifdef WITH_DEVELOPER_MODE
#include <StdGtkWindow.h>
typedef CStdGtkWindow C4ConsoleBase;
#else
typedef CStdWindow C4ConsoleBase;
#endif
class C4Console: public C4ConsoleBase
{
public:
C4Console();
virtual ~C4Console();
BOOL Editing;
C4PropertyDlg PropertyDlg;
C4ToolsDlg ToolsDlg;
C4ObjectListDlg ObjectListDlg;
C4EditCursor EditCursor;
void Default();
virtual void Clear();
virtual void Close();
virtual CStdWindow * Init(CStdApp * app);
void Execute();
void ClearPointers(C4Object *pObj);
bool Message(const char *szMessage, bool fQuery=FALSE);
void SetCaption(const char *szCaption);
bool In(const char *szText);
bool Out(const char *szText);
bool ClearLog(); // empty log text
void DoPlay();
void DoHalt();
bool UpdateCursorBar(const char *szCursor);
bool UpdateHaltCtrls(bool fHalt);
bool UpdateModeCtrls(int iMode);
void UpdateInputCtrl();
void UpdateMenus();
bool OpenGame(const char * szCmdLine = 0);
bool TogglePause(); // key callpack: pause
protected:
bool CloseGame();
bool fGameOpen;
void EnableControls(bool fEnable);
bool UpdatePlayerMenu();
bool UpdateViewportMenu();
bool UpdateStatusBars();
// Menu
void ClearPlayerMenu();
void ClearViewportMenu();
void UpdateNetMenu();
void ClearNetMenu();
void PlayerJoin();
void EditObjects();
void EditInfo();
void EditScript();
void EditTitle();
void ViewportNew();
void HelpAbout();
BOOL FileSelect(char *sFilename, int iSize, const char *szFilter, DWORD dwFlags, BOOL fSave=FALSE);
BOOL SaveGame(BOOL fSaveGame);
BOOL FileSaveAs(BOOL fSaveGame);
BOOL FileSave(BOOL fSaveGame);
BOOL FileOpen();
BOOL FileOpenWPlrs();
BOOL FileCommand();
BOOL FileClose();
BOOL FileQuit();
BOOL FileRecord();
int ScriptCounter;
int FrameCounter;
int Time,FPS;
int MenuIndexFile;
int MenuIndexComponents;
int MenuIndexPlayer;
int MenuIndexViewport;
int MenuIndexNet;
int MenuIndexHelp;
#ifdef _WIN32
void UpdateMenuText(HMENU hMenu);
BOOL AddMenuItem(HMENU hMenu, DWORD dwID, const char *szString, BOOL fEnabled=TRUE);
BOOL RegisterConsoleWindowClass(HINSTANCE hInst);
virtual bool Win32DialogMessageHandling(MSG * msg)
{
return (hWindow && IsDialogMessage(hWindow,msg)) || (PropertyDlg.hDialog && IsDialogMessage(PropertyDlg.hDialog,msg));
};
HBITMAP hbmMouse;
HBITMAP hbmMouse2;
HBITMAP hbmCursor;
HBITMAP hbmCursor2;
HBITMAP hbmBrush;
HBITMAP hbmBrush2;
HBITMAP hbmPlay;
HBITMAP hbmPlay2;
HBITMAP hbmHalt;
HBITMAP hbmHalt2;
friend BOOL CALLBACK ConsoleDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
#elif defined(WITH_DEVELOPER_MODE)
virtual GtkWidget* InitGUI();
GdkCursor* cursorDefault;
GdkCursor* cursorWait;
GtkWidget* txtLog;
GtkWidget* txtScript;
GtkWidget* btnPlay;
GtkWidget* btnHalt;
GtkWidget* btnModePlay;
GtkWidget* btnModeEdit;
GtkWidget* btnModeDraw;
GtkWidget* menuBar;
GtkWidget* itemNet;
GtkWidget* menuViewport;
GtkWidget* menuPlayer;
GtkWidget* fileOpen;
GtkWidget* fileOpenWithPlayers;
GtkWidget* fileSave;
GtkWidget* fileSaveAs;
GtkWidget* fileSaveGame;
GtkWidget* fileSaveGameAs;
GtkWidget* fileRecord;
GtkWidget* fileClose;
GtkWidget* fileQuit;
GtkWidget* compScript;
GtkWidget* compTitle;
GtkWidget* compInfo;
GtkWidget* compObjects;
GtkWidget* plrJoin;
GtkWidget* viewNew;
GtkWidget* helpAbout;
GtkWidget* lblCursor;
GtkWidget* lblFrame;
GtkWidget* lblScript;
GtkWidget* lblTime;
gulong handlerPlay;
gulong handlerHalt;
gulong handlerModePlay;
gulong handlerModeEdit;
gulong handlerModeDraw;
static void OnScriptEntry(GtkWidget* entry, gpointer data);
static void OnPlay(GtkWidget* button, gpointer data);
static void OnHalt(GtkWidget* button, gpointer data);
static void OnModePlay(GtkWidget* button, gpointer data);
static void OnModeEdit(GtkWidget* button, gpointer data);
static void OnModeDraw(GtkWidget* button, gpointer data);
static void OnFileOpen(GtkWidget* item, gpointer data);
static void OnFileOpenWPlrs(GtkWidget* item, gpointer data);
static void OnFileSave(GtkWidget* item, gpointer data);
static void OnFileSaveAs(GtkWidget* item, gpointer data);
static void OnFileSaveGame(GtkWidget* item, gpointer data);
static void OnFileSaveGameAs(GtkWidget* item, gpointer data);
static void OnFileRecord(GtkWidget* item, gpointer data);
static void OnFileClose(GtkWidget* item, gpointer data);
static void OnFileQuit(GtkWidget* item, gpointer data);
static void OnCompObjects(GtkWidget* item, gpointer data);
static void OnCompScript(GtkWidget* item, gpointer data);
static void OnCompTitle(GtkWidget* item, gpointer data);
static void OnCompInfo(GtkWidget* item, gpointer data);
static void OnPlrJoin(GtkWidget* item, gpointer data);
static void OnPlrQuit(GtkWidget* item, gpointer data);
static void OnViewNew(GtkWidget* item, gpointer data);
static void OnViewNewPlr(GtkWidget* item, gpointer data);
static void OnHelpAbout(GtkWidget* item, gpointer data);
static void OnNetClient(GtkWidget* item, gpointer data);
#elif defined(USE_X11) && !defined(WITH_DEVELOPER_MODE)
virtual void HandleMessage (XEvent &);
#endif
};
#define C4ConsoleWindowClassname "C4Console"
extern C4Console Console;
#endif

View File

@ -0,0 +1,310 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Lots of constants */
#ifndef INC_C4Constants
#define INC_C4Constants
//============================= Main =====================================================
const int C4MaxNameList = 10,
C4MaxName = 30, // player names, etc.
C4MaxLongName = 120, // scenario titles, etc. - may include markup
C4MaxComment = 256, // network game and player comments
C4MaxDefString = 100,
C4MaxTitle = 512,
C4MaxMessage = 256,
C4MaxServerName = 255,
C4MaxVariable = 10,
C4ViewDelay = 100,
C4RetireDelay = 60,
C4MaxColor = 12,
C4MaxKey = 12,
C4MaxKeyboardSet = 4,
C4MaxControlSet = C4MaxKeyboardSet+4, // keyboard sets+gamepads
C4MaxControlRate = 20,
C4MaxGammaUserRamps = 8,
C4MaxGammaRamps = C4MaxGammaUserRamps+1;
// gamma ramp indices
#define C4GRI_SCENARIO 0
#define C4GRI_SEASON 1
#define C4GRI_RESERVED1 2
#define C4GRI_DAYTIME 3
#define C4GRI_RESERVED2 4
#define C4GRI_LIGHTNING 5
#define C4GRI_MAGIC 6
#define C4GRI_RESERVED3 7
#define C4GRI_USER 8
const int C4M_MaxName = 15,
C4M_MaxDefName = 2*C4M_MaxName+1,
C4M_ColsPerMat = 3,
C4M_MaxTexIndex = 127; // last texture map index is reserved for diff
const int C4S_MaxPlayer = 4;
const int C4D_MaxName = C4MaxName,
C4D_MaxVertex = 30,
C4D_MaxIDLen = C4D_MaxName;
const int C4Px_MaxName = C4MaxName,// maximum length of a particle def name
C4Px_MaxParticle= 256, // maximum number of particles of one type
C4Px_BufSize = 128, // number of particles in one buffer
C4Px_MaxIDLen = 30; // maximum length of internal identifiers
const int C4SymbolSize = 35,
C4SymbolBorder = 5,
C4UpperBoardHeight = 50,
C4PictureSize = 64,
C4MaxPictureSize = 150,
C4MaxBigIconSize = 64;
const int C4P_MaxPosition = 4;
const int C4P_Control_None = -1,
C4P_Control_Keyboard1 = 0,
C4P_Control_Keyboard2 = 1,
C4P_Control_Keyboard3 = 2,
C4P_Control_Keyboard4 = 3,
C4P_Control_GamePad1 = 4,
C4P_Control_GamePad2 = 5,
C4P_Control_GamePad3 = 6,
C4P_Control_GamePad4 = 7,
C4P_Control_GamePadMax = C4P_Control_GamePad4;
const int C4ViewportScrollBorder = 40; // scrolling past landscape allowed at range of this border
//============================= Engine Return Values ======================================
const int C4XRV_Completed = 0,
C4XRV_Failure = 1,
C4XRV_Aborted = 2;
//============================= Object Character Flags ====================================
const uint32_t OCF_None=0,
OCF_All=~OCF_None,
OCF_Normal=1,
OCF_Construct=1<<1,
OCF_Grab=1<<2,
OCF_Carryable=1<<3,
OCF_OnFire=1<<4,
OCF_HitSpeed1=1<<5,
OCF_FullCon=1<<6,
OCF_Inflammable=1<<7,
OCF_Chop=1<<8,
OCF_Rotate=1<<9,
OCF_Exclusive=1<<10,
OCF_Entrance=1<<11,
OCF_HitSpeed2=1<<12,
OCF_HitSpeed3=1<<13,
OCF_Collection=1<<14,
OCF_Living=1<<15,
OCF_HitSpeed4=1<<16,
OCF_FightReady=1<<17,
OCF_LineConstruct=1<<18,
OCF_Prey=1<<19,
OCF_AttractLightning=1<<20,
OCF_NotContained=1<<21,
OCF_CrewMember=1<<22,
OCF_Edible=1<<23,
OCF_InLiquid=1<<24,
OCF_InSolid=1<<25,
OCF_InFree=1<<26,
OCF_Available=1<<27,
OCF_PowerConsumer=1<<28,
OCF_PowerSupply=1<<29,
OCF_Container=1<<30,
OCF_Alive=1<<31;
//================================== Contact / Attachment ==============================================
const BYTE // Directional
CNAT_None = 0,
CNAT_Left = 1,
CNAT_Right = 2,
CNAT_Top = 4,
CNAT_Bottom = 8,
CNAT_Center = 16,
// Additional flags
CNAT_MultiAttach = 32, // new attachment behaviour; see C4Shape::Attach
CNAT_NoCollision = 64; // turn off collision for this vertex
const BYTE CNAT_Flags = CNAT_MultiAttach | CNAT_NoCollision; // all attchment flags that can be combined with regular attachment
//=============================== Keyboard Input Controls =====================================================
const int C4DoubleClick = 10;
const int CON_CursorLeft = 0,
CON_CursorToggle = 1,
CON_CursorRight = 2,
CON_Throw = 3,
CON_Up = 4,
CON_Dig = 5,
CON_Left = 6,
CON_Down = 7,
CON_Right = 8,
CON_Menu = 9,
CON_Special = 10,
CON_Special2 = 11;
//=================================== Control Commands ======================================================
const BYTE COM_Single = 64,
COM_Double = 128;
const BYTE COM_None = 0;
const BYTE COM_Left = 1,
COM_Right = 2,
COM_Up = 3,
COM_Down = 4,
COM_Throw = 5,
COM_Dig = 6,
COM_Special = 7,
COM_Special2 = 8,
COM_Contents = 9,
COM_WheelUp = 10,
COM_WheelDown= 11,
COM_Left_R = COM_Left + 16,
COM_Right_R = COM_Right + 16,
COM_Up_R = COM_Up + 16,
COM_Down_R = COM_Down + 16,
COM_Throw_R = COM_Throw + 16,
COM_Dig_R = COM_Dig + 16,
COM_Special_R = COM_Special + 16,
COM_Special2_R = COM_Special2 + 16,
COM_ReleaseFirst = COM_Left_R,
COM_ReleaseLast = COM_Special2_R,
COM_Left_S = COM_Left | COM_Single,
COM_Right_S = COM_Right | COM_Single,
COM_Up_S = COM_Up | COM_Single,
COM_Down_S = COM_Down | COM_Single,
COM_Throw_S = COM_Throw | COM_Single,
COM_Dig_S = COM_Dig | COM_Single,
COM_Special_S = COM_Special | COM_Single,
COM_Special2_S = COM_Special2 | COM_Single,
COM_Left_D = COM_Left | COM_Double,
COM_Right_D = COM_Right | COM_Double,
COM_Up_D = COM_Up | COM_Double,
COM_Down_D = COM_Down | COM_Double,
COM_Throw_D = COM_Throw | COM_Double,
COM_Dig_D = COM_Dig | COM_Double,
COM_Special_D = COM_Special | COM_Double,
COM_Special2_D = COM_Special2 | COM_Double;
const BYTE COM_CursorLeft = 30,
COM_CursorRight = 31,
COM_CursorToggle = 32;
const BYTE COM_CursorToggle_D = COM_CursorToggle | COM_Double;
const BYTE COM_Help = 35,
COM_PlayerMenu = 36,
COM_Chat = 37;
const BYTE COM_MenuEnter = 38,
COM_MenuEnterAll = 39,
COM_MenuClose = 40,
COM_MenuShowText = 42,
COM_MenuLeft = 52,
COM_MenuRight = 53,
COM_MenuUp = 54,
COM_MenuDown = 55,
COM_MenuSelect = 60,
COM_MenuFirst = COM_MenuEnter,
COM_MenuLast = COM_MenuSelect,
COM_MenuNavigation1 = COM_MenuShowText,
COM_MenuNavigation2 = COM_MenuSelect;
//=================================== SendCommand ========================================
const int32_t C4P_Command_None = 0,
C4P_Command_Set = 1,
C4P_Command_Add = 2,
C4P_Command_Append = 4,
C4P_Command_Range = 8;
extern char OSTR[500];
//=================================== Owners ==============================================
const int NO_OWNER = -1,
ANY_OWNER = -2,
BY_OWNER = 10000,
BY_HOSTILE_OWNER = 20000;
//=================================== Base functionalities =================================
const int BASE_RegenerateEnergyPrice = 5,
BASEFUNC_Default = 0xffff,
BASEFUNC_AutoSellContents = 1<<0,
BASEFUNC_RegenerateEnergy = 1<<1,
BASEFUNC_Buy = 1<<2,
BASEFUNC_Sell = 1<<3,
BASEFUNC_RejectEntrance = 1<<4,
BASEFUNC_Extinguish = 1<<5;
//=================================== League (escape those damn circular includes =========
enum C4LeagueDisconnectReason
{
C4LDR_Unknown,
C4LDR_ConnectionFailed,
C4LDR_Desync,
};
//=================================== Player (included by C4PlayerInfo and C4Player)
enum C4PlayerType
{
C4PT_None=0,
C4PT_User=1, // Normal player
C4PT_Script=2, // AI players, etc.
};
//=================================== AllowPictureStack (DefCore value)
enum C4AllowPictureStack
{
APS_Color= 1<<0,
APS_Graphics=1<<1,
APS_Name= 1<<2,
APS_Overlay= 1<<3,
};
// Object size
const int32_t FullCon=100000;
#endif // INC_C4Constants

View File

@ -0,0 +1,469 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Control packets contain all player input in the message queue */
#ifndef INC_C4Control
#define INC_C4Control
#include "C4Id.h"
#include "C4PacketBase.h"
#include "C4PlayerInfo.h"
#include "C4Client.h"
// *** control base classes
class C4ControlPacket : public C4PacketBase
{
public:
C4ControlPacket();
~C4ControlPacket();
protected:
int32_t iByClient;
public:
int32_t getByClient() const { return iByClient; }
bool LocalControl() const;
bool HostControl() const { return iByClient == C4ClientIDHost; }
void SetByClient(int32_t iByClient);
virtual bool PreExecute() const { return true; }
virtual void Execute() const = 0;
virtual void PreRec(C4Record *pRecord) { }
// allowed in lobby (without dynamic loaded)?
virtual bool Lobby() const { return false; }
// allowed as direct/private control?
virtual bool Sync() const { return true; }
virtual void CompileFunc(StdCompiler *pComp);
};
#define DECLARE_C4CONTROL_VIRTUALS \
virtual void Execute() const; \
virtual void CompileFunc(StdCompiler *pComp);
class C4Control : public C4PacketBase
{
public:
C4Control();
~C4Control();
protected:
C4PacketList Pkts;
public:
void Clear();
// packet list wrappers
C4IDPacket *firstPkt() const { return Pkts.firstPkt(); }
C4IDPacket *nextPkt(C4IDPacket *pPkt) const { return Pkts.nextPkt(pPkt); }
void AddHead(C4PacketType eType, C4ControlPacket *pCtrl) { Pkts.AddHead(eType, pCtrl); }
void Add(C4PacketType eType, C4ControlPacket *pCtrl) { Pkts.Add(eType, pCtrl); }
void Take(C4Control &Ctrl) { Pkts.Take(Ctrl.Pkts); }
void Append(const C4Control &Ctrl) { Pkts.Append(Ctrl.Pkts); }
void Copy(const C4Control &Ctrl) { Clear(); Pkts.Append(Ctrl.Pkts); }
void Remove(C4IDPacket *pPkt) { Pkts.Remove(pPkt); }
void Delete(C4IDPacket *pPkt) { Pkts.Delete(pPkt); }
// control execution
bool PreExecute() const;
void Execute() const;
void PreRec(C4Record *pRecord) const;
virtual void CompileFunc(StdCompiler *pComp);
};
// *** control packets
enum C4CtrlValueType
{
C4CVT_None = -1,
C4CVT_ControlRate = 0,
C4CVT_AllowDebug = 1,
C4CVT_MaxPlayer = 2,
C4CVT_TeamDistribution = 3,
C4CVT_TeamColors = 4,
C4CVT_FairCrew = 5,
};
class C4ControlSet : public C4ControlPacket // sync, lobby
{
public:
C4ControlSet()
: eValType(C4CVT_None), iData(0)
{ }
C4ControlSet(C4CtrlValueType eValType, int32_t iData)
: eValType(eValType), iData(iData)
{ }
protected:
C4CtrlValueType eValType;
int32_t iData;
public:
// C4CVT_TeamDistribution and C4CVT_TeamColors are lobby-packets
virtual bool Lobby() const { return eValType == C4CVT_TeamDistribution || eValType == C4CVT_TeamColors; }
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlScript : public C4ControlPacket // sync
{
public:
enum { SCOPE_Console=-2, SCOPE_Global=-1, }; // special scopes to be passed as target objects
C4ControlScript()
: iTargetObj(-1), fInternal(true)
{ }
C4ControlScript(const char *szScript, int32_t iTargetObj = SCOPE_Global, bool fInternal = true)
: iTargetObj(iTargetObj), fInternal(fInternal), Script(szScript, true)
{ }
protected:
int32_t iTargetObj;
bool fInternal; // silent execute
StdStrBuf Script;
public:
void SetTargetObj(int32_t iObj) { iTargetObj = iObj; }
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlPlayerSelect : public C4ControlPacket // sync
{
public:
C4ControlPlayerSelect()
: iPlr(-1), iObjCnt(0), pObjNrs(NULL) { }
C4ControlPlayerSelect(int32_t iPlr, const C4ObjectList &Objs);
~C4ControlPlayerSelect() { delete[] pObjNrs; }
protected:
int32_t iPlr;
int32_t iObjCnt;
int32_t *pObjNrs;
public:
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlPlayerControl : public C4ControlPacket // sync
{
public:
C4ControlPlayerControl()
: iPlr(-1), iCom(-1), iData(-1) { }
C4ControlPlayerControl(int32_t iPlr, int32_t iCom, int32_t iData)
: iPlr(iPlr), iCom(iCom), iData(iData) { }
protected:
int32_t iPlr, iCom, iData;
public:
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlPlayerCommand : public C4ControlPacket // sync
{
public:
C4ControlPlayerCommand()
: iPlr(-1), iCmd(-1) { }
C4ControlPlayerCommand(int32_t iPlr, int32_t iCmd, int32_t iX, int32_t iY,
C4Object *pTarget, C4Object *pTarget2, int32_t iData, int32_t iAddMode);
protected:
int32_t iPlr, iCmd, iX, iY, iTarget, iTarget2, iData, iAddMode;
public:
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlSyncCheck : public C4ControlPacket // not sync
{
public:
C4ControlSyncCheck();
protected:
int32_t Frame;
int32_t ControlTick;
int32_t Random3;
int32_t RandomCount;
int32_t AllCrewPosX;
int32_t PXSCount;
int32_t MassMoverIndex;
int32_t ObjectCount;
int32_t ObjectEnumerationIndex;
int32_t SectShapeSum;
public:
void Set();
int32_t getFrame() const { return Frame; }
virtual bool Sync() const { return false; }
DECLARE_C4CONTROL_VIRTUALS
protected:
static int32_t GetAllCrewPosX();
};
class C4ControlSynchronize : public C4ControlPacket // sync
{
public:
C4ControlSynchronize(bool fSavePlrFiles = false, bool fSyncClearance = false)
: fSavePlrFiles(fSavePlrFiles), fSyncClearance(fSyncClearance)
{ }
protected:
bool fSavePlrFiles, fSyncClearance;
public:
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlClientJoin : public C4ControlPacket // not sync, lobby
{
public:
C4ControlClientJoin() { }
C4ControlClientJoin(const C4ClientCore &Core) : Core(Core) { }
public:
C4ClientCore Core;
public:
virtual bool Sync() const { return false; }
virtual bool Lobby() const { return true; }
DECLARE_C4CONTROL_VIRTUALS
};
enum C4ControlClientUpdType
{
CUT_None = -1, CUT_Activate = 0, CUT_SetObserver = 1,
};
class C4ControlClientUpdate : public C4ControlPacket // sync, lobby
{
public:
C4ControlClientUpdate() { }
C4ControlClientUpdate(int32_t iID, C4ControlClientUpdType eType, int32_t iData = 0)
: iID(iID), eType(eType), iData(iData)
{ }
public:
int32_t iID;
C4ControlClientUpdType eType;
int32_t iData;
public:
virtual bool Sync() const { return false; }
virtual bool Lobby() const { return true; }
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlClientRemove : public C4ControlPacket // not sync, lobby
{
public:
C4ControlClientRemove() { }
C4ControlClientRemove(int32_t iID, const char *szReason = "") : iID(iID), strReason(szReason) { }
public:
int32_t iID;
StdCopyStrBuf strReason;
public:
virtual bool Sync() const { return false; }
virtual bool Lobby() const { return true; }
DECLARE_C4CONTROL_VIRTUALS
};
// control used for initial player info, as well as for player info updates
class C4ControlPlayerInfo : public C4ControlPacket // not sync, lobby
{
public:
C4ControlPlayerInfo()
{ }
C4ControlPlayerInfo(const C4ClientPlayerInfos &PlrInfo)
: PlrInfo(PlrInfo)
{ }
protected:
C4ClientPlayerInfos PlrInfo;
public:
const C4ClientPlayerInfos &GetInfo() const { return PlrInfo; }
virtual bool Sync() const { return false; }
virtual bool Lobby() const { return true; }
DECLARE_C4CONTROL_VIRTUALS;
};
struct C4ControlJoinPlayer : public C4ControlPacket // sync
{
public:
C4ControlJoinPlayer() : iAtClient(-1), idInfo(-1) { }
C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo, const C4Network2ResCore &ResCore);
C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo);
protected:
StdStrBuf Filename;
int32_t iAtClient;
int32_t idInfo;
bool fByRes;
StdBuf PlrData; // for fByRes == false
C4Network2ResCore ResCore; // for fByRes == true
public:
DECLARE_C4CONTROL_VIRTUALS;
virtual bool PreExecute() const;
virtual void PreRec(C4Record *pRecord);
void Strip();
};
enum C4ControlEMObjectAction
{
EMMO_Move, // move objects by offset
EMMO_Enter, // enter objects into iTargetObj
EMMO_Duplicate, // duplicate objects at same position; reset EditCursor
EMMO_Script, // execute Script
EMMO_Remove, // remove objects
EMMO_Exit, // exit objects
};
class C4ControlEMMoveObject : public C4ControlPacket // sync
{
public:
C4ControlEMMoveObject() : pObjects(NULL) { }
C4ControlEMMoveObject(C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj,
int32_t iObjectNum = 0, int32_t *pObjects = NULL, const char *szScript = NULL);
~C4ControlEMMoveObject();
protected:
C4ControlEMObjectAction eAction; // action to be performed
int32_t tx,ty; // target position
int32_t iTargetObj; // enumerated ptr to target object
int32_t iObjectNum; // number of objects moved
int32_t *pObjects; // pointer on array of objects moved
StdStrBuf Script; // script to execute
public:
DECLARE_C4CONTROL_VIRTUALS
};
enum C4ControlEMDrawAction
{
EMDT_SetMode, // set new landscape mode
EMDT_Brush, // drawing tool
EMDT_Fill, // drawing tool
EMDT_Line, // drawing tool
EMDT_Rect, // drawing tool
};
class C4ControlEMDrawTool : public C4ControlPacket // sync
{
public:
C4ControlEMDrawTool() { }
C4ControlEMDrawTool(C4ControlEMDrawAction eAction, int32_t iMode,
int32_t iX=-1, int32_t iY=-1, int32_t iX2=-1, int32_t iY2=-1, int32_t iGrade=-1,
bool fIFT=true, const char *szMaterial=NULL, const char *szTexture=NULL);
protected:
C4ControlEMDrawAction eAction; // action to be performed
int32_t iMode; // new mode, or mode action was performed in (action will fail if changed)
int32_t iX,iY,iX2,iY2,iGrade; // drawing parameters
bool fIFT; // sky/tunnel-background
StdStrBuf Material; // used material
StdStrBuf Texture; // used texture
public:
DECLARE_C4CONTROL_VIRTUALS
};
enum C4ControlMessageType
{
C4CMT_Normal = 0,
C4CMT_Me = 1,
C4CMT_Say = 2,
C4CMT_Team = 3,
C4CMT_Private = 4,
C4CMT_Sound = 5, // "message" is played as a sound instead
C4CMT_Alert = 6, // no message. just flash taskbar for inactive clients.
C4CMT_System = 10,
};
class C4ControlMessage : public C4ControlPacket // not sync, lobby
{
public:
C4ControlMessage()
: eType(C4CMT_Normal), iPlayer(-1) { }
C4ControlMessage(C4ControlMessageType eType, const char *szMessage, int32_t iPlayer = -1, int32_t iToPlayer = -1)
: eType(eType), iPlayer(iPlayer), iToPlayer(iToPlayer), Message(szMessage, true)
{ }
protected:
C4ControlMessageType eType;
int32_t iPlayer, iToPlayer;
StdStrBuf Message;
public:
virtual bool Sync() const { return false; }
virtual bool Lobby() const { return true; }
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlRemovePlr : public C4ControlPacket // sync
{
public:
C4ControlRemovePlr()
: iPlr(-1) { }
C4ControlRemovePlr(int32_t iPlr, bool fDisconnected)
: iPlr(iPlr), fDisconnected(fDisconnected) { }
protected:
int32_t iPlr;
bool fDisconnected;
public:
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlDebugRec : public C4ControlPacket // sync
{
public:
C4ControlDebugRec()
{ }
C4ControlDebugRec(StdBuf &Data)
: Data(Data) { }
protected:
StdBuf Data;
public:
DECLARE_C4CONTROL_VIRTUALS
};
enum C4ControlVoteType
{
VT_None = -1,
VT_Cancel,
VT_Kick,
VT_Pause
};
class C4ControlVote : public C4ControlPacket
{
public:
C4ControlVote(C4ControlVoteType eType = VT_None, bool fApprove = true, int iData = 0)
: eType(eType), fApprove(fApprove), iData(iData)
{ }
private:
C4ControlVoteType eType;
bool fApprove;
int32_t iData;
public:
C4ControlVoteType getType() const { return eType; }
bool isApprove() const { return fApprove; }
int32_t getData() const { return iData; }
StdStrBuf getDesc() const;
StdStrBuf getDescWarning() const;
virtual bool Sync() const { return false; }
DECLARE_C4CONTROL_VIRTUALS
};
class C4ControlVoteEnd : public C4ControlVote
{
public:
C4ControlVoteEnd(C4ControlVoteType eType = VT_None, bool fApprove = true, int iData = 0)
: C4ControlVote(eType, fApprove, iData)
{ }
virtual bool Sync() const { return true; }
DECLARE_C4CONTROL_VIRTUALS
};
#endif

455
engine/inc/C4Def.h 100644
View File

@ -0,0 +1,455 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Object definition */
#ifndef INC_C4Def
#define INC_C4Def
#include <C4Shape.h>
#include <C4InfoCore.h>
#include <C4IDList.h>
#include <C4ValueMap.h>
#include <C4Facet.h>
#include <C4Surface.h>
#include <C4ComponentHost.h>
#ifdef C4ENGINE
#include <C4ScriptHost.h>
#include <C4DefGraphics.h>
#include "C4LangStringTable.h"
#endif
const int32_t C4D_None = 0,
C4D_All = ~C4D_None,
C4D_StaticBack = 1<<0,
C4D_Structure = 1<<1,
C4D_Vehicle = 1<<2,
C4D_Living = 1<<3,
C4D_Object = 1<<4,
C4D_SortLimit = C4D_StaticBack | C4D_Structure | C4D_Vehicle | C4D_Living | C4D_Object,
C4D_Goal = 1<<5,
C4D_Environment = 1<<6,
C4D_SelectBuilding = 1<<7,
C4D_SelectVehicle = 1<<8,
C4D_SelectMaterial = 1<<9,
C4D_SelectKnowledge = 1<<10,
C4D_SelectHomebase = 1<<11,
C4D_SelectAnimal = 1<<12,
C4D_SelectNest = 1<<13,
C4D_SelectInEarth = 1<<14,
C4D_SelectVegetation = 1<<15,
C4D_TradeLiving = 1<<16,
C4D_Magic = 1<<17,
C4D_CrewMember = 1<<18,
C4D_Rule = 1<<19,
C4D_Background = 1<<20,
C4D_Parallax = 1<<21,
C4D_MouseSelect = 1<<22,
C4D_Foreground = 1<<23,
C4D_MouseIgnore = 1<<24,
C4D_IgnoreFoW = 1<<25,
C4D_BackgroundOrForeground = (C4D_Background | C4D_Foreground);
const int32_t C4D_Grab_Put = 1,
C4D_Grab_Get = 2,
C4D_Border_Sides = 1,
C4D_Border_Top = 2,
C4D_Border_Bottom = 4,
C4D_Border_Layer = 8,
C4D_Line_Power = 1,
C4D_Line_Source = 2,
C4D_Line_Drain = 3,
C4D_Line_Lightning = 4,
C4D_Line_Volcano = 5,
C4D_Line_Rope = 6,
C4D_Line_Colored = 7,
C4D_Line_Vertex = 8,
C4D_Power_Input = 1,
C4D_Power_Output = 2,
C4D_Liquid_Input = 4,
C4D_Liquid_Output = 8,
C4D_Power_Generator = 16,
C4D_Power_Consumer = 32,
C4D_Liquid_Pump = 64,
C4D_Connect_Rope = 128,
C4D_EnergyHolder = 256,
C4D_Place_Surface = 0,
C4D_Place_Liquid = 1,
C4D_Place_Air = 2;
const int32_t C4D_VehicleControl_None = 0,
C4D_VehicleControl_Outside = 1,
C4D_VehicleControl_Inside = 2;
const int32_t C4D_Sell = C4D_StaticBack | C4D_Structure | C4D_Vehicle | C4D_Object | C4D_TradeLiving,
C4D_Get = C4D_Sell,
C4D_Take = C4D_Get,
C4D_Activate = C4D_Get;
const DWORD C4D_Load_None = 0,
C4D_Load_Picture = 1,
C4D_Load_Bitmap = 2,
C4D_Load_Script = 4,
C4D_Load_Desc = 8,
C4D_Load_ActMap = 16,
C4D_Load_Image = 32,
C4D_Load_Sounds = 64,
C4D_Load_ClonkNames= 128,
C4D_Load_RankNames = 256,
C4D_Load_RankFaces = 512,
C4D_Load_FE = C4D_Load_Image | C4D_Load_Desc,
C4D_Load_RX = C4D_Load_Bitmap | C4D_Load_Script | C4D_Load_ClonkNames | C4D_Load_Desc | C4D_Load_ActMap | C4D_Load_Sounds | C4D_Load_RankNames | C4D_Load_RankFaces,
C4D_Load_Temporary = 1024;
#define C4D_Blit_Normal 0
#define C4D_Blit_Additive 1
#define C4D_Blit_ModAdd 2
#define C4DGFXMODE_NEWGFX 1
#define C4DGFXMODE_OLDGFX 2
const int32_t ActIdle=-1;
const int32_t ActHold=-2;
class C4ActionDef
{
public:
C4ActionDef();
public:
char Name[C4D_MaxIDLen+1];
char ProcedureName[C4D_MaxIDLen+1];
int32_t Procedure; // Mapped by C4Def::Load
int32_t Directions;
int32_t FlipDir;
int32_t Length;
int32_t Delay;
int32_t Attach;
char NextActionName[C4D_MaxIDLen+1];
int32_t NextAction; // Mapped by C4Def::Load
char InLiquidAction[C4D_MaxIDLen+1];
char TurnAction[C4D_MaxIDLen+1];
int32_t FacetBase;
C4TargetRect Facet;
int32_t FacetTopFace;
int32_t NoOtherAction;
int32_t Disabled;
int32_t DigFree;
int32_t FacetTargetStretch;
char Sound[C4D_MaxIDLen+1];
int32_t EnergyUsage;
int32_t Reverse;
int32_t Step;
char SStartCall[C4D_MaxIDLen+1];
char SEndCall[C4D_MaxIDLen+1];
char SAbortCall[C4D_MaxIDLen+1];
char SPhaseCall[C4D_MaxIDLen+1];
class C4AulScriptFunc *StartCall;
C4AulScriptFunc *EndCall;
C4AulScriptFunc *AbortCall;
C4AulScriptFunc *PhaseCall;
public:
void Default();
void CompileFunc(StdCompiler *pComp);
};
class C4DefCore
{
public:
C4DefCore();
public:
C4ID id;
int32_t rC4XVer[4];
StdCopyStrBuf Name;
C4IDList RequireDef;
C4PhysicalInfo Physical;
C4Shape Shape;
C4Rect Entrance;
C4Rect Collection;
C4Rect PictureRect;
#ifndef C4ENGINE
C4Rect PictureRectFE;
#endif
C4TargetRect SolidMask;
C4TargetRect TopFace;
C4IDList Component;
C4ID BurnTurnTo;
C4ID BuildTurnTo;
int32_t GrowthType;
int32_t Basement;
int32_t CanBeBase;
int32_t CrewMember;
int32_t NativeCrew;
int32_t Mass;
int32_t Value;
int32_t Exclusive;
int32_t Category;
int32_t Growth;
int32_t Rebuyable;
int32_t ContactIncinerate; // 0 off 1 high - 5 low
int32_t BlastIncinerate; // 0 off 1 - x if > damage
int32_t Constructable;
int32_t Grab; // 0 not 1 push 2 grab only
int32_t Carryable;
int32_t Rotateable;
int32_t Chopable;
int32_t Float;
int32_t ColorByOwner;
int32_t NoHorizontalMove;
int32_t BorderBound;
int32_t LiftTop;
int32_t CollectionLimit;
int32_t GrabPutGet;
int32_t ContainBlast;
int32_t UprightAttach;
int32_t ContactFunctionCalls;
int32_t MaxUserSelect;
int32_t Line;
int32_t LineConnect;
int32_t LineIntersect;
int32_t NoBurnDecay;
int32_t IncompleteActivity;
int32_t Placement;
int32_t Prey;
int32_t Edible;
int32_t AttractLightning;
int32_t Oversize;
int32_t Fragile;
int32_t Projectile;
int32_t Explosive;
int32_t NoPushEnter;
int32_t DragImagePicture;
int32_t VehicleControl;
int32_t Pathfinder;
int32_t MoveToRange;
int32_t Timer;
int32_t NoComponentMass;
int32_t NoStabilize;
char STimerCall[C4D_MaxIDLen];
char ColorByMaterial[C4M_MaxName+1];
int32_t ClosedContainer; // if set, contained objects are not damaged by lava/acid etc. 1: Contained objects can't view out; 2: They can
int32_t SilentCommands; // if set, no command failure messages are printed
int32_t NoBurnDamage; // if set, the object won't take damage when burning
int32_t TemporaryCrew; // if set, info objects are not written into regular player files
int32_t SmokeRate; // amount of smoke produced when on fire. 100 is default
int32_t BlitMode; // special blit mode for objects of this def. C4D_Blit_X
int32_t NoBreath; // object does not need to breath, although it's living
int32_t ConSizeOff; // number of pixels to be subtracted from the needed height for this building
int32_t NoSell; // if set, object can't be sold (doesn't even appear in sell-menu)
int32_t NoGet; // if set, object can't be taken out of a containers manually (doesn't appear in get/activate-menus)
int32_t NoFight; // if set, object is never OCF_FightReady
int32_t RotatedSolidmasks;// if set, solidmasks can be rotated
int32_t NeededGfxMode; // if set, the def will only be loaded in given gfx mode
int32_t RotatedEntrance; // 0 entrance not rotateable, 1 entrance always, 2-360 entrance within this rotation
int32_t NoTransferZones;
int32_t AutoContextMenu; // automatically open context menu for this object
int32_t AllowPictureStack; // allow stacking of multiple items in menus even if some attributes do not match. APS_*-values
public:
void Default();
BOOL Load(C4Group &hGroup);
BOOL Save(C4Group &hGroup);
void CompileFunc(StdCompiler *pComp);
const char * GetName() const { return Name.getData(); }
protected:
BOOL Compile(const char *szSource, const char *szName);
BOOL Decompile(StdStrBuf *pOut, const char *szName);
};
class C4Def: public C4DefCore
{
friend class C4DefList;
public:
C4Def();
~C4Def();
public:
#if defined(_WIN32) && !defined(C4ENGINE) && !defined(C4GROUP)
HBITMAP Picture;
HBITMAP Image;
#endif
int32_t ActNum; C4ActionDef *ActMap;
char Maker[C4MaxName+1];
char Filename[_MAX_FNAME+1];
int32_t Creation;
int32_t Count; // number of instanciations
C4AulScriptFunc *TimerCall;
C4ComponentHost Desc;
#ifdef C4ENGINE
// Currently cannot have script host in frontend because that
// would need C4Script, C4AulScript, and all that as well...
C4DefScriptHost Script;
C4LangStringTable StringTable;
// clonknames are simply not needed in frontend
C4ComponentHost *pClonkNames; bool fClonkNamesOwned;
// neither are ranknames nor the symbols...yet!
C4RankSystem *pRankNames; bool fRankNamesOwned;
C4FacetSurface *pRankSymbols; bool fRankSymbolsOwned;
int32_t iNumRankSymbols; // number of rank symbols available, if loaded
C4DefGraphics Graphics; // base graphics. points to additional graphics
int32_t PortraitCount;
C4PortraitGraphics *Portraits; // Portraits (linked list of C4AdditionalDefGraphics)
protected:
// copy of the physical info used in FairCrew-mode
C4PhysicalInfo *pFairCrewPhysical;
C4Facet MainFace;
#endif
protected:
C4Def *Next;
BOOL Temporary;
public:
void Clear();
void Default();
BOOL Load(C4Group &hGroup,
DWORD dwLoadWhat, const char *szLanguage,
class C4SoundSystem *pSoundSystem = NULL);
void Draw(C4Facet &cgo, BOOL fSelected=FALSE, DWORD iColor=0, C4Object *pObj=NULL, int32_t iPhaseX=0, int32_t iPhaseY=0);
#ifdef C4ENGINE
inline C4Facet &GetMainFace(C4DefGraphics *pGraphics, DWORD dwClr=0) { MainFace.Surface=pGraphics->GetBitmap(dwClr); return MainFace; }
int32_t GetValue(C4Object *pInBase, int32_t iBuyPlayer); // get value of def; calling script functions if defined
C4PhysicalInfo *GetFairCrewPhysicals(); // get fair crew physicals at current fair crew strength
void ClearFairCrewPhysicals(); // remove cached fair crew physicals, will be created fresh on demand
void Synchronize();
#endif
const char *GetDesc() { return Desc.GetData(); }
protected:
bool LoadPortraits(C4Group &hGroup);
BOOL ColorizeByMaterial(class C4MaterialMap &rMats, BYTE bGBM);
BOOL LoadActMap(C4Group &hGroup);
void CrossMapActMap();
private:
C4ValueArray *GetCustomComponents(C4Value *pvArrayHolder, C4Object *pBuilder, C4Object *pObjInstance=NULL);
public:
// return def components - may be overloaded by script callback
int32_t GetComponentCount(C4ID idComponent, C4Object *pBuilder=NULL);
C4ID GetIndexedComponent(int32_t idx, C4Object *pBuilder=NULL);
void GetComponents(C4IDList *pOutList, C4Object *pObjInstance=NULL, C4Object *pBuilder=NULL);
void IncludeDefinition(C4Def *pIncludeDef); // inherit components from other definition
void ResetIncludeDependencies(); // resets all pointers into foreign definitions caused by include chains
};
class C4DefList
#ifdef C4ENGINE
: public CStdFont::CustomImages
#endif
{
public:
C4DefList();
virtual ~C4DefList();
public:
BOOL LoadFailure;
C4Def **Table[64]; // From space to _; some minor waste of mem
bool fTable;
protected:
C4Def *FirstDef;
public:
void Default();
void Clear();
int32_t Load(C4Group &hGroup,
DWORD dwLoadWhat, const char *szLanguage,
C4SoundSystem *pSoundSystem = NULL,
BOOL fOverload = FALSE,
BOOL fSearchMessage = FALSE, int32_t iMinProgress=0, int32_t iMaxProgress=0, bool fLoadSysGroups = true);
int32_t Load(const char *szSearch,
DWORD dwLoadWhat, const char *szLanguage,
C4SoundSystem *pSoundSystem = NULL,
BOOL fOverload = FALSE, int32_t iMinProgress=0, int32_t iMaxProgress=0);
int32_t LoadFolderLocal(const char *szPath,
DWORD dwLoadWhat, const char *szLanguage,
C4SoundSystem *pSoundSystem = NULL,
BOOL fOverload = FALSE, char *szStoreName=NULL, int32_t iMinProgress=0, int32_t iMaxProgress=0);
int32_t LoadForScenario(const char *szScenario,
const char *szSpecified,
DWORD dwLoadWhat, const char *szLanguage,
C4SoundSystem *pSoundSystem = NULL,
BOOL fOverload = FALSE, int32_t iMinProgress=0, int32_t iMaxProgress=0);
C4Def *ID2Def(C4ID id);
C4Def *GetDef(int32_t Index, DWORD dwCategory = C4D_All);
C4Def *GetByPath(const char *szPath);
int32_t GetDefCount(DWORD dwCategory = C4D_All);
int32_t GetIndex(C4ID id);
int32_t RemoveTemporary();
int32_t ColorizeByMaterial(C4MaterialMap &rMats, BYTE bGBM);
int32_t CheckEngineVersion(int32_t ver1, int32_t ver2, int32_t ver3, int32_t ver4);
int32_t CheckRequireDef();
void Draw(C4ID id, C4Facet &cgo, BOOL fSelected, int32_t iColor);
void Remove(C4Def *def);
BOOL Remove(C4ID id);
BOOL Reload(C4Def *pDef, DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem = NULL);
BOOL Add(C4Def *ndef, BOOL fOverload);
void BuildTable(); // build quick access table
void ResetIncludeDependencies(); // resets all pointers into foreign definitions caused by include chains
#ifdef C4ENGINE
void Synchronize();
#endif
// callback from font renderer: get ID image
virtual bool GetFontImage(const char *szImageTag, CFacet &rOutImgFacet);
private:
void SortByID(); // sorts list by quick access table
};
// Default Action Procedures
#define DFA_NONE -1
#define DFA_WALK 0
#define DFA_FLIGHT 1
#define DFA_KNEEL 2
#define DFA_SCALE 3
#define DFA_HANGLE 4
#define DFA_DIG 5
#define DFA_SWIM 6
#define DFA_THROW 7
#define DFA_BRIDGE 8
#define DFA_BUILD 9
#define DFA_PUSH 10
#define DFA_CHOP 11
#define DFA_LIFT 12
#define DFA_FLOAT 13
#define DFA_ATTACH 14
#define DFA_FIGHT 15
#define DFA_CONNECT 16
#define DFA_PULL 17
#define C4D_MaxDFA 18
// procedure name table
extern const char *ProcedureName[C4D_MaxDFA];
#endif

View File

@ -0,0 +1,260 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2004-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// graphics used by object definitions (object and portraits)
#ifndef INC_C4DefGraphics
#define INC_C4DefGraphics
#include <C4FacetEx.h>
#include <C4Surface.h>
#define C4Portrait_None "none"
#define C4Portrait_Random "random"
#define C4Portrait_Custom "custom"
// defintion graphics
class C4AdditionalDefGraphics;
class C4DefGraphicsPtrBackup;
class C4PortraitGraphics;
class C4DefGraphics
{
public:
C4Def *pDef; // underlying definition
protected:
C4AdditionalDefGraphics *pNext; // next graphics
C4DefGraphics *GetLast(); // get last graphics in list
public:
C4Surface *Bitmap, *BitmapClr;
bool fColorBitmapAutoCreated; // if set, the color-by-owner-bitmap has been created automatically by all blue shades of the bitmap
inline C4Surface *GetBitmap(DWORD dwClr=0) { if (BitmapClr) { BitmapClr->SetClr(dwClr); return BitmapClr; } else return Bitmap; }
C4DefGraphics(C4Def *pOwnDef=NULL); // ctor
virtual ~C4DefGraphics() { Clear(); }; // dtor
bool LoadBitmap(C4Group &hGroup, const char *szFilename, const char *szFilenamePNG, const char *szOverlayPNG, bool fColorByOwner); // load specified graphics from group
bool LoadBitmaps(C4Group &hGroup, bool fColorByOwner); // load graphics from group
bool ColorizeByMaterial(int32_t iMat, C4MaterialMap &rMats, BYTE bGBM); // colorize all graphics by material
C4DefGraphics *Get(const char *szGrpName); // get graphics by name
void Clear(); // clear fields; delete additional graphics
bool IsColorByOwner() // returns whether ColorByOwner-surfaces have been created
{ return !!BitmapClr; }
bool CopyGraphicsFrom(C4DefGraphics &rSource); // copy bitmaps from source graphics
virtual const char *GetName() { return NULL; } // return name to be stored in safe game files
C4AdditionalDefGraphics *GetNext() { return pNext; }
virtual C4PortraitGraphics *IsPortrait() { return NULL; }
void DrawClr(C4Facet &cgo, BOOL fAspect=TRUE, DWORD dwClr=0); // set surface color and draw
void CompileFunc(StdCompiler *pComp);
friend class C4DefGraphicsPtrBackup;
};
// additional definition graphics
class C4AdditionalDefGraphics : public C4DefGraphics
{
protected:
char Name[C4MaxName+1]; // graphics name
public:
C4AdditionalDefGraphics(C4Def *pOwnDef, const char *szName); // ctor
virtual const char *GetName() { return Name; }
};
// portrait graphics within object definition
class C4PortraitGraphics : public C4AdditionalDefGraphics
{
public:
C4PortraitGraphics(C4Def *pOwnDef, const char *szName) // ctor
: C4AdditionalDefGraphics(pOwnDef, szName) { }
virtual C4PortraitGraphics *IsPortrait() { return this; }
C4PortraitGraphics *GetByIndex(int32_t iIndex);
C4PortraitGraphics *Get(const char *szGrpName); // get portrait graphics by name
};
// backup class holding dead graphics pointers and names
class C4DefGraphicsPtrBackup
{
protected:
C4DefGraphics *pGraphicsPtr; // dead graphics ptr
C4Def *pDef; // definition of dead graphics
char Name[C4MaxName+1]; // name of graphics
C4DefGraphicsPtrBackup *pNext; // next member of linked list
public:
C4DefGraphicsPtrBackup(C4DefGraphics *pSourceGraphics); // ctor
~C4DefGraphicsPtrBackup(); // dtor
void AssignUpdate(C4DefGraphics *pNewGraphics); // update all game objects with new graphics pointers
void AssignRemoval(); // remove graphics of this def from all game objects
};
// Helper to compile C4DefGraphics-Pointer
class C4DefGraphicsAdapt
{
protected:
C4DefGraphics *&pDefGraphics;
public:
C4DefGraphicsAdapt(C4DefGraphics *&pDefGraphics) : pDefGraphics(pDefGraphics) { }
void CompileFunc(StdCompiler *pComp);
// Default checking / setting
bool operator == (C4DefGraphics *pDef2) { return pDefGraphics == pDef2; }
void operator = (C4DefGraphics *pDef2) { pDefGraphics = pDef2; }
ALLOW_TEMP_TO_REF(C4DefGraphicsAdapt)
};
// portrait link class
class C4Portrait
{
protected:
C4DefGraphics *pGfxPortrait; // the portrait graphics
bool fGraphicsOwned; // if true, the portrait graphics are owned (and deleted upon destruction)
public:
C4Portrait() : pGfxPortrait(NULL), fGraphicsOwned(false) {} // ctor
~C4Portrait() { if (fGraphicsOwned) delete pGfxPortrait; } // dtor
void Default() { pGfxPortrait=NULL; fGraphicsOwned=false; }
void Clear() { if (fGraphicsOwned) { delete pGfxPortrait; fGraphicsOwned=false; } pGfxPortrait=NULL; }
bool CopyFrom(C4DefGraphics &rCopyGfx); // copy portrait from graphics
bool CopyFrom(C4Portrait &rCopy); // copy portrait
bool Load(C4Group &rGrp, const char *szFilename, const char *szFilenamePNG, const char *szOverlayPNG); // load own portrait from group
bool Link(C4DefGraphics *pGfxPortrait); // link with a present portrait surface
bool SavePNG(C4Group &rGroup, const char *szFilename, const char *szOverlayFN); // store portrait gfx to file (including overlay)
C4DefGraphics *GetGfx() { return pGfxPortrait; }
bool IsOwnedGfx() { return fGraphicsOwned; } // return if it's a custom portrait
static const char *EvaluatePortraitString(const char *szPortrait, C4ID &rIDOut, C4ID idDefaultID, uint32_t *pdwClrOut); // get portrait source and def from string
};
// graphics overlay used to attach additional graphics to objects
class C4GraphicsOverlay
{
public:
enum Mode
{
MODE_None=0,
MODE_Base=1, // display base facet
MODE_Action=2, // display action facet specified in Action
MODE_Picture=3, // overlay picture to this picture only
MODE_IngamePicture=4, // draw picture of source def
MODE_Object=5, // draw another object gfx
MODE_ExtraGraphics=6, // draw like this were a ClrByOwner-surface
};
protected:
Mode eMode; // overlay mode
C4DefGraphics *pSourceGfx; // source graphics - used for savegame saving and comparisons in ReloadDef
char Action[C4MaxName+1]; // action used as overlay in source gfx
C4TargetFacet fctBlit; // current blit data
uint32_t dwBlitMode; // extra parameters for additive blits, etc.
uint32_t dwClrModulation; // colormod for this overlay
#ifdef C4ENGINE
C4Object *pOverlayObj; // object to be drawn as overlay in MODE_Object
int32_t nOverlayObj; // compiled ptr
C4DrawTransform Transform; // drawing transformation: Rotation, zoom, etc.
#endif
int32_t iPhase; // action face for MODE_Action
bool fZoomToShape; // if true, overlay will be zoomed to match the target object shape
int32_t iID; // identification number for Z-ordering and script identification
C4GraphicsOverlay *pNext; // singly linked list
void UpdateFacet(); // update fctBlit to reflect current data
void Set(Mode aMode, C4DefGraphics *pGfx, const char *szAction, DWORD dwBMode, C4Object *pOvrlObj);
public:
C4GraphicsOverlay() : eMode(MODE_None), pSourceGfx(NULL), fctBlit(), dwBlitMode(0), dwClrModulation(0xffffff),
#ifdef C4ENGINE
pOverlayObj(NULL), nOverlayObj(0), Transform(+1),
#endif
iPhase(0), fZoomToShape(false), iID(0), pNext(NULL) { *Action=0; } // std ctor
~C4GraphicsOverlay(); // dtor
void Read(const char **ppInput);
void Write(char *ppOutput);
void CompileFunc(StdCompiler *pComp);
// object pointer management
void EnumeratePointers();
void DenumeratePointers();
void SetAsBase(C4DefGraphics *pBaseGfx, DWORD dwBMode) // set in MODE_Base
{ Set(MODE_Base, pBaseGfx, NULL, dwBMode, NULL); }
void SetAsAction(C4DefGraphics *pBaseGfx, const char *szAction, DWORD dwBMode)
{ Set(MODE_Action, pBaseGfx, szAction, dwBMode, NULL); }
void SetAsPicture(C4DefGraphics *pBaseGfx, DWORD dwBMode)
{ Set(MODE_Picture, pBaseGfx, NULL, dwBMode, NULL); }
void SetAsIngamePicture(C4DefGraphics *pBaseGfx, DWORD dwBMode)
{ Set(MODE_IngamePicture, pBaseGfx, NULL, dwBMode, NULL); }
void SetAsObject(C4Object *pOverlayObj, DWORD dwBMode)
{ Set(MODE_Object, NULL, NULL, dwBMode, pOverlayObj); }
void SetAsExtraGraphics(C4DefGraphics *pGfx, DWORD dwBMode)
{ Set(MODE_ExtraGraphics, pGfx, NULL, dwBMode, NULL); }
bool IsValid(const C4Object *pForObj) const;
#ifdef C4ENGINE
C4DrawTransform *GetTransform() { return &Transform; }
C4Object *GetOverlayObject() const { return pOverlayObj; }
#endif
int32_t GetID() const { return iID; }
void SetID(int32_t aID) { iID = aID; }
void SetPhase(int32_t iToPhase);
C4GraphicsOverlay *GetNext() const { return pNext; }
void SetNext(C4GraphicsOverlay *paNext) { pNext = paNext; }
bool IsPicture() { return eMode == MODE_Picture; }
C4DefGraphics *GetGfx() const { return pSourceGfx; }
void Draw(C4TargetFacet &cgo, C4Object *pForObj, int32_t iByPlayer);
void DrawPicture(C4Facet &cgo, C4Object *pForObj);
bool operator == (const C4GraphicsOverlay &rCmp) const; // comparison operator
uint32_t GetClrModulation() const { return dwClrModulation; }
void SetClrModulation(uint32_t dwToMod) { dwClrModulation = dwToMod; }
uint32_t GetBlitMode() const { return dwBlitMode; }
void SetBlitMode(uint32_t dwToMode) { dwBlitMode = dwToMode; }
};
// Helper to compile lists of C4GraphicsOverlay
class C4GraphicsOverlayListAdapt
{
protected:
C4GraphicsOverlay *&pOverlay;
public:
C4GraphicsOverlayListAdapt(C4GraphicsOverlay *&pOverlay) : pOverlay(pOverlay) { }
void CompileFunc(StdCompiler *pComp);
// Default checking / setting
bool operator == (C4GraphicsOverlay *pDefault) { return pOverlay == pDefault; }
void operator = (C4GraphicsOverlay *pDefault) { delete pOverlay; pOverlay = pDefault; }
ALLOW_TEMP_TO_REF(C4GraphicsOverlayListAdapt)
};
#endif // INC_C4DefGraphics

View File

@ -0,0 +1,51 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Common window for drawing and property tool dialogs in console mode */
#ifndef INC_C4DevmodeDlg
#define INC_C4DevmodeDlg
#ifdef WITH_DEVELOPER_MODE
#include <gtk/gtkwidget.h>
#include <gtk/gtkwindow.h>
#endif // WITH_DEVELOPER_MODE
// TODO: Threadsafety?
class C4DevmodeDlg
{
// Make sure all developer tools are held in the same window
#ifdef WITH_DEVELOPER_MODE
private:
static GtkWidget* window;
static GtkWidget* notebook;
static int x, y;
static void OnDestroy(GtkWidget* widget, gpointer user_data);
public:
static GtkWidget* GetWindow() { return window; }
static void AddPage(GtkWidget* widget, GtkWindow* parent, const char* title);
static void RemovePage(GtkWidget* widget);
static void SwitchPage(GtkWidget* widget);
static void SetTitle(GtkWidget* widget, const char* title);
#endif // WITH_DEVELOPER_MODE
};
#endif //INC_C4DevmodeDlg

View File

@ -0,0 +1,67 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2007-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// HTTP download dialog; downloads a file
// (like, e.g., a .c4u update group)
#ifndef INC_C4DownloadDlg
#define INC_C4DownloadDlg
#include "C4Gui.h"
#include "C4Network2Reference.h" // includes HTTP client
// dialog to download a file
class C4DownloadDlg : public C4GUI::Dialog
{
private:
C4Network2HTTPClient HTTPClient;
C4GUI::Icon *pIcon;
C4GUI::Label *pStatusLabel;
C4GUI::ProgressBar *pProgressBar;
C4GUI::CancelButton *pCancelBtn;
const char *szError;
#ifdef HAVE_WINSOCK
bool fWinSock;
#endif
protected:
C4DownloadDlg(const char *szDLType);
virtual ~C4DownloadDlg();
private:
// updates the displayed status text and progress bar - repositions elements if necessary
void SetStatus(const char *szNewText, int32_t iProgressPercent);
protected:
// idle proc: Continue download; close when finished
virtual void OnIdle();
// user presses cancel button: Abort download
virtual void UserClose(bool fOK);
// downloads the specified file to the specified location. Returns whether successful
bool ShowModal(C4GUI::Screen *pScreen, const char *szURL, const char *szSaveAsFilename);
const char *GetError();
public:
// download file showing download dialog; display error if download failed
static bool DownloadFile(const char *szDLType, C4GUI::Screen *pScreen, const char *szURL, const char *szSaveAsFilename, const char *szNotFoundMessage = NULL);
};
#endif // INC_C4DownloadDlg

View File

@ -0,0 +1,107 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Handles viewport editing in console mode */
#ifndef INC_C4EditCursor
#define INC_C4EditCursor
#include "C4ObjectList.h"
#include "C4Control.h"
#ifdef WITH_DEVELOPER_MODE
#include <gtk/gtkwidget.h>
#endif
class C4EditCursor
{
public:
C4EditCursor();
~C4EditCursor();
protected:
bool fAltWasDown;
bool fSelectionChanged;
int32_t Mode;
int32_t X,Y,X2,Y2;
BOOL Hold,DragFrame,DragLine;
C4Object *Target,*DropTarget;
#ifdef _WIN32
HMENU hMenu;
#else
#ifdef WITH_DEVELOPER_MODE
GtkWidget* menuContext;
GtkWidget* itemDelete;
GtkWidget* itemDuplicate;
GtkWidget* itemGrabContents;
GtkWidget* itemProperties;
#endif
#endif // _WIN32
C4ObjectList Selection;
public:
void Default();
void Clear();
void Execute();
void ClearPointers(C4Object *pObj);
bool ToggleMode();
void Draw(C4TargetFacet &cgo, float Zoom);
int32_t GetMode();
C4Object* GetTarget();
BOOL SetMode(int32_t iMode);
BOOL In(const char *szText);
BOOL Duplicate();
BOOL OpenPropTools();
bool Delete();
BOOL LeftButtonUp();
BOOL LeftButtonDown(BOOL fControl);
BOOL RightButtonUp();
BOOL RightButtonDown(BOOL fControl);
bool Move(float iX, float iY, WORD wKeyFlags);
BOOL Init();
BOOL EditingOK();
C4ObjectList &GetSelection() { return Selection; }
void SetHold(BOOL fToState) { Hold = fToState; }
void OnSelectionChanged();
bool AltDown();
bool AltUp();
protected:
BOOL UpdateStatusBar();
void ApplyToolPicker();
void ToolFailure();
void PutContents();
void UpdateDropTarget(WORD wKeyFlags);
void GrabContents();
BOOL DoContextMenu();
void ApplyToolFill();
void ApplyToolRect();
void ApplyToolLine();
void ApplyToolBrush();
void DrawSelectMark(C4Facet &cgo, FLOAT_RECT r);
void FrameSelection();
void MoveSelection(int32_t iXOff, int32_t iYOff);
void EMMoveObject(enum C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj, const C4ObjectList *pObjs = NULL, const char *szScript = NULL);
void EMControl(enum C4PacketType eCtrlType, class C4ControlPacket *pCtrl);
#ifdef WITH_DEVELOPER_MODE
static void OnDelete(GtkWidget* widget, gpointer data);
static void OnDuplicate(GtkWidget* widget, gpointer data);
static void OnGrabContents(GtkWidget* widget, gpointer data);
static void OnProperties(GtkWidget* widget, gpointer data);
#endif
};
#endif

View File

@ -0,0 +1,166 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// C4AulFun-based effects assigned to an object
// an effect itself only supplies the callback mechanism for effects assigned to objects
// the effect itself supplies the callback mechanism for creation, destruction, timers
// and overlapped effects
/* Also contains some helper functions for various landscape effects */
#ifndef INC_C4Effects
#define INC_C4Effects
#include <C4Constants.h>
// callback return values
#define C4Fx_OK 0 // generic standard behaviour for all effect callbacks
#define C4Fx_Effect_Deny -1 // delete effect
#define C4Fx_Effect_Annul -2 // delete effect, because it has annulled a countereffect
#define C4Fx_Effect_AnnulCalls -3 // delete effect, because it has annulled a countereffect; temp readd countereffect
#define C4Fx_Execute_Kill -1 // execute callback: Remove effect now
#define C4Fx_Stop_Deny -1 // deny effect removal
#define C4Fx_Start_Deny -1 // deny effect start
// parameters for effect callbacks
#define C4FxCall_Normal 0 // normal call; effect is being added or removed
#define C4FxCall_Temp 1 // temp call; effect is being added or removed in responce to a lower-level effect change
#define C4FxCall_TempAddForRemoval 2 // temp call; effect is being added because it had been temp removed and is now removed forever
#define C4FxCall_RemoveClear 3 // effect is being removed because object is being removed
#define C4FxCall_RemoveDeath 4 // effect is being removed because object died - return -1 to avoid removal
// damage-callbacks
#define C4FxCall_DmgScript 0 // damage through script call
#define C4FxCall_DmgBlast 1 // damage through blast
#define C4FxCall_DmgFire 2 // damage through fire
#define C4FxCall_DmgChop 3 // damage through chopping
// energy loss callbacks
#define C4FxCall_EngScript 32 // energy loss through script call
#define C4FxCall_EngBlast 33 // energy loss through blast
#define C4FxCall_EngObjHit 34 // energy loss through object hitting the living
#define C4FxCall_EngFire 35 // energy loss through fire
#define C4FxCall_EngBaseRefresh 36 // energy reload in base (also by base object, but that's normally not called)
#define C4FxCall_EngAsphyxiation 37 // energy loss through asphyxiaction
#define C4FxCall_EngCorrosion 38 // energy loss through corrosion (acid)
#define C4FxCall_EngStruct 39 // regular structure energy loss (normally not called)
#define C4FxCall_EngGetPunched 40 // energy loss during fighting
// fire drawing modes
#define C4Fx_FireMode_Default 0 // determine mode by category
#define C4Fx_FireMode_LivingVeg 2 // C4D_Living and C4D_StaticBack
#define C4Fx_FireMode_StructVeh 1 // C4D_Structure and C4D_Vehicle
#define C4Fx_FireMode_Object 3 // other (C4D_Object and no bit set (magic))
#define C4Fx_FireMode_Last 3 // largest valid fire mode
#define C4Fx_FireParticle1 "Fire"
#define C4Fx_FireParticle2 "Fire2"
// generic object effect
class C4Effect
{
public:
char Name[C4MaxDefString+1]; // name of effect
C4Object *pCommandTarget; // target object for script callbacks - if deleted, the effect is removed without callbacks
C4ID idCommandTarget; // ID of command target definition
int32_t nCommandTarget; // enumerated ptr for target object (argh, when will this system be changed?)
int32_t iPriority; // effect priority for sorting into effect list; -1 indicates a dead effect
C4ValueList EffectVars; // custom effect variables
int32_t iTime, iIntervall; // effect time; effect callback intervall
int32_t iNumber; // effect number for addressing
C4Effect *pNext; // next effect in linked list
protected:
// presearched callback functions for faster calling
C4AulFunc *pFnTimer; // timer function Fx%sTimer
C4AulFunc *pFnStart, *pFnStop; // init/deinit-functions Fx%sStart, Fx%sStop
C4AulFunc *pFnEffect; // callback if other effect tries to register
C4AulFunc *pFnDamage; // callback when owned object gets damage
void AssignCallbackFunctions(); // resolve callback function names
public:
C4Effect(C4Object *pForObj, const char *szName, int32_t iPrio, int32_t iTimerIntervall, C4Object *pCmdTarget, C4ID idCmdTarget, C4Value &rVal1, C4Value &rVal2, C4Value &rVal3, C4Value &rVal4, bool fDoCalls, int32_t &riStoredAsNumber); // ctor
C4Effect(StdCompiler *pComp); // ctor: compile
~C4Effect(); // dtor - deletes all following effects
void EnumeratePointers(); // object pointers to numbers
void DenumeratePointers(); // numbers to object pointers
void ClearPointers(C4Object *pObj); // clear all pointers to object - may kill some effects w/o callback, because the callback target is lost
void SetDead() { iPriority=0; } // mark effect to be removed in next execution cycle
bool IsDead() { return !iPriority; } // return whether effect is to be removed
void FlipActive() { iPriority*=-1; } // alters activation status
bool IsActive() { return iPriority>0; } // returns whether effect is active
bool IsInactiveAndNotDead() { return iPriority<0; } // as the name says
C4Effect *Get(const char *szName, int32_t iIndex=0, int32_t iMaxPriority=0); // get effect by name
C4Effect *Get(int32_t iNumber, bool fIncludeDead, int32_t iMaxPriority=0); // get effect by number
int32_t GetCount(const char *szMask, int32_t iMaxPriority=0); // count effects that match the mask
int32_t Check(C4Object *pForObj, const char *szCheckEffect, int32_t iPrio, int32_t iTimer, C4Value &rVal1, C4Value &rVal2, C4Value &rVal3, C4Value &rVal4); // do some effect callbacks
C4AulScript *GetCallbackScript(); // get script context for effect callbacks
void Execute(C4Object *pObj); // execute all effects
void Kill(C4Object *pObj); // mark this effect deleted and do approprioate calls
void ClearAll(C4Object *pObj, int32_t iClearFlag);// kill all effects doing removal calls w/o reagard of inactive effects
void DoDamage(C4Object *pObj, int32_t &riDamage, int32_t iDamageType, int32_t iCausePlr); // ask all effects for damage
C4Value DoCall(C4Object *pObj, const char *szFn, C4Value &rVal1, C4Value &rVal2, C4Value &rVal3, C4Value &rVal4, C4Value &rVal5, C4Value &rVal6, C4Value &rVal7); // custom call
void ReAssignCallbackFunctions()
{ AssignCallbackFunctions(); }
void ReAssignAllCallbackFunctions()
{ ReAssignCallbackFunctions();
if (pNext) pNext->ReAssignAllCallbackFunctions(); }
void OnObjectChangedDef(C4Object *pObj);
void CompileFunc(StdCompiler *pComp);
protected:
void TempRemoveUpperEffects(C4Object *pObj, bool fTempRemoveThis, C4Effect **ppLastRemovedEffect); // temp remove all effects with higher priority
void TempReaddUpperEffects(C4Object *pObj, C4Effect *pLastReaddEffect); // temp remove all effects with higher priority
};
// ctor for StdPtrAdapt
inline void CompileNewFunc(C4Effect *&pRes, StdCompiler *pComp) { pRes = new C4Effect(pComp); }
// fire effect constants
#define MaxFirePhase 15
#define C4Fx_Fire "Fire"
#define C4Fx_AnyFire "*Fire*"
#define C4Fx_Internal "Int*"
#define C4Fx_FirePriority 100
#define C4Fx_FireTimer 1
// fire effect
int32_t FnFxFireStart(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_t iTemp, int32_t iCausedBy, bool fBlasted, C4Object *pIncineratingObject);
int32_t FnFxFireTimer(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_t iTime);
int32_t FnFxFireStop(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_t iReason, bool fTemp);
C4String *FnFxFireInfo(C4AulContext *ctx, C4Object *pObj, int32_t iNumber);
class C4Value &FxFireVarCausedBy(C4Effect *pEffect);
// some other hardcoded engine effects
void Splash(int32_t tx, int32_t ty, int32_t amt, C4Object *pByObj);
void Explosion(int32_t tx, int32_t ty, int32_t level, C4Object *inobj, int32_t iCausedBy, C4Object *pByObj, C4ID idEffect, const char *szEffect);
void Smoke(int32_t tx, int32_t ty, int32_t level, DWORD dwClr=0);
void BubbleOut(int32_t tx, int32_t ty);
#endif

View File

@ -0,0 +1,42 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// user-customizable multimedia package Extra.c4g
#ifndef INC_C4Extra
#define INC_C4Extra
#include <C4Group.h>
class C4Extra
{
public:
C4Extra() { Default(); }; // ctor
~C4Extra() { Clear(); }; // dtor
void Default(); // zero fields
void Clear(); // free class members
bool Init(); // init extra group, using scneario presets
bool InitGroup(); // open extra group
C4Group ExtraSysGrp; // extra.c4g root folder
C4Group ExtraUserGrp; // extra.c4g root folder
protected:
bool LoadDef(C4Group &hGroup, const char *szName); // load preset for definition
};
#endif

View File

@ -0,0 +1,170 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* A piece of a DirectDraw surface */
#ifndef INC_C4Facet
#define INC_C4Facet
#include <StdDDraw2.h>
const int32_t C4FCT_None = 0,
C4FCT_Left = 1,
C4FCT_Right = 2,
C4FCT_Top = 4,
C4FCT_Bottom = 8,
C4FCT_Center = 16,
C4FCT_Alignment = C4FCT_Left | C4FCT_Right | C4FCT_Top | C4FCT_Bottom | C4FCT_Center,
C4FCT_Half = 32,
C4FCT_Double = 64,
C4FCT_Triple = 128;
// tuple of two integers
struct C4Vec2D
{
int32_t x,y;
C4Vec2D(int32_t x=0, int32_t y=0) : x(x), y(y) {}
};
#ifdef C4ENGINE
class C4DrawTransform : public CBltTransform
{
public:
int32_t FlipDir; // +1 or -1; multiplied as x-flip
C4DrawTransform(C4DrawTransform &rCopy, float iOffX, float iOffY) // ctor doing transform at given offset - doesn't init FlipDir (for temp use only)
{
SetTransformAt(rCopy, iOffX, iOffY);
}
C4DrawTransform()
{
// ctor without matrix initialization
FlipDir = 1;
}
C4DrawTransform(int32_t iFlipDir)
{
// ctor setting flipdir only
FlipDir = iFlipDir;
// set identity
Set(1,0,0,0,1,0,0,0,1);
}
~C4DrawTransform()
{
}
// do transform at given offset - doesn't init FlipDir (for temp use only)
void SetTransformAt(C4DrawTransform &rCopy, float iOffX, float iOffY);
void Set(float fA, float fB, float fC, float fD, float fE, float fF, float fG, float fH, float fI)
{
// set values; apply flipdir
CBltTransform::Set(fA*FlipDir, fB, fC, fD, fE, fF, fG, fH, fI);
}
void SetFlipDir(int32_t iNewFlipDir)
{
// no change?
if (iNewFlipDir == FlipDir) return;
// set and apply in matrix
FlipDir = iNewFlipDir; mat[0] = -mat[0];
}
bool IsIdentity()
{
return (mat[0]==1.0f) && (mat[1]==0.0f) && (mat[2]=0.0f)
&& (mat[3]==0.0f) && (mat[4]==1.0f) && (mat[5]=0.0f)
&& (mat[6]==0.0f) && (mat[7]==0.0f) && (mat[8]=1.0f)
&& (FlipDir==1); // flipdir must be 1, because otherwise matrices flipped by action+script would be removed
}
// default comparison op won't work :(
bool operator == (const C4DrawTransform &rCmp) const
{
return (mat[0]==rCmp.mat[0]) && (mat[1]==rCmp.mat[1]) && (mat[2]==rCmp.mat[2])
&& (mat[3]==rCmp.mat[3]) && (mat[4]==rCmp.mat[4]) && (mat[5]==rCmp.mat[5])
&& (mat[6]==rCmp.mat[6]) && (mat[7]==rCmp.mat[7]) && (mat[8]==rCmp.mat[8]) && (FlipDir == rCmp.FlipDir);
}
C4DrawTransform * operator&() { return this; }
void CompileFunc(StdCompiler *pComp);
// rounded pixel offsets generated by this transformation
int32_t GetXOffset() const { return static_cast<int32_t>(mat[2]); }
int32_t GetYOffset() const { return static_cast<int32_t>(mat[5]); }
};
#endif // C4ENGINE
class C4Facet
{
public:
SURFACE Surface;
int32_t X,Y,Wdt,Hgt;
public:
C4Facet();
C4Facet(SURFACE pSfc, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt)
: Surface(pSfc), X(iX), Y(iY), Wdt(iWdt), Hgt(iHgt) { }
public:
void Default();
void Set(CSurface &rSfc);
void Set(SURFACE nsfc, int32_t nx, int32_t ny, int32_t nwdt, int32_t nhgt);
void Set(const C4Facet &cpy) { *this=cpy; }
void Wipe();
void Expand(int32_t iLeft=0, int32_t iRight=0, int32_t iTop=0, int32_t iBottom=0);
void DrawTile(SURFACE sfcTarget, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt);
void DrawEnergyLevel(int32_t iLevel, int32_t iRange, int32_t iColor=45); // draw energy level using solid colors
void DrawEnergyLevelEx(int32_t iLevel, int32_t iRange, const C4Facet &gfx, int32_t bar_idx); // draw energy level using graphics
void DrawX(SURFACE sfcTarget, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iPhaseX=0, int32_t iPhaseY=0) const;
void DrawXFloat(SURFACE sfcTarget, float fX, float fY, float fWdt, float fHgt) const;
void DrawValue(C4Facet &cgo, int32_t iValue, int32_t iPhaseX=0, int32_t iPhaseY=0, int32_t iAlign=C4FCT_Center);
void DrawValue2(C4Facet &cgo, int32_t iValue1, int32_t iValue2, int32_t iPhaseX=0, int32_t iPhaseY=0, int32_t iAlign=C4FCT_Center, int32_t *piUsedWidth=NULL);
void Draw(C4Facet &cgo, BOOL fAspect=TRUE, int32_t iPhaseX=0, int32_t iPhaseY=0, BOOL fTransparent=TRUE);
void DrawFullScreen(C4Facet &cgo);
#ifdef C4ENGINE
void DrawT(SURFACE sfcTarget, int32_t iX, int32_t iY, int32_t iPhaseX, int32_t iPhaseY, C4DrawTransform *pTransform); // draw with transformation (if pTransform is assigned)
void DrawT(C4Facet &cgo, BOOL fAspect, int32_t iPhaseX, int32_t iPhaseY, C4DrawTransform *pTransform);
void DrawXT(SURFACE sfcTarget, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iPhaseX, int32_t iPhaseY, C4DrawTransform *pTransform);
#endif // C4ENGINE
void DrawClr(C4Facet &cgo, BOOL fAspect=TRUE, DWORD dwClr=0); // set surface color and draw
void DrawXClr(SURFACE sfcTarget, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, DWORD dwClr); // set surface color and draw
void DrawValue2Clr(C4Facet &cgo, int32_t iValue1, int32_t iValue2, DWORD dwClr); // set surface color and draw
void DrawXR(SURFACE sfcTarget, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iPhaseX=0, int32_t iPhaseY=0, int32_t r=0); // draw rotated
void Draw(SURFACE sfcTarget, float iX, float iY, int32_t iPhaseX=0, int32_t iPhaseY=0);
void DrawSectionSelect(C4Facet &cgo, int32_t iSelection, int32_t iMaxSelect);
bool GetPhaseNum(int32_t &rX, int32_t &rY); // return number of phases in this graphic
C4Facet GetSection(int32_t iSection);
C4Facet GetPhase(int iPhaseX=0, int iPhaseY=0);
C4Facet GetFraction(int32_t percentWdt, int32_t percentHgt=0, int32_t alignX=C4FCT_Left, int32_t alignY=C4FCT_Top);
C4Facet TruncateSection(int32_t iAlign=C4FCT_Left);
C4Facet Truncate(int32_t iAlign, int32_t iSize);
int32_t GetSectionCount();
int32_t GetWidthByHeight(int32_t iHeight) // calc width so it matches facet aspect to height
{ return iHeight * Wdt / (Hgt ? Hgt : 1); }
int32_t GetHeightByWidth(int32_t iWidth) // calc height so it matches facet aspect to width
{ return iWidth * Hgt / (Wdt ? Wdt : 1); }
#ifdef _WIN32
void Draw(HWND hWnd, int32_t iTx, int32_t iTy, int32_t iTWdt, int32_t iTHgt, BOOL fAspect=TRUE, int32_t iPhaseX=0, int32_t iPhaseY=0);
#endif
};
#endif // INC_C4Facet

View File

@ -0,0 +1,113 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* A facet that can hold its own surface and also target coordinates */
#ifndef INC_C4FacetEx
#define INC_C4FacetEx
#include <C4Facet.h>
#include <C4Surface.h>
const int C4FCT_Full = -1,
C4FCT_Height = -2,
C4FCT_Width = -3;
class C4TargetRect;
class CSurface;
class C4Rect;
class C4TargetFacet: public C4Facet
{
public:
C4TargetFacet() { Default(); }
~C4TargetFacet() { }
public:
float TargetX,TargetY;
public:
void Default() { TargetX=TargetY=0; C4Facet::Default(); }
void Clear() { Surface=NULL; }
void Set(const C4Facet &cpy) { TargetX=TargetY=0; C4Facet::Set(cpy); }
void Set(const C4TargetFacet &cpy) { *this = cpy; }
void Set(class CSurface *nsfc, int nx, int ny, int nwdt, int nhgt, float ntx=0, float nty=0);
void Set(class CSurface *nsfc, const C4Rect & r, float ntx=0, float nty=0);
void DrawBolt(int iX1, int iY1, int iX2, int iY2, BYTE bCol, BYTE bCol2);
void DrawLine(int iX1, int iY1, int iX2, int iY2, BYTE bCol1, BYTE bCol2);
public:
C4TargetFacet &operator = (const C4Facet& rhs)
{
Set(rhs.Surface,rhs.X,rhs.Y,rhs.Wdt,rhs.Hgt);
return *this;
}
void SetRect(C4TargetRect &rSrc);
};
// facet that can hold its own surface
class C4FacetSurface : public C4Facet
{
private:
C4Surface Face;
private:
C4FacetSurface(const C4FacetSurface &rCpy); // NO copy!
C4FacetSurface &operator = (const C4FacetSurface &rCpy); // NO copy assignment!
public:
C4FacetSurface() { Default(); }
~C4FacetSurface() { Clear(); }
void Default() { Face.Default(); C4Facet::Default(); }
void Clear() { Face.Clear(); }
void Set(const C4Facet &cpy) { Clear(); C4Facet::Set(cpy); }
void Set(const C4TargetFacet &cpy) { Clear(); C4Facet::Set(cpy); }
void Set(SURFACE nsfc, int nx, int ny, int nwdt, int nhgt, int ntx=0, int nty=0)
{ C4Facet::Set(nsfc, nx,ny,nwdt,nhgt); }
void Grayscale(int32_t iOffset = 0);
BOOL Create(int iWdt, int iHgt, int iWdt2=C4FCT_Full, int iHgt2=C4FCT_Full);
C4Surface &GetFace() { return Face; } // get internal face
BOOL CreateClrByOwner(CSurface *pBySurface);
BOOL EnsureSize(int iMinWdt, int iMinHgt);
bool EnsureOwnSurface();
BOOL Load(C4Group &hGroup, const char *szName, int iWdt=C4FCT_Full, int iHgt=C4FCT_Full, bool fOwnPal=false, bool fNoErrIfNotFound=false);
BOOL Load(BYTE *bpBitmap, int iWdt=C4FCT_Full, int iHgt=C4FCT_Full);
BOOL Save(C4Group &hGroup, const char *szName);
void GrabFrom(C4FacetSurface &rSource)
{
Clear(); Default();
Face.MoveFrom(&rSource.Face);
Set(rSource.Surface == &rSource.Face ? &Face : rSource.Surface, rSource.X, rSource.Y, rSource.Wdt, rSource.Hgt);
rSource.Default();
}
bool CopyFromSfcMaxSize(C4Surface &srcSfc, int32_t iMaxSize, uint32_t dwColor=0u);
};
// facet with source group ID; used to avoid doubled loading from same group
class C4FacetID : public C4FacetSurface
{
public:
int32_t idSourceGroup;
C4FacetID() : C4FacetSurface(), idSourceGroup(0) { } // ctor
void Default() { C4FacetSurface::Default(); idSourceGroup = 0; } // default to std values
void Clear() { C4FacetSurface::Clear(); idSourceGroup = 0; } // clear all data in class
};
#endif

View File

@ -0,0 +1,25 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Some class entries in the Windows registry */
#ifndef INC_C4FileClasses
#define INC_C4FileClasses
BOOL SetC4FileClasses(const char *szEnginePath);
#endif

View File

@ -0,0 +1,80 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2008-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// An inotify wrapper
#ifndef STD_FILE_MONITOR_H_INC
#define STD_FILE_MONITOR_H_INC
#include <StdScheduler.h>
#include <C4InteractiveThread.h>
#include <map>
class C4FileMonitor: public StdSchedulerProc, public C4InteractiveThread::Callback {
public:
typedef void (*ChangeNotify)(const char *, const char *);
C4FileMonitor(ChangeNotify pCallback);
~C4FileMonitor();
void StartMonitoring();
void AddDirectory(const char *szDir);
void AddTree(const char *szDir);
//void Remove(const char * file);
// StdSchedulerProc:
virtual bool Execute(int iTimeout = -1, pollfd * = 0);
// Signal for calling Execute()
#ifdef STDSCHEDULER_USE_EVENTS
virtual HANDLE GetEvent();
#else
virtual void GetFDs(std::vector<struct pollfd> & FDs);
#endif
// C4InteractiveThread::Callback:
virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData);
private:
bool fStarted;
ChangeNotify pCallback;
#if defined(HAVE_SYS_INOTIFY_H) || defined(HAVE_SYS_SYSCALL_H)
int fd;
std::map<int, const char *> watch_descriptors;
#elif defined(_WIN32)
HANDLE hEvent;
struct TreeWatch
{
HANDLE hDir;
StdCopyStrBuf DirName;
OVERLAPPED ov;
char Buffer[1024];
TreeWatch *Next;
};
TreeWatch *pWatches;
void HandleNotify(const char *szDir, const struct _FILE_NOTIFY_INFORMATION *pNotify);
#endif
};
#endif // STD_FILE_MONITOR_H_INC

View File

@ -0,0 +1,269 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2008-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// file selection dialogs
#ifndef INC_C4FileSelDlg
#define INC_C4FileSelDlg
#include <C4Gui.h>
// callback handler for file selection dialog
class C4FileSel_BaseCB
{
public:
C4FileSel_BaseCB() {}
virtual ~C4FileSel_BaseCB() {}
public:
virtual void OnFileSelected(const char *szFilename) = 0;
};
template <class CB> class C4FileSel_CBEx : public C4FileSel_BaseCB
{
public:
typedef void (CB::*FileSelFunc)(const char *szFilename, int32_t idToken);
private:
CB *pCBClass;
FileSelFunc SelFunc;
int32_t idToken;
public:
virtual void OnFileSelected(const char *szFilename)
{ if (pCBClass && SelFunc) (pCBClass->*SelFunc)(szFilename, idToken); }
public:
C4FileSel_CBEx(CB * pCBClass, FileSelFunc SelFunc, int32_t idToken) : pCBClass(pCBClass), SelFunc(SelFunc), idToken(idToken) { }
};
// dialog to select one or more files
class C4FileSelDlg : public C4GUI::Dialog
{
public:
class ListItem : public C4GUI::Control
{
protected:
StdStrBuf sFilename; // full path to file
virtual bool IsFocusOnClick() { return false; } // do not focus; keep focus on listbox
public:
ListItem(const char *szFilename);
virtual ~ListItem();
const char *GetFilename() { return sFilename.getData(); }
// multisel-checkbox-options
virtual bool IsChecked() const { return false; }
virtual void SetChecked(bool fChecked) {}
virtual bool IsGrayed() const { return false; }
virtual bool UserToggleCheck() { return false; }
};
class DefaultListItem : public ListItem
{
private:
typedef ListItem BaseClass;
class C4GUI::Icon *pIco; class C4GUI::Label *pLbl;
class C4GUI::CheckBox *pCheck;
class C4KeyBinding *pKeyCheck; // space activates/deactivates selected file
bool fGrayed;
protected:
void UpdateOwnPos();
public:
DefaultListItem(const char *szFilename, bool fTruncateExtension, bool fCheckbox, bool fGrayed, C4GUI::Icons eIcon);
virtual ~DefaultListItem();
virtual bool IsChecked() const;
virtual void SetChecked(bool fChecked);
virtual bool IsGrayed() const { return fGrayed; }
virtual bool UserToggleCheck();
};
private:
typedef C4GUI::Dialog BaseClass;
C4KeyBinding *pKeyRefresh, *pKeyEnterOverride;
C4GUI::ComboBox *pLocationComboBox;
C4GUI::ListBox *pFileListBox;
C4GUI::TextWindow *pSelectionInfoBox;
C4GUI::Button *btnOK;
StdCopyStrBuf sTitle; // dlg title
StdCopyStrBuf sPath; // current path
struct Location
{
StdCopyStrBuf sName;
StdCopyStrBuf sPath;
};
Location *pLocations;
int32_t iLocationCount;
int32_t iCurrentLocationIndex;
ListItem *pSelection;
C4FileSel_BaseCB *pSelCallback;
void UpdateFileList(); // rebuild file listbox from sPath
protected:
virtual void OnShown();
virtual void UserClose(bool fOK); // allow OK only if something is sth is selected
virtual void OnClosed(bool fOK); // callback when dlg got closed
virtual const char *GetFileMask() const { return NULL; }
virtual bool IsMultiSelection() const { return false; } // if true, files are checked/unchecked using checkboxes
virtual bool IsItemGrayed(const char *szFilename) const { return false; }
virtual void UpdateSelection();
virtual bool HasNoneItem() const { return false; } // if true, an empty item can be selected
virtual bool HasPreviewArea() const { return true; }
virtual bool HasExtraOptions() const { return false; }
virtual void AddExtraOptions(const C4Rect &rcOptionsRect) {}
virtual C4GUI::Icons GetFileItemIcon() const { return C4GUI::Ico_None; }
virtual int32_t GetFileSelColWidth() const { return 0; } // width of each file selection element; 0 for default all listbox
void OnSelChange(class C4GUI::Element *pEl) { UpdateSelection(); }
void OnSelDblClick(class C4GUI::Element *pEl);
bool KeyRefresh() { UpdateFileList(); return true; }
void OnLocationComboFill(C4GUI::ComboBox_FillCB *pFiller);
bool OnLocationComboSelChange(C4GUI::ComboBox *pForCombo, int32_t idNewSelection);
void AddLocation(const char *szName, const char *szPath); // add location to be shown in dropdown list
void AddCheckedLocation(const char *szName, const char *szPath); // add location to be shown in dropdown list, only if path exists and isn't added yet
int32_t GetCurrentLocationIndex() const;
void SetCurrentLocation(int32_t idx, bool fRefresh);
virtual ListItem *CreateListItem(const char *szFilename);
virtual void BeginFileListUpdate() {}
virtual void EndFileListUpdate() {}
public:
C4FileSelDlg(const char *szRootPath, const char *szTitle, C4FileSel_BaseCB *pSelCallback, bool fInitElements=true);
virtual ~C4FileSelDlg();
void InitElements();
void SetPath(const char *szNewPath, bool fRefresh=true);
void SetSelection(const char *szNewSelection, bool fFilenameOnly);
StdStrBuf GetSelection(const char *szFixedSelection, bool fFilenameOnly) const; // get single selected file for single selection dlg ';'-seperated list for multi selection dlg
};
// dialog to select a player file
class C4PlayerSelDlg : public C4FileSelDlg
{
protected:
virtual const char *GetFileMask() const { return C4CFN_PlayerFiles; }
virtual C4GUI::Icons GetFileItemIcon() const { return C4GUI::Ico_Player; }
public:
C4PlayerSelDlg(C4FileSel_BaseCB *pSelCallback);
};
// dialog to select definition files
class C4DefinitionSelDlg : public C4FileSelDlg
{
private:
StdStrBuf sFixedSelection; // initial selection which cannot be deselected
protected:
virtual void OnShown();
virtual const char *GetFileMask() const { return C4CFN_DefFiles; }
virtual bool IsMultiSelection() const { return true; }
virtual bool IsItemGrayed(const char *szFilename) const;
virtual C4GUI::Icons GetFileItemIcon() const { return C4GUI::Ico_Definition; }
public:
C4DefinitionSelDlg(C4FileSel_BaseCB *pSelCallback, const char *szFixedSelection);
static bool SelectDefinitions(C4GUI::Screen *pOnScreen, StdStrBuf *pSelection);
};
// dialog to select portrait files
class C4PortraitSelDlg : public C4FileSelDlg
{
public:
enum { ImagePreviewSize = 100 };
private:
class ListItem : public C4FileSelDlg::ListItem
{
private:
bool fError; // loading error
bool fLoaded; // image loaded but not yet scaled
C4FacetSurface fctImage; // portrait, if loaded
C4FacetSurface fctLoadedImage; // image as loaded by background thread. Must be scaled by main thread
StdCopyStrBuf sFilenameLabelText;
protected:
void DrawElement(C4TargetFacet &cgo);
public:
ListItem(const char *szFilename);
void Load();
};
// portrait loader thread
class LoaderThread : public StdThread
{
private:
std::list<ListItem *> LoadItems; // items to be loaded by this thread
public:
LoaderThread() {}
virtual ~LoaderThread() { Stop(); }
void ClearLoadItems(); // stops thread
void AddLoadItem(ListItem *pItem); // not to be called when thread is running!
public:
virtual void Execute();
};
private:
C4GUI::CheckBox *pCheckSetPicture, *pCheckSetBigIcon;
bool fDefSetPicture, fDefSetBigIcon;
LoaderThread ImageLoader;
protected:
void OnClosed(bool fOK);
virtual const char *GetFileMask() const { return C4CFN_ImageFiles; }
virtual bool HasNoneItem() const { return true; } // if true, a special <none> item can be selected
virtual bool HasPreviewArea() const { return false; } // no preview area. Preview images directly
virtual bool HasExtraOptions() const { return true; }
virtual void AddExtraOptions(const C4Rect &rcOptionsRect);
virtual int32_t GetFileSelColWidth() const { return ImagePreviewSize; } // width of each file selection element
virtual C4FileSelDlg::ListItem *CreateListItem(const char *szFilename);
virtual void BeginFileListUpdate();
virtual void EndFileListUpdate();
virtual void OnIdle();
public:
C4PortraitSelDlg(C4FileSel_BaseCB *pSelCallback, bool fSetPicture, bool fSetBigIcon);
bool IsSetPicture() const { return pCheckSetPicture ? pCheckSetPicture->GetChecked() : fDefSetPicture; }
bool IsSetBigIcon() const { return pCheckSetBigIcon ? pCheckSetBigIcon->GetChecked() : fDefSetBigIcon; }
static bool SelectPortrait(C4GUI::Screen *pOnScreen, StdStrBuf *pSelection, bool *pfSetPicture, bool *pfSetBigIcon);
};
#endif // INC_C4FileSelDlg

View File

@ -0,0 +1,475 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#ifndef C4FINDOBJECT_H
#define C4FINDOBJECT_H
#include "C4Id.h"
#include "C4Shape.h"
#include "C4Value.h"
#include "C4Aul.h"
// Condition map
enum C4FindObjectCondID
{
C4FO_Not = 1,
C4FO_And = 2,
C4FO_Or = 3,
C4FO_Exclude = 5,
C4FO_InRect = 10,
C4FO_AtPoint = 11,
C4FO_AtRect = 12,
C4FO_OnLine = 13,
C4FO_Distance = 14,
C4FO_ID = 20,
C4FO_OCF = 21,
C4FO_Category = 22,
C4FO_Action = 30,
C4FO_ActionTarget = 31,
C4FO_Container = 40,
C4FO_AnyContainer = 41,
C4FO_Owner = 50,
C4FO_Func = 60,
C4FO_Layer = 70,
};
// Sort map - using same values as C4FindObjectCondID!
enum C4SortObjectCondID
{
C4SO_First = 100, // no sort condition smaller than this
C4SO_Reverse = 101, // reverse sort order
C4SO_Multiple = 102, // multiple sorts; high priority first; lower priorities if higher prio returned equal
C4SO_Distance = 110, // nearest first
C4SO_Random = 120, // random first
C4SO_Speed = 130, // slowest first
C4SO_Mass = 140, // lightest first
C4SO_Value = 150, // cheapest first
C4SO_Func = 160, // least return values first
C4SO_Last = 200, // no sort condition larger than this
};
// Base class
class C4FindObject
{
friend class C4FindObjectNot;
friend class C4FindObjectAnd;
friend class C4FindObjectOr;
class C4SortObject *pSort;
public:
C4FindObject() : pSort(NULL) { }
virtual ~C4FindObject();
static C4FindObject *CreateByValue(const C4Value &Data, C4SortObject **ppSortObj=NULL); // createFindObject or SortObject - if ppSortObj==NULL, SortObject is not allowed
int32_t Count(const C4ObjectList &Objs); // Counts objects for which the condition is true
C4Object *Find(const C4ObjectList &Objs); // Returns first object for which the condition is true
C4ValueArray *FindMany(const C4ObjectList &Objs); // Returns all objects for which the condition is true
int32_t Count(const C4ObjectList &Objs, const C4LSectors &Sct); // Counts objects for which the condition is true
C4Object *Find(const C4ObjectList &Objs, const C4LSectors &Sct); // Returns first object for which the condition is true
C4ValueArray *FindMany(const C4ObjectList &Objs, const C4LSectors &Sct); // Returns all objects for which the condition is true
void SetSort(C4SortObject *pToSort);
protected:
// Overridables
virtual bool Check(C4Object *pObj) = 0;
virtual C4Rect *GetBounds() { return NULL; }
virtual bool UseShapes() { return false; }
virtual bool IsImpossible() { return false; }
virtual bool IsEnsured() { return false; }
private:
void CheckObjectStatus(C4ValueArray *pArray);
};
// Combinators
class C4FindObjectNot : public C4FindObject
{
public:
C4FindObjectNot(C4FindObject *pCond)
: pCond(pCond) { }
virtual ~C4FindObjectNot();
private:
C4FindObject *pCond;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsImpossible() { return pCond->IsEnsured(); }
virtual bool IsEnsured() { return pCond->IsImpossible(); }
};
class C4FindObjectAnd : public C4FindObject
{
public:
C4FindObjectAnd(int32_t iCnt, C4FindObject **ppConds, bool fFreeArray = true);
virtual ~C4FindObjectAnd();
private:
int32_t iCnt;
C4FindObject **ppConds; bool fFreeArray; bool fUseShapes;
C4Rect Bounds; bool fHasBounds;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return fHasBounds ? &Bounds : NULL; }
virtual bool UseShapes() { return fUseShapes; }
virtual bool IsEnsured() { return !iCnt; }
virtual bool IsImpossible();
};
class C4FindObjectOr : public C4FindObject
{
public:
C4FindObjectOr(int32_t iCnt, C4FindObject **ppConds);
virtual ~C4FindObjectOr();
private:
int32_t iCnt;
C4FindObject **ppConds;
C4Rect Bounds; bool fHasBounds;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return fHasBounds ? &Bounds : NULL; }
virtual bool IsEnsured();
virtual bool IsImpossible() { return !iCnt; }
};
// Primitive conditions
class C4FindObjectExclude : public C4FindObject
{
public:
C4FindObjectExclude(C4Object *pExclude)
: pExclude(pExclude) { }
private:
C4Object *pExclude;
protected:
virtual bool Check(C4Object *pObj);
};
class C4FindObjectID : public C4FindObject
{
public:
C4FindObjectID(C4ID id)
: id(id) { }
private:
C4ID id;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsImpossible();
};
class C4FindObjectInRect : public C4FindObject
{
public:
C4FindObjectInRect(const C4Rect &rect)
: rect(rect) { }
private:
C4Rect rect;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return &rect; }
virtual bool IsImpossible();
};
class C4FindObjectAtPoint : public C4FindObject
{
public:
C4FindObjectAtPoint(int32_t x, int32_t y)
: bounds(x, y, 1, 1) { }
private:
C4Rect bounds;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return &bounds; }
virtual bool UseShapes() { return true; }
};
class C4FindObjectAtRect : public C4FindObject
{
public:
C4FindObjectAtRect(int32_t x, int32_t y, int32_t wdt, int32_t hgt)
: bounds(x, y, wdt, hgt) { }
private:
C4Rect bounds;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return &bounds; }
virtual bool UseShapes() { return true; }
};
class C4FindObjectOnLine : public C4FindObject
{
public:
C4FindObjectOnLine(int32_t x, int32_t y, int32_t x2, int32_t y2)
: x(x), y(y), x2(x2), y2(y2), bounds(x, y, 1, 1) { bounds.Add(C4Rect(x2, y2, 1,1)); }
private:
int32_t x, y, x2, y2;
C4Rect bounds;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return &bounds; }
virtual bool UseShapes() { return true; }
};
class C4FindObjectDistance : public C4FindObject
{
public:
C4FindObjectDistance(int32_t x, int32_t y, int32_t r)
: x(x), y(y), r2(r*r), bounds(x-r, y-r, 2*r+1, 2*r+1) { }
private:
int32_t x, y, r2;
C4Rect bounds;
protected:
virtual bool Check(C4Object *pObj);
virtual C4Rect *GetBounds() { return &bounds; }
};
class C4FindObjectOCF : public C4FindObject
{
public:
C4FindObjectOCF(int32_t ocf)
: ocf(ocf) { }
private:
int32_t ocf;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsImpossible();
};
class C4FindObjectCategory : public C4FindObject
{
public:
C4FindObjectCategory(int32_t iCategory)
: iCategory(iCategory) { }
private:
int32_t iCategory;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsEnsured();
};
class C4FindObjectAction : public C4FindObject
{
public:
C4FindObjectAction(const char *szAction)
: szAction(szAction) { }
private:
const char *szAction;
protected:
virtual bool Check(C4Object *pObj);
};
class C4FindObjectActionTarget : public C4FindObject
{
public:
C4FindObjectActionTarget(C4Object *pActionTarget)
: pActionTarget(pActionTarget) { }
private:
C4Object *pActionTarget;
protected:
virtual bool Check(C4Object *pObj);
};
class C4FindObjectContainer : public C4FindObject
{
public:
C4FindObjectContainer(C4Object *pContainer)
: pContainer(pContainer) { }
private:
C4Object *pContainer;
protected:
virtual bool Check(C4Object *pObj);
};
class C4FindObjectAnyContainer : public C4FindObject
{
public:
C4FindObjectAnyContainer() { }
protected:
virtual bool Check(C4Object *pObj);
};
class C4FindObjectOwner : public C4FindObject
{
public:
C4FindObjectOwner(int32_t iOwner)
: iOwner(iOwner) { }
private:
int32_t iOwner;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsImpossible();
};
class C4FindObjectFunc : public C4FindObject
{
public:
C4FindObjectFunc(const char *Name): Name(Name) { }
void SetPar(int i, const C4Value &val);
private:
const char * Name;
C4AulParSet Pars;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsImpossible();
};
class C4FindObjectLayer : public C4FindObject
{
public:
C4FindObjectLayer(C4Object *pLayer) : pLayer(pLayer) {}
private:
C4Object *pLayer;
protected:
virtual bool Check(C4Object *pObj);
virtual bool IsImpossible();
};
// result sorting
class C4SortObject
{
public:
C4SortObject() {}
virtual ~C4SortObject() {}
public:
// Overridables
virtual int32_t Compare(C4Object *pObj1, C4Object *pObj2) = 0; // return value <0 if obj1 is to be sorted before obj2
virtual bool PrepareCache(const C4ValueList *pObjs) { return false; }
virtual int32_t CompareCache(int32_t iObj1, int32_t iObj2, C4Object *pObj1, C4Object *pObj2) { return Compare(pObj1, pObj2); }
public:
static C4SortObject *CreateByValue(const C4Value &Data);
static C4SortObject *CreateByValue(int32_t iType, const C4ValueArray &Data);
void SortObjects(C4ValueArray *pArray);
};
class C4SortObjectByValue : public C4SortObject
{
public:
C4SortObjectByValue();
virtual ~C4SortObjectByValue();
private:
int32_t *pVals;
int32_t iSize;
public:
// Overridables
virtual int32_t Compare(C4Object *pObj1, C4Object *pObj2);
virtual int32_t CompareGetValue(C4Object *pOf) = 0;
virtual bool PrepareCache(const C4ValueList *pObjs);
virtual int32_t CompareCache(int32_t iObj1, int32_t iObj2, C4Object *pObj1, C4Object *pObj2);
};
class C4SortObjectReverse : public C4SortObject // reverse sort
{
public:
C4SortObjectReverse(C4SortObject *pSort)
: C4SortObject(), pSort(pSort) {}
virtual ~C4SortObjectReverse();
private:
C4SortObject *pSort;
protected:
int32_t Compare(C4Object *pObj1, C4Object *pObj2);
virtual bool PrepareCache(const C4ValueList *pObjs);
virtual int32_t CompareCache(int32_t iObj1, int32_t iObj2, C4Object *pObj1, C4Object *pObj2);
};
class C4SortObjectMultiple : public C4SortObject // apply next sort if previous compares to equality
{
public:
C4SortObjectMultiple(int32_t iCnt, C4SortObject **ppSorts, bool fFreeArray = true)
: C4SortObject(), iCnt(iCnt), ppSorts(ppSorts), fFreeArray(fFreeArray) {}
virtual ~C4SortObjectMultiple();
private:
bool fFreeArray;
int32_t iCnt;
C4SortObject **ppSorts;
protected:
int32_t Compare(C4Object *pObj1, C4Object *pObj2);
virtual bool PrepareCache(const C4ValueList *pObjs);
virtual int32_t CompareCache(int32_t iObj1, int32_t iObj2, C4Object *pObj1, C4Object *pObj2);
};
class C4SortObjectDistance : public C4SortObjectByValue // sort by distance from point x/y
{
public:
C4SortObjectDistance(int iX, int iY)
: C4SortObjectByValue(), iX(iX), iY(iY) {}
private:
int iX, iY;
protected:
int32_t CompareGetValue(C4Object *pFor);
};
class C4SortObjectRandom : public C4SortObjectByValue // randomize order
{
public:
C4SortObjectRandom() : C4SortObjectByValue(){}
protected:
int32_t CompareGetValue(C4Object *pFor);
};
class C4SortObjectSpeed : public C4SortObjectByValue // sort by object xdir/ydir
{
public:
C4SortObjectSpeed() : C4SortObjectByValue(){}
protected:
int32_t CompareGetValue(C4Object *pFor);
};
class C4SortObjectMass : public C4SortObjectByValue // sort by mass
{
public:
C4SortObjectMass() : C4SortObjectByValue(){}
protected:
int32_t CompareGetValue(C4Object *pFor);
};
class C4SortObjectValue : public C4SortObjectByValue // sort by value
{
public:
C4SortObjectValue() : C4SortObjectByValue(){}
protected:
int32_t CompareGetValue(C4Object *pFor);
};
class C4SortObjectFunc : public C4SortObjectByValue // sort by script function
{
public:
C4SortObjectFunc(const char * Name): Name(Name) { }
void SetPar(int i, const C4Value &val);
private:
const char * Name;
C4AulParSet Pars;
protected:
int32_t CompareGetValue(C4Object *pFor);
};
#endif

View File

@ -0,0 +1,52 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Core component of a folder */
#ifndef INC_C4Folder
#define INC_C4Folder
const int C4MaxFolderSort = 4096;
class C4FolderHead
{
public:
int32_t Index; // Folder index in scenario selection dialog
char Sort[C4MaxFolderSort + 1]; // Folder-defined group sort list (to be used for folder maps)
public:
void Default();
void CompileFunc(StdCompiler *pComp);
};
class C4Folder
{
public:
C4Folder();
public:
C4FolderHead Head;
public:
void Default();
//void Clear();
BOOL Load(C4Group &hGroup);
//BOOL Save(C4Group &hGroup);
void CompileFunc(StdCompiler *pComp);
protected:
BOOL Compile(const char *szSource);
//BOOL Decompile(char **ppOutput, int32_t *ipSize);
};
#endif // INC_C4Folder

View File

@ -0,0 +1,98 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2004-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// engine font loading
#ifndef INC_C4Fonts
#define INC_C4Fonts
#include <vector>
class C4Group;
class C4GroupSet;
class C4Config;
class CStdFont;
// font definition to be read
class C4FontDef
{
public:
StdCopyStrBuf Name; // font name
int32_t iSize; // average font height of base font
StdCopyStrBuf LogFont; // very small font used for log messages
StdCopyStrBuf SmallFont; // pretty small font used in tiny dialogs
StdCopyStrBuf Font; // base font used for anything
StdCopyStrBuf CaptionFont; // caption font used in GUI
StdCopyStrBuf TitleFont; // font used to draw the loader caption
C4FontDef(): iSize(0) { } // ctor
void CompileFunc(StdCompiler * pComp);
};
// holder class for loaded ttf fonts
class C4VectorFont
{
protected:
StdStrBuf Name;
StdBuf Data;
CStdVectorFont * pFont;
char FileName[_MAX_PATH+1]; // file name of temprarily extracted file
bool fIsTempFile; // if set, the file resides at the temp path and is to be deleted
public:
C4VectorFont *pNext; // next font
C4VectorFont() : pFont(NULL), fIsTempFile(false), pNext(NULL) { *FileName=0; } // ctor
~C4VectorFont(); // dtor - releases font and deletes temp file
bool Init(C4Group &hGrp, const char *szFilename, C4Config &rCfg); // load font from group
bool Init(const char *szFacename, int32_t iSize, uint32_t dwWeight, const char *szCharSet); // load system font specified by face name
void Init(const char *szName, CStdVectorFont *pFont); // init from a font that has been laoded already
friend class C4FontLoader;
};
// font loader
class C4FontLoader
{
protected:
std::vector<C4FontDef> FontDefs; // array of loaded font definitions
C4VectorFont *pVectorFonts; // vector fonts loaded and extracted to temp store
public:
// enum of different fonts used in the clonk engine
enum FontType { C4FT_Log, C4FT_MainSmall, C4FT_Main, C4FT_Caption, C4FT_Title };
public:
C4FontLoader() : pVectorFonts(NULL) { } // ctor
~C4FontLoader() { Clear(); } // dtor
void Clear(); // clear loaded fonts
int32_t LoadDefs(C4Group &hGroup, C4Config &rCfg); // load font definitions from group file; return number of loaded font defs
bool IsFontLoaded(const char *szFontName); // return whether given font name is found in the list
const char *GetFontNameByIndex(int32_t iIndex); // get indexed font name; not doubling fonts of same name
int32_t GetClosestAvailableSize(const char *szFontName, int32_t iWantedSize); // return possible font size that mathces the desired value closest
void AddVectorFont(C4VectorFont *pAddFont); // adds a new font to the list
#ifdef C4ENGINE
bool InitFont(CStdFont &rFont, C4VectorFont * pFont, int32_t iSize, uint32_t dwWeight, bool fDoShadow);
// init a font class of the given type
// iSize is always the size of the normal font, which is adjusted for larger (title) and smaller (log) font types
bool InitFont(CStdFont &rFont, const char *szFontName, FontType eType, int32_t iSize, C4GroupSet *pGfxGroups, bool fDoShadow=true);
#endif
};
#endif // INC_C4Fonts

View File

@ -0,0 +1,60 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Main class to execute the game fullscreen mode */
#ifndef INC_C4FullScreen
#define INC_C4FullScreen
#include "C4MainMenu.h"
#include <StdWindow.h>
#ifndef BIG_C4INCLUDE
#include "C4Game.h"
#endif
bool IsKeyDown(int iKey);
class C4FullScreen: public CStdWindow
{
public:
C4MainMenu *pMenu;
public:
C4FullScreen();
~C4FullScreen();
void Execute();
BOOL Restart();
BOOL ViewportCheck();
BOOL OpenGame(const char *szCmdLine);
bool ShowAbortDlg(); // show game abort dialog (Escape pressed)
bool ActivateMenuMain();
BOOL MenuCommand(const char *szCommand);
void CloseMenu();
bool MenuKeyControl(BYTE byCom); // direct keyboard callback
// User requests close
virtual void Close();
virtual void CharIn(const char * c);
#ifdef USE_X11
virtual void HandleMessage (XEvent &e);
#elif USE_SDL_MAINLOOP
virtual void HandleMessage (SDL_Event &e);
#endif
};
extern C4FullScreen FullScreen;
#endif

379
engine/inc/C4Game.h 100644
View File

@ -0,0 +1,379 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Main class to run the game */
#ifndef INC_C4Game
#define INC_C4Game
#ifdef C4ENGINE
#include <C4Def.h>
#include <C4Texture.h>
#include <C4RankSystem.h>
#include <C4GraphicsSystem.h>
#include <C4GraphicsResource.h>
#include <C4GameMessage.h>
#include <C4MouseControl.h>
#include <C4MessageInput.h>
#include <C4Weather.h>
#include <C4Material.h>
#include <C4GameObjects.h>
#include <C4Landscape.h>
#include <C4Scenario.h>
#include <C4MassMover.h>
#include <C4PXS.h>
#include <C4PlayerList.h>
#include <C4Teams.h>
#include <C4PlayerInfo.h>
#include <C4Control.h>
#include <C4PathFinder.h>
#include <C4ComponentHost.h>
#include <C4ScriptHost.h>
#include <C4Particles.h>
#include <C4GroupSet.h>
#include <C4Extra.h>
#include <C4GameControl.h>
#include <C4Effects.h>
#include <C4Fonts.h>
#include "C4LangStringTable.h"
#include "C4Scoreboard.h"
#include <C4Network2.h>
#include <C4Scenario.h>
#include <C4Client.h>
#include <C4Network2Reference.h>
#include <C4VideoPlayback.h>
#include <C4RoundResults.h>
class C4Game
{
private:
// used as StdCompiler-parameter
struct CompileSettings
{
bool fScenarioSection;
bool fPlayers;
bool fExact;
CompileSettings(bool fScenarioSection, bool fPlayers, bool fExact)
: fScenarioSection(fScenarioSection), fPlayers(fPlayers), fExact(fExact) { }
};
// struct of keyboard set and indexed control key
struct C4KeySetCtrl
{
int32_t iKeySet, iCtrl;
C4KeySetCtrl(int32_t iKeySet, int32_t iCtrl) : iKeySet(iKeySet), iCtrl(iCtrl) {}
};
public:
C4Game();
~C4Game();
public:
C4DefList Defs;
C4TextureMap TextureMap;
C4RankSystem Rank;
C4GraphicsSystem GraphicsSystem;
C4MessageInput MessageInput;
C4GraphicsResource GraphicsResource;
C4Network2 Network;
C4ClientList &Clients; // Shortcut
C4GameParameters Parameters;
C4TeamList &Teams; // Shortcut
C4PlayerInfoList &PlayerInfos; // Shortcut
C4PlayerInfoList &RestorePlayerInfos; // Shortcut
C4RoundResults RoundResults;
C4GameMessageList Messages;
C4MouseControl MouseControl;
C4Weather Weather;
C4MaterialMap Material;
C4GameObjects Objects;
C4ObjectList BackObjects; // objects in background (C4D_Background)
C4ObjectList ForeObjects; // objects in foreground (C4D_Foreground)
C4Landscape Landscape;
C4Scenario C4S;
C4ComponentHost Info;
C4ComponentHost Title;
C4ComponentHost Names;
C4ComponentHost GameText;
C4AulScriptEngine ScriptEngine;
C4GameScriptHost Script;
C4LangStringTable MainSysLangStringTable, ScenarioLangStringTable, ScenarioSysLangStringTable;
C4MassMoverSet MassMover;
C4PXSSystem PXS;
C4ParticleSystem Particles;
C4PlayerList Players;
StdStrBuf PlayerNames;
C4GameControl Control;
C4Control &Input; // shortcut
C4PathFinder PathFinder;
C4TransferZones TransferZones;
C4Group ScenarioFile;
C4GroupSet GroupSet;
C4Group *pParentGroup;
C4Extra Extra;
C4GUIScreen *pGUI;
C4ScenarioSection *pScenarioSections, *pCurrentScenarioSection;
C4Effect *pGlobalEffects;
#ifndef USE_CONSOLE
// We don't need fonts when we don't have graphics
C4FontLoader FontLoader;
#endif
C4Scoreboard Scoreboard;
C4VideoPlayer VideoPlayer;
class C4Network2Stats *pNetworkStatistics; // may be NULL if no statistics are recorded
class C4KeyboardInput &KeyboardInput;
class C4FileMonitor *pFileMonitor;
class C4GameSec1Timer *pSec1Timer;
char CurrentScenarioSection[C4MaxName+1];
char ScenarioFilename[_MAX_PATH+1];
StdCopyStrBuf ScenarioTitle;
char PlayerFilenames[20*_MAX_PATH+1];
char DefinitionFilenames[20*_MAX_PATH+1];
char DirectJoinAddress[_MAX_PATH+1];
class C4Network2Reference *pJoinReference;
int32_t StartupPlayerCount;
int32_t FPS,cFPS;
int32_t HaltCount;
bool GameOver;
bool Evaluated;
bool GameOverDlgShown;
bool fScriptCreatedObjects;
bool fLobby;
int32_t iLobbyTimeout;
bool fObserve;
bool fReferenceDefinitionOverride;
bool NetworkActive;
bool Record;
bool RegJoinOnly; // default false; set to true only by command line parameter or in console builds
StdStrBuf RecordDumpFile;
StdStrBuf RecordStream;
bool TempScenarioFile;
bool fPreinited; // set after PreInit has been called; unset by Clear and Default
int32_t FrameCounter;
int32_t iTick2,iTick3,iTick5,iTick10,iTick35,iTick255,iTick500,iTick1000;
bool TimeGo;
int32_t Time;
int32_t StartTime;
int32_t InitProgress; int32_t LastInitProgress; int32_t LastInitProgressShowTime;
int32_t RandomSeed;
int32_t ObjectEnumerationIndex;
int32_t Rules;
bool GameGo;
bool FullSpeed;
int32_t FrameSkip; bool DoSkipFrame;
uint32_t FoWColor; // FoW-color; may contain transparency
bool fResortAnyObject; // if set, object list will be checked for unsorted objects next frame
bool IsRunning; // (NoSave) if set, the game is running; if not, just the startup message board is painted
bool PointersDenumerated; // (NoSave) set after object pointers have been denumerated
size_t StartupLogPos, QuitLogPos; // current log positions when game was last started and cleared
bool fQuitWithError; // if set, game shut down irregularly
int32_t iMusicLevel; // scenario-defined music level
// current play list
StdCopyStrBuf PlayList;
bool DebugMode;
// next mission to be played after this one
StdCopyStrBuf NextMission, NextMissionText, NextMissionDesc;
public:
// Init and execution
void Default();
void Clear();
void Abort(bool fApproved = false); // hard-quit on Esc+Y (/J/O)
void Evaluate();
void ShowGameOverDlg();
bool DoKeyboardInput(C4KeyCode vk_code, C4KeyEventType eEventType, bool fAlt, bool fCtrl, bool fShift, bool fRepeated, class C4GUI::Dialog *pForDialog=NULL, bool fPlrCtrlOnly=false);
void DrawCursors(C4TargetFacet &cgo, int32_t iPlayer);
bool LocalControlKey(C4KeyCodeEx key, C4KeySetCtrl Ctrl);
bool LocalControlKeyUp(C4KeyCodeEx key, C4KeySetCtrl Ctrl);
void LocalPlayerControl(int32_t iPlayer, int32_t iCom);
void FixRandom(int32_t iSeed);
bool Init();
bool PreInit();
void ParseCommandLine(const char *szCmdLine);
BOOL Execute();
class C4Player *JoinPlayer(const char *szFilename, int32_t iAtClient, const char *szAtClientName, C4PlayerInfo *pInfo);
BOOL DoGameOver();
bool CanQuickSave();
BOOL QuickSave(const char *strFilename, const char *strTitle, bool fForceSave=false);
void SetInitProgress(float fToProgress);
void OnResolutionChanged(unsigned int iXRes, unsigned int iYRes); // update anything that's dependant on screen resolution
void InitFullscreenComponents(bool fRunning);
bool ToggleChat();
// Pause
bool TogglePause();
bool Pause();
bool Unpause();
bool IsPaused();
// Network
void Synchronize(BOOL fSavePlayerFiles);
void SyncClearance();
BOOL ReSync();
void SyncCheckFiles(); // check if files are in sync
// Editing
BOOL DropFile(const char *szFilename, float iX, float iY);
BOOL CreateViewport(int32_t iPlayer, bool fSilent=false);
BOOL DropDef(C4ID id, float iX, float iY);
BOOL LoadDef(const char *szFilename);
BOOL ReloadFile(const char *szPath);
BOOL ReloadDef(C4ID id);
BOOL ReloadParticle(const char *szName);
// Object functions
void ClearPointers(C4Object *cobj);
C4Object *CreateObject(C4ID type, C4Object *pCreator, int32_t owner=NO_OWNER,
int32_t x=50, int32_t y=50, int32_t r=0,
FIXED xdir=Fix0, FIXED ydir=Fix0, FIXED rdir=Fix0, int32_t iController=NO_OWNER);
C4Object *CreateObjectConstruction(C4ID type,
C4Object *pCreator,
int32_t owner,
int32_t ctx=0, int32_t bty=0,
int32_t con=1, BOOL terrain=FALSE);
C4Object *CreateInfoObject(C4ObjectInfo *cinf, int32_t owner,
int32_t tx=50, int32_t ty=50);
void BlastObjects(int32_t tx, int32_t ty, int32_t level, C4Object *inobj, int32_t iCausedBy, C4Object *pByObj);
void ShakeObjects(int32_t tx, int32_t ry, int32_t range);
C4Object *OverlapObject(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt,
int32_t category);
C4Object *FindObject(C4ID id,
int32_t iX=0, int32_t iY=0, int32_t iWdt=0, int32_t iHgt=0,
DWORD ocf=OCF_All,
const char *szAction=NULL, C4Object *pActionTarget=NULL,
C4Object *pExclude=NULL,
C4Object *pContainer=NULL,
int32_t iOwner=ANY_OWNER,
C4Object *pFindNext=NULL);
C4Object *FindVisObject( // find object in view at pos, regarding parallaxity and visibility (but not distance)
float tx, float ty, int32_t iPlr, const C4Facet &fctViewport,
float iX=0, float iY=0, float iWdt=0, float iHgt=0,
DWORD ocf=OCF_All,
C4Object *pExclude=NULL,
int32_t iOwner=ANY_OWNER,
C4Object *pFindNext=NULL);
int32_t ObjectCount(C4ID id,
int32_t x=0, int32_t y=0, int32_t wdt=0, int32_t hgt=0,
DWORD ocf=OCF_All,
const char *szAction=NULL, C4Object *pActionTarget=NULL,
C4Object *pExclude=NULL,
C4Object *pContainer=NULL,
int32_t iOwner=ANY_OWNER);
C4Object *FindBase(int32_t iPlayer, int32_t iIndex);
C4Object *FindFriendlyBase(int32_t iPlayer, int32_t iIndex);
C4Object *FindObjectByCommand(int32_t iCommand, C4Object *pTarget=NULL, C4Value iTx=C4VNull, int32_t iTy=0, C4Object *pTarget2=NULL, C4Object *pFindNext=NULL);
void CastObjects(C4ID id, C4Object *pCreator, int32_t num, int32_t level, int32_t tx, int32_t ty, int32_t iOwner=NO_OWNER, int32_t iController=NO_OWNER);
void BlastCastObjects(C4ID id, C4Object *pCreator, int32_t num, int32_t tx, int32_t ty, int32_t iController=NO_OWNER);
C4Object *PlaceVegetation(C4ID id, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iGrowth);
C4Object *PlaceAnimal(C4ID idAnimal);
BOOL LoadScenarioSection(const char *szSection, DWORD dwFlags);
BOOL SaveDesc(C4Group &hGroup, BOOL fSaveGame=FALSE, BOOL fReference=FALSE, BOOL fLobby=FALSE, BOOL fUnregistered=FALSE, BOOL fRecord=FALSE);
bool DrawTextSpecImage(C4FacetSurface &fctTarget, const char *szSpec, uint32_t dwClr=0xff);
bool SpeedUp();
bool SlowDown();
bool InitKeyboard(); // register main keyboard input functions
protected:
bool InitSystem();
void InitInEarth();
void InitVegetation();
void InitAnimals();
void InitGoals();
void InitRules();
void InitValueOverloads();
void InitEnvironment();
void UpdateRules();
void CloseScenario();
void DeleteObjects(bool fDeleteInactive);
void ExecObjects();
void Ticks();
const char *FoldersWithLocalsDefs(const char *szPath);
BOOL CheckScenarioAccess();
BOOL CheckObjectEnumeration();
BOOL LocalFileMatch(const char *szFilename, int32_t iCreation);
BOOL DefinitionFilenamesFromSaveGame();
bool LoadScenarioComponents();
bool LoadScenarioScripts();
public:
BOOL SaveGameTitle(C4Group &hGroup);
protected:
BOOL InitGame(C4Group &hGroup, bool fLoadSection, bool fLoadSky);
BOOL InitGameFinal();
BOOL InitNetworkFromAddress(const char *szAddress);
BOOL InitNetworkFromReference(const C4Network2Reference &Reference);
BOOL InitNetworkHost();
BOOL DoLobby();
BOOL PreInitControl();
BOOL InitControl();
BOOL InitScriptEngine();
BOOL LinkScriptEngine();
BOOL InitPlayers();
BOOL InitRecord();
BOOL OpenScenario();
BOOL InitDefs();
BOOL InitMaterialTexture();
BOOL EnumerateMaterials();
BOOL GameOverCheck();
BOOL PlaceInEarth(C4ID id);
BOOL Compile(const char *szSource);
BOOL Decompile(StdStrBuf &rBuf, bool fSaveSection, bool fSaveExact);
public:
void CompileFunc(StdCompiler *pComp, CompileSettings comp);
BOOL SaveData(C4Group &hGroup, bool fSaveSection, bool fInitial, bool fSaveExact);
protected:
BOOL CompileRuntimeData(C4ComponentHost &rGameData);
BOOL StoreParticipantPlayers();
BOOL RecreatePlayerFiles();
// Object function internals
C4Object *NewObject( C4Def *ndef, C4Object *pCreator,
int32_t owner, C4ObjectInfo *info,
int32_t tx, int32_t ty, int32_t tr,
FIXED xdir, FIXED ydir, FIXED rdir,
int32_t con, int32_t iController);
void ClearObjectPtrs(C4Object *tptr);
void ObjectRemovalCheck();
bool ToggleDebugMode(); // dbg modeon/off if allowed
bool ActivateMenu(const char *szCommand); // exec given menu command for first local player
public:
bool ToggleChart(); // chart dlg on/off
void SetMusicLevel(int32_t iToLvl); // change game music volume; multiplied by config volume for real volume
};
const int32_t C4RULE_StructuresNeedEnergy = 1,
C4RULE_ConstructionNeedsMaterial = 2,
C4RULE_FlagRemoveable = 4,
C4RULE_StructuresSnowIn = 8;
extern char OSTR[500];
extern C4Game Game;
// a global wrapper
inline StdStrBuf GetKeyboardInputName(const char *szKeyName, bool fShort = false, int32_t iIndex = 0)
{
return Game.KeyboardInput.GetKeyCodeNameByKeyName(szKeyName, fShort, iIndex);
}
#endif // C4ENGINE
#endif

View File

@ -0,0 +1,168 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* control management */
#ifndef INC_C4GameControl
#define INC_C4GameControl
#include "C4Control.h"
#include "C4Network2Client.h"
#include "C4Record.h"
enum C4ControlMode
{
CM_None,
CM_Local, // control = input
CM_Network, // control = input + network input
CM_Replay, // control = replay
};
enum C4ControlDeliveryType
{
CDT_Queue = 0, // Send in control queue (sync)
CDT_Sync = 1, // Send, delay execution until net is sync (sync)
CDT_Direct = 2, // Send directly to all clients (not sync)
CDT_Private = 3, // Send only to some clients (not sync, obviously)
CDT_Decide, // Use whatever sync mode seems fastest atm (sync)
};
// Additional notes / requirements:
// * Direct control always reaches all clients faster than queue control.
// * Sync is the only synchronous control mode were it's garantueed that
// the control is actually executed within a fixed time.
// * CDT_Decide is guesswork, control isn't garantueed to be faster.
#include "C4GameControlNetwork.h"
#ifdef _DEBUG
const int32_t C4SyncCheckRate = 1,
#else
const int32_t C4SyncCheckRate = 100,
#endif
C4SyncCheckMaxKeep = 50;
class C4GameControl
{
friend class C4ControlSyncCheck;
friend class C4GameControlNetwork;
public:
C4GameControl();
~C4GameControl();
public:
C4Control Input;
C4GameControlNetwork Network;
protected:
C4ControlMode eMode;
bool fPreInit, fInitComplete;
bool fHost; // (set for local, too)
bool fActivated;
bool fRecordNeeded;
int32_t iClientID;
C4Record *pRecord;
C4Playback *pPlayback;
C4Control SyncChecks;
C4GameControlClient *pClients;
C4Control *pExecutingControl; // Control that is in the process of being executed - needed by non-initial records
public:
// ticks
int32_t ControlRate;
int32_t ControlTick;
int32_t SyncRate;
bool DoSync;
public:
// configuration
bool isLocal() const { return eMode == CM_Local; }
bool isNetwork() const { return eMode == CM_Network; }
bool isReplay() const { return eMode == CM_Replay; }
bool isCtrlHost() const { return fHost; }
bool isRecord() const { return !! pRecord; }
int32_t ClientID() const { return iClientID; }
bool SyncMode() const { return eMode != CM_Local || pRecord; }
bool NoInput() const { return isReplay(); }
// client list
C4GameControlClient *getClient(int32_t iID);
C4GameControlClient *getClient(const char *szName);
// initialization
bool InitLocal(C4Client *pLocal);
bool InitNetwork(C4Client *pLocal);
bool InitReplay(C4Group &rGroup);
void ChangeToLocal();
void Clear();
void Default();
// records
bool StartRecord(bool fInitial, bool fStreaming);
void StopRecord(StdStrBuf *pRecordName = NULL, BYTE *pRecordSHA1 = NULL);
void RequestRuntimeRecord();
bool IsRuntimeRecordPossible() const;
bool RecAddFile(const char *szLocalFilename, const char *szAddAs);
// execution
bool Prepare();
void Execute();
void Ticks();
// public helpers
bool CtrlTickReached(int32_t iTick);
int32_t getCtrlTick(int32_t iFrame) const;
int32_t getNextControlTick() const;
// control rate
void AdjustControlRate(int32_t iBy);
bool KeyAdjustControlRate(int32_t iBy)
{ AdjustControlRate(iBy); return true; }
// activation
void SetActivated(bool fActivated);
// input
void DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, C4ControlDeliveryType eDelivery);
void DbgRec(C4RecordChunkType eType, const uint8_t *pData=NULL, size_t iSize=0); // record debug stuff
C4ControlDeliveryType DecideControlDelivery();
// sync check
void DoSyncCheck();
// execute and record control (by self or C4GameControlNetwork)
void ExecControl(const C4Control &rCtrl);
void ExecControlPacket(C4PacketType eCtrlType, class C4ControlPacket *pPkt);
void OnGameSynchronizing(); // start record if desired
protected:
// sync checks
C4ControlSyncCheck *GetSyncCheck(int32_t iTick);
void RemoveOldSyncChecks();
};
#endif // INC_C4GameControl

View File

@ -0,0 +1,284 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#include "C4GameControl.h"
#ifndef INC_C4GameControlNetwork
#define INC_C4GameControlNetwork
#include "C4Control.h"
#include "C4PacketBase.h"
#include "C4Network2.h"
// constants
const int32_t C4ControlBacklog = 100, // (ctrl ticks)
C4ClientIDAll = C4ClientIDUnknown,
C4ControlOverflowLimit = 3, // (ctrl ticks)
C4MaxPreSend = 15; // (frames) - must be smaller than C4ControlBacklog!
const uint32_t C4ControlRequestInterval = 2000; // (ms)
enum C4GameControlNetworkMode
{
CNM_Decentral = 0, // 0 is the standard mode set in config
CNM_Central = 1,
CNM_Async = 2,
};
// declarations
class C4GameControlPacket; class C4GameControlClient;
class C4PacketControlReq; class C4ClientList;
// main class
class C4GameControlNetwork // run by network thread
{
public:
C4GameControlNetwork(class C4GameControl *pParent);
~C4GameControlNetwork();
protected:
volatile bool fEnabled, fRunning;
// local status
int32_t iClientID;
bool fHost, fActivated;
C4GameControlNetworkMode eMode;
int32_t iTargetTick;
// options
volatile int32_t iControlPreSend;
// statistics
int32_t iWaitStart;
int32_t iAvgControlSendTime;
int32_t iTargetFPS; // used for PreSend-colculation
// control send / recv status
volatile int32_t iControlSent, iControlReady;
// control list
C4GameControlPacket *pCtrlStack;
CStdCSec CtrlCSec;
// list of clients (activated only!)
C4GameControlClient *pClients;
CStdCSec ClientsCSec;
// holds control that needs to be executed synchronized (main thread only)
C4Control SyncControl;
C4GameControlPacket *pSyncCtrlQueue;
// control request timing
uint32_t iNextControlReqeust;
// links
C4GameControl *const pParent;
C4Network2 *pNetwork;
public:
bool IsEnabled() const { return fEnabled; }
bool IsRunning() const { return fRunning; }
bool IsActivated() const { return fActivated; }
int32_t getControlPreSend() const { return iControlPreSend; }
void setControlPreSend(int32_t iToVal) { iControlPreSend = Min(iToVal, C4MaxPreSend); }
int32_t getAvgControlSendTime() const { return iAvgControlSendTime; }
void setTargetFPS(int32_t iToVal) { iTargetFPS = iToVal; }
// main thread communication
bool Init(int32_t iClientID, bool fHost, int32_t iStartTick, bool fActivated, C4Network2 *pNetwork); // by main thread
void Clear(); // by main thread
void Execute(); // by main thread
bool CtrlReady(int32_t iTick); // by main thread
bool CtrlOverflow(int32_t iTick) const { return fRunning && iControlReady >= iTick + C4ControlOverflowLimit; } // by main thread
int32_t GetBehind(int32_t iTick) const { return iControlReady - iTick + 1; } // by main thread
bool GetControl(C4Control *pCtrl, int32_t iTick); // by main thread
bool ClientReady(int32_t iClientID, int32_t iTick); // by main thread
int32_t ClientPerfStat(int32_t iClientID); // by main thread
int32_t ClientNextControl(int32_t iClientID); // by main thread
bool CtrlNeeded(int32_t iTick) const; // by main thread
void DoInput(const C4Control &Input); // by main thread
void DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, enum C4ControlDeliveryType eType); // by main thread
// sync control
C4ControlDeliveryType DecideControlDelivery() const; // by main thread
void ExecSyncControl(); // by main thread
void ExecSyncControl(int32_t iControlTick); // by main thread
// clients
void CopyClientList(const C4ClientList &rClients);
// pausing
void SetRunning(bool fnRunning, int32_t inTargetTick = -1); // by main thread
void SetActivated(bool fnActivated); // by main thread
void SetCtrlMode(C4GameControlNetworkMode enMode); // by main thread
C4GameControlNetworkMode GetCtrlMode() const { return eMode; } // by main thread
// performance
void CalcPerformance(int32_t iCtrlTick); // by main thread
// interfaces
void HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Network2IOConnection *pConn);
void OnResComplete(C4Network2Res *pRes);
protected:
// clients
void AddClient(int32_t iClientID, const char *szName); // by main thread
void RemoveClient(int32_t iClientID); // by main thread
void ClearClients(); // by main thread
// packet handling
void HandleControl(int32_t iByClientID, const C4GameControlPacket &rPkt);
void HandleControlReq(const C4PacketControlReq &rPkt, C4Network2IOConnection *pConn);
void HandleControlPkt(C4PacketType eCtrlType, C4ControlPacket *pPkt, enum C4ControlDeliveryType eType);
// client list
C4GameControlClient *getClient(int32_t iID);
void AddClient(C4GameControlClient *pClient);
void RemoveClient(C4GameControlClient *pClient);
// control stack
C4GameControlPacket *getCtrl(int32_t iClientID, int32_t iCtrlTick); // by both
void AddCtrl(C4GameControlPacket *pCtrl);
void ClearCtrl(int32_t iBeforeTick = -1);
void CheckCompleteCtrl(bool fSetEvent); // by both
C4GameControlPacket *PackCompleteCtrl(int32_t iTick); // by main thread
// sync control
void AddSyncCtrlToQueue(const C4Control &Ctrl, int32_t iTick); // by main thread
void ExecQueuedSyncCtrl(); // by main thread
};
class C4GameControlPacket : public C4PacketBase
{
friend class C4GameControlNetwork;
public:
C4GameControlPacket();
// needed as C4Control doesn't seem to implement correct copying behavior
C4GameControlPacket(const C4GameControlPacket &Pkt2);
C4GameControlPacket &operator = (const C4GameControlPacket &Pkt2);
protected:
// header
int32_t iClientID, iCtrlTick;
int32_t iTime;
// data
C4Control Ctrl;
// list (C4GameControlNetwork)
C4GameControlPacket *pNext;
public:
int32_t getClientID() const { return iClientID; }
int32_t getCtrlTick() const { return iCtrlTick; }
int32_t getTime() const { return iTime; }
const C4Control &getControl() const { return Ctrl; }
void Set(int32_t iClientID, int32_t iCtrlTick);
void Set(int32_t iClientID, int32_t iCtrlTick, const C4Control &Ctrl);
void Add(const C4GameControlPacket &Ctrl);
virtual void CompileFunc(StdCompiler *pComp);
};
class C4GameControlClient
{
friend class C4GameControlNetwork;
public:
C4GameControlClient();
protected:
// core data
int32_t iClientID;
char szName[C4MaxName + 1];
// next expected control for this client
int32_t iNextControl;
// performance data
int32_t iPerformance;
// list (C4GameControl)
C4GameControlClient *pNext;
public:
int32_t getClientID() const { return iClientID; }
const char *getName() const { return szName; }
int32_t getNextControl() const { return iNextControl; }
int32_t getPerfStat() const;
void Set(int32_t iClientID, const char *szName);
void SetNextControl(int32_t inNextControl) { iNextControl = inNextControl; }
void AddPerf(int32_t iTime);
};
// * Packet classes *
class C4PacketControlReq : public C4PacketBase
{
public:
C4PacketControlReq(int32_t iCtrlTick = -1);
protected:
int32_t iCtrlTick;
public:
int32_t getCtrlTick() const { return iCtrlTick; }
virtual void CompileFunc(StdCompiler *pComp);
};
class C4PacketControlPkt : public C4PacketBase
{
public:
C4PacketControlPkt() { }
C4PacketControlPkt(enum C4ControlDeliveryType eDelivery, const C4IDPacket &Ctrl)
: eDelivery(eDelivery), Ctrl(Ctrl)
{ }
protected:
enum C4ControlDeliveryType eDelivery;
C4IDPacket Ctrl;
public:
C4ControlDeliveryType getDelivery() const { return eDelivery; }
const C4IDPacket &getCtrl() const { return Ctrl; }
virtual void CompileFunc(StdCompiler *pComp);
};
class C4PacketExecSyncCtrl : public C4PacketBase
{
public:
C4PacketExecSyncCtrl(int32_t iControlTick = ~0) : iControlTick(iControlTick) { }
protected:
int32_t iControlTick;
public:
int32_t getControlTick() const { return iControlTick; }
virtual void CompileFunc(StdCompiler *pComp) { pComp->Value(mkNamingAdapt(iControlTick, "ControlTick", -1)); }
};
#endif // INC_C4GameControlNetwork

View File

@ -0,0 +1,52 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2005-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// main game dialogs (abort game dlg, observer dlg)
#ifndef INC_C4GameDialogs
#define INC_C4GameDialogs
#include <C4Gui.h>
class C4AbortGameDialog : public C4GUI::ConfirmationDialog
{
public:
C4AbortGameDialog();
~C4AbortGameDialog();
protected:
static bool is_shown;
// callbacks to halt game
virtual void OnShown(); // inc game halt counter
virtual void OnClosed(bool fOK); // dec game halt counter
virtual const char *GetID() { return "AbortGameDialog"; }
// align by screen, not viewport
virtual bool IsFreePlaceDialog() { return true; }
// true for dialogs that receive full keyboard and mouse input even in shared mode
virtual bool IsExclusiveDialog() { return true; }
bool fGameHalted;
public:
static bool IsShown() { return is_shown; }
};
#endif // INC_C4GameDialogs

View File

@ -0,0 +1,183 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// the ingame-lobby
// Tab: NickCompletion (2do TODO) - and can't do this here, because tab is used to cycle controls!
//if (dwKey == VK_TAB) { /*CompleteNick();*/ return TRUE; }
#ifndef INC_C4GameLobby
#define INC_C4GameLobby
#include "C4Gui.h"
#include "C4Client.h"
#include "C4PlayerInfo.h"
class C4PlayerInfo;
class C4PlayerInfoListBox;
class C4ClientPlayerInfos;
class C4Network2ResDlg;
class C4GameOptionsList;
class C4GameOptionButtons;
namespace C4GameLobby
{
class MainDlg;
// countdown time from which the elevator sound starts and team selection becomes unavailable
const int32_t AlmostStartCountdownTime = 10; // seconds
extern bool UserAbort;
// * PID_LobbyCountdown
// initiates or aborts countdown
class C4PacketCountdown : public C4PacketBase
{
private:
int32_t iCountdown; // countdown timer, or zero for abort
public:
enum { Abort = -1 };
C4PacketCountdown(int32_t iaCountdown) : iCountdown(iaCountdown) { } // ctor
C4PacketCountdown() : iCountdown(Abort) { } // std ctor
bool IsAbort() const { return iCountdown == Abort; }
int32_t GetCountdown() const { return iCountdown; }
StdStrBuf GetCountdownMsg(bool fInitialMsg=false) const;
virtual void CompileFunc(StdCompiler *pComp);
};
// scneario info tab: displays scenario description
class ScenDesc : public C4GUI::Window, private C4ApplicationSec1Timer
{
private:
C4GUI::Label *pTitle; // scenario title or warning label if unloaded
C4GUI::TextWindow *pDescBox; // scenario description box
bool fDescFinished; // if set, scenario resource has been loaded
void Update();
public:
ScenDesc(const C4Rect &rcBounds, bool fActive); // ctor
~ScenDesc() { Deactivate(); }
void OnSec1Timer() { Update(); }
// activate/deactivate periodic updates
void Activate();
void Deactivate();
};
class MainDlg : public C4GUI::FullscreenDialog, private C4ApplicationSec1Timer
{
private:
time_t tLastPingUpdate; // time when pings were updated last time
enum CountdownState { CDS_None=0, CDS_LongCountdown=1, CDS_Countdown=2, CDS_Start=3 } eCountdownState; // nonzero when a packet was received that the game is about to start (starts elevator sound, etc.)
int32_t iBackBufferIndex; // chat message history index
C4KeyBinding *pKeyHistoryUp, *pKeyHistoryDown; // keys used to scroll through chat history
enum { SheetIdx_PlayerList = 0, SheetIdx_Res = 1, SheetIdx_Options = 2, SheetIdx_Scenario = 3, };
C4PlayerInfoListBox *pPlayerList;
C4Network2ResDlg *pResList;
C4GameOptionButtons *pGameOptionButtons;
C4GameOptionsList *pOptionsList;
ScenDesc *pScenarioInfo;
C4GUI::TextWindow *pChatBox;
C4GUI::Label *pRightTabLbl;
C4GUI::Tabular *pRightTab;
C4GUI::Edit *pEdt; // chat input
C4GUI::CallbackButton<MainDlg> *btnRun; // host only
C4GUI::CallbackButton<MainDlg, C4GUI::IconButton> *btnPlayers, *btnResources, *btnTeams, *btnOptions, *btnScenario, *btnChat; // right list sheet selection
protected:
void OnRunBtn(C4GUI::Control *btn); // callback: run button pressed
void OnTestBtn(C4GUI::Control *btn); // callback: test button pressed
void OnExitBtn(C4GUI::Control *btn); // callback: exit button pressed
bool KeyHistoryUpDown(bool fUp); // key callback
C4GUI::Edit::InputResult OnChatInput(C4GUI::Edit *edt, bool fPasting, bool fPastingMore); // callback: chat input performed
void OnClosed(bool fOK); // callback when dlg is closed
void OnSec1Timer(); // timer proc; update pings
C4GUI::ContextMenu *OnRightTabContext(C4GUI::Element *pLabel, int32_t iX, int32_t iY); // open context menu
void OnCtxTabPlayers(C4GUI::Element *pListItem) { OnTabPlayers(NULL); }
void OnTabPlayers(C4GUI::Control *btn);
void OnCtxTabTeams(C4GUI::Element *pListItem) { OnTabTeams(NULL); }
void OnTabTeams(C4GUI::Control *btn);
void OnCtxTabRes(C4GUI::Element *pListItem) { OnTabRes(NULL); }
void OnTabRes(C4GUI::Control *btn);
void OnCtxTabOptions(C4GUI::Element *pListItem) { OnTabOptions(NULL); }
void OnTabOptions(C4GUI::Control *btn);
void OnCtxTabScenario(C4GUI::Element *pListItem) { OnTabScenario(NULL); }
void OnTabScenario(C4GUI::Control *btn);
void UpdateRightTab(); // update label and tooltips for sheet change
void OnBtnChat(C4GUI::Control *btn);
virtual class C4GUI::Control *GetDefaultControl() { return pEdt; } // def focus chat input
private:
void SetCountdownState(CountdownState eToState, int32_t iTimer);
void Start(int32_t iCountdownTime); // host only: Do game start with specified countdown time (forwards to network system)
int32_t ValidatedCountdownTime(int32_t iTimeout); // correct invalid timeout settings
void UpdatePlayerList();
public:
MainDlg(bool fHost); // ctor
~MainDlg(); // dtor
// callback by network system
void OnClientJoin(C4Client *pNewClient); // called when a new client joined (connection not necessarily ready)
void OnClientConnect(C4Client *pClient, C4Network2IOConnection *pConn); // called when new clinet connection is established (notice of lobby status)
void OnClientPart(C4Client *pPartClient); // called when a client disconnects
bool OnMessage(C4Client *pOfClient, const char *szMessage); // display message in chat window
void OnClientSound(C4Client *pOfClient); // show that someone played a sound
void OnLog(const char *szLogMsg, DWORD dwClr=C4GUI_LogFontClr); // log callback
void OnError(const char *szErrMsg); // error sound + log in red
void OnPlayersChange() { UpdatePlayerList(); }
void OnClientAddPlayer(const char *szFilename, int32_t idClient);
// packet callbacks from C4Network2
void HandlePacket(char cStatus, const C4PacketBase *pBasePkt, C4Network2Client *pClient);
void OnCountdownPacket(const C4PacketCountdown &Pkt); // called when a countdown packet is received: Update countdown state
bool IsCountdown();
void UpdateFairCrew();
void UpdatePassword();
void ClearLog();
};
// helper
void LobbyError(const char *szErrorMsg);
// lobby countdown: Moves game from lobby to go state. Only created by host.
class Countdown : private C4ApplicationSec1Timer
{
private:
int32_t iStartTimer; // countdown timer for round start; 0 for not started, -1 for start overdue
public:
void OnSec1Timer(); // timer proc; count down; send important countdown packets
public:
Countdown(int32_t iStartTimer); // ctor: Init; sends initial countdown packet
~Countdown();
void Abort();
};
};
#endif

View File

@ -0,0 +1,107 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Text messages drawn inside the viewport */
#ifndef INC_C4GameMessage
#define INC_C4GameMessage
#include <C4Surface.h>
#include <C4Gui.h>
const int32_t C4GM_MaxText = 256,
C4GM_MinDelay = 20;
const int32_t C4GM_Global = 1,
C4GM_GlobalPlayer = 2,
C4GM_Target = 3,
C4GM_TargetPlayer = 4;
const int32_t C4GM_NoBreak = 1<<0,
C4GM_Bottom = 1<<1, // message placed at bottom of screen
C4GM_Multiple= 1<<2,
C4GM_Top = 1<<3,
C4GM_Left = 1<<4,
C4GM_Right = 1<<5,
C4GM_HCenter = 1<<6,
C4GM_VCenter = 1<<7,
C4GM_DropSpeech = 1<<8, // cut any text after '$'
C4GM_WidthRel = 1<<9,
C4GM_XRel = 1<<10,
C4GM_YRel = 1<<11;
const int32_t C4GM_PositioningFlags = C4GM_Bottom | C4GM_Top | C4GM_Left | C4GM_Right | C4GM_HCenter | C4GM_VCenter;
class C4GameMessage
{
friend class C4GameMessageList;
public:
void Draw(C4TargetFacet &cgo, int32_t iPlayer, float Zoom);
C4GameMessage();
~C4GameMessage();
protected:
int32_t X,Y,Wdt;
int32_t Delay;
DWORD ColorDw;
int32_t Player;
int32_t Type;
C4Object *Target;
StdCopyStrBuf Text;
C4GameMessage *Next;
C4ID DecoID; StdStrBuf PortraitDef;
C4GUI::FrameDecoration *pFrameDeco;
uint32_t dwFlags;
protected:
void Init(int32_t iType, const StdStrBuf & Text, C4Object *pTarget, int32_t iPlayer, int32_t iX, int32_t iY, uint32_t dwCol, C4ID idDecoID, const char *szPortraitDef, uint32_t dwFlags, int width);
void Append(const char *szText, BOOL fNoDuplicates = FALSE);
BOOL Execute();
const char *WordWrap(int32_t iMaxWidth);
void UpdateDef(C4ID idUpdDef);
public:
int32_t GetPositioningFlags() const { return dwFlags & C4GM_PositioningFlags; }
};
class C4GameMessageList
{
public:
C4GameMessageList();
~C4GameMessageList();
protected:
C4GameMessage *First;
public:
void Default();
void Clear();
void Execute();
void Draw(C4TargetFacet &cgo, int32_t iPlayer, float Zoom);
void ClearPlayers(int32_t iPlayer, int32_t dwPositioningFlags);
void ClearPointers(C4Object *pObj);
void UpdateDef(C4ID idUpdDef); // called after reloaddef
bool New(int32_t iType, const StdStrBuf & Text, C4Object *pTarget, int32_t iPlayer, int32_t iX = -1, int32_t iY = -1, uint32_t dwClr = 0xffFFFFFF, C4ID idDecoID=C4ID_None, const char *szPortraitDef=NULL, uint32_t dwFlags=0u, int32_t width=0);
bool New(int32_t iType, const char *szText, C4Object *pTarget, int32_t iPlayer, int32_t iX, int32_t iY, uint8_t bCol);
bool New(int32_t iType, const char *szText, C4Object *pTarget, int32_t iPlayer, int32_t iX, int32_t iY, uint32_t dwClr, C4ID idDecoID=C4ID_None, const char *szPortraitDef=NULL, uint32_t dwFlags=0u, int32_t width=0);
bool Append(int32_t iType, const char *szText, C4Object *pTarget, int32_t iPlayer, int32_t iX, int32_t iY, uint8_t bCol, bool fNoDuplicates = false);
};
void GameMsgObject(const char *szText, C4Object *pTarget, int32_t iFCol=FWhite);
void GameMsgObjectPlayer(const char *szText, C4Object *pTarget, int32_t iPlayer, int32_t iFCol=FWhite);
void GameMsgGlobal(const char *szText, int32_t iFCol=FWhite);
void GameMsgPlayer(const char *szText, int32_t iPlayer, int32_t iFCol=FWhite);
void GameMsgObjectDw(const char *szText, C4Object *pTarget, uint32_t dwClr);
#endif

View File

@ -0,0 +1,108 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// game object lists
#ifndef INC_C4GameObjects
#define INC_C4GameObjects
#include <C4ObjectList.h>
#include <C4FindObject.h>
#include <C4Sector.h>
class C4ObjResort;
// main object list class
class C4GameObjects : public C4NotifyingObjectList
{
public:
C4GameObjects(); // constructor
~C4GameObjects(); // destructor
void Default();
void Init(int32_t iWidth, int32_t iHeight);
void Clear(bool fClearInactive = true); // clear objects
public:
C4LSectors Sectors; // section object lists
C4ObjectList InactiveObjects; // inactive objects (Status=2)
C4ObjResort *ResortProc; // current sheduled user resorts
unsigned int LastUsedMarker; // last used value for C4Object::Marker
BOOL Add(C4Object *nObj); // add object
BOOL Remove(C4Object *pObj); // clear pointers to object
C4ObjectList &ObjectsAt(int ix, int iy); // get object list for map pos
void CrossCheck(); // various collision-checks
C4Object *AtObject(int ctx, int cty, DWORD &ocf, C4Object *exclude=NULL); // find object at ctx/cty
void Synchronize(); // network synchronization
C4Object *FindInternal(C4ID id); // find object in first sector
virtual C4Object *ObjectPointer(int32_t iNumber); // object pointer by number
long ObjectNumber(C4Object *pObj); // object number by pointer
C4ObjectList &ObjectsInt(); // return object list containing system objects
void PutSolidMasks();
void RemoveSolidMasks();
void RecheckSolidMasks();
int Load(C4Group &hGroup, bool fKeepInactive);
BOOL Save(const char *szFilename, BOOL fSaveGame, bool fSaveInactive);
BOOL Save(C4Group &hGroup, BOOL fSaveGame, bool fSaveInactive);
void UpdateScriptPointers(); // update pointers to C4AulScript *
void UpdatePos(C4Object *pObj);
void UpdatePosResort(C4Object *pObj);
BOOL OrderObjectBefore(C4Object *pObj1, C4Object *pObj2); // order pObj1 before pObj2
BOOL OrderObjectAfter(C4Object *pObj1, C4Object *pObj2); // order pObj1 after pObj2
void FixObjectOrder(); // Called after loading: Resort any objects that are out of order
void ResortUnsorted(); // resort any objects with unsorted-flag set into lists
void ExecuteResorts(); // execute custom resort procs
void DeleteObjects(); // delete all objects and links
void ClearDefPointers(C4Def *pDef); // clear all pointers into definition
void UpdateDefPointers(C4Def *pDef); // restore any cleared pointers after def reload
bool ValidateOwners();
bool AssignInfo();
};
class C4AulFunc;
// sheduled resort holder
class C4ObjResort
{
public:
C4ObjResort(); // constructor
~C4ObjResort(); // destructor
void Execute(); // do the resort!
void Sort(C4ObjectLink *pFirst, C4ObjectLink *pLast); // sort list between pFirst and pLast
void SortObject(); // sort single object within its category
int Category; // object category mask to be sorted
C4AulFunc *OrderFunc; // function determining new sort order
C4ObjResort *Next; // next resort holder
C4Object *pSortObj, *pObjBefore; // objects that are swapped if no OrderFunc is given
BOOL fSortAfter; // if set, the sort object is sorted
};
#endif

View File

@ -0,0 +1,226 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2005-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// Custom game options and configuration dialog
#ifndef INC_C4GameOptions
#define INC_C4GameOptions
#include "C4Gui.h"
class C4GameOptionsList;
// scenario-defined game options (2do)
class C4GameOptions
{
public:
// base class for an option
class Option
{
private:
Option *pNext; // singly linked list maintained by C4GameOptions class
friend class C4GameOptions;
public:
Option() : pNext(NULL) {}
virtual ~Option() {}
static Option *CreateOptionByTypeName(const char *szTypeName);
virtual void CompileFunc(StdCompiler *pComp) = 0;
private:
virtual C4GUI::Element *CreateOptionControl(C4GameOptionsList *pContainer) = 0;
};
// option of enumeration type
class OptionEnum : public Option
{
public:
// element of the enumeration
struct Element
{
StdCopyStrBuf Name;
int32_t id;
Element *pNext; // singly linked list maintained by OptionEnum class
Element() : Name(), id(0), pNext(NULL) {}
void CompileFunc(StdCompiler *pComp);
};
private:
Element *pFirstElement;
public:
OptionEnum() : pFirstElement(NULL) {}
virtual ~OptionEnum() { Clear(); }
void Clear();
virtual void CompileFunc(StdCompiler *pComp);
private:
virtual C4GUI::Element *CreateOptionControl(C4GameOptionsList *pContainer);
};
private:
Option *pFirstOption; // linked list of options
public:
C4GameOptions() : pFirstOption(NULL) {}
~C4GameOptions() { Clear(); }
void Clear();
void CompileFunc(StdCompiler *pComp);
};
// options dialog: created as listbox inside another dialog
// used to configure some standard runtime options, as well as custom game options
class C4GameOptionsList : public C4GUI::ListBox, private C4ApplicationSec1Timer
{
public:
enum { IconLabelSpacing = 2 }; // space between an icon and its text
private:
class Option : public C4GUI::Control
{
protected:
typedef C4GUI::Control BaseClass;
// primary subcomponent: forward focus to this element
C4GUI::Control *pPrimarySubcomponent;
virtual bool IsFocused(C4GUI::Control *pCtrl)
{
// also forward own focus to primary control
return BaseClass::IsFocused(pCtrl) || (HasFocus() && pPrimarySubcomponent == pCtrl);
}
public:
Option(class C4GameOptionsList *pForDlg); // ctor - adds to list
void InitOption(C4GameOptionsList *pForDlg); // add to list and do initial update
virtual void Update() {}; // update data
Option *GetNext() { return static_cast<Option *>(BaseClass::GetNext()); }
};
// dropdown list option
class OptionDropdown : public Option
{
public:
OptionDropdown(class C4GameOptionsList *pForDlg, const char *szCaption, bool fReadOnly);
protected:
C4GUI::Label *pCaption;
C4GUI::ComboBox *pDropdownList;
virtual void DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller) = 0;
void OnDropdownFill(C4GUI::ComboBox_FillCB *pFiller)
{ DoDropdownFill(pFiller); }
virtual void DoDropdownSelChange(int32_t idNewSelection) = 0;
bool OnDropdownSelChange(C4GUI::ComboBox *pForCombo, int32_t idNewSelection)
{ DoDropdownSelChange(idNewSelection); Update(); return true; }
};
// drop down list to specify central/decentral control mode
class OptionControlMode : public OptionDropdown
{
public:
OptionControlMode(class C4GameOptionsList *pForDlg);
protected:
virtual void DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller);
virtual void DoDropdownSelChange(int32_t idNewSelection);
virtual void Update(); // update data to current control rate
};
// drop down list option to adjust control rate
class OptionControlRate : public OptionDropdown
{
public:
OptionControlRate(class C4GameOptionsList *pForDlg);
protected:
virtual void DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller);
virtual void DoDropdownSelChange(int32_t idNewSelection);
virtual void Update(); // update data to current control rate
};
// drop down list option to adjust team usage
class OptionTeamDist : public OptionDropdown
{
public:
OptionTeamDist(class C4GameOptionsList *pForDlg);
protected:
virtual void DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller);
virtual void DoDropdownSelChange(int32_t idNewSelection);
virtual void Update(); // update data to current team mode
};
// drop down list option to adjust team color state
class OptionTeamColors : public OptionDropdown
{
public:
OptionTeamColors(class C4GameOptionsList *pForDlg);
protected:
virtual void DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller);
virtual void DoDropdownSelChange(int32_t idNewSelection);
virtual void Update(); // update data to current team color mode
};
// drop down list option to adjust control rate
class OptionRuntimeJoin : public OptionDropdown
{
public:
OptionRuntimeJoin(class C4GameOptionsList *pForDlg);
protected:
virtual void DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller);
virtual void DoDropdownSelChange(int32_t idNewSelection);
virtual void Update(); // update data to current runtime join state
};
public:
C4GameOptionsList(const C4Rect &rcBounds, bool fActive, bool fRuntime);
~C4GameOptionsList() { Deactivate(); }
private:
bool fRuntime; // set for runtime options dialog - does not provide pre-game options such as team colors
void InitOptions(); // creates option selection components
public:
// update all option flags by current game state
void Update();
void OnSec1Timer() { Update(); }
// activate/deactivate periodic updates
void Activate();
void Deactivate();
// config
bool IsTabular() const { return fRuntime; } // wide runtime dialog allows tabular layout
bool IsRuntime() const { return fRuntime; }
};
#endif //INC_C4GameOptions

View File

@ -0,0 +1,97 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2008-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// game over dialog showing winners and losers
#ifndef INC_C4GameOverDlg
#define INC_C4GameOverDlg
#include <C4Gui.h>
#include <C4RoundResults.h>
// horizontal display of goal symbols; filfilled goals marked
// maybe to be reused for a game goal dialog?
class C4GoalDisplay : public C4GUI::Window
{
private:
// element that draws one goal
class GoalPicture : public C4GUI::Window
{
private:
C4ID idGoal;
bool fFulfilled;
C4FacetSurface Picture;
public:
GoalPicture(const C4Rect &rcBounds, C4ID idGoal, bool fFulfilled);
protected:
virtual void DrawElement(C4TargetFacet &cgo);
};
public:
C4GoalDisplay(const C4Rect &rcBounds) : C4GUI::Window() { SetBounds(rcBounds); }
virtual ~C4GoalDisplay() {}
void SetGoals(const C4IDList &rAllGoals, const C4IDList &rFulfilledGoals, int32_t iGoalSymbolHeight);
};
class C4GameOverDlg : public C4GUI::Dialog, private C4ApplicationSec1Timer
{
private:
static bool is_shown;
int32_t iPlrListCount;
class C4PlayerInfoListBox **ppPlayerLists;
C4GoalDisplay *pGoalDisplay;
C4GUI::Label *pNetResultLabel; // label showing league result, disconnect, etc.
C4GUI::Button *pBtnExit, *pBtnContinue;
bool fIsNetDone; // set if league is evaluated and round results arrived
bool fIsQuitBtnVisible; // quit button available? set if not host or when fIsNetDone
bool fHasNextMissionButton; // continue button replaced by "next mission"-button?
private:
void OnExitBtn(C4GUI::Control *btn); // callback: exit button pressed
void OnContinueBtn(C4GUI::Control *btn); // callback: continue button pressed
void Update();
void SetNetResult(const char *szResultString, C4RoundResults::NetResult eResultType, size_t iPendingStreamingData, bool fIsStreaming);
protected:
virtual void OnShown();
virtual void OnClosed(bool fOK);
virtual bool OnEnter() { if (fIsQuitBtnVisible) OnExitBtn(NULL); return true; } // enter on non-button: Always quit
virtual bool OnEscape() { if (fIsQuitBtnVisible) UserClose(false); return true; } // escape ignored if still streaming
// true for dialogs that should span the whole screen
// not just the mouse-viewport
virtual bool IsFreePlaceDialog() { return true; }
// true for dialogs that receive full keyboard and mouse input even in shared mode
virtual bool IsExclusiveDialog() { return true; }
// sec1 timer
virtual void OnSec1Timer() { Update(); }
public:
C4GameOverDlg();
~C4GameOverDlg();
static bool IsShown() { return is_shown; }
};
#endif // INC_C4GameOverDlg

View File

@ -0,0 +1,83 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Gamepad control - forwards gamepad events of opened gamepads to Game.KeyboardInput */
#ifndef INC_C4GamePadCon
#define INC_C4GamePadCon
#ifdef _WIN32
#include <StdJoystick.h>
#endif
#ifdef HAVE_SDL
#include <C4KeyboardInput.h>
#include <set>
#endif
struct _SDL_Joystick;
typedef struct _SDL_Joystick SDL_Joystick;
union SDL_Event;
typedef union SDL_Event SDL_Event;
class C4GamePadControl {
#ifdef _WIN32
private:
struct Pad
{
CStdGamePad *pGamepad;
int iRefCount;
uint32_t Buttons;
CStdGamePad::AxisPos AxisPosis[CStdGamepad_MaxAxis];
};
Pad Gamepads[CStdGamepad_MaxGamePad];
int iNumGamepads;
public:
void OpenGamepad(int id); // add gamepad ref
void CloseGamepad(int id); // del gamepad ref
static C4GamePadControl *pInstance; // singleton
#elif defined HAVE_SDL
public:
void FeedEvent(SDL_Event& e);
private:
std::set<C4KeyCode> PressedAxis;
#endif
public:
C4GamePadControl();
~C4GamePadControl();
void Clear();
int GetGamePadCount();
void Execute();
static bool AnyButtonDown();
};
class C4GamePadOpener {
#ifdef _WIN32
int iGamePad;
#endif
public:
C4GamePadOpener(int iGamePad);
~C4GamePadOpener();
void SetGamePad(int iNewGamePad);
#ifdef HAVE_SDL
SDL_Joystick *Joy;
#endif
};
#endif

View File

@ -0,0 +1,156 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Game parameters - game data that is valid before the game is started */
#ifndef C4GAMEPARAMETERS_H
#define C4GAMEPARAMETERS_H
#include "C4IDList.h"
#include "C4PlayerInfo.h"
#include "C4LangStringTable.h"
#include "C4Teams.h"
class C4GameRes
{
friend class C4GameResList;
public:
C4GameRes();
C4GameRes(const C4GameRes &Res);
~C4GameRes();
C4GameRes &operator = (const C4GameRes &Res);
private:
C4Network2ResType eType;
StdCopyStrBuf File;
const C4Network2ResCore *pResCore;
C4Network2Res::Ref pNetRes;
public:
C4Network2ResType getType() const { return eType; }
const char *getFile() const { return File.getData(); }
bool isPresent() const { return !! File; }
const C4Network2ResCore *getResCore() const { return pResCore; }
C4Network2Res::Ref getNetRes() const { return pNetRes; }
void SetFile(C4Network2ResType eType, const char *szFile);
void SetResCore(C4Network2ResCore *pResCore);
void SetNetRes(C4Network2Res::Ref pRes);
bool Publish(C4Network2ResList *pResList);
bool Load(C4Network2ResList *pResList);
bool InitNetwork(C4Network2ResList *pResList);
void CalcHash();
void Clear();
void CompileFunc(StdCompiler *pComp);
};
class C4GameResList
{
private:
C4GameRes **pResList;
int32_t iResCount, iResCapacity;
public:
C4GameResList() : pResList(NULL), iResCount(0), iResCapacity(0) {}
~C4GameResList() { Clear(); }
C4GameResList &operator = (const C4GameResList &List);
int32_t getResCount() const { return iResCount; }
C4GameRes *iterRes(C4GameRes *pLast, C4Network2ResType eType = NRT_Null);
void Clear();
bool Load(const char *szDefinitionFilenames); // host: create res cores by definition filenames
C4GameRes *CreateByFile(C4Network2ResType eType, const char *szFile);
C4GameRes *CreateByNetRes(C4Network2Res::Ref pNetRes);
bool InitNetwork(C4Network2ResList *pNetResList);
void CalcHashes();
bool RetrieveFiles(); // client: make sure all definition files are loaded
void CompileFunc(StdCompiler *pComp);
protected:
void Add(C4GameRes *pRes);
};
class C4GameParameters
{
public:
C4GameParameters();
~C4GameParameters();
// League (empty if it's not a league game)
StdCopyStrBuf League;
StdCopyStrBuf LeagueAddress;
StdCopyStrBuf StreamAddress;
// Maximum player count allowed
int32_t MaxPlayers;
// Fair crew option
bool UseFairCrew;
bool FairCrewForced; // true for scenarios in which this setting may not be altered
int32_t FairCrewStrength;
// Original network game? Also set in replays of network games for sync safety
bool IsNetworkGame;
// Control rate
int32_t ControlRate;
// Allow debug mode?
bool AllowDebug;
// Active rules and goals
C4IDList Rules;
C4IDList Goals;
// Game resources
C4GameRes Scenario;
C4GameResList GameRes;
// Clients
C4ClientList Clients;
// Players & Teams
C4PlayerInfoList PlayerInfos;
C4PlayerInfoList RestorePlayerInfos;
C4TeamList Teams;
bool isLeague() const { return !!LeagueAddress.getLength(); }
bool doStreaming() const { return !!StreamAddress.getLength(); }
const char* getLeague() { return League.getData(); }
StdStrBuf GetGameGoalString();
void EnforceLeagueRules(class C4Scenario *pScenario);
void Clear();
BOOL Load(C4Group &hGroup, C4Scenario *pDefault, const char *szGameText, C4LangStringTable *pLang, const char *DefinitionFilenames);
BOOL InitNetwork(C4Network2ResList *pResList);
BOOL Save(C4Group &hGroup, C4Scenario *pDefault);
void CompileFunc(StdCompiler *pComp, C4Scenario *pScenario = NULL);
};
#endif // C4GAMEPARAMETERS_H

View File

@ -0,0 +1,190 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// game saving functionality
// merely controls what to save when how - actual saving procedures reside in the subclasses
//
// Game saving is done on the following occasions:
// -scenario saving (C4GameSaveScenario) [SyncStateScenario; KeepFiles]
// -savegames (C4GameSaveSavegame) [SyncStateSavegame; KeepFiles]
// -records (C4GameSaveRecord) [SyncStateSynced; KeepFiles] - initially and while game is running
// -network synchronizations (C4GameSaveNetwork) [SyncStateSynced] - in lobby and runtime mode
// -network references (C4GameSaveNetReference) [SyncStateScenario]
#ifndef INC_C4GameSave
#define INC_C4GameSave
#include <C4Scenario.h>
#include <C4Group.h>
#include <C4Components.h>
class C4GameSave
{
private:
C4Scenario rC4S; // local scenario core copy
protected:
C4Group *pSaveGroup; // group file written to
bool fOwnGroup; // whether group file is owned
// if set, the game is saved at initial (pre-frame0) state
// (lobby-dynamics, initial records and network references)
// no runtime data will be saved for initial-state-saves
// SafeGame/NoInitialize-core-settings will be kept in its current state for initial saves
bool fInitial;
// sync state describes what to save
enum SyncState
{
SyncNONE = 0,
SyncScenario = 1, // save (eventually static) landscape and objects only to play as a seperate scenario later
SyncSavegame = 2, // save all runtime data, so the scenario can be continued at a future date
SyncSynchronized = 3, // save exact runtime data to be network- or replay-save
} Sync; // sync is set by ctor
// query functions
virtual bool GetSaveRuntimeData() { return !fInitial; } // save exact landscape, players, etc.
virtual bool GetKeepTitle() { return !IsExact(); } // whether original, localized title with image and icon shall be deleted
virtual bool GetSaveDesc() { return true; } // should WriteDescData be executed in Save()-call?
virtual bool GetCopyScenario() { return true; } // return whether the savegame depends on the game scenario file
virtual const char *GetSortOrder() { return C4FLS_Scenario; } // return NULL to prevent sorting
virtual bool GetCreateSmallFile() { return false; } // return whether file size should be minimized
virtual bool GetForceExactLandscape() { return GetSaveRuntimeData() && IsExact(); } // whether exact landscape shall be saved
virtual bool GetSaveOrigin() { return false; } // return whether C4S.Head.Origin shall be set
virtual bool GetClearOrigin() { return !GetSaveOrigin(); } // return whether C4S.Head.Origin shall be cleared if it's set
virtual bool GetSaveUserPlayers() { return IsExact(); } // return whether joined user players shall be saved into SavePlayerInfos
virtual bool GetSaveScriptPlayers() { return IsExact(); } // return whether joined script players shall be saved into SavePlayerInfos
virtual bool GetSaveUserPlayerFiles() { return IsExact(); } // return whether .c4p files of joined user players shall be put into the scenario
virtual bool GetSaveScriptPlayerFiles() { return IsExact(); } // return whether .c4p files of joined script players shall be put into the scenario
// savegame specializations
virtual void AdjustCore(C4Scenario &rC4S) {} // set specific C4S values
virtual bool WriteDesc(StdStrBuf &sBuf) { return true; } // write desc (contents only)
virtual bool SaveComponents() { return true; } // save (or remove) custom components for specialization
virtual bool OnSaving() { return true; } // callback for special actions to be performed when saving (like, add sync)
// query sync level
bool IsExact() { return Sync>=SyncSavegame; } // exact save (players, always exact landscape, etc.)
bool IsSynced() { return Sync>=SyncSynchronized; } // synchronized
// protected constructor
C4GameSave(bool fAInitial, SyncState ASync) : pSaveGroup(NULL), fOwnGroup(false), fInitial(fAInitial), Sync(ASync) { }
protected:
// some desc writing helpers
void WriteDescLineFeed(StdStrBuf &sBuf); // append a line break to desc
void WriteDescDate(StdStrBuf &sBuf, bool fRecord = false); // append current date to desc buffer
void WriteDescGameTime(StdStrBuf &sBuf); // append game time to desc buffer, if it's >0
void WriteDescDefinitions(StdStrBuf &sBuf); // append used definition filenames to desc buffer
void WriteDescNetworkClients(StdStrBuf &sBuf); // append current network client list to desc buffer
void WriteDescPlayers(StdStrBuf &sBuf, bool fByTeam, int32_t idTeam); // helper func used by WriteDescPlayers: Write all players matching team
void WriteDescPlayers(StdStrBuf &sBuf); // append currently participating players to desc buffer
void WriteDescLeague(StdStrBuf &sBuf, bool fLeague, const char *strLeagueName); // append league status
void WriteDescEngine(StdStrBuf &sBuf); // append engine build
private:
// saving subcalls
bool SaveCreateGroup(const char *szFilename, C4Group &hUseGroup); // create/copy group at target filename
bool SaveCore(); // save C4S core
bool SaveScenarioSections(); // save scenario sections
bool SaveLandscape(); // save current landscape
bool SaveRuntimeData(); // save any runtime data
public:
virtual ~C4GameSave() { Close(); } // dtor: close group
bool Save(const char *szFilename); // create group at filename and do actual saving; group is kept open until dtor or Close()-call!
bool Save(C4Group &hToGroup, bool fKeepGroup); // save game directly to target group
bool SaveDesc(C4Group &hToGroup); // save scenario desc to file
bool Close(); // close scenario group
C4Group *GetGroup() { return pSaveGroup; } // get scenario saving group; only open between calls to Save() and Close()
};
class C4GameSaveScenario : public C4GameSave
{
public:
C4GameSaveScenario(bool fForceExactLandscape, bool fSaveOrigin) : C4GameSave(false, SyncScenario), fForceExactLandscape(fForceExactLandscape), fSaveOrigin(fSaveOrigin) {} // ctor
protected:
bool fForceExactLandscape;
bool fSaveOrigin;
virtual bool GetSaveOrigin() { return fSaveOrigin; }
virtual bool GetClearOrigin() { return false; } // always keep existing origin
virtual bool GetSaveDesc() { return false; } // should WriteDescData be executed in Save()-call?
virtual bool GetForceExactLandscape() { return C4GameSave::GetForceExactLandscape() || fForceExactLandscape; }
virtual bool GetSaveScriptPlayers() { return true; } // script players are also saved; but user players aren't!
virtual bool GetSaveScriptPlayerFiles() { return true; } // script players are also saved; but user players aren't!
};
class C4GameSaveSavegame : public C4GameSave
{
public:
C4GameSaveSavegame() : C4GameSave(false, SyncSavegame) {}
protected:
// savegame specializations
virtual bool GetSaveOrigin() { return true; } // origin must be saved in savegames
virtual bool GetSaveUserPlayerFiles() { return false; } // user player files are not needed in savegames, because they will be replaced by player files of resuming playerss
virtual void AdjustCore(C4Scenario &rC4S); // set specific C4S values
virtual bool WriteDesc(StdStrBuf &sBuf); // write savegame desc (contents only)
virtual bool SaveComponents(); // custom savegame components (title)
virtual bool OnSaving(); // add sync when saving
};
class C4GameSaveRecord : public C4GameSave
{
private:
int iNum; // record number
bool fLeague; // recording of a league game?
bool fCopyScenario; // copy scenario?
public:
C4GameSaveRecord(bool fAInitial, int iANum, bool fLeague, bool fCopyScenario = true)
: C4GameSave(fAInitial, SyncSynchronized), iNum(iANum), fLeague(fLeague), fCopyScenario(fCopyScenario)
{}
protected:
// query functions
virtual bool GetSaveDesc() { return false; } // desc is saved by external call when the record is finished
virtual bool GetCreateSmallFile() { return true; } // no need to save players complete with portraits
virtual bool GetSaveOrigin() { return true; } // origin must be saved to trace language packs, folder local material, etc. for records
virtual bool GetCopyScenario() { return fCopyScenario; } // records without copied scenario are a lot smaller can be reconstructed later (used for streaming)
// savegame specializations
virtual void AdjustCore(C4Scenario &rC4S); // set specific C4S values
virtual bool WriteDesc(StdStrBuf &sBuf); // write desc (contents only) - using old-style unchecked string buffers here...
virtual bool SaveComponents(); // custom components: PlayerInfos even if fInitial
};
class C4GameSaveNetwork : public C4GameSave
{
public:
C4GameSaveNetwork(bool fAInitial) : C4GameSave(fAInitial, SyncSynchronized) {}
protected:
// query functions
virtual bool GetSaveOrigin() { return true; } // clients must know where to get music and localization
virtual bool GetKeepTitle() { return false; } // always delete title files (not used in dynamics)
virtual bool GetSaveDesc() { return false; } // no desc in dynamics
virtual bool GetCreateSmallFile() { return true; }// return whether file size should be minimized
virtual bool GetCopyScenario() { return false; } // network dynamics do not base on normal scenario
// savegame specializations
virtual void AdjustCore(C4Scenario &rC4S); // set specific C4S values
};
#endif // INC_C4GameSave

View File

@ -0,0 +1,65 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#ifndef C4GAMEVERSION_H
#define C4GAMEVERSION_H
#include "C4Version.h"
#include "C4InputValidation.h"
struct C4GameVersion
{
ValidatedStdCopyStrBuf<C4InVal::VAL_NameAllowEmpty> sEngineName; // status only - not used for comparison
int32_t iVer[4];
int32_t iBuild;
C4GameVersion(const char *szEngine=C4ENGINENAME, int32_t iVer1=C4XVER1, int32_t iVer2=C4XVER2, int32_t iVer3=C4XVER3, int32_t iVer4=C4XVER4, int32_t iVerBuild=C4XVERBUILD)
{ Set(szEngine, iVer1, iVer2, iVer3, iVer4, iVerBuild); }
void Set(const char *szEngine=C4ENGINENAME, int32_t iVer1=C4XVER1, int32_t iVer2=C4XVER2, int32_t iVer3=C4XVER3, int32_t iVer4=C4XVER4, int32_t iVerBuild=C4XVERBUILD)
{ sEngineName.CopyValidated(szEngine); iVer[0]=iVer1; iVer[1]=iVer2; iVer[2]=iVer3; iVer[3]=iVer4; iBuild=iVerBuild; }
StdStrBuf GetString() const
{ return FormatString("%s %d.%d.%d.%d [%d]", sEngineName.getData(), (int)iVer[0], (int)iVer[1], (int)iVer[2], (int)iVer[3], (int)iBuild); }
bool operator == (const C4GameVersion &rCmp) const
{ return /*sEngineName==rCmp.sEngineName &&*/ iVer[0]==rCmp.iVer[0] && iVer[1]==rCmp.iVer[1] && iVer[2]==rCmp.iVer[2] && iVer[3]==rCmp.iVer[3] && iBuild==rCmp.iBuild; }
void CompileFunc(StdCompiler *pComp, bool fEngineName)
{
if(fEngineName)
{
pComp->Value(mkDefaultAdapt(sEngineName, ""));
pComp->Seperator();
}
else if(pComp->isCompiler())
sEngineName = "";
pComp->Value(mkArrayAdapt(iVer,4,0));
pComp->Seperator();
pComp->Value(mkDefaultAdapt(iBuild, 0));
}
};
// helper
inline int CompareVersion(int iVer1, int iVer2, int iVer3, int iVer4,
int iRVer1 = C4XVER1, int iRVer2 = C4XVER2, int iRVer3 = C4XVER3, int iRVer4 = C4XVER4)
{
if(iVer1 > iRVer1) return 1; if(iVer1 < iRVer1) return -1;
if(iVer2 > iRVer2) return 1; if(iVer2 < iRVer2) return -1;
if(iVer3 > iRVer3) return 1; if(iVer3 < iRVer3) return -1;
if(iVer4 > iRVer4) return 1; if(iVer4 < iRVer4) return -1;
return 0;
}
#endif // C4GAMEVERSION_H

View File

@ -0,0 +1,119 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Loads all standard graphics from Graphics.c4g */
#ifndef INC_C4GraphicsResource
#define INC_C4GraphicsResource
#include <C4Group.h>
#include <C4GroupSet.h>
#include <C4Surface.h>
#include <C4FacetEx.h>
namespace C4GUI { class Resource; };
class C4GraphicsResource
{
private:
bool fInitialized;
public:
C4GraphicsResource();
~C4GraphicsResource();
protected:
C4Surface sfcControl;
int32_t idSfcControl; // id of source group of control surface
int32_t idPalGrp; // if of source group of pal file
// ID of last group in main group set that was already registered into the Files-set
// used to avoid doubled entries by subsequent calls to RegisterMainGroups
int32_t idRegisteredMainGroupSetFiles;
public:
C4GroupSet Files;
BYTE GamePalette[256*3];
BYTE AlphaPalette[256*3];
C4FacetID fctPlayer;
C4FacetID fctFlag;
C4FacetID fctCrew;
C4FacetID fctScore;
C4FacetID fctWealth;
C4FacetID fctRank;
int32_t iNumRanks;
C4FacetID fctFire;
C4FacetID fctBackground;
C4Surface sfcLiquidAnimation; int32_t idSfcLiquidAnimation;
C4FacetID fctCaptain;
C4FacetID fctMouseCursor;
bool fOldStyleCursor; // if set, offsets need to be applied to some cursor facets
C4FacetID fctSelectMark;
C4FacetID fctOptions;
C4FacetID fctMenu;
C4FacetID fctUpperBoard;
C4FacetID fctLogo;
C4FacetID fctConstruction;
C4FacetID fctEnergy;
C4FacetID fctMagic;
C4FacetID fctArrow;
C4FacetID fctExit;
C4FacetID fctHand;
C4FacetID fctGamepad;
C4FacetID fctBuild;
C4FacetID fctEnergyBars;
C4Facet fctCursor;
C4Facet fctDropTarget;
C4Facet fctInsideSymbol;
C4Facet fctKeyboard;
C4Facet fctMouse;
C4Facet fctCommand;
C4Facet fctKey;
C4Facet fctOKCancel;
C4FacetID fctCrewClr; // ColorByOwner-surface of fctCrew
C4FacetID fctFlagClr; // ColorByOwner-surface of fctFlag
C4FacetID fctPlayerClr; // ColorByOwner-surface of fctPlayer
C4FacetID fctPlayerGray; // grayed out version of fctPlayer
// fonts
CStdFont FontTiny; // used for logs
CStdFont FontRegular; // normal font - just refed from graphics system
CStdFont FontCaption; // used for title bars
CStdFont FontTitle; // huge font for titles
CStdFont FontTooltip; // normal, non-shadowed font (same as BookFont)
public:
int32_t GetColorIndex(int32_t iColor, bool fLast=false);
void Default();
void Clear();
bool InitFonts(); // init fonts only (early init done by loader screen)
BOOL Init(bool fInitGUI);
bool IsInitialized() { return fInitialized; } // return whether any gfx are loaded (so dlgs can be shown)
bool RegisterGlobalGraphics(); // register global Graphics.c4g into own group set
bool RegisterMainGroups(); // register new groups of Game.GroupSet into own group set
void CloseFiles(); // free group set
bool ReloadResolutionDependantFiles(); // reload any files that depend on the current resolution
protected:
bool LoadFile(C4FacetID& fct, const char *szName, C4GroupSet &rGfxSet, int32_t iWdt = C4FCT_Full, int32_t iHgt = C4FCT_Full, bool fNoWarnIfNotFound=false);
bool LoadFile(C4Surface& sfc, const char *szName, C4GroupSet &rGfxSet, int32_t &ridCurrSfc);
bool FindLoadRes(C4Group *pSecondFile, const char *szName);
bool LoadCursorGfx();
friend class C4GUI::Resource;
friend class C4StartupGraphics;
};
#endif

View File

@ -0,0 +1,123 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Operates viewports, message board and draws the game */
#ifndef INC_C4GraphicsSystem
#define INC_C4GraphicsSystem
#include <C4FacetEx.h>
#include <C4MessageBoard.h>
#include <C4UpperBoard.h>
#include <C4Video.h>
#include <C4Shape.h>
class C4Game;
class C4LoaderScreen;
extern C4Game Game;
const float C4GFX_ZoomStep = 1.1040895f;
class C4GraphicsSystem
{
public:
C4GraphicsSystem();
~C4GraphicsSystem();
C4MessageBoard MessageBoard;
C4UpperBoard UpperBoard;
int32_t iRedrawBackground;
BOOL ShowHelp;
BOOL ShowVertices;
BOOL ShowAction;
BOOL ShowCommand;
BOOL ShowEntrance;
BOOL ShowPathfinder;
BOOL ShowNetstatus;
BOOL ShowSolidMask;
BYTE DarkColorTable[256];
BOOL fSetPalette;
uint32_t dwGamma[C4MaxGammaRamps*3]; // gamma ramps
BOOL fSetGamma; // must gamma ramp be reassigned?
C4Video Video;
C4LoaderScreen *pLoaderScreen;
void Default();
void Clear();
bool StartDrawing();
void FinishDrawing();
void Execute();
void FlashMessage(const char *szMessage);
void FlashMessageOnOff(const char *strWhat, bool fOn);
void SetDarkColorTable();
void DeactivateDebugOutput();
void MouseMove(int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyParam, class C4Viewport *pVP); // pVP specified for console mode viewports only
void SetMouseInGUI(bool fInGUI, bool fByMouse);
void SortViewportsByPlayerControl();
void ClearPointers(C4Object *pObj);
//void UpdateMouse(HWND hwnd, int32_t iX, int32_t iY, int32_t iB);
void RecalculateViewports();
BOOL Init();
BOOL InitLoaderScreen(const char *szLoaderSpec, bool fDrawBlackScreenFirst);
void EnableLoaderDrawing(); // reset black screen loader flag
bool SaveScreenshot(bool fSaveAll);
BOOL DoSaveScreenshot(bool fSaveAll, const char *szFilename);
BOOL SetPalette();
BOOL CreateViewport(int32_t iPlayer, bool fSilent);
BOOL CloseViewport(int32_t iPlayer, bool fSilent);
int32_t GetAudibility(int32_t iX, int32_t iY, int32_t *iPan, int32_t iAudibilityRadius=0);
int32_t GetViewportCount();
C4Viewport* GetViewport(int32_t iPlayer);
C4Viewport* GetFirstViewport() { return FirstViewport; }
inline void InvalidateBg() { iRedrawBackground=2; }
inline void OverwriteBg() { InvalidateBg(); }
void SetGamma(DWORD dwClr1, DWORD dwClr2, DWORD dwClr3, int32_t iRampIndex); // set gamma ramp
void ApplyGamma(); // apply gamma ramp to ddraw
BOOL CloseViewport(C4Viewport * cvp);
#ifdef _WIN32
C4Viewport* GetViewport(HWND hwnd);
BOOL RegisterViewportClass(HINSTANCE hInst);
#endif
protected:
C4Viewport *FirstViewport;
BOOL fViewportClassRegistered;
C4Facet ViewportArea;
#ifdef C4ENGINE
C4RectList BackgroundAreas; // rectangles covering background without viewports in fullscreen
#endif
char FlashMessageText[C4MaxTitle+1];
int32_t FlashMessageTime,FlashMessageX,FlashMessageY;
void DrawHelp();
void DrawFlashMessage();
void DrawHoldMessages();
void DrawFullscreenBackground();
void ClearFullscreenBackground();
int32_t SeekLoaderScreens(C4Group &rFromGrp, const char *szWildcard, int32_t iLoaderCount, char *szDstName, C4Group **ppDestGrp);
void MouseMoveToViewport(int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyParam);
public:
bool ToggleShowSolidMask();
bool ToggleShowNetStatus();
bool ToggleShowVertices();
bool ToggleShowAction();
bool ViewportNextPlayer();
bool ToggleShowHelp();
bool FreeScroll(C4Vec2D vScrollBy); // key callback: Scroll ownerless viewport by some offset
bool ViewportZoomOut();
bool ViewportZoomIn();
};
#endif

View File

@ -0,0 +1,326 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Handles group files */
#ifndef INC_C4Group
#define INC_C4Group
#ifdef HAVE_IO_H
#include <io.h>
#endif
#include <CStdFile.h>
#include <StdBuf.h>
#include <StdCompiler.h>
// C4Group-Rewind-warning:
// The current C4Group-implementation cannot handle random file access very well,
// because all files are written within a single zlib-stream.
// For every out-of-order-file accessed a group-rewind must be performed, and every
// single file up to the accessed file unpacked. As a workaround, all C4Groups are
// packed in a file order matching the reading order of the engine.
// If the reading order doesn't match the packing order, and a rewind has to be performed,
// a warning is issued in Debug-builds of the engine. But since some components require
// random access because they are loaded on-demand at runtime (e.g. global sounds), the
// warning may be temp disabled for those files using C4GRP_DISABLE_REWINDWARN and
// C4GRP_ENABLE_REWINDWARN. A ref counter keeps track of nested calls to those functions.
//
// If you add any new components to scenario or definition files, remember to adjust the
// sort order lists in C4Components.h accordingly, and enforce a reading order for that
// component.
//
// Maybe some day, someone will write a C4Group-implementation that is probably capable of
// random access...
#ifdef _DEBUG
extern int iC4GroupRewindFilePtrNoWarn;
#define C4GRP_DISABLE_REWINDWARN ++iC4GroupRewindFilePtrNoWarn;
#define C4GRP_ENABLE_REWINDWARN --iC4GroupRewindFilePtrNoWarn;
#else
#define C4GRP_DISABLE_REWINDWARN ;
#define C4GRP_ENABLE_REWINDWARN ;
#endif
const int C4GroupFileVer1=1, C4GroupFileVer2=2;
const int C4GroupMaxMaker = 30,
C4GroupMaxPassword = 30,
C4GroupMaxError = 100;
const int32_t C4GroupSwapThreshold = 10 * 1024 * 1024;
#define C4GroupFileID "RedWolf Design GrpFolder"
void C4Group_SetMaker(const char *szMaker);
void C4Group_SetPasswords(const char *szPassword);
void C4Group_SetTempPath(const char *szPath);
const char* C4Group_GetTempPath();
void C4Group_SetSortList(const char **ppSortList);
void C4Group_SetProcessCallback(BOOL (*fnCallback)(const char *, int));
BOOL C4Group_IsGroup(const char *szFilename);
BOOL C4Group_CopyItem(const char *szSource, const char *szTarget, bool fNoSort=false, bool fResetAttributes=false);
BOOL C4Group_MoveItem(const char *szSource, const char *szTarget, bool fNoSort=false);
BOOL C4Group_DeleteItem(const char *szItem, bool fRecycle=false);
bool C4Group_PackDirectoryTo(const char *szFilename, const char *szFilenameTo);
bool C4Group_PackDirectory(const char *szFilename);
BOOL C4Group_UnpackDirectory(const char *szFilename);
bool C4Group_ExplodeDirectory(const char *szFilename);
int C4Group_GetCreation(const char *szFilename);
BOOL C4Group_SetOriginal(const char *szFilename, BOOL fOriginal);
bool C4Group_ReadFile(const char *szFilename, char **pData, size_t *iSize);
bool C4Group_GetFileCRC(const char *szFilename, uint32_t *pCRC32);
bool C4Group_GetFileSHA1(const char *szFilename, BYTE *pSHA1);
BOOL EraseItemSafe(const char *szFilename);
extern const char *C4CFN_FLS[];
extern time_t C4Group_AssumeTimeOffset;
#pragma pack (push, 1)
class C4GroupHeader
{
public:
C4GroupHeader();
public:
char id[24+4];
int Ver1,Ver2;
int Entries;
char Maker[C4GroupMaxMaker+2];
char Password[C4GroupMaxPassword+2];
int Creation,Original;
BYTE fbuf[92];
public:
void Init();
};
const char C4GECS_None = 0,
C4GECS_Old = 1,
C4GECS_New = 2;
class C4GroupEntryCore
{
public:
C4GroupEntryCore();
public:
char FileName[260];
BOOL Packed,ChildGroup;
int32_t Size, __Unused, Offset;
uint32_t Time;
char HasCRC; unsigned int CRC;
char Executable;
BYTE fbuf[26];
};
#pragma pack (pop)
const int C4GRES_InGroup = 0,
C4GRES_OnDisk = 1,
C4GRES_InMemory = 2,
C4GRES_Deleted = 3;
class C4GroupEntry: public C4GroupEntryCore
{
public:
C4GroupEntry();
~C4GroupEntry();
public:
char DiskPath[_MAX_PATH + 1];
int Status;
BOOL DeleteOnDisk;
BOOL HoldBuffer;
bool BufferIsStdbuf;
BOOL NoSort;
BYTE *bpMemBuf;
C4GroupEntry *Next;
public:
void Set(const DirectoryIterator & iter, const char * szPath);
};
const int GRPF_Inactive=0,
GRPF_File=1,
GRPF_Folder=2;
class C4Group: public CStdStream
{
public:
C4Group();
~C4Group();
protected:
int Status;
char FileName[_MAX_PATH+1];
// Parent status
C4Group *Mother;
BOOL ExclusiveChild;
// File & Folder
C4GroupEntry *SearchPtr;
CStdFile StdFile;
size_t iCurrFileSize; // size of last accessed file
// File only
int FilePtr;
int MotherOffset;
int EntryOffset;
BOOL Modified;
C4GroupHeader Head;
C4GroupEntry *FirstEntry;
// Folder only
//struct _finddata_t Fdt;
//long hFdt;
DirectoryIterator FolderSearch;
C4GroupEntry FolderSearchEntry;
C4GroupEntry LastFolderSearchEntry;
BOOL StdOutput;
BOOL (*fnProcessCallback)(const char *, int);
char ErrorString[C4GroupMaxError+1];
BOOL MadeOriginal;
BOOL NoSort; // If this flag is set, all entries will be marked NoSort in AddEntry
public:
bool Open(const char *szGroupName, BOOL fCreate=FALSE);
bool Close();
bool Save(BOOL fReOpen);
bool OpenAsChild(C4Group *pMother, const char *szEntryName, BOOL fExclusive=FALSE, BOOL fCreate=FALSE);
bool OpenChild(const char* strEntry);
bool OpenMother();
bool Add(const char *szFiles);
bool Add(const char *szFile, const char *szAddAs);
bool Add(const char *szName, void *pBuffer, int iSize, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false);
bool Add(const char *szName, StdBuf &pBuffer, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false);
bool Add(const char *szName, StdStrBuf &pBuffer, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false);
bool Add(const char *szEntryname, C4Group &hSource);
bool Merge(const char *szFolders);
bool Move(const char *szFiles);
bool Move(const char *szFile, const char *szAddAs);
bool Extract(const char *szFiles, const char *szExtractTo=NULL, const char *szExclude=NULL);
bool ExtractEntry(const char *szFilename, const char *szExtractTo=NULL);
bool Delete(const char *szFiles, bool fRecursive = false);
bool DeleteEntry(const char *szFilename, bool fRecycle=false);
bool Rename(const char *szFile, const char *szNewName);
bool Sort(const char *szSortList);
bool SortByList(const char **ppSortList, const char *szFilename=NULL);
bool View(const char *szFiles);
bool GetOriginal();
bool AccessEntry(const char *szWildCard,
size_t *iSize=NULL, char *sFileName=NULL,
bool *fChild=NULL, bool NeedsToBeAGroup = false);
bool AccessNextEntry(const char *szWildCard,
size_t *iSize=NULL, char *sFileName=NULL,
bool *fChild=NULL);
bool LoadEntry(const char *szEntryName, char **lpbpBuf,
size_t *ipSize=NULL, int iAppendZeros=0);
bool LoadEntry(const char *szEntryName, StdBuf &Buf);
bool LoadEntryString(const char *szEntryName, StdStrBuf &Buf);
bool FindEntry(const char *szWildCard,
char *sFileName=NULL,
size_t *iSize=NULL,
bool *fChild=NULL);
bool FindNextEntry(const char *szWildCard,
char *sFileName=NULL,
size_t *iSize=NULL,
bool *fChild=NULL,
bool fStartAtFilename=false);
bool Read(void *pBuffer, size_t iSize);
bool Advance(int iOffset);
#ifdef C4FRONTEND
// Stuff for the FE
bool LoadIcon(const char *szEntryname, HICON *lphIcon);
bool ReadDDB(HBITMAP *lphBitmap, HDC hdc = NULL);
bool ReadDDBSection(HBITMAP *lphBitmap, HDC hdc,
int iSecX, int iSecY, int iSecWdt, int iSecHgt,
int iImgWdt=-1, int iImgHgt=-1,
BOOL fTransCol = FALSE);
bool ReadPNGSection(HBITMAP *lphBitmap, HDC hdc,
int iSecX, int iSecY, int iSecWdt, int iSecHgt,
int iImgWdt=-1, int iImgHgt=-1);
#endif
void SetMaker(const char *szMaker);
void SetPassword(const char *szPassword);
void SetStdOutput(BOOL fStatus);
void SetProcessCallback(BOOL (*fnCallback)(const char *, int));
void MakeOriginal(BOOL fOriginal);
void ResetSearch();
const char *GetError();
const char *GetMaker();
const char *GetPassword();
const char *GetName();
StdStrBuf GetFullName() const;
int EntryCount(const char *szWildCard=NULL);
int EntrySize(const char *szWildCard=NULL);
int AccessedEntrySize() { return iCurrFileSize; } // retrieve size of last accessed entry
int EntryTime(const char *szFilename);
unsigned int EntryCRC32(const char *szWildCard=NULL);
int GetVersion();
int GetCreation();
int GetStatus();
inline bool IsOpen() { return Status != GRPF_Inactive; }
C4Group *GetMother();
inline bool IsPacked() { return Status == GRPF_File; }
inline bool HasPackedMother() { if (!Mother) return false; return Mother->IsPacked(); }
inline bool SetNoSort(BOOL fNoSort) { NoSort = fNoSort; return true; }
#ifdef _DEBUG
void PrintInternals(const char *szIndent=NULL);
#endif
protected:
void Init();
void Default();
void Clear();
void ProcessOut(const char *szMessage, int iProcess=0);
bool EnsureChildFilePtr(C4Group *pChild);
bool CloseExclusiveMother();
bool Error(const char *szStatus);
bool OpenReal(const char *szGroupName);
bool OpenRealGrpFile();
bool SetFilePtr(int iOffset);
bool RewindFilePtr();
bool AdvanceFilePtr(int iOffset, C4Group *pByChild=NULL);
bool AddEntry(int status,
bool childgroup,
const char *fname,
long size,
time_t time,
char cCRC,
unsigned int iCRC,
const char *entryname = NULL,
BYTE *membuf = NULL,
bool fDeleteOnDisk = false,
bool fHoldBuffer = false,
bool fExecutable = false,
bool fBufferIsStdbuf = false);
bool AddEntryOnDisk(const char *szFilename, const char *szAddAs=NULL, bool fMove=FALSE);
bool SetFilePtr2Entry(const char *szName, C4Group *pByChild=NULL, bool NeedsToBeAGroup = false);
bool AppendEntry2StdFile(C4GroupEntry *centry, CStdFile &stdfile);
C4GroupEntry *GetEntry(const char *szName);
C4GroupEntry *SearchNextEntry(const char *szName);
C4GroupEntry *GetNextFolderEntry();
#ifdef C4FRONTEND
HBITMAP SubReadDDB(HDC hdc,
int sx=-1, int sy=-1, int swdt=-1, int shgt=-1,
int twdt=-1, int thgt=-1,
BOOL transcol=FALSE);
HBITMAP SubReadPNG(HDC hdc,
int sx=-1, int sy=-1, int swdt=-1, int shgt=-1,
int twdt=-1, int thgt=-1);
#endif
bool CalcCRC32(C4GroupEntry *pEntry);
};
#endif

View File

@ -0,0 +1,114 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// a set of group files
// manages system file overwriting by scearios or folders
#ifndef INC_C4GroupSet
#define INC_C4GroupSet
// group set priorities
#define C4GSPrio_Base 0 // lowest priority for global system files
#define C4GSPrio_Pack 1 // overloads by object packs
#define C4GSPrio_ExtraRoot 2 // overloads by Extra.c4g root folder
#define C4GSPrio_Extra 3 // overloads by Extra.c4g
#define C4GSPrio_Definition 4 // overloads by definition file - latter defined definition files have higher priority
#define C4GSPrio_Definition2 99 // highest priority a given definition may have
#define C4GSPrio_Folder 100 // overloads by local scenario folder - each child folder has higher priority
#define C4GSPrio_Folder2 199 // highest priority a folder may have
#define C4GSPrio_Scenario 200 // overloads by scenario: highest priority
// group node contents
#define C4GSCnt_Graphics 1 // contains Graphics.c4g
#define C4GSCnt_Loaders 2 // contains loader files
#define C4GSCnt_Material 4 // contains Material.c4g
#define C4GSCnt_Music 8 // contains music
#define C4GSCnt_Definitions 16 // contains definition files
#define C4GSCnt_FontDefs 32 // contains font definitions
#define C4GSCnt_Language 64 // contains language files
#define C4GSCnt_Component 128 // other components
#define C4GSCnt_Folder (C4GSCnt_Graphics | C4GSCnt_Loaders | C4GSCnt_Material | C4GSCnt_Music | C4GSCnt_FontDefs)
#define C4GSCnt_OriginFolder (C4GSCnt_Graphics | C4GSCnt_Loaders | C4GSCnt_Material | C4GSCnt_Music | C4GSCnt_FontDefs)
#define C4GSCnt_Directory (C4GSCnt_Loaders | C4GSCnt_Music)
#define C4GSCnt_Scenario C4GSCnt_Folder
#define C4GSCnt_Root (C4GSCnt_Graphics | C4GSCnt_Material)
#define C4GSCnt_Extra (C4GSCnt_Graphics | C4GSCnt_Loaders | C4GSCnt_Material | C4GSCnt_Music | C4GSCnt_FontDefs)
#define C4GSCnt_ExtraRoot (C4GSCnt_Graphics | C4GSCnt_Loaders | C4GSCnt_Material | C4GSCnt_Music | C4GSCnt_FontDefs)
#define C4GSCnt_All ~0
// class predefs
class C4GroupSet;
class C4GroupSetNode;
// one node in the group set holds one group
class C4GroupSetNode
{
protected:
C4GroupSet *pParent; // owning set
C4GroupSetNode *pPrev, *pNext; // linked list - always valid
C4Group *pGroup; // ptr to group owned by this node
bool fGrpOwned; // flag if group ptr is owned
int32_t id; // group node ID
public:
C4GroupSetNode(C4GroupSet &rParent, C4GroupSetNode *pPrev, C4Group &rGroup, bool fGrpOwned, int32_t id); // ctor
~C4GroupSetNode(); // dtor
int32_t Priority; // group priority
int32_t Contents; // content held by this group
friend class C4GroupSet;
};
// a group set manages file overloading within several groups
class C4GroupSet
{
protected:
C4GroupSetNode *pFirst, *pLast; // linked list
int32_t iIndex; // index to keep track of group node IDs
public:
bool UnregisterGroup(int32_t iIndex);
void Clear();
void Default();
C4GroupSet(); // ctor
C4GroupSet(C4GroupSet &rCopy); // copy-constructor that registers all groups with all contents
~C4GroupSet(); // dtor
bool RegisterGroup(C4Group &rGroup, bool fOwnGrp, int32_t Priority, int32_t Contents, bool fCheckContent=true); // add group to list
bool RegisterGroups(C4GroupSet &rCopy, int32_t Contents, const char *szFilename=NULL, int32_t iMaxSkipID=0); // add all matching (child-)groups of the set
C4Group *FindGroup(int32_t Contents, C4Group *pAfter=NULL, bool fSamePrio=false); // search for suitable group in list
C4Group *FindEntry(const char *szWildcard, int32_t *pPriority=NULL, int32_t *pID=NULL); // find entry in groups; store priority of group if ptr is given
int32_t GetGroupCount();
C4Group *GetGroup(int32_t iIndex);
bool LoadEntry(const char *szEntryName, char **lpbpBuf, size_t *ipSize=NULL, int32_t iAppendZeros=0);
bool LoadEntryString(const char *szEntryName, StdStrBuf & rBuf);
C4Group *RegisterParentFolders(const char *szScenFilename); // register all parent .c4f groups to the given scenario filename and return an open group file of the innermost parent c4f
static int32_t CheckGroupContents(C4Group &rGroup, int32_t Contents);
int32_t GetLastID() { return iIndex; } // return ID assigned to the last added group
bool CloseFolders(); // remove all groups associated with scenario folders
friend class C4GroupSetNode;
};
#endif

2732
engine/inc/C4Gui.h 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,103 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* A dynamic list of C4IDs */
#ifndef INC_C4IDList
#define INC_C4IDList
#include <C4Id.h>
// note that setting the chunk size for ID-Lists so low looks like an enormous waste
// at first glance - however, due there's an incredibly large number of small ID-Lists
// (99% of the lists have only one to three items!)
const size_t C4IDListChunkSize = 5; // size of id-chunks
class C4IDListChunk
{
public:
C4ID id[C4IDListChunkSize];
int32_t Count[C4IDListChunkSize];
C4IDListChunk *pNext; // next chunk
public:
C4IDListChunk(); // ctor
~C4IDListChunk(); // dtor
public:
void Clear(); // empty chunk and all behind
};
class C4IDList : protected C4IDListChunk
{
public:
C4IDList();
C4IDList(const C4IDList &rCopy); // copy ctor
C4IDList &operator = (const C4IDList &rCopy); // assignment
~C4IDList();
bool operator==(const C4IDList& rhs) const;
// trick g++
ALLOW_TEMP_TO_REF(C4IDList)
protected:
size_t Count; // number of IDs in this list
public:
// General
void Default();
void Clear();
bool IsClear() const;
// Access by direct index
C4ID GetID(size_t index, int32_t *ipCount=NULL) const;
int32_t GetCount(size_t index) const;
bool SetCount(size_t index, int32_t iCount);
// Access by ID
int32_t GetIDCount(C4ID c_id, int32_t iZeroDefVal=0) const;
bool SetIDCount(C4ID c_id, int32_t iCount, bool fAddNewID=false);
bool IncreaseIDCount(C4ID c_id, bool fAddNewID=TRUE, int32_t IncreaseBy=1, bool fRemoveEmpty=false);
bool DecreaseIDCount(C4ID c_id, bool fRemoveEmptyID=TRUE)
{ return IncreaseIDCount(c_id, false, -1, fRemoveEmptyID); }
int32_t GetNumberOfIDs() const;
int32_t GetIndex(C4ID c_id) const;
// Access by category-sorted index
C4ID GetID(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t *ipCount=NULL) const;
int32_t GetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index) const;
bool SetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t iCount);
int32_t GetNumberOfIDs(C4DefList &rDefs, int32_t dwCategory) const;
// IDList merge
bool Add(C4IDList &rList);
// Aux
bool Consolidate();
bool ConsolidateValids(C4DefList &rDefs, int32_t dwCategory = 0);
bool ConsolidateCounts();
void SortByCategory(C4DefList &rDefs);
void SortByValue(C4DefList &rDefs);
void Load(C4DefList &rDefs, int32_t dwCategory);
// Item operation
bool DeleteItem(size_t iIndex);
bool SwapItems(size_t iIndex1, size_t iIndex2);
// Compilation
bool Read(const char *szSource, int32_t iDefValue=0);
bool Write(char *szTarget, bool fValues=true) const;
// Graphics
void Draw(C4Facet &cgo, int32_t iSelection,
C4DefList &rDefs, DWORD dwCategory,
bool fCounts=TRUE, int32_t iAlign=0) const;
// Compiling
void CompileFunc(StdCompiler *pComp, bool fValues = true);
};
#endif

92
engine/inc/C4Id.h 100644
View File

@ -0,0 +1,92 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* 32-bit value to identify object definitions */
#ifndef INC_C4Id
#define INC_C4Id
#include <StdAdaptors.h>
// Use 64 Bit for C4ID (on x86_64) to pass 64 bit for each script function
// parameter
class C4ID
{
uint32_t v;
public:
C4ID() {}
C4ID(unsigned int i): v(i) {}
operator unsigned int () const { return v; }
friend bool operator ==(C4ID a, C4ID b);
};
inline bool operator ==(C4ID a, C4ID b) { return a.v == b.v; }
const C4ID C4ID_None = 0x0,
C4ID_Clonk = 0x4B4E4C43, // CLNK
C4ID_Flag = 0x47414C46, // FLAG
C4ID_Conkit = 0x544B4E43, // CNKT
C4ID_Gold = 0x444C4F47, // GOLD
C4ID_Lorry = 0x59524F4C, // LORY
C4ID_Meteor = 0x4F54454D, // METO
C4ID_Linekit = 0x544B4E4C, // LNKT
C4ID_PowerLine = 0x4C525750, // PWRL
C4ID_SourcePipe = 0x50495053, // SPIP
C4ID_DrainPipe = 0x50495044, // DPIP
C4ID_Energy = 0x47524E45, // ENRG
C4ID_CnMaterial = 0x544D4E43, // CNMT
C4ID_FlagRemvbl = 0x56524746, // FGRV
C4ID_Contents = 0x00002710; // 10001
C4ID C4Id(const char *szId);
void GetC4IdText(C4ID id, char *sBuf);
const char *C4IdText(C4ID id);
BOOL LooksLikeID(const char *szText);
bool LooksLikeID(C4ID id);
// * C4ID Adaptor
struct C4IDAdapt
{
C4ID &rValue;
explicit C4IDAdapt(C4ID &rValue) : rValue(rValue) { }
inline void CompileFunc(StdCompiler *pComp) const
{
char cC4ID[5];
if(pComp->isDecompiler())
GetC4IdText(rValue, cC4ID);
pComp->Value(mkStringAdapt(cC4ID, 4, StdCompiler::RCT_ID));
if(pComp->isCompiler())
{
if (strlen(cC4ID) != 4)
rValue = 0;
else
rValue = C4Id(cC4ID);
}
}
// Operators for default checking/setting
inline bool operator == (const C4ID &nValue) const { return rValue == nValue; }
inline C4IDAdapt &operator = (const C4ID &nValue) { rValue = nValue; return *this; }
// trick g++
ALLOW_TEMP_TO_REF(C4IDAdapt)
};
inline C4IDAdapt mkC4IDAdapt(C4ID &rValue) { return C4IDAdapt(rValue); }
#endif

View File

@ -0,0 +1,252 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Main header to include all others */
#ifndef INC_C4Include
#define INC_C4Include
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#pragma warning(disable: 4706)
#pragma warning(disable: 4239)
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif //HAVE_CONFIG_H
#ifdef _WIN32
#define C4_OS "win32"
#elif defined(__linux__)
#define C4_OS "linux"
#elif defined(__APPLE__)
#define C4_OS "mac"
#else
#define C4_OS "unknown";
#endif
#ifdef C4ENGINE
#ifndef HAVE_CONFIG_H
// different debugrec options
//#define DEBUGREC
// define directive STAT here to activate statistics
#undef STAT
#endif // HAVE_CONFIG_H
#ifdef DEBUGREC
#define DEBUGREC_SCRIPT
#define DEBUGREC_START_FRAME 0
#define DEBUGREC_PXS
#define DEBUGREC_OBJCOM
#define DEBUGREC_MATSCAN
//#define DEBUGREC_RECRUITMENT
#define DEBUGREC_MENU
#define DEBUGREC_OCF
#endif
// solidmask debugging
//#define SOLIDMASK_DEBUG
// fmod
#if defined USE_FMOD && !defined HAVE_SDL_MIXER
#define C4SOUND_USE_FMOD
#endif
#ifdef _WIN32
// resources
#include "../res/resource.h"
#endif // _WIN32
// Probably not working
#if defined(HAVE_MIDI_H) && !defined(USE_FMOD)
#define USE_WINDOWS_MIDI
#endif
#endif // C4ENGINE
#include <Standard.h>
#include <CStdFile.h>
#include <Fixed.h>
#include <StdAdaptors.h>
#include <StdBuf.h>
#include <StdConfig.h>
#include <StdCompiler.h>
#include <StdDDraw2.h>
#include <StdFacet.h>
#include <StdFile.h>
#include <StdFont.h>
#include <StdMarkup.h>
#include <StdPNG.h>
#include <StdResStr2.h>
#include <StdSurface2.h>
#include "C4Id.h"
#include "C4Prototypes.h"
#include "C4Constants.h"
#ifdef _WIN32
#include <mmsystem.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <time.h>
#include <map>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <stdarg.h>
//#define BIG_C4INCLUDE
#if defined(BIG_C4INCLUDE) && defined(C4ENGINE)
#include "C4AList.h"
#include "C4Application.h"
#include "C4Aul.h"
#include "C4ChatDlg.h"
#include "C4Client.h"
#include "C4Command.h"
#include "C4ComponentHost.h"
#include "C4Components.h"
#include "C4Config.h"
#include "C4Console.h"
#include "C4Control.h"
#include "C4DefGraphics.h"
#include "C4Def.h"
#include "C4DevmodeDlg.h"
#include "C4EditCursor.h"
#include "C4Effects.h"
#include "C4Extra.h"
#include "C4FacetEx.h"
#include "C4Facet.h"
#include "C4FileClasses.h"
#include "C4FileSelDlg.h"
#include "C4FindObject.h"
#include "C4Fonts.h"
#include "C4FullScreen.h"
#include "C4GameControl.h"
#include "C4GameControlNetwork.h"
#include "C4GameDialogs.h"
#include "C4Game.h"
#include "C4GameLobby.h"
#include "C4GameMessage.h"
#include "C4GameObjects.h"
#include "C4GameOptions.h"
#include "C4GameOverDlg.h"
#include "C4GamePadCon.h"
#include "C4GameSave.h"
#include "C4GraphicsResource.h"
#include "C4GraphicsSystem.h"
#include "C4Group.h"
#include "C4GroupSet.h"
#include "C4Gui.h"
#include "C4IDList.h"
#include "C4InfoCore.h"
#include "C4InputValidation.h"
#include "C4KeyboardInput.h"
#include "C4Landscape.h"
#include "C4LangStringTable.h"
#include "C4Language.h"
#ifndef NONETWORK
# include "C4League.h"
#endif
#include "C4LoaderScreen.h"
#include "C4LogBuf.h"
#include "C4Log.h"
#include "C4MapCreatorS2.h"
#include "C4Map.h"
#include "C4MassMover.h"
#include "C4Material.h"
#include "C4MaterialList.h"
#include "C4Menu.h"
#include "C4MessageBoard.h"
#include "C4MessageInput.h"
#include "C4MouseControl.h"
#include "C4MusicFile.h"
#include "C4MusicSystem.h"
#include "C4NameList.h"
#include "C4NetIO.h"
#include "C4Network2Client.h"
#include "C4Network2Dialogs.h"
#include "C4Network2Discover.h"
#include "C4Network2.h"
#include "C4Network2IO.h"
#include "C4Network2Players.h"
#include "C4Network2Res.h"
#include "C4Network2Stats.h"
#include "C4ObjectCom.h"
#include "C4Object.h"
#include "C4ObjectInfo.h"
#include "C4ObjectInfoList.h"
#include "C4ObjectList.h"
#include "C4ObjectMenu.h"
#include "C4PacketBase.h"
#include "C4Particles.h"
#include "C4PathFinder.h"
#include "C4Physics.h"
#include "C4Player.h"
#include "C4PlayerInfo.h"
#include "C4PlayerInfoListBox.h"
#include "C4PlayerList.h"
#include "C4PropertyDlg.h"
#include "C4PXS.h"
#include "C4Random.h"
#include "C4RankSystem.h"
#include "C4Record.h"
#include "C4Region.h"
#include "C4RoundResults.h"
#include "C4RTF.H"
#include "C4Scenario.h"
#include "C4Scoreboard.h"
#include "C4Script.h"
#include "C4ScriptHost.h"
#include "C4Sector.h"
#include "C4Shape.h"
#include "C4Sky.h"
#include "C4SolidMask.h"
#include "C4SoundSystem.h"
#include "C4Startup.h"
#include "C4StartupMainDlg.h"
#include "C4StartupNetDlg.h"
#include "C4StartupOptionsDlg.h"
#include "C4StartupAboutDlg.h"
#include "C4StartupPlrSelDlg.h"
#include "C4StartupScenSelDlg.h"
#include "C4Stat.h"
#include "C4StringTable.h"
#include "C4SurfaceFile.h"
#include "C4Surface.h"
#include "C4Teams.h"
#include "C4Texture.h"
#include "C4ToolsDlg.h"
#include "C4TransferZone.h"
#include "C4Update.h"
#include "C4UpperBoard.h"
#include "C4UserMessages.h"
#include "C4Value.h"
#include "C4ValueList.h"
#include "C4ValueMap.h"
#include "C4Video.h"
#include "C4Viewport.h"
#include "C4Weather.h"
#include "C4Wrappers.h"
#endif
#endif // INC_C4Include

View File

@ -0,0 +1,224 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Structures for object and player info components */
#ifndef INC_C4InfoCore
#define INC_C4InfoCore
#include <C4Id.h>
#include <C4ValueMap.h>
#include <Fixed.h>
class C4RankSystem;
const int32_t C4MaxPhysical = 100000,
C4MaxDeathMsg = 75;
class C4PhysicalInfo
{
public:
C4PhysicalInfo();
typedef int32_t C4PhysicalInfo::* Offset;
public:
int32_t Energy;
int32_t Breath;
int32_t Walk;
int32_t Jump;
int32_t Scale;
int32_t Hangle;
int32_t Dig;
int32_t Swim;
int32_t Throw;
int32_t Push;
int32_t Fight;
int32_t Magic;
int32_t CanScale;
int32_t CanHangle;
int32_t CanDig;
int32_t CanConstruct;
int32_t CanChop;
int32_t CanSwimDig;
int32_t CanFly;
int32_t CorrosionResist;
int32_t BreatheWater;
int32_t Float;
public:
void Default();
void PromotionUpdate(int32_t iRank, bool fUpdateTrainablePhysicals=false, class C4Def *pTrainDef=NULL);
void CompileFunc(StdCompiler *pComp);
// conversion of physical names to member pointers and vice versa
static bool GetOffsetByName(const char *szPhysicalName, Offset *pmpiOut);
static const char *GetNameByOffset(Offset mpiOff);
const char *GetNameByIndex(int32_t iIdx, Offset *pmpiOut=NULL);
// comparison
bool operator ==(const C4PhysicalInfo &cmp) const;
// physical training
protected:
static void TrainValue(int32_t *piVal, int32_t iTrainBy, int32_t iMaxTrain);
public:
void Train(Offset mpiOffset, int32_t iTrainBy, int32_t iMaxTrain);
};
class C4PhysicalChange
{
public:
int32_t PrevVal;
C4PhysicalInfo::Offset mpiOffset;
C4PhysicalChange() : PrevVal(0), mpiOffset(NULL) {}
C4PhysicalChange(int32_t iPrevVal, C4PhysicalInfo::Offset mpiOffset)
: PrevVal(iPrevVal), mpiOffset(mpiOffset) {}
C4PhysicalChange(const C4PhysicalChange &rCpy) : PrevVal(rCpy.PrevVal), mpiOffset(rCpy.mpiOffset) {}
bool operator ==(const C4PhysicalChange &rCmp) const
{ return PrevVal==rCmp.PrevVal && mpiOffset == rCmp.mpiOffset; }
C4PhysicalChange&operator =(const C4PhysicalChange &rSet)
{ PrevVal=rSet.PrevVal; mpiOffset=rSet.mpiOffset; return *this; }
void CompileFunc(StdCompiler *pComp);
};
class C4TempPhysicalInfo : public C4PhysicalInfo
{
private:
// changes done to the original physicals; used for backtracing
#ifdef C4ENGINE
std::vector<C4PhysicalChange> Changes;
#endif
public:
void Clear()
{
#ifdef C4ENGINE
Changes.clear();
#endif
}
void Default() { Clear(); C4PhysicalInfo::Default(); } // clears
void CompileFunc(StdCompiler *pComp);
void RegisterChange(C4PhysicalInfo::Offset mpiOffset); // append physical change to list
bool ResetPhysical(C4PhysicalInfo::Offset mpiOffset); // undo given physical change
bool HasChanges(C4PhysicalInfo *pRefPhysical); // return true if changes list is not empty
// also trains any change buffered physicals
void Train(Offset mpiOffset, int32_t iTrainBy, int32_t iMaxTrain);
C4PhysicalInfo &operator =(const C4PhysicalInfo &rSet)
{ Clear(); static_cast<C4PhysicalInfo &>(*this) = rSet; return *this; }
};
class C4ObjectInfoCore
{
public:
C4ObjectInfoCore();
public:
C4ID id;
char Name[C4MaxName+1];
int32_t Participation;
int32_t Rank;
StdStrBuf sRankName;
StdStrBuf sNextRankName;
int32_t NextRankExp; // EXP_NoPromotion for no more promotion; 0 if standard rank system is used
int32_t Experience,Rounds;
int32_t DeathCount;
char TypeName[C4MaxName+1+1];
int32_t Birthday,TotalPlayingTime;
int32_t Age;
char DeathMessage[C4MaxDeathMsg+1];
char PortraitFile[C4MaxName+2+4+1]; // used portrait
C4PhysicalInfo Physical;
C4ValueMapData ExtraData;
BOOL NoSave; // set for _XYZ-CrewMembers
public:
BOOL Save(C4Group &hGroup, class C4DefList *pDefs);
BOOL Load(C4Group &hGroup);
void Default(C4ID n_id=C4ID_None, class C4DefList *pDefs=NULL, const char *cpNames=NULL);
//BOOL LoadNext(C4Group &hGroup); Old c4o support disabled...
//BOOL Add(C4Group &hGroup);
void Promote(int32_t iRank, C4RankSystem &rRanks, bool fForceRankName);
bool GetNextRankInfo(C4RankSystem &rDefaultRanks, int32_t *piNextRankExp, StdStrBuf *psNextRankName);
void CompileFunc(StdCompiler *pComp);
protected:
BOOL Compile(const char *szSource);
BOOL Decompile(char **ppOutput, size_t *ipSize);
void UpdateCustomRanks(C4DefList *pDefs); // sets NextRankName and NextRankExp
};
class C4RoundResult
{
public:
C4RoundResult();
public:
StdCopyStrBuf Title;
uint32_t Date;
int32_t Duration;
int32_t Won;
int32_t Score,FinalScore,TotalScore;
int32_t Bonus;
int32_t Level;
public:
void Default();
void CompileFunc(StdCompiler *pComp);
};
class C4PlayerInfoCore
{
public:
C4PlayerInfoCore();
public:
// Player Info
char PrefName[C4MaxName+1];
char Comment[C4MaxComment+1];
int32_t Rank;
char RankName[C4MaxName+1];
int32_t Score;
int32_t Rounds,RoundsWon,RoundsLost;
int32_t TotalPlayingTime;
int32_t PrefMouse;
C4RoundResult LastRound;
C4ValueMapData ExtraData;
char LeagueName[C4MaxName+1];
// Preferences
int32_t PrefColor;
uint32_t PrefColorDw, PrefColor2Dw;
int32_t PrefControl;
int32_t PrefPosition;
int32_t PrefControlStyle;
int32_t PrefAutoContextMenu; // enable automatically opened context menus in structures
public:
void Default(C4RankSystem *pRanks=NULL);
void Promote(int32_t iRank, C4RankSystem &rRanks);
BOOL Load(C4Group &hGroup);
BOOL Save(C4Group &hGroup);
BOOL CheckPromotion(C4RankSystem &rRanks);
static DWORD GetPrefColorValue(int32_t iPrefColor);
void CompileFunc(StdCompiler *pComp);
};
inline FIXED ValByPhysical(int32_t iPercent, int32_t iPhysical) // get percentage of max physical value
{
return itofix(iPhysical * (iPercent / 5),C4MaxPhysical * 20);
}
#endif

View File

@ -0,0 +1,109 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2007-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// user input validation functions
#ifndef INC_C4InputValidation
#define INC_C4InputValidation
namespace C4InVal
{
// validation options
enum ValidationOption
{
VAL_Filename, // regular filenames only (Sven2.c4p)
VAL_SubPathFilename, // filenames and optional subpath (Spieler\Sven2.c4p)
VAL_FullPath, // full filename paths (C:\Clonk\Sven2.c4p; ..\..\..\..\AutoExec.bat)
VAL_NameAllowEmpty, // stuff like player names (Sven2). No markup. Max. C4MaxName characters. Spaces trimmed.
VAL_NameNoEmpty, // same as above, but empty string not allowed
VAL_NameExAllowEmpty,// stuff like Clonk names (Joki the {{WIPF}}). Markup allowed. Max. C4MaxLongName characters. Spaces trimmed.
VAL_NameExNoEmpty, // same as above, but empty string not allowed
VAL_IRCName, // nickname for IRC. a-z, A-Z, _^{[]} only; 0-9|- inbetween
VAL_IRCPass, // password for IRC
VAL_IRCChannel, // IRC channel name
VAL_Comment, // comment - just a length limit
};
// input validation functions: Validate input by changing it to an allowed value if possible
// issues warnings in log and returns true if such an action is performed
bool ValidateString(char *szString, ValidationOption eOption, size_t iMaxSize);
bool ValidateString(StdStrBuf &rsString, ValidationOption eOption);
bool ValidateInt(int32_t &riVal, int32_t iMinVal, int32_t iMaxVal);
inline bool ValidateFilename(char *szFilename, size_t iMaxSize=_MAX_PATH) { return ValidateString(szFilename, VAL_Filename, iMaxSize); }
// checks for phising attacks: Return true if input contains user's webcode
bool IsConfidentialData(const char *szInput, bool fShowWarningMessage);
};
// Validation adapter: Call ValidateString on string after compiling it
template <class T> struct C4StrValAdapt
{
T &rValue; C4InVal::ValidationOption eValType;
explicit C4StrValAdapt(T &rValue, C4InVal::ValidationOption eValType) : rValue(rValue), eValType(eValType) { }
inline void CompileFunc(StdCompiler *pComp)
{
pComp->Value(rValue);
if (pComp->isCompiler()) C4InVal::ValidateString(rValue.GetObj(), eValType); // works on Par adapt only :(
}
template <class D> inline bool operator == (const D &nValue) const { return rValue == nValue; }
template <class D> inline C4StrValAdapt<T> &operator = (const D &nValue) { rValue = nValue; return *this; }
ALLOW_TEMP_TO_REF(C4StrValAdapt)
};
template <class T> inline C4StrValAdapt<T> mkStrValAdapt(T RREF rValue, C4InVal::ValidationOption eValType) { return C4StrValAdapt<T>(rValue, eValType); }
// StdStrBuf that validates on compilation
struct ValidatedStdCopyStrBufBase : public StdCopyStrBuf
{
ValidatedStdCopyStrBufBase(const char *szCopy) : StdCopyStrBuf(szCopy) {}
ValidatedStdCopyStrBufBase() : StdCopyStrBuf() {}
inline void CompileFunc(StdCompiler *pComp, int iRawType = 0)
{
pComp->Value(mkParAdapt(static_cast<StdCopyStrBuf &>(*this), iRawType));
if (pComp->isCompiler()) Validate();
}
virtual bool Validate() = 0;
void CopyValidated(const char *szFromVal)
{
Copy(szFromVal);
Validate();
}
void CopyValidated(const StdStrBuf &sFromVal)
{
Copy(sFromVal);
Validate();
}
virtual ~ValidatedStdCopyStrBufBase() { }
};
template <int V> struct ValidatedStdCopyStrBuf : public ValidatedStdCopyStrBufBase
{
ValidatedStdCopyStrBuf(const char *szCopy) : ValidatedStdCopyStrBufBase(szCopy) {}
ValidatedStdCopyStrBuf() : ValidatedStdCopyStrBufBase() {}
virtual bool Validate()
{
return C4InVal::ValidateString(*this, (C4InVal::ValidationOption) V);
}
template <class D> inline bool operator == (const D &nValue) const { return static_cast<const StdCopyStrBuf &>(*this) == nValue; }
template <class D> inline ValidatedStdCopyStrBuf<V> &operator = (const D &nValue) { static_cast<StdCopyStrBuf &>(*this) = nValue; return *this; }
};
#endif // INC_C4InputValidation

View File

@ -0,0 +1,121 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#ifndef C4INTERACTIVETHREAD_H
#define C4INTERACTIVETHREAD_H
#include "StdScheduler.h"
#include "StdSync.h"
#include "StdWindow.h"
// Event types
enum C4InteractiveEventType
{
Ev_None = 0,
Ev_Log,
Ev_LogSilent,
Ev_LogFatal,
Ev_FileChange,
Ev_HTTP_Response,
Ev_IRC_Message,
Ev_Net_Conn,
Ev_Net_Disconn,
Ev_Net_Packet,
Ev_Last = Ev_Net_Packet,
};
class C4InteractiveThreadNotifyProc : public CStdNotifyProc
{
private:
class C4InteractiveThread *pNotify;
public:
void SetNotify(class C4InteractiveThread *pnNotify) { pNotify = pnNotify; }
virtual bool Execute(int iTimeout, pollfd * readyfds);
};
// Collects StdSchedulerProc objects and executes them in a seperate thread
// Provides an event queue for the procs to communicate with the main thread
class C4InteractiveThread
{
public:
C4InteractiveThread();
~C4InteractiveThread();
// Event callback interface
class Callback
{
public:
virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) = 0;
virtual ~Callback() { }
};
private:
// the thread itself
StdSchedulerThread Scheduler;
// event queue (signals to main thread)
struct Event
{
C4InteractiveEventType Type;
void *Data;
#ifdef _DEBUG
int Time;
#endif
Event *Next;
};
Event *pFirstEvent, *pLastEvent;
CStdCSec EventPushCSec, EventPopCSec;
// callback objects for events of special types
Callback *pCallbacks[Ev_Last + 1];
// proc that is added to the main thread to receive messages from our thread
C4InteractiveThreadNotifyProc NotifyProc;
public:
// process management
bool AddProc(StdSchedulerProc *pProc);
void RemoveProc(StdSchedulerProc *pProc);
// event queue
bool PushEvent(C4InteractiveEventType eEventType, void *pData = NULL);
void ProcessEvents(); // by main thread
// special events
bool ThreadLog(const char *szMessage, ...) GNUC_FORMAT_ATTRIBUTE_O;
bool ThreadLogFatal(const char *szMessage, ...) GNUC_FORMAT_ATTRIBUTE_O;
bool ThreadLogS(const char *szMessage, ...) GNUC_FORMAT_ATTRIBUTE_O;
// event handlers
void SetCallback(C4InteractiveEventType eEvent, Callback *pnNetworkCallback)
{ pCallbacks[eEvent] = pnNetworkCallback; }
void ClearCallback(C4InteractiveEventType eEvent, Callback *pnNetworkCallback)
{ if(pCallbacks[eEvent] == pnNetworkCallback) pCallbacks[eEvent] = NULL; }
private:
bool PopEvent(C4InteractiveEventType *pEventType, void **ppData); // by main thread
};
#endif // C4INTERACTIVETHREAD_H

View File

@ -0,0 +1,426 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2005-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// Keyboard input mapping to engine functions
#ifndef INC_C4KeyboardInput
#define INC_C4KeyboardInput
// key context classifications
enum C4KeyScope
{
KEYSCOPE_None = 0,
KEYSCOPE_Control = 1, // player control (e.g. NUM1 to move left on keypad control)
KEYSCOPE_Gui = 2, // keys used to manipulate GUI elements (e.g. Tab to cycle through controls)
KEYSCOPE_Fullscreen = 4, // generic fullscreen-only keys (e.g. F9 for screenshot)
KEYSCOPE_Console = 8, // generic console-mode only keys (e.g. Space to switch edit cursor)
KEYSCOPE_Generic = 16, // generic keys available in fullscreen and console mode outside GUI (e.g. F1 for music on/off)
KEYSCOPE_FullSMenu = 32, // fullscreen menu control. If fullscreen menu is active, this disables viewport controls (e.g. Return to close player join menu)
KEYSCOPE_FilmView = 64, // ownerless viewport scrolling in film mode, player switching, etc. (e.g. Enter to switch to next player)
KEYSCOPE_FreeView = 128, // ownerless viewport scrolling, player switching, etc. (e.g. arrow left to scroll left in view)
KEYSCOPE_FullSView = 256, // player fullscreen viewport
};
// what can happen to keys
enum C4KeyEventType
{
KEYEV_None = 0, // no event
KEYEV_Down = 1, // in response to WM_KEYDOWN or joypad button pressed
KEYEV_Up = 2, // in response to WM_KEYUP or joypad button released
KEYEV_Pressed = 3, // in response to WM_KEYPRESSED
};
// keyboard code
typedef unsigned long C4KeyCode;
const C4KeyCode KEY_Default = 0, // no key
KEY_Any = ~0, // used for default key processing
KEY_Undefined = (~0)^1, // used to indicate an unknown key
KEY_JOY_Left = 1, // joypad axis control: Any x axis min
KEY_JOY_Up = 2, // joypad axis control: Any y axis min
KEY_JOY_Right = 3, // joypad axis control: Any x axis max
KEY_JOY_Down = 4, // joypad axis control: Any y axis max
KEY_JOY_Button1 = 10, // key index of joypad buttons + button index for more buttons
KEY_JOY_ButtonMax = KEY_JOY_Button1+31, // maximum number of supported buttons on a gamepad
KEY_JOY_Axis1Min = 0x30,
KEY_JOY_Axis1Max = 0x31,
KEY_JOY_AxisMax = KEY_JOY_Axis1Min + 0x20,
KEY_JOY_AnyButton = 0xff, // any joypad button (not axis)
KEY_JOY_AnyOddButton = 0xfe, // joypad buttons 1, 3, 5, etc.
KEY_JOY_AnyEvenButton = 0xfd, // joypad buttons 2, 4, 6, etc.
KEY_JOY_AnyLowButton = 0xfc, // joypad buttons 1 - 4
KEY_JOY_AnyHighButton = 0xfb; // joypad buttons > 4
inline uint8_t KEY_JOY_Button(uint8_t idx) { return KEY_JOY_Button1+idx; }
inline uint8_t KEY_JOY_Axis(uint8_t idx, bool fMax) { return KEY_JOY_Axis1Min+2*idx+fMax; }
inline C4KeyCode KEY_Gamepad(uint8_t idGamepad, uint8_t idButton) // convert gamepad key to Clonk-gamepad-keycode
{
// mask key as 0x0042ggbb, where gg is gamepad ID and bb is button ID.
return 0x00420000 + (idGamepad<<8) + idButton;
}
inline bool Key_IsGamepad(C4KeyCode key)
{
return (0xff0000 & key) == 0x420000;
}
inline uint8_t Key_GetGamepad(C4KeyCode key)
{
return ((uint32_t)key >> 8) & 0xff;
}
inline uint8_t Key_GetGamepadButton(C4KeyCode key)
{
return ((uint32_t)key) & 0xff;
}
inline bool Key_IsGamepadButton(C4KeyCode key)
{
// whether this is a unique button event (AnyButton not included)
return Key_IsGamepad(key) && Inside<uint8_t>(Key_GetGamepadButton(key), KEY_JOY_Button1, KEY_JOY_ButtonMax);
}
inline bool Key_IsGamepadAxis(C4KeyCode key)
{
// whether this is a unique button event (AnyButton not included)
return Key_IsGamepad(key) && Inside<uint8_t>(Key_GetGamepadButton(key), KEY_JOY_Axis1Min, KEY_JOY_AxisMax);
}
inline uint8_t Key_GetGamepadButtonIndex(C4KeyCode key)
{
// get zero-based button index
return Key_GetGamepadButton(key) - KEY_JOY_Button1;
}
inline uint8_t Key_GetGamepadAxisIndex(C4KeyCode key)
{
// get zero-based axis index
return (Key_GetGamepadButton(key) - KEY_JOY_Axis1Min) / 2;
}
inline bool Key_IsGamepadAxisHigh(C4KeyCode key)
{
return !!(key & 1);
}
#ifdef _WIN32
#define TOUPPERIFX11(key) (key)
#else
#define TOUPPERIFX11(key) toupper(key)
#endif
enum C4KeyShiftState
{
KEYS_None = 0,
KEYS_First = 1,
KEYS_Alt = 1,
KEYS_Control = 2,
KEYS_Shift = 4,
KEYS_Max = KEYS_Shift,
KEYS_Undefined = 0xffff,
};
// extended key information containing shift state
struct C4KeyCodeEx
{
C4KeyCode Key; // the key
DWORD dwShift; // the status of Alt, Shift, Control
// if set, the keycode was generated by a key that has been held down
// this flag is ignored in comparison operations
bool fRepeated;
// helpers
static C4KeyShiftState String2KeyShift(const StdStrBuf &sName);
static C4KeyCode String2KeyCode(const StdStrBuf &sName);
static StdStrBuf KeyCode2String(C4KeyCode wCode, bool fHumanReadable, bool fShort);
StdStrBuf ToString(bool fHumanReadable, bool fShort);
static StdStrBuf KeyShift2String(C4KeyShiftState eShift);
// comparison operator for map access
inline bool operator <(const C4KeyCodeEx &v2) const
{
return Key < v2.Key || (Key == v2.Key && dwShift < v2.dwShift);
}
inline bool operator ==(const C4KeyCodeEx &v2) const
{
return Key == v2.Key && dwShift == v2.dwShift;
}
void CompileFunc(StdCompiler *pComp);
C4KeyCodeEx(C4KeyCode Key = KEY_Default, C4KeyShiftState Shift = KEYS_None, bool fIsRepeated = false)
: Key(Key), dwShift(Shift), fRepeated(fIsRepeated) {}
bool IsRepeated() { return fRepeated; }
};
// callback interface
class C4KeyboardCallbackInterface
{
private:
int iRef;
public:
class C4CustomKey *pOriginalKey;
public:
virtual bool OnKeyEvent(C4KeyCodeEx key, C4KeyEventType eEv) = 0; // return true if processed
friend class C4KeyboardMapping;
// reference counter
inline void Ref() { ++iRef; }
inline void Deref() { if (!--iRef) delete this; }
C4KeyboardCallbackInterface() : iRef(0), pOriginalKey(NULL) {}
virtual ~C4KeyboardCallbackInterface() {}
bool IsOriginalKey(const class C4CustomKey *pCheckKey) const { return pCheckKey == pOriginalKey; }
};
// callback interface
template <class TargetClass> class C4KeyCB : public C4KeyboardCallbackInterface
{
public:
typedef bool(TargetClass::*CallbackFunc)();
protected:
TargetClass &rTarget;
CallbackFunc pFuncDown, pFuncUp, pFuncPressed;
protected:
virtual bool OnKeyEvent(C4KeyCodeEx key, C4KeyEventType eEv)
{
if (!CheckCondition()) return false;
switch (eEv)
{
case KEYEV_Down: return pFuncDown ? (rTarget.*pFuncDown)() : false;
case KEYEV_Up: return pFuncUp ? (rTarget.*pFuncUp)() : false;
case KEYEV_Pressed: return pFuncPressed ? (rTarget.*pFuncPressed)() : false;
}
return false;
}
virtual bool CheckCondition() { return true; }
public:
C4KeyCB(TargetClass &rTarget, CallbackFunc pFuncDown, CallbackFunc pFuncUp=NULL, CallbackFunc pFuncPressed=NULL)
: rTarget(rTarget), pFuncDown(pFuncDown), pFuncUp(pFuncUp), pFuncPressed(pFuncPressed) {}
};
// callback interface that passes the pressed key as a parameter
template <class TargetClass> class C4KeyCBPassKey : public C4KeyboardCallbackInterface
{
public:
typedef bool(TargetClass::*CallbackFunc)(C4KeyCodeEx key);
protected:
TargetClass &rTarget;
CallbackFunc pFuncDown, pFuncUp, pFuncPressed;
protected:
virtual bool OnKeyEvent(C4KeyCodeEx key, C4KeyEventType eEv)
{
if (!CheckCondition()) return false;
switch (eEv)
{
case KEYEV_Down: return pFuncDown ? (rTarget.*pFuncDown)(key) : false;
case KEYEV_Up: return pFuncUp ? (rTarget.*pFuncUp)(key) : false;
case KEYEV_Pressed: return pFuncPressed ? (rTarget.*pFuncPressed)(key) : false;
}
return false;
}
virtual bool CheckCondition() { return true; }
public:
C4KeyCBPassKey(TargetClass &rTarget, CallbackFunc pFuncDown, CallbackFunc pFuncUp=NULL, CallbackFunc pFuncPressed=NULL)
: rTarget(rTarget), pFuncDown(pFuncDown), pFuncUp(pFuncUp), pFuncPressed(pFuncPressed) {}
};
// parameterized callback interface
template <class TargetClass, class ParameterType> class C4KeyCBEx : public C4KeyboardCallbackInterface
{
public:
typedef bool(TargetClass::*CallbackFunc)(ParameterType par);
protected:
TargetClass &rTarget;
CallbackFunc pFuncDown, pFuncUp, pFuncPressed;
ParameterType par;
protected:
virtual bool OnKeyEvent(C4KeyCodeEx key, C4KeyEventType eEv)
{
if (!CheckCondition()) return false;
switch (eEv)
{
case KEYEV_Down: return pFuncDown ? (rTarget.*pFuncDown)(par) : false;
case KEYEV_Up: return pFuncUp ? (rTarget.*pFuncUp)(par) : false;
case KEYEV_Pressed: return pFuncPressed ? (rTarget.*pFuncPressed)(par) : false;
}
return false;
}
virtual bool CheckCondition() { return true; }
public:
C4KeyCBEx(TargetClass &rTarget, const ParameterType &par, CallbackFunc pFuncDown, CallbackFunc pFuncUp=NULL, CallbackFunc pFuncPressed=NULL)
: rTarget(rTarget), pFuncDown(pFuncDown), pFuncUp(pFuncUp), pFuncPressed(pFuncPressed), par(par) {}
};
template <class TargetClass, class ParameterType> class C4KeyCBExPassKey : public C4KeyboardCallbackInterface
{
public:
typedef bool(TargetClass::*CallbackFunc)(C4KeyCodeEx key, ParameterType par);
protected:
TargetClass &rTarget;
CallbackFunc pFuncDown, pFuncUp, pFuncPressed;
ParameterType par;
protected:
virtual bool OnKeyEvent(C4KeyCodeEx key, C4KeyEventType eEv)
{
if (!CheckCondition()) return false;
switch (eEv)
{
case KEYEV_Down: return pFuncDown ? (rTarget.*pFuncDown)(key, par) : false;
case KEYEV_Up: return pFuncUp ? (rTarget.*pFuncUp)(key, par) : false;
case KEYEV_Pressed: return pFuncPressed ? (rTarget.*pFuncPressed)(key, par) : false;
}
return false;
}
virtual bool CheckCondition() { return true; }
public:
C4KeyCBExPassKey(TargetClass &rTarget, const ParameterType &par, CallbackFunc pFuncDown, CallbackFunc pFuncUp=NULL, CallbackFunc pFuncPressed=NULL)
: rTarget(rTarget), pFuncDown(pFuncDown), pFuncUp(pFuncUp), pFuncPressed(pFuncPressed), par(par) {}
};
// one mapped keyboard entry
class C4CustomKey
{
public:
typedef std::vector<C4KeyCodeEx> CodeList;
private:
CodeList Codes, DefaultCodes; // keyboard scancodes of OS plus shift state
C4KeyScope Scope; // scope in which key is processed
StdStrBuf Name; // custom key name; used for association in config files
typedef std::vector<C4KeyboardCallbackInterface *> CBVec;
unsigned int uiPriority; // key priority: If multiple keys of same code are defined, high prio overwrites low prio keys
public:
CBVec vecCallbacks; // a list of all callbacks assigned to that key
enum Priority
{
PRIO_None = 0u,
PRIO_Base = 1u,
PRIO_Dlg = 2u,
PRIO_Ctrl = 3u, // controls have higher priority than dialogs in GUI
PRIO_CtrlOverride = 4u, // dialog handlings of keys that overwrite regular control handlings
PRIO_FocusCtrl = 5u, // controls override special dialog handling keys (e.g., RenameEdit)
PRIO_Context = 6u, // context menus above controls
PRIO_PlrControl = 7u, // player controls overwrite any other controls
PRIO_MoreThanMax = 100u, // must be larger than otherwise largest used priority
};
protected:
int iRef;
public:
C4CustomKey(C4KeyCodeEx DefCode, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key
C4CustomKey(const CodeList &rDefCodes, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key with multiple possible keys assigned
C4CustomKey(C4KeyCodeEx Code, const StdStrBuf &rName); // ctor for single custom key override
C4CustomKey(const C4CustomKey &rCpy, bool fCopyCallbacks);
virtual ~C4CustomKey(); // dtor
inline void Ref() { ++iRef; }
inline void Deref() { if (!--iRef) delete this; }
const CodeList &GetCodes() const { return Codes.size() ? Codes : DefaultCodes; } // return assigned codes; default if no custom has been assigned
const StdStrBuf &GetName() const { return Name; }
C4KeyScope GetScope() const { return Scope; }
unsigned int GetPriority() const { return uiPriority; }
void Update(const C4CustomKey *pByKey); // merge given key into this
bool Execute(C4KeyEventType eEv, C4KeyCodeEx key);
void KillCallbacks(const C4CustomKey *pOfKey); // remove any callbacks that were created by given key
void CompileFunc(StdCompiler *pComp);
};
// a key that auto-registers itself into main game keyboard input class and does dereg when deleted
class C4KeyBinding : protected C4CustomKey
{
public:
C4KeyBinding(C4KeyCodeEx DefCode, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key
C4KeyBinding(const CodeList &rDefCodes, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key
~C4KeyBinding();
};
// main keyboard mapping class
class C4KeyboardInput
{
private:
// comparison fn for map
struct szLess
{
bool operator()(const char *p, const char *q) const { return p && q && (strcmp(p,q)<0); }
};
typedef std::multimap<C4KeyCodeEx, C4CustomKey *> KeyCodeMap;
typedef std::map<const char *, C4CustomKey *, szLess> KeyNameMap;
// mapping of all keys by code and name
KeyCodeMap KeysByCode;
KeyNameMap KeysByName;
public:
static bool IsValid; // global var to fix any deinitialization orders of key map and static keys
C4KeyboardInput() { IsValid = true; }
~C4KeyboardInput() { Clear(); IsValid = false; }
void Clear(); // empty keyboard maps
private:
// assign keycodes changed for a key: Update codemap
void UpdateKeyCodes(C4CustomKey *pKey, const C4CustomKey::CodeList &rOldCodes, const C4CustomKey::CodeList &rNewCodes);
public:
void RegisterKey(C4CustomKey *pRegKey); // register key into code and name maps, or update specific key
void UnregisterKey(const StdStrBuf &rsName); // remove key from all maps
void UnregisterKeyBinding(C4CustomKey *pKey); // just remove callbacks from a key
bool DoInput(const C4KeyCodeEx &InKey, C4KeyEventType InEvent, DWORD InScope);
void CompileFunc(StdCompiler *pComp);
bool LoadCustomConfig(); // load keyboard customization file
C4CustomKey *GetKeyByName(const char *szKeyName);
StdStrBuf GetKeyCodeNameByKeyName(const char *szKeyName, bool fShort = false, int32_t iIndex = 0);
};
// keyboardinput-initializer-helper
C4KeyboardInput &C4KeyboardInput_Init();
#endif // INC_C4KeyboardInput

View File

@ -0,0 +1,251 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Handles landscape and sky */
#ifndef INC_C4Landscape
#define INC_C4Landscape
#include "C4Sky.h"
#include "C4Shape.h"
#include <StdSurface8.h>
const uint8_t GBM = 128,
GBM_ColNum = 64,
IFT = 0x80,
IFTOld = GBM_ColNum;
const uint8_t CSkyDef1=104,CSkyDef2=123;
const int32_t C4MaxMaterial = 125;
const int32_t C4LSC_Undefined = 0,
C4LSC_Dynamic = 1,
C4LSC_Static = 2,
C4LSC_Exact = 3;
const int32_t C4LS_MaxRelights = 50;
class C4MapCreatorS2;
class C4Landscape
{
public:
C4Landscape();
~C4Landscape();
public:
int32_t Mode;
int32_t Width,Height;
int32_t MapWidth,MapHeight,MapZoom;
CSurface8 * Map;
DWORD MatCount[C4MaxMaterial]; // NoSave //
DWORD EffectiveMatCount[C4MaxMaterial]; // NoSave //
int32_t BlastMatCount[C4MaxMaterial]; // SyncClearance-NoSave //
bool NoScan; // ExecuteScan() disabled
int32_t ScanX,ScanSpeed; // SyncClearance-NoSave //
int32_t LeftOpen,RightOpen,TopOpen,BottomOpen;
FIXED Gravity;
uint32_t Modulation; // landscape blit modulation; 0 means normal
int32_t MapSeed; // random seed for MapToLandscape
C4Sky Sky;
C4MapCreatorS2 *pMapCreator; // map creator for script-generated maps
bool fMapChanged;
BYTE *pInitial; // Initial landscape after creation - used for diff
protected:
CSurface * Surface32;
CSurface * AnimationSurface;
CSurface8 * Surface8;
int32_t Pix2Mat[256], Pix2Dens[256], Pix2Place[256];
int32_t PixCntPitch;
uint8_t *PixCnt;
C4Rect Relights[C4LS_MaxRelights];
public:
void Default();
void Clear(bool fClearMapCreator=true, bool fClearSky=true);
void Execute();
void Synchronize();
void Draw(C4TargetFacet &cgo, int32_t iPlayer=-1);
void ScenarioInit();
void ClearRect(int32_t iTx, int32_t iTy, int32_t iWdt, int32_t iHgt);
void ClearRectDensity(int32_t iTx, int32_t iTy, int32_t iWdt, int32_t iHgt, int32_t iOfDensity);
void ClearMatCount();
void ClearBlastMatCount();
void ScanSideOpen();
void CheckInstabilityRange(int32_t tx, int32_t ty);
void ShakeFree(int32_t tx, int32_t ty, int32_t rad);
void DigFree(int32_t tx, int32_t ty, int32_t rad, BOOL fRequest=FALSE, C4Object *pByObj=NULL);
void DigFreeRect(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, BOOL fRequest=FALSE, C4Object *pByObj=NULL);
void DigFreeMat(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t mat);
void BlastFree(int32_t tx, int32_t ty, int32_t rad, int32_t grade, int32_t iByPlayer);
void DrawMaterialRect(int32_t mat, int32_t tx, int32_t ty, int32_t wdt, int32_t hgt);
void RaiseTerrain(int32_t tx, int32_t ty, int32_t wdt);
void FindMatTop(int32_t mat, int32_t &x, int32_t &y);
BYTE GetMapIndex(int32_t iX, int32_t iY);
BOOL Load(C4Group &hGroup, bool fLoadSky, bool fSavegame);
BOOL Save(C4Group &hGroup);
BOOL SaveDiff(C4Group &hGroup, bool fSyncSave);
BOOL SaveMap(C4Group &hGroup);
BOOL SaveInitial();
bool SaveTextures(C4Group &hGroup);
BOOL Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bool &rfLoaded, bool fSavegame);
BOOL MapToLandscape();
BOOL ApplyDiff(C4Group &hGroup);
BOOL SetMode(int32_t iMode);
BOOL SetPix(int32_t x, int32_t y, BYTE npix); // set landscape pixel (bounds checked)
BOOL SetPixDw(int32_t x, int32_t y, DWORD dwPix); // set pixel how it is visible only
BOOL _SetPix(int32_t x, int32_t y, BYTE npix); // set landsape pixel (bounds not checked)
BOOL _SetPixIfMask(int32_t x, int32_t y, BYTE npix, BYTE nMask) ; // set landscape pixel, if it matches nMask color (no bound-checks)
BOOL CheckInstability(int32_t tx, int32_t ty);
BOOL ClearPix(int32_t tx, int32_t ty);
BOOL InsertMaterial(int32_t mat, int32_t tx, int32_t ty, int32_t vx = 0, int32_t vy = 0);
BOOL FindMatPath(int32_t &fx, int32_t &fy, int32_t ydir, int32_t mdens, int32_t mslide);
BOOL FindMatSlide(int32_t &fx, int32_t &fy, int32_t ydir, int32_t mdens, int32_t mslide);
BOOL FindMatPathPush(int32_t &fx, int32_t &fy, int32_t mdens, int32_t mslide, bool liquid);
BOOL FindMatPathPull(int32_t &fx, int32_t &fy, int32_t mdens, int32_t mslide, bool liquid);
BOOL Incinerate(int32_t x, int32_t y);
BOOL DrawBrush(int32_t iX, int32_t iY, int32_t iGrade, const char *szMaterial, const char *szTexture, BOOL fIFT);
BOOL DrawLine(int32_t iX1, int32_t iY1, int32_t iX2, int32_t iY2, int32_t iGrade, const char *szMaterial, const char *szTexture, BOOL fIFT);
BOOL DrawBox(int32_t iX1, int32_t iY1, int32_t iX2, int32_t iY2, int32_t iGrade, const char *szMaterial, const char *szTexture, BOOL fIFT);
BOOL DrawChunks(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t icntx, int32_t icnty, const char *szMaterial, const char *szTexture, bool bIFT);
BOOL DrawQuad(int32_t iX1, int32_t iY1, int32_t iX2, int32_t iY2, int32_t iX3, int32_t iY3, int32_t iX4, int32_t iY4, const char *szMaterial, bool bIFT);
CStdPalette *GetPal() const { return Surface8 ? Surface8->pPal : NULL; }
inline BYTE _GetPix(int32_t x, int32_t y) // get landscape pixel (bounds not checked)
{
return Surface8->_GetPix(x,y);
}
inline DWORD _GetPixDw(int32_t x, int32_t y, bool fApplyModulation) // get landscape pixel (bounds not checked)
{
return Surface32->GetPixDw(x, y, fApplyModulation);
}
inline BYTE GetPix(int32_t x, int32_t y) // get landscape pixel (bounds checked)
{
extern BYTE MCVehic;
// Border checks
if (x<0)
if (y<LeftOpen) return 0;
else return MCVehic;
if (x>=Width)
if (y<RightOpen) return 0;
else return MCVehic;
if (y<0)
if (TopOpen) return 0;
else return MCVehic;
if (y>=Height)
if (BottomOpen) return 0;
else return MCVehic;
return Surface8->_GetPix(x,y);
}
inline int32_t _GetMat(int32_t x, int32_t y) // get landscape material (bounds not checked)
{
return Pix2Mat[_GetPix(x, y)];
}
inline int32_t _GetDensity(int32_t x, int32_t y) // get landscape density (bounds not checked)
{
return Pix2Dens[_GetPix(x, y)];
}
inline int32_t _GetPlacement(int32_t x, int32_t y) // get landscape material placement (bounds not checked)
{
return Pix2Place[_GetPix(x, y)];
}
inline int32_t GetMat(int32_t x, int32_t y) // get landscape material (bounds checked)
{
return Pix2Mat[GetPix(x, y)];
}
inline int32_t GetDensity(int32_t x, int32_t y) // get landscape density (bounds checked)
{
return Pix2Dens[GetPix(x, y)];
}
inline int32_t GetPlacement(int32_t x, int32_t y) // get landscape material placement (bounds checked)
{
return Pix2Place[GetPix(x, y)];
}
inline int32_t GetPixMat(BYTE byPix) { return Pix2Mat[byPix]; }
inline int32_t GetPixDensity(BYTE byPix) { return Pix2Dens[byPix]; }
bool _PathFree(int32_t x, int32_t y, int32_t x2, int32_t y2); // quickly checks wether there *might* be pixel in the path.
int32_t GetMatHeight(int32_t x, int32_t y, int32_t iYDir, int32_t iMat, int32_t iMax);
int32_t DigFreePix(int32_t tx, int32_t ty);
int32_t ShakeFreePix(int32_t tx, int32_t ty);
int32_t BlastFreePix(int32_t tx, int32_t ty, int32_t grade, int32_t iBlastSize);
int32_t AreaSolidCount(int32_t x, int32_t y, int32_t wdt, int32_t hgt);
int32_t ExtractMaterial(int32_t fx, int32_t fy);
BOOL DrawMap(int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, const char *szMapDef); // creates and draws a map section using MapCreatorS2
bool ClipRect(int32_t &rX, int32_t &rY, int32_t &rWdt, int32_t &rHgt); // clip given rect by landscape size; return whether anything is left unclipped
BOOL DrawDefMap(int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, const char *szMapDef); // creates and draws a map section using MapCreatorS2 and a map from the loaded Landscape.txt
bool SetModulation(DWORD dwWithClr) // adjust the way the landscape is blitted
{ Modulation=dwWithClr; return true; }
DWORD GetModulation() { return Modulation; }
void DiscardMap(); // discard map if present
bool PostInitMap(); // do script callbacks of MapCreatorS2 in finished landscape
bool ReplaceMapColor(BYTE iOldIndex, BYTE iNewIndex); // find every occurance of iOldIndex in map; replace it by new index
BOOL SetTextureIndex(const char *szMatTex, BYTE iNewIndex, bool fInsert); // change color index of map texture, or insert a new one
void SetMapChanged() { fMapChanged = true; }
void HandleTexMapUpdate();
void UpdatePixMaps();
bool DoRelights();
void RemoveUnusedTexMapEntries();
protected:
void ExecuteScan();
int32_t DoScan(int32_t x, int32_t y, int32_t mat, int32_t dir);
int32_t ChunkyRandom(int32_t &iOffset, int32_t iRange); // return static random value, according to offset and MapSeed
void DrawChunk(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t mcol, int32_t iChunkType, int32_t cro);
void DrawSmoothOChunk(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t mcol, BYTE flip, int32_t cro);
void ChunkOZoom(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, int32_t iMapWdt, int32_t iMapHgt, int32_t iTexture,int32_t iOffX=0,int32_t iOffY=0);
BOOL GetTexUsage(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, int32_t iMapWdt, int32_t iMapHgt, DWORD *dwpTextureUsage);
BOOL TexOZoom(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, int32_t iMapWdt, int32_t iMapHgt, DWORD *dwpTextureUsage, int32_t iToX=0,int32_t iToY=0);
BOOL MapToSurface(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, int32_t iMapWdt, int32_t iMapHgt, int32_t iToX, int32_t iToY, int32_t iToWdt, int32_t iToHgt, int32_t iOffX, int32_t iOffY);
BOOL MapToLandscape(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, int32_t iMapWdt, int32_t iMapHgt, int32_t iOffsX = 0, int32_t iOffsY = 0); // zoom map segment to surface (or sector surfaces)
BOOL GetMapColorIndex(const char *szMaterial, const char *szTexture, BOOL fIFT, BYTE &rbyCol);
BOOL SkyToLandscape(int32_t iToX, int32_t iToY, int32_t iToWdt, int32_t iToHgt, int32_t iOffX, int32_t iOffY);
CSurface8 * CreateMap(); // create map by landscape attributes
CSurface8 * CreateMapS2(C4Group &ScenFile); // create map by def file
bool Relight(C4Rect To);
bool ApplyLighting(C4Rect To);
DWORD GetClrByTex(int32_t iX, int32_t iY);
bool Mat2Pal(); // assign material colors to landscape palette
void DigFreeSinglePix(int32_t x, int32_t y, int32_t dx, int32_t dy)
{
if(GetDensity(x, y) > GetDensity(x + dx, y + dy))
DigFreePix(x, y);
}
void UpdatePixCnt(const class C4Rect &Rect, bool fCheck = false);
void UpdateMatCnt(C4Rect Rect, bool fPlus);
void PrepareChange(C4Rect BoundingBox);
void FinishChange(C4Rect BoundingBox);
static bool DrawLineLandscape(int32_t iX, int32_t iY, int32_t iGrade);
public:
void CompileFunc(StdCompiler *pComp); // without landscape bitmaps and sky
bool DebugSave(const char *szFilename);
};
/* Some global landscape functions */
BOOL AboveSolid(int32_t &rx, int32_t &ry);
BOOL AboveSemiSolid(int32_t &rx, int32_t &ry);
BOOL SemiAboveSolid(int32_t &rx, int32_t &ry);
BOOL FindSolidGround(int32_t &rx, int32_t &ry, int32_t width);
BOOL FindLiquid(int32_t &rx, int32_t &ry, int32_t width, int32_t height);
BOOL FindSurfaceLiquid(int32_t &rx, int32_t &ry, int32_t width, int32_t height);
BOOL FindLevelGround(int32_t &rx, int32_t &ry, int32_t width, int32_t hrange);
BOOL FindConSiteSpot(int32_t &rx, int32_t &ry, int32_t wdt, int32_t hgt, DWORD category, int32_t hrange=-1);
BOOL FindThrowingPosition(int32_t iTx, int32_t iTy, FIXED fXDir, FIXED fYDir, int32_t iHeight, int32_t &rX, int32_t &rY);
BOOL PathFree(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t *ix=NULL, int32_t *iy=NULL);
BOOL PathFreeIgnoreVehicle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t *ix=NULL, int32_t *iy=NULL);
BOOL FindClosestFree(int32_t &rX, int32_t &rY, int32_t iAngle1, int32_t iAngle2, int32_t iExcludeAngle1, int32_t iExcludeAngle2);
BOOL ConstructionCheck(C4ID id, int32_t iX, int32_t iY, C4Object *pByObj=NULL);
#endif

View File

@ -0,0 +1,33 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// Loads StringTbl* and replaces $..$-strings by localized versions
#ifndef INC_C4LangStringTable
#define INC_C4LangStringTable
#include "C4ComponentHost.h"
class C4LangStringTable : public C4ComponentHost
{
public:
// do replacement in buffer
// if any replacement is done, the buffer will be realloced
void ReplaceStrings(StdStrBuf &rBuf);
void ReplaceStrings(const StdStrBuf &rBuf, StdStrBuf &rTarget, const char *szParentFilePath = NULL);
};
#endif // INC_C4LangStringTable

View File

@ -0,0 +1,99 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Language module controlling external language packs */
#ifndef INC_C4Language
#define INC_C4Language
#include <C4Group.h>
#include <C4GroupSet.h>
#ifdef HAVE_ICONV
#include <iconv.h>
#endif
const int C4MaxLanguageInfo = 1024;
class C4Language;
class C4LanguageInfo
{
friend class C4Language;
public:
char Code[2 + 1];
char Name[C4MaxLanguageInfo + 1];
char Info[C4MaxLanguageInfo + 1];
char Fallback[C4MaxLanguageInfo + 1];
char Charset[C4MaxLanguageInfo + 1];
//char Location[C4MaxLanguageInfo + 1]; ...store group name here
protected:
C4LanguageInfo* Next;
};
class C4Language
{
public:
C4Language();
~C4Language();
protected:
C4Group PackDirectory;
C4GroupSet Packs;
C4GroupSet PackGroups;
C4LanguageInfo* Infos;
char PackGroupLocation[_MAX_FNAME + 1];
public:
bool CloseGroup(const char *strPath);
void ClearLanguage();
// Initialization
bool Init();
void Clear();
// Handling of external language packs
int GetPackCount();
C4GroupSet& GetPackGroups(const char *strRelativePath);
// Handling of language info loaded from string tables
int GetInfoCount();
C4LanguageInfo *GetInfo(int iIndex);
C4LanguageInfo *FindInfo(const char *strCode);
// Loading of actual resource string table
bool LoadLanguage(const char *strLanguages);
// Encoding conversion functions
static StdStrBuf IconvClonk(const char * string);
static StdStrBuf IconvSystem(const char * string);
static StdStrBuf IconvUtf8(const char * string);
protected:
// Handling of language info loaded from string tables
void InitInfos();
void LoadInfos(C4Group &hGroup);
// Loading of actual resource string table
bool InitStringTable(const char *strCode);
bool LoadStringTable(C4Group &hGroup, const char *strCode);
#ifdef HAVE_ICONV
static iconv_t local_to_host;
static iconv_t host_to_local;
static iconv_t local_to_utf_8;
static StdStrBuf Iconv(const char * string, iconv_t cd);
#endif
};
extern C4Language Languages;
static inline StdStrBuf LoadResStrUtf8(const char* ident)
{
return Languages.IconvUtf8(LoadResStr(ident));
}
#endif

View File

@ -0,0 +1,269 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* engine handler of league system */
#ifndef C4LEAGUE_H_INCLUDED
#define C4LEAGUE_H_INCLUDED
#include <openssl/sha.h>
#include <C4Network2Reference.h>
#include <C4Gui.h>
#define C4League_Name_Valid_Characters "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD9\xDA\xDB\xDC\xDD\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF\x20\x2E\x2D\x5F"
// maximum league count a game can run in
const int32_t C4NetMaxLeagues = 10;
enum C4LeagueAction
{
C4LA_None, // no action
C4LA_Start, // [host] Game registration
C4LA_Update, // [host] Game status update (heartbeat)
C4LA_End, // [host] Final game status
C4LA_PlrAuthCheck,// [host] Player authentication check
C4LA_RefQuery, // [client] Query reference list
C4LA_PlrAuth, // [client] Player authentication request
C4LA_ReportDisconnect, // [both] Sent by host and client when a client is disconnected irregularly
};
class C4LeagueRequestHead
{
public:
C4LeagueRequestHead(C4LeagueAction eAction, const char *szCSID = "", const char *szAUID = "")
: eAction(eAction), CSID(szCSID), AUID(szAUID)
{ }
private:
C4LeagueAction eAction;
StdCopyStrBuf CSID;
StdCopyStrBuf AUID;
// Auth
StdCopyStrBuf Account;
StdCopyStrBuf Password;
StdCopyStrBuf NewAccount;
StdCopyStrBuf NewPassword;
public:
void SetAuth(const char *szAccount, const char *szPassword);
void SetNewAccount(const char *szNewAccount);
void SetNewPassword(const char *szNewPassword);
void CompileFunc(StdCompiler *pComp);
};
class C4LeagueReportDisconnectHead : public C4LeagueRequestHead
{
private:
C4LeagueDisconnectReason eReason;
public:
C4LeagueReportDisconnectHead(const char *szCSID, C4LeagueDisconnectReason eReason) : eReason(eReason), C4LeagueRequestHead(C4LA_ReportDisconnect, szCSID, NULL) {}
public:
void CompileFunc(StdCompiler *pComp);
};
class C4LeagueRequestHeadEnd : public C4LeagueRequestHead
{
public:
C4LeagueRequestHeadEnd(C4LeagueAction eAction, const char *szCSID, const char *szRecordName = NULL, const BYTE *pRecordSHA = NULL)
: C4LeagueRequestHead(eAction, szCSID), RecordName(szRecordName)
{
if(pRecordSHA)
memcpy(RecordSHA, pRecordSHA, SHA_DIGEST_LENGTH);
}
private:
StdCopyStrBuf RecordName;
uint8_t RecordSHA[SHA_DIGEST_LENGTH];
public:
void CompileFunc(StdCompiler *pComp);
};
class C4LeagueResponseHead
{
public:
C4LeagueResponseHead() { }
private:
StdCopyStrBuf Status;
StdCopyStrBuf CSID;
StdCopyStrBuf Message;
// Auth
StdCopyStrBuf Account;
StdCopyStrBuf AUID;
StdCopyStrBuf FBID;
public:
const char *getCSID() const { return CSID.getData(); }
const char *getMessage() const { return Message.getData(); }
bool isSuccess() const { return SEqualNoCase(Status.getData(), "Success"); }
bool isStatusRegister() const { return SEqualNoCase(Status.getData(), "Register"); }
const char *getAccount() const { return Account.getData(); }
const char *getAUID() const { return AUID.getData(); }
const char *getFBID() const { return FBID.getData(); }
void CompileFunc(StdCompiler *pComp);
};
class C4LeagueResponseHeadStart : public C4LeagueResponseHead
{
private:
StdCopyStrBuf League;
StdCopyStrBuf StreamingAddr;
int32_t fHaveSeed;
int32_t iSeed;
int32_t iMaxPlayers;
public:
const char *getLeague() const { return League.getData(); }
const char *getStreamingAddr() const { return StreamingAddr.getData(); }
bool haveSeed() const { return !!fHaveSeed; }
int32_t getSeed() const { return iSeed; }
int32_t getMaxPlayers() const { return iMaxPlayers; }
void CompileFunc(StdCompiler *pComp);
};
class C4LeagueResponseHeadUpdate : public C4LeagueResponseHead
{
private:
StdCopyStrBuf League;
C4ClientPlayerInfos PlrInfos;
public:
const char *getLeague() const { return League.getData(); }
const C4ClientPlayerInfos &GetPlrInfos() const { return PlrInfos; }
void CompileFunc(StdCompiler *pComp);
};
class C4LeagueResponseHeadAuthCheck : public C4LeagueResponseHead
{
private:
StdCopyStrBuf Leagues[C4NetMaxLeagues];
int32_t Scores[C4NetMaxLeagues];
int32_t Ranks[C4NetMaxLeagues];
int32_t RankSymbols[C4NetMaxLeagues];
StdCopyStrBuf ClanTag;
public:
int32_t getScore(const char *szLeague) const;
int32_t getRank(const char *szLeague) const;
int32_t getRankSymbol(const char *szLeague) const;
const char *getClanTag() const { return ClanTag.getData(); }
void CompileFunc(StdCompiler *pComp);
};
// a linked list of all known feedback IDs, associated to player IDs
class C4LeagueFBIDList
{
private:
struct FBIDItem
{
StdCopyStrBuf Account;
StdCopyStrBuf FBID;
FBIDItem *pNext;
} *pFirst;
public:
C4LeagueFBIDList() : pFirst(NULL) {}
~C4LeagueFBIDList() { Clear(); }
void Clear();
void RemoveFBIDByAccount(const char *szAccount);
bool FindFBIDByAccount(const char *szAccount, StdStrBuf *pFBIDOut);
void AddFBID(const char *szFBID, const char *szAccount);
};
class C4LeagueClient : public C4Network2RefClient
{
private:
StdCopyStrBuf CSID;
C4LeagueAction eCurrAction;
C4LeagueFBIDList FBIDList;
public:
C4LeagueClient() : CSID(), eCurrAction(C4LA_None), C4Network2RefClient() { }
const char *getCSID() const { return CSID.getData(); }
C4LeagueAction getCurrentAction() const { return eCurrAction; }
void ResetCurrentAction() { eCurrAction = C4LA_None; }
// Action "Start"
bool Start(const C4Network2Reference &Ref);
bool GetStartReply(StdStrBuf *pMessage, StdStrBuf *pLeague, StdStrBuf *pStreamingAddr, int32_t *pSeed, int32_t *pMaxPlayers);
// Action "Update"
bool Update(const C4Network2Reference &Ref);
bool GetUpdateReply(StdStrBuf *pMessage, C4ClientPlayerInfos *pPlayerLeagueInfos);
// Action "End"
bool End(const C4Network2Reference &Ref, const char *szRecordName, const BYTE *pRecordSHA);
bool GetEndReply(StdStrBuf *pMessage, class C4RoundResultsPlayers *pRoundResults);
// Action "Auth"
bool Auth(const C4PlayerInfo &PlrInfo, const char *szAccount, const char *szPassword, const char *szNewAccount = NULL, const char *szNewPassword = NULL);
bool GetAuthReply(StdStrBuf *pMessage, StdStrBuf *pAUID, StdStrBuf *pAccount, bool *pRegister);
// Action "Join"
bool AuthCheck(const C4PlayerInfo &PlrInfo);
bool GetAuthCheckReply(StdStrBuf *pMessage, const char *szLeague, class C4PlayerInfo *pPlrInfo);
// Action "Disconnect" - sent by host and client when one or more clients are disconnected irregularly
bool ReportDisconnect(const C4ClientPlayerInfos &rSendPlayerFBIDs, C4LeagueDisconnectReason eReason);
bool GetReportDisconnectReply(StdStrBuf *pMessage);
};
// dialog shown for each participating player to enter league authentication data
class C4LeagueSignupDialog : public C4GUI::Dialog
{
private:
C4GUI::CheckBox *pChkPassword;
C4GUI::LabeledEdit *pEdtAccount, *pEdtPass, *pEdtPass2;
C4GUI::Button *pBtnOK, *pBtnAbort;
int32_t iEdtPassSpace;
StdStrBuf strPlayerName;
public:
C4LeagueSignupDialog(const char *szPlayerName, const char *szLeagueName, const char *szLeagueServerName, const char *szAccountPref, const char *szPassPref, bool fWarnThirdParty, bool fRegister);
~C4LeagueSignupDialog() {}
const char *GetAccount() { return pEdtAccount->GetText(); }
bool HasPass() { return !pChkPassword || pChkPassword->GetChecked(); }
const char *GetPass() { return pEdtPass->GetText(); }
// check for errors (overridden)
virtual void UserClose(bool fOK);
// show modal league dialog to query password for player; return
static bool ShowModal(const char *szPlayerName, const char *szLeagueName, const char *szLeagueServerName, StdStrBuf *psAccount, StdStrBuf *psPass, bool fWarnThirdParty, bool fRegister);
private:
void OnChkPassword();
};
#endif // C4LEAGUE_H_INCLUDED

View File

@ -0,0 +1,44 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2003-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// startup screen
#ifndef INC_C4LoaderScreen
#define INC_C4LoaderScreen
#include <C4FacetEx.h>
class C4LoaderScreen
{
public:
CStdFont &TitleFont; // font used for title output
CStdFont &LogFont; // font used for logging
C4FacetSurface fctBackground; // background image
char *szInfo; // info text to be drawn on loader screen
bool fBlackScreen; // if set, a black screen is drawn instead of a loader
public:
C4LoaderScreen(); // ctor
~C4LoaderScreen(); // dtor
bool Init(const char *szLoaderSpec); // inits and loads from global C4Game-class
void SetBlackScreen(bool fIsBlack); // enabled/disables drawing of loader screen
int SeekLoaderScreens(C4Group &rFromGrp, const char *szWildcard, int iLoaderCount, char *szDstName, C4Group **ppDestGrp);
void Draw(C4Facet &cgo, int iProgress=0, class C4LogBuffer *pLog=NULL, int Process=0); // draw loader screen (does not page flip!)
};
#endif //INC_C4LoaderScreen

47
engine/inc/C4Log.h 100644
View File

@ -0,0 +1,47 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Log file handling */
#ifndef INC_C4Log
#define INC_C4Log
#include <StdBuf.h>
#include <StdCompiler.h>
BOOL OpenLog();
BOOL CloseLog();
/* Declared in Standard.h
BOOL LogSilent(const char *szMessage);
BOOL Log(const char *szMessage);
BOOL LogSilentF(const char *strMessage, ...) GNUC_FORMAT_ATTRIBUTE;
BOOL LogF(const char *strMessage, ...) GNUC_FORMAT_ATTRIBUTE;*/
BOOL DebugLog(const char *strMessage);
BOOL DebugLogF(const char *strMessage ...) GNUC_FORMAT_ATTRIBUTE;
bool LogFatal(const char *szMessage); // log message and store it as a fatal error
void ResetFatalError(); // clear any fatal error message
const char *GetFatalError(); // return message that was set as fatal error, if any
BOOL CompileError(bool fWarning, StdCompiler::Exception *Exc);
size_t GetLogPos(); // get current log position;
bool GetLogSection(size_t iStart, size_t iLength, StdStrBuf &rsOut); // re-read log data from file
// Used to print a backtrace after a crash
int GetLogFD();
#endif

View File

@ -0,0 +1,62 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// a buffer holding a log history
#ifndef INC_C4LogBuf
#define INC_C4LogBuf
// circular log buffer to holding line-wise log data
class C4LogBuffer
{
private:
struct LineData
{
CStdFont *pFont; // line font
DWORD dwClr; // line clr
bool fNewParagraph; // if set, this line marks a new paragraph (and is not the wrapped line of a previous par)
};
char *szBuf; // string buffer
LineData *pLineDataBuf; // line data buffer
int iBufSize; // size of string buffer
int iFirstLinePos, iAfterLastLinePos; // current string buffer positions
int iLineDataPos, iNextLineDataPos; // current line data buffer positions
int iMaxLineCount; // max number of valid lines - size of line data buffer
int iLineCount; // number of valid lines in buffer
int iLineBreakWidth; // line breaking width
char *szIndent; // chars inserted as indent space
bool fDynamicGrow; // if true, lines are always added to the buffer. If false, the buffer is used circular and old lines removed
bool fMarkup; // if set, '|' is treated as linebreak
void GrowLineCountBuffer(size_t iGrowBy);
void GrowTextBuffer(size_t iGrowBy);
void DiscardFirstLine(); // discard oldest line in buffer
void AppendSingleLine(const char *szLine, int iLineLength, const char *szIndent, CStdFont *pFont, DWORD dwClr, bool fNewParagraph); // append given string as single line
public:
C4LogBuffer(int iSize, int iMaxLines, int iLBWidth, const char *szIndentChars=" ", bool fDynamicGrow = false, bool fMarkup = true); // ctor
~C4LogBuffer(); // dtor
void AppendLines(const char *szLine, CStdFont *pFont, DWORD dwClr, CStdFont *pFirstLineFont=NULL); // append message line to buffer; overwriting old lines if necessary
const char *GetLine(int iLineIndex, CStdFont **ppFont, DWORD *pdwClr, bool *pNewParagraph) const; // get indexed line - negative indices -n return last-n'th-line
void Clear(); // clear all lines
int GetCount() const { return iLineCount; }// retrieve number of valid lines in buffer
void SetLBWidth(int iToWidth);
};
#endif // C4LogBuf

View File

@ -0,0 +1,76 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// Engine internal C4Menus: Main menu, Options, Player join, Hostility, etc.
#ifndef INC_C4MainMenu
#define INC_C4MainMenu
#include "C4Menu.h"
// Menu identification constants for main menus
enum
{
C4MN_Hostility = 1, // identification for hostility menu
C4MN_Main = 2, // identification for all other menus
C4MN_TeamSelection= 3,
C4MN_TeamSwitch = 4,
C4MN_Observer = 5,
};
class C4MainMenu : public C4Menu
{
public:
C4MainMenu();
virtual void Default();
protected:
int32_t Player;
public:
bool Init(C4FacetSurface &fctSymbol, const char *szEmpty, int32_t iPlayer, int32_t iExtra=C4MN_Extra_None, int32_t iExtraData=0, int32_t iId=0, int32_t iStyle=C4MN_Style_Normal);
bool InitRefSym(const C4Facet &fctSymbol, const char *szEmpty, int32_t iPlayer, int32_t iExtra=C4MN_Extra_None, int32_t iExtraData=0, int32_t iId=0, int32_t iStyle=C4MN_Style_Normal);
bool ActivateMain(int32_t iPlayer);
bool ActivateNewPlayer(int32_t iPlayer);
bool ActivateHostility(int32_t iPlayer);
bool ActivateGoals(int32_t iPlayer, bool fDoActivate);
bool ActivateRules(int32_t iPlayer);
bool ActivateSavegame(int32_t iPlayer);
bool ActivateHost(int32_t iPlayer);
bool ActivateClient(int32_t iPlayer);
bool ActivateOptions(int32_t iPlayer, int32_t selection = 0);
bool ActivateDisplay(int32_t iPlayer, int32_t selection = 0);
bool ActivateSurrender(int32_t iPlayer);
bool ActivateObserver();
protected:
virtual bool MenuCommand(const char *szCommand, bool fIsCloseCommand);
virtual bool DoRefillInternal(bool &rfRefilled);
virtual void OnSelectionChanged(int32_t iNewSelection);
virtual void OnUserSelectItem(int32_t Player, int32_t iIndex);
virtual void OnUserEnter(int32_t Player, int32_t iIndex, bool fRight);
virtual void OnUserClose();
virtual int32_t GetControllingPlayer() { return Player; }
public:
bool ActivateCommand(int32_t iPlayer, const char *szCommand);
};
#endif

51
engine/inc/C4Map.h 100644
View File

@ -0,0 +1,51 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Create map from dynamic landscape data in scenario */
#ifndef INC_C4Map
#define INC_C4Map
#include <C4Scenario.h>
class C4MapCreator
{
public:
C4MapCreator();
protected:
int32_t MapIFT;
CSurface8 *MapBuf;
int32_t MapWdt,MapHgt;
int32_t Exclusive;
public:
void Create(CSurface8 *sfcMap,
C4SLandscape &rLScape, C4TextureMap &rTexMap,
BOOL fLayers=FALSE, int32_t iPlayerNum=1);
BOOL Load(BYTE **pbypBuffer,
int32_t &rBufWdt, int32_t &rMapWdt, int32_t &rMapHgt,
C4Group &hGroup, const char *szEntryName,
C4TextureMap &rTexMap);
protected:
void Reset();
void SetPix(int32_t x, int32_t y, BYTE col);
void SetSpot(int32_t x, int32_t y, int32_t rad, BYTE col);
void DrawLayer(int32_t x, int32_t y, int32_t size, BYTE col);
void ValidateTextureIndices(C4TextureMap &rTexMap);
BYTE GetPix(int32_t x, int32_t y);
};
#endif

View File

@ -0,0 +1,410 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// complex dynamic landscape creator
#ifndef INC_C4MapCreatorS2
#define INC_C4MapCreatorS2
#include <C4Group.h>
#include <C4Scenario.h>
#include <C4Surface.h>
#define C4MC_SizeRes 100 // positions in percent
#define C4MC_ZoomRes 100 // zoom resolution (-100 to +99)
// string consts
#define C4MC_Overlay "overlay" // overlay node
#define C4MC_Point "point" // polygon point
#define C4MC_Map "map" // map node
#define C4MC_DefAlgo "solid" // default overlay algorithm
// error messages
#define C4MCErr_404 "file not found"
#define C4MCErr_NoGroup "internal error: no group"
#define C4MCErr_EOF "unexpected end of file"
#define C4MCErr_NoDirGlobal "can't use directives in local scope"
#define C4MCErr_UnknownDir "unknown directive: %s"
#define C4MCErr_MapNoGlobal "can't declare map in local scope"
#define C4MCErr_OpTypeErr "operator type mismatch"
#define C4MCErr_IdtfExp "identifier expected"
#define C4MCErr_UnnamedNoGlbl "unnamed objects not allowed in global scope"
#define C4MCErr_BlOpenExp "'{' expected"
#define C4MCErr_OpsNoGlobal "operators not allowed in global scope"
#define C4MCErr_SColonOrOpExp "';' or operator expected"
#define C4MCErr_Obj2Exp "second operand expected"
#define C4MCErr_ReinstNoGlobal "can't reinstanciate object '%s' in global scope"
#define C4MCErr_UnknownObj "unknown object: %s"
#define C4MCErr_ReinstUnknown "can't reinstanciate '%s'; object type is unknown"
#define C4MCErr_EqSColonBlOpenExp "'=', ';' or '{' expected"
#define C4MCErr_FieldConstExp "constant for field '%s' expected"
#define C4MCErr_SColonExp "';' expected"
#define C4MCErr_Field404 "field '%s' not found"
#define C4MCErr_FieldValInvalid "'%s' is not a valid value for this field"
#define C4MCErr_MatNotFound "material '%s' not found"
#define C4MCErr_TexNotFound "texture '%s' not found"
#define C4MCErr_AlgoNotFound "algorithm '%s' not found"
#define C4MCErr_SFuncNotFound "script func '%s' not found in scenario script"
#define C4MCErr_PointOnlyOvl "point only allowed in overlays"
// predef
class C4MCCallbackArray;
class C4MCCallbackArrayList;
class C4MCNode;
class C4MCOverlay;
class C4MCPoint;
class C4MCMap;
class C4MapCreatorS2;
class C4MCParserErr;
class C4MCParser;
struct C4MCAlgorithm
{
char Identifier[C4MaxName];
bool (*Function) (C4MCOverlay*, int32_t, int32_t);
};
extern C4MCAlgorithm C4MCAlgoMap[];
// node type enum
enum C4MCNodeType { MCN_Node, MCN_Overlay, MCN_Point, MCN_Map };
// one token type
enum C4MCTokenType
{
MCT_NONE, // nothing
MCT_DIR, // directive (stored in CurrTokenIdtf)
MCT_IDTF, // identifier (stored in CurrTokenIdtf)
MCT_INT, // integer constant (stored in CurrTokenVal)
MCT_EQ, // =
MCT_BLOPEN, // {
MCT_BLCLOSE,// }
MCT_SCOLON, // ;
MCT_AND, // &
MCT_OR, // |
MCT_XOR, // ^
MCT_RANGE, // -
MCT_PERCENT,// integer constant (stored in CurrTokenVal) + %
MCT_PX, // integer constant (stored in CurrTokenVal) + px
MCT_EOF // end of file
};
// a callback array
// contains a script func, and a map to call the func for
class C4MCCallbackArray
{
public:
C4MCCallbackArray(C4AulFunc *pSFunc, C4MapCreatorS2 *pMapCreator); // ctor
~C4MCCallbackArray(); // dtor
protected:
C4MapCreatorS2 *pMapCreator; // map creator class to query current map of
BYTE *pMap; // bitmap whether or not to call the function for a map pixel
int32_t iWdt, iHgt; // size of the bitmap, when created
C4AulFunc *pSF; // script func to be called
C4MCCallbackArray *pNext; // next array in linked list
public:
void EnablePixel(int32_t iX, int32_t iY); // enable pixel in map; create map if necessary
void Execute(int32_t iMapZoom); // evaluate the array
friend class C4MCCallbackArrayList;
};
// callback array list: contains all callbacks
class C4MCCallbackArrayList
{
public:
C4MCCallbackArrayList() { pFirst=NULL; } // ctor
~C4MCCallbackArrayList() { Clear(); } // ctor
protected:
C4MCCallbackArray *pFirst; // first array in list
public:
void Add(C4MCCallbackArray *pNewArray); // add given array to list
void Clear(); // clear the list
void Execute(int32_t iMapZoom);// execute all arrays
};
// generic map creator tree node
// the code has been STL-free so far, so keep the line
class C4MCNode
{
public:
C4MCNode *Owner, *Child0, *ChildL, *Prev, *Next; // tree structure
C4MapCreatorS2 *MapCreator; // owning map creator
char Name[C4MaxName]; // name, if named
public:
C4MCNode(C4MCNode *pOwner=NULL); // constructor
C4MCNode(C4MCNode *pOwner, C4MCNode &rTemplate, bool fClone); // constructor using template
virtual ~C4MCNode(); // destructor
virtual C4MCNode *clone(C4MCNode *pToNode) { return new C4MCNode(pToNode, *this, true); }
void Clear(); // clear all child nodes
void Reg2Owner(C4MCNode *pOwner); // register into list
protected:
virtual BOOL GlobalScope() { return FALSE; } // whether node is a global scope
virtual BOOL SetOp(C4MCTokenType eOp) { return FALSE; } // set following operator
C4MCNode *GetNodeByName(const char *szName); // search node by name
virtual bool SetField(C4MCParser *pParser, const char *szField, const char *szSVal, int32_t iVal, C4MCTokenType ValType); // set field
int32_t IntPar(C4MCParser *pParser, const char *szSVal, int32_t iVal, C4MCTokenType ValType); // ensure par is int32_t
const char *StrPar(C4MCParser *pParser, const char *szSVal, int32_t iVal, C4MCTokenType ValType); // ensure par is string
virtual void Evaluate() { } // called when all fields are initialized
void ReEvaluate(); // evaluate everything again
// For Percents and Pixels
class int_bool {
public:
int32_t Evaluate(int32_t relative_to)
{ if (percent) return value * relative_to / C4MC_SizeRes; else return value; }
void Set(int32_t value, bool percent)
{ this->value = value; this->percent = percent; }
private:
int32_t value;
bool percent;
};
public:
virtual C4MCNodeType Type() { return MCN_Node; } // get node type
virtual C4MCOverlay *Overlay() { return NULL; } // return overlay, if this is one
C4MCOverlay *OwnerOverlay(); // return an owner who is an overlay
friend class C4MCParser;
};
// node attribute entry for SetField search
enum C4MCValueType
{
C4MCV_None,
C4MCV_Integer,
C4MCV_Percent,
C4MCV_Pixels,
C4MCV_Material,
C4MCV_Texture,
C4MCV_Algorithm,
C4MCV_Boolean,
C4MCV_Zoom,
C4MCV_ScriptFunc,
};
struct C4MCNodeAttr
{
char Name[C4MaxName]; // name of field
C4MCValueType Type; // type of field
int32_t iOff; // offset of field in overlay MCOverlay-class
};
extern C4MCNodeAttr C4MCOvrlMap[];
// overlay node
class C4MCOverlay : public C4MCNode
{
public:
C4MCOverlay(C4MCNode *pOwner=NULL); // constructor
C4MCOverlay(C4MCNode *pOwner, C4MCOverlay &rTemplate, bool fClone); // construct of template
C4MCNode *clone(C4MCNode *pToNode) { return new C4MCOverlay(pToNode, *this, true); }
protected:
void Default(); // set default values for default presets
public:
int32_t Seed; // random seed
int32_t FixedSeed; // fixed random seed set in def
int32_t X,Y,Wdt,Hgt,OffX,OffY; // extends/offset
int_bool RX, RY, RWdt, RHgt, ROffX, ROffY; // extends/offset relatively to owner
int32_t Material; // material index
bool Sub; // tunnel bg?
char Texture[C4M_MaxName+1]; // texture name
BYTE MatClr; // resolved mat-tex color
C4MCTokenType Op; // following operator
C4MCAlgorithm *Algorithm; // algorithm to calc whether filled or not
int32_t Turbulence, Lambda, Rotate; // turbulence factors; rotation angle
int_bool Alpha, Beta; // extra params
int32_t ZoomX, ZoomY; // zoom factor for algorithm
bool Invert, LooseBounds, Group, Mask; // extra algo behaviour
C4MCCallbackArray *pEvaluateFunc; // function called for nodes being evaluated and fulfilled
C4MCCallbackArray *pDrawFunc; // function called when this node is drawn - pass drawcolor as first param, return color to be actually used
BOOL SetOp(C4MCTokenType eOp) { Op=eOp; return TRUE; } // set following operator
C4MCAlgorithm *GetAlgo(const char *szName);
bool SetField(C4MCParser *pParser, const char *szField, const char *szSVal, int32_t iVal, C4MCTokenType ValType); // set field
void Evaluate(); // called when all fields are initialized
C4MCOverlay *Overlay() { return this; } // this is an overlay
C4MCOverlay *FirstOfChain(); // go backwards in op chain until first overlay of chain
bool CheckMask(int32_t iX, int32_t iY); // check whether algorithms succeeds at iX/iY
bool RenderPix(int32_t iX, int32_t iY, BYTE &rPix, C4MCTokenType eLastOp=MCT_NONE, bool fLastSet=false, bool fDraw=true, C4MCOverlay **ppPixelSetOverlay=NULL); // render this pixel
bool PeekPix(int32_t iX, int32_t iY); // check mask; regard operator chain
bool InBounds(int32_t iX, int32_t iY) { return iX>=X && iY>=Y && iX<X+Wdt && iY<Y+Hgt; } // return whether point iX/iY is inside bounds
public:
C4MCNodeType Type() { return MCN_Overlay; } // get node type
friend class C4MapCreatorS2;
friend class C4MCParser;
};
// point of polygon node
class C4MCPoint : public C4MCNode
{
public:
C4MCPoint(C4MCNode *pOwner=NULL); // constructor
C4MCPoint(C4MCNode *pOwner, C4MCPoint &rTemplate, bool fClone); // construct of template
C4MCNode *clone(C4MCNode *pToNode) { return new C4MCPoint(pToNode, *this, true); }
protected:
void Default(); // set default values for default presets
public:
int32_t X,Y;
int_bool RX,RY;
virtual void Evaluate(); // called when all fields are initialized
bool SetField(C4MCParser *pParser, const char *szField, const char *szSVal, int32_t iVal, C4MCTokenType ValType); // set field
public:
C4MCNodeType Type() { return MCN_Point; } // get node type
friend class C4MapCreatorS2;
friend class C4MCParser;
};
// simply an overlay that can be rendered
class C4MCMap : public C4MCOverlay
{
public:
C4MCMap(C4MCNode *pOwner=NULL); // constructor
C4MCMap(C4MCNode *pOwner, C4MCMap &rTemplate, bool fClone); // construct of template
C4MCNode *clone(C4MCNode *pToNode) { return new C4MCMap(pToNode, *this, true); }
protected:
void Default(); // set default values for default presets
public:
bool RenderTo(BYTE *pToBuf, int32_t iPitch); // render to buffer
void SetSize(int32_t iWdt, int32_t iHgt);
public:
C4MCNodeType Type() { return MCN_Map; } // get node type
friend class C4MapCreatorS2;
friend class C4MCParser;
};
// main map creator class
class C4MapCreatorS2 : public C4MCNode
{
public:
C4MapCreatorS2(C4SLandscape *pLandscape, C4TextureMap *pTexMap, C4MaterialMap *pMatMap, int iPlayerCount); // constructor
~C4MapCreatorS2(); // destructor
void Default(); // set default data
void Clear(); // clear any data
BOOL ReadFile(const char *szFilename, C4Group *pGrp); // read defs of file
BOOL ReadScript(const char *szScript); // reads def directly from mem
public:
C4MCMap *GetMap(const char *szMapName); // get map by name
public:
#ifdef C4ENGINE
CSurface8 * Render(const char *szMapName); // create map surface
#endif
BYTE *RenderBuf(const char *szMapName, int32_t &sfcWdt, int32_t &sfcHgt); // create buffer and render it
void SetC4SLandscape(C4SLandscape *pLandscape) // update source for map size
{ Landscape=pLandscape; }
protected:
C4SLandscape *Landscape; // landsape presets
C4TextureMap *TexMap; // texture map
C4MaterialMap *MatMap; // material map
C4MCMap DefaultMap; // default template: landscape
C4MCOverlay DefaultOverlay; // default template: overlay
C4MCPoint DefaultPoint; // default template: point
C4MCMap *pCurrentMap; // map currently rendered
C4MCCallbackArrayList CallbackArrays; // list of callback arrays
int PlayerCount; // player count for MapPlayerExtend
BOOL GlobalScope() { return TRUE; } // it's the global node
public:
void ExecuteCallbacks(int32_t iMapZoom) { CallbackArrays.Execute(iMapZoom); }
friend class C4MCOverlay;
friend class C4MCMap;
friend class C4MCParser;
friend class C4MCCallbackArray;
};
// file parser for map creator
// parser error
class C4MCParserErr
{
public:
char Msg[C4MaxMessage]; // message string
C4MCParserErr(C4MCParser *pParser, const char *szMsg); // construct setting error msg
C4MCParserErr(C4MCParser *pParser, const char *szMsg, const char *szPar); // construct setting error msg
void show(); // log error
};
// the parser
class C4MCParser
{
private:
C4MapCreatorS2 *MapCreator; // map creator parsing into
char *Code; // loaded code
const char *CPos; // current parser pos in code
C4MCTokenType CurrToken; // last token read
char CurrTokenIdtf[C4MaxName]; // current token string
int32_t CurrTokenVal; // current token value
char Filename[C4MaxName]; // filename
BOOL AdvanceSpaces(); // advance to next token char; return whether EOF is reached
BOOL GetNextToken(); // get token, store in fields and advance to next; return whether not EOF
void ParseTo(C4MCNode *pToNode); // parse stuff into
void ParseValue(C4MCNode *pToNode, const char *szFieldName); // Set Field
public:
C4MCParser(C4MapCreatorS2 *pMapCreator); // constructor
~C4MCParser(); // destructor
void Clear(); // clear stuff
void ParseFile(const char *szFilename, C4Group *pGrp); // load and parse file
void Parse(const char *szScript); // load and parse from mem
friend class C4MCParserErr;
};
#endif

View File

@ -0,0 +1,63 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Move liquids in the landscape using individual transport spots */
#ifndef INC_C4MassMover
#define INC_C4MassMover
const int32_t C4MassMoverChunk = 10000;
class C4MassMoverSet;
class C4MassMover
{
friend class C4MassMoverSet;
protected:
int32_t Mat,x,y;
protected:
void Cease();
BOOL Execute();
BOOL Init(int32_t tx, int32_t ty);
BOOL Corrosion(int32_t dx, int32_t dy);
};
class C4MassMoverSet
{
public:
C4MassMoverSet();
~C4MassMoverSet();
public:
int32_t Count;
int32_t CreatePtr;
protected:
C4MassMover Set[C4MassMoverChunk];
public:
void Copy(C4MassMoverSet &rSet);
void Synchronize();
void Default();
void Clear();
void Draw();
void Execute();
BOOL Create(int32_t x, int32_t y, BOOL fExecute=FALSE);
BOOL Load(C4Group &hGroup);
BOOL Save(C4Group &hGroup);
protected:
void Consolidate();
};
#endif

View File

@ -0,0 +1,215 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Material definitions used by the landscape */
#ifndef INC_C4Material
#define INC_C4Material
#include <C4Id.h>
#include <C4Shape.h>
#include <C4Facet.h>
#include <vector>
#define C4MatOv_Default 0
#define C4MatOv_Exact 1
#define C4MatOv_None 2
#define C4MatOv_HugeZoom 4
#define C4MatOv_Monochrome 8
enum MaterialInteractionEvent
{
meePXSPos=0, // PXS check before movement
meePXSMove=1, // PXS movement
meeMassMove=2, // MassMover-movement
};
typedef bool (*C4MaterialReactionFunc)(struct C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
struct C4MaterialReaction
{
static inline bool NoReaction(struct C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged) { return false; }
C4MaterialReactionFunc pFunc; // Guarantueed to be non-NULL
bool fUserDefined; // false for internal reactions generated by material parameters
StdCopyStrBuf TargetSpec; // target material specification
StdCopyStrBuf ScriptFunc; // for reaction func 'script': Script func to be called for reaction evaluation
#ifdef C4ENGINE
C4AulFunc *pScriptFunc; // resolved script function
#endif
uint32_t iExecMask; // execution mask: Bit mask with indices into MaterialInteractionEvent
bool fReverse; // if set, spec will be handled as if specified in target mat def
bool fInverseSpec; // if set, all mats except the given are used
bool fInsertionCheck; // if set, splash/slide checks are done prior to reaction execution
int32_t iDepth; // in mat conversion depth
StdCopyStrBuf sConvertMat;// in mat conversion material (string)
int32_t iConvertMat; // in mat conversion material; evaluated in CrossMapMaterials
int32_t iCorrosionRate; // chance of doing a corrosion
#ifdef C4ENGINE
C4MaterialReaction(C4MaterialReactionFunc pFunc) : pFunc(pFunc), fUserDefined(false), pScriptFunc(NULL), iExecMask(~0u), fReverse(false), fInverseSpec(false), fInsertionCheck(true), iDepth(0), iConvertMat(-1), iCorrosionRate(100) {}
C4MaterialReaction() : pFunc(&NoReaction), fUserDefined(true), pScriptFunc(NULL), iExecMask(~0u), fReverse(false), fInverseSpec(false), fInsertionCheck(true), iDepth(0), iConvertMat(-1), iCorrosionRate(100) { }
#endif
void CompileFunc(StdCompiler *pComp);
#ifdef C4ENGINE
void ResolveScriptFuncs(const char *szMatName);
#endif
bool operator ==(const C4MaterialReaction &rCmp) const { return false; } // never actually called; only comparing with empty vector of C4MaterialReactions
};
class C4MaterialCore
{
public:
C4MaterialCore();
~C4MaterialCore() { Clear(); }
public:
std::vector<C4MaterialReaction> CustomReactionList;
public:
char Name[C4M_MaxName+1];
uint32_t Color[C4M_ColsPerMat*3];
uint32_t Alpha[C4M_ColsPerMat*2];
int32_t MapChunkType;
int32_t Density;
int32_t Friction;
int32_t DigFree;
int32_t BlastFree;
C4ID Dig2Object;
int32_t Dig2ObjectRatio;
int32_t Dig2ObjectOnRequestOnly;
C4ID Blast2Object;
int32_t Blast2ObjectRatio;
int32_t Blast2PXSRatio;
int32_t Instable;
int32_t MaxAirSpeed;
int32_t MaxSlide;
int32_t WindDrift;
int32_t Inflammable;
int32_t Incindiary;
int32_t Extinguisher;
int32_t Corrosive;
int32_t Corrode;
int32_t Soil;
int32_t Placement; // placement order for landscape shading
StdCopyStrBuf sTextureOverlay; // overlayed texture for this material
int32_t OverlayType; // defines the way in which the overlay texture is applied
StdCopyStrBuf sPXSGfx; // newgfx: picture used for loose pxs
C4TargetRect PXSGfxRt; // newgfx: facet rect of pixture used for loose pixels
int32_t PXSGfxSize;
StdCopyStrBuf sBlastShiftTo;
StdCopyStrBuf sInMatConvert;
StdCopyStrBuf sInMatConvertTo;
int32_t InMatConvertDepth; // material converts only if it finds the same material above
int32_t BelowTempConvert;
int32_t BelowTempConvertDir;
StdCopyStrBuf sBelowTempConvertTo;
int32_t AboveTempConvert;
int32_t AboveTempConvertDir;
StdCopyStrBuf sAboveTempConvertTo;
int32_t ColorAnimation;
int32_t TempConvStrength;
int32_t MinHeightCount; // minimum material thickness in order for it to be counted
int32_t SplashRate;
public:
void Clear();
void Default();
BOOL Load(C4Group &hGroup, const char *szEntryName);
DWORD GetDWordColor(int32_t iIndex); // get indexed material color as DWord
void CompileFunc(StdCompiler *pComp);
};
class C4Material: public C4MaterialCore
{
public:
C4Material();
public:
// Cross-mapped material values
int32_t BlastShiftTo; // MatTex
int32_t InMatConvertTo; // Mat
int32_t BelowTempConvertTo; // MatTex
int32_t AboveTempConvertTo; // MatTex
#ifdef C4ENGINE
int32_t DefaultMatTex; // texture used for single pixel values
CPattern MatPattern;
C4Facet PXSFace; // loose pixel facet
void UpdateScriptPointers(); // set all material script pointers
#endif
};
class C4MaterialMap
{
public:
C4MaterialMap();
~C4MaterialMap();
public:
int32_t Num;
C4Material *Map;
C4MaterialReaction **ppReactionMap;
C4MaterialReaction DefReactConvert, DefReactPoof, DefReactCorrode, DefReactIncinerate, DefReactInsert;
public:
// default reactions
static bool mrfConvert(C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
static bool mrfPoof (C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
static bool mrfCorrode(C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
static bool mrfIncinerate(C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
static bool mrfInsert (C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
// user-defined actions
#ifdef C4ENGINE
static bool mrfScript(C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged);
#endif
public:
void Default();
void Clear();
int32_t Load(C4Group &hGroup, C4Group* OverloadFile = 0);
bool HasMaterials(C4Group &hGroup) const;
int32_t Get(const char *szMaterial);
BOOL SaveEnumeration(C4Group &hGroup);
BOOL LoadEnumeration(C4Group &hGroup);
C4MaterialReaction *GetReactionUnsafe(int32_t iPXSMat, int32_t iLandscapeMat)
{ assert(ppReactionMap); assert(Inside<int32_t>(iPXSMat,-1,Num-1)); assert(Inside<int32_t>(iLandscapeMat,-1,Num-1));
return ppReactionMap[(iLandscapeMat+1)*(Num+1) + iPXSMat+1]; }
C4MaterialReaction *GetReaction(int32_t iPXSMat, int32_t iLandscapeMat);
#ifdef C4ENGINE
void UpdateScriptPointers(); // set all material script pointers
void CrossMapMaterials();
#endif
protected:
void SetMatReaction(int32_t iPXSMat, int32_t iLSMat, C4MaterialReaction *pReact);
BOOL SortEnumeration(int32_t iMat, const char *szMatName);
};
const int32_t C4M_Flat = 0,
C4M_TopFlat = 1,
C4M_Smooth = 2,
C4M_Rough = 3,
// Material Density Levels
C4M_Vehicle = 100,
C4M_Solid = 50,
C4M_SemiSolid = 25,
C4M_Liquid = 25,
C4M_Background= 0;
const int32_t MNone = -1;
#endif

View File

@ -0,0 +1,41 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* A primitive list to store one amount value per mapped material */
#ifndef INC_C4MaterialList
#define INC_C4MaterialList
#include <C4Landscape.h>
class C4MaterialList
{
public:
C4MaterialList();
~C4MaterialList();
public:
int32_t Amount[C4MaxMaterial];
public:
void Default();
void Clear();
void Reset();
int32_t Get(int32_t iMaterial);
void Add(int32_t iMaterial, int32_t iAmount);
void Set(int32_t iMaterial, int32_t iAmount);
};
#endif // INC_C4MaterialList

261
engine/inc/C4Menu.h 100644
View File

@ -0,0 +1,261 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* In-game menu as used by objects, players, and fullscreen options */
#ifndef INC_C4Menu
#define INC_C4Menu
#include "C4Id.h"
#include "C4FacetEx.h"
#include "C4Shape.h"
#include "C4Gui.h"
#include "C4IDList.h"
enum {
C4MN_SymbolSize = 16,
C4MN_FrameWidth = 2
};
enum {
C4MN_Style_Normal = 0,
C4MN_Style_Context = 1,
C4MN_Style_Info = 2,
C4MN_Style_Dialog = 3,
C4MN_Style_BaseMask = 127,
C4MN_Style_EqualItemHeight = 128
};
enum {
C4MN_Extra_None = 0,
C4MN_Extra_Components = 1,
C4MN_Extra_Value = 2,
C4MN_Extra_MagicValue = 3,
C4MN_Extra_Info = 4,
C4MN_Extra_ComponentsMagic= 5,
C4MN_Extra_LiveMagicValue = 6,
C4MN_Extra_ComponentsLiveMagic = 7,
};
enum {
C4MN_Align_Left = 1,
C4MN_Align_Right = 2,
C4MN_Align_Top = 4,
C4MN_Align_Bottom = 8,
C4MN_Align_Free = 16
};
enum {
C4MN_Item_NoCount = 12345678
};
enum {
C4MN_AdjustPosition = 1<<31,
};
void DrawMenuSymbol(int32_t iMenu, C4Facet &cgo, int32_t iOwner, C4Object *cObj);
class C4MenuItem : public C4GUI::Element
{
friend class C4Menu;
public:
~C4MenuItem();
protected:
char Caption[C4MaxTitle+1];
char Command[_MAX_FNAME+30+1];
char Command2[_MAX_FNAME+30+1];
char InfoCaption[2*C4MaxTitle+1];
int32_t Count;
C4ID id;
C4Object *Object;
C4FacetSurface Symbol;
uint32_t dwSymbolClr;
bool fOwnValue; // if set, a specific value is to be shown
int32_t iValue; // specific value to be shown
bool fSelected; // item is selected; set by menu
int32_t iStyle;
class C4Menu *pMenu;
int32_t iIndex;
bool IsSelectable;
int32_t TextDisplayProgress; // dialog menus only: Amount of text which is to be displayed already (-1 for everything)
C4IDList Components; // components to be displayed in info line if item is selected
private:
bool IsDragElement();
int32_t GetSymbolWidth(int32_t iForHeight);
protected:
virtual void DrawElement(C4TargetFacet &cgo); // draw menu item
// ctor
C4MenuItem(C4Menu *pMenu, int32_t iIndex, const char *szCaption, const char *szCommand,
int32_t iCount, C4Object *pObject, const char *szInfoCaption,
C4ID idID, const char *szCommand2, bool fOwnValue, int32_t iValue, int32_t iStyle, bool fIsSelectable);
void GrabSymbol(C4FacetSurface &fctSymbol) { Symbol.GrabFrom(fctSymbol); if (Symbol.Surface) dwSymbolClr=Symbol.Surface->GetClr(); }
void RefSymbol(const C4Facet &fctSymbol) { Symbol.Set(fctSymbol); if (Symbol.Surface) dwSymbolClr=Symbol.Surface->GetClr(); }
void SetSelected(bool fToVal) { fSelected = fToVal; }
void DoTextProgress(int32_t &riByVal); // progress number of shown characters by given amount
// GUI calls
virtual void MouseInput(class C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyParam); // input: mouse movement or buttons
virtual void MouseEnter(class C4GUI::CMouse &rMouse); // called when mouse cursor enters element region: Select this item (deselects any other)
virtual void DoDragging(class C4GUI::CMouse &rMouse, int32_t iX, int32_t iY, DWORD dwKeyParam); // called by mouse: dragging process
virtual void StopDragging(class C4GUI::CMouse &rMouse, int32_t iX, int32_t iY, DWORD dwKeyParam); // called by mouse: mouse released after dragging process
public:
C4ID GetC4ID() const { return id; }
C4Object *GetObject() const { return Object; }
const char *GetCommand() const { return Command; }
void ClearObject() { Object = NULL; }
};
class C4Menu : public C4GUI::Dialog
{
typedef C4GUI::Dialog BaseClass;
public:
C4Menu();
~C4Menu() { Clear(); }
void Clear();
virtual void Default();
protected:
BOOL LocationSet;
BOOL Permanent;
BOOL NeedRefill;
int32_t Style;
int32_t Selection,TimeOnSelection;
int32_t ItemCount;
int32_t ItemWidth,ItemHeight;
int32_t Extra,ExtraData;
int32_t DrawMenuControls;
int32_t Identification;
int32_t Columns; // sync
int32_t Lines; // async
int32_t Alignment;
int32_t VisibleCount;
int32_t LastSelection; // used by AutoContextMenus
StdStrBuf CloseCommand; // script command that will be executed on menu close
char Caption[C4MaxTitle+1];
C4FacetSurface Symbol;
C4GUI::ScrollWindow *pClientWindow; // window containing the menu items
bool fHasPortrait; // if set, first menu item is used at a portrait at topleft of menu
bool fTextProgressing; // if true, text is being shown progressively (dialog menus)
bool fEqualIconItemHeight; // for dialog menus only: If set, all options with an icon are forced to have the same height
bool fActive; // set if menu is shown - independant of GUI to keep synchronized when there's no GUI
public:
BOOL ConvertCom(int32_t &rCom, int32_t &rData, bool fAsyncConversion);
void ClearPointers(C4Object *pObj);
BOOL Refill();
void Execute();
void SetPermanent(BOOL fPermanent);
void SetAlignment(int32_t iAlignment);
int32_t GetIdentification();
int32_t GetItemCount();
int32_t GetPosition();
int32_t GetSelection();
bool IsContextMenu() { return Style == C4MN_Style_Context; }
int GetSymbolSize() { return (Style == C4MN_Style_Dialog) ? 64 : C4SymbolSize; }
int32_t GetItemHeight() { return ItemHeight; }
C4MenuItem* GetSelectedItem();
C4MenuItem* GetItem(int32_t iIndex);
virtual C4Object *GetParentObject() { return NULL; }
bool MoveSelection(int32_t iBy, bool fAdjustPosition, bool fDoCalls);
BOOL SetSelection(int32_t iSelection, bool fAdjustPosition, bool fDoCalls);
BOOL SetPosition(int32_t iPosition);
void SetSize(int32_t iToWdt, int32_t iToHgt);
BOOL Enter(BOOL fRight=FALSE);
BOOL IsActive();
BOOL Control(BYTE byCom, int32_t iData);
bool KeyControl(BYTE byCom); // direct keyboard callback
BOOL AddRefSym(const char *szCaption, const C4Facet &fctSymbol, const char *szCommand,
int32_t iCount=C4MN_Item_NoCount, C4Object *pObject=NULL,
const char *szInfoCaption=NULL,
C4ID idID=C4ID_None, const char *szCommand2=NULL, bool fOwnValue=false, int32_t iValue=0, bool fIsSelectable=true);
BOOL Add(const char *szCaption, C4FacetSurface &fctSymbol, const char *szCommand,
int32_t iCount=C4MN_Item_NoCount, C4Object *pObject=NULL,
const char *szInfoCaption=NULL,
C4ID idID=C4ID_None, const char *szCommand2=NULL, bool fOwnValue=false, int32_t iValue=0, bool fIsSelectable=true);
void ClearItems(bool fResetSelection=false);
void ResetLocation() { LocationSet = false; }
BOOL SetLocation(int32_t iX, int32_t iY); // set location relative to user viewport
bool SetTextProgress(int32_t iToProgress, bool fAdd); // enable/disable progressive text display and set starting pos
void SetEqualItemHeight(bool fToVal) { fEqualIconItemHeight = fToVal; } // enable/disable equal item heights
bool TryClose(bool fOK, bool fControl);
void SetCloseCommand(const char *strCommand);
#ifdef _DEBUG
void AssertSurfaceNotUsed(C4Surface *sfc);
#endif
private:
BOOL AddItem(C4MenuItem *pNew, const char *szCaption, const char *szCommand,
int32_t iCount, C4Object *pObject, const char *szInfoCaption,
C4ID idID, const char *szCommand2, bool fOwnValue, int32_t iValue, bool fIsSelectable);
bool InitMenu(const char *szEmpty, int32_t iExtra, int32_t iExtraData, int32_t iId, int32_t iStyle);
protected:
bool DoInitRefSym(const C4Facet &fctSymbol, const char *szEmpty, int32_t iExtra=C4MN_Extra_None, int32_t iExtraData=0, int32_t iId=0, int32_t iStyle=C4MN_Style_Normal);
bool DoInit(C4FacetSurface &fctSymbol, const char *szEmpty, int32_t iExtra=C4MN_Extra_None, int32_t iExtraData=0, int32_t iId=0, int32_t iStyle=C4MN_Style_Normal);
void DrawBuffer(C4Facet &cgo, C4RegionList *pRegions);
void AdjustSelection();
void AdjustPosition();
BOOL CheckBuffer();
BOOL RefillInternal();
void DrawButton(C4Facet &cgo);
void DrawScrollbar(C4Facet &cgo, int32_t iTotal, int32_t iVisible, int32_t iPosition);
void DrawFrame(C4Facet &cgo, int32_t iAlign);
void DrawFrame(SURFACE sfcSurface, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt);
void InitLocation(C4Facet &cgo);
void InitSize();
void UpdateScrollBar(); // call InitSize if a scroll bar is needed but not present or vice vera
void UserSelectItem(int32_t Player, C4MenuItem *pItem); // select item (direct) or do control (object menus)
void UserEnter(int32_t Player, C4MenuItem *pItem, bool fRight); // enter on an item
bool HasMouse(); // returns whether the controlling player has mouse control
virtual bool DoRefillInternal(bool &rfRefilled) { return true; };
virtual bool MenuCommand(const char *szCommand, bool fIsCloseCommand) { return true; }
virtual void OnSelectionChanged(int32_t iNewSelection) {} // do object callbacks if selection changed in user menus
virtual bool IsCloseDenied() { return false; } // do MenuQueryCancel-callbacks for user menus
virtual void OnUserSelectItem(int32_t Player, int32_t iIndex) {}
virtual void OnUserEnter(int32_t Player, int32_t iIndex, bool fRight) {}
virtual void OnUserClose() {};
virtual bool IsReadOnly() { return false; } // determine whether the menu is just viewed by an observer, and should not issue any calls
virtual int32_t GetControllingPlayer() { return NO_OWNER; }
virtual const char *GetID() { return 0; } // no ID needed, because it's a viewport dlg
bool HasPortrait() { return fHasPortrait; } // dialog menus only: Whether a portrait is shown in the topleft
protected:
// C4GUI
virtual class C4Viewport *GetViewport(); // return associated viewport
virtual bool IsExternalDrawDialog() { return true; } // drawn by viewport drawing proc
virtual bool IsMouseControlled() { return false; }
virtual void UpdateOwnPos();
void UpdateElementPositions(); // reposition list items so they are stacked vertically
virtual int32_t GetZOrdering() { return -1; }
virtual void Draw(C4TargetFacet &cgo);
virtual void DrawElement(C4TargetFacet &cgo); // draw menu
virtual bool IsOwnPtrElement() { return true; }
virtual void UserClose(bool fOK);
// bottom area needed for extra info
virtual int32_t GetMarginBottom() { return ((Extra || DrawMenuControls) ? C4MN_SymbolSize : 0) + C4MN_FrameWidth + BaseClass::GetMarginBottom(); }
virtual int32_t GetMarginLeft() { return C4MN_FrameWidth + BaseClass::GetMarginLeft(); }
virtual int32_t GetMarginRight() { return C4MN_FrameWidth + BaseClass::GetMarginRight(); }
friend class C4Viewport; // for drawing
friend class C4MenuItem;
};
#endif

View File

@ -0,0 +1,76 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Fullscreen startup log and chat type-in */
#ifndef INC_C4MessageBoard
#define INC_C4MessageBoard
const int C4MSGB_MaxMsgFading = 6;
#include <C4Facet.h>
#include <C4LogBuf.h>
class C4MessageBoard
{
public:
C4MessageBoard();
~C4MessageBoard();
public:
C4Facet Output;
BOOL Active;
protected:
int ScreenFader;
BOOL Startup;
int iMode; // 0 = one line (std), 1 = > 1 lines, 2 = invisible
// mode 0:
int Delay; // how long the curr msg will stay
int Fader; // =0: hold curr msg until Delay == 0
// <0: fade curr msg out
// >0: fade curr msg in
int Speed; // fade/delay speed
bool Empty; // msgboard empty?
// mode 1:
int iLines; // how many lines are visible? (+ one line for typin! )
int iBackScroll; // how many lines scrolled back?
// all modes:
int iLineHgt; // line height
C4LogBuffer LogBuffer; // backbuffer for log
public:
void Default();
void Clear();
void Init(C4Facet &cgo, BOOL fStartup);
void Execute();
void DrawLoader(C4Facet &cgo);
void Draw(C4Facet &cgo);
void AddLog(const char *szMessage);
void ClearLog();
void LogNotify();
void EnsureLastMessage();
bool ControlScrollUp();
bool ControlScrollDown();
bool ControlChangeMode();
C4Player* GetMessagePlayer(const char *szMessage);
void ChangeMode(int inMode);
friend class C4MessageInput;
};
#endif

View File

@ -0,0 +1,182 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2005-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
// handles input dialogs, last-message-buffer, MessageBoard-commands
#ifndef INC_C4MessageInput
#define INC_C4MessageInput
#include "C4Gui.h"
#include "C4KeyboardInput.h"
const int32_t C4MSGB_BackBufferMax = 20;
// chat input dialog
class C4ChatInputDialog : public C4GUI::InputDialog
{
private:
typedef C4GUI::InputDialog BaseClass;
class C4KeyBinding *pKeyHistoryUp, *pKeyHistoryDown, *pKeyAbort, *pKeyNickComplete, *pKeyPlrControl, *pKeyGamepadControl, *pKeyBackClose;
bool fObjInput; // input queried by script?
bool fUppercase; // script input converted to uppercase
class C4Object *pTarget; // target object for script callback
int32_t iPlr; // target player for script callback
// last message lookup
int32_t BackIndex;
bool fProcessed; // set if chat input has been processed
static C4ChatInputDialog *pInstance; // singleton-instance
private:
bool KeyHistoryUpDown(bool fUp);
bool KeyCompleteNick(); // complete nick at cursor pos of edit
bool KeyPlrControl(C4KeyCodeEx key);
bool KeyGamepadControlDown(C4KeyCodeEx key);
bool KeyGamepadControlUp(C4KeyCodeEx key);
bool KeyGamepadControlPressed(C4KeyCodeEx key);
bool KeyBackspaceClose(); // close if chat text box is empty (on backspace)
protected:
// chat input callback
C4GUI::Edit::InputResult OnChatInput(C4GUI::Edit *edt, bool fPasting, bool fPastingMore);
void OnChatCancel();
virtual void OnClosed(bool fOK);
virtual const char *GetID() { return "ChatDialog"; }
public:
C4ChatInputDialog(bool fObjInput, C4Object *pScriptTarget, bool fUpperCase, bool fTeam, int32_t iPlr, const StdStrBuf &rsInputQuery); // ctor - construct by screen ratios
~C4ChatInputDialog();
// place on top of normal dialogs
virtual int32_t GetZOrdering() { return C4GUI_Z_CHAT; }
// align by screen, not viewport
virtual bool IsFreePlaceDialog() { return true; }
// place more to the bottom of the screen
virtual bool IsBottomPlacementDialog() { return true; }
// true for dialogs that receive full keyboard and mouse input even in shared mode
virtual bool IsExclusiveDialog() { return true; }
// don't enable mouse just for this dlg
virtual bool IsMouseControlled() { return false; }
// usually processed by edit;
// but may reach this if the user managed to deselect the edit control
virtual bool OnEnter() { OnChatInput(pEdit, false, false); return true; }
static bool IsShown() { return !!pInstance; } // external query fn whether dlg is visible
static C4ChatInputDialog *GetInstance() { return pInstance; }
bool IsScriptQueried() const { return fObjInput; }
class C4Object *GetScriptTargetObject() const { return pTarget; }
int32_t GetScriptTargetPlayer() const { return iPlr; }
};
class C4MessageBoardCommand
{
public:
C4MessageBoardCommand();
public:
char Name[C4MaxName + 1];
char Script[_MAX_FNAME+30+1];
enum Restriction { C4MSGCMDR_Escaped=0, C4MSGCMDR_Plain, C4MSGCMDR_Identifier };
Restriction eRestriction;
C4MessageBoardCommand *Next;
};
class C4MessageInput
{
public:
C4MessageInput() : pCommands(NULL) { Default(); }
~C4MessageInput() { Clear(); }
void Default();
void Clear();
bool Init();
private:
// last input messages to be accessed via 'up'/'down' in input dialog
char BackBuffer[C4MSGB_BackBufferMax][C4MaxMessage];
// MessageBoard-commands
private:
class C4MessageBoardCommand *pCommands;
public:
void AddCommand(const char *strCommand, const char *strScript, C4MessageBoardCommand::Restriction eRestriction = C4MessageBoardCommand::C4MSGCMDR_Escaped);
class C4MessageBoardCommand *GetCommand(const char *strName);
// Input
public:
bool CloseTypeIn();
bool StartTypeIn(bool fObjInput = false, C4Object *pObj = NULL, bool fUpperCase = FALSE, bool fTeam = false, int32_t iPlr = -1, const StdStrBuf &rsInputQuery = StdStrBuf());
bool KeyStartTypeIn(bool fTeam);
bool ToggleTypeIn();
bool IsTypeIn();
C4ChatInputDialog *GetTypeIn() { return C4ChatInputDialog::GetInstance(); }
void StoreBackBuffer(const char *szMessage);
const char *GetBackBuffer(int32_t iIndex);
bool ProcessInput(const char *szText);
bool ProcessCommand(const char *szCommand);
public:
void ClearPointers(C4Object *pObj);
void AbortMsgBoardQuery(C4Object *pObj, int32_t iPlr);
friend class C4ChatInputDialog;
};
// script query to ask a player for a string
class C4MessageBoardQuery
{
public:
union
{
C4Object *pCallbackObj; // callback target object
int32_t nCallbackObj; // callback target object (enumerated)
};
StdStrBuf sInputQuery; // question being asked to the player
bool fAnswered; // if set, an answer packet is in the queue (NOSAVE, as the queue isn't saved either!)
bool fIsUppercase; // if set, any input is converted to uppercase be4 sending to script
// linked list to allow for multiple queries
C4MessageBoardQuery *pNext;
// ctors
C4MessageBoardQuery(C4Object *pCallbackObj, const StdStrBuf &rsInputQuery, bool fIsUppercase)
: pCallbackObj(pCallbackObj), fAnswered(false), fIsUppercase(fIsUppercase), pNext(NULL)
{
sInputQuery.Copy(rsInputQuery);
}
C4MessageBoardQuery() : pCallbackObj(NULL), fAnswered(false), fIsUppercase(false), pNext(NULL) {}
// use default copy ctor
// compilation
void CompileFunc(StdCompiler *pComp);
};
#endif // INC_C4MessageInput

View File

@ -0,0 +1,145 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Mouse input */
#ifndef INC_C4MouseControl
#define INC_C4MouseControl
#include "C4ObjectList.h"
#include "C4Region.h"
const int32_t C4MC_Button_None = 0,
C4MC_Button_LeftDown = 1,
C4MC_Button_LeftUp = 2,
C4MC_Button_RightDown = 3,
C4MC_Button_RightUp = 4,
C4MC_Button_LeftDouble = 5,
C4MC_Button_RightDouble = 6,
C4MC_Button_Wheel = 7,
C4MC_Button_MiddleDown = 8,
C4MC_Button_MiddleUp = 9;
const int32_t C4MC_DragSensitivity = 5;
class C4MouseControl
{
friend class C4Viewport;
public:
C4MouseControl();
~C4MouseControl();
protected:
BOOL Active;
bool fMouseOwned;
int32_t Player;
C4Player *pPlayer; // valid during Move()
C4Viewport *Viewport; // valid during Move()
StdStrBuf Caption;
bool IsHelpCaption;
int32_t Cursor;
int32_t DownCursor;
int32_t CaptionBottomY;
int32_t VpX,VpY; // Pixel coordinates of mouse pos
float ViewX,ViewY; // Game coordinate scrolling offset of viewport
float GameX,GameY; // Game coordinates of mouse pos
float GuiX,GuiY; // GUI coorindates of mouse pos
C4Facet fctViewport;
float DownX,DownY; // Game coordinates of mouse-down-pos while dragging
float DownOffsetX,DownOffsetY; // GUI coordinate offset from target region while dragging
int32_t ShowPointX,ShowPointY; // Game coordinates of throw point
int32_t KeepCaption;
int32_t ScrollSpeed;
int32_t Drag,DragSelecting;
int32_t DragImagePhase;
bool LeftButtonDown,RightButtonDown,LeftDoubleIgnoreUp;
bool ButtonDownOnSelection;
bool ControlDown;
bool ShiftDown;
bool Scrolling;
bool InitCentered;
bool Help;
bool FogOfWar;
bool Visible;
C4ID DragID;
C4ObjectList Selection;
C4Facet DragImage;
// Target object
C4Object *TargetObject; // valid during Move()
C4Object *DownTarget;
int32_t TimeOnTargetObject;
// Region
C4Region *TargetRegion; // valid during Move()
C4Region DownRegion;
public:
void Default();
void Clear();
bool Init(int32_t iPlayer);
void Execute();
const char *GetCaption();
void HideCursor();
void ShowCursor();
void Draw(C4TargetFacet &cgo, const ZoomData &GameZoom);
void Move(int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyFlags, BOOL fCenter = FALSE);
bool IsViewport(C4Viewport *pViewport);
void ClearPointers(C4Object *pObj);
void UpdateClip(); // update clipping region for mouse cursor
void SetOwnedMouse(bool fToVal) { fMouseOwned = fToVal; }
bool IsMouseOwned() { return fMouseOwned; }
bool IsActive() { return !!Active; }
protected:
void SendPlayerSelectNext();
void UpdateFogOfWar();
void RightUpDragNone();
void ButtonUpDragConstruct();
void ButtonUpDragMoving();
void ButtonUpDragSelecting();
void LeftUpDragNone();
void DragConstruct();
void Wheel(DWORD dwFlags);
void RightUp();
void RightDown();
void LeftDouble();
void DragNone();
void DragMoving();
void LeftUp();
void DragSelect();
void LeftDown();
void UpdateTargetRegion();
void UpdateScrolling();
void CreateDragImage(C4ID id);
void UpdateCursorTarget();
void SendCommand(int32_t iCommand, int32_t iX=0, int32_t iY=0, C4Object *pTarget=NULL, C4Object *pTarget2=NULL, int32_t iData=0, int32_t iAddMode=C4P_Command_Set);
int32_t UpdateObjectSelection();
int32_t UpdateCrewSelection();
int32_t UpdateSingleSelection();
BOOL SendControl(int32_t iCom, int32_t iData=0);
BOOL IsValidMenu(C4Menu *pMenu);
BOOL UpdatePutTarget(BOOL fVehicle);
C4Object *GetTargetObject(float iX, float iY, DWORD &dwOCF, C4Object *pExclude=NULL);
BOOL IsPassive(); // return whether mouse is only used to look around
void ScrollView(int32_t iX, int32_t iY, int32_t ViewWdt, int32_t ViewHgt);
public:
bool IsHelp() { return Help; }
void SetHelp() { Help = true; }
void AbortHelp() { Help = false; }
bool IsDragging();
void StartConstructionDrag(C4ID id);
int32_t GetPlayer() { return Player; }
};
#endif

View File

@ -0,0 +1,150 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Handles Music Files */
#ifndef INC_C4MusicFile
#define INC_C4MusicFile
#ifdef USE_FMOD
#include <fmod.h>
#endif
#ifdef HAVE_LIBSDL_MIXER
#define USE_RWOPS
#include <SDL_mixer.h>
#undef USE_RWOPS
#endif
/* Base class */
class C4MusicFile
{
public:
C4MusicFile() : LastPlayed(-1), NoPlay(FALSE), SongExtracted(FALSE) { }
virtual ~C4MusicFile() { }
// data
char FileName[_MAX_FNAME +1];
C4MusicFile *pNext;
int LastPlayed;
BOOL NoPlay;
virtual BOOL Init(const char *strFile);
virtual BOOL Play(BOOL loop = FALSE) = 0;
virtual void Stop(int fadeout_ms = 0) = 0;
virtual void CheckIfPlaying() = 0;
virtual void SetVolume(int) = 0;
protected:
// helper: copy data to a (temp) file
BOOL ExtractFile();
BOOL RemTempFile(); // remove the temp file
BOOL SongExtracted;
};
#if defined(USE_FMOD) || defined(USE_WINDOWS_MIDI)
class C4MusicFileMID : public C4MusicFile
{
public:
BOOL Play(BOOL loop = FALSE);
BOOL Extract();
void Stop(int fadeout_ms = 0);
void CheckIfPlaying();
//C4MusicFileMID();
void SetVolume(int);
#ifdef USE_FMOD
protected:
FMUSIC_MODULE *mod;
#endif
};
#endif
#ifdef USE_FMOD
/* MOD class */
class C4MusicFileMOD : public C4MusicFile
{
public:
C4MusicFileMOD();
~C4MusicFileMOD();
BOOL Play(BOOL loop = FALSE);
void Stop(int fadeout_ms = 0);
void CheckIfPlaying();
void SetVolume(int);
protected:
FMUSIC_MODULE *mod;
char *Data;
};
/* MP3 class */
class C4MusicFileMP3 : public C4MusicFile
{
public:
C4MusicFileMP3();
~C4MusicFileMP3();
BOOL Play(BOOL loop = FALSE);
void Stop(int fadeout_ms = 0);
void CheckIfPlaying();
void SetVolume(int);
protected:
FSOUND_STREAM *stream;
char *Data;
int Channel;
};
/* Ogg class */
class C4MusicFileOgg : public C4MusicFile
{
public:
C4MusicFileOgg();
~C4MusicFileOgg();
BOOL Play(BOOL loop = FALSE);
void Stop(int fadeout_ms = 0);
void CheckIfPlaying();
void SetVolume(int);
static signed char __stdcall OnEnd(FSOUND_STREAM* stream, void* buff, int length, void* param);
protected:
FSOUND_STREAM *stream;
char *Data;
int Channel;
BOOL Playing;
};
#endif
#ifdef HAVE_LIBSDL_MIXER
typedef struct _Mix_Music Mix_Music;
class C4MusicFileSDL : public C4MusicFile
{
public:
C4MusicFileSDL();
~C4MusicFileSDL();
BOOL Play(BOOL loop = FALSE);
void Stop(int fadeout_ms = 0);
void CheckIfPlaying();
void SetVolume(int);
protected:
char *Data;
Mix_Music * Music;
};
#endif // HAVE_LIBSDL_MIXER
#endif

View File

@ -0,0 +1,89 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* Handles Music.c4g and randomly plays songs */
#ifndef INC_C4MusicSystem
#define INC_C4MusicSystem
#include <C4Group.h>
class C4MusicFileInfoNode;
class C4MusicFile;
class C4MusicSystem
{
friend class C4SoundEffect;
friend class C4SoundInstance;
friend class C4SoundSystem;
public:
C4MusicSystem();
~C4MusicSystem();
void Clear();
int SetVolume(int);
void Execute();
void NotifySuccess();
bool Init(const char * PlayList = NULL);
bool InitForScenario(C4Group & hGroup);
bool Play(const char *szSongname = NULL, bool fLoop = FALSE);
bool Stop();
void FadeOut(int fadeout_ms);
int SetPlayList(const char *szPlayList);
bool ToggleOnOff(); // keyboard callback
protected:
// song list
C4MusicFile* Songs;
int SongCount, ASongCount, SCounter;
// play
C4MusicFile *PlayMusicFile;
int Volume; bool Loop;
void LoadDir(const char *szPath); // load some music files (by wildcard / directory)
void Load(const char *szFile); // load a music file
void LoadMoreMusic(); // load music file names from MoreMusic.txt
void ClearSongs();
bool GrpContainsMusic(C4Group &rGrp); // return whether this group contains music files
// FMod / SDL_mixer
bool MODInitialized;
bool InitializeMOD();
void DeinitializeMOD();
};
// --- helper stuff --- //
enum MusicType { MUSICTYPE_MID, MUSICTYPE_MOD, MUSICTYPE_MP3, MUSICTYPE_OGG, MUSICTYPE_UNKNOWN };
class C4MusicFileInfoNode // We need this for the MoreMusic.txt stuff
{
public:
C4MusicFileInfoNode() { next=NULL; str=NULL; };
~C4MusicFileInfoNode() { if (str) delete [] str; }
char* str;
MusicType type;
C4MusicFileInfoNode *next;
};
MusicType GetMusicFileTypeByExtension(const char* ext);
#endif

View File

@ -0,0 +1,43 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* A static list of strings and integer values, i.e. for material amounts */
#ifndef INC_C4NameList
#define INC_C4NameList
class C4NameList
{
public:
C4NameList();
public:
char Name[C4MaxNameList][C4MaxName+1];
int32_t Count[C4MaxNameList];
public:
void Clear();
bool Add(const char *szName, int32_t iCount=0);
bool Set(const char *szName, int32_t iCount);
bool Read(const char *szSource, int32_t iDefValue=0);
bool Write(char *szTarget, bool fValues=true);
public:
bool IsEmpty();
bool operator==(const C4NameList& rhs)
{ return MemEqual((const uint8_t*)this,(const uint8_t*)&rhs,sizeof(C4NameList)); }
void CompileFunc(StdCompiler *pComp, bool fValues = true);
};
#endif

View File

@ -0,0 +1,847 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
/* network i/o, featuring tcp, udp and multicast */
#ifndef C4NETIO_H
#define C4NETIO_H
#include "Standard.h"
#include "StdSync.h"
#include "StdBuf.h"
#include "StdCompiler.h"
#include "StdScheduler.h"
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
// Events are Windows-specific
#define HAVE_WINSOCK
#else
#define SOCKET int
#define INVALID_SOCKET (-1)
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifndef HAVE_CONFIG_H
// #define C4NETIO_DEBUG
#endif
// net i/o base class
class C4NetIO : public StdSchedulerProc
{
public:
C4NetIO();
virtual ~C4NetIO();
// *** constants / types
static const int TO_INF; // = -1;
static const uint16_t P_NONE; // = -1
typedef sockaddr_in addr_t;
// callback class
class CBClass
{
public:
virtual bool OnConn(const addr_t &AddrPeer, const addr_t &AddrConnect, const addr_t *pOwnAddr, C4NetIO *pNetIO) { return true; }
virtual void OnDisconn(const addr_t &AddrPeer, C4NetIO *pNetIO, const char *szReason) { }
virtual void OnPacket(const class C4NetIOPacket &rPacket, C4NetIO *pNetIO) = 0;
virtual ~CBClass() { }
};
// used to explicitly callback to a specific class
template <class T>
class CBProxy : public CBClass
{
T *pTarget;
public:
CBProxy *operator () (T *pnTarget) { pTarget = pnTarget; return this; }
virtual bool OnConn(const addr_t &AddrPeer, const addr_t &AddrConnect, const addr_t *pOwnAddr, C4NetIO *pNetIO)
{ return pTarget->T::OnConn(AddrPeer, AddrConnect, pOwnAddr, pNetIO); }
virtual void OnDisconn(const addr_t &AddrPeer, C4NetIO *pNetIO, const char *szReason)
{ pTarget->T::OnDisconn(AddrPeer, pNetIO, szReason); }
virtual void OnPacket(const class C4NetIOPacket &rPacket, C4NetIO *pNetIO)
{ pTarget->T::OnPacket(rPacket, pNetIO); }
};
#ifdef _MSC_VER
#define NETIO_CREATE_CALLBACK_PROXY(ForClass, ProxyName) \
typedef class C4NetIO::CBProxy<ForClass> CBProxyT; \
friend CBProxyT; \
CBProxyT ProxyName;
#else
#define NETIO_CREATE_CALLBACK_PROXY(ForClass, ProxyName) \
friend class C4NetIO::CBProxy<ForClass>; \
C4NetIO::CBProxy<ForClass> ProxyName;
#endif
// *** interface
// * not multithreading safe
virtual bool Init(uint16_t iPort = P_NONE) = 0;
virtual bool InitBroadcast(addr_t *pBroadcastAddr) = 0;
virtual bool Close() = 0;
virtual bool CloseBroadcast() = 0;
virtual bool Execute(int iTimeout = -1, pollfd * = 0) = 0; // (for StdSchedulerProc)
// * multithreading safe
virtual bool Connect(const addr_t &addr) = 0; // async!
virtual bool Close(const addr_t &addr) = 0;
virtual bool Send(const class C4NetIOPacket &rPacket) = 0;
virtual bool SetBroadcast(const addr_t &addr, bool fSet = true) = 0;
virtual bool Broadcast(const class C4NetIOPacket &rPacket) = 0;
// statistics
virtual bool GetStatistic(int *pBroadcastRate) = 0;
virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) = 0;
virtual void ClearStatistic() = 0;
// *** errors
protected:
StdCopyStrBuf Error;
void SetError(const char *strnError, bool fSockErr = false);
public:
virtual const char *GetError() const { return Error.getData(); }
void ResetError() { Error.Clear(); }
// *** callbacks
virtual void SetCallback(CBClass *pnCallback) = 0;
};
// packet class
class C4NetIOPacket : public StdCopyBuf
{
public:
C4NetIOPacket();
// construct from memory (copies / references data)
C4NetIOPacket(const void *pnData, size_t inSize, bool fCopy = false, const C4NetIO::addr_t &naddr = C4NetIO::addr_t());
// construct from buffer (copies data)
explicit C4NetIOPacket(const StdBuf &Buf, const C4NetIO::addr_t &naddr);
// construct from status byte + buffer (copies data)
C4NetIOPacket(uint8_t cStatusByte, const char *pnData, size_t inSize, const C4NetIO::addr_t &naddr = C4NetIO::addr_t());
~C4NetIOPacket();
protected:
// address
C4NetIO::addr_t addr;
public:
const C4NetIO::addr_t &getAddr() const { return addr; }
uint8_t getStatus()const { return getSize() ? *getBufPtr<char>(*this) : 0; }
const char *getPData() const { return getSize() ? getBufPtr<char>(*this, 1) : NULL; }
size_t getPSize() const { return getSize() ? getSize() - 1 : 0; }
StdBuf getPBuf() const { return getSize() ? getPart(1, getSize() - 1) : getRef(); }
// Some overloads
C4NetIOPacket getRef() const { return C4NetIOPacket(StdBuf::getRef(), addr); }
C4NetIOPacket Duplicate() const { return C4NetIOPacket(StdBuf::Duplicate(), addr); }
// change addr
void SetAddr(const C4NetIO::addr_t &naddr) { addr = naddr; }
// delete contents
void Clear();
// Talk gcc into accepting references to temporaries
ALLOW_TEMP_TO_REF(C4NetIOPacket)
};
// tcp network i/o
class C4NetIOTCP : public C4NetIO, protected CStdCSecExCallback
{
public:
C4NetIOTCP();
virtual ~C4NetIOTCP();
// *** interface
// * not multithreading safe
virtual bool Init(uint16_t iPort = P_NONE);
virtual bool InitBroadcast(addr_t *pBroadcastAddr);
virtual bool Close();
virtual bool CloseBroadcast();
virtual bool Execute(int iMaxTime = TO_INF, pollfd * readyfds = 0);
// * multithreading safe
virtual bool Connect(const addr_t &addr);
virtual bool Close(const addr_t &addr);
virtual bool Send(const C4NetIOPacket &rPacket);
virtual bool Broadcast(const C4NetIOPacket &rPacket);
virtual bool SetBroadcast(const addr_t &addr, bool fSet = true);
virtual void UnBlock();
#ifdef STDSCHEDULER_USE_EVENTS
virtual HANDLE GetEvent();
#else
virtual void GetFDs(std::vector<struct pollfd> & FDs);
#endif
virtual int GetNextTick(int Now);
// statistics
virtual bool GetStatistic(int *pBroadcastRate);
virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss);
virtual void ClearStatistic();
protected:
// * overridables (packet format)
// Append packet data to output buffer
virtual void PackPacket(const C4NetIOPacket &rPacket, StdBuf &rOutBuf);
// Extract a packet from the start of the input buffer (if possible) and call OnPacket.
// Should return the numer of bytes used.
virtual size_t UnpackPacket(const StdBuf &rInBuf, const C4NetIO::addr_t &Addr);
// *** data
// peer class
class Peer
{
public:
Peer(const C4NetIO::addr_t &naddr, SOCKET nsock, C4NetIOTCP *pnParent);
~Peer();
protected:
// constants
static const unsigned int iTCPHeaderSize; // = 28 + 24; // (bytes)
static const unsigned int iMinIBufSize; // = 8192; // (bytes)
// parent
C4NetIOTCP *const pParent;
// addr
C4NetIO::addr_t addr;
// socket connected
SOCKET sock;
// incoming & outgoing buffer
StdBuf IBuf, OBuf;
int iIBufUsage;
// statistics
int iIRate, iORate;
// status (1 = open, 0 = closed)
bool fOpen;
// selected for broadcast?
bool fDoBroadcast;
// IO critical sections
CStdCSec ICSec; CStdCSec OCSec;
public:
// data access
const C4NetIO::addr_t &GetAddr() const { return addr; }
SOCKET GetSocket() const { return sock; }
int GetIRate() const { return iIRate; }
int GetORate() const { return iORate; }
// send a packet to this peer
bool Send(const C4NetIOPacket &rPacket);
// send as much data of the interal outgoing buffer as possible
bool Send();
// request buffer space for new input. Must call OnRecv or NoRecv afterwards!
void *GetRecvBuf(int iSize);
// called after the buffer returned by GetRecvBuf has been filled with fresh data
void OnRecv(int iSize);
// close socket
void Close();
// test: open?
bool Open() const { return fOpen; }
// selected for broadcast?
bool doBroadcast() const { return fDoBroadcast; }
// outgoing data waiting?
bool hasWaitingData() const { return !OBuf.isNull(); }
// select/unselect peer
void SetBroadcast(bool fSet) { fDoBroadcast = fSet; }
// statistics
void ClearStatistics();
public:
// next peer
Peer *Next;
};
friend class Peer;
// peer list
Peer *pPeerList;
// small list for waited-for connections
struct ConnectWait
{
SOCKET sock;
addr_t addr;
ConnectWait *Next;
}
*pConnectWaits;
CStdCSecEx PeerListCSec;
CStdCSec PeerListAddCSec;
// initialized?
bool fInit;
// listen socket
uint16_t iListenPort;
SOCKET lsock;
#ifdef STDSCHEDULER_USE_EVENTS
// event indicating network activity
HANDLE Event;
#else
// Pipe used for cancelling select
int Pipe[2];
#endif
// *** implementation
bool Listen(uint16_t inListenPort);
Peer *Accept(SOCKET nsock = INVALID_SOCKET, const addr_t &ConnectAddr = addr_t());
Peer *GetPeer(const addr_t &addr);
void OnShareFree(CStdCSecEx *pCSec);
void AddConnectWait(SOCKET sock, const addr_t &addr);
ConnectWait *GetConnectWait(const addr_t &addr);
void ClearConnectWaits();
// *** callbacks
public:
virtual void SetCallback(CBClass *pnCallback) { pCB = pnCallback; };
private:
CBClass *pCB;
};
// simple udp network i/o
// - No connections
// - Delivery not garantueed
// - Broadcast will multicast the packet to all clients with the same broadcast address.
class C4NetIOSimpleUDP : public C4NetIO
{
public:
C4NetIOSimpleUDP();
virtual ~C4NetIOSimpleUDP();
virtual bool Init(uint16_t iPort = P_NONE);
virtual bool InitBroadcast(addr_t *pBroadcastAddr);
virtual bool Close();
virtual bool CloseBroadcast();
virtual bool Execute(int iMaxTime = TO_INF, pollfd * = 0);
virtual bool Send(const C4NetIOPacket &rPacket);
virtual bool Broadcast(const C4NetIOPacket &rPacket);
virtual void UnBlock();
#ifdef STDSCHEDULER_USE_EVENTS
virtual HANDLE GetEvent();
#else
virtual void GetFDs(std::vector<struct pollfd> & FDs);
#endif
virtual int GetNextTick(int Now);
// not implemented
virtual bool Connect(const addr_t &addr) { assert(false); return false; }
virtual bool Close(const addr_t &addr) { assert(false); return false; }
virtual bool SetBroadcast(const addr_t &addr, bool fSet = true) { assert(false); return false; }
virtual bool GetStatistic(int *pBroadcastRate) { assert(false); return false; }
virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss)
{ assert(false); return false; }
virtual void ClearStatistic() { assert(false); }
private:
// status
bool fInit;
bool fMultiCast;
uint16_t iPort;
// the socket and the associated event
SOCKET sock;
#ifdef STDSCHEDULER_USE_EVENTS
HANDLE hEvent;
#else
int Pipe[2];
#endif
// multicast
addr_t MCAddr; ip_mreq MCGrpInfo;
bool fMCLoopback;
// multibind
int fAllowReUse;
protected:
// multicast address
const addr_t &getMCAddr() const { return MCAddr; }
// (try to) control loopback
bool SetMCLoopback(int fLoopback);
bool getMCLoopback() const { return fMCLoopback; }
// enable multi-bind (call before Init!)
void SetReUseAddress(bool fAllow);
private:
// socket wait (check for readability)
enum WaitResult { WR_Timeout, WR_Readable, WR_Cancelled, WR_Error = -1, };
WaitResult WaitForSocket(int iTimeout);
// *** callbacks
public:
virtual void SetCallback(CBClass *pnCallback) { pCB = pnCallback; };
private:
CBClass *pCB;
};
// udp network i/o
// - Connection are emulated
// - Delivery garantueed
// - Broadcast will automatically be activated on one side if it's active on the other side.
// If the peer can't be reached through broadcasting, packets will be sent directly.
class C4NetIOUDP : public C4NetIOSimpleUDP, protected CStdCSecExCallback
{
public:
C4NetIOUDP();
virtual ~C4NetIOUDP();
// *** interface
virtual bool Init(uint16_t iPort = P_NONE);
virtual bool InitBroadcast(addr_t *pBroadcastAddr);
virtual bool Close();
virtual bool CloseBroadcast();
virtual bool Execute(int iMaxTime = TO_INF, pollfd * = 0);
virtual bool Connect(const addr_t &addr);
virtual bool Close(const addr_t &addr);
virtual bool Send(const C4NetIOPacket &rPacket);
virtual bool Broadcast(const C4NetIOPacket &rPacket);
virtual bool SetBroadcast(const addr_t &addr, bool fSet = true);
virtual int GetNextTick(int Now);
virtual bool GetStatistic(int *pBroadcastRate);
virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss);
virtual void ClearStatistic();
protected:
// *** data
// internal packet type ids
enum IPTypeID
{
IPID_Ping = 0,
IPID_Test = 1,
IPID_Conn = 2,
IPID_ConnOK = 3,
IPID_AddAddr = 7,
IPID_Data = 4,
IPID_Check = 5,
IPID_Close = 6,
};
// packet structures
struct PacketHdr; struct TestPacket; struct ConnPacket; struct ConnOKPacket; struct AddAddrPacket;
struct DataPacketHdr; struct CheckPacketHdr; struct ClosePacket;
// constants
static const unsigned int iVersion; // = 2;
static const unsigned int iStdTimeout, // = 1000, // (ms)
iCheckInterval; // = 1000 // (ms)
static const unsigned int iMaxOPacketBacklog; // = 100;
static const unsigned int iUDPHeaderSize; // = 8 + 24; // (bytes)
// packet class
class PacketList;
class Packet
{
friend class PacketList;
public:
// constants / structures
static const size_t MaxSize; // = 1024;
static const size_t MaxDataSize; // = MaxSize - sizeof(Header);
// types used for packing
typedef uint32_t nr_t;
// construction / destruction
Packet();
Packet(C4NetIOPacket RREF rnData, nr_t inNr);
~Packet();
protected:
// data
nr_t iNr;
C4NetIOPacket Data;
bool *pFragmentGot;
public:
// data access
C4NetIOPacket &GetData() { return Data; }
const C4NetIOPacket &GetData() const { return Data; }
nr_t GetNr() const { return iNr; }
bool Empty() const { return Data.isNull(); }
bool Multicast() const { return !!(Data.getStatus() & 0x80); }
// fragmention
nr_t FragmentCnt() const;
C4NetIOPacket GetFragment(nr_t iFNr, bool fBroadcastFlag = false) const;
bool Complete() const;
bool FragmentPresent(nr_t iFNr) const;
bool AddFragment(const C4NetIOPacket &Packet, const C4NetIO::addr_t &addr);
protected:
::size_t FragmentSize(nr_t iFNr) const;
// list
Packet *Next, *Prev;
};
friend class Packet;
class PacketList
{
public:
PacketList(unsigned int iMaxPacketCnt = ~0);
~PacketList();
protected:
// packet list
Packet *pFront, *pBack;
// packet counts
unsigned int iPacketCnt, iMaxPacketCnt;
// critical section
CStdCSecEx ListCSec;
public:
Packet *GetPacket(unsigned int iNr);
Packet *GetPacketFrgm(unsigned int iNr);
Packet *GetFirstPacketComplete();
bool FragmentPresent(unsigned int iNr);
bool AddPacket(Packet *pPacket);
bool DeletePacket(Packet *pPacket);
void ClearPackets(unsigned int iUntil);
void Clear();
};
friend class PacketList;
// peer class
class Peer
{
public:
// construction / destruction
Peer(const C4NetIO::addr_t &naddr, C4NetIOUDP *pnParent);
~Peer();
protected:
// constants
static const unsigned int iConnectRetries; // = 5
static const unsigned int iReCheckInterval; // = 1000 (ms)
// parent class
C4NetIOUDP *const pParent;
// peer address
C4NetIO::addr_t addr;
// alternate peer address
C4NetIO::addr_t addr2;
// the address used by the peer
addr_t PeerAddr;
// connection status
enum ConnStatus
{
CS_None, CS_Conn, CS_Works, CS_Closed
}
eStatus;
// does multicast work?
bool fMultiCast;
// selected for broadcast?
bool fDoBroadcast;
// do callback on connection timeout?
bool fConnFailCallback;
// packet lists (outgoing, incoming, incoming multicast)
PacketList OPackets;
PacketList IPackets, IMCPackets;
// packet counters
unsigned int iOPacketCounter;
unsigned int iIPacketCounter, iRIPacketCounter;
unsigned int iIMCPacketCounter, iRIMCPacketCounter;
unsigned int iMCAckPacketCounter;
// output critical section
CStdCSec OutCSec;
// connection check time limit
unsigned int iNextReCheck;
unsigned int iLastPacketAsked, iLastMCPacketAsked;
// timeout
unsigned int iTimeout;
unsigned int iRetries;
// statistics
int iIRate, iORate, iLoss;
CStdCSec StatCSec;
public:
// data access
const C4NetIO::addr_t &GetAddr() const { return addr; }
const C4NetIO::addr_t &GetAltAddr() const { return addr2; }
// initiate connection
bool Connect(bool fFailCallback);
// send something to this computer
bool Send(const C4NetIOPacket &rPacket);
// check for lost packets
bool Check(bool fForceCheck = true);
// called if something from this peer was received
void OnRecv(const C4NetIOPacket &Packet);
// close connection
void Close(const char *szReason);
// open?
bool Open() const { return eStatus == CS_Works; }
// closed?
bool Closed() const { return eStatus == CS_Closed; }
// multicast support?
bool MultiCast() const { return fMultiCast; }
// acknowledgment check
unsigned int GetMCAckPacketCounter() const { return iMCAckPacketCounter; }
// timeout checking
int GetTimeout() { return iTimeout; }
void CheckTimeout();
// selected for broadcast?
bool doBroadcast() const { return fDoBroadcast; }
// select/unselect peer
void SetBroadcast(bool fSet) { fDoBroadcast = fSet; }
// alternate address
void SetAltAddr(const C4NetIO::addr_t &naddr2) { addr2 = naddr2; }
// statistics
int GetIRate() const { return iIRate; }
int GetORate() const { return iORate; }
int GetLoss() const { return iLoss; }
void ClearStatistics();
protected:
// helpers
bool DoConn(bool fMC);
bool DoCheck(int iAskCnt = 0, int iMCAskCnt = 0, unsigned int *pAskList = NULL);
// sending
bool SendDirect(const Packet &rPacket, unsigned int iNr = ~0);
bool SendDirect(C4NetIOPacket RREF rPacket);
// events
void OnConn();
void OnClose(const char *szReason);
// incoming packet list
void CheckCompleteIPackets();
// timeout
void SetTimeout(int iLength = iStdTimeout, int iRetryCnt = 0);
void OnTimeout();
public:
// next peer
Peer *Next;
};
friend class Peer;
// critical sections
CStdCSecEx PeerListCSec;
CStdCSec PeerListAddCSec;
CStdCSec OutCSec;
// status
bool fInit;
bool fMultiCast;
uint16_t iPort;
// peer list
Peer *pPeerList;
// currently initializing - do not process packets, save them back instead
bool fSavePacket;
C4NetIOPacket LastPacket;
// multicast support data
addr_t MCLoopbackAddr;
bool fDelayedLoopbackTest;
// check timing
unsigned int iNextCheck;
// outgoing packet list (for multicast)
PacketList OPackets;
unsigned int iOPacketCounter;
// statistics
int iBroadcastRate;
CStdCSec StatCSec;
// callback proxy
NETIO_CREATE_CALLBACK_PROXY(C4NetIOUDP, CBProxy);
// * helpers
// sending
bool BroadcastDirect(const Packet &rPacket, unsigned int iNr = ~0u); // (mt-safe)
bool SendDirect(C4NetIOPacket RREF rPacket); // (mt-safe)
// multicast related
bool DoLoopbackTest();
void ClearMCPackets();
// peer list
void AddPeer(Peer *pPeer);
Peer *GetPeer(const addr_t &addr);
Peer *ConnectPeer(const addr_t &PeerAddr, bool fFailCallback);
void OnShareFree(CStdCSecEx *pCSec);
// connection check
void DoCheck();
// critical section: only one execute at a time
CStdCSec ExecuteCSec;
// debug
#ifdef C4NETIO_DEBUG
int hDebugLog;
void OpenDebugLog();
void CloseDebugLog();
void DebugLogPkt(bool fOut, const C4NetIOPacket &Pkt);
#endif
// *** callbacks
public:
virtual void SetCallback(CBClass *pnCallback) { pCB = pnCallback; };
private:
CBClass *pCB;
// callback interface for C4NetIO
virtual bool OnConn(const addr_t &AddrPeer, const addr_t &AddrConnect, const addr_t *pOwnAddr, C4NetIO *pNetIO);
virtual void OnDisconn(const addr_t &AddrPeer, C4NetIO *pNetIO, const char *szReason);
virtual void OnPacket(const class C4NetIOPacket &rPacket, C4NetIO *pNetIO);
void OnAddAddress(const addr_t &FromAddr, const AddAddrPacket &Packet);
};
// net i/o management (e.g. thread support)
class C4NetIOMan : public C4NetIO::CBClass, public StdSchedulerThread
{
public:
C4NetIOMan();
virtual ~C4NetIOMan();
void Clear();
void AddIO(C4NetIO *pNetIO, bool fSetCallback = true);
void RemoveIO(C4NetIO *pNetIO);
protected:
// net i/o list
int iNetIOCnt, iNetIOCapacity;
C4NetIO **ppNetIO;
// overridables
virtual void OnError(const char *strError, C4NetIO *pNetIO) { };
private:
virtual void OnError(StdSchedulerProc *pProc);
void EnlargeIO(int iBy);
};
// helpers
inline bool AddrEqual(const C4NetIO::addr_t addr1, const C4NetIO::addr_t addr2)
{
return addr1.sin_addr.s_addr == addr2.sin_addr.s_addr &&
addr1.sin_family == addr2.sin_family &&
addr1.sin_port == addr2.sin_port;
}
inline bool operator == (const C4NetIO::addr_t addr1, const C4NetIO::addr_t addr2) { return AddrEqual(addr1, addr2); }
inline bool operator != (const C4NetIO::addr_t addr1, const C4NetIO::addr_t addr2) { return !AddrEqual(addr1, addr2); }
// there seems to be no standard way to get these numbers, so let's do it the dirty way...
inline uint8_t &in_addr_b(in_addr &addr, int i) {
assert(0 <= i && i < 4);
return *(reinterpret_cast<uint8_t *>(&addr.s_addr) + i);
}
inline void CompileFunc(in_addr &ip, StdCompiler *pComp)
{
pComp->Value(in_addr_b(ip, 0)); pComp->Seperator(StdCompiler::SEP_PART);
pComp->Value(in_addr_b(ip, 1)); pComp->Seperator(StdCompiler::SEP_PART);
pComp->Value(in_addr_b(ip, 2)); pComp->Seperator(StdCompiler::SEP_PART);
pComp->Value(in_addr_b(ip, 3));
}
inline void CompileFunc(C4NetIO::addr_t &addr, StdCompiler *pComp)
{
pComp->Value(addr.sin_addr); pComp->Seperator(StdCompiler::SEP_PART2);
uint16_t iPort = htons(addr.sin_port);
pComp->Value(iPort);
addr.sin_port = htons(iPort);
if(pComp->isCompiler())
{
addr.sin_family = AF_INET;
ZeroMem(addr.sin_zero, sizeof(addr.sin_zero));
}
}
#ifdef HAVE_WINSOCK
bool AcquireWinSock();
void ReleaseWinSock();
#endif
bool ResolveAddress(const char *szAddress, C4NetIO::addr_t *paddr, uint16_t iPort);
#endif

View File

@ -0,0 +1,442 @@
/*
* OpenClonk, http://www.openclonk.org
*
* Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de
*
* Portions might be copyrighted by other authors who have contributed
* to OpenClonk.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
* See isc_license.txt for full license and disclaimer.
*
* "Clonk" is a registered trademark of Matthes Bender.
* See clonk_trademark_license.txt for full license.
*/
#ifndef INC_C4Network2
#define INC_C4Network2
#include "C4NetIO.h"
#include "C4Application.h"
#include "C4Network2Client.h"
#include "C4Network2Res.h"
#include "C4Network2IO.h"
#include "C4Network2Players.h"
#include "C4GameParameters.h"
#ifndef BIG_C4INCLUDE
#include "C4PlayerInfo.h"
#include "C4Teams.h"
#include "C4Control.h"
#include "C4Gui.h"
#endif
// lobby predef - no need to include lobby in header just for the class ptr
namespace C4GameLobby { class MainDlg; class Countdown; }
class C4PacketJoinData;
// standard ports
const int16_t C4NetStdPortTCP = 11112,
C4NetStdPortUDP = 11113,
C4NetStdPortDiscovery = 11114,
C4NetStdPortRefServer = 11111,
C4NetStdPortPuncher = 11115,
C4NetStdPortHTTP = 80;
// ressource retrieve wait timeout
const int C4NetResRetrieveTimeout = 100000; // (ms)
// client (de)activation
const int C4NetActivationReqInterval = 5000, // (ms)
C4NetMaxBehind4Activation = 20, // (ticks)
C4NetDeactivationDelay = 500; // (ticks)
// client chase
const unsigned int C4NetChaseTargetUpdateInterval = 5; // (s)
// reference
const unsigned int C4NetReferenceUpdateInterval = 120; // (s)
const unsigned int C4NetMinLeagueUpdateInterval = 10; // (s)
// voting
const unsigned int C4NetVotingTimeout = 10; // (s)
const unsigned int C4NetMinVotingInterval = 120; // (s)
// streaming
const int C4NetStreamingMinBlockSize = 10 * 1024;
const int C4NetStreamingMaxBlockSize = 20 * 1024;
const int C4NetStreamingInterval = 30; // (s)
enum C4NetGameState
{
GS_None, // network not active
GS_Init, // connecting to host, waiting for join data
GS_Lobby, // lobby mode
GS_Pause, // game paused
GS_Go, // game running
};
class C4Network2Status : public C4PacketBase
{
public:
C4Network2Status();
protected:
C4NetGameState eState;
int32_t iCtrlMode;
int32_t iTargetCtrlTick;
public:
C4NetGameState getState() const { return eState; }
int32_t getCtrlMode() const { return iCtrlMode; }
int32_t getTargetCtrlTick() const { return iTargetCtrlTick; }
const char *getStateName() const;
const char *getDescription() const;
bool isEnabled() const { return eState != GS_None; }
bool isLobbyActive() const { return eState == GS_Lobby; }
bool isPastLobby() const { return eState > GS_Lobby; }
bool isPaused() const { return eState == GS_Pause; }
bool isRunning() const { return eState == GS_Go; }
void Set(C4NetGameState eState, int32_t iTargetCtrlTick);
void SetCtrlMode(int32_t iCtrlMode);
void SetTargetTick(int32_t iTargetCtrlTick);
void Clear();
void CompileFunc(StdCompiler *pComp, bool fReference);
virtual void CompileFunc(StdCompiler *pComp);
};
class C4Network2 : private C4ApplicationSec1Timer
{
friend class C4Network2IO;
public:
C4Network2();
virtual ~C4Network2();
public:
// network i/o class
C4Network2IO NetIO;
// ressource list
C4Network2ResList ResList;
// client list
C4Network2ClientList Clients;
// player list
C4Network2Players Players;
// game status
C4Network2Status Status;
protected:
// role
bool fHost;
// options
bool fAllowJoin, fAllowObserve;
// join resource
C4Network2ResCore ResDynamic;
// ressources
int32_t iDynamicTick;
bool fDynamicNeeded;
// game status flags
bool fStatusAck, fStatusReached;
bool fChasing;
// control
class C4GameControlNetwork *pControl;
// lobby
C4GameLobby::MainDlg *pLobby;
bool fLobbyRunning;
C4GameLobby::Countdown *pLobbyCountdown;
// master server used
StdCopyStrBuf MasterServerAddress;
// clients
int32_t iNextClientID;
// chase
uint32_t iLastChaseTargetUpdate;
// activation
uint32_t iLastActivateRequest;
// reference
uint32_t iLastReferenceUpdate;
uint32_t iLastLeagueUpdate, iLeagueUpdateDelay;
bool fLeagueEndSent;
// league
class C4LeagueClient *pLeagueClient;
// game password
StdStrBuf sPassword;
// connection failed because password needed?
bool fWrongPassword;
// delayed activation request?
bool fDelayedActivateReq;
// voting
C4Control Votes;
class C4VoteDialog *pVoteDialog;
bool fPausedForVote;
time_t iVoteStartTime, iLastOwnVoting;
// streaming
bool fStreaming;
time_t iLastStreamAttempt;
C4Record *pStreamedRecord;
StdBuf StreamingBuf;
z_stream StreamCompressor;
class C4Network2HTTPClient *pStreamer;
unsigned int iCurrentStreamAmount, iCurrentStreamPosition;
public:
// data access
bool isEnabled() const { return Status.isEnabled(); }
bool isLobbyActive()const { return Status.isLobbyActive(); }
bool isPastLobby() const { return Status.isPastLobby(); }
bool isRunning() const { return Status.isRunning() && isStatusAck(); }
bool isPaused() const { return Status.isPaused() && isStatusAck(); }
bool isPausing() const { return Status.isPaused() && !fStatusAck; }
bool isHost() const { return fHost; }
bool isStatusAck() const { return fStatusAck; }
bool isFrozen() const;
bool isJoinAllowed() const { return fAllowJoin; }
bool isObservingAllowed() const { return fAllowObserve; }
class C4GameLobby::MainDlg *GetLobby() const { return pLobby; } // lobby publication
const char *GetPassword() const { return sPassword.getData(); } // Oh noez, now the password is public!
bool isPassworded() const { return !sPassword.isNull(); }
// initialization result type
enum InitResult
{
IR_Success, IR_Error, IR_Fatal,
};
// initialization
bool InitHost(bool fLobby);
InitResult InitClient(const class C4Network2Reference &Ref, bool fObserver);
InitResult InitClient(const class C4Network2Address *pAddrs, int iAddrCount, const class C4ClientCore &HostCore, const char *szPassword = NULL);
bool InitHostRessources();
bool DoLobby();
bool Start();
bool Pause();
bool Sync();
bool FinalInit();
bool RetrieveScenario(char *szScenario);
C4Network2Res::Ref RetrieveRes(const C4Network2ResCore &Core, int32_t iTimeout, const char *szResName, bool fWaitForCore = false);
// idle processes
void OnSec1Timer();
void Execute();
// termination
void Clear();
// some options
bool ToggleAllowJoin();
bool ToggleClientListDlg();
void AllowJoin(bool fAllow);
void SetAllowObserve(bool fAllow);
void SetCtrlMode(int32_t iCtrlMode);
void SetPassword(const char *szToPassword);
StdStrBuf QueryClientPassword(); // ask client for a password; empty if user canceled
// interface for C4Network2IO
void OnConn(C4Network2IOConnection *pConn);
void OnDisconn(C4Network2IOConnection *pConn);
void HandlePacket(char cStatus, const C4PacketBase *pBasePkt, C4Network2IOConnection *pConn);
void HandleLobbyPacket(char cStatus, const C4PacketBase *pBasePkt, C4Network2IOConnection *pConn);
// runtime join stuff
void OnGameSynchronized();
// status
void DrawStatus(C4TargetFacet &cgo);
// client activation
void RequestActivate();
void DeactivateInactiveClients(); // host
// league
void LeagueGameEvaluate(const char *szRecordName = NULL, const BYTE *pRecordSHA = NULL);
void LeagueSignupDisable(); // if "internet game" button is switched off in lobby: Remove from league server
bool LeagueSignupEnable(); // if "internet game" button is switched on in lobby: (re)Add to league server
void InvalidateReference(); // forces a recreation and re-send of the game reference in the next execution cycle
bool LeaguePlrAuth(C4PlayerInfo *pInfo); // client: get authentication for a player from the league server
bool LeaguePlrAuthCheck(C4PlayerInfo *pInfo); // host: check AUID of player info with league server
void LeagueNotifyDisconnect(int32_t iClientID, enum C4LeagueDisconnectReason eReason); //
void LeagueWaitNotBusy(); // block until league serveris no longer busy. Process update reply if last message was an update
void LeagueSurrender(); // forfeit in league - just fake a disconnect
void LeagueShowError(const char *szMsg); // show league error msg box in fullscreen; just log in console
// voting
void Vote(C4ControlVoteType eType, bool fApprove = true, int32_t iData = 0);
void AddVote(const C4ControlVote &Vote);
C4IDPacket *GetVote(int32_t iClientID, C4ControlVoteType eType, int32_t iData);
void EndVote(C4ControlVoteType eType, bool fApprove, int32_t iData);
void OpenVoteDialog();
void OpenSurrenderDialog(C4ControlVoteType eType, int32_t iData);
void OnVoteDialogClosed();
// lobby countdown
void StartLobbyCountdown(int32_t iCountdownTime);
void AbortLobbyCountdown();
// streaming
size_t getPendingStreamData() const { return StreamingBuf.getSize() - StreamCompressor.avail_out; }
bool isStreaming() const;
bool StartStreaming(C4Record *pRecord);
bool FinishStreaming();
bool StopStreaming();
protected:
// net i/o initialization
bool InitNetIO(bool fNoClientID, bool fHost);
// handling of own packets
void HandleConn(const class C4PacketConn &Pkt, C4Network2IOConnection *pConn, C4Network2Client *pClient);
bool CheckConn(const C4ClientCore &CCore, C4Network2IOConnection *pConn, C4Network2Client *pClient, const char *&szReply);
bool HostConnect(const C4ClientCore &CCore, C4Network2IOConnection *pConn, const char *&szReply);
bool Join(C4ClientCore &CCore, C4Network2IOConnection *pConn, const char *&szReply);
void HandleConnRe(const class C4PacketConnRe &Pkt, C4Network2IOConnection *pConn, C4Network2Client *pClient);
void HandleStatus(const C4Network2Status &nStatus);
void HandleStatusAck(const C4Network2Status &nStatus, C4Network2Client *pClient);
void HandleActivateReq(int32_t iTick, C4Network2Client *pClient);
void HandleJoinData(const class C4PacketJoinData &rPkt);
// events
void OnConnect(C4Network2Client *pClient, C4Network2IOConnection *pConn, const char *szMsg, bool fFirstConnection);
void OnConnectFail(C4Network2IOConnection *pConn);
void OnDisconnect(C4Network2Client *pClient, C4Network2IOConnection *pConn);
void OnClientConnect(C4Network2Client *pClient, C4Network2IOConnection *pConn);
void OnClientDisconnect(C4Network2Client *pClient);
void SendJoinData(C4Network2Client *pClient);
// ressource list
bool CreateDynamic(bool fInit);
void RemoveDynamic();
// status changes
bool PauseGame(bool fAutoContinue);
bool ChangeGameStatus(C4NetGameState enState, int32_t iTargetCtrlTick, int32_t iCtrlMode = -1);
void CheckStatusReached(bool fFromFinalInit = false);
void CheckStatusAck();
void OnStatusReached();
void OnStatusAck();
// chase
void UpdateChaseTarget();
// league
bool InitLeague(bool *pCancel);
void DeinitLeague();
bool LeagueStart(bool *pCancel);
bool LeagueUpdate();
bool LeagueUpdateProcessReply();
bool LeagueEnd(const char *szRecordName = NULL, const BYTE *pRecordSHA = NULL);
// streaming
bool StreamIn(bool fFinish);
bool StreamOut();
};
class C4VoteDialog : public C4GUI::MessageDialog
{
public:
C4VoteDialog(const char *szText, C4ControlVoteType eVoteType, int32_t iVoteData, bool fSurrender);
private:
C4ControlVoteType eVoteType;
int32_t iVoteData;
bool fSurrender;
public:
C4ControlVoteType getVoteType() const { return eVoteType; }
int32_t getVoteData() const { return iVoteData; }
private:
virtual bool OnEnter() { UserClose(false); return true; } // the vote dialog defaults to "No" [MarkFra]
virtual void OnClosed(bool fOK);
// true for dialogs that receive full keyboard and mouse input even in shared mode
virtual bool IsExclusiveDialog() { return true; }
};
// * Packets *
class C4PacketJoinData : public C4PacketBase
{
public:
C4PacketJoinData() { }
protected:
// the client ID
int32_t iClientID;
// Dynamic data to boot
C4Network2ResCore Dynamic;
// network status
C4Network2Status GameStatus;
// control tick
int32_t iStartCtrlTick;
public:
// the game parameters
C4GameParameters Parameters;
public:
const int32_t &getClientID() const { return iClientID; }
const C4Network2ResCore&getDynamicCore() const { return Dynamic; }
const C4Network2Status &getStatus() const { return GameStatus; }
int32_t getStartCtrlTick() const { return iStartCtrlTick; }
void SetClientID(int32_t inClientID) { iClientID = inClientID; }
void SetGameStatus(const C4Network2Status &Status) { GameStatus = Status; }
void SetDynamicCore(const C4Network2ResCore &Core) { Dynamic = Core; }
void SetStartCtrlTick(int32_t iTick) { iStartCtrlTick = iTick; }
virtual void CompileFunc(StdCompiler *pComp);
};
class C4PacketActivateReq : public C4PacketBase
{
public:
C4PacketActivateReq(int32_t iTick = -1) : iTick(iTick) { }
protected:
int32_t iTick;
public:
int32_t getTick() const { return iTick; }
virtual void CompileFunc(StdCompiler *pComp);
};
#endif

Some files were not shown because too many files have changed in this diff Show More