Conflicts:
	src/sound/sound.h
dev-ui
erihel 2012-08-09 20:20:47 +02:00
commit 611680a72e
236 changed files with 32411 additions and 23225 deletions

View File

@ -5,16 +5,29 @@ cmake_minimum_required(VERSION 2.8)
project(colobot C CXX) project(colobot C CXX)
# Required packages # Required packages
find_package(OpenGL REQUIRED) find_package(OpenGL 1.4 REQUIRED)
find_package(SDL REQUIRED) find_package(SDL 1.2.10 REQUIRED)
find_package(SDL_image REQUIRED) find_package(SDL_image 1.2 REQUIRED)
find_package(PNG 1.2 REQUIRED)
# GLEW requirement depends on platform
# By default it is auto detected
# This setting may be used to override
# Possible values:
# - auto -> determine automatically
# - 1 -> always enable
# - 0 -> always disable
set(USE_GLEW auto)
# Build with debugging symbols # Build with debugging symbols
set(CMAKE_BUILD_TYPE debug) set(CMAKE_BUILD_TYPE debug)
# Global compile flags # Global compile flags
set(CMAKE_CXX_FLAGS_RELEASE "-O2") set(CMAKE_CXX_FLAGS_RELEASE "-O2 -Wall -Wold-style-cast -std=gnu++0x")
set(CMAKE_CXX_FLAGS_DEBUG "-w -g -O0") set(CMAKE_CXX_FLAGS_DEBUG "-g -O0 -Wall -Wold-style-cast -std=gnu++0x")
# Include cmake directory
SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${colobot_SOURCE_DIR}/cmake")
# Subdirectory with sources # Subdirectory with sources
add_subdirectory(src bin) add_subdirectory(src bin)

View File

@ -690,8 +690,7 @@ INPUT_ENCODING = UTF-8
# *.f90 *.f *.for *.vhd *.vhdl # *.f90 *.f *.for *.vhd *.vhdl
FILE_PATTERNS = *.h \ FILE_PATTERNS = *.h \
*.cpp \ *.cpp
*.doc.txt
# The RECURSIVE tag can be used to turn specify whether or not subdirectories # The RECURSIVE tag can be used to turn specify whether or not subdirectories
# should be searched for input files as well. Possible values are YES and NO. # should be searched for input files as well. Possible values are YES and NO.

133
HOWTO.txt
View File

@ -1,77 +1,104 @@
EN
How to... How to...
1. Compile the game with MinGW. 1. Compile the game.
1. Download and install DirectX 8.1 SDK. It can be difficult to find it now as it is old SDK, but here is a working dowload link: 1.1 Windows:
http://dl.dropbox.com/u/32866936/dx81sdk_full.exe
2. Download and install MinGW and MSYS: 1. Download and install MinGW and MSYS:
http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/ http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/
When installing, select all available components. When installing, select all available components.
3. Download and install CMake: 2. Download and install CMake:
http://www.cmake.org/cmake/resources/software.html (the Windows zip file) http://www.cmake.org/cmake/resources/software.html (the Windows zip file)
Unpack the contents of the archive to where MinGW is installed (files from bin/ should go into bin/, etc.) Unpack the contents of the archive to where MinGW is installed (files from bin/ should go into bin/, etc.)
4. In the file src/CMakeLists.txt, change "set(DXSDK_DIR "c:/dxsdk") to the directory, where you have DirectX SDK 3. Download the following libraries, installing them in your MinGW directory like with CMake:
(the slashes must be in this form: /, not \). SDL >=1.2.10, SDL_imgage >= 1.2, SDL_ttf >= 2.0, libpng >= 1.2, GLEW >= 1.8.0
5. Run MinGW console from the shortcut in menu start. Note #1: For most libraries, you can download binary packages with compiled files.
6. Change to the directory where you have the Colobot sources by typing "cd /c/where/the/sources/are" However, you must ensure that they work with MinGW as some are built with MSVC
7. Type "cmake -G 'MSYS Makefiles' ." and may be incompatible. If that is the case, you should compile the libraries from sources
8. Type "make" using MinGW.
9. Everything should compile without errors. Note #2: For GLEW, you need to compile from source under MinGW. Since there is no automated
make script for that, follow the instructions here: http://stackoverflow.com/questions/6005076/
4. Run MinGW console from the shortcut in menu start.
5. Change to the directory where you have the Colobot sources by typing "cd /c/where/the/sources/are"
6. Type "cmake -G 'MSYS Makefiles' ."
7. Type "make"
8. Everything should compile without errors.
1.2 Linux:
Since you're running Linux, you probably know how to do this anyway ;)
But just in case, here's what you need:
gcc compiler (with gcc-g++), cmake, libraries with header files: SDL, SDL_image, SDL_ttf, libpng
Instructions are the same:
$ cmake .
$ make
Note: If you experience problems with OpenGL's extensions, install GLEW library and enable
it in compilation by setting USE_GLEW to 1 in CMakeLists.txt
1.3 Other platforms, compilers, etc.
We haven't checked other platforms yet but the code isn't particularly tied to any compiler or platform, so in theory it should work.
If you can, please try to compile the code on your platform and let us know how it goes.
2. Run the compiled game. 2. Run the compiled game.
1. Download and unpack the package with the game data files. 1. Download development data package - make sure you get the latest version as the files will be changed/moved around.
2. Copy the compiled files from bin/colobot.exe, bin/CBot/libCBot.dll Currently the files are hosted at: http://colobot.info/files (packages are named colobot-data-YYYY-MM-DD.zip)
and from the directory, where MinGW is installed bin/libgcc_s_dw2-1.dll and bin/libstdc++-6.dll 2. Unpack the data package to any place you want.
to the directory with game data (there should be several files named colobot*.dat). 3. Run the game with commandline option "-datadir where_you_put_the_data_dir" and enjoy the game.
3. Create a shortcut to the colobot.exe executable and add to the executed command " -nocd" option.
4. Run the shortcut and enjoy the game.
3. But it's in French! How to change the language?
1. In the source code, find language.h file and change the line #define FRENCH TRUE to #define FRENCH FALSE and do the reverse
on on the language of your choice (English, German or Polish).
2. Recompile the game and copy bin/colobot.exe.
3. In the directory with game data switch the directories scene, script and help with those from the directory of given language
(e.g. english/).
4. Run the game.
PL PL
Jak... Jak...
1. Skompilować projekt pod MinGW. 1. Skompilować grę.
1. Ściągamy i instalujemy DirectX SDK w wersji 8.1. Może być problem ze znalezieniem linka bo to już stary SDK, ale można ściągnąć stąd: 1.1 Windows:
http://dl.dropbox.com/u/32866936/dx81sdk_full.exe
2. Ściągamy i instalujemy MinGW i MSYS: 1. Ściągamy i instalujemy MinGW i MSYS:
http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/ http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/
Przy instalacji zaznaczamy wszystkie komponenty do instalacji. Przy instalacji zaznaczamy wszystkie komponenty do instalacji.
3. Ściągamy i instalujemy CMake: 2. Ściągamy i instalujemy CMake:
http://www.cmake.org/cmake/resources/software.html (plik zip dla Windowsa) http://www.cmake.org/cmake/resources/software.html (plik zip dla Windowsa)
Zip rozpakowujemy do katalogu, gdzie zainstalowany jest MinGW (pliki z bin/ mają trafić do bin/ itd.). Zip rozpakowujemy do katalogu, gdzie zainstalowany jest MinGW (pliki z bin/ mają trafić do bin/ itd.).
4. W pliku src/CMakeLists.txt zmieniamy set(DXSDK_DIR "c:/dxsdk") na katalog, gdzie jest zainstalowany DirectX SDK (w wersji 8.1) 3. Ścągamy następujące biblioteki i instalujemy je tam, gdzie MinGW, podobnie jak z CMake:
(slashe mają być właśnie w takiej postaci: / a nie \). SDL >= 1.2.10, SDL_image >= 1.2, SDL_ttf >= 2.0, libpng >= 1.2
5. Uruchamiamy MinGW console ze skrótu w menu start. Uwaga #1: W większości wymienionych bibliotek można ściągnąć paczki binarne ze skompilowanymi plikami.
6. Przechodzimy do katalogu, gdzie są źródła wpisując "cd /c/tam/gdzie/sa/zrodla" Jednak musisz się upewnić, że pliki te będą współpracowały z MinGW, bo część z nich
7. Wpisujemy "cmake -G 'MSYS Makefiles' ." jest kompilowana MSVC i może być niezgodna. W takim wypadku, musisz skompilować bibliotekę
8. Wpisujemy "make" ze źródeł pod MinGW.
9. Wszystko powinno się skomplikować bez błędów.
Uwaga #2: W przypadku GLEW, musisz skompilować bibiotekę ze źródeł pod MinGW. Ponieważ nie ma skryptu
make do tego, użyj poleceń opisanych tutaj: http://stackoverflow.com/questions/6005076/
4. Uruchamiamy MinGW console ze skrótu w menu start.
5. Przechodzimy do katalogu, gdzie są źródła wpisując "cd /c/tam/gdzie/sa/zrodla"
6. Wpisujemy "cmake -G 'MSYS Makefiles' ."
7. Wpisujemy "make"
8. Wszystko powinno się skomplikować bez błędów.
1.2 Linux:
Skoro już masz Linuksa, to prawdpobodobnie wiesz co robić ;)
Ale na wszelki wypadek, potrzebujesz tego:
kompilator gcc (razem z gcc-g++), cmake, biblioteki wraz z nagłówkami: SDL, SDL_image, SDL_ttf, libpng
Polecenia są takie same:
$ cmake .
$ make
Uwaga: Jeśli natrafisz na problemy z rozszerzeniami OpenGL, zainstaluj bibliotekę GLEW i włącz ją
przy kompilacji, ustawiając USE_GLEW na 1 w CMakeLists.txt
1.3 Inne platformy, kompilatory, etc.
Nie sprawdzaliśmy jeszcze innych platform, ale kod nie jest jakoś specjalnie związany z danym kompilatorem czy platformą, więc w teorii powinien zadziałać.
Jeśli możesz, spróbuj skompilować kod na twojej platformie i daj nam znać jak poszło.
2. Uruchomić skompilowaną grę. 2. Uruchomić skompilowaną grę.
1. Ściągamy paczkę z plikami danych gry. 1. Ściągamy paczkę developerską z plikami danych gry - upewnij się, że jest to najnowsza wersja, bo pliki będą zmieniane/przenoszone.
2. Kopiujemy skompilowane pliki bin/colobot.exe, bin/CBot/libCBot.dll 2. Wypakowujemy pliki gdziekolwiek.
i z katalogu, gdzie jest zainstalowany MinGW bin/libgcc_s_dw2-1.dll i bin/libstdc++-6.dll 3. Uruchamiamy grę wraz z opcją "-datadir tam_gdzie_rozpakowałeś_paczkę" i cieszymy się grą.
do katalogu z plikami danych (powinno być tam kilka plików colobot*.dat).
3. Tworzymy skrót do colobot.exe, przy czym w wywoływanej komendzie dopisujemy na końcu opcję " -nocd".
4. Odpalamy skrót i cieszymy się grą.
3. Ale gra jest po francusku! Jak zmienić język?
1. W kodzie źródłowym znajdujemy plik language.h i zmieniamy #define FRENCH TRUE na #define FRENCH FALSE i robimy odwrotnie
dla wybranego języka (angielski, niemiecki lub polski).
2. Kompilujemy od nowa grę i kopiujemy bin/colobot.exe.
3. W katalogu z plikami danych podmieniamy katalogi scene, script i help z tymi z katalogu danego języka (np. english/).
4. Odpalamy grę.

674
LICENSE.txt Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,4 +1,4 @@
README for Developers README for Developers
Please refer to our wiki for developers for current information. Its current address is: Please refer to our wiki for developers for current information. Its current address is:
http://colobot.info/wiki/doku.php?id=developers http://colobot.info/wiki/

View File

@ -1,14 +1,30 @@
EN
Welcome to Colobot project repository Welcome to Colobot project repository
This repository contains the source files of Colobot game released on open source license (GNU GPLv3) by the producer Epsitec CH. The sources were released and the rights granted to a group of Polish Colobot fans centered around the site http://colobot.cba.pl/ . This repository contains only the source code of the game. The necessary data files will soon be available as a separate download. For now, though, you can download the original download package released by Epsitec (the link is on http://colobot.cba.pl/ site). This is official repository for the open-source Colobot project developed by Polish Portal of Colobot (PPC; Polish: Polski Portal Colobota) with the official site at: http://colobot.cba.pl/.
The source code contained here was released by Epsitec -- the original creator of the game -- on open source (GPLv3) license. The code was given and the rights granted specifically to PPC community in March 2012. Since then, we have been modifying the code and working on our goals, which are briefly summed up below. More information about the project in general will soon appear on our site and a wiki we are writing.
This repository contains only the source code of the game. The game requires also data files which will soon be made available in separate packages. For now, though, you can download the original download package released by Epsitec (the link is on our site).
For more information on the project, see the wiki pages.
Status Status
Our first goal has been reached now: the project has been successfully ported to CMake build system and MinGW compiler from the original MSVC6 project. Our main goals can be summed up in three milestones:
Milestone 1 - Colobot Classic
This is a version of the game that is comprised of the original source files with only minor changes and bugfixes. It is currently maintained in branch named "original" and the master branch is synced to it to provide a working version of the project. There will soon be download packages for the game, in several language versions.
Milestone 2 - Colobot Gold
This is a version of the game that we are now focusing our efforts on. It will be the original, refreshed game rewritten using SDL and OpenGL libraries, thus making it multiplatform. Development for this version is continued in dev branch and sub-branches dev-*. The data files will not be altered and the game will be as close to the original as possible. With this release, we hope to reach wider audience and gain more support.
Milestone 3 - Colobot 2
This will be a new installment in the Colobot series. We have many ideas for the new game and we are still discussing them. Generally, the development of this version will begin only after finishing Colobot Gold (it will be probably hosted in another repository, forked off the Colobot Gold code).
Now our goal is to port the game to OpenGL and SDL, thus making it multiplatform. Further goals include adding new features to the game, though that will be decided later on.
Compiling and running the game Compiling and running the game
@ -16,4 +32,38 @@ For these instructions see HOWTO.txt file.
Contact Contact
If you want to help in the project, please contact us on the forum on our website (there is also an English board). If you want to help in the project, please contact us on our IRC channel #colobot at pirc.pl or the forum on our website: http://colobot.cba.pl/forum (there is also an English board).
PL
Witamy w repozytorium projektu Colobot
To jest oficjalne repozytorium z kodem projektu open-source Colobot rozwijanego przez Polski Portal Colobota (PPC; angielski: Polish Portal of Colobot) z oficjalną stroną: http://colobot.cba.pl/.
Kod źródłowy zawarty tutaj został wydany przez Epsitec -- oryginalnego twórcę gry -- na otwartej licencji (GPLv3). Kod został wydany i prawa nadane specjalnie dla społeczności PPC w marcu 2012. Od tamtej pory, zajmujemy się modyfikowaniem kodu i pracowaniem nad naszymi celami, które są krótko podsumowane poniżej. Więcej informacji o projekcie w ogóle pojawi się wkrótce na naszej stronie i na wiki, które w tej chwili piszemy.
To repozytorium zawiera tylko kod źródłowy gry. Gra wymaga też plików danych, które niedługo zostaną przygotowane w osobnej paczce. Na razie, możesz pobrać oryginalną paczkę wydaną przez Epsitec (link znajduje się na naszej stronie).
Status
Nasze główne cele można podsumować w trzech krokach, które chcemy osiągnąć:
Krok 1 - Colobot Classic
To jest wersja gry, która składa się z oryginalnych źródeł, z jedynie niewielkimi zmianami i poprawkami. Obecnie znajduje się w gałęzi nazwanej "original", a gałąź master jest z nią zsynchronizowana, aby udostępnić działającą wersję projektu. Niedługo pojawią się paczki do pobrania gry w kilku wersjach językowych.
Krok 2 - Colobot Gold
To jest wersja gry, na której obecnie się skupiamy. Jest to oryginalna, odświeżona gra, przepisana z użyciem bibliotek SDL i OpenGL, w ten sposób czyniąc ją wieloplatformową. Rozwój tej wersji kontynuujemy w gałęzi dev i podgałęziach dev-*. Pliki danych nie będą zmienione dla tej wersji i gra będzie na tyle zbliżona do oryginału na ile to możliwe. Z tym wydaniem, chcemy dotrzeć do szerszej społeczności i uzyskać większe poparcie.
Krok 3 - Colobot 2
To będzie nowa część z cyklu gier Colobot. Mamy wiele pomysłów na nową grę i nadal dyskutujemy nad nimi. Ogólnie, rozwój tej wersji zacznie się po skończeniu wersji Colobot Gold (prawdopodobnie będzie hostowane w osobnym repozytorium, sforkowanym z kodu Colobot Gold).
Kompilacja i uruchomienie gry
Instrukcje te znajdują się w pliku HOWTO.txt.
Kontakt
Jeżeli chcesz pomóc w projekcie, prosimy o kontakt na naszym kanale IRC: #colobot na pirc.pl albo na forum na naszej stronie: http://colobot.cba.pl/forum.

51
cmake/FindGLEW.cmake Normal file
View File

@ -0,0 +1,51 @@
# CMake module to find GLEW
# Borrowed from http://code.google.com/p/nvidia-texture-tools/
# MIT license Copyright (c) 2007 NVIDIA Corporation
# Try to find GLEW library and include path.
# Once done this will define
#
# GLEW_FOUND
# GLEW_INCLUDE_PATH
# GLEW_LIBRARY
#
IF (WIN32)
FIND_PATH( GLEW_INCLUDE_PATH GL/glew.h
$ENV{PROGRAMFILES}/GLEW/include
${PROJECT_SOURCE_DIR}/src/nvgl/glew/include
DOC "The directory where GL/glew.h resides")
FIND_LIBRARY( GLEW_LIBRARY
NAMES glew GLEW glew32 glew32s
PATHS
/mingw/bin # for MinGW's MSYS
/mingw/lib
${PROJECT_SOURCE_DIR}/glew/bin # or in local directory
${PROJECT_SOURCE_DIR}/glew/lib
DOC "The GLEW library")
ELSE (WIN32)
FIND_PATH( GLEW_INCLUDE_PATH GL/glew.h
/usr/include
/usr/local/include
/sw/include
/opt/local/include
DOC "The directory where GL/glew.h resides")
FIND_LIBRARY( GLEW_LIBRARY
NAMES GLEW glew
PATHS
/usr/lib64
/usr/lib
/usr/local/lib64
/usr/local/lib
/sw/lib
/opt/local/lib
DOC "The GLEW library")
ENDIF (WIN32)
IF (GLEW_INCLUDE_PATH)
SET( GLEW_FOUND 1 CACHE STRING "Set to 1 if GLEW is found, 0 otherwise")
ELSE (GLEW_INCLUDE_PATH)
SET( GLEW_FOUND 0 CACHE STRING "Set to 1 if GLEW is found, 0 otherwise")
ENDIF (GLEW_INCLUDE_PATH)
MARK_AS_ADVANCED( GLEW_FOUND )

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,279 +0,0 @@
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// French (France) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA)
#ifdef _WIN32
LANGUAGE LANG_FRENCH, SUBLANG_FRENCH
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE DISCARDABLE
BEGIN
ID_IF "if"
ID_ELSE "else"
ID_WHILE "while"
ID_DO "do"
ID_FOR "for"
ID_BREAK "break"
ID_CONTINUE "continue"
ID_SWITCH "switch"
ID_CASE "case"
ID_DEFAULT "default"
ID_TRY "try"
ID_THROW "throw"
ID_CATCH "catch"
ID_FINALLY "finally"
ID_TXT_AND "and"
ID_TXT_OR "or"
END
STRINGTABLE DISCARDABLE
BEGIN
ID_DEBUGDD "STARTDEBUGDD"
ID_INT "int"
ID_FLOAT "float"
ID_BOOLEAN "boolean"
ID_STRING "string"
ID_VOID "void"
ID_BOOL "bool"
END
STRINGTABLE DISCARDABLE
BEGIN
ID_TXT_NOT "not"
ID_RETURN "return"
ID_CLASS "class"
ID_EXTENDS "extends"
ID_SYNCHO "synchronized"
ID_NEW "new"
ID_PUBLIC "public"
ID_EXTERN "extern"
ID_FINAL "final"
ID_STATIC "static"
ID_PROTECTED "protected"
ID_PRIVATE "private"
ID_REPEAT "repeat"
END
STRINGTABLE DISCARDABLE
BEGIN
TX_OPENPAR "Il manque une parenthèse ouvrante."
TX_CLOSEPAR "Il manque une parenthèse fermante."
TX_NOTBOOL "L'expression doit être un boolean."
TX_UNDEFVAR "Variable non déclarée."
TX_BADLEFT "Assignation impossible."
TX_ENDOF "Terminateur point-virgule non trouvé."
TX_OUTCASE "Instruction ""case"" hors d'un bloc ""switch""."
TX_NOTERM "Instructions après la fin."
END
STRINGTABLE DISCARDABLE
BEGIN
TX_CLOSEBLK "Il manque la fin du bloc."
TX_ELSEWITHOUTIF "Instruction ""else"" sans ""if"" correspondant."
TX_OPENBLK "Début d'un bloc attendu."
TX_BADTYPE "Mauvais type de résultat pour l'assignation."
TX_REDEFVAR "Redéfinition d'une variable."
TX_BAD2TYPE "Les deux opérandes ne sont pas de types compatibles."
TX_UNDEFCALL "Routine inconnue."
TX_MISDOTS "Séparateur "" : "" attendu."
TX_WHILE "Manque le mot ""while""."
TX_BREAK "Instruction ""break"" en dehors d'une boucle."
TX_LABEL "Un label ne peut se placer que devant un ""for"", un ""while"" ou un ""do""."
TX_NOLABEL "Cette étiquette n'existe pas"
TX_NOCASE "Manque une instruction ""case""."
TX_BADNUM "Un nombre est attendu."
TX_VOID "Paramètre void."
TX_NOTYP "Déclaration de type attendu."
END
STRINGTABLE DISCARDABLE
BEGIN
TX_DIVZERO "Division par zéro."
TX_NOTINIT "Variable non initialisée."
TX_BADTHROW "Valeur négative refusée pour ""throw""."
TX_NORETVAL "La fonction n'a pas retourné de résultat"
TX_NORUN "Pas de fonction en exécution"
TX_NOCALL "Appel d'une fonction inexistante"
TX_NOCLASS "Cette classe n'existe pas"
TX_NULLPT "Pointeur nul."
TX_OPNAN "Opération sur un ""nan"""
TX_OUTARRAY "Accès hors du tableau"
TX_STACKOVER "Dépassement de la pile"
TX_DELETEDPT "Pointeur à un objet détruit"
TX_FILEOPEN "Ouverture du fichier impossible"
TX_NOTOPEN "Fichier pas ouvert"
TX_ERRREAD "Erreur de lecture"
TX_ERRWRITE "Erreur d'écriture"
END
STRINGTABLE DISCARDABLE
BEGIN
TX_NOVAR "Nom d'une variable attendu."
TX_NOFONC "Nom de la fonction attendu."
TX_OVERPARAM "Trop de paramètres."
TX_REDEF "Cette fonction existe déjà."
TX_LOWPARAM "Pas assez de paramètres."
TX_BADPARAM "Aucune fonction de ce nom n'accepte ce(s) type(s) de paramètre(s)."
TX_NUMPARAM "Aucune fonction de ce nom n'accepte ce nombre de paramètres."
TX_NOITEM "Cet élément n'existe pas dans cette classe."
TX_DOT "L'objet n'est pas une instance d'une classe."
TX_NOCONST "Il n'y a pas de constructeur approprié."
TX_REDEFCLASS "Cette classe existe déjà."
TX_CLBRK """ ] "" attendu."
TX_RESERVED "Ce mot est réservé."
TX_BADNEW "Mauvais argument pour ""new""."
TX_OPBRK """ [ "" attendu."
TX_BADSTRING "Une chaîne de caractère est attendue."
END
STRINGTABLE DISCARDABLE
BEGIN
TX_BADINDEX "Mauvais type d'index"
TX_PRIVATE "Membre privé de la classe"
TX_NOPUBLIC """public"" manque"
END
STRINGTABLE DISCARDABLE
BEGIN
ID_OPENPAR "("
ID_CLOSEPAR ")"
ID_OPBLK "{"
ID_CLBLK "}"
END
STRINGTABLE DISCARDABLE
BEGIN
ID_SEP ";"
ID_COMMA ","
ID_DOTS ":"
ID_DOT "."
ID_OPBRK "["
ID_CLBRK "]"
ID_DBLDOTS "::"
ID_LOGIC "?"
ID_ADD "+"
ID_SUB "-"
ID_MUL "*"
ID_DIV "/"
ID_ASS "="
ID_ASSADD "+="
ID_ASSSUB "-="
ID_ASSMUL "*="
END
STRINGTABLE DISCARDABLE
BEGIN
ID_TRUE "true"
ID_FALSE "false"
ID_NULL "null"
ID_NAN "nan"
END
STRINGTABLE DISCARDABLE
BEGIN
ID_ASSDIV "/="
ID_ASSOR "|="
ID_ASSAND "&="
ID_ASSXOR "^="
ID_ASSSL "<<="
ID_ASSSR ">>>="
ID_ASSASR ">>="
ID_SL "<<"
ID_SR ">>>"
ID_ASR ">>"
ID_INC "++"
ID_DEC "--"
ID_LO "<"
ID_HI ">"
ID_LS "<="
ID_HS ">="
END
STRINGTABLE DISCARDABLE
BEGIN
ID_EQ "=="
ID_NE "!="
ID_AND "&"
ID_XOR "^"
ID_OR "|"
ID_LOG_AND "&&"
ID_LOG_OR "||"
ID_LOG_NOT "!"
ID_NOT "~"
ID_MODULO "%"
ID_POWER "**"
ID_ASSMODULO "%="
END
STRINGTABLE DISCARDABLE
BEGIN
TX_UNDEF "undefined"
TX_NAN "not a number"
END
STRINGTABLE DISCARDABLE
BEGIN
ID_SUPER "super"
END
#endif // French (France) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@ -12,18 +12,20 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/./////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// expression du genre Opérande1 + Opérande2
// Opérande1 - Opérande2 ///////////////////////////////////////////////////
// expressions of type Operand1 + Operand2
// Operand1 - Operand2
#include "CBot.h" #include "CBot.h"
// divers constructeurs // various constructors
CBotAddExpr::CBotAddExpr() CBotAddExpr::CBotAddExpr()
{ {
m_leftop = m_leftop =
m_rightop = NULL; // NULL pour pouvoir faire delete sans autre m_rightop = NULL; // NULL to be able to delete without further
name = "CBotAddExpr"; // debug name = "CBotAddExpr"; // debug
} }
@ -38,105 +40,105 @@ CBotAddExpr::~CBotAddExpr()
CBotInstr* CBotAddExpr::Compile(CBotToken* &p, CBotStack* pStack) CBotInstr* CBotAddExpr::Compile(CBotToken* &p, CBotStack* pStack)
{ {
CBotStack* pStk = pStack->TokenStack(); // un bout de pile svp CBotStack* pStk = pStack->TokenStack(); // one end of stack please
// cherche des instructions qui peuvent convenir à gauche de l'opération + ou - // looking statements that may be suitable to the left of the operation + or -
CBotInstr* left = CBotMulExpr::Compile( p, pStk ); // expression A * B à gauche CBotInstr* left = CBotMulExpr::Compile( p, pStk ); // expression A * B left
if (left == NULL) return pStack->Return(NULL, pStk); // si erreur, la transmet if (left == NULL) return pStack->Return(NULL, pStk); // if error, transmit
// est-ce qu'on a le token + ou - ensuite ? // do we have the token + or - next?
if ( p->GetType() == ID_ADD || if ( p->GetType() == ID_ADD ||
p->GetType() == ID_SUB) // plus ou moins p->GetType() == ID_SUB) // more or less
{ {
CBotAddExpr* inst = new CBotAddExpr(); // élément pour opération CBotAddExpr* inst = new CBotAddExpr(); // element for operation
inst->SetToken(p); // mémorise l'opération inst->SetToken(p); // stores the operation
int type1, type2; int type1, type2;
type1 = pStack->GetType(); // de quel type le premier opérande ? type1 = pStack->GetType(); // what kind of the first operand?
p = p->Next(); // saute le token de l'opération p = p->Next(); // skip the token of the operation
// cherche des instructions qui peuvent convenir à droite // looking statements that may be suitable for right
if ( NULL != (inst->m_rightop = CBotAddExpr::Compile( p, pStk )) ) // expression (...) à droite if ( NULL != (inst->m_rightop = CBotAddExpr::Compile( p, pStk )) ) // expression (...) rigth
{ {
// il y a un second opérande acceptable // there is an acceptable second operand
type2 = pStack->GetType(); // de quel type le résultat ? type2 = pStack->GetType(); // what kind of results?
if ( type1 == type2 ) // les résultats sont-ils compatibles if ( type1 == type2 ) // are the results consistent ?
{ {
// si ok, enregistre l'opérande dans l'objet // ok so, saves the operand in the object
inst->m_leftop = left; inst->m_leftop = left;
// et rend l'object à qui l'a demandé // and makes the object on demand
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
} }
// en cas d'erreur, libère les éléments // in case of error, free the elements
delete left; delete left;
delete inst; delete inst;
// et transmet l'erreur qui se trouve sur la pile // and transmits the error that is on the stack
return pStack->Return(NULL, pStk); return pStack->Return(NULL, pStk);
} }
// si on n'a pas affaire à une opération + ou - // if we are not dealing with an operation + or -
// rend à qui l'a demandé, l'opérande (de gauche) trouvé // goes to that requested, the operand (left) found
// à la place de l'objet "addition" // place the object "addition"
return pStack->Return(left, pStk); return pStack->Return(left, pStk);
} }
// fait l'opération d'addition ou de soustraction // operation is addition or subtraction
BOOL CBotAddExpr::Execute(CBotStack* &pStack) bool CBotAddExpr::Execute(CBotStack* &pStack)
{ {
CBotStack* pStk1 = pStack->AddStack(this); // ajoute un élément à la pile CBotStack* pStk1 = pStack->AddStack(this); // adds an item to the stack
// ou le retrouve en cas de reprise // or is found in case of recovery
// if ( pSk1 == EOX ) return TRUE; // if ( pSk1 == EOX ) return TRUE;
// selon la reprise, on peut être dans l'un des 2 états // according to recovery, it may be in one of two states
if ( pStk1->GetState() == 0 && // 1er état, évalue l'opérande de gauche if ( pStk1->GetState() == 0 && // first state, evaluates the left operand
!m_leftop->Execute(pStk1) ) return FALSE; // interrompu ici ? !m_leftop->Execute(pStk1) ) return FALSE; // interrupted here?
// passe à l'étape suivante // passes to the next step
pStk1->SetState(1); // prêt pour la suite pStk1->SetState(1); // ready for further
// demande un peu plus de stack pour ne pas toucher le résultat de gauche // requires a little more stack to not touch the result of the left
// qui se trouve sur la pile, justement. // which is on the stack, precisely.
CBotStack* pStk2 = pStk1->AddStack(); // ajoute un élément à la pile CBotStack* pStk2 = pStk1->AddStack(); // adds an item to the stack
// ou le retrouve en cas de reprise // or is found in case of recovery
// 2e état, évalue l'opérande de droite // Second state, evaluates the right operand
if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrompu ici ? if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrupted here?
int type1 = pStk1->GetType(); // de quels types les résultats ? int type1 = pStk1->GetType(); // what kind of results?
int type2 = pStk2->GetType(); int type2 = pStk2->GetType();
// crée une variable temporaire pour y mettre le résultat // creates a temporary variable to put the result
CBotVar* result = new CBotVar( NULL, MAX(type1, type2)); CBotVar* result = new CBotVar( NULL, MAX(type1, type2));
// fait l'opération selon la demande // is the operation as requested
switch (GetTokenType()) switch (GetTokenType())
{ {
case ID_ADD: case ID_ADD:
result->Add(pStk1->GetVar(), pStk2->GetVar()); // additionne result->Add(pStk1->GetVar(), pStk2->GetVar()); // addition
break; break;
case ID_SUB: case ID_SUB:
result->Sub(pStk1->GetVar(), pStk2->GetVar()); // soustrait result->Sub(pStk1->GetVar(), pStk2->GetVar()); // subtraction
break; break;
} }
pStk2->SetVar(result); // met le résultat sur la pile pStk2->SetVar(result); // puts the result on the stack
pStk1->Return(pStk2); // libère la pile pStk1->Return(pStk2); // frees the stack
return pStack->Return(pStk1); // transmet le résultat return pStack->Return(pStk1); // transmits the result
} }

View File

@ -12,8 +12,10 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/./////////////////////////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.//
// Gestion des variables de type classe
/////////////////////////////////////////////////////////////////////
// Management of variables of class type
// //
#include "CBot.h" #include "CBot.h"
@ -21,7 +23,7 @@
CBotClass* CBotClass::m_ExClass = NULL; CBotClass* CBotClass::m_ExClass = NULL;
CBotClass::CBotClass(const char* name, CBotClass* pPapa, BOOL bIntrinsic) CBotClass::CBotClass(const char* name, CBotClass* pPapa, bool bIntrinsic)
{ {
m_pParent = pPapa; m_pParent = pPapa;
m_name = name; m_name = name;
@ -30,7 +32,7 @@ CBotClass::CBotClass(const char* name, CBotClass* pPapa, BOOL bIntrinsic)
m_pCalls = NULL; m_pCalls = NULL;
m_pMethod = NULL; m_pMethod = NULL;
m_rMaj = NULL; m_rMaj = NULL;
m_IsDef = TRUE; m_IsDef = true;
m_bIntrinsic= bIntrinsic; m_bIntrinsic= bIntrinsic;
m_cptLock = 0; m_cptLock = 0;
m_cptOne = 0; m_cptOne = 0;
@ -42,7 +44,7 @@ CBotClass::CBotClass(const char* name, CBotClass* pPapa, BOOL bIntrinsic)
} }
// se place tout seul dans la liste // is located alone in the list
if (m_ExClass) m_ExClass->m_ExPrev = this; if (m_ExClass) m_ExClass->m_ExPrev = this;
m_ExNext = m_ExClass; m_ExNext = m_ExClass;
m_ExPrev = NULL; m_ExPrev = NULL;
@ -52,7 +54,7 @@ CBotClass::CBotClass(const char* name, CBotClass* pPapa, BOOL bIntrinsic)
CBotClass::~CBotClass() CBotClass::~CBotClass()
{ {
// retire la classe de la liste // removes the list of class
if ( m_ExPrev ) m_ExPrev->m_ExNext = m_ExNext; if ( m_ExPrev ) m_ExPrev->m_ExNext = m_ExNext;
else m_ExClass = m_ExNext; else m_ExClass = m_ExNext;
@ -64,7 +66,7 @@ CBotClass::~CBotClass()
delete m_pCalls; delete m_pCalls;
delete m_pMethod; delete m_pMethod;
delete m_next; // libère toutes celle de ce niveau delete m_next; // releases all of them on this level
} }
@ -86,15 +88,15 @@ void CBotClass::Purge()
m_pCalls = NULL; m_pCalls = NULL;
delete m_pMethod; delete m_pMethod;
m_pMethod = NULL; m_pMethod = NULL;
m_IsDef = FALSE; m_IsDef = false;
m_nbVar = m_pParent == NULL ? 0 : m_pParent->m_nbVar; m_nbVar = m_pParent == NULL ? 0 : m_pParent->m_nbVar;
m_next->Purge(); m_next->Purge();
m_next = NULL; // n'appartient plus à cette chaîne m_next = NULL; // no longer belongs to this chain
} }
BOOL CBotClass::Lock(CBotProgram* p) bool CBotClass::Lock(CBotProgram* p)
{ {
int i = m_cptLock++; int i = m_cptLock++;
@ -102,13 +104,13 @@ BOOL CBotClass::Lock(CBotProgram* p)
{ {
m_cptOne = 1; m_cptOne = 1;
m_ProgInLock[0] = p; m_ProgInLock[0] = p;
return TRUE; return true;
} }
if ( p == m_ProgInLock[0] ) if ( p == m_ProgInLock[0] )
{ {
m_cptOne++; m_cptOne++;
m_cptLock--; // a déjà été compté m_cptLock--; // has already been counted
return TRUE; return true;
} }
for ( int j = 1 ; j <= i ; j++) for ( int j = 1 ; j <= i ; j++)
@ -116,18 +118,18 @@ BOOL CBotClass::Lock(CBotProgram* p)
if ( p == m_ProgInLock[j] ) if ( p == m_ProgInLock[j] )
{ {
m_cptLock--; m_cptLock--;
return FALSE; // déjà en attente return false; // already pending
} }
} }
if ( i < 5 ) // maxi 5 en attente if ( i < 5 ) // max 5 in query
{ {
m_ProgInLock[i] = p; // se place dans la queue m_ProgInLock[i] = p; // located in a queue
} }
else else
m_cptLock--; m_cptLock--;
return FALSE; return false;
} }
void CBotClass::Unlock() void CBotClass::Unlock()
@ -170,7 +172,7 @@ void CBotClass::FreeLock(CBotProgram* p)
BOOL CBotClass::AddItem(CBotString name, CBotTypResult type, int mPrivate) bool CBotClass::AddItem(CBotString name, CBotTypResult type, int mPrivate)
{ {
CBotToken token(name, CBotString()); CBotToken token(name, CBotString());
CBotClass* pClass = type.GivClass(); CBotClass* pClass = type.GivClass();
@ -184,7 +186,7 @@ BOOL CBotClass::AddItem(CBotString name, CBotTypResult type, int mPrivate)
// pVar->SetClass(pClass); // pVar->SetClass(pClass);
if ( type.Eq(CBotTypClass) ) if ( type.Eq(CBotTypClass) )
{ {
// ajoute une instruction new pour initialiser l'object // adds a new statement for the object initialization
pVar->m_InitExpr = new CBotNew() ; pVar->m_InitExpr = new CBotNew() ;
CBotToken nom( pClass->GivName() ); CBotToken nom( pClass->GivName() );
pVar->m_InitExpr->SetToken(&nom); pVar->m_InitExpr->SetToken(&nom);
@ -194,14 +196,14 @@ BOOL CBotClass::AddItem(CBotString name, CBotTypResult type, int mPrivate)
} }
BOOL CBotClass::AddItem(CBotVar* pVar) bool CBotClass::AddItem(CBotVar* pVar)
{ {
pVar->SetUniqNum(++m_nbVar); pVar->SetUniqNum(++m_nbVar);
if ( m_pVar == NULL ) m_pVar = pVar; if ( m_pVar == NULL ) m_pVar = pVar;
else m_pVar->AddNext(pVar); else m_pVar->AddNext(pVar);
return TRUE; return true;
} }
void CBotClass::AddNext(CBotClass* pClass) void CBotClass::AddNext(CBotClass* pClass)
@ -223,15 +225,15 @@ CBotClass* CBotClass::GivParent()
return m_pParent; return m_pParent;
} }
BOOL CBotClass::IsChildOf(CBotClass* pClass) bool CBotClass::IsChildOf(CBotClass* pClass)
{ {
CBotClass* p = this; CBotClass* p = this;
while ( p != NULL ) while ( p != NULL )
{ {
if ( p == pClass ) return TRUE; if ( p == pClass ) return true;
p = p->m_pParent; p = p->m_pParent;
} }
return FALSE; return false;
} }
@ -266,7 +268,7 @@ CBotVar* CBotClass::GivItemRef(int nIdent)
return NULL; return NULL;
} }
BOOL CBotClass::IsIntrinsic() bool CBotClass::IsIntrinsic()
{ {
return m_bIntrinsic; return m_bIntrinsic;
} }
@ -289,11 +291,11 @@ CBotClass* CBotClass::Find(const char* name)
return NULL; return NULL;
} }
BOOL CBotClass::AddFunction(const char* name, bool CBotClass::AddFunction(const char* name,
BOOL rExec (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception), bool rExec (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception),
CBotTypResult rCompile (CBotVar* pThis, CBotVar* &pVar)) CBotTypResult rCompile (CBotVar* pThis, CBotVar* &pVar))
{ {
// mémorise les pointeurs aux deux fonctions // stores pointers to the two functions
CBotCallMethode* p = m_pCalls; CBotCallMethode* p = m_pCalls;
CBotCallMethode* pp = NULL; CBotCallMethode* pp = NULL;
@ -313,32 +315,32 @@ BOOL CBotClass::AddFunction(const char* name,
p = new CBotCallMethode(name, rExec, rCompile); p = new CBotCallMethode(name, rExec, rCompile);
if (m_pCalls == NULL) m_pCalls = p; if (m_pCalls == NULL) m_pCalls = p;
else m_pCalls->AddNext(p); // ajoute à la liste else m_pCalls->AddNext(p); // added to the list
return TRUE; return true;
} }
BOOL CBotClass::AddUpdateFunc( void rMaj ( CBotVar* pThis, void* pUser ) ) bool CBotClass::AddUpdateFunc( void rMaj ( CBotVar* pThis, void* pUser ) )
{ {
m_rMaj = rMaj; m_rMaj = rMaj;
return TRUE; return true;
} }
// compile une méthode associée à une instance de classe // compiles a method associated with an instance of class
// la méthode peut être déclarée par AddFunction ou par l'utilisateur // the method can be declared by the user or AddFunction
CBotTypResult CBotClass::CompileMethode(const char* name, CBotTypResult CBotClass::CompileMethode(const char* name,
CBotVar* pThis, CBotVar** ppParams, CBotVar* pThis, CBotVar** ppParams,
CBotCStack* pStack, long& nIdent) CBotCStack* pStack, long& nIdent)
{ {
nIdent = 0; // oublie le précédent s'il y a lieu nIdent = 0; // forget the previous one if necessary
// recherche dans les méthodes déclarées par AddFunction // find the methods declared by AddFunction
CBotTypResult r = m_pCalls->CompileCall(name, pThis, ppParams, pStack, nIdent); CBotTypResult r = m_pCalls->CompileCall(name, pThis, ppParams, pStack, nIdent);
if ( r.GivType() >= 0) return r; if ( r.GivType() >= 0) return r;
// recherche dans les méthodes déclarées par l'utilisateur // find the methods declared by user
r = m_pMethod->CompileCall(name, ppParams, nIdent); r = m_pMethod->CompileCall(name, ppParams, nIdent);
if ( r.Eq(TX_UNDEFCALL) && m_pParent != NULL ) if ( r.Eq(TX_UNDEFCALL) && m_pParent != NULL )
@ -346,9 +348,9 @@ CBotTypResult CBotClass::CompileMethode(const char* name,
return r; return r;
} }
// exécute une méthode // executes a method
BOOL CBotClass::ExecuteMethode(long& nIdent, const char* name, bool CBotClass::ExecuteMethode(long& nIdent, const char* name,
CBotVar* pThis, CBotVar** ppParams, CBotVar* pThis, CBotVar** ppParams,
CBotVar* &pResult, CBotStack* &pStack, CBotVar* &pResult, CBotStack* &pStack,
CBotToken* pToken) CBotToken* pToken)
@ -360,7 +362,7 @@ BOOL CBotClass::ExecuteMethode(long& nIdent, const char* name,
return ret; return ret;
} }
// rétabli la pile d'exécution // restored the execution stack
void CBotClass::RestoreMethode(long& nIdent, const char* name, CBotVar* pThis, void CBotClass::RestoreMethode(long& nIdent, const char* name, CBotVar* pThis,
CBotVar** ppParams, CBotStack* &pStack) CBotVar** ppParams, CBotStack* &pStack)
@ -371,77 +373,77 @@ void CBotClass::RestoreMethode(long& nIdent, const char* name, CBotVar* pThis,
BOOL CBotClass::SaveStaticState(FILE* pf) bool CBotClass::SaveStaticState(FILE* pf)
{ {
if (!WriteWord( pf, CBOTVERSION*2)) return FALSE; if (!WriteWord( pf, CBOTVERSION*2)) return false;
// sauve l'état des variables statiques dans les classes // saves the state of static variables in classes
CBotClass* p = m_ExClass; CBotClass* p = m_ExClass;
while ( p != NULL ) while ( p != NULL )
{ {
if (!WriteWord( pf, 1)) return FALSE; if (!WriteWord( pf, 1)) return false;
// enregistre le nom de la classe // save the name of the class
if (!WriteString( pf, p->GivName() )) return FALSE; if (!WriteString( pf, p->GivName() )) return false;
CBotVar* pv = p->GivVar(); CBotVar* pv = p->GivVar();
while( pv != NULL ) while( pv != NULL )
{ {
if ( pv->IsStatic() ) if ( pv->IsStatic() )
{ {
if (!WriteWord( pf, 1)) return FALSE; if (!WriteWord( pf, 1)) return false;
if (!WriteString( pf, pv->GivName() )) return FALSE; if (!WriteString( pf, pv->GivName() )) return false;
if ( !pv->Save0State(pf)) return FALSE; // entête commune if ( !pv->Save0State(pf)) return false; // common header
if ( !pv->Save1State(pf) ) return FALSE; // sauve selon la classe fille if ( !pv->Save1State(pf) ) return false; // saves as the child class
if ( !WriteWord( pf, 0)) return FALSE; if ( !WriteWord( pf, 0)) return false;
} }
pv = pv->GivNext(); pv = pv->GivNext();
} }
if (!WriteWord( pf, 0)) return FALSE; if (!WriteWord( pf, 0)) return false;
p = p->m_ExNext; p = p->m_ExNext;
} }
if (!WriteWord( pf, 0)) return FALSE; if (!WriteWord( pf, 0)) return false;
return TRUE; return true;
} }
BOOL CBotClass::RestoreStaticState(FILE* pf) bool CBotClass::RestoreStaticState(FILE* pf)
{ {
CBotString ClassName, VarName; CBotString ClassName, VarName;
CBotClass* pClass; CBotClass* pClass;
WORD w; unsigned short w;
if (!ReadWord( pf, w )) return FALSE; if (!ReadWord( pf, w )) return false;
if ( w != CBOTVERSION*2 ) return FALSE; if ( w != CBOTVERSION*2 ) return false;
while (TRUE) while (true)
{ {
if (!ReadWord( pf, w )) return FALSE; if (!ReadWord( pf, w )) return false;
if ( w == 0 ) return TRUE; if ( w == 0 ) return true;
if (!ReadString( pf, ClassName )) return FALSE; if (!ReadString( pf, ClassName )) return false;
pClass = Find(ClassName); pClass = Find(ClassName);
while (TRUE) while (true)
{ {
if (!ReadWord( pf, w )) return FALSE; if (!ReadWord( pf, w )) return false;
if ( w == 0 ) break; if ( w == 0 ) break;
CBotVar* pVar = NULL; CBotVar* pVar = NULL;
CBotVar* pv = NULL; CBotVar* pv = NULL;
if (!ReadString( pf, VarName )) return FALSE; if (!ReadString( pf, VarName )) return false;
if ( pClass != NULL ) pVar = pClass->GivItem(VarName); if ( pClass != NULL ) pVar = pClass->GivItem(VarName);
if (!CBotVar::RestoreState(pf, pv)) return FALSE; // la variable temp if (!CBotVar::RestoreState(pf, pv)) return false; // the temp variable
if ( pVar != NULL ) pVar->Copy(pv); if ( pVar != NULL ) pVar->Copy(pv);
delete pv; delete pv;
} }
} }
return TRUE; return true;
} }
@ -453,7 +455,7 @@ CBotClassInst::CBotClassInst()
m_var = NULL; m_var = NULL;
m_Parameters = NULL; m_Parameters = NULL;
m_expr = NULL; m_expr = NULL;
m_hasParams = FALSE; m_hasParams = false;
m_nMethodeIdent = 0; m_nMethodeIdent = 0;
name = "CBotClassInst"; name = "CBotClassInst";
} }
@ -461,59 +463,58 @@ CBotClassInst::CBotClassInst()
CBotClassInst::~CBotClassInst() CBotClassInst::~CBotClassInst()
{ {
delete m_var; delete m_var;
// delete m_next; // fait par le destructeur de la classe de base ~CBotInstr() // delete m_next; // done by the destructor of the base class ~CBotInstr()
} }
// définition de pointeur(s) à un objet // definition of pointer (s) to an object
// du style // style
// CPoint A, B ; // CPoint A, B ;
CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass* pClass) CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass* pClass)
{ {
// cherche la classe correspondante // seeks the corresponding classes
if ( pClass == NULL ) if ( pClass == NULL )
{ {
pStack->SetStartError(p->GivStart()); pStack->SetStartError(p->GivStart());
pClass = CBotClass::Find(p); pClass = CBotClass::Find(p);
if ( pClass == NULL ) if ( pClass == NULL )
{ {
// pas trouvé ? c'est bizare // not found? is bizare
pStack->SetError(TX_NOCLASS, p); pStack->SetError(TX_NOCLASS, p);
return NULL; return NULL;
} }
p = p->GivNext(); p = p->GivNext();
} }
BOOL bIntrinsic = pClass->IsIntrinsic(); bool bIntrinsic = pClass->IsIntrinsic();
CBotTypResult CBotTypResult type = CBotTypResult( bIntrinsic ? CBotTypIntrinsic : CBotTypPointer, pClass );
type = CBotTypResult( bIntrinsic ? CBotTypIntrinsic : CBotTypPointer,
pClass );
CBotClassInst* inst = (CBotClassInst*)CompileArray(p, pStack, type); CBotClassInst* inst = (CBotClassInst*)CompileArray(p, pStack, type);
if ( inst != NULL || !pStack->IsOk() ) return inst; if ( inst != NULL || !pStack->IsOk() ) return inst;
CBotCStack* pStk = pStack->TokenStack(); CBotCStack* pStk = pStack->TokenStack();
inst = new CBotClassInst(); inst = new CBotClassInst();
/// \TODO Need to be revised and fixed after adding unit tests
inst->SetToken(&pClass->GivName(), p->GivStart(), p->GivEnd()); CBotToken token(pClass->GivName(), CBotString(), p->GivStart(), p->GivEnd());
inst->SetToken(&token);
CBotToken* vartoken = p; CBotToken* vartoken = p;
if ( NULL != (inst->m_var = CBotLeftExprVar::Compile( p, pStk )) ) if ( NULL != (inst->m_var = CBotLeftExprVar::Compile( p, pStk )) )
{ {
((CBotLeftExprVar*)inst->m_var)->m_typevar = type; ((CBotLeftExprVar*)inst->m_var)->m_typevar = type;
if (pStk->CheckVarLocal(vartoken)) // redéfinition de la variable if (pStk->CheckVarLocal(vartoken)) // redefinition of the variable
{ {
pStk->SetStartError(vartoken->GivStart()); pStk->SetStartError(vartoken->GivStart());
pStk->SetError(TX_REDEFVAR, vartoken->GivEnd()); pStk->SetError(TX_REDEFVAR, vartoken->GivEnd());
goto error; goto error;
} }
if (IsOfType(p, ID_OPBRK)) // avec des indices ? if (IsOfType(p, ID_OPBRK)) // with any clues?
{ {
delete inst; // n'est pas de type CBotInt delete inst; // is not type CBotInt
p = vartoken; // revient sur le nom de la variable p = vartoken; // returns to the variable name
// compile une déclaration de tableau // compiles declaration an array
inst = (CBotClassInst*)CBotInstArray::Compile( p, pStk, type ); inst = (CBotClassInst*)CBotInstArray::Compile( p, pStk, type );
@ -522,42 +523,42 @@ CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass*
pStk->SetError(TX_CLBRK, p->GivStart()); pStk->SetError(TX_CLBRK, p->GivStart());
goto error; goto error;
} }
goto suite; // pas d'assignation, variable déjà créée goto suite; // no assignment, variable already created
} }
CBotVar* var; CBotVar* var;
var = CBotVar::Create(vartoken->GivString(), type); // crée l'instance var = CBotVar::Create(vartoken->GivString(), type); // creates the instance
// var->SetClass(pClass); // var->SetClass(pClass);
var->SetUniqNum( var->SetUniqNum(
((CBotLeftExprVar*)inst->m_var)->m_nIdent = CBotVar::NextUniqNum()); ((CBotLeftExprVar*)inst->m_var)->m_nIdent = CBotVar::NextUniqNum());
// lui attribut un numéro unique // its attribute a unique number
pStack->AddVar(var); // la place sur la pile pStack->AddVar(var); // placed on the stack
// regarde s'il y a des paramètres // look if there are parameters
inst->m_hasParams = (p->GivType() == ID_OPENPAR); inst->m_hasParams = (p->GivType() == ID_OPENPAR);
CBotVar* ppVars[1000]; CBotVar* ppVars[1000];
inst->m_Parameters = CompileParams(p, pStk, ppVars); inst->m_Parameters = CompileParams(p, pStk, ppVars);
if ( !pStk->IsOk() ) goto error; if ( !pStk->IsOk() ) goto error;
// s'il y a des paramètres, fait l'équivalent de l'instruction new // if there are parameters, is the equivalent to the stament "new"
// CPoint A ( 0, 0 ) est équivalent à // CPoint A ( 0, 0 ) is equivalent to
// CPoint A = new CPoint( 0, 0 ) // CPoint A = new CPoint( 0, 0 )
// if ( NULL != inst->m_Parameters ) // if ( NULL != inst->m_Parameters )
if ( inst->m_hasParams ) if ( inst->m_hasParams )
{ {
// le constructeur existe-il ? // the constructor is there?
// CBotString noname; // CBotString noname;
CBotTypResult r = pClass->CompileMethode(pClass->GivName(), var, ppVars, pStk, inst->m_nMethodeIdent); CBotTypResult r = pClass->CompileMethode(pClass->GivName(), var, ppVars, pStk, inst->m_nMethodeIdent);
delete pStk->TokenStack(); // libère le supplément de pile delete pStk->TokenStack(); // releases the supplement stack
int typ = r.GivType(); int typ = r.GivType();
if (typ == TX_UNDEFCALL) if (typ == TX_UNDEFCALL)
{ {
// si le constructeur n'existe pas // si le constructeur n'existe pas
if (inst->m_Parameters != NULL) // avec des paramètres if (inst->m_Parameters != NULL) // with parameters
{ {
pStk->SetError(TX_NOCONST, vartoken); pStk->SetError(TX_NOCONST, vartoken);
goto error; goto error;
@ -573,7 +574,7 @@ CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass*
} }
if (IsOfType(p, ID_ASS)) // avec une assignation ? if (IsOfType(p, ID_ASS)) // with a assignment?
{ {
if (inst->m_hasParams) if (inst->m_hasParams)
{ {
@ -596,35 +597,35 @@ CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass*
// if ( !bIntrinsic ) var->SetPointer(pStk->GivVar()->GivPointer()); // if ( !bIntrinsic ) var->SetPointer(pStk->GivVar()->GivPointer());
if ( !bIntrinsic ) if ( !bIntrinsic )
{ {
// n'utilise pas le résultat sur la pile, pour imposer la classe // does not use the result on the stack, to impose the class
CBotVar* pvar = CBotVar::Create("", pClass); CBotVar* pvar = CBotVar::Create("", pClass);
var->SetPointer( pvar ); // var déjà déclarée pointe l'instance var->SetPointer( pvar ); // variable already declared instance pointer
delete pvar; // supprime le second pointeur delete pvar; // removes the second pointer
} }
var->SetInit(TRUE); // marque le pointeur comme init var->SetInit(true); // marks the pointer as init
} }
else if (inst->m_hasParams) else if (inst->m_hasParams)
{ {
// crée l'objet sur le "tas" // creates the object on the "job" (\TODO "tas")
// avec un pointeur sur cet objet // with a pointer to the object
if ( !bIntrinsic ) if ( !bIntrinsic )
{ {
CBotVar* pvar = CBotVar::Create("", pClass); CBotVar* pvar = CBotVar::Create("", pClass);
var->SetPointer( pvar ); // var déjà déclarée pointe l'instance var->SetPointer( pvar ); // variable already declared instance pointer
delete pvar; // supprime le second pointeur delete pvar; // removes the second pointer
} }
var->SetInit(2); // marque le pointeur comme init var->SetInit(2); // marks the pointer as init
} }
suite: suite:
if (IsOfType(p, ID_COMMA)) // plusieurs définitions enchaînées if (IsOfType(p, ID_COMMA)) // several chained definitions
{ {
if ( NULL != ( inst->m_next = CBotClassInst::Compile(p, pStk, pClass) )) // compile la suivante if ( NULL != ( inst->m_next = CBotClassInst::Compile(p, pStk, pClass) )) // compiles the following
{ {
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
} }
if (IsOfType(p, ID_SEP)) // instruction terminée if (IsOfType(p, ID_SEP)) // complete instruction
{ {
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
@ -637,22 +638,22 @@ error:
return pStack->Return(NULL, pStk); return pStack->Return(NULL, pStk);
} }
// déclaration de l'instance d'une classe, par exemple: // declaration of the instance of a class, for example:
// CPoint A, B; // CPoint A, B;
BOOL CBotClassInst::Execute(CBotStack* &pj) bool CBotClassInst::Execute(CBotStack* &pj)
{ {
CBotVar* pThis = NULL; CBotVar* pThis = NULL;
CBotStack* pile = pj->AddStack(this);//indispensable pour SetState() CBotStack* pile = pj->AddStack(this);//essential for SetState()
// if ( pile == EOX ) return TRUE; // if ( pile == EOX ) return true;
CBotToken* pt = &m_token; CBotToken* pt = &m_token;
CBotClass* pClass = CBotClass::Find(pt); CBotClass* pClass = CBotClass::Find(pt);
BOOL bIntrincic = pClass->IsIntrinsic(); bool bIntrincic = pClass->IsIntrinsic();
// crée la variable de type pointeur à l'objet // creates the variable of type pointer to the object
if ( pile->GivState()==0) if ( pile->GivState()==0)
{ {
@ -666,8 +667,8 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
pThis = CBotVar::Create(name, CBotTypResult( CBotTypPointer, pClass )); pThis = CBotVar::Create(name, CBotTypResult( CBotTypPointer, pClass ));
} }
pThis->SetUniqNum(((CBotLeftExprVar*)m_var)->m_nIdent); // lui attribut un numéro unique pThis->SetUniqNum(((CBotLeftExprVar*)m_var)->m_nIdent); // its attribute as unique number
pile->AddVar(pThis); // la place sur la pile pile->AddVar(pThis); // place on the stack
pile->IncState(); pile->IncState();
} }
@ -675,14 +676,14 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
if ( pile->GivState()<3) if ( pile->GivState()<3)
{ {
// y a-t-il une assignation ou des paramètres (constructeur) // ss there an assignment or parameters (contructor)
// CBotVarClass* pInstance = NULL; // CBotVarClass* pInstance = NULL;
if ( m_expr != NULL ) if ( m_expr != NULL )
{ {
// évalue l'expression pour l'assignation // evaluates the expression for the assignment
if (!m_expr->Execute(pile)) return FALSE; if (!m_expr->Execute(pile)) return false;
if ( bIntrincic ) if ( bIntrincic )
{ {
@ -692,27 +693,27 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
pile->SetError(TX_NULLPT, &m_token); pile->SetError(TX_NULLPT, &m_token);
return pj->Return(pile); return pj->Return(pile);
} }
pThis->Copy(pile->GivVar(), FALSE); pThis->Copy(pile->GivVar(), false);
} }
else else
{ {
CBotVarClass* pInstance; CBotVarClass* pInstance;
pInstance = ((CBotVarPointer*)pile->GivVar())->GivPointer(); // valeur pour l'assignation pInstance = ((CBotVarPointer*)pile->GivVar())->GivPointer(); // value for the assignment
pThis->SetPointer(pInstance); pThis->SetPointer(pInstance);
} }
pThis->SetInit(TRUE); pThis->SetInit(true);
} }
else if ( m_hasParams ) else if ( m_hasParams )
{ {
// évalue le constructeur d'une instance // evaluates the constructor of an instance
if ( !bIntrincic && pile->GivState() == 1) if ( !bIntrincic && pile->GivState() == 1)
{ {
CBotToken* pt = &m_token; CBotToken* pt = &m_token;
CBotClass* pClass = CBotClass::Find(pt); CBotClass* pClass = CBotClass::Find(pt);
// crée une instance de la classe demandée // creates an instance of the requested class
CBotVarClass* pInstance; CBotVarClass* pInstance;
pInstance = (CBotVarClass*)CBotVar::Create("", pClass); pInstance = (CBotVarClass*)CBotVar::Create("", pClass);
@ -728,16 +729,16 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
int i = 0; int i = 0;
CBotInstr* p = m_Parameters; CBotInstr* p = m_Parameters;
// évalue les paramètres // evaluates the parameters
// et place les valeurs sur la pile // and places the values on the stack
// pour pouvoir être interrompu n'importe quand // to (can) be interrupted (broken) at any time
if ( p != NULL) while ( TRUE ) if ( p != NULL) while ( true )
{ {
pile2 = pile2->AddStack(); // de la place sur la pile pour les résultats pile2 = pile2->AddStack(); // place on the stack for the results
if ( pile2->GivState() == 0 ) if ( pile2->GivState() == 0 )
{ {
if (!p->Execute(pile2)) return FALSE; // interrompu ici ? if (!p->Execute(pile2)) return false; // interrupted here?
pile2->SetState(1); pile2->SetState(1);
} }
ppVars[i++] = pile2->GivVar(); ppVars[i++] = pile2->GivVar();
@ -746,37 +747,37 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
} }
ppVars[i] = NULL; ppVars[i] = NULL;
// crée une variable pour le résultat // creates a variable for the result
CBotVar* pResult = NULL; // constructeurs toujours void CBotVar* pResult = NULL; // constructor still void
if ( !pClass->ExecuteMethode(m_nMethodeIdent, pClass->GivName(), if ( !pClass->ExecuteMethode(m_nMethodeIdent, pClass->GivName(),
pThis, ppVars, pThis, ppVars,
pResult, pile2, GivToken())) return FALSE; // interrompu pResult, pile2, GivToken())) return false; // interrupt
pThis->SetInit(TRUE); pThis->SetInit(true);
pThis->ConstructorSet(); // signale que le constructeur a été appelé pThis->ConstructorSet(); // indicates that the constructor has been called
pile->Return(pile2); // libère un bout de pile pile->Return(pile2); // releases a piece of stack
// pInstance = pThis->GivPointer(); // pInstance = pThis->GivPointer();
} }
// if ( !bIntrincic ) pThis->SetPointer(pInstance); // le fait pointer l'instance // if ( !bIntrincic ) pThis->SetPointer(pInstance); // a pointer to the instance
pile->SetState(3); // fini cette partie pile->SetState(3); // finished this part
} }
if ( pile->IfStep() ) return FALSE; if ( pile->IfStep() ) return false;
if ( m_next2b != NULL && if ( m_next2b != NULL &&
!m_next2b->Execute(pile)) return FALSE; // autre(s) définition(s) !m_next2b->Execute(pile)) return false; // other (s) definition (s)
return pj->Return( pile ); // transmet en dessous return pj->Return( pile ); // transmits below (further)
} }
void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain) void CBotClassInst::RestoreState(CBotStack* &pj, bool bMain)
{ {
CBotVar* pThis = NULL; CBotVar* pThis = NULL;
@ -784,33 +785,33 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
if ( bMain ) pile = pj->RestoreStack(this); if ( bMain ) pile = pj->RestoreStack(this);
if ( pile == NULL ) return; if ( pile == NULL ) return;
// crée la variable de type pointeur à l'objet // creates the variable of type pointer to the object
{ {
CBotString name = m_var->m_token.GivString(); CBotString name = m_var->m_token.GivString();
pThis = pile->FindVar(name); pThis = pile->FindVar(name);
pThis->SetUniqNum(((CBotLeftExprVar*)m_var)->m_nIdent); // lui attribut un numéro unique pThis->SetUniqNum(((CBotLeftExprVar*)m_var)->m_nIdent); // its attribute a unique number
} }
CBotToken* pt = &m_token; CBotToken* pt = &m_token;
CBotClass* pClass = CBotClass::Find(pt); CBotClass* pClass = CBotClass::Find(pt);
BOOL bIntrincic = pClass->IsIntrinsic(); bool bIntrincic = pClass->IsIntrinsic();
if ( bMain && pile->GivState()<3) if ( bMain && pile->GivState()<3)
{ {
// y a-t-il une assignation ou des paramètres (constructeur) // is there an assignment or parameters (constructor)
// CBotVarClass* pInstance = NULL; // CBotVarClass* pInstance = NULL;
if ( m_expr != NULL ) if ( m_expr != NULL )
{ {
// évalue l'expression pour l'assignation // evaluates the expression for the assignment
m_expr->RestoreState(pile, bMain); m_expr->RestoreState(pile, bMain);
return; return;
} }
else if ( m_hasParams ) else if ( m_hasParams )
{ {
// évalue le constructeur d'une instance // evaluates the constructor of an instance
if ( !bIntrincic && pile->GivState() == 1) if ( !bIntrincic && pile->GivState() == 1)
{ {
@ -823,18 +824,18 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
int i = 0; int i = 0;
CBotInstr* p = m_Parameters; CBotInstr* p = m_Parameters;
// évalue les paramètres // evaluates the parameters
// et place les valeurs sur la pile // and the values an the stack
// pour pouvoir être interrompu n'importe quand // for the ability to be interrupted at any time (\TODO pour pouvoir être interrompu n'importe quand)
if ( p != NULL) while ( TRUE ) if ( p != NULL) while ( true )
{ {
pile2 = pile2->RestoreStack(); // de la place sur la pile pour les résultats pile2 = pile2->RestoreStack(); // place on the stack for the results
if ( pile2 == NULL ) return; if ( pile2 == NULL ) return;
if ( pile2->GivState() == 0 ) if ( pile2->GivState() == 0 )
{ {
p->RestoreState(pile2, bMain); // interrompu ici ? p->RestoreState(pile2, bMain); // interrupted here?
return; return;
} }
ppVars[i++] = pile2->GivVar(); ppVars[i++] = pile2->GivVar();
@ -843,8 +844,8 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
} }
ppVars[i] = NULL; ppVars[i] = NULL;
// crée une variable pour le résultat // creates a variable for the result
CBotVar* pResult = NULL; // constructeurs toujours void CBotVar* pResult = NULL; // constructor still void
pClass->RestoreMethode(m_nMethodeIdent, pClass->GivName(), pThis, ppVars, pile2); pClass->RestoreMethode(m_nMethodeIdent, pClass->GivName(), pThis, ppVars, pile2);
return; return;
@ -852,30 +853,30 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
} }
if ( m_next2b != NULL ) if ( m_next2b != NULL )
m_next2b->RestoreState(pile, bMain); // autre(s) définition(s) m_next2b->RestoreState(pile, bMain); // other(s) definition(s)
} }
// test si un nom de procédure est déjà défini quelque part // test if a procedure name is already defined somewhere
BOOL CBotClass::CheckCall(CBotToken* &pToken, CBotDefParam* pParam) bool CBotClass::CheckCall(CBotToken* &pToken, CBotDefParam* pParam)
{ {
CBotString name = pToken->GivString(); CBotString name = pToken->GivString();
if ( CBotCall::CheckCall(name) ) return TRUE; if ( CBotCall::CheckCall(name) ) return true;
CBotFunction* pp = m_pMethod; CBotFunction* pp = m_pMethod;
while ( pp != NULL ) while ( pp != NULL )
{ {
if ( pToken->GivString() == pp->GivName() ) if ( pToken->GivString() == pp->GivName() )
{ {
// les paramètres sont-ils exactement les mêmes ? // are their parameters exactly the same?
if ( pp->CheckParam( pParam ) ) if ( pp->CheckParam( pParam ) )
return TRUE; return true;
} }
pp = pp->Next(); pp = pp->Next();
} }
return FALSE; return false;
} }

View File

@ -12,14 +12,16 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/./////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// expression du genre Opérande1 > Opérande2
// Opérande1 != Opérande2 ///////////////////////////////////////////////////
// expression of type Opérande1 > Opérande2
// Opérande1 != Opérande2
// etc. // etc.
#include "CBot.h" #include "CBot.h"
// divers constructeurs // various constructeurs
CBotCompExpr::CBotCompExpr() CBotCompExpr::CBotCompExpr()
{ {
@ -36,38 +38,38 @@ CBotCompExpr::~CBotCompExpr()
fichier plus utilise; fichier plus utilise;
// compile une instruction de type A < B // compile instruction of type A < B
CBotInstr* CBotCompExpr::Compile(CBotToken* &p, CBotCStack* pStack) CBotInstr* CBotCompExpr::Compile(CBotToken* &p, CBotCStack* pStack)
{ {
CBotCStack* pStk = pStack->AddStack(); CBotCStack* pStk = pStack->AddStack();
CBotInstr* left = CBotAddExpr::Compile( p, pStk ); // expression A + B à gauche CBotInstr* left = CBotAddExpr::Compile( p, pStk ); // expression A + B left
if (left == NULL) return pStack->Return(NULL, pStk); // erreur if (left == NULL) return pStack->Return(NULL, pStk); // error
if ( p->GetType() == ID_HI || if ( p->GetType() == ID_HI ||
p->GetType() == ID_LO || p->GetType() == ID_LO ||
p->GetType() == ID_HS || p->GetType() == ID_HS ||
p->GetType() == ID_LS || p->GetType() == ID_LS ||
p->GetType() == ID_EQ || p->GetType() == ID_EQ ||
p->GetType() == ID_NE) // les diverses comparaisons p->GetType() == ID_NE) // the various comparisons
{ {
CBotCompExpr* inst = new CBotCompExpr(); // élément pour opération CBotCompExpr* inst = new CBotCompExpr(); // element for operation
inst->SetToken(p); // mémorise l'opération inst->SetToken(p); // stores the operation
int type1, type2; int type1, type2;
type1 = pStack->GetType(); type1 = pStack->GetType();
p = p->Next(); p = p->Next();
if ( NULL != (inst->m_rightop = CBotAddExpr::Compile( p, pStk )) ) // expression A + B à droite if ( NULL != (inst->m_rightop = CBotAddExpr::Compile( p, pStk )) ) // expression A + B right
{ {
type2 = pStack->GetType(); type2 = pStack->GetType();
// les résultats sont-ils compatibles // are the results compatible
if ( type1 == type2 ) if ( type1 == type2 )
{ {
inst->m_leftop = left; inst->m_leftop = left;
pStk->SetVar(new CBotVar(NULL, CBotTypBoolean)); pStk->SetVar(new CBotVar(NULL, CBotTypBoolean));
// le résultat est un boolean // the result is a boolean
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
} }
@ -81,21 +83,21 @@ CBotInstr* CBotCompExpr::Compile(CBotToken* &p, CBotCStack* pStack)
} }
// fait l'opération // perform the operation
BOOL CBotCompExpr::Execute(CBotStack* &pStack) bool CBotCompExpr::Execute(CBotStack* &pStack)
{ {
CBotStack* pStk1 = pStack->AddStack(this); CBotStack* pStk1 = pStack->AddStack(this);
// if ( pStk1 == EOX ) return TRUE; // if ( pStk1 == EOX ) return TRUE;
if ( pStk1->GetState() == 0 && !m_leftop->Execute(pStk1) ) return FALSE; // interrompu ici ? if ( pStk1->GetState() == 0 && !m_leftop->Execute(pStk1) ) return FALSE; // interrupted here ?
pStk1->SetState(1); // opération terminée pStk1->SetState(1); // finished
// demande un peu plus de stack pour ne pas toucher le résultat de gauche // requires a little more stack to not touch the result of the left
CBotStack* pStk2 = pStk1->AddStack(); CBotStack* pStk2 = pStk1->AddStack();
if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrompu ici ? if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrupted here ?
int type1 = pStk1->GetType(); int type1 = pStk1->GetType();
int type2 = pStk2->GetType(); int type2 = pStk2->GetType();
@ -105,27 +107,27 @@ BOOL CBotCompExpr::Execute(CBotStack* &pStack)
switch (GetTokenType()) switch (GetTokenType())
{ {
case ID_LO: case ID_LO:
result->Lo(pStk1->GetVar(), pStk2->GetVar()); // inférieur result->Lo(pStk1->GetVar(), pStk2->GetVar()); // lower
break; break;
case ID_HI: case ID_HI:
result->Hi(pStk1->GetVar(), pStk2->GetVar()); // supérieur result->Hi(pStk1->GetVar(), pStk2->GetVar()); // higher
break; break;
case ID_LS: case ID_LS:
result->Ls(pStk1->GetVar(), pStk2->GetVar()); // inférieur ou égal result->Ls(pStk1->GetVar(), pStk2->GetVar()); // lower or equal
break; break;
case ID_HS: case ID_HS:
result->Hs(pStk1->GetVar(), pStk2->GetVar()); // supérieur ou égal result->Hs(pStk1->GetVar(), pStk2->GetVar()); // higher of equal
break; break;
case ID_EQ: case ID_EQ:
result->Eq(pStk1->GetVar(), pStk2->GetVar()); // égal result->Eq(pStk1->GetVar(), pStk2->GetVar()); // equal
break; break;
case ID_NE: case ID_NE:
result->Ne(pStk1->GetVar(), pStk2->GetVar()); // différent result->Ne(pStk1->GetVar(), pStk2->GetVar()); // not equal
break; break;
} }
pStk2->SetVar(result); // met le résultat sur la pile pStk2->SetVar(result); // puts the result on the stack
pStk1->Return(pStk2); // libère la pile pStk1->Return(pStk2); // frees the stack
return pStack->Return(pStk1); // transmet le résultat return pStack->Return(pStk1); // transmit the result
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,148 +12,150 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/./////////////////////////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// instruction if (condition) opération1 else opération2;
///////////////////////////////////////////////////////////////////////
// instruction if (condition) operation1 else operation2;
#include "CBot.h" #include "CBot.h"
// les divers constructeurs / destructeurs // various constructors / destructors
CBotIf::CBotIf() CBotIf::CBotIf()
{ {
m_Condition = m_Condition =
m_Block = m_Block =
m_BlockElse = NULL; // NULL pour pouvoir faire delete directement m_BlockElse = NULL; // NULL so that delete is not possible further
name = "CBotIf"; // debug name = "CBotIf"; // debug
} }
CBotIf::~CBotIf() CBotIf::~CBotIf()
{ {
delete m_Condition; // libère la condition delete m_Condition; // frees the condition
delete m_Block; // libère le bloc d'instruction1 delete m_Block; // frees the block of instruction1
delete m_BlockElse; // libère le bloc d'instruction2 delete m_BlockElse; // frees the block of instruction2
} }
// compilation (routine statique) // compilation (static routine)
// appelé lorsque le token "if" a été trouvé // called when the token "if" has been found
CBotInstr* CBotIf::Compile(CBotToken* &p, CBotCStack* pStack) CBotInstr* CBotIf::Compile(CBotToken* &p, CBotCStack* pStack)
{ {
CBotToken* pp = p; // conserve le ^au token (début instruction) CBotToken* pp = p; // preserves at the ^ token (starting instruction)
if (!IsOfType(p, ID_IF)) return NULL; // ne doit jamais arriver if (!IsOfType(p, ID_IF)) return NULL; // should never happen
CBotCStack* pStk = pStack->TokenStack(pp); // un petit bout de pile svp CBotCStack* pStk = pStack->TokenStack(pp); // un petit bout de pile svp
CBotIf* inst = new CBotIf(); // crée l'object CBotIf* inst = new CBotIf(); // create the object
inst->SetToken( pp ); inst->SetToken( pp );
if ( NULL != (inst->m_Condition = CBotCondition::Compile( p, pStk )) ) if ( NULL != (inst->m_Condition = CBotCondition::Compile( p, pStk )) )
{ {
// la condition existe bel et bien // the condition does exist
inst->m_Block = CBotBlock::CompileBlkOrInst( p, pStk, TRUE ); inst->m_Block = CBotBlock::CompileBlkOrInst( p, pStk, true );
if ( pStk->IsOk() ) if ( pStk->IsOk() )
{ {
// le bloc d'instruction est ok (peut être vide) // the statement block is ok (can be empty)
// regarde si l'instruction suivante est le token "else" // see if the next instruction is the token "else"
if (IsOfType(p, ID_ELSE)) if (IsOfType(p, ID_ELSE))
{ {
// si oui, compile le bloc d'instruction qui suit // if so, compiles the following statement block
inst->m_BlockElse = CBotBlock::CompileBlkOrInst( p, pStk, TRUE ); inst->m_BlockElse = CBotBlock::CompileBlkOrInst( p, pStk, true );
if (!pStk->IsOk()) if (!pStk->IsOk())
{ {
// il n'y a pas de bloc correct après le else // there is no correct block after the else
// libère l'objet, et transmet l'erreur qui est sur la pile // frees the object, and transmits the error that is on the stack
delete inst; delete inst;
return pStack->Return(NULL, pStk); return pStack->Return(NULL, pStk);
} }
} }
// rend l'object correct à qui le demande. // return the corrent object to the application
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
} }
// erreur, libère l'objet // error, frees the object
delete inst; delete inst;
// et transmet l'erreur qui se trouve sur la pile. // and transmits the error that is on the stack.
return pStack->Return(NULL, pStk); return pStack->Return(NULL, pStk);
} }
// exécution de l'instruction // execution of the instruction
BOOL CBotIf :: Execute(CBotStack* &pj) bool CBotIf :: Execute(CBotStack* &pj)
{ {
CBotStack* pile = pj->AddStack(this); // ajoute un élément à la pile CBotStack* pile = pj->AddStack(this); // adds an item to the stack
// ou le retrouve en cas de reprise // or found in case of recovery
// if ( pile == EOX ) return TRUE; // if ( pile == EOX ) return true;
if ( pile->IfStep() ) return FALSE; if ( pile->IfStep() ) return false;
// selon la reprise, on peut être dans l'un des 2 états // according to recovery, it may be in one of two states
if( pile->GivState() == 0 ) if( pile->GivState() == 0 )
{ {
// évalue la condition // evaluates the condition
if ( !m_Condition->Execute(pile) ) return FALSE; // interrompu ici ? if ( !m_Condition->Execute(pile) ) return false; // interrupted here?
// termine s'il y a une erreur // terminates if there is an error
if ( !pile->IsOk() ) if ( !pile->IsOk() )
{ {
return pj->Return(pile); // transmet le résultat et libère la pile return pj->Return(pile); // returns the results and releases the stack
} }
// passe dans le second état // passes into the second state
if (!pile->SetState(1)) return FALSE; // prêt pour la suite if (!pile->SetState(1)) return false; // ready for further
} }
// second état, évalue les instructions associées // second state, evaluates the associated instructions
// le résultat de la condition est sur la pile // the result of the condition is on the stack
if ( pile->GivVal() == TRUE ) // condition était vraie ? if ( pile->GivVal() == true ) // condition was true?
{ {
if ( m_Block != NULL && // bloc peut être absent if ( m_Block != NULL && // block may be absent
!m_Block->Execute(pile) ) return FALSE; // interrompu ici ? !m_Block->Execute(pile) ) return false; // interrupted here?
} }
else else
{ {
if ( m_BlockElse != NULL && // s'il existe un bloc alternatif if ( m_BlockElse != NULL && // if there is an alternate block
!m_BlockElse->Execute(pile) ) return FALSE; // interrompu ici !m_BlockElse->Execute(pile) ) return false; // interrupted here
} }
// transmet le résultat et libère la pile // sends the results and releases the stack
return pj->Return(pile); return pj->Return(pile);
} }
void CBotIf :: RestoreState(CBotStack* &pj, BOOL bMain) void CBotIf :: RestoreState(CBotStack* &pj, bool bMain)
{ {
if ( !bMain ) return; if ( !bMain ) return;
CBotStack* pile = pj->RestoreStack(this); // ajoute un élément à la pile CBotStack* pile = pj->RestoreStack(this); // adds an item to the stack
if ( pile == NULL ) return; if ( pile == NULL ) return;
// selon la reprise, on peut être dans l'un des 2 états // according to recovery, it may be in one of two states
if( pile->GivState() == 0 ) if( pile->GivState() == 0 )
{ {
// évalue la condition // evaluates the condition
m_Condition->RestoreState(pile, bMain); // interrompu ici ! m_Condition->RestoreState(pile, bMain); // interrupted here!
return; return;
} }
// second état, évalue les instructions associées // second state, evaluates the associated instructions
// le résultat de la condition est sur la pile // the result of the condition is on the stack
if ( pile->GivVal() == TRUE ) // condition était vraie ? if ( pile->GivVal() == true ) // condition was true?
{ {
if ( m_Block != NULL ) // bloc peut être absent if ( m_Block != NULL ) // block may be absent
m_Block->RestoreState(pile, bMain); // interrompu ici ! m_Block->RestoreState(pile, bMain); // interrupted here!
} }
else else
{ {
if ( m_BlockElse != NULL ) // s'il existe un bloc alternatif if ( m_BlockElse != NULL ) // if there is an alternate block
m_BlockElse->RestoreState(pile, bMain); // interrompu ici ! m_BlockElse->RestoreState(pile, bMain); // interrupted here!
} }
} }

View File

@ -12,8 +12,10 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.////////////////////////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// gestion de base d'un programme CBot
//////////////////////////////////////////////////////////////////////
// database management of CBoT program
#include "CBot.h" #include "CBot.h"
#include <stdio.h> #include <stdio.h>
@ -62,14 +64,14 @@ CBotProgram::~CBotProgram()
} }
BOOL CBotProgram::Compile( const char* program, CBotStringArray& ListFonctions, void* pUser ) bool CBotProgram::Compile( const char* program, CBotStringArray& ListFonctions, void* pUser )
{ {
int error = 0; int error = 0;
Stop(); Stop();
// delete m_pClass; // delete m_pClass;
m_pClass->Purge(); // purge les anciennes définitions des classes m_pClass->Purge(); // purge the old definitions of classes
// mais sans détruire l'object // but without destroying the object
m_pClass = NULL; m_pClass = NULL;
delete m_Prog; m_Prog= NULL; delete m_Prog; m_Prog= NULL;
@ -79,21 +81,21 @@ BOOL CBotProgram::Compile( const char* program, CBotStringArray& ListFonctions,
if (m_pInstance != NULL && m_pInstance->m_pUserPtr != NULL) if (m_pInstance != NULL && m_pInstance->m_pUserPtr != NULL)
pUser = m_pInstance->m_pUserPtr; pUser = m_pInstance->m_pUserPtr;
// transforme le programme en Tokens // transforms the program in Tokens
CBotToken* pBaseToken = CBotToken::CompileTokens(program, error); CBotToken* pBaseToken = CBotToken::CompileTokens(program, error);
if ( pBaseToken == NULL ) return FALSE; if ( pBaseToken == NULL ) return false;
CBotCStack* pStack = new CBotCStack(NULL); CBotCStack* pStack = new CBotCStack(NULL);
CBotToken* p = pBaseToken->GivNext(); // saute le 1er token (séparateur) CBotToken* p = pBaseToken->GivNext(); // skips the first token (separator)
pStack->SetBotCall(this); // défini les routines utilisables pStack->SetBotCall(this); // defined used routines
CBotCall::SetPUser(pUser); CBotCall::SetPUser(pUser);
// fait une première passe rapide juste pour prendre les entêtes de routines et de classes // first made a quick pass just to take the headers of routines and classes
while ( pStack->IsOk() && p != NULL && p->GivType() != 0) while ( pStack->IsOk() && p != NULL && p->GivType() != 0)
{ {
if ( IsOfType(p, ID_SEP) ) continue; // des point-virgules qui trainent if ( IsOfType(p, ID_SEP) ) continue; // semicolons lurking
if ( p->GivType() == ID_CLASS || if ( p->GivType() == ID_CLASS ||
( p->GivType() == ID_PUBLIC && p->GivNext()->GivType() == ID_CLASS )) ( p->GivType() == ID_PUBLIC && p->GivNext()->GivType() == ID_CLASS ))
@ -115,36 +117,36 @@ BOOL CBotProgram::Compile( const char* program, CBotStringArray& ListFonctions,
delete m_Prog; delete m_Prog;
m_Prog = NULL; m_Prog = NULL;
delete pBaseToken; delete pBaseToken;
return FALSE; return false;
} }
// CBotFunction* temp = NULL; // CBotFunction* temp = NULL;
CBotFunction* next = m_Prog; // reprend la liste CBotFunction* next = m_Prog; // rewind the list
p = pBaseToken->GivNext(); // revient au début p = pBaseToken->GivNext(); // returns to the beginning
while ( pStack->IsOk() && p != NULL && p->GivType() != 0 ) while ( pStack->IsOk() && p != NULL && p->GivType() != 0 )
{ {
if ( IsOfType(p, ID_SEP) ) continue; // des point-virgules qui trainent if ( IsOfType(p, ID_SEP) ) continue; // semicolons lurking
if ( p->GivType() == ID_CLASS || if ( p->GivType() == ID_CLASS ||
( p->GivType() == ID_PUBLIC && p->GivNext()->GivType() == ID_CLASS )) ( p->GivType() == ID_PUBLIC && p->GivNext()->GivType() == ID_CLASS ))
{ {
m_bCompileClass = TRUE; m_bCompileClass = true;
CBotClass::Compile(p, pStack); // complète la définition de la classe CBotClass::Compile(p, pStack); // completes the definition of the class
} }
else else
{ {
m_bCompileClass = FALSE; m_bCompileClass = false;
CBotFunction::Compile(p, pStack, next); CBotFunction::Compile(p, pStack, next);
if (next->IsExtern()) ListFonctions.Add(next->GivName()/* + next->GivParams()*/); if (next->IsExtern()) ListFonctions.Add(next->GivName()/* + next->GivParams()*/);
next->m_pProg = this; // garde le pointeur au module next->m_pProg = this; // keeps pointers to the module
next = next->Next(); next = next->Next();
} }
} }
// delete m_Prog; // la liste de la 1ère passe // delete m_Prog; // the list of first pass
// m_Prog = temp; // la liste de la seconde passe // m_Prog = temp; // list of the second pass
if ( !pStack->IsOk() ) if ( !pStack->IsOk() )
{ {
@ -160,7 +162,7 @@ BOOL CBotProgram::Compile( const char* program, CBotStringArray& ListFonctions,
} }
BOOL CBotProgram::Start(const char* name) bool CBotProgram::Start(const char* name)
{ {
#if STACKMEM #if STACKMEM
m_pStack->Delete(); m_pStack->Delete();
@ -179,21 +181,21 @@ BOOL CBotProgram::Start(const char* name)
if ( m_pRun == NULL ) if ( m_pRun == NULL )
{ {
m_ErrorCode = TX_NORUN; m_ErrorCode = TX_NORUN;
return FALSE; return false;
} }
#if STACKMEM #if STACKMEM
m_pStack = CBotStack::FirstStack(); m_pStack = CBotStack::FirstStack();
#else #else
m_pStack = new CBotStack(NULL); // crée une pile d'exécution m_pStack = new CBotStack(NULL); // creates an execution stack
#endif #endif
m_pStack->SetBotCall(this); // bases pour les routines m_pStack->SetBotCall(this); // bases for routines
return TRUE; // on est prêt pour un Run() return true; // we are ready for Run ()
} }
BOOL CBotProgram::GetPosition(const char* name, int& start, int& stop, CBotGet modestart, CBotGet modestop) bool CBotProgram::GetPosition(const char* name, int& start, int& stop, CBotGet modestart, CBotGet modestop)
{ {
CBotFunction* p = m_Prog; CBotFunction* p = m_Prog;
while (p != NULL) while (p != NULL)
@ -202,15 +204,15 @@ BOOL CBotProgram::GetPosition(const char* name, int& start, int& stop, CBotGet m
p = p->m_next; p = p->m_next;
} }
if ( p == NULL ) return FALSE; if ( p == NULL ) return false;
p->GetPosition(start, stop, modestart, modestop); p->GetPosition(start, stop, modestart, modestop);
return TRUE; return true;
} }
BOOL CBotProgram::Run(void* pUser, int timer) bool CBotProgram::Run(void* pUser, int timer)
{ {
BOOL ok; bool ok;
if (m_pStack == NULL || m_pRun == NULL) goto error; if (m_pStack == NULL || m_pRun == NULL) goto error;
@ -218,13 +220,13 @@ BOOL CBotProgram::Run(void* pUser, int timer)
if (m_pInstance != NULL && m_pInstance->m_pUserPtr != NULL) if (m_pInstance != NULL && m_pInstance->m_pUserPtr != NULL)
pUser = m_pInstance->m_pUserPtr; pUser = m_pInstance->m_pUserPtr;
m_pStack->Reset(pUser); // vide l'éventuelle erreur précédente, et remet le timer m_pStack->Reset(pUser); // empty the possible previous error, and resets the timer
if ( timer >= 0 ) m_pStack->SetTimer(timer); if ( timer >= 0 ) m_pStack->SetTimer(timer);
m_pStack->SetBotCall(this); // bases pour les routines m_pStack->SetBotCall(this); // bases for routines
#if STACKRUN #if STACKRUN
// reprend l'exécution sur le haut de la pile // resumes execution on the top of the stack
ok = m_pStack->Execute(); ok = m_pStack->Execute();
if ( ok ) if ( ok )
{ {
@ -235,7 +237,7 @@ BOOL CBotProgram::Run(void* pUser, int timer)
ppVar[2] = NULL; ppVar[2] = NULL;
ok = m_pRun->Execute(ppVar, m_pStack, m_pInstance); ok = m_pRun->Execute(ppVar, m_pStack, m_pInstance);
#else #else
// revient sur l'exécution normale // returns to normal execution
ok = m_pRun->Execute(NULL, m_pStack, m_pInstance); ok = m_pRun->Execute(NULL, m_pStack, m_pInstance);
#endif #endif
} }
@ -243,7 +245,7 @@ BOOL CBotProgram::Run(void* pUser, int timer)
ok = m_pRun->Execute(NULL, m_pStack, m_pInstance); ok = m_pRun->Execute(NULL, m_pStack, m_pInstance);
#endif #endif
// terminé sur une erreur ? // completed on a mistake?
if (!ok && !m_pStack->IsOk()) if (!ok && !m_pStack->IsOk())
{ {
m_ErrorCode = m_pStack->GivError(m_ErrorStart, m_ErrorEnd); m_ErrorCode = m_pStack->GivError(m_ErrorStart, m_ErrorEnd);
@ -253,15 +255,15 @@ BOOL CBotProgram::Run(void* pUser, int timer)
delete m_pStack; delete m_pStack;
#endif #endif
m_pStack = NULL; m_pStack = NULL;
return TRUE; // exécution terminée !! return true; // execution is finished!
} }
if ( ok ) m_pRun = NULL; // plus de fonction en exécution if ( ok ) m_pRun = NULL; // more function in execution
return ok; return ok;
error: error:
m_ErrorCode = TX_NORUN; m_ErrorCode = TX_NORUN;
return TRUE; return true;
} }
void CBotProgram::Stop() void CBotProgram::Stop()
@ -277,14 +279,14 @@ void CBotProgram::Stop()
BOOL CBotProgram::GetRunPos(const char* &FunctionName, int &start, int &end) bool CBotProgram::GetRunPos(const char* &FunctionName, int &start, int &end)
{ {
FunctionName = NULL; FunctionName = NULL;
start = end = 0; start = end = 0;
if (m_pStack == NULL) return FALSE; if (m_pStack == NULL) return false;
m_pStack->GetRunPos(FunctionName, start, end); m_pStack->GetRunPos(FunctionName, start, end);
return TRUE; return true;
} }
CBotVar* CBotProgram::GivStackVars(const char* &FunctionName, int level) CBotVar* CBotProgram::GivStackVars(const char* &FunctionName, int level)
@ -295,12 +297,6 @@ CBotVar* CBotProgram::GivStackVars(const char* &FunctionName, int level)
return m_pStack->GivStackVars(FunctionName, level); return m_pStack->GivStackVars(FunctionName, level);
} }
void CBotProgram::SetTimer(int n) void CBotProgram::SetTimer(int n)
{ {
CBotStack::SetTimer( n ); CBotStack::SetTimer( n );
@ -321,7 +317,7 @@ long CBotProgram::GivIdent()
return m_Ident; return m_Ident;
} }
BOOL CBotProgram::GetError(int& code, int& start, int& end) bool CBotProgram::GetError(int& code, int& start, int& end)
{ {
code = m_ErrorCode; code = m_ErrorCode;
start = m_ErrorStart; start = m_ErrorStart;
@ -329,7 +325,7 @@ BOOL CBotProgram::GetError(int& code, int& start, int& end)
return code > 0; return code > 0;
} }
BOOL CBotProgram::GetError(int& code, int& start, int& end, CBotProgram* &pProg) bool CBotProgram::GetError(int& code, int& start, int& end, CBotProgram* &pProg)
{ {
code = m_ErrorCode; code = m_ErrorCode;
start = m_ErrorStart; start = m_ErrorStart;
@ -346,7 +342,7 @@ CBotString CBotProgram::GivErrorText(int code)
if (TextError.IsEmpty()) if (TextError.IsEmpty())
{ {
char buf[100]; char buf[100];
sprintf(buf, "Exception numéro %d.", code); sprintf(buf, "Exception numéro %d.", code);
TextError = buf; TextError = buf;
} }
return TextError; return TextError;
@ -358,34 +354,34 @@ CBotFunction* CBotProgram::GivFunctions()
return m_Prog; return m_Prog;
} }
BOOL CBotProgram::AddFunction(const char* name, bool CBotProgram::AddFunction(const char* name,
BOOL rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser), bool rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser),
CBotTypResult rCompile (CBotVar* &pVar, void* pUser)) CBotTypResult rCompile (CBotVar* &pVar, void* pUser))
{ {
// mémorise les pointeurs aux deux fonctions // stores pointers to the two functions
return CBotCall::AddFunction(name, rExec, rCompile); return CBotCall::AddFunction(name, rExec, rCompile);
} }
BOOL WriteWord(FILE* pf, WORD w) bool WriteWord(FILE* pf, unsigned short w)
{ {
size_t lg; size_t lg;
lg = fwrite(&w, sizeof( WORD ), 1, pf ); lg = fwrite(&w, sizeof( unsigned short ), 1, pf );
return (lg == 1); return (lg == 1);
} }
BOOL ReadWord(FILE* pf, WORD& w) bool ReadWord(FILE* pf, unsigned short& w)
{ {
size_t lg; size_t lg;
lg = fread(&w, sizeof( WORD ), 1, pf ); lg = fread(&w, sizeof( unsigned short ), 1, pf );
return (lg == 1); return (lg == 1);
} }
BOOL WriteFloat(FILE* pf, float w) bool WriteFloat(FILE* pf, float w)
{ {
size_t lg; size_t lg;
@ -394,7 +390,7 @@ BOOL WriteFloat(FILE* pf, float w)
return (lg == 1); return (lg == 1);
} }
BOOL ReadFloat(FILE* pf, float& w) bool ReadFloat(FILE* pf, float& w)
{ {
size_t lg; size_t lg;
@ -403,7 +399,7 @@ BOOL ReadFloat(FILE* pf, float& w)
return (lg == 1); return (lg == 1);
} }
BOOL WriteLong(FILE* pf, long w) bool WriteLong(FILE* pf, long w)
{ {
size_t lg; size_t lg;
@ -412,7 +408,7 @@ BOOL WriteLong(FILE* pf, long w)
return (lg == 1); return (lg == 1);
} }
BOOL ReadLong(FILE* pf, long& w) bool ReadLong(FILE* pf, long& w)
{ {
size_t lg; size_t lg;
@ -421,24 +417,24 @@ BOOL ReadLong(FILE* pf, long& w)
return (lg == 1); return (lg == 1);
} }
BOOL WriteString(FILE* pf, CBotString s) bool WriteString(FILE* pf, CBotString s)
{ {
size_t lg1, lg2; size_t lg1, lg2;
lg1 = s.GivLength(); lg1 = s.GivLength();
if (!WriteWord(pf, lg1)) return FALSE; if (!WriteWord(pf, lg1)) return false;
lg2 = fwrite(s, 1, lg1, pf ); lg2 = fwrite(s, 1, lg1, pf );
return (lg1 == lg2); return (lg1 == lg2);
} }
BOOL ReadString(FILE* pf, CBotString& s) bool ReadString(FILE* pf, CBotString& s)
{ {
WORD w; unsigned short w;
char buf[1000]; char buf[1000];
size_t lg1, lg2; size_t lg1, lg2;
if (!ReadWord(pf, w)) return FALSE; if (!ReadWord(pf, w)) return false;
lg1 = w; lg1 = w;
lg2 = fread(buf, 1, lg1, pf ); lg2 = fread(buf, 1, lg1, pf );
buf[lg2] = 0; buf[lg2] = 0;
@ -447,29 +443,29 @@ BOOL ReadString(FILE* pf, CBotString& s)
return (lg1 == lg2); return (lg1 == lg2);
} }
BOOL WriteType(FILE* pf, CBotTypResult type) bool WriteType(FILE* pf, CBotTypResult type)
{ {
int typ = type.GivType(); int typ = type.GivType();
if ( typ == CBotTypIntrinsic ) typ = CBotTypClass; if ( typ == CBotTypIntrinsic ) typ = CBotTypClass;
if ( !WriteWord(pf, typ) ) return FALSE; if ( !WriteWord(pf, typ) ) return false;
if ( typ == CBotTypClass ) if ( typ == CBotTypClass )
{ {
CBotClass* p = type.GivClass(); CBotClass* p = type.GivClass();
if ( !WriteString(pf, p->GivName()) ) return FALSE; if ( !WriteString(pf, p->GivName()) ) return false;
} }
if ( type.Eq( CBotTypArrayBody ) || if ( type.Eq( CBotTypArrayBody ) ||
type.Eq( CBotTypArrayPointer ) ) type.Eq( CBotTypArrayPointer ) )
{ {
if ( !WriteWord(pf, type.GivLimite()) ) return FALSE; if ( !WriteWord(pf, type.GivLimite()) ) return false;
if ( !WriteType(pf, type.GivTypElem()) ) return FALSE; if ( !WriteType(pf, type.GivTypElem()) ) return false;
} }
return TRUE; return true;
} }
BOOL ReadType(FILE* pf, CBotTypResult& type) bool ReadType(FILE* pf, CBotTypResult& type)
{ {
WORD w, ww; unsigned short w, ww;
if ( !ReadWord(pf, w) ) return FALSE; if ( !ReadWord(pf, w) ) return false;
type.SetType(w); type.SetType(w);
if ( type.Eq( CBotTypIntrinsic ) ) if ( type.Eq( CBotTypIntrinsic ) )
@ -480,7 +476,7 @@ BOOL ReadType(FILE* pf, CBotTypResult& type)
if ( type.Eq( CBotTypClass ) ) if ( type.Eq( CBotTypClass ) )
{ {
CBotString s; CBotString s;
if ( !ReadString(pf, s) ) return FALSE; if ( !ReadString(pf, s) ) return false;
type = CBotTypResult( w, s ); type = CBotTypResult( w, s );
} }
@ -488,54 +484,54 @@ BOOL ReadType(FILE* pf, CBotTypResult& type)
type.Eq( CBotTypArrayBody ) ) type.Eq( CBotTypArrayBody ) )
{ {
CBotTypResult r; CBotTypResult r;
if ( !ReadWord(pf, ww) ) return FALSE; if ( !ReadWord(pf, ww) ) return false;
if ( !ReadType(pf, r) ) return FALSE; if ( !ReadType(pf, r) ) return false;
type = CBotTypResult( w, r ); type = CBotTypResult( w, r );
type.SetLimite((short)ww); type.SetLimite((short)ww);
} }
return TRUE; return true;
} }
BOOL CBotProgram::DefineNum(const char* name, long val) bool CBotProgram::DefineNum(const char* name, long val)
{ {
return CBotToken::DefineNum(name, val); return CBotToken::DefineNum(name, val);
} }
BOOL CBotProgram::SaveState(FILE* pf) bool CBotProgram::SaveState(FILE* pf)
{ {
if (!WriteWord( pf, CBOTVERSION)) return FALSE; if (!WriteWord( pf, CBOTVERSION)) return false;
if ( m_pStack != NULL ) if ( m_pStack != NULL )
{ {
if (!WriteWord( pf, 1)) return FALSE; if (!WriteWord( pf, 1)) return false;
if (!WriteString( pf, m_pRun->GivName() )) return FALSE; if (!WriteString( pf, m_pRun->GivName() )) return false;
if (!m_pStack->SaveState(pf)) return FALSE; if (!m_pStack->SaveState(pf)) return false;
} }
else else
{ {
if (!WriteWord( pf, 0)) return FALSE; if (!WriteWord( pf, 0)) return false;
} }
return TRUE; return true;
} }
BOOL CBotProgram::RestoreState(FILE* pf) bool CBotProgram::RestoreState(FILE* pf)
{ {
WORD w; unsigned short w;
CBotString s; CBotString s;
Stop(); Stop();
if (!ReadWord( pf, w )) return FALSE; if (!ReadWord( pf, w )) return false;
if ( w != CBOTVERSION ) return FALSE; if ( w != CBOTVERSION ) return false;
if (!ReadWord( pf, w )) return FALSE; if (!ReadWord( pf, w )) return false;
if ( w == 0 ) return TRUE; if ( w == 0 ) return true;
if (!ReadString( pf, s )) return FALSE; if (!ReadString( pf, s )) return false;
Start(s); // point de reprise Start(s); // point de reprise
#if STACKMEM #if STACKMEM
@ -545,14 +541,14 @@ BOOL CBotProgram::RestoreState(FILE* pf)
#endif #endif
m_pStack = NULL; m_pStack = NULL;
// récupère la pile depuis l'enregistrement // retrieves the stack from the memory
// utilise un pointeur NULL (m_pStack) mais c'est ok comme ça // uses a NULL pointer (m_pStack) but it's ok like that
if (!m_pStack->RestoreState(pf, m_pStack)) return FALSE; if (!m_pStack->RestoreState(pf, m_pStack)) return false;
m_pStack->SetBotCall(this); // bases pour les routines m_pStack->SetBotCall(this); // bases for routines
// rétabli certains états dans la pile selon la structure // restored some states in the stack according to the structure
m_pRun->RestoreState(NULL, m_pStack, m_pInstance); m_pRun->RestoreState(NULL, m_pStack, m_pInstance);
return TRUE; return true;
} }
int CBotProgram::GivVersion() int CBotProgram::GivVersion()
@ -566,7 +562,7 @@ int CBotProgram::GivVersion()
CBotCall* CBotCall::m_ListCalls = NULL; CBotCall* CBotCall::m_ListCalls = NULL;
CBotCall::CBotCall(const char* name, CBotCall::CBotCall(const char* name,
BOOL rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser), bool rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser),
CBotTypResult rCompile (CBotVar* &pVar, void* pUser)) CBotTypResult rCompile (CBotVar* &pVar, void* pUser))
{ {
m_name = name; m_name = name;
@ -587,8 +583,8 @@ void CBotCall::Free()
delete CBotCall::m_ListCalls; delete CBotCall::m_ListCalls;
} }
BOOL CBotCall::AddFunction(const char* name, bool CBotCall::AddFunction(const char* name,
BOOL rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser), bool rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser),
CBotTypResult rCompile (CBotVar* &pVar, void* pUser)) CBotTypResult rCompile (CBotVar* &pVar, void* pUser))
{ {
CBotCall* p = m_ListCalls; CBotCall* p = m_ListCalls;
@ -598,16 +594,16 @@ BOOL CBotCall::AddFunction(const char* name,
{ {
if ( p->GivName() == name ) if ( p->GivName() == name )
{ {
// libère une fonction qu'on redéfini // frees redefined function
if ( pp ) pp->m_next = p->m_next; if ( pp ) pp->m_next = p->m_next;
else m_ListCalls = p->m_next; else m_ListCalls = p->m_next;
pp = p; pp = p;
p = p->m_next; p = p->m_next;
pp->m_next = NULL; // ne pas détruire la suite de la liste pp->m_next = NULL; // not to destroy the following list
delete pp; delete pp;
continue; continue;
} }
pp = p; // pointeur précédent pp = p; // previous pointer
p = p->m_next; p = p->m_next;
} }
@ -616,18 +612,18 @@ BOOL CBotCall::AddFunction(const char* name,
if (p) p->m_next = pp; if (p) p->m_next = pp;
else m_ListCalls = pp; else m_ListCalls = pp;
return TRUE; return true;
} }
// transforme le tableau de pointeurs aux variables // transforms the array of pointers to variables
// en une liste de variables chaînées // in a chained list of variables
CBotVar* MakeListVars(CBotVar** ppVars, BOOL bSetVal=FALSE) CBotVar* MakeListVars(CBotVar** ppVars, bool bSetVal=false)
{ {
int i = 0; int i = 0;
CBotVar* pVar = NULL; CBotVar* pVar = NULL;
while( TRUE ) while( true )
{ {
ppVars[i]; ppVars[i];
if ( ppVars[i] == NULL ) break; if ( ppVars[i] == NULL ) break;
@ -637,7 +633,7 @@ CBotVar* MakeListVars(CBotVar** ppVars, BOOL bSetVal=FALSE)
else else
if ( ppVars[i]->GivType() == CBotTypPointer ) if ( ppVars[i]->GivType() == CBotTypPointer )
pp->SetClass( ppVars[i]->GivClass()); pp->SetClass( ppVars[i]->GivClass());
// copier le pointeur selon indirection // copy the pointer according to indirections
if (pVar == NULL) pVar = pp; if (pVar == NULL) pVar = pp;
else pVar->AddNext(pp); else pVar->AddNext(pp);
i++; i++;
@ -645,8 +641,8 @@ CBotVar* MakeListVars(CBotVar** ppVars, BOOL bSetVal=FALSE)
return pVar; return pVar;
} }
// trouve un appel acceptable selon le nom de la procédure // is acceptable by a call procedure name
// et les paramètres donnés // and given parameters
CBotTypResult CBotCall::CompileCall(CBotToken* &p, CBotVar** ppVar, CBotCStack* pStack, long& nIdent) CBotTypResult CBotCall::CompileCall(CBotToken* &p, CBotVar** ppVar, CBotCStack* pStack, long& nIdent)
{ {
@ -663,7 +659,7 @@ CBotTypResult CBotCall::CompileCall(CBotToken* &p, CBotVar** ppVar, CBotCStack*
CBotTypResult r = pt->m_rComp(pVar2, m_pUser); CBotTypResult r = pt->m_rComp(pVar2, m_pUser);
int ret = r.GivType(); int ret = r.GivType();
// si une classe est retournée, c'est en fait un pointeur // if a class is returned, it is actually a pointer
if ( ret == CBotTypClass ) r.SetType( ret = CBotTypPointer ); if ( ret == CBotTypClass ) r.SetType( ret = CBotTypPointer );
if ( ret > 20 ) if ( ret > 20 )
@ -686,16 +682,16 @@ void CBotCall::SetPUser(void* pUser)
m_pUser = pUser; m_pUser = pUser;
} }
int CBotCall::CheckCall(const char* name) bool CBotCall::CheckCall(const char* name)
{ {
CBotCall* p = m_ListCalls; CBotCall* p = m_ListCalls;
while ( p != NULL ) while ( p != NULL )
{ {
if ( name == p->GivName() ) return TRUE; if ( name == p->GivName() ) return true;
p = p->m_next; p = p->m_next;
} }
return FALSE; return false;
} }
@ -744,29 +740,29 @@ int CBotCall::DoCall(long& nIdent, CBotToken* token, CBotVar** ppVar, CBotStack*
fund: fund:
#if !STACKRUN #if !STACKRUN
// fait la liste des paramètres selon le contenu de la pile (pStackVar) // lists the parameters depending on the contents of the stack (pStackVar)
CBotVar* pVar = MakeListVars(ppVar, TRUE); CBotVar* pVar = MakeListVars(ppVar, true);
CBotVar* pVarToDelete = pVar; CBotVar* pVarToDelete = pVar;
// crée une variable pour le résultat // creates a variable to the result
CBotVar* pResult = rettype.Eq(0) ? NULL : CBotVar::Create("", rettype); CBotVar* pResult = rettype.Eq(0) ? NULL : CBotVar::Create("", rettype);
CBotVar* pRes = pResult; CBotVar* pRes = pResult;
int Exception = 0; int Exception = 0;
int res = pt->m_rExec(pVar, pResult, Exception, pStack->GivPUser()); int res = pt->m_rExec(pVar, pResult, Exception, pStack->GivPUser());
if ( pResult != pRes ) delete pRes; // si résultat différent rendu if ( pResult != pRes ) delete pRes; // different result if made
delete pVarToDelete; delete pVarToDelete;
if (res == FALSE) if (res == false)
{ {
if (Exception!=0) if (Exception!=0)
{ {
pStack->SetError(Exception, token); pStack->SetError(Exception, token);
} }
delete pResult; delete pResult;
return FALSE; return false;
} }
pStack->SetVar(pResult); pStack->SetVar(pResult);
@ -775,19 +771,19 @@ fund:
pStack->SetError(TX_NORETVAL, token); pStack->SetError(TX_NORETVAL, token);
} }
nIdent = pt->m_nFuncIdent; nIdent = pt->m_nFuncIdent;
return TRUE; return true;
#else #else
CBotStack* pile = pStack->AddStackEOX(pt); CBotStack* pile = pStack->AddStackEOX(pt);
if ( pile == EOX ) return TRUE; if ( pile == EOX ) return true;
// fait la liste des paramètres selon le contenu de la pile (pStackVar) // lists the parameters depending on the contents of the stack (pStackVar)
CBotVar* pVar = MakeListVars(ppVar, TRUE); CBotVar* pVar = MakeListVars(ppVar, true);
CBotVar* pVarToDelete = pVar; CBotVar* pVarToDelete = pVar;
// crée une variable pour le résultat // creates a variable to the result
CBotVar* pResult = rettype.Eq(0) ? NULL : CBotVar::Create("", rettype); CBotVar* pResult = rettype.Eq(0) ? NULL : CBotVar::Create("", rettype);
pile->SetVar( pVar ); pile->SetVar( pVar );
@ -795,7 +791,7 @@ fund:
CBotStack* pile2 = pile->AddStack(); CBotStack* pile2 = pile->AddStack();
pile2->SetVar( pResult ); pile2->SetVar( pResult );
pile->SetError(0, token); // pour la position en cas d'erreur + loin pile->SetError(0, token); // for the position on error + away
return pt->Run( pStack ); return pt->Run( pStack );
#endif #endif
@ -804,7 +800,7 @@ fund:
#if STACKRUN #if STACKRUN
BOOL CBotCall::RestoreCall(long& nIdent, CBotToken* token, CBotVar** ppVar, CBotStack* pStack) bool CBotCall::RestoreCall(long& nIdent, CBotToken* token, CBotVar** ppVar, CBotStack* pStack)
{ {
CBotCall* pt = m_ListCalls; CBotCall* pt = m_ListCalls;
@ -817,22 +813,22 @@ BOOL CBotCall::RestoreCall(long& nIdent, CBotToken* token, CBotVar** ppVar, CBot
nIdent = pt->m_nFuncIdent; nIdent = pt->m_nFuncIdent;
CBotStack* pile = pStack->RestoreStackEOX(pt); CBotStack* pile = pStack->RestoreStackEOX(pt);
if ( pile == NULL ) return TRUE; if ( pile == NULL ) return true;
CBotStack* pile2 = pile->RestoreStack(); CBotStack* pile2 = pile->RestoreStack();
return TRUE; return true;
} }
pt = pt->m_next; pt = pt->m_next;
} }
} }
return FALSE; return false;
} }
BOOL CBotCall::Run(CBotStack* pStack) bool CBotCall::Run(CBotStack* pStack)
{ {
CBotStack* pile = pStack->AddStackEOX(this); CBotStack* pile = pStack->AddStackEOX(this);
if ( pile == EOX ) return TRUE; if ( pile == EOX ) return true;
CBotVar* pVar = pile->GivVar(); CBotVar* pVar = pile->GivVar();
CBotStack* pile2 = pile->AddStack(); CBotStack* pile2 = pile->AddStack();
@ -842,20 +838,20 @@ BOOL CBotCall::Run(CBotStack* pStack)
int Exception = 0; int Exception = 0;
int res = m_rExec(pVar, pResult, Exception, pStack->GivPUser()); int res = m_rExec(pVar, pResult, Exception, pStack->GivPUser());
if (res == FALSE) if (res == false)
{ {
if (Exception!=0) if (Exception!=0)
{ {
pStack->SetError(Exception); pStack->SetError(Exception);
} }
if ( pResult != pRes ) delete pResult; // si résultat différent rendu if ( pResult != pRes ) delete pResult; // different result if made
return FALSE; return false;
} }
if ( pResult != NULL ) pStack->SetCopyVar( pResult ); if ( pResult != NULL ) pStack->SetCopyVar( pResult );
if ( pResult != pRes ) delete pResult; // si résultat différent rendu if ( pResult != pRes ) delete pResult; // different result if made
return TRUE; return true;
} }
#endif #endif
@ -863,7 +859,7 @@ BOOL CBotCall::Run(CBotStack* pStack)
/////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////
CBotCallMethode::CBotCallMethode(const char* name, CBotCallMethode::CBotCallMethode(const char* name,
BOOL rExec (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception), bool rExec (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception),
CBotTypResult rCompile (CBotVar* pThis, CBotVar* &pVar)) CBotTypResult rCompile (CBotVar* pThis, CBotVar* &pVar))
{ {
m_name = name; m_name = name;
@ -879,8 +875,8 @@ CBotCallMethode::~CBotCallMethode()
m_next = NULL; m_next = NULL;
} }
// trouve un appel acceptable selon le nom de la procédure // is acceptable by a call procedure name
// et les paramètres donnés // and given parameters
CBotTypResult CBotCallMethode::CompileCall(const char* name, CBotVar* pThis, CBotTypResult CBotCallMethode::CompileCall(const char* name, CBotVar* pThis,
CBotVar** ppVar, CBotCStack* pStack, CBotVar** ppVar, CBotCStack* pStack,
@ -893,7 +889,7 @@ CBotTypResult CBotCallMethode::CompileCall(const char* name, CBotVar* pThis,
{ {
if ( pt->m_name == name ) if ( pt->m_name == name )
{ {
CBotVar* pVar = MakeListVars(ppVar, TRUE); CBotVar* pVar = MakeListVars(ppVar, true);
CBotVar* pVar2 = pVar; CBotVar* pVar2 = pVar;
CBotTypResult r = pt->m_rComp(pThis, pVar2); CBotTypResult r = pt->m_rComp(pThis, pVar2);
int ret = r.GivType(); int ret = r.GivType();
@ -934,24 +930,24 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
{ {
CBotCallMethode* pt = this; CBotCallMethode* pt = this;
// recherche selon l'identificateur // search by the identifier
if ( nIdent ) while ( pt != NULL ) if ( nIdent ) while ( pt != NULL )
{ {
if ( pt->m_nFuncIdent == nIdent ) if ( pt->m_nFuncIdent == nIdent )
{ {
// fait la liste des paramètres selon le contenu de la pile (pStackVar) // lists the parameters depending on the contents of the stack (pStackVar)
CBotVar* pVar = MakeListVars(ppVars, TRUE); CBotVar* pVar = MakeListVars(ppVars, true);
CBotVar* pVarToDelete = pVar; CBotVar* pVarToDelete = pVar;
// puis appelle la routine externe au module // then calls the routine external to the module
int Exception = 0; int Exception = 0;
int res = pt->m_rExec(pThis, pVar, pResult, Exception); int res = pt->m_rExec(pThis, pVar, pResult, Exception);
pStack->SetVar(pResult); pStack->SetVar(pResult);
if (res == FALSE) if (res == false)
{ {
if (Exception!=0) if (Exception!=0)
{ {
@ -959,30 +955,30 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
pStack->SetError(Exception, pToken); pStack->SetError(Exception, pToken);
} }
delete pVarToDelete; delete pVarToDelete;
return FALSE; return false;
} }
delete pVarToDelete; delete pVarToDelete;
return TRUE; return true;
} }
pt = pt->m_next; pt = pt->m_next;
} }
// recherche selon le nom // search by name
while ( pt != NULL ) while ( pt != NULL )
{ {
if ( pt->m_name == name ) if ( pt->m_name == name )
{ {
// fait la liste des paramètres selon le contenu de la pile (pStackVar) // lists the parameters depending on the contents of the stack (pStackVar)
CBotVar* pVar = MakeListVars(ppVars, TRUE); CBotVar* pVar = MakeListVars(ppVars, true);
CBotVar* pVarToDelete = pVar; CBotVar* pVarToDelete = pVar;
int Exception = 0; int Exception = 0;
int res = pt->m_rExec(pThis, pVar, pResult, Exception); int res = pt->m_rExec(pThis, pVar, pResult, Exception);
pStack->SetVar(pResult); pStack->SetVar(pResult);
if (res == FALSE) if (res == false)
{ {
if (Exception!=0) if (Exception!=0)
{ {
@ -990,11 +986,11 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
pStack->SetError(Exception, pToken); pStack->SetError(Exception, pToken);
} }
delete pVarToDelete; delete pVarToDelete;
return FALSE; return false;
} }
delete pVarToDelete; delete pVarToDelete;
nIdent = pt->m_nFuncIdent; nIdent = pt->m_nFuncIdent;
return TRUE; return true;
} }
pt = pt->m_next; pt = pt->m_next;
} }
@ -1002,7 +998,7 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
return -1; return -1;
} }
BOOL rSizeOf( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rSizeOf( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
if ( pVar == NULL ) return TX_LOWPARAM; if ( pVar == NULL ) return TX_LOWPARAM;
@ -1016,7 +1012,7 @@ BOOL rSizeOf( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
} }
pResult->SetValInt(i); pResult->SetValInt(i);
return TRUE; return true;
} }
CBotTypResult cSizeOf( CBotVar* &pVar, void* pUser ) CBotTypResult cSizeOf( CBotVar* &pVar, void* pUser )
@ -1030,19 +1026,19 @@ CBotTypResult cSizeOf( CBotVar* &pVar, void* pUser )
CBotString CBotProgram::m_DebugVarStr = ""; CBotString CBotProgram::m_DebugVarStr = "";
BOOL rCBotDebug( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rCBotDebug( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
pResult->SetValString( CBotProgram::m_DebugVarStr ); pResult->SetValString( CBotProgram::m_DebugVarStr );
return TRUE; return true;
} }
CBotTypResult cCBotDebug( CBotVar* &pVar, void* pUser ) CBotTypResult cCBotDebug( CBotVar* &pVar, void* pUser )
{ {
// pas de paramètre // no parameter
if ( pVar != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar != NULL ) return CBotTypResult( TX_OVERPARAM );
// la fonction retourne un résultat "string" // function returns a result "string"
return CBotTypResult( CBotTypString ); return CBotTypResult( CBotTypString );
} }
@ -1051,59 +1047,60 @@ CBotTypResult cCBotDebug( CBotVar* &pVar, void* pUser )
void CBotProgram::Init() void CBotProgram::Init()
{ {
CBotToken::DefineNum( "CBotErrOpenPar", 5000) ; // manque la parenthèse ouvrante CBotToken::DefineNum( "CBotErrOpenPar", 5000) ; // missing the opening parenthesis
CBotToken::DefineNum( "CBotErrClosePar", 5001) ; // manque la parenthèse fermante CBotToken::DefineNum( "CBotErrClosePar", 5001) ; // missing the closing parenthesis
CBotToken::DefineNum( "CBotErrNotBoolean", 5002) ; // l'expression doit être un boolean CBotToken::DefineNum( "CBotErrNotBoolean", 5002) ; // expression must be a boolean
CBotToken::DefineNum( "CBotErrUndefVar", 5003) ; // variable non déclarée CBotToken::DefineNum( "CBotErrUndefVar", 5003) ; // undeclared variable
CBotToken::DefineNum( "CBotErrBadLeft", 5004) ; // assignation impossible ( 5 = ... ) CBotToken::DefineNum( "CBotErrBadLeft", 5004) ; // impossible assignment (5 = ...)
CBotToken::DefineNum( "CBotErrNoTerminator", 5005) ;// point-virgule attendu CBotToken::DefineNum( "CBotErrNoTerminator", 5005) ;// semicolon expected
CBotToken::DefineNum( "CBotErrCaseOut", 5006) ; // case en dehors d'un switch CBotToken::DefineNum( "CBotErrCaseOut", 5006) ; // case outside a switch
CBotToken::DefineNum( "CBotErrCloseBlock", 5008) ; // manque " } " CBotToken::DefineNum( "CBotErrCloseBlock", 5008) ; // missing " } "
CBotToken::DefineNum( "CBotErrElseWhitoutIf", 5009) ;// else sans if correspondant CBotToken::DefineNum( "CBotErrElseWhitoutIf", 5009) ;// else without matching if
CBotToken::DefineNum( "CBotErrOpenBlock", 5010) ; // manque " { " CBotToken::DefineNum( "CBotErrOpenBlock", 5010) ; // missing " { "
CBotToken::DefineNum( "CBotErrBadType1", 5011) ; // mauvais type pour l'assignation CBotToken::DefineNum( "CBotErrBadType1", 5011) ; // wrong type for the assignment
CBotToken::DefineNum( "CBotErrRedefVar", 5012) ; // redéfinition de la variable CBotToken::DefineNum( "CBotErrRedefVar", 5012) ; // redefinition of the variable
CBotToken::DefineNum( "CBotErrBadType2", 5013) ; // 2 opérandes de type incompatibles CBotToken::DefineNum( "CBotErrBadType2", 5013) ; // two operands are incompatible
CBotToken::DefineNum( "CBotErrUndefCall", 5014) ; // routine inconnue CBotToken::DefineNum( "CBotErrUndefCall", 5014) ; // routine unknown
CBotToken::DefineNum( "CBotErrNoDoubleDots", 5015) ;// " : " attendu CBotToken::DefineNum( "CBotErrNoDoubleDots", 5015) ;// " : " expected
CBotToken::DefineNum( "CBotErrBreakOutside", 5017) ;// break en dehors d'une boucle CBotToken::DefineNum( "CBotErrBreakOutside", 5017) ;// break outside of a loop
CBotToken::DefineNum( "CBotErrUndefLabel", 5019) ; // label inconnu CBotToken::DefineNum( "CBotErrUndefLabel", 5019) ; // unknown label
CBotToken::DefineNum( "CBotErrLabel", 5018) ; // label ne peut se mettre ici CBotToken::DefineNum( "CBotErrLabel", 5018) ; // label can not get here
CBotToken::DefineNum( "CBotErrNoCase", 5020) ; // manque " case " CBotToken::DefineNum( "CBotErrNoCase", 5020) ; // missing " case "
CBotToken::DefineNum( "CBotErrBadNum", 5021) ; // nombre attendu CBotToken::DefineNum( "CBotErrBadNum", 5021) ; // expected number
CBotToken::DefineNum( "CBotErrVoid", 5022) ; // " void " pas possible ici CBotToken::DefineNum( "CBotErrVoid", 5022) ; // " void " not possble here
CBotToken::DefineNum( "CBotErrNoType", 5023) ; // déclaration de type attendue CBotToken::DefineNum( "CBotErrNoType", 5023) ; // type declaration expected
CBotToken::DefineNum( "CBotErrNoVar", 5024) ; // nom de variable attendu CBotToken::DefineNum( "CBotErrNoVar", 5024) ; // variable name expected
CBotToken::DefineNum( "CBotErrNoFunc", 5025) ; // nom de fonction attendu CBotToken::DefineNum( "CBotErrNoFunc", 5025) ; // expected function name
CBotToken::DefineNum( "CBotErrOverParam", 5026) ; // trop de paramètres CBotToken::DefineNum( "CBotErrOverParam", 5026) ; // too many parameters
CBotToken::DefineNum( "CBotErrRedefFunc", 5027) ; // cette fonction existe déjà CBotToken::DefineNum( "CBotErrRedefFunc", 5027) ; // this function already exists
CBotToken::DefineNum( "CBotErrLowParam", 5028) ; // pas assez de paramètres CBotToken::DefineNum( "CBotErrLowParam", 5028) ; // not enough parameters
CBotToken::DefineNum( "CBotErrBadParam", 5029) ; // mauvais types de paramètres CBotToken::DefineNum( "CBotErrBadParam", 5029) ; // mauvais types de paramètres
CBotToken::DefineNum( "CBotErrNbParam", 5030) ; // mauvais nombre de paramètres CBotToken::DefineNum( "CBotErrNbParam", 5030) ; // wrong number of parameters
CBotToken::DefineNum( "CBotErrUndefItem", 5031) ; // élément n'existe pas dans la classe CBotToken::DefineNum( "CBotErrUndefItem", 5031) ; // element does not exist in the class
CBotToken::DefineNum( "CBotErrUndefClass", 5032) ; // variable n'est pas une classe CBotToken::DefineNum( "CBotErrUndefClass", 5032) ; // variable is not a class
CBotToken::DefineNum( "CBotErrNoConstruct", 5033) ; // pas de constructeur approprié CBotToken::DefineNum( "CBotErrNoConstruct", 5033) ; // no appropriate constructor
CBotToken::DefineNum( "CBotErrRedefClass", 5034) ; // classe existe déjà CBotToken::DefineNum( "CBotErrRedefClass", 5034) ; // Class already exists
CBotToken::DefineNum( "CBotErrCloseIndex", 5035) ; // " ] " attendu CBotToken::DefineNum( "CBotErrCloseIndex", 5035) ; // " ] " expected
CBotToken::DefineNum( "CBotErrReserved", 5036) ; // mot réservé (par un DefineNum) CBotToken::DefineNum( "CBotErrReserved", 5036) ; // reserved word (for a DefineNum)
// voici la liste des erreurs pouvant être retournées par le module // Here are the list of errors that can be returned by the module
// pour l'exécution // for the execution
CBotToken::DefineNum( "CBotErrZeroDiv", 6000) ; // division par zéro CBotToken::DefineNum( "CBotErrZeroDiv", 6000) ; // division by zero
CBotToken::DefineNum( "CBotErrNotInit", 6001) ; // variable non initialisée CBotToken::DefineNum( "CBotErrNotInit", 6001) ; // uninitialized variable
CBotToken::DefineNum( "CBotErrBadThrow", 6002) ; // throw d'une valeur négative CBotToken::DefineNum( "CBotErrBadThrow", 6002) ; // throw a negative value
CBotToken::DefineNum( "CBotErrNoRetVal", 6003) ; // fonction n'a pas retourné de résultat CBotToken::DefineNum( "CBotErrNoRetVal", 6003) ; // function did not return results
CBotToken::DefineNum( "CBotErrNoRun", 6004) ; // Run() sans fonction active CBotToken::DefineNum( "CBotErrNoRun", 6004) ; // active Run () without a function
CBotToken::DefineNum( "CBotErrUndefFunc", 6005) ; // appel d'une fonction qui n'existe plus CBotToken::DefineNum( "CBotErrUndefFunc", 6005) ; // Calling a function that no longer exists
CBotProgram::AddFunction("sizeof", rSizeOf, cSizeOf ); CBotProgram::AddFunction("sizeof", rSizeOf, cSizeOf );
InitStringFunctions(); InitStringFunctions();
// une fonction juste pour les debug divers // just a function for various debug
CBotProgram::AddFunction("CBOTDEBUGDD", rCBotDebug, cCBotDebug); CBotProgram::AddFunction("CBOTDEBUGDD", rCBotDebug, cCBotDebug);
DeleteFile("CbotDebug.txt"); //TODO implement this deletion
// DeleteFile("CbotDebug.txt");
} }

File diff suppressed because it is too large Load Diff

View File

@ -12,39 +12,134 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.///////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// gestion de chaine /////////////////////////////////////////////////////
// basé sur le CString de MFC
// mais moins complet //strings management
#include "CBot.h" #include "CBot.h"
#include <string.h> #include <cstdlib>
#include <cstring>
HINSTANCE CBotString::m_hInstance = (HINSTANCE)LoadLibrary("libCbot.dll"); // comment le récupérer autrement ?? #include <algorithm>
//Map is filled with id-string pars that are needed for CBot language parsing
const std::map<EID, char *> CBotString::s_keywordString =
{
{ID_IF, "if"},
{ID_ELSE, "else"},
{ID_WHILE, "while"},
{ID_DO, "do"},
{ID_FOR, "for"},
{ID_BREAK, "break"},
{ID_CONTINUE, "continue"},
{ID_SWITCH, "switch"},
{ID_CASE, "case"},
{ID_DEFAULT, "default"},
{ID_TRY, "try"},
{ID_THROW, "throw"},
{ID_CATCH, "catch"},
{ID_FINALLY, "finally"},
{ID_TXT_AND, "and"},
{ID_TXT_OR, "or"},
{ID_TXT_NOT, "not"},
{ID_RETURN, "return"},
{ID_CLASS, "class"},
{ID_EXTENDS, "extends"},
{ID_SYNCHO, "synchronized"},
{ID_NEW, "new"},
{ID_PUBLIC, "public"},
{ID_EXTERN, "extern"},
{ID_FINAL, "final"},
{ID_STATIC, "static"},
{ID_PROTECTED, "protected"},
{ID_PRIVATE, "private"},
{ID_REPEAT, "repeat"},
{ID_DEBUGDD, "STARTDEBUGDD"},
{ID_INT, "int"},
{ID_FLOAT, "float"},
{ID_BOOLEAN, "boolean"},
{ID_STRING, "string"},
{ID_VOID, "void"},
{ID_BOOL, "bool"},
{ID_TRUE, "true"},
{ID_FALSE, "false"},
{ID_NULL, "null"},
{ID_NAN, "nan"},
{ID_OPENPAR, "("},
{ID_CLOSEPAR, ")"},
{ID_OPBLK, "{"},
{ID_CLBLK, "}"},
{ID_SEP, "},"},
{ID_COMMA, ","},
{ID_DOTS, ":"},
{ID_DOT, "."},
{ID_OPBRK, "["},
{ID_CLBRK, "]"},
{ID_DBLDOTS, "::"},
{ID_LOGIC, "?"},
{ID_ADD, "+"},
{ID_SUB, "-"},
{ID_MUL, "*"},
{ID_DIV, "/"},
{ID_ASS, "="},
{ID_ASSADD, "+="},
{ID_ASSSUB, "-="},
{ID_ASSMUL, "*="},
{ID_ASSDIV, "/="},
{ID_ASSOR, "|="},
{ID_ASSAND, "&="},
{ID_ASSXOR, "^="},
{ID_ASSSL, "<<="},
{ID_ASSSR, ">>>="},
{ID_ASSASR, ">>="},
{ID_SL, "<<"},
{ID_SR, ">>"},
{ID_ASR, ">>"},
{ID_INC, "++"},
{ID_DEC, "--"},
{ID_LO, "<"},
{ID_HI, ">"},
{ID_LS, "<<"},
{ID_HS, ">="},
{ID_EQ, "=="},
{ID_NE, "!="},
{ID_AND, "&"},
{ID_XOR, "^"},
{ID_OR, "|"},
{ID_LOG_AND, "&&"},
{ID_LOG_OR, "||"},
{ID_LOG_NOT, "!"},
{ID_NOT, "~"},
{ID_MODULO, "%"},
{ID_POWER, "**"},
{ID_ASSMODULO, "%="},
{ID_SUPER, "super"},
{TX_UNDEF, "undefined"},
{TX_NAN, "not a number"}
};
CBotString::CBotString() CBotString::CBotString()
{ {
m_ptr = NULL; // chaine vide m_ptr = NULL;
m_lg = 0; m_lg = 0;
} }
CBotString::~CBotString() CBotString::~CBotString()
{ {
if (m_ptr != NULL) free(m_ptr); free(m_ptr); //we can call free on null pointer as it's save
} }
CBotString::CBotString(const char* p) CBotString::CBotString(const char* p)
{ {
m_lg = lstrlen( p ); m_lg = strlen(p);
m_ptr = NULL; m_ptr = NULL;
if (m_lg>0) if (m_lg>0)
{ {
m_ptr = (char*)malloc(m_lg+1); m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, p); strcpy(m_ptr, p);
} }
} }
@ -56,7 +151,7 @@ CBotString::CBotString(const CBotString& srcString)
if (m_lg>0) if (m_lg>0)
{ {
m_ptr = (char*)malloc(m_lg+1); m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, srcString.m_ptr); strcpy(m_ptr, srcString.m_ptr);
} }
} }
@ -66,91 +161,87 @@ CBotString::CBotString(const CBotString& srcString)
int CBotString::GivLength() int CBotString::GivLength()
{ {
if (m_ptr == NULL) return 0; if (m_ptr == NULL) return 0;
return lstrlen( m_ptr ); return strlen( m_ptr );
} }
CBotString CBotString::Left(int nCount) const CBotString CBotString::Left(int nCount) const
{ {
char chaine[2000]; char chain[2000];
int i; size_t i;
for (i = 0; i < m_lg && i < nCount && i < 1999; i++) for (i = 0; i < m_lg && i < nCount && i < 1999; ++i)
{ {
chaine[i] = m_ptr[i]; chain[i] = m_ptr[i];
} }
chaine[i] = 0 ; chain[i] = 0 ;
return CBotString( chaine ); return CBotString(chain);
} }
CBotString CBotString::Right(int nCount) const CBotString CBotString::Right(int nCount) const
{ {
char chaine[2000]; char chain[2000];
int i = m_lg - nCount; int i = m_lg - nCount;
if ( i < 0 ) i = 0; if ( i < 0 ) i = 0;
int j; size_t j;
for ( j = 0 ; i < m_lg && i < 1999; i++) for (size_t j = 0 ; i < m_lg && i < 1999; ++i)
{ {
chaine[j++] = m_ptr[i]; chain[j++] = m_ptr[i];
} }
chaine[j] = 0 ; chain[j] = 0 ;
return CBotString( chaine ); return CBotString(chain);
} }
CBotString CBotString::Mid(int nFirst, int nCount) const CBotString CBotString::Mid(int nFirst, int nCount) const
{ {
char chaine[2000]; char chain[2000];
int i; size_t i;
for (i = nFirst; i < m_lg && i < 1999 && i <= nFirst + nCount; ++i)
for ( i = nFirst; i < m_lg && i < 1999 && i <= nFirst + nCount; i++)
{ {
chaine[i] = m_ptr[i]; chain[i] = m_ptr[i];
} }
chaine[i] = 0 ; chain[i] = 0 ;
return CBotString( chaine ); return CBotString(chain);
} }
CBotString CBotString::Mid(int nFirst) const CBotString CBotString::Mid(int nFirst) const
{ {
char chaine[2000]; char chain[2000];
int i; size_t i;
for (i = nFirst; i < m_lg && i < 1999 ; ++i)
for ( i = nFirst; i < m_lg && i < 1999 ; i++)
{ {
chaine[i] = m_ptr[i]; chain[i] = m_ptr[i];
} }
chaine[i] = 0 ; chain[i] = 0 ;
return CBotString( chaine ); return CBotString(chain);
} }
int CBotString::Find(const char c) int CBotString::Find(const char c)
{ {
int i; for (size_t i = 0; i < m_lg; ++i)
for (i = 0; i < m_lg; i++)
{ {
if (m_ptr[i] == c) return i; if (m_ptr[i] == c) return i;
} }
return -1; return -1;
} }
int CBotString::Find(LPCTSTR lpsz) int CBotString::Find(const char * lpsz)
{ {
int i, j; int l = strlen(lpsz);
int l = lstrlen(lpsz);
for (i = 0; i <= m_lg-l; i++) for (size_t i = 0; i <= m_lg-l; ++i)
{ {
for (j = 0; j < l; j++) for (size_t j = 0; j < l; ++j)
{ {
if (m_ptr[i+j] != lpsz[j]) goto bad; if (m_ptr[i+j] != lpsz[j]) goto bad;
} }
@ -163,21 +254,21 @@ bad:;
int CBotString::ReverseFind(const char c) int CBotString::ReverseFind(const char c)
{ {
int i; int i;
for (i = m_lg-1; i >= 0; i--) for (i = m_lg-1; i >= 0; --i)
{ {
if (m_ptr[i] == c) return i; if (m_ptr[i] == c) return i;
} }
return -1; return -1;
} }
int CBotString::ReverseFind(LPCTSTR lpsz) int CBotString::ReverseFind(const char * lpsz)
{ {
int i, j; int i, j;
int l = lstrlen(lpsz); int l = strlen(lpsz);
for (i = m_lg-l; i >= 0; i--) for (i = m_lg-l; i >= 0; --i)
{ {
for (j = 0; j < l; j++) for (j = 0; j < l; ++j)
{ {
if (m_ptr[i+j] != lpsz[j]) goto bad; if (m_ptr[i+j] != lpsz[j]) goto bad;
} }
@ -195,7 +286,7 @@ CBotString CBotString::Mid(int start, int lg)
if ( lg < 0 ) lg = m_lg - start; if ( lg < 0 ) lg = m_lg - start;
char* p = (char*)malloc(m_lg+1); char* p = (char*)malloc(m_lg+1);
lstrcpy(p, m_ptr+start); strcpy(p, m_ptr+start);
p[lg] = 0; p[lg] = 0;
res = p; res = p;
@ -205,9 +296,7 @@ CBotString CBotString::Mid(int start, int lg)
void CBotString::MakeUpper() void CBotString::MakeUpper()
{ {
int i; for (size_t i = 0; i < m_lg && i < 1999 ; ++i)
for ( i = 0; i < m_lg && i < 1999 ; i++)
{ {
char c = m_ptr[i]; char c = m_ptr[i];
if ( c >= 'a' && c <= 'z' ) m_ptr[i] = c - 'a' + 'A'; if ( c >= 'a' && c <= 'z' ) m_ptr[i] = c - 'a' + 'A';
@ -216,55 +305,48 @@ void CBotString::MakeUpper()
void CBotString::MakeLower() void CBotString::MakeLower()
{ {
int i; for (size_t i = 0; i < m_lg && i < 1999 ; ++i)
for ( i = 0; i < m_lg && i < 1999 ; i++)
{ {
char c = m_ptr[i]; char c = m_ptr[i];
if ( c >= 'A' && c <= 'Z' ) m_ptr[i] = c - 'A' + 'a'; if ( c >= 'A' && c <= 'Z' ) m_ptr[i] = c - 'A' + 'a';
} }
} }
bool CBotString::LoadString(unsigned int id)
#define MAXSTRING 256
BOOL CBotString::LoadString(UINT id)
{ {
char buffer[MAXSTRING]; const char * str = NULL;
str = MapIdToString((EID)id);
m_lg = ::LoadString( m_hInstance, id, buffer, MAXSTRING );
if (m_ptr != NULL) free(m_ptr); if (m_ptr != NULL) free(m_ptr);
m_lg = strlen(str);
m_ptr = NULL; m_ptr = NULL;
if (m_lg > 0) if (m_lg > 0)
{ {
m_ptr = (char*)malloc(m_lg+1); m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, buffer); strcpy(m_ptr, str);
return TRUE; return true;
} }
return FALSE; return false;
} }
const CBotString& CBotString::operator=(const CBotString& stringSrc) const CBotString& CBotString::operator=(const CBotString& stringSrc)
{ {
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_ptr = NULL;
m_lg = stringSrc.m_lg; m_lg = stringSrc.m_lg;
m_ptr = NULL;
if (m_lg > 0) if (m_lg > 0)
{ {
m_ptr = (char*)malloc(m_lg+1); m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, stringSrc.m_ptr); strcpy(m_ptr, stringSrc.m_ptr);
} }
return *this; return *this;
} }
CBotString operator+(const CBotString& string, LPCTSTR lpsz) CBotString operator+(const CBotString& string, const char * lpsz)
{ {
CBotString s(string); CBotString s(string);
s += lpsz; s += lpsz;
@ -275,11 +357,11 @@ const CBotString& CBotString::operator+(const CBotString& stringSrc)
{ {
char* p = (char*)malloc(m_lg+stringSrc.m_lg+1); char* p = (char*)malloc(m_lg+stringSrc.m_lg+1);
lstrcpy(p, m_ptr); strcpy(p, m_ptr);
char* pp = p + m_lg; char* pp = p + m_lg;
lstrcpy(pp, stringSrc.m_ptr); strcpy(pp, stringSrc.m_ptr);
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_ptr = p; m_ptr = p;
m_lg += stringSrc.m_lg; m_lg += stringSrc.m_lg;
@ -288,7 +370,7 @@ const CBotString& CBotString::operator+(const CBotString& stringSrc)
const CBotString& CBotString::operator=(const char ch) const CBotString& CBotString::operator=(const char ch)
{ {
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_lg = 1; m_lg = 1;
@ -301,17 +383,17 @@ const CBotString& CBotString::operator=(const char ch)
const CBotString& CBotString::operator=(const char* pString) const CBotString& CBotString::operator=(const char* pString)
{ {
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_ptr = NULL; m_ptr = NULL;
if (pString != NULL) if (pString != NULL)
{ {
m_lg = lstrlen(pString); m_lg = strlen(pString);
if (m_lg != 0) if (m_lg != 0)
{ {
m_ptr = (char*)malloc(m_lg+1); m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, pString); strcpy(m_ptr, pString);
} }
} }
@ -323,11 +405,11 @@ const CBotString& CBotString::operator+=(const char ch)
{ {
char* p = (char*)malloc(m_lg+2); char* p = (char*)malloc(m_lg+2);
if (m_ptr!=NULL) lstrcpy(p, m_ptr); if (m_ptr!=NULL) strcpy(p, m_ptr);
p[m_lg++] = ch; p[m_lg++] = ch;
p[m_lg] = 0; p[m_lg] = 0;
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_ptr = p; m_ptr = p;
@ -338,112 +420,122 @@ const CBotString& CBotString::operator+=(const CBotString& str)
{ {
char* p = (char*)malloc(m_lg+str.m_lg+1); char* p = (char*)malloc(m_lg+str.m_lg+1);
lstrcpy(p, m_ptr); strcpy(p, m_ptr);
char* pp = p + m_lg; char* pp = p + m_lg;
lstrcpy(pp, str.m_ptr); strcpy(pp, str.m_ptr);
m_lg = m_lg + str.m_lg; m_lg = m_lg + str.m_lg;
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_ptr = p; m_ptr = p;
return *this; return *this;
} }
BOOL CBotString::operator==(const CBotString& str) bool CBotString::operator==(const CBotString& str)
{ {
return Compare(str) == 0; return Compare(str) == 0;
} }
BOOL CBotString::operator==(const char* p) bool CBotString::operator==(const char* p)
{ {
return Compare(p) == 0; return Compare(p) == 0;
} }
BOOL CBotString::operator!=(const CBotString& str) bool CBotString::operator!=(const CBotString& str)
{ {
return Compare(str) != 0; return Compare(str) != 0;
} }
BOOL CBotString::operator!=(const char* p) bool CBotString::operator!=(const char* p)
{ {
return Compare(p) != 0; return Compare(p) != 0;
} }
BOOL CBotString::operator>(const CBotString& str) bool CBotString::operator>(const CBotString& str)
{ {
return Compare(str) > 0; return Compare(str) > 0;
} }
BOOL CBotString::operator>(const char* p) bool CBotString::operator>(const char* p)
{ {
return Compare(p) > 0; return Compare(p) > 0;
} }
BOOL CBotString::operator>=(const CBotString& str) bool CBotString::operator>=(const CBotString& str)
{ {
return Compare(str) >= 0; return Compare(str) >= 0;
} }
BOOL CBotString::operator>=(const char* p) bool CBotString::operator>=(const char* p)
{ {
return Compare(p) >= 0; return Compare(p) >= 0;
} }
BOOL CBotString::operator<(const CBotString& str) bool CBotString::operator<(const CBotString& str)
{ {
return Compare(str) < 0; return Compare(str) < 0;
} }
BOOL CBotString::operator<(const char* p) bool CBotString::operator<(const char* p)
{ {
return Compare(p) < 0; return Compare(p) < 0;
} }
BOOL CBotString::operator<=(const CBotString& str) bool CBotString::operator<=(const CBotString& str)
{ {
return Compare(str) <= 0; return Compare(str) <= 0;
} }
BOOL CBotString::operator<=(const char* p) bool CBotString::operator<=(const char* p)
{ {
return Compare(p) <= 0; return Compare(p) <= 0;
} }
BOOL CBotString::IsEmpty() const bool CBotString::IsEmpty() const
{ {
return (m_lg == 0); return (m_lg == 0);
} }
void CBotString::Empty() void CBotString::Empty()
{ {
if (m_ptr != NULL) free(m_ptr); free(m_ptr);
m_ptr = NULL; m_ptr = NULL;
m_lg = 0; m_lg = 0;
} }
static char nilstring[] = {0}; static char emptyString[] = {0};
CBotString::operator LPCTSTR() const CBotString::operator const char * () const
{ {
if (this == NULL || m_ptr == NULL) return nilstring; if (this == NULL || m_ptr == NULL) return emptyString;
return m_ptr; return m_ptr;
} }
int CBotString::Compare(LPCTSTR lpsz) const int CBotString::Compare(const char * lpsz) const
{ {
char* p = m_ptr; char* p = m_ptr;
if (lpsz == NULL) lpsz = nilstring; if (lpsz == NULL) lpsz = emptyString;
if (m_ptr == NULL) p = nilstring; if (m_ptr == NULL) p = emptyString;
return strcmp(p, lpsz); // wcscmp return strcmp(p, lpsz); // wcscmp
} }
const char * CBotString::MapIdToString(EID id)
{
if (s_keywordString.find(id) != s_keywordString.end())
{
return s_keywordString.at(id);
}
else
{
return emptyString;
}
}
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// tableaux de chaines // arrays of strings
CBotStringArray::CBotStringArray() CBotStringArray::CBotStringArray()
{ {
@ -453,7 +545,7 @@ CBotStringArray::CBotStringArray()
CBotStringArray::~CBotStringArray() CBotStringArray::~CBotStringArray()
{ {
SetSize(0); // détruit les données ! SetSize(0); // destroys data !
} }
@ -469,9 +561,8 @@ void CBotStringArray::Add(const CBotString& str)
m_pData[m_nSize-1] = str; m_pData[m_nSize-1] = str;
} }
/////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////
// routines utilitaires // utility routines
static inline void ConstructElement(CBotString* pNewData) static inline void ConstructElement(CBotString* pNewData)
{ {
@ -518,7 +609,7 @@ static void CopyElements(CBotString* pDest, CBotString* pSrc, int nCount)
// sélect la taille du tableau // set the array size
void CBotStringArray::SetSize(int nNewSize) void CBotStringArray::SetSize(int nNewSize)
{ {
@ -527,14 +618,14 @@ void CBotStringArray::SetSize(int nNewSize)
// shrink to nothing // shrink to nothing
DestructElements(m_pData, m_nSize); DestructElements(m_pData, m_nSize);
delete[] (BYTE*)m_pData; delete[] (unsigned char *)m_pData;
m_pData = NULL; m_pData = NULL;
m_nSize = m_nMaxSize = 0; m_nSize = m_nMaxSize = 0;
} }
else if (m_pData == NULL) else if (m_pData == NULL)
{ {
// create one with exact size // create one with exact size
m_pData = (CBotString*) new BYTE[nNewSize * sizeof(CBotString)]; m_pData = (CBotString*) new unsigned char[nNewSize * sizeof(CBotString)];
ConstructElements(m_pData, nNewSize); ConstructElements(m_pData, nNewSize);
@ -563,7 +654,7 @@ void CBotStringArray::SetSize(int nNewSize)
{ {
// heuristically determine growth when nGrowBy == 0 // heuristically determine growth when nGrowBy == 0
// (this avoids heap fragmentation in many situations) // (this avoids heap fragmentation in many situations)
nGrowBy = min(1024, max(4, m_nSize / 8)); nGrowBy = std::min(1024, std::max(4, m_nSize / 8));
} }
int nNewMax; int nNewMax;
if (nNewSize < m_nMaxSize + nGrowBy) if (nNewSize < m_nMaxSize + nGrowBy)
@ -571,7 +662,7 @@ void CBotStringArray::SetSize(int nNewSize)
else else
nNewMax = nNewSize; // no slush nNewMax = nNewSize; // no slush
CBotString* pNewData = (CBotString*) new BYTE[nNewMax * sizeof(CBotString)]; CBotString* pNewData = (CBotString*) new unsigned char[nNewMax * sizeof(CBotString)];
// copy new data from old // copy new data from old
memcpy(pNewData, m_pData, m_nSize * sizeof(CBotString)); memcpy(pNewData, m_pData, m_nSize * sizeof(CBotString));
@ -580,8 +671,8 @@ void CBotStringArray::SetSize(int nNewSize)
ConstructElements(&pNewData[m_nSize], nNewSize-m_nSize); ConstructElements(&pNewData[m_nSize], nNewSize-m_nSize);
// Ret rid of old stuff (note: no destructors called) // Get rid of old stuff (note: no destructors called)
delete[] (BYTE*)m_pData; delete[] (unsigned char *)m_pData;
m_pData = pNewData; m_pData = pNewData;
m_nSize = nNewSize; m_nSize = nNewSize;
m_nMaxSize = nNewMax; m_nMaxSize = nNewMax;
@ -599,5 +690,3 @@ CBotString& CBotStringArray::ElementAt(int nIndex)
return m_pData[nIndex]; return m_pData[nIndex];
} }

View File

@ -12,29 +12,33 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.////////////////////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// Gestion des Tokens
// le texte d'un programme est d'abord transformé
// en une suite de tokens pour facilité l'interprétation
// il faudra traiter le seul cas d'erreur possible
// qui est un caractère illégal dans une string //CBotToken.cpp
//////////////////////////////////////////////////////////////////
// Managing Tokens
// the text of a program is first transformed
// into a sequence of tokens for easy interpretation
// it will only treat the case as an error
// where there is an illegal character in a string
#include "CBot.h" #include "CBot.h"
#include <cstdarg>
CBotStringArray CBotToken::m_ListKeyWords; CBotStringArray CBotToken::m_ListKeyWords;
int CBotToken::m_ListIdKeyWords[200]; int CBotToken::m_ListIdKeyWords[200];
CBotStringArray CBotToken::m_ListKeyDefine; CBotStringArray CBotToken::m_ListKeyDefine;
long CBotToken::m_ListKeyNums[MAXDEFNUM]; long CBotToken::m_ListKeyNums[MAXDEFNUM];
// constructeurs //! contructors
CBotToken::CBotToken() CBotToken::CBotToken()
{ {
m_next = NULL; m_next = NULL;
m_prev = NULL; m_prev = NULL;
m_type = TokenTypVar; // at the beginning a default variable type
m_type = TokenTypVar; // à priori un nom d'une variable
m_IdKeyWord = -1; m_IdKeyWord = -1;
} }
@ -54,12 +58,13 @@ CBotToken::CBotToken(const CBotToken* pSrc)
if ( pSrc != NULL ) if ( pSrc != NULL )
{ {
m_Text = pSrc->m_Text;
m_Sep = pSrc->m_Sep;
m_type = pSrc->m_type; m_type = pSrc->m_type;
m_IdKeyWord = pSrc->m_IdKeyWord; m_IdKeyWord = pSrc->m_IdKeyWord;
m_Text = pSrc->m_Text;
m_Sep = pSrc->m_Sep;
m_start = pSrc->m_start; m_start = pSrc->m_start;
m_end = pSrc->m_end; m_end = pSrc->m_end;
} }
@ -67,14 +72,14 @@ CBotToken::CBotToken(const CBotToken* pSrc)
CBotToken::CBotToken(const CBotString& mot, const CBotString& sep, int start, int end) CBotToken::CBotToken(const CBotString& mot, const CBotString& sep, int start, int end)
{ {
m_Text = mot; // mot trouvé comme token m_Text = mot; // word (mot) found as token
m_Sep = sep; // séparateurs qui suivent m_Sep = sep; // separator
m_next = NULL; m_next = NULL;
m_prev = NULL; m_prev = NULL;
m_start = start; m_start = start;
m_end = end; m_end = end;
m_type = TokenTypVar; // à priori un nom d'une variable m_type = TokenTypVar; // at the beginning a default variable type
m_IdKeyWord = -1; m_IdKeyWord = -1;
} }
@ -85,13 +90,13 @@ CBotToken::CBotToken(const char* mot, const char* sep)
m_next = NULL; m_next = NULL;
m_prev = NULL; m_prev = NULL;
m_type = TokenTypVar; // à priori un nom d'une variable m_type = TokenTypVar; // at the beginning a default variable type
m_IdKeyWord = -1; m_IdKeyWord = -1;
} }
CBotToken::~CBotToken() CBotToken::~CBotToken()
{ {
delete m_next; // récursif delete m_next; // recursive
m_next = NULL; m_next = NULL;
} }
@ -188,168 +193,168 @@ void CBotToken::SetPos(int start, int end)
m_end = end; m_end = end;
} }
BOOL CharInList(const char c, const char* list) bool CharInList(const char c, const char* list)
{ {
int i = 0; int i = 0;
while (TRUE) while (true)
{ {
if (c == list[i++]) return TRUE; if (c == list[i++]) return true;
if (list[i] == 0) return FALSE; if (list[i] == 0) return false;
} }
} }
BOOL Char2InList(const char c, const char cc, const char* list) bool Char2InList(const char c, const char cc, const char* list)
{ {
int i = 0; int i = 0;
while (TRUE) while (true)
{ {
if (c == list[i++] && if (c == list[i++] &&
cc == list[i++]) return TRUE; cc == list[i++]) return true;
if (list[i] == 0) return FALSE; if (list[i] == 0) return false;
} }
} }
static char* sep1 = " \r\n\t,:()[]{}-+*/=;><!~^|&%."; static char* sep1 = " \r\n\t,:()[]{}-+*/=;><!~^|&%.";
static char* sep2 = " \r\n\t"; // séparateurs pures static char* sep2 = " \r\n\t"; // only separators
static char* sep3 = ",:()[]{}-+*/=;<>!~^|&%."; // séparateurs opérationnels static char* sep3 = ",:()[]{}-+*/=;<>!~^|&%."; // operational separators
static char* num = "0123456789"; // le point (unique) est testé séparément static char* num = "0123456789"; // point (single) is tested separately
static char* hexnum = "0123456789ABCDEFabcdef"; static char* hexnum = "0123456789ABCDEFabcdef";
static char* nch = "\"\r\n\t"; // refusé dans les chaines static char* nch = "\"\r\n\t"; // forbidden in chains
//static char* duo = "+=-=*=/===!=<=>=++--///**/||&&";// les opérateurs doubles //static char* duo = "+=-=*=/===!=<=>=++--///**/||&&"; // double operators
// cherche le prochain token dans une phrase // looking for the next token in a sentence
// ne doit pas commencer par des séparateurs // do not start with separators
// qui sont pris avec le token précédent // which are made in the previous token
CBotToken* CBotToken::NextToken(char* &program, int& error, BOOL first) CBotToken* CBotToken::NextToken(char* &program, int& error, bool first)
{ {
CBotString mot; // le mot trouvé CBotString mot; // the word which is found
CBotString sep; // les séparateurs qui le suivent CBotString sep; // separators that are after
char c; char c;
BOOL stop = first; bool stop = first;
if (*program == 0) return NULL; if (*program == 0) return NULL;
c = *(program++); // prochain caractère c = *(program++); // next character
if (!first) if (!first)
{ {
mot = c; // construit le mot mot = c; // built the word
c = *(program++); // prochain caractère c = *(program++); // next character
// cas particulier pour les chaînes de caractères // special case for strings
if ( mot[0] == '\"' ) if ( mot[0] == '\"' )
{ {
while (c != 0 && !CharInList(c, nch)) while (c != 0 && !CharInList(c, nch))
{ {
mot += c; mot += c;
c = *(program++); // prochain caractère c = *(program++); // next character
if ( c == '\\' ) if ( c == '\\' )
{ {
c = *(program++); // prochain caractère c = *(program++); // next character
if ( c == 'n' ) c = '\n'; if ( c == 'n' ) c = '\n';
if ( c == 'r' ) c = '\r'; if ( c == 'r' ) c = '\r';
if ( c == 't' ) c = '\t'; if ( c == 't' ) c = '\t';
mot += c; mot += c;
c = *(program++); // prochain caractère c = *(program++); // next character
} }
} }
if ( c == '\"' ) if ( c == '\"' )
{ {
mot += c; // chaîne complète mot += c; // string is complete
c = *(program++); // prochain caractère c = *(program++); // next character
} }
stop = TRUE; stop = true;
} }
// cas particulier pour les nombres // special case for numbers
if ( CharInList(mot[0], num )) if ( CharInList(mot[0], num ))
{ {
BOOL bdot = FALSE; // trouvé un point ? bool bdot = false; // found a point?
BOOL bexp = FALSE; // trouvé un exposant ? bool bexp = false; // found an exponent?
char* liste = num; char* liste = num;
if (mot[0] == '0' && c == 'x') // valeur hexadécimale ? if (mot[0] == '0' && c == 'x') // hexadecimal value?
{ {
mot += c; mot += c;
c = *(program++); // prochain caractère c = *(program++); // next character
liste = hexnum; liste = hexnum;
} }
cw: cw:
while (c != 0 && CharInList(c, liste)) while (c != 0 && CharInList(c, liste))
{ {
cc: mot += c; cc: mot += c;
c = *(program++); // prochain caractère c = *(program++); // next character
} }
if ( liste == num ) // pas pour les exadécimaux if ( liste == num ) // not for hexadecimal
{ {
if ( !bdot && c == '.' ) { bdot = TRUE; goto cc; } if ( !bdot && c == '.' ) { bdot = true; goto cc; }
if ( !bexp && ( c == 'e' || c == 'E' ) ) if ( !bexp && ( c == 'e' || c == 'E' ) )
{ {
bexp = TRUE; bexp = true;
mot += c; mot += c;
c = *(program++); // prochain caractère c = *(program++); // next character
if ( c == '-' || if ( c == '-' ||
c == '+' ) goto cc; c == '+' ) goto cc;
goto cw; goto cw;
} }
} }
stop = TRUE; stop = true;
} }
if (CharInList(mot[0], sep3)) // un séparateur opérationnel ? if (CharInList(mot[0], sep3)) // an operational separator?
{ {
CBotString motc = mot; CBotString motc = mot;
while (motc += c, c != 0 && GivKeyWords(motc)>0) // cherche l'opérande le plus long possible while (motc += c, c != 0 && GivKeyWords(motc)>0) // operand seeks the longest possible
{ {
mot += c; // construit le mot mot += c; // build the word
c = *(program++); // prochain caractère c = *(program++); // next character
} }
stop = TRUE; stop = true;
} }
} }
while (TRUE) while (true)
{ {
if (stop || c == 0 || CharInList(c, sep1)) if (stop || c == 0 || CharInList(c, sep1))
{ {
if (!first && mot.IsEmpty()) return NULL; // fin de l'analyse if (!first && mot.IsEmpty()) return NULL; // end of the analysis
bis: bis:
while (CharInList(c, sep2)) while (CharInList(c, sep2))
{ {
sep += c; // tous les séparateurs qui suivent sep += c; // after all the separators
c = *(program++); c = *(program++);
} }
if (c == '/' && *program == '/') // un commentaire dans le tas ? if (c == '/' && *program == '/') // comment on the heap?
{ {
while( c != '\n' && c != 0 ) while( c != '\n' && c != 0 )
{ {
sep += c; sep += c;
c = *(program++); // prochain caractère c = *(program++); // next character
} }
goto bis; goto bis;
} }
if (c == '/' && *program == '*') // un commentaire dans le tas ? if (c == '/' && *program == '*') // comment on the heap?
{ {
while( c != 0 && (c != '*' || *program != '/')) while( c != 0 && (c != '*' || *program != '/'))
{ {
sep += c; sep += c;
c = *(program++); // prochain caractère c = *(program++); // next character
} }
if ( c != 0 ) if ( c != 0 )
{ {
sep += c; sep += c;
c = *(program++); // prochain caractère c = *(program++); // next character
sep += c; sep += c;
c = *(program++); // prochain caractère c = *(program++); // next character
} }
goto bis; goto bis;
} }
@ -364,13 +369,13 @@ bis:
token->m_IdKeyWord = GivKeyWords(mot); token->m_IdKeyWord = GivKeyWords(mot);
if (token->m_IdKeyWord > 0) token->m_type = TokenTypKeyWord; if (token->m_IdKeyWord > 0) token->m_type = TokenTypKeyWord;
else GivKeyDefNum(mot, token) ; // traite les DefineNum else GivKeyDefNum(mot, token) ; // treats DefineNum
return token; return token;
} }
mot += c; // construit le mot mot += c; // built the word
c = *(program++); // prochain caractère c = *(program++); // next character
} }
} }
@ -381,7 +386,7 @@ CBotToken* CBotToken::CompileTokens(const char* program, int& error)
int pos = 0; int pos = 0;
error = 0; error = 0;
prv = tokenbase = NextToken(p, error, TRUE); prv = tokenbase = NextToken(p, error, true);
if (tokenbase == NULL) return NULL; if (tokenbase == NULL) return NULL;
@ -393,24 +398,24 @@ CBotToken* CBotToken::CompileTokens(const char* program, int& error)
char* pp = p; char* pp = p;
while (NULL != (nxt = NextToken(p, error))) while (NULL != (nxt = NextToken(p, error)))
{ {
prv->m_next = nxt; // ajoute à la suite prv->m_next = nxt; // added after
nxt->m_prev = prv; nxt->m_prev = prv;
prv = nxt; // avance prv = nxt; // advance
nxt->m_start = pos; nxt->m_start = pos;
/* pos += nxt->m_Text.GivLength(); // la chaîne peut être plus courte (BOA supprimés) /* pos += nxt->m_Text.GivLength(); // chain may be shorter (BOA deleted)
nxt->m_end = pos; nxt->m_end = pos;
pos += nxt->m_Sep.GivLength();*/ pos += nxt->m_Sep.GivLength();*/
pos += (p - pp); // taille totale pos += (p - pp); // total size
nxt->m_end = pos - nxt->m_Sep.GivLength(); nxt->m_end = pos - nxt->m_Sep.GivLength();
pp = p; pp = p;
} }
// ajoute un token comme terminateur // adds a token as a terminator
// ( utile pour avoir le précédent ) // ( useful for the previous )
nxt = new CBotToken(); nxt = new CBotToken();
nxt->m_type = 0; nxt->m_type = 0;
prv->m_next = nxt; // ajoute à la suite prv->m_next = nxt; // added after
nxt->m_prev = prv; nxt->m_prev = prv;
return tokenbase; return tokenbase;
@ -422,7 +427,7 @@ void CBotToken::Delete(CBotToken* pToken)
} }
// recherche si un mot fait parti des mots clefs // search if a word is part of the keywords
int CBotToken::GivKeyWords(const char* w) int CBotToken::GivKeyWords(const char* w)
{ {
@ -431,7 +436,7 @@ int CBotToken::GivKeyWords(const char* w)
if (l == 0) if (l == 0)
{ {
LoadKeyWords(); // prend la liste la première fois LoadKeyWords(); // takes the list for the first time
l = m_ListKeyWords.GivSize(); l = m_ListKeyWords.GivSize();
} }
@ -443,7 +448,7 @@ int CBotToken::GivKeyWords(const char* w)
return -1; return -1;
} }
BOOL CBotToken::GivKeyDefNum(const char* w, CBotToken* &token) bool CBotToken::GivKeyDefNum(const char* w, CBotToken* &token)
{ {
int i; int i;
int l = m_ListKeyDefine.GivSize(); int l = m_ListKeyDefine.GivSize();
@ -454,28 +459,32 @@ BOOL CBotToken::GivKeyDefNum(const char* w, CBotToken* &token)
{ {
token->m_IdKeyWord = m_ListKeyNums[i]; token->m_IdKeyWord = m_ListKeyNums[i];
token->m_type = TokenTypDef; token->m_type = TokenTypDef;
return TRUE; return true;
} }
} }
return FALSE; return false;
} }
// reprend la liste des mots clefs dans les ressources
/// \todo Fixme Figure out how this should work.
// recreates the list of keywords and its IDs basing on some resources
// defines of TokenKey.. are in CBotDll.h
void CBotToken::LoadKeyWords() void CBotToken::LoadKeyWords()
{ {
CBotString s; CBotString s;
int i, n = 0; int i, n = 0;
i = TokenKeyWord; i = TokenKeyWord; //start with keywords of the language
while (s.LoadString(i)) while (s.LoadString(i))
{ {
m_ListKeyWords.Add(s); m_ListKeyWords.Add(s);
m_ListIdKeyWords[n++] = i++; m_ListIdKeyWords[n++] = i++;
} }
i = TokenKeyDeclare; i = TokenKeyDeclare; //keywords of declarations
while (s.LoadString(i)) while (s.LoadString(i))
{ {
m_ListKeyWords.Add(s); m_ListKeyWords.Add(s);
@ -483,14 +492,14 @@ void CBotToken::LoadKeyWords()
} }
i = TokenKeyVal; i = TokenKeyVal; //keywords of values
while (s.LoadString(i)) while (s.LoadString(i))
{ {
m_ListKeyWords.Add(s); m_ListKeyWords.Add(s);
m_ListIdKeyWords[n++] = i++; m_ListIdKeyWords[n++] = i++;
} }
i = TokenKeyOp; i = TokenKeyOp; //operators
while (s.LoadString(i)) while (s.LoadString(i))
{ {
m_ListKeyWords.Add(s); m_ListKeyWords.Add(s);
@ -498,36 +507,35 @@ void CBotToken::LoadKeyWords()
} }
} }
BOOL CBotToken::DefineNum(const char* name, long val) bool CBotToken::DefineNum(const char* name, long val)
{ {
int i; int i;
int l = m_ListKeyDefine.GivSize(); int l = m_ListKeyDefine.GivSize();
for (i = 0; i < l; i++) for (i = 0; i < l; i++)
{ {
if (m_ListKeyDefine[i] == name) return FALSE; if (m_ListKeyDefine[i] == name) return false;
} }
if ( i == MAXDEFNUM ) return FALSE; if ( i == MAXDEFNUM ) return false;
m_ListKeyDefine.Add( name ); m_ListKeyDefine.Add( name );
m_ListKeyNums[i] = val; m_ListKeyNums[i] = val;
return TRUE; return true;
} }
BOOL IsOfType(CBotToken* &p, int type1, int type2) bool IsOfType(CBotToken* &p, int type1, int type2)
{ {
if (p->GivType() == type1 || if (p->GivType() == type1 ||
p->GivType() == type2 ) p->GivType() == type2 )
{ {
p = p->GivNext(); p = p->GivNext();
return TRUE; return true;
} }
return FALSE; return false;
} }
// Same with any number of arguments
// idem avec un nombre indéfini d'arguments // There must be a zero as the last argument
// il faut mettre un zéro comme dernier argument bool IsOfTypeList(CBotToken* &p, int type1, ...)
BOOL IsOfTypeList(CBotToken* &p, int type1, ...)
{ {
int i = type1; int i = type1;
int max = 20; int max = 20;
@ -536,18 +544,18 @@ BOOL IsOfTypeList(CBotToken* &p, int type1, ...)
va_list marker; va_list marker;
va_start( marker, type1 ); /* Initialize variable arguments. */ va_start( marker, type1 ); /* Initialize variable arguments. */
while (TRUE) while (true)
{ {
if (type == i) if (type == i)
{ {
p = p->GivNext(); p = p->GivNext();
va_end( marker ); /* Reset variable arguments. */ va_end( marker ); /* Reset variable arguments. */
return TRUE; return true;
} }
if (--max == 0 || 0 == (i = va_arg( marker, int))) if (--max == 0 || 0 == (i = va_arg( marker, int)))
{ {
va_end( marker ); /* Reset variable arguments. */ va_end( marker ); /* Reset variable arguments. */
return FALSE; return false;
} }
} }
} }

View File

@ -12,15 +12,15 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.//////////////////////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// interpréteur pour le language CBot du jeu COLOBOT
// un programme écrit est tout d'abord transformé en une liste de tokens // interpreter of the lanuage CBot for game COLOBOT
// avant d'aborder le compilateur proprement dit // writing a program is first transformed into a list of tokens
// par exemple // before tackling the compiler itself
// for example
// int var = 3 * ( pos.y + x ) // int var = 3 * ( pos.y + x )
// est décomposé en (chaque ligne est un token) // is decomposed into (each line is a token)
// int // int
// var // var
// = // =
@ -32,6 +32,7 @@
// x // x
// ) // )
#pragma once
extern BOOL IsOfType(CBotToken* &p, int type1, int type2 = -1); extern bool IsOfType(CBotToken* &p, int type1, int type2 = -1);
extern BOOL IsOfTypeList(CBotToken* &p, int type1, ...); extern bool IsOfTypeList(CBotToken* &p, int type1, ...);

View File

@ -12,18 +12,20 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/./////////////////////////////////////////////////// // * along with this program. If not, see http://www.gnu.org/licenses/.
// expression du genre Opérande1 + Opérande2
// Opérande1 > Opérande2 ///////////////////////////////////////////////////
// expression of type Opérande1 + Opérande2
// Opérande1 > Opérande2
#include "CBot.h" #include "CBot.h"
// divers constructeurs // various constructors
CBotTwoOpExpr::CBotTwoOpExpr() CBotTwoOpExpr::CBotTwoOpExpr()
{ {
m_leftop = m_leftop =
m_rightop = NULL; // NULL pour pouvoir faire delete sans autre m_rightop = NULL; // NULL to be able to delete without other
name = "CBotTwoOpExpr"; // debug name = "CBotTwoOpExpr"; // debug
} }
@ -37,7 +39,7 @@ CBotLogicExpr::CBotLogicExpr()
{ {
m_condition = m_condition =
m_op1 = m_op1 =
m_op2 = NULL; // NULL pour pouvoir faire delete sans autre m_op2 = NULL; // NULL to be able to delete without other
name = "CBotLogicExpr"; // debug name = "CBotLogicExpr"; // debug
} }
@ -49,7 +51,7 @@ CBotLogicExpr::~CBotLogicExpr()
} }
// type d'opérandes acceptés par les opérations // type of operands accepted by operations
#define ENTIER ((1<<CBotTypByte)|(1<<CBotTypShort)|(1<<CBotTypChar)|(1<<CBotTypInt)|(1<<CBotTypLong)) #define ENTIER ((1<<CBotTypByte)|(1<<CBotTypShort)|(1<<CBotTypChar)|(1<<CBotTypInt)|(1<<CBotTypLong))
#define FLOTANT ((1<<CBotTypFloat)|(1<<CBotTypDouble)) #define FLOTANT ((1<<CBotTypFloat)|(1<<CBotTypDouble))
#define BOOLEEN (1<<CBotTypBoolean) #define BOOLEEN (1<<CBotTypBoolean)
@ -57,9 +59,9 @@ CBotLogicExpr::~CBotLogicExpr()
#define POINTER (1<<CBotTypPointer) #define POINTER (1<<CBotTypPointer)
#define INSTANCE (1<<CBotTypClass) #define INSTANCE (1<<CBotTypClass)
// liste des opérations (précéance) // list of operations (précéance)
// type acceptable, opérande // acceptable type, operand
// le zéro termine un niveau de précéance // zero ends level \TODO précéance
static int ListOp[] = static int ListOp[] =
{ {
@ -95,26 +97,26 @@ static int ListOp[] =
0, 0,
}; };
BOOL IsInList( int val, int* list, int& typemasque ) bool IsInList( int val, int* list, int& typemasque )
{ {
while (TRUE) while (true)
{ {
if ( *list == 0 ) return FALSE; if ( *list == 0 ) return false;
typemasque = *list++; typemasque = *list++;
if ( *list++ == val ) return TRUE; if ( *list++ == val ) return true;
} }
} }
BOOL TypeOk( int type, int test ) bool TypeOk( int type, int test )
{ {
while (TRUE) while (true)
{ {
if ( type == 0 ) return (test & 1); if ( type == 0 ) return (test & 1);
type--; test /= 2; type--; test /= 2;
} }
} }
// compile une instruction de type A op B // compiles a instruction of type A op B
CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOperations) CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOperations)
{ {
@ -122,25 +124,25 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
if ( pOperations == NULL ) pOperations = ListOp; if ( pOperations == NULL ) pOperations = ListOp;
int* pOp = pOperations; int* pOp = pOperations;
while ( *pOp++ != 0 ); // suite de la table while ( *pOp++ != 0 ); // follows the table
CBotCStack* pStk = pStack->TokenStack(); // un bout de pile svp CBotCStack* pStk = pStack->TokenStack(); // one end of stack please
// cherche des instructions qui peuvent convenir à gauche de l'opération // search the intructions that may be suitable to the left of the operation
CBotInstr* left = (*pOp == 0) ? CBotInstr* left = (*pOp == 0) ?
CBotParExpr::Compile( p, pStk ) : // expression (...) à gauche CBotParExpr::Compile( p, pStk ) : // expression (...) left
CBotTwoOpExpr::Compile( p, pStk, pOp ); // expression A * B à gauche CBotTwoOpExpr::Compile( p, pStk, pOp ); // expression A * B left
if (left == NULL) return pStack->Return(NULL, pStk); // si erreur, la transmet if (left == NULL) return pStack->Return(NULL, pStk); // if error, transmit
// est-ce qu'on a l'opérande prévu ensuite ? // did we expected the operand?
int TypeOp = p->GivType(); int TypeOp = p->GivType();
if ( IsInList( TypeOp, pOperations, typemasque ) ) if ( IsInList( TypeOp, pOperations, typemasque ) )
{ {
CBotTypResult type1, type2; CBotTypResult type1, type2;
type1 = pStk->GivTypResult(); // de quel type le premier opérande ? type1 = pStk->GivTypResult(); // what kind of the first operand?
if ( TypeOp == ID_LOGIC ) // cas spécial pour condition ? op1 : op2 ; if ( TypeOp == ID_LOGIC ) // special case provided for: ? op1: op2;
{ {
if ( !type1.Eq(CBotTypBoolean) ) if ( !type1.Eq(CBotTypBoolean) )
{ {
@ -150,7 +152,7 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
CBotLogicExpr* inst = new CBotLogicExpr(); CBotLogicExpr* inst = new CBotLogicExpr();
inst->m_condition = left; inst->m_condition = left;
p = p->GivNext(); // saute le token de l'opération p = p->GivNext(); // skip the token of the operation
inst->m_op1 = CBotExpression::Compile(p, pStk); inst->m_op1 = CBotExpression::Compile(p, pStk);
CBotToken* pp = p; CBotToken* pp = p;
if ( inst->m_op1 == NULL || !IsOfType( p, ID_DOTS ) ) if ( inst->m_op1 == NULL || !IsOfType( p, ID_DOTS ) )
@ -176,39 +178,39 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
return pStack->Return(NULL, pStk); return pStack->Return(NULL, pStk);
} }
pStk->SetType(type1); // le plus grand des 2 types pStk->SetType(type1); // the greatest of 2 types
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
CBotTwoOpExpr* inst = new CBotTwoOpExpr(); // élément pour opération CBotTwoOpExpr* inst = new CBotTwoOpExpr(); // element for operation
inst->SetToken(p); // mémorise l'opération inst->SetToken(p); // stores the operation
p = p->GivNext(); // saute le token de l'opération p = p->GivNext(); // skip the token of the operation
// cherche des instructions qui peuvent convenir à droite // looking statements that may be suitable for right
if ( NULL != (inst->m_rightop = CBotTwoOpExpr::Compile( p, pStk, pOp )) ) if ( NULL != (inst->m_rightop = CBotTwoOpExpr::Compile( p, pStk, pOp )) )
// expression (...) à droite // expression (...) right
{ {
// il y a un second opérande acceptable // there is an second operand acceptable
type2 = pStk->GivTypResult(); // de quel type le résultat ? type2 = pStk->GivTypResult(); // what kind of results?
// quel est le type du résultat ? // what kind of result?
int TypeRes = MAX( type1.GivType(3), type2.GivType(3) ); int TypeRes = MAX( type1.GivType(3), type2.GivType(3) );
if ( TypeOp == ID_ADD && type1.Eq(CBotTypString) ) if ( TypeOp == ID_ADD && type1.Eq(CBotTypString) )
{ {
TypeRes = CBotTypString; TypeRes = CBotTypString;
type2 = type1; // tout type convertible en chaîne type2 = type1; // any type convertible chain
} }
else if ( TypeOp == ID_ADD && type2.Eq(CBotTypString) ) else if ( TypeOp == ID_ADD && type2.Eq(CBotTypString) )
{ {
TypeRes = CBotTypString; TypeRes = CBotTypString;
type1 = type2; // tout type convertible en chaîne type1 = type2; // any type convertible chain
} }
else if (!TypeOk( TypeRes, typemasque )) type1.SetType(99);// erreur de type else if (!TypeOk( TypeRes, typemasque )) type1.SetType(99);// error of type
switch ( TypeOp ) switch ( TypeOp )
{ {
@ -224,25 +226,25 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
case ID_LS: case ID_LS:
TypeRes = CBotTypBoolean; TypeRes = CBotTypBoolean;
} }
if ( TypeCompatible (type1, type2, TypeOp ) ) // les résultats sont-ils compatibles if ( TypeCompatible (type1, type2, TypeOp ) ) // the results are compatible
{ {
// si ok, enregistre l'opérande dans l'objet // ok so, saves the operand in the object
inst->m_leftop = left; inst->m_leftop = left;
// spécial pour évaluer les opérations de même niveau de gauche à droite // special for evaluation of the operations of the same level from left to right
while ( IsInList( p->GivType(), pOperations, typemasque ) ) // même(s) opération(s) suit ? while ( IsInList( p->GivType(), pOperations, typemasque ) ) // same operation(s) follows?
{ {
TypeOp = p->GivType(); TypeOp = p->GivType();
CBotTwoOpExpr* i = new CBotTwoOpExpr(); // élément pour opération CBotTwoOpExpr* i = new CBotTwoOpExpr(); // element for operation
i->SetToken(p); // mémorise l'opération i->SetToken(p); // stores the operation
i->m_leftop = inst; // opérande de gauche i->m_leftop = inst; // left operand
type1 = TypeRes; type1 = TypeRes;
p = p->GivNext(); // avance à la suite p = p->GivNext(); // advance after
i->m_rightop = CBotTwoOpExpr::Compile( p, pStk, pOp ); i->m_rightop = CBotTwoOpExpr::Compile( p, pStk, pOp );
type2 = pStk->GivTypResult(); type2 = pStk->GivTypResult();
if ( !TypeCompatible (type1, type2, TypeOp) ) // les résultats sont-ils compatibles if ( !TypeCompatible (type1, type2, TypeOp) ) // the results are compatible
{ {
pStk->SetError(TX_BAD2TYPE, &i->m_token); pStk->SetError(TX_BAD2TYPE, &i->m_token);
delete i; delete i;
@ -256,96 +258,96 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
CBotTypResult t(type1); CBotTypResult t(type1);
t.SetType(TypeRes); t.SetType(TypeRes);
// met une variable sur la pile pour avoir le type de résultat // is a variable on the stack for the type of result
pStk->SetVar(CBotVar::Create((CBotToken*)NULL, t)); pStk->SetVar(CBotVar::Create((CBotToken*)NULL, t));
// et rend l'object à qui l'a demandé // and returns the requested object
return pStack->Return(inst, pStk); return pStack->Return(inst, pStk);
} }
pStk->SetError(TX_BAD2TYPE, &inst->m_token); pStk->SetError(TX_BAD2TYPE, &inst->m_token);
} }
// en cas d'erreur, libère les éléments // in case of error, releases the elements
delete left; delete left;
delete inst; delete inst;
// et transmet l'erreur qui se trouve sur la pile // and transmits the error to the stack
return pStack->Return(NULL, pStk); return pStack->Return(NULL, pStk);
} }
// si on n'a pas affaire à une opération + ou - // if we are not dealing with an operation + or -
// rend à qui l'a demandé, l'opérande (de gauche) trouvé // goes to that requested, the operand (left) found
// à la place de l'objet "addition" // instead of the object "addition"
return pStack->Return(left, pStk); return pStack->Return(left, pStk);
} }
BOOL IsNan(CBotVar* left, CBotVar* right, int* err = NULL) bool IsNan(CBotVar* left, CBotVar* right, int* err = NULL)
{ {
if ( left ->GivInit() > IS_DEF || right->GivInit() > IS_DEF ) if ( left ->GivInit() > IS_DEF || right->GivInit() > IS_DEF )
{ {
if ( err != NULL ) *err = TX_OPNAN ; if ( err != NULL ) *err = TX_OPNAN ;
return TRUE; return true;
} }
return FALSE; return false;
} }
// fait l'opération sur 2 opérandes // performes the operation on two operands
BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack) bool CBotTwoOpExpr::Execute(CBotStack* &pStack)
{ {
CBotStack* pStk1 = pStack->AddStack(this); // ajoute un élément à la pile CBotStack* pStk1 = pStack->AddStack(this); // adds an item to the stack
// ou le retrouve en cas de reprise // or return in case of recovery
// if ( pStk1 == EOX ) return TRUE; // if ( pStk1 == EOX ) return true;
// selon la reprise, on peut être dans l'un des 2 états // according to recovery, it may be in one of two states
if ( pStk1->GivState() == 0 ) // 1er état, évalue l'opérande de gauche if ( pStk1->GivState() == 0 ) // first state, evaluates the left operand
{ {
if (!m_leftop->Execute(pStk1) ) return FALSE; // interrompu ici ? if (!m_leftop->Execute(pStk1) ) return false; // interrupted here?
// pour les OU et ET logique, n'évalue pas la seconde expression si pas nécessaire // for OR and AND logic does not evaluate the second expression if not necessary
if ( (GivTokenType() == ID_LOG_AND || GivTokenType() == ID_TXT_AND ) && pStk1->GivVal() == FALSE ) if ( (GivTokenType() == ID_LOG_AND || GivTokenType() == ID_TXT_AND ) && pStk1->GivVal() == false )
{ {
CBotVar* res = CBotVar::Create( (CBotToken*)NULL, CBotTypBoolean); CBotVar* res = CBotVar::Create( (CBotToken*)NULL, CBotTypBoolean);
res->SetValInt(FALSE); res->SetValInt(false);
pStk1->SetVar(res); pStk1->SetVar(res);
return pStack->Return(pStk1); // transmet le résultat return pStack->Return(pStk1); // transmits the result
} }
if ( (GivTokenType() == ID_LOG_OR||GivTokenType() == ID_TXT_OR) && pStk1->GivVal() == TRUE ) if ( (GivTokenType() == ID_LOG_OR||GivTokenType() == ID_TXT_OR) && pStk1->GivVal() == true )
{ {
CBotVar* res = CBotVar::Create( (CBotToken*)NULL, CBotTypBoolean); CBotVar* res = CBotVar::Create( (CBotToken*)NULL, CBotTypBoolean);
res->SetValInt(TRUE); res->SetValInt(true);
pStk1->SetVar(res); pStk1->SetVar(res);
return pStack->Return(pStk1); // transmet le résultat return pStack->Return(pStk1); // transmits the result
} }
// passe à l'étape suivante // passes to the next step
pStk1->SetState(1); // prêt pour la suite pStk1->SetState(1); // ready for further
} }
// demande un peu plus de stack pour ne pas toucher le résultat de gauche // requires a little more stack to avoid touching the result
// qui se trouve sur la pile, justement. // of which is left on the stack, precisely
CBotStack* pStk2 = pStk1->AddStack(); // ajoute un élément à la pile CBotStack* pStk2 = pStk1->AddStack(); // adds an item to the stack
// ou le retrouve en cas de reprise // or return in case of recovery
// 2e état, évalue l'opérande de droite // 2e état, évalue l'opérande de droite
if ( pStk2->GivState() == 0 ) if ( pStk2->GivState() == 0 )
{ {
if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrompu ici ? if ( !m_rightop->Execute(pStk2) ) return false; // interrupted here?
pStk2->IncState(); pStk2->IncState();
} }
CBotTypResult type1 = pStk1->GivTypResult(); // de quels types les résultats ? CBotTypResult type1 = pStk1->GivTypResult(); // what kind of results?
CBotTypResult type2 = pStk2->GivTypResult(); CBotTypResult type2 = pStk2->GivTypResult();
CBotStack* pStk3 = pStk2->AddStack(this); // ajoute un élément à la pile CBotStack* pStk3 = pStk2->AddStack(this); // adds an item to the stack
if ( pStk3->IfStep() ) return FALSE; // montre l'opération si step by step if ( pStk3->IfStep() ) return false; // shows the operation if step by step
// crée une variable temporaire pour y mettre le résultat // creates a temporary variable to put the result
// quel est le type du résultat ? // what kind of result?
int TypeRes = MAX(type1.GivType(), type2.GivType()); int TypeRes = MAX(type1.GivType(), type2.GivType());
if ( GivTokenType() == ID_ADD && type1.Eq(CBotTypString) ) if ( GivTokenType() == ID_ADD && type1.Eq(CBotTypString) )
@ -371,10 +373,10 @@ BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack)
TypeRes = MAX(TypeRes, CBotTypFloat); TypeRes = MAX(TypeRes, CBotTypFloat);
} }
// crée une variable pour le résultat // creates a variable for the result
CBotVar* result = CBotVar::Create( (CBotToken*)NULL, TypeRes); CBotVar* result = CBotVar::Create( (CBotToken*)NULL, TypeRes);
// crée une variable pour effectuer le calcul dans le type adapté // creates a variable to perform the calculation in the appropriate type
TypeRes = MAX(type1.GivType(), type2.GivType()); TypeRes = MAX(type1.GivType(), type2.GivType());
if ( GivTokenType() == ID_ADD && type1.Eq(CBotTypString) ) if ( GivTokenType() == ID_ADD && type1.Eq(CBotTypString) )
@ -389,70 +391,70 @@ BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack)
else temp = CBotVar::Create( (CBotToken*)NULL, TypeRes ); else temp = CBotVar::Create( (CBotToken*)NULL, TypeRes );
int err = 0; int err = 0;
// fait l'opération selon la demande // is a operation according to request
CBotVar* left = pStk1->GivVar(); CBotVar* left = pStk1->GivVar();
CBotVar* right = pStk2->GivVar(); CBotVar* right = pStk2->GivVar();
switch (GivTokenType()) switch (GivTokenType())
{ {
case ID_ADD: case ID_ADD:
if ( !IsNan(left, right, &err) ) result->Add(left , right); // additionne if ( !IsNan(left, right, &err) ) result->Add(left , right); // addition
break; break;
case ID_SUB: case ID_SUB:
if ( !IsNan(left, right, &err) ) result->Sub(left , right); // soustrait if ( !IsNan(left, right, &err) ) result->Sub(left , right); // substraction
break; break;
case ID_MUL: case ID_MUL:
if ( !IsNan(left, right, &err) ) result->Mul(left , right); // multiplie if ( !IsNan(left, right, &err) ) result->Mul(left , right); // multiplies
break; break;
case ID_POWER: case ID_POWER:
if ( !IsNan(left, right, &err) ) result->Power(left , right); // puissance if ( !IsNan(left, right, &err) ) result->Power(left , right); // power
break; break;
case ID_DIV: case ID_DIV:
if ( !IsNan(left, right, &err) ) err = result->Div(left , right);// divise if ( !IsNan(left, right, &err) ) err = result->Div(left , right);// division
break; break;
case ID_MODULO: case ID_MODULO:
if ( !IsNan(left, right, &err) ) err = result->Modulo(left , right);// reste de division if ( !IsNan(left, right, &err) ) err = result->Modulo(left , right);// remainder of division
break; break;
case ID_LO: case ID_LO:
if ( !IsNan(left, right, &err) ) if ( !IsNan(left, right, &err) )
result->SetValInt(temp->Lo(left , right)); // inférieur result->SetValInt(temp->Lo(left , right)); // lower
break; break;
case ID_HI: case ID_HI:
if ( !IsNan(left, right, &err) ) if ( !IsNan(left, right, &err) )
result->SetValInt(temp->Hi(left , right)); // supérieur result->SetValInt(temp->Hi(left , right)); // top
break; break;
case ID_LS: case ID_LS:
if ( !IsNan(left, right, &err) ) if ( !IsNan(left, right, &err) )
result->SetValInt(temp->Ls(left , right)); // inférieur ou égal result->SetValInt(temp->Ls(left , right)); // less than or equal
break; break;
case ID_HS: case ID_HS:
if ( !IsNan(left, right, &err) ) if ( !IsNan(left, right, &err) )
result->SetValInt(temp->Hs(left , right)); // supérieur ou égal result->SetValInt(temp->Hs(left , right)); // greater than or equal
break; break;
case ID_EQ: case ID_EQ:
if ( IsNan(left, right) ) if ( IsNan(left, right) )
result->SetValInt(left->GivInit() == right->GivInit()) ; result->SetValInt(left->GivInit() == right->GivInit()) ;
else else
result->SetValInt(temp->Eq(left , right)); // égal result->SetValInt(temp->Eq(left , right)); // equal
break; break;
case ID_NE: case ID_NE:
if ( IsNan(left, right) ) if ( IsNan(left, right) )
result->SetValInt(left ->GivInit() != right->GivInit()) ; result->SetValInt(left ->GivInit() != right->GivInit()) ;
else else
result->SetValInt(temp->Ne(left , right)); // différent result->SetValInt(temp->Ne(left , right)); // different
break; break;
case ID_TXT_AND: case ID_TXT_AND:
case ID_LOG_AND: case ID_LOG_AND:
case ID_AND: case ID_AND:
if ( !IsNan(left, right, &err) ) result->And(left , right); // ET if ( !IsNan(left, right, &err) ) result->And(left , right); // AND
break; break;
case ID_TXT_OR: case ID_TXT_OR:
case ID_LOG_OR: case ID_LOG_OR:
case ID_OR: case ID_OR:
if ( !IsNan(left, right, &err) ) result->Or(left , right); // OU if ( !IsNan(left, right, &err) ) result->Or(left , right); // OR
break; break;
case ID_XOR: case ID_XOR:
if ( !IsNan(left, right, &err) ) result->XOr(left , right); // OU exclusif if ( !IsNan(left, right, &err) ) result->XOr(left , right); // exclusive OR
break; break;
case ID_ASR: case ID_ASR:
if ( !IsNan(left, right, &err) ) result->ASR(left , right); if ( !IsNan(left, right, &err) ) result->ASR(left , right);
@ -468,68 +470,68 @@ BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack)
} }
delete temp; delete temp;
pStk2->SetVar(result); // met le résultat sur la pile pStk2->SetVar(result); // puts the result on the stack
if ( err ) pStk2->SetError(err, &m_token); // et l'erreur éventuelle (division par zéro) if ( err ) pStk2->SetError(err, &m_token); // and the possible error (division by zero)
// pStk1->Return(pStk2); // libère la pile // pStk1->Return(pStk2); // releases the stack
return pStack->Return(pStk2); // transmet le résultat return pStack->Return(pStk2); // transmits the result
} }
void CBotTwoOpExpr::RestoreState(CBotStack* &pStack, BOOL bMain) void CBotTwoOpExpr::RestoreState(CBotStack* &pStack, bool bMain)
{ {
if ( !bMain ) return; if ( !bMain ) return;
CBotStack* pStk1 = pStack->RestoreStack(this); // ajoute un élément à la pile CBotStack* pStk1 = pStack->RestoreStack(this); // adds an item to the stack
if ( pStk1 == NULL ) return; if ( pStk1 == NULL ) return;
// selon la reprise, on peut être dans l'un des 2 états // according to recovery, it may be in one of two states
if ( pStk1->GivState() == 0 ) // 1er état, évalue l'opérande de gauche if ( pStk1->GivState() == 0 ) // first state, evaluates the left operand
{ {
m_leftop->RestoreState(pStk1, bMain); // interrompu ici ! m_leftop->RestoreState(pStk1, bMain); // interrupted here!
return; return;
} }
CBotStack* pStk2 = pStk1->RestoreStack(); // ajoute un élément à la pile CBotStack* pStk2 = pStk1->RestoreStack(); // adds an item to the stack
if ( pStk2 == NULL ) return; if ( pStk2 == NULL ) return;
// 2e état, évalue l'opérande de droite // second state, evaluates the right operand
if ( pStk2->GivState() == 0 ) if ( pStk2->GivState() == 0 )
{ {
m_rightop->RestoreState(pStk2, bMain); // interrompu ici ! m_rightop->RestoreState(pStk2, bMain); // interrupted here!
return; return;
} }
} }
BOOL CBotLogicExpr::Execute(CBotStack* &pStack) bool CBotLogicExpr::Execute(CBotStack* &pStack)
{ {
CBotStack* pStk1 = pStack->AddStack(this); // ajoute un élément à la pile CBotStack* pStk1 = pStack->AddStack(this); // adds an item to the stack
// ou le retrouve en cas de reprise // or return in case of recovery
// if ( pStk1 == EOX ) return TRUE; // if ( pStk1 == EOX ) return true;
if ( pStk1->GivState() == 0 ) if ( pStk1->GivState() == 0 )
{ {
if ( !m_condition->Execute(pStk1) ) return FALSE; if ( !m_condition->Execute(pStk1) ) return false;
if (!pStk1->SetState(1)) return FALSE; if (!pStk1->SetState(1)) return false;
} }
if ( pStk1->GivVal() == TRUE ) if ( pStk1->GivVal() == true )
{ {
if ( !m_op1->Execute(pStk1) ) return FALSE; if ( !m_op1->Execute(pStk1) ) return false;
} }
else else
{ {
if ( !m_op2->Execute(pStk1) ) return FALSE; if ( !m_op2->Execute(pStk1) ) return false;
} }
return pStack->Return(pStk1); // transmet le résultat return pStack->Return(pStk1); // transmits the result
} }
void CBotLogicExpr::RestoreState(CBotStack* &pStack, BOOL bMain) void CBotLogicExpr::RestoreState(CBotStack* &pStack, bool bMain)
{ {
if ( !bMain ) return; if ( !bMain ) return;
CBotStack* pStk1 = pStack->RestoreStack(this); // ajoute un élément à la pile CBotStack* pStk1 = pStack->RestoreStack(this); // adds an item to the stack
if ( pStk1 == NULL ) return; if ( pStk1 == NULL ) return;
if ( pStk1->GivState() == 0 ) if ( pStk1->GivState() == 0 )
@ -538,7 +540,7 @@ void CBotLogicExpr::RestoreState(CBotStack* &pStack, BOOL bMain)
return; return;
} }
if ( pStk1->GivVal() == TRUE ) if ( pStk1->GivVal() == true )
{ {
m_op1->RestoreState(pStk1, bMain); m_op1->RestoreState(pStk1, bMain);
} }
@ -557,7 +559,7 @@ void t()
#endif #endif
#if 01 #if 01
void t(BOOL t) void t(bool t)
{ {
int x; int x;
x = 1 + t ? 1 : 3 + 4 * 2 ; x = 1 + t ? 1 : 3 + 4 * 2 ;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,6 @@ CBotToken.cpp
CBotTwoOpExpr.cpp CBotTwoOpExpr.cpp
CBotVar.cpp CBotVar.cpp
CBotWhile.cpp CBotWhile.cpp
CBot.rc
) )
add_library(CBot SHARED ${SOURCES}) add_library(CBot SHARED ${SOURCES})

View File

@ -12,13 +12,15 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.// ClassFile.cpp // * along with this program. If not, see http://www.gnu.org/licenses/.
// ClassFile.cpp
// //
// définition des méthodes pour la classe FILE // definition of methods for class FILE
// Variables statiques // Static variables
static CBotClass* m_pClassFILE; static CBotClass* m_pClassFILE;
static CBotProgram* m_pFuncFile; static CBotProgram* m_pFuncFile;
@ -26,7 +28,7 @@ static int m_CompteurFileOpen = 0;
// Prépare un nom de fichier. // Prepares a file name.
void PrepareFilename(CBotString &filename) //DD! void PrepareFilename(CBotString &filename) //DD!
{ {
@ -35,110 +37,110 @@ void PrepareFilename(CBotString &filename) //DD!
pos = filename.ReverseFind('\\'); pos = filename.ReverseFind('\\');
if ( pos > 0 ) if ( pos > 0 )
{ {
filename = filename.Mid(pos+1); // enlève les dossiers filename = filename.Mid(pos+1); // remove the records (files)??
} }
pos = filename.ReverseFind('/'); pos = filename.ReverseFind('/');
if ( pos > 0 ) if ( pos > 0 )
{ {
filename = filename.Mid(pos+1); // aussi ceux avec / filename = filename.Mid(pos+1); // also those with /
} }
pos = filename.ReverseFind(':'); pos = filename.ReverseFind(':');
if ( pos > 0 ) if ( pos > 0 )
{ {
filename = filename.Mid(pos+1); // enlève aussi la lettre d'unité C: filename = filename.Mid(pos+1); // also removes the drive letter C:
} }
filename = CBotString("files\\") + filename; filename = CBotString("files\\") + filename;
} }
// constructeur de la classe // constructor of the class
// reçois le nom du fichier en paramètre // gets the filename as a parameter
// exécution // execution
BOOL rfconstruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfconstruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
CBotString mode; CBotString mode;
// accepte sans paramètre // accepts no parameters
if ( pVar == NULL ) return TRUE; if ( pVar == NULL ) return true;
// qui doit être une chaîne de caractères // must be a string
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return FALSE; } if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return false; }
CBotString filename = pVar->GivValString(); CBotString filename = pVar->GivValString();
PrepareFilename(filename); //DR PrepareFilename(filename); //DR
// il peut y avoir un second paramètre // there may be a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar != NULL ) if ( pVar != NULL )
{ {
// récupère le mode // recovers the mode
mode = pVar->GivValString(); mode = pVar->GivValString();
if ( mode != "r" && mode != "w" ) { Exception = CBotErrBadParam; return FALSE; } if ( mode != "r" && mode != "w" ) { Exception = CBotErrBadParam; return false; }
// pas de 3e paramètre // no third parameter, only two or one possible
if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return FALSE; } if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return false; }
} }
// enregistre le nom du fichier // save the file name
pVar = pThis->GivItem("filename"); pVar = pThis->GivItem("filename");
pVar->SetValString(filename); pVar->SetValString(filename);
if ( ! mode.IsEmpty() ) if ( ! mode.IsEmpty() )
{ {
// ouvre le ficher demandé // open the called file
FILE* pFile = fopen( filename, mode ); FILE* pFile = fopen( filename, mode );
if ( pFile == NULL ) { Exception = CBotErrFileOpen; return FALSE; } if ( pFile == NULL ) { Exception = CBotErrFileOpen; return false; }
m_CompteurFileOpen ++; m_CompteurFileOpen ++;
// enregiste le canal du fichier // save the handle of file
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
pVar->SetValInt((long)pFile); pVar->SetValInt((long)pFile);
} }
return TRUE; return true;
} }
// compilation // compilation
CBotTypResult cfconstruct (CBotVar* pThis, CBotVar* &pVar) CBotTypResult cfconstruct (CBotVar* pThis, CBotVar* &pVar)
{ {
// accepte sans paramètre // accepts no parameters
if ( pVar == NULL ) return CBotTypResult( 0 ); if ( pVar == NULL ) return CBotTypResult( 0 );
// qui doit être une chaine // must be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString ); return CBotTypResult( CBotErrBadString );
// il peut y avoir un second paramètre // there may be a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar != NULL ) if ( pVar != NULL )
{ {
// qui doit être une chaine // must be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString ); return CBotTypResult( CBotErrBadString );
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam ); if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam );
} }
// le résultat est de type void (constructeur) // le r<>sultat est de type void (constructeur)
return CBotTypResult( 0 ); return CBotTypResult( 0 );
} }
// destructeur de la classe // destructor of the class
// exécution // execution
BOOL rfdestruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfdestruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
// récupère l'élément "handle" // retrieves the element "handle"
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
// pas ouvert ? pas de problème // not open? no problem
if ( pVar->GivInit() != IS_DEF) return TRUE; if ( pVar->GivInit() != IS_DEF) return true;
FILE* pFile= (FILE*)pVar->GivValInt(); FILE* pFile= (FILE*)pVar->GivValInt();
fclose(pFile); fclose(pFile);
@ -146,112 +148,112 @@ BOOL rfdestruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception
pVar->SetInit(IS_NAN); pVar->SetInit(IS_NAN);
return TRUE; return true;
} }
// méthode FILE :: open // FILE :: open method
// reçois le mode r/w en paramètre // get the r / w mode as a parameter
// exécution // execution
BOOL rfopen (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfopen (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
// il doit y avoir un paramètre // there must be a parameter
if ( pVar == NULL ) { Exception = CBotErrLowParam; return FALSE; } if ( pVar == NULL ) { Exception = CBotErrLowParam; return false; }
// qui doit être une chaîne de caractères // must be a string
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return FALSE; } if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return false; }
// il peut y avoir un second paramètre // there may be a second parameter
if ( pVar->GivNext() != NULL ) if ( pVar->GivNext() != NULL )
{ {
// dans ce cas le premier paramètre est le nom du fichier // in this case the first parameter is the file name
CBotString filename = pVar->GivValString(); CBotString filename = pVar->GivValString();
PrepareFilename(filename); //DR PrepareFilename(filename); //DR
// enregistre le nom du fichier // saves the file name
CBotVar* pVar2 = pThis->GivItem("filename"); CBotVar* pVar2 = pThis->GivItem("filename");
pVar2->SetValString(filename); pVar2->SetValString(filename);
// paramètre suivant est le mode // next parameter is the mode
pVar = pVar -> GivNext(); pVar = pVar -> GivNext();
} }
CBotString mode = pVar->GivValString(); CBotString mode = pVar->GivValString();
if ( mode != "r" && mode != "w" ) { Exception = CBotErrBadParam; return FALSE; } if ( mode != "r" && mode != "w" ) { Exception = CBotErrBadParam; return false; }
// pas de 3e paramètre // No third parameter
if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return FALSE; } if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return false; }
// récupère l'élément "handle" // retrieves the element "handle"
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
// qui doit pas être initialisé // which must not be initialized
if ( pVar->GivInit() == IS_DEF) { Exception = CBotErrFileOpen; return FALSE; } if ( pVar->GivInit() == IS_DEF) { Exception = CBotErrFileOpen; return false; }
// reprend le nom du fichier // contains filename
pVar = pThis->GivItem("filename"); pVar = pThis->GivItem("filename");
CBotString filename = pVar->GivValString(); CBotString filename = pVar->GivValString();
PrepareFilename(filename); //DD! (si le nom a été attribué par h.filename = "..."; PrepareFilename(filename); //DD! (if the name was assigned by h.filename = "...";
// ouvre le ficher demandé // open requsted file
FILE* pFile = fopen( filename, mode ); FILE* pFile = fopen( filename, mode );
if ( pFile == NULL ) //DR if ( pFile == NULL ) //DR
{ {
pResult->SetValInt(FALSE); //DR pResult->SetValInt(false); //DR
return TRUE; //DR return true; //DR
} }
m_CompteurFileOpen ++; m_CompteurFileOpen ++;
// enregiste le canal du fichier // saves the handle of file
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
pVar->SetValInt((long)pFile); pVar->SetValInt((long)pFile);
pResult->SetValInt(TRUE); //DR pResult->SetValInt(true); //DR
return TRUE; return true;
} }
// compilation // compilation
CBotTypResult cfopen (CBotVar* pThis, CBotVar* &pVar) CBotTypResult cfopen (CBotVar* pThis, CBotVar* &pVar)
{ {
// il doit y avoir un paramètre // there must be a parameter
if ( pVar == NULL ) return CBotTypResult( CBotErrLowParam ); if ( pVar == NULL ) return CBotTypResult( CBotErrLowParam );
// qui doit être une chaine // must be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString ); return CBotTypResult( CBotErrBadString );
// il peut y avoir un second paramètre // there may be a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar != NULL ) if ( pVar != NULL )
{ {
// qui doit être une chaine // must be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString ); return CBotTypResult( CBotErrBadString );
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam ); if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam );
} }
// le résultat est de type bool // the result is of type bool
return CBotTypResult(CBotTypBoolean); //DR return CBotTypResult(CBotTypBoolean); //DR
} }
// méthode FILE :: close // FILE :: close method
// exécution // execution
BOOL rfclose (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfclose (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
// il ne doit pas y avoir de paramètre // it should not be any parameter
if ( pVar != NULL ) return CBotErrOverParam; if ( pVar != NULL ) return CBotErrOverParam;
// récupère l'élément "handle" // retrieves the element "handle"
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return FALSE; } if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return false; }
FILE* pFile= (FILE*)pVar->GivValInt(); FILE* pFile= (FILE*)pVar->GivValInt();
fclose(pFile); fclose(pFile);
@ -259,75 +261,75 @@ BOOL rfclose (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
pVar->SetInit(IS_NAN); pVar->SetInit(IS_NAN);
return TRUE; return true;
} }
// compilation // compilation
CBotTypResult cfclose (CBotVar* pThis, CBotVar* &pVar) CBotTypResult cfclose (CBotVar* pThis, CBotVar* &pVar)
{ {
// il ne doit pas y avoir de paramètre // it should not be any parameter
if ( pVar != NULL ) return CBotTypResult( CBotErrOverParam ); if ( pVar != NULL ) return CBotTypResult( CBotErrOverParam );
// la fonction retourne un résultat "void" // function returns a result "void"
return CBotTypResult( 0 ); return CBotTypResult( 0 );
} }
// méthode FILE :: writeln // FILE :: writeln method
// exécution // execution
BOOL rfwrite (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfwrite (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
// il doit y avoir un paramètre // there must be a parameter
if ( pVar == NULL ) { Exception = CBotErrLowParam; return FALSE; } if ( pVar == NULL ) { Exception = CBotErrLowParam; return false; }
// qui doit être une chaîne de caractères // must be a string
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return FALSE; } if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return false; }
CBotString param = pVar->GivValString(); CBotString param = pVar->GivValString();
// récupère l'élément "handle" //retrieves the element "handle"
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return FALSE; } if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return false; }
FILE* pFile= (FILE*)pVar->GivValInt(); FILE* pFile= (FILE*)pVar->GivValInt();
int res = fputs(param+CBotString("\n"), pFile); int res = fputs(param+CBotString("\n"), pFile);
// en cas d'erreur génère une exception // on error throws an exception
if ( res < 0 ) { Exception = CBotErrWrite; return FALSE; } if ( res < 0 ) { Exception = CBotErrWrite; return false; }
return TRUE; return true;
} }
// compilation // compilation
CBotTypResult cfwrite (CBotVar* pThis, CBotVar* &pVar) CBotTypResult cfwrite (CBotVar* pThis, CBotVar* &pVar)
{ {
// il doit y avoir un paramètre // there must be a parameter
if ( pVar == NULL ) return CBotTypResult( CBotErrLowParam ); if ( pVar == NULL ) return CBotTypResult( CBotErrLowParam );
// qui doit être une chaîne de caractères // must be a string
if ( pVar->GivType() != CBotTypString ) return CBotTypResult( CBotErrBadString ); if ( pVar->GivType() != CBotTypString ) return CBotTypResult( CBotErrBadString );
// pas d'autre paramètre // no other parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam ); if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam );
// la fonction retourne un résultat void // function returns "void" result
return CBotTypResult( 0 ); return CBotTypResult( 0 );
} }
// méthode FILE :: readln // FILE :: readln method
// exécution // execution
BOOL rfread (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfread (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
// il ne doit pas y avoir de paramètre // there shouldn't be any parameter
if ( pVar != NULL ) { Exception = CBotErrOverParam; return FALSE; } if ( pVar != NULL ) { Exception = CBotErrOverParam; return false; }
// récupère l'élément "handle" //retrieves the element "handle"
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return FALSE; } if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return false; }
FILE* pFile= (FILE*)pVar->GivValInt(); FILE* pFile= (FILE*)pVar->GivValInt();
@ -339,51 +341,51 @@ BOOL rfread (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
for ( i = 0 ; i < 2000 ; i++ ) if (chaine[i] == '\n') chaine[i] = 0; for ( i = 0 ; i < 2000 ; i++ ) if (chaine[i] == '\n') chaine[i] = 0;
// en cas d'erreur génère une exception // on error throws an exception
if ( ferror(pFile) ) { Exception = CBotErrRead; return FALSE; } if ( ferror(pFile) ) { Exception = CBotErrRead; return false; }
pResult->SetValString( chaine ); pResult->SetValString( chaine );
return TRUE; return true;
} }
// compilation // compilation
CBotTypResult cfread (CBotVar* pThis, CBotVar* &pVar) CBotTypResult cfread (CBotVar* pThis, CBotVar* &pVar)
{ {
// il ne doit pas y avoir de paramètre // there shouldn't be any parameter
if ( pVar != NULL ) return CBotTypResult( CBotErrOverParam ); if ( pVar != NULL ) return CBotTypResult( CBotErrOverParam );
// la fonction retourne un résultat "string" // function return "string" result
return CBotTypResult( CBotTypString ); return CBotTypResult( CBotTypString );
} }
// méthode FILE :: readln // FILE :: readln method
// exécution // execution
BOOL rfeof (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception) bool rfeof (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{ {
// il ne doit pas y avoir de paramètre // there shouldn't be any parameter
if ( pVar != NULL ) { Exception = CBotErrOverParam; return FALSE; } if ( pVar != NULL ) { Exception = CBotErrOverParam; return false; }
// récupère l'élément "handle" // retrieves the element "handle"
pVar = pThis->GivItem("handle"); pVar = pThis->GivItem("handle");
if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return FALSE; } if ( pVar->GivInit() != IS_DEF) { Exception = CBotErrNotOpen; return false; }
FILE* pFile= (FILE*)pVar->GivValInt(); FILE* pFile= (FILE*)pVar->GivValInt();
pResult->SetValInt( feof( pFile ) ); pResult->SetValInt( feof( pFile ) );
return TRUE; return true;
} }
// compilation // compilation
CBotTypResult cfeof (CBotVar* pThis, CBotVar* &pVar) CBotTypResult cfeof (CBotVar* pThis, CBotVar* &pVar)
{ {
// il ne doit pas y avoir de paramètre // there shouldn't be any parameter
if ( pVar != NULL ) return CBotTypResult( CBotErrOverParam ); if ( pVar != NULL ) return CBotTypResult( CBotErrOverParam );
// la fonction retourne un résultat booleen // function return boolean result
return CBotTypResult( CBotTypBoolean ); return CBotTypResult( CBotTypBoolean );
} }
@ -393,25 +395,25 @@ CBotTypResult cfeof (CBotVar* pThis, CBotVar* &pVar)
void InitClassFILE() void InitClassFILE()
{ {
// crée une classe pour la gestion des fichiers // creates a class for file management
// l'utilisation en est la suivante: // the usage is as follows:
// file canal( "NomFichier.txt" ) // file canal( "NomFichier.txt" )
// canal.open( "r" ); // ouvre en lecture // canal.open( "r" ); // open reading
// s = canal.readln( ); // lit une ligne // s = canal.readln( ); // reads a line
// canal.close(); // referme le fichier // canal.close(); // closes the file
// crée la classe FILE // create class FILE
m_pClassFILE = new CBotClass("file", NULL); m_pClassFILE = new CBotClass("file", NULL);
// ajoute le composant ".filename" // add the component ".filename"
m_pClassFILE->AddItem("filename", CBotTypString); m_pClassFILE->AddItem("filename", CBotTypString);
// ajoute le composant ".handle" // add the component ".handle"
m_pClassFILE->AddItem("handle", CBotTypInt, PR_PRIVATE); m_pClassFILE->AddItem("handle", CBotTypInt, PR_PRIVATE);
// défini un constructeur et un destructeur // define a constructor and destructor
m_pClassFILE->AddFunction("file", rfconstruct, cfconstruct ); m_pClassFILE->AddFunction("file", rfconstruct, cfconstruct );
m_pClassFILE->AddFunction("~file", rfdestruct, NULL ); m_pClassFILE->AddFunction("~file", rfdestruct, NULL );
// défini les méthodes associées // defined associated methods
m_pClassFILE->AddFunction("open", rfopen, cfopen ); m_pClassFILE->AddFunction("open", rfopen, cfopen );
m_pClassFILE->AddFunction("close", rfclose, cfclose ); m_pClassFILE->AddFunction("close", rfclose, cfclose );
m_pClassFILE->AddFunction("writeln", rfwrite, cfwrite ); m_pClassFILE->AddFunction("writeln", rfwrite, cfwrite );
@ -421,6 +423,6 @@ void InitClassFILE()
m_pFuncFile = new CBotProgram( ); m_pFuncFile = new CBotProgram( );
CBotStringArray ListFonctions; CBotStringArray ListFonctions;
m_pFuncFile->Compile( "public file openfile(string name, string mode) {return new file(name, mode);}", ListFonctions); m_pFuncFile->Compile( "public file openfile(string name, string mode) {return new file(name, mode);}", ListFonctions);
m_pFuncFile->SetIdent(-2); // identificateur spécial pour RestoreState dans cette fonction m_pFuncFile->SetIdent(-2); // restoreState as a special identifier for this function
} }

View File

@ -12,29 +12,31 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.// définition des fonctions sur les chaînes // * along with this program. If not, see http://www.gnu.org/licenses/.
// definition of string functions
// donne la longueur d'une chaîne // gives the length of a chain
// exécution // execution
BOOL rStrLen( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrLen( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// pas de second paramètre // no second parameter
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// met la longueur sur la pile // puts the length of the stack
pResult->SetValInt( s.GivLength() ); pResult->SetValInt( s.GivLength() );
return TRUE; return true;
} }
// int xxx ( string ) // int xxx ( string )
@ -42,54 +44,54 @@ BOOL rStrLen( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cIntStr( CBotVar* &pVar, void* pUser ) CBotTypResult cIntStr( CBotVar* &pVar, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADPARAM ); return CBotTypResult( TX_BADPARAM );
// pas de second paramètre // no second parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est un nombre entier // the end result is an integer
return CBotTypResult( CBotTypInt ); return CBotTypResult( CBotTypInt );
} }
// donne la partie gauche d'une chaîne // gives the left side of a chain
// exécution // execution
BOOL rStrLeft( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrLeft( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; } if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre // retrieves this number
int n = pVar->GivValInt(); int n = pVar->GivValInt();
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return true; }
// prend la partie intéressante // takes the interesting part
s = s.Left( n ); s = s.Left( n );
// la met sur la pile // puts on the stack
pResult->SetValString( s ); pResult->SetValString( s );
return TRUE; return true;
} }
// string xxx ( string, int ) // string xxx ( string, int )
@ -97,175 +99,175 @@ BOOL rStrLeft( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cStrStrInt( CBotVar* &pVar, void* pUser ) CBotTypResult cStrStrInt( CBotVar* &pVar, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING ); return CBotTypResult( TX_BADSTRING );
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) if ( pVar->GivType() > CBotTypDouble )
return CBotTypResult( TX_BADNUM ); return CBotTypResult( TX_BADNUM );
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est une string // the end result is a string
return CBotTypResult( CBotTypString ); return CBotTypResult( CBotTypString );
} }
// donne la partie droite d'une chaîne // gives the right of a string
// exécution // execution
BOOL rStrRight( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrRight( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; } if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre // retrieves this number
int n = pVar->GivValInt(); int n = pVar->GivValInt();
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return true; }
// prend la partie intéressante // takes the interesting part
s = s.Right( n ); s = s.Right( n );
// la met sur la pile // puts on the stack
pResult->SetValString( s ); pResult->SetValString( s );
return TRUE; return true;
} }
// donne la partie centrale d'une chaîne // gives the central part of a chain
// exécution // execution
BOOL rStrMid( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrMid( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; } if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre // retrieves this number
int n = pVar->GivValInt(); int n = pVar->GivValInt();
// 3e paramètre optionnel // third parameter optional
if ( pVar->GivNext() != NULL ) if ( pVar->GivNext() != NULL )
{ {
pVar = pVar->GivNext(); pVar = pVar->GivNext();
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; } if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre // retrieves this number
int l = pVar->GivValInt(); int l = pVar->GivValInt();
// mais pas de 4e paramètre // but no fourth parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
// prend la partie intéressante // takes the interesting part
s = s.Mid( n, l ); s = s.Mid( n, l );
} }
else else
{ {
// prend la partie intéressante // takes the interesting part
s = s.Mid( n ); s = s.Mid( n );
} }
// la met sur la pile // puts on the stack
pResult->SetValString( s ); pResult->SetValString( s );
return TRUE; return true;
} }
// donne la partie centrale d'une chaîne // gives the central part of a chain
// compilation // compilation
CBotTypResult cStrStrIntInt( CBotVar* &pVar, void* pUser ) CBotTypResult cStrStrIntInt( CBotVar* &pVar, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING ); return CBotTypResult( TX_BADSTRING );
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) if ( pVar->GivType() > CBotTypDouble )
return CBotTypResult( TX_BADNUM ); return CBotTypResult( TX_BADNUM );
// 3e paramètre optionnel // third parameter optional
if ( pVar->GivNext() != NULL ) if ( pVar->GivNext() != NULL )
{ {
pVar = pVar->GivNext(); pVar = pVar->GivNext();
// qui doit être un nombre // which must be a number
if ( pVar->GivType() > CBotTypDouble ) if ( pVar->GivType() > CBotTypDouble )
return CBotTypResult( TX_BADNUM ); return CBotTypResult( TX_BADNUM );
// pas de 4e paramètre // no fourth parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
} }
// le résultat final est une string // the end result is a string
return CBotTypResult( CBotTypString ); return CBotTypResult( CBotTypString );
} }
// donne le nombre contenu dans une chaîne // gives the number stored in a string
// exécution // execution
BOOL rStrVal( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrVal( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// mais pas de 2e paramètre // but no second parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
float val = GivNumFloat(s); float val = GivNumFloat(s);
// la met la valeur sur la pile // puts the value on the stack
pResult->SetValFloat( val ); pResult->SetValFloat( val );
return TRUE; return true;
} }
// float xxx ( string ) // float xxx ( string )
@ -273,53 +275,53 @@ BOOL rStrVal( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cFloatStr( CBotVar* &pVar, void* pUser ) CBotTypResult cFloatStr( CBotVar* &pVar, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING ); return CBotTypResult( TX_BADSTRING );
// pas de 2e paramètre // no second parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est un nombre // the end result is a number
return CBotTypResult( CBotTypFloat ); return CBotTypResult( CBotTypFloat );
} }
// trouve une chaine dans une autre // find string in other
// exécution // exécution
BOOL rStrFind( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrFind( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// récupère ce nombre // retrieves this number
CBotString s2 = pVar->GivValString(); CBotString s2 = pVar->GivValString();
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return true; }
// met le résultat sur la pile // puts the result on the stack
int res = s.Find(s2); int res = s.Find(s2);
pResult->SetValInt( res ); pResult->SetValInt( res );
if ( res < 0 ) pResult->SetInit( IS_NAN ); if ( res < 0 ) pResult->SetInit( IS_NAN );
return TRUE; return true;
} }
// int xxx ( string, string ) // int xxx ( string, string )
@ -327,76 +329,76 @@ BOOL rStrFind( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cIntStrStr( CBotVar* &pVar, void* pUser ) CBotTypResult cIntStrStr( CBotVar* &pVar, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING ); return CBotTypResult( TX_BADSTRING );
// il faut un second paramètre // it takes a second parameter
pVar = pVar->GivNext(); pVar = pVar->GivNext();
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING ); return CBotTypResult( TX_BADSTRING );
// pas de 3e paramètre // no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est un nombre // the end result is a number
return CBotTypResult( CBotTypInt ); return CBotTypResult( CBotTypInt );
} }
// donne une chaine en majuscule // gives a string to uppercase
// exécution // exécution
BOOL rStrUpper( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrUpper( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// mais pas de 2e paramètre // but no second parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
s.MakeUpper(); s.MakeUpper();
// la met la valeur sur la pile // puts the value on the stack
pResult->SetValString( s ); pResult->SetValString( s );
return TRUE; return true;
} }
// donne une chaine en minuscules // gives a string to lowercase
// exécution // exécution
BOOL rStrLower( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser ) bool rStrLower( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; } if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; } if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// recupére le contenu de la string // get the contents of the string
CBotString s = pVar->GivValString(); CBotString s = pVar->GivValString();
// mais pas de 2e paramètre // but no second parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; } if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
s.MakeLower(); s.MakeLower();
// la met la valeur sur la pile // puts the value on the stack
pResult->SetValString( s ); pResult->SetValString( s );
return TRUE; return true;
} }
// string xxx ( string ) // string xxx ( string )
@ -404,17 +406,17 @@ BOOL rStrLower( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cStrStr( CBotVar* &pVar, void* pUser ) CBotTypResult cStrStr( CBotVar* &pVar, void* pUser )
{ {
// il faut un paramètre // it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM ); if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string // to be a string
if ( pVar->GivType() != CBotTypString ) if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING ); return CBotTypResult( TX_BADSTRING );
// pas de 2e paramètre // no second parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM ); if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est une string // the end result is a string
return CBotTypResult( CBotTypString ); return CBotTypResult( CBotTypString );
} }

View File

@ -1,2 +0,0 @@
copy debug\cbot.dll "F:\Program Files\Ceebot\cbot.dll"
cls

View File

@ -1,49 +0,0 @@
[Directory]
scene=scene
savegame=savegame
public=program
user=user
[Setup]
TotoMode=1
Tooltips=1
InterfaceGlint=1
NiceMouse=0
Movies=1
NiceReset=1
HimselfDamage=1
CameraScroll=1
CameraInvertX=0
InterfaceEffect=1
GroundShadow=1
GroundSpot=1
ObjectDirty=1
FogMode=1
LensMode=1
SkyMode=1
PlanetMode=1
LightMode=1
UseJoystick=0
ParticuleDensity=1.00
ClippingDistance=1.00
ObjectDetail=2.00
GadgetQuantity=1.00
TextureQuality=1
AudioVolume=20
MidiVolume=15
Sound3D=0
EditIndentMode=1
EditIndentValue=4
KeyMap=37+0 39+0 38+0 40+0 16+0 17+0 32+258 96+262 13+257 107+261 109+260 9+259 36+263 27+0 112+0 113+0 110+0 115+0 116+0 117+0
[Engine]
AlphaMode=1
StateColor=-1
BlackSrcBlend=0
BlackDestBlend=0
WhiteSrcBlend=0
WhiteDestBlend=0
DiffuseSrcBlend=0
DiffuseDestBlend=0
AlphaSrcBlend=0
AlphaDestBlend=0
[Gamer]
LastName=Player

View File

@ -1,39 +1,41 @@
pour la gestion des instances d'une classe.
l'objet créé actuellement avec CBotVar::Create(nom, pClasse) for managing instances of a class.
est a conserver tel quel, en dehors des vars sur la pile
il faut un autre type de variable pour garder les pointeurs the object being created with CBotVar :: Create (name, pClasse)
CBotTypPtClass par exemple is to keep as is, outside the vars on the stack
L'instance de la classe doit avoir un compteur d'utilisation we need another type of variable to keep the pointers
qui est le nombre d'objet de classe CBotTypPtClass qui y réfèrent. For example CBotTypPtClass
Le compteur est décrémenté lorsque le pointeur est détruit,
l'objet supprimé lorsqu'il n'y a plus de pointeurs. The instance of the class must have a usage count
which is the number of class object to which they refer CBotTypPtClass.
The counter is decremented when the pointer is destroyed,
be deleted when there is more pointers.
Dans le cas des robots, Daniel crée une instance de sa classe "Object" In the case of robots, Daniel creates an instance of class "Object"
et peut retourner des pointeurs à cette instance par des routines genre FindRobot() and can return pointers to this proceeding by routines such FindRobot ()
Object FindRobot (int n) {} Object FindRobot (int n) {}
pResult dans ce cas est un pointeur CBotTypPtClass pResult in this case is a pointer CBotTypPtClass
lorsqu'il a trouvé le robot concerné, il lui faudra faire when he found the robot concerned, it must make
pResult-> SetPointeur (InstanceDeLaClassObject); pResult-> SetPointeur (InstanceDeLaClassObject);
cette opération incrémente le compteur des références this operation increments the reference
-- -
lorsque le robot est détruit, l'instance de la classe Object correspondant when the robot is destroyed, the instance of the Object class corresponding
est détruit également. is also destroyed.
s'il reste des pointeurs à cet objet, et l'on risque la planté if there are pointers to that object, and we planted the risk
solution 1: Solution 1:
garder non pas le pointeur à l'objet directement, mais not keep the pointer to the object directly, but
un index dans une tables de pointeurs an index into a table of pointers
Solution 2:
not destroy the object when there imédiatement pointers
but marked as virtually destroyed
solution 2:
ne pas détruire l'objet imédiatement lorsqu'il reste des pointeurs
mais le marqué comme virtuellement détruit

View File

@ -1,15 +0,0 @@
// * This file is part of the COLOBOT source code
// * Copyright (C) 2001-2008, Daniel ROUX & EPSITEC SA, www.epsitec.ch
// *
// * This program is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.

View File

@ -12,101 +12,108 @@
// * GNU General Public License for more details. // * GNU General Public License for more details.
// * // *
// * You should have received a copy of the GNU General Public License // * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.//{{NO_DEPENDENCIES}} // * along with this program. If not, see http://www.gnu.org/licenses/.
// Microsoft Developer Studio generated include file.
// Used by CBot.rc #pragma once
// #ifndef _RESOURCE_H_
#define ID_KEYWORDS 2000 #define _RESOURCE_H_
#define ID_IF 2000
#define ID_ELSE 2001 enum EID
#define ID_WHILE 2002 {
#define ID_DO 2003 ID_IF = 2000,
#define ID_FOR 2004 ID_ELSE,
#define ID_BREAK 2005 ID_WHILE,
#define ID_CONTINUE 2006 ID_DO,
#define ID_SWITCH 2007 ID_FOR,
#define ID_CASE 2008 ID_BREAK,
#define ID_DEFAULT 2009 ID_CONTINUE,
#define ID_TRY 2010 ID_SWITCH,
#define ID_THROW 2011 ID_CASE,
#define ID_CATCH 2012 ID_DEFAULT,
#define ID_FINALLY 2013 ID_TRY,
#define ID_TXT_AND 2014 ID_THROW,
#define ID_TXT_OR 2015 ID_CATCH,
#define ID_TXT_NOT 2016 ID_FINALLY,
#define ID_RETURN 2017 ID_TXT_AND,
#define ID_CLASS 2018 ID_TXT_OR,
#define ID_EXTENDS 2019 ID_TXT_NOT,
#define ID_SYNCHO 2020 ID_RETURN,
#define ID_NEW 2021 ID_CLASS,
#define ID_PUBLIC 2022 ID_EXTENDS,
#define ID_EXTERN 2023 ID_SYNCHO,
#define ID_FINAL 2024 ID_NEW,
#define ID_STATIC 2025 ID_PUBLIC,
#define ID_PROTECTED 2026 ID_EXTERN,
#define ID_PRIVATE 2027 ID_FINAL,
#define ID_REPEAT 2028 ID_STATIC,
#define ID_DEBUGDD 2099 ID_PROTECTED,
#define ID_INT 2100 ID_PRIVATE,
#define ID_FLOAT 2101 ID_REPEAT,
#define ID_BOOLEAN 2102 ID_DEBUGDD,
#define ID_STRING 2103 ID_INT,
#define ID_VOID 2104 ID_FLOAT,
#define ID_BOOL 2105 ID_BOOLEAN,
#define ID_TRUE 2200 ID_STRING,
#define ID_FALSE 2201 ID_VOID,
#define ID_NULL 2202 ID_BOOL,
#define ID_NAN 2203
#define ID_OPENPAR 2300 ID_TRUE = 2200,
#define ID_CLOSEPAR 2301 ID_FALSE,
#define ID_OPBLK 2302 ID_NULL,
#define ID_CLBLK 2303 ID_NAN,
#define ID_SEP 2304
#define ID_COMMA 2305 ID_OPENPAR = 2300,
#define ID_DOTS 2306 ID_CLOSEPAR,
#define ID_DOT 2307 ID_OPBLK,
#define ID_OPBRK 2308 ID_CLBLK,
#define ID_CLBRK 2309 ID_SEP,
#define ID_DBLDOTS 2310 ID_COMMA,
#define ID_LOGIC 2311 ID_DOTS,
#define ID_ADD 2312 ID_DOT,
#define ID_SUB 2313 ID_OPBRK,
#define ID_MUL 2314 ID_CLBRK,
#define ID_DIV 2315 ID_DBLDOTS,
#define ID_ASS 2316 ID_LOGIC,
#define ID_ASSADD 2317 ID_ADD,
#define ID_ASSSUB 2318 ID_SUB,
#define ID_ASSMUL 2319 ID_MUL,
#define ID_ASSDIV 2320 ID_DIV,
#define ID_ASSOR 2321 ID_ASS,
#define ID_ASSAND 2322 ID_ASSADD,
#define ID_ASSXOR 2323 ID_ASSSUB,
#define ID_ASSSL 2324 ID_ASSMUL,
#define ID_ASSSR 2325 ID_ASSDIV,
#define ID_ASSASR 2326 ID_ASSOR,
#define ID_SL 2327 ID_ASSAND,
#define ID_SR 2328 ID_ASSXOR,
#define ID_ASR 2329 ID_ASSSL,
#define ID_INC 2330 ID_ASSSR,
#define ID_DEC 2331 ID_ASSASR,
#define ID_LO 2332 ID_SL,
#define ID_HI 2333 ID_SR,
#define ID_LS 2334 ID_ASR,
#define ID_HS 2335 ID_INC,
#define ID_EQ 2336 ID_DEC,
#define ID_NE 2337 ID_LO,
#define ID_AND 2338 ID_HI,
#define ID_XOR 2339 ID_LS,
#define ID_OR 2340 ID_HS,
#define ID_LOG_AND 2341 ID_EQ,
#define ID_LOG_OR 2342 ID_NE,
#define ID_LOG_NOT 2343 ID_AND,
#define ID_NOT 2344 ID_XOR,
#define ID_MODULO 2345 ID_OR,
#define ID_POWER 2346 ID_LOG_AND,
#define ID_ASSMODULO 2347 ID_LOG_OR,
#define TX_UNDEF 4000 ID_LOG_NOT,
#define TX_NAN 4001 ID_NOT,
ID_MODULO,
ID_POWER,
ID_ASSMODULO,
TX_UNDEF = 4000,
TX_NAN,
ID_SUPER = 6000
};
#define TX_OPENPAR 5000 #define TX_OPENPAR 5000
#define TX_CLOSEPAR 5001 #define TX_CLOSEPAR 5001
#define TX_NOTBOOL 5002 #define TX_NOTBOOL 5002
@ -166,15 +173,5 @@
#define TX_NOTOPEN 6013 #define TX_NOTOPEN 6013
#define TX_ERRREAD 6014 #define TX_ERRREAD 6014
#define TX_ERRWRITE 6015 #define TX_ERRWRITE 6015
#define ID_SUPER 62020
// Next default values for new objects #endif //_RESOURCE_H_
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1,96 @@
object radarGuepe(point orig, float dist)
{
int i;
object pr, r;
float mindist;
i = 0;
mindist = 1000;
while (i<30)
{
pr = radar(i);
if (pr != null)
{
if (F(orig, pr.position) < mindist and pr.category == AlienWasp and pr.altitude > 3)
{
mindist = distance(orig, pr.position);
r = pr;
}
}
i = i+1;
}
if (mindist < dist) return(r); else return(null);
}
class Guepe
{
point pos;
void cherche(point orig, float dist)
{
object p;
point o;
p = radarGuepe(orig, dist);
while (p == null)
{
wait(0.1);
p = radarGuepe(orig, dist);
}
pos.x = p.position.x;
pos.y = p.position.y;
pos.z = p.position.z;
//o = p.position;
//wait(0.1);
//vitessex = (p.position.x - o.x)/0.1;
//vitessey = (p.position.y - o.y)/0.1;
//vitessez = (p.position.z - o.z)/0.1;
}
void tire(point orig, float orient)
{
//float t = 3; //temps d'anticipation
float angle;
point cible;
cible.x = pos.x;// + t*vitessex;
cible.y = pos.y;// + t*vitessey;
cible.z = pos.z;// + t*vitessez;
if (cible.x == 0) angle = 90; else
angle = atan(cible.y / cible.x);
if (cible.x < 0) angle = angle + 180;
angle = angle - orient;
if (angle > 180) angle = angle - 360;
if (angle < -180) angle = angle + 360;
turn(angle);
angle = atan((cible.z-orig.z) / distance2d(orig, cible));
aim(angle);
fire(0.1);
}
}
extern void object::Fourmi6()
{
//fps(1000);
Guepe guepe = new Guepe();
while (true)
{
guepe.cherche(position, 50);
guepe.tire(position, orientation);
}
}

View File

@ -0,0 +1,96 @@
object radarGuepe(point orig, float dist)
{
int i;
object pr, r;
float mindist;
i = 0;
mindist = 1000;
while (i<30)
{
pr = radar(i);
if (pr != null)
{
if (F(orig, pr.position) < mindist and pr.category == AlienWasp and pr.altitude > 3)
{
mindist = distance(orig, pr.position);
r = pr;
}
}
i = i+1;
}
if (mindist < dist) return(r); else return(null);
}
class Guepe
{
point pos;
void cherche(point orig, float dist)
{
object p;
point o;
p = radarGuepe(orig, dist);
while (p == null)
{
wait(0.1);
p = radarGuepe(orig, dist);
}
pos.x = p.position.x;
pos.y = p.position.y;
pos.z = p.position.z;
//o = p.position;
//wait(0.1);
//vitessex = (p.position.x - o.x)/0.1;
//vitessey = (p.position.y - o.y)/0.1;
//vitessez = (p.position.z - o.z)/0.1;
}
void tire(point orig, float orient)
{
//float t = 3; //temps d'anticipation
float angle;
point cible;
cible.x = pos.x;// + t*vitessex;
cible.y = pos.y;// + t*vitessey;
cible.z = pos.z;// + t*vitessez;
if (cible.x == 0) angle = 90; else
angle = atan(cible.y / cible.x);
if (cible.x < 0) angle = angle + 180;
angle = angle - orient;
if (angle > 180) angle = angle - 360;
if (angle < -180) angle = angle + 360;
turn(angle);
angle = atan((cible.z-orig.z) / distance2d(orig, cible));
aim(angle);
fire(0.1);
}
}
extern void object::Fourmi6()
{
//fps(1000);
Guepe guepe = new Guepe();
while (true)
{
guepe.cherche(position, 50);
guepe.tire(position, orientation);
}
}

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