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)
# Required packages
find_package(OpenGL REQUIRED)
find_package(SDL REQUIRED)
find_package(SDL_image REQUIRED)
find_package(OpenGL 1.4 REQUIRED)
find_package(SDL 1.2.10 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
set(CMAKE_BUILD_TYPE debug)
# Global compile flags
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
set(CMAKE_CXX_FLAGS_DEBUG "-w -g -O0")
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -Wall -Wold-style-cast -std=gnu++0x")
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
add_subdirectory(src bin)

View File

@ -690,8 +690,7 @@ INPUT_ENCODING = UTF-8
# *.f90 *.f *.for *.vhd *.vhdl
FILE_PATTERNS = *.h \
*.cpp \
*.doc.txt
*.cpp
# 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.

133
HOWTO.txt
View File

@ -1,77 +1,104 @@
EN
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:
http://dl.dropbox.com/u/32866936/dx81sdk_full.exe
2. Download and install MinGW and MSYS:
1.1 Windows:
1. Download and install MinGW and MSYS:
http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/
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)
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
(the slashes must be in this form: /, not \).
5. Run MinGW console from the shortcut in menu start.
6. Change to the directory where you have the Colobot sources by typing "cd /c/where/the/sources/are"
7. Type "cmake -G 'MSYS Makefiles' ."
8. Type "make"
9. Everything should compile without errors.
3. Download the following libraries, installing them in your MinGW directory like with CMake:
SDL >=1.2.10, SDL_imgage >= 1.2, SDL_ttf >= 2.0, libpng >= 1.2, GLEW >= 1.8.0
Note #1: For most libraries, you can download binary packages with compiled files.
However, you must ensure that they work with MinGW as some are built with MSVC
and may be incompatible. If that is the case, you should compile the libraries from sources
using MinGW.
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.
1. Download and unpack the package with the game data files.
2. Copy the compiled files from bin/colobot.exe, bin/CBot/libCBot.dll
and from the directory, where MinGW is installed bin/libgcc_s_dw2-1.dll and bin/libstdc++-6.dll
to the directory with game data (there should be several files named colobot*.dat).
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.
1. Download development data package - make sure you get the latest version as the files will be changed/moved around.
Currently the files are hosted at: http://colobot.info/files (packages are named colobot-data-YYYY-MM-DD.zip)
2. Unpack the data package to any place you want.
3. Run the game with commandline option "-datadir where_you_put_the_data_dir" and enjoy the game.
PL
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:
http://dl.dropbox.com/u/32866936/dx81sdk_full.exe
2. Ściągamy i instalujemy MinGW i MSYS:
1.1 Windows:
1. Ściągamy i instalujemy MinGW i MSYS:
http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/
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)
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)
(slashe mają być właśnie w takiej postaci: / a nie \).
5. Uruchamiamy MinGW console ze skrótu w menu start.
6. Przechodzimy do katalogu, gdzie są źródła wpisując "cd /c/tam/gdzie/sa/zrodla"
7. Wpisujemy "cmake -G 'MSYS Makefiles' ."
8. Wpisujemy "make"
9. Wszystko powinno się skomplikować bez błędów.
3. Ścągamy następujące biblioteki i instalujemy je tam, gdzie MinGW, podobnie jak z CMake:
SDL >= 1.2.10, SDL_image >= 1.2, SDL_ttf >= 2.0, libpng >= 1.2
Uwaga #1: W większości wymienionych bibliotek można ściągnąć paczki binarne ze skompilowanymi plikami.
Jednak musisz się upewnić, że pliki te będą współpracowały z MinGW, bo część z nich
jest kompilowana MSVC i może być niezgodna. W takim wypadku, musisz skompilować bibliotekę
ze źródeł pod MinGW.
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ę.
1. Ściągamy paczkę z plikami danych gry.
2. Kopiujemy skompilowane pliki bin/colobot.exe, bin/CBot/libCBot.dll
i z katalogu, gdzie jest zainstalowany MinGW bin/libgcc_s_dw2-1.dll i bin/libstdc++-6.dll
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ę.
1. Ściągamy paczkę developerską z plikami danych gry - upewnij się, że jest to najnowsza wersja, bo pliki będą zmieniane/przenoszone.
2. Wypakowujemy pliki gdziekolwiek.
3. Uruchamiamy grę wraz z opcją "-datadir tam_gdzie_rozpakowałeś_paczkę" i cieszymy się 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
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
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
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
@ -16,4 +32,38 @@ For these instructions see HOWTO.txt file.
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.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.///////////////////////////////////////////////////
// expression du genre Opérande1 + Opérande2
// Opérande1 - Opérande2
// * along with this program. If not, see http://www.gnu.org/licenses/.
///////////////////////////////////////////////////
// expressions of type Operand1 + Operand2
// Operand1 - Operand2
#include "CBot.h"
// divers constructeurs
// various constructors
CBotAddExpr::CBotAddExpr()
{
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
}
@ -38,105 +40,105 @@ CBotAddExpr::~CBotAddExpr()
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
if (left == NULL) return pStack->Return(NULL, pStk); // si erreur, la transmet
CBotInstr* left = CBotMulExpr::Compile( p, pStk ); // expression A * B left
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 ||
p->GetType() == ID_SUB) // plus ou moins
p->GetType() == ID_SUB) // more or less
{
CBotAddExpr* inst = new CBotAddExpr(); // élément pour opération
inst->SetToken(p); // mémorise l'opération
CBotAddExpr* inst = new CBotAddExpr(); // element for operation
inst->SetToken(p); // stores the operation
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;
// et rend l'object à qui l'a demandé
// and makes the object on demand
return pStack->Return(inst, pStk);
}
}
// en cas d'erreur, libère les éléments
// in case of error, free the elements
delete left;
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);
}
// si on n'a pas affaire à une opération + ou -
// rend à qui l'a demandé, l'opérande (de gauche) trouvé
// à la place de l'objet "addition"
// if we are not dealing with an operation + or -
// goes to that requested, the operand (left) found
// place the object "addition"
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
// ou le retrouve en cas de reprise
CBotStack* pStk1 = pStack->AddStack(this); // adds an item to the stack
// or is found in case of recovery
// 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
!m_leftop->Execute(pStk1) ) return FALSE; // interrompu ici ?
if ( pStk1->GetState() == 0 && // first state, evaluates the left operand
!m_leftop->Execute(pStk1) ) return FALSE; // interrupted here?
// passe à l'étape suivante
pStk1->SetState(1); // prêt pour la suite
// passes to the next step
pStk1->SetState(1); // ready for further
// demande un peu plus de stack pour ne pas toucher le résultat de gauche
// qui se trouve sur la pile, justement.
// requires a little more stack to not touch the result of the left
// which is on the stack, precisely.
CBotStack* pStk2 = pStk1->AddStack(); // ajoute un élément à la pile
// ou le retrouve en cas de reprise
CBotStack* pStk2 = pStk1->AddStack(); // adds an item to the stack
// or is found in case of recovery
// 2e état, évalue l'opérande de droite
if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrompu ici ?
// Second state, evaluates the right operand
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();
// 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));
// fait l'opération selon la demande
// is the operation as requested
switch (GetTokenType())
{
case ID_ADD:
result->Add(pStk1->GetVar(), pStk2->GetVar()); // additionne
result->Add(pStk1->GetVar(), pStk2->GetVar()); // addition
break;
case ID_SUB:
result->Sub(pStk1->GetVar(), pStk2->GetVar()); // soustrait
result->Sub(pStk1->GetVar(), pStk2->GetVar()); // subtraction
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
return pStack->Return(pStk1); // transmet le résultat
pStk1->Return(pStk2); // frees the stack
return pStack->Return(pStk1); // transmits the result
}

View File

@ -12,8 +12,10 @@
// * 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/.///////////////////////////////////////////////////////////////////////
// Gestion des variables de type classe
// * along with this program. If not, see http://www.gnu.org/licenses/.//
/////////////////////////////////////////////////////////////////////
// Management of variables of class type
//
#include "CBot.h"
@ -21,7 +23,7 @@
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_name = name;
@ -30,7 +32,7 @@ CBotClass::CBotClass(const char* name, CBotClass* pPapa, BOOL bIntrinsic)
m_pCalls = NULL;
m_pMethod = NULL;
m_rMaj = NULL;
m_IsDef = TRUE;
m_IsDef = true;
m_bIntrinsic= bIntrinsic;
m_cptLock = 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;
m_ExNext = m_ExClass;
m_ExPrev = NULL;
@ -52,7 +54,7 @@ CBotClass::CBotClass(const char* name, CBotClass* pPapa, BOOL bIntrinsic)
CBotClass::~CBotClass()
{
// retire la classe de la liste
// removes the list of class
if ( m_ExPrev ) m_ExPrev->m_ExNext = m_ExNext;
else m_ExClass = m_ExNext;
@ -64,7 +66,7 @@ CBotClass::~CBotClass()
delete m_pCalls;
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;
delete m_pMethod;
m_pMethod = NULL;
m_IsDef = FALSE;
m_IsDef = false;
m_nbVar = m_pParent == NULL ? 0 : m_pParent->m_nbVar;
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++;
@ -102,13 +104,13 @@ BOOL CBotClass::Lock(CBotProgram* p)
{
m_cptOne = 1;
m_ProgInLock[0] = p;
return TRUE;
return true;
}
if ( p == m_ProgInLock[0] )
{
m_cptOne++;
m_cptLock--; // a déjà été compté
return TRUE;
m_cptLock--; // has already been counted
return true;
}
for ( int j = 1 ; j <= i ; j++)
@ -116,18 +118,18 @@ BOOL CBotClass::Lock(CBotProgram* p)
if ( p == m_ProgInLock[j] )
{
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
m_cptLock--;
return FALSE;
return false;
}
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());
CBotClass* pClass = type.GivClass();
@ -184,7 +186,7 @@ BOOL CBotClass::AddItem(CBotString name, CBotTypResult type, int mPrivate)
// pVar->SetClass(pClass);
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() ;
CBotToken nom( pClass->GivName() );
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);
if ( m_pVar == NULL ) m_pVar = pVar;
else m_pVar->AddNext(pVar);
return TRUE;
return true;
}
void CBotClass::AddNext(CBotClass* pClass)
@ -223,15 +225,15 @@ CBotClass* CBotClass::GivParent()
return m_pParent;
}
BOOL CBotClass::IsChildOf(CBotClass* pClass)
bool CBotClass::IsChildOf(CBotClass* pClass)
{
CBotClass* p = this;
while ( p != NULL )
{
if ( p == pClass ) return TRUE;
if ( p == pClass ) return true;
p = p->m_pParent;
}
return FALSE;
return false;
}
@ -266,7 +268,7 @@ CBotVar* CBotClass::GivItemRef(int nIdent)
return NULL;
}
BOOL CBotClass::IsIntrinsic()
bool CBotClass::IsIntrinsic()
{
return m_bIntrinsic;
}
@ -289,11 +291,11 @@ CBotClass* CBotClass::Find(const char* name)
return NULL;
}
BOOL CBotClass::AddFunction(const char* name,
BOOL rExec (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception),
bool CBotClass::AddFunction(const char* name,
bool rExec (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception),
CBotTypResult rCompile (CBotVar* pThis, CBotVar* &pVar))
{
// mémorise les pointeurs aux deux fonctions
// stores pointers to the two functions
CBotCallMethode* p = m_pCalls;
CBotCallMethode* pp = NULL;
@ -313,32 +315,32 @@ BOOL CBotClass::AddFunction(const char* name,
p = new CBotCallMethode(name, rExec, rCompile);
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;
return TRUE;
return true;
}
// compile une méthode associée à une instance de classe
// la méthode peut être déclarée par AddFunction ou par l'utilisateur
// compiles a method associated with an instance of class
// the method can be declared by the user or AddFunction
CBotTypResult CBotClass::CompileMethode(const char* name,
CBotVar* pThis, CBotVar** ppParams,
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);
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);
if ( r.Eq(TX_UNDEFCALL) && m_pParent != NULL )
@ -346,9 +348,9 @@ CBotTypResult CBotClass::CompileMethode(const char* name,
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* &pResult, CBotStack* &pStack,
CBotToken* pToken)
@ -360,7 +362,7 @@ BOOL CBotClass::ExecuteMethode(long& nIdent, const char* name,
return ret;
}
// rétabli la pile d'exécution
// restored the execution stack
void CBotClass::RestoreMethode(long& nIdent, const char* name, CBotVar* pThis,
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;
while ( p != NULL )
{
if (!WriteWord( pf, 1)) return FALSE;
// enregistre le nom de la classe
if (!WriteString( pf, p->GivName() )) return FALSE;
if (!WriteWord( pf, 1)) return false;
// save the name of the class
if (!WriteString( pf, p->GivName() )) return false;
CBotVar* pv = p->GivVar();
while( pv != NULL )
{
if ( pv->IsStatic() )
{
if (!WriteWord( pf, 1)) return FALSE;
if (!WriteString( pf, pv->GivName() )) return FALSE;
if (!WriteWord( pf, 1)) return false;
if (!WriteString( pf, pv->GivName() )) return false;
if ( !pv->Save0State(pf)) return FALSE; // entête commune
if ( !pv->Save1State(pf) ) return FALSE; // sauve selon la classe fille
if ( !WriteWord( pf, 0)) return FALSE;
if ( !pv->Save0State(pf)) return false; // common header
if ( !pv->Save1State(pf) ) return false; // saves as the child class
if ( !WriteWord( pf, 0)) return false;
}
pv = pv->GivNext();
}
if (!WriteWord( pf, 0)) return FALSE;
if (!WriteWord( pf, 0)) return false;
p = p->m_ExNext;
}
if (!WriteWord( pf, 0)) return FALSE;
return TRUE;
if (!WriteWord( pf, 0)) return false;
return true;
}
BOOL CBotClass::RestoreStaticState(FILE* pf)
bool CBotClass::RestoreStaticState(FILE* pf)
{
CBotString ClassName, VarName;
CBotClass* pClass;
WORD w;
unsigned short w;
if (!ReadWord( pf, w )) return FALSE;
if ( w != CBOTVERSION*2 ) return FALSE;
if (!ReadWord( pf, w )) return false;
if ( w != CBOTVERSION*2 ) return false;
while (TRUE)
while (true)
{
if (!ReadWord( pf, w )) return FALSE;
if ( w == 0 ) return TRUE;
if (!ReadWord( pf, w )) return false;
if ( w == 0 ) return true;
if (!ReadString( pf, ClassName )) return FALSE;
if (!ReadString( pf, ClassName )) return false;
pClass = Find(ClassName);
while (TRUE)
while (true)
{
if (!ReadWord( pf, w )) return FALSE;
if (!ReadWord( pf, w )) return false;
if ( w == 0 ) break;
CBotVar* pVar = NULL;
CBotVar* pv = NULL;
if (!ReadString( pf, VarName )) return FALSE;
if (!ReadString( pf, VarName )) return false;
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);
delete pv;
}
}
return TRUE;
return true;
}
@ -453,7 +455,7 @@ CBotClassInst::CBotClassInst()
m_var = NULL;
m_Parameters = NULL;
m_expr = NULL;
m_hasParams = FALSE;
m_hasParams = false;
m_nMethodeIdent = 0;
name = "CBotClassInst";
}
@ -461,59 +463,58 @@ CBotClassInst::CBotClassInst()
CBotClassInst::~CBotClassInst()
{
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
// du style
// definition of pointer (s) to an object
// style
// CPoint A, B ;
CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass* pClass)
{
// cherche la classe correspondante
// seeks the corresponding classes
if ( pClass == NULL )
{
pStack->SetStartError(p->GivStart());
pClass = CBotClass::Find(p);
if ( pClass == NULL )
{
// pas trouvé ? c'est bizare
// not found? is bizare
pStack->SetError(TX_NOCLASS, p);
return NULL;
}
p = p->GivNext();
}
BOOL bIntrinsic = pClass->IsIntrinsic();
CBotTypResult
type = CBotTypResult( bIntrinsic ? CBotTypIntrinsic : CBotTypPointer,
pClass );
bool bIntrinsic = pClass->IsIntrinsic();
CBotTypResult type = CBotTypResult( bIntrinsic ? CBotTypIntrinsic : CBotTypPointer, pClass );
CBotClassInst* inst = (CBotClassInst*)CompileArray(p, pStack, type);
if ( inst != NULL || !pStack->IsOk() ) return inst;
CBotCStack* pStk = pStack->TokenStack();
inst = new CBotClassInst();
inst->SetToken(&pClass->GivName(), p->GivStart(), p->GivEnd());
/// \TODO Need to be revised and fixed after adding unit tests
CBotToken token(pClass->GivName(), CBotString(), p->GivStart(), p->GivEnd());
inst->SetToken(&token);
CBotToken* vartoken = p;
if ( NULL != (inst->m_var = CBotLeftExprVar::Compile( p, pStk )) )
{
((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->SetError(TX_REDEFVAR, vartoken->GivEnd());
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
p = vartoken; // revient sur le nom de la variable
delete inst; // is not type CBotInt
p = vartoken; // returns to the variable name
// compile une déclaration de tableau
// compiles declaration an array
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());
goto error;
}
goto suite; // pas d'assignation, variable déjà créée
goto suite; // no assignment, variable already created
}
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->SetUniqNum(
((CBotLeftExprVar*)inst->m_var)->m_nIdent = CBotVar::NextUniqNum());
// lui attribut un numéro unique
pStack->AddVar(var); // la place sur la pile
// its attribute a unique number
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);
CBotVar* ppVars[1000];
inst->m_Parameters = CompileParams(p, pStk, ppVars);
if ( !pStk->IsOk() ) goto error;
// s'il y a des paramètres, fait l'équivalent de l'instruction new
// CPoint A ( 0, 0 ) est équivalent à
// if there are parameters, is the equivalent to the stament "new"
// CPoint A ( 0, 0 ) is equivalent to
// CPoint A = new CPoint( 0, 0 )
// if ( NULL != inst->m_Parameters )
if ( inst->m_hasParams )
{
// le constructeur existe-il ?
// the constructor is there?
// CBotString noname;
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();
if (typ == TX_UNDEFCALL)
{
// 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);
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)
{
@ -596,35 +597,35 @@ CBotInstr* CBotClassInst::Compile(CBotToken* &p, CBotCStack* pStack, CBotClass*
// if ( !bIntrinsic ) var->SetPointer(pStk->GivVar()->GivPointer());
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);
var->SetPointer( pvar ); // var déjà déclarée pointe l'instance
delete pvar; // supprime le second pointeur
var->SetPointer( pvar ); // variable already declared instance pointer
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)
{
// crée l'objet sur le "tas"
// avec un pointeur sur cet objet
// creates the object on the "job" (\TODO "tas")
// with a pointer to the object
if ( !bIntrinsic )
{
CBotVar* pvar = CBotVar::Create("", pClass);
var->SetPointer( pvar ); // var déjà déclarée pointe l'instance
delete pvar; // supprime le second pointeur
var->SetPointer( pvar ); // variable already declared instance pointer
delete pvar; // removes the second pointer
}
var->SetInit(2); // marque le pointeur comme init
var->SetInit(2); // marks the pointer as init
}
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);
}
}
if (IsOfType(p, ID_SEP)) // instruction terminée
if (IsOfType(p, ID_SEP)) // complete instruction
{
return pStack->Return(inst, pStk);
}
@ -637,22 +638,22 @@ error:
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;
BOOL CBotClassInst::Execute(CBotStack* &pj)
bool CBotClassInst::Execute(CBotStack* &pj)
{
CBotVar* pThis = NULL;
CBotStack* pile = pj->AddStack(this);//indispensable pour SetState()
// if ( pile == EOX ) return TRUE;
CBotStack* pile = pj->AddStack(this);//essential for SetState()
// if ( pile == EOX ) return true;
CBotToken* pt = &m_token;
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)
{
@ -666,8 +667,8 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
pThis = CBotVar::Create(name, CBotTypResult( CBotTypPointer, pClass ));
}
pThis->SetUniqNum(((CBotLeftExprVar*)m_var)->m_nIdent); // lui attribut un numéro unique
pile->AddVar(pThis); // la place sur la pile
pThis->SetUniqNum(((CBotLeftExprVar*)m_var)->m_nIdent); // its attribute as unique number
pile->AddVar(pThis); // place on the stack
pile->IncState();
}
@ -675,14 +676,14 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
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;
if ( m_expr != NULL )
{
// évalue l'expression pour l'assignation
if (!m_expr->Execute(pile)) return FALSE;
// evaluates the expression for the assignment
if (!m_expr->Execute(pile)) return false;
if ( bIntrincic )
{
@ -692,27 +693,27 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
pile->SetError(TX_NULLPT, &m_token);
return pj->Return(pile);
}
pThis->Copy(pile->GivVar(), FALSE);
pThis->Copy(pile->GivVar(), false);
}
else
{
CBotVarClass* pInstance;
pInstance = ((CBotVarPointer*)pile->GivVar())->GivPointer(); // valeur pour l'assignation
pInstance = ((CBotVarPointer*)pile->GivVar())->GivPointer(); // value for the assignment
pThis->SetPointer(pInstance);
}
pThis->SetInit(TRUE);
pThis->SetInit(true);
}
else if ( m_hasParams )
{
// évalue le constructeur d'une instance
// evaluates the constructor of an instance
if ( !bIntrincic && pile->GivState() == 1)
{
CBotToken* pt = &m_token;
CBotClass* pClass = CBotClass::Find(pt);
// crée une instance de la classe demandée
// creates an instance of the requested class
CBotVarClass* pInstance;
pInstance = (CBotVarClass*)CBotVar::Create("", pClass);
@ -728,16 +729,16 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
int i = 0;
CBotInstr* p = m_Parameters;
// évalue les paramètres
// et place les valeurs sur la pile
// pour pouvoir être interrompu n'importe quand
// evaluates the parameters
// and places the values on the stack
// 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 (!p->Execute(pile2)) return FALSE; // interrompu ici ?
if (!p->Execute(pile2)) return false; // interrupted here?
pile2->SetState(1);
}
ppVars[i++] = pile2->GivVar();
@ -746,37 +747,37 @@ BOOL CBotClassInst::Execute(CBotStack* &pj)
}
ppVars[i] = NULL;
// crée une variable pour le résultat
CBotVar* pResult = NULL; // constructeurs toujours void
// creates a variable for the result
CBotVar* pResult = NULL; // constructor still void
if ( !pClass->ExecuteMethode(m_nMethodeIdent, pClass->GivName(),
pThis, ppVars,
pResult, pile2, GivToken())) return FALSE; // interrompu
pResult, pile2, GivToken())) return false; // interrupt
pThis->SetInit(TRUE);
pThis->ConstructorSet(); // signale que le constructeur a été appelé
pile->Return(pile2); // libère un bout de pile
pThis->SetInit(true);
pThis->ConstructorSet(); // indicates that the constructor has been called
pile->Return(pile2); // releases a piece of stack
// 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 &&
!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;
@ -784,33 +785,33 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
if ( bMain ) pile = pj->RestoreStack(this);
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();
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;
CBotClass* pClass = CBotClass::Find(pt);
BOOL bIntrincic = pClass->IsIntrinsic();
bool bIntrincic = pClass->IsIntrinsic();
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;
if ( m_expr != NULL )
{
// évalue l'expression pour l'assignation
// evaluates the expression for the assignment
m_expr->RestoreState(pile, bMain);
return;
}
else if ( m_hasParams )
{
// évalue le constructeur d'une instance
// evaluates the constructor of an instance
if ( !bIntrincic && pile->GivState() == 1)
{
@ -823,18 +824,18 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
int i = 0;
CBotInstr* p = m_Parameters;
// évalue les paramètres
// et place les valeurs sur la pile
// pour pouvoir être interrompu n'importe quand
// evaluates the parameters
// and the values an the stack
// 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->GivState() == 0 )
{
p->RestoreState(pile2, bMain); // interrompu ici ?
p->RestoreState(pile2, bMain); // interrupted here?
return;
}
ppVars[i++] = pile2->GivVar();
@ -843,8 +844,8 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
}
ppVars[i] = NULL;
// crée une variable pour le résultat
CBotVar* pResult = NULL; // constructeurs toujours void
// creates a variable for the result
CBotVar* pResult = NULL; // constructor still void
pClass->RestoreMethode(m_nMethodeIdent, pClass->GivName(), pThis, ppVars, pile2);
return;
@ -852,30 +853,30 @@ void CBotClassInst::RestoreState(CBotStack* &pj, BOOL bMain)
}
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();
if ( CBotCall::CheckCall(name) ) return TRUE;
if ( CBotCall::CheckCall(name) ) return true;
CBotFunction* pp = m_pMethod;
while ( pp != NULL )
{
if ( pToken->GivString() == pp->GivName() )
{
// les paramètres sont-ils exactement les mêmes ?
// are their parameters exactly the same?
if ( pp->CheckParam( pParam ) )
return TRUE;
return true;
}
pp = pp->Next();
}
return FALSE;
return false;
}

View File

@ -12,14 +12,16 @@
// * 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/.///////////////////////////////////////////////////
// expression du genre Opérande1 > Opérande2
// Opérande1 != Opérande2
// * along with this program. If not, see http://www.gnu.org/licenses/.
///////////////////////////////////////////////////
// expression of type Opérande1 > Opérande2
// Opérande1 != Opérande2
// etc.
#include "CBot.h"
// divers constructeurs
// various constructeurs
CBotCompExpr::CBotCompExpr()
{
@ -36,38 +38,38 @@ CBotCompExpr::~CBotCompExpr()
fichier plus utilise;
// compile une instruction de type A < B
// compile instruction of type A < B
CBotInstr* CBotCompExpr::Compile(CBotToken* &p, CBotCStack* pStack)
{
CBotCStack* pStk = pStack->AddStack();
CBotInstr* left = CBotAddExpr::Compile( p, pStk ); // expression A + B à gauche
if (left == NULL) return pStack->Return(NULL, pStk); // erreur
CBotInstr* left = CBotAddExpr::Compile( p, pStk ); // expression A + B left
if (left == NULL) return pStack->Return(NULL, pStk); // error
if ( p->GetType() == ID_HI ||
p->GetType() == ID_LO ||
p->GetType() == ID_HS ||
p->GetType() == ID_LS ||
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
inst->SetToken(p); // mémorise l'opération
CBotCompExpr* inst = new CBotCompExpr(); // element for operation
inst->SetToken(p); // stores the operation
int type1, type2;
type1 = pStack->GetType();
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();
// les résultats sont-ils compatibles
// are the results compatible
if ( type1 == type2 )
{
inst->m_leftop = left;
pStk->SetVar(new CBotVar(NULL, CBotTypBoolean));
// le résultat est un boolean
// the result is a boolean
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);
// 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();
if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrompu ici ?
if ( !m_rightop->Execute(pStk2) ) return FALSE; // interrupted here ?
int type1 = pStk1->GetType();
int type2 = pStk2->GetType();
@ -105,27 +107,27 @@ BOOL CBotCompExpr::Execute(CBotStack* &pStack)
switch (GetTokenType())
{
case ID_LO:
result->Lo(pStk1->GetVar(), pStk2->GetVar()); // inférieur
result->Lo(pStk1->GetVar(), pStk2->GetVar()); // lower
break;
case ID_HI:
result->Hi(pStk1->GetVar(), pStk2->GetVar()); // supérieur
result->Hi(pStk1->GetVar(), pStk2->GetVar()); // higher
break;
case ID_LS:
result->Ls(pStk1->GetVar(), pStk2->GetVar()); // inférieur ou égal
result->Ls(pStk1->GetVar(), pStk2->GetVar()); // lower or equal
break;
case ID_HS:
result->Hs(pStk1->GetVar(), pStk2->GetVar()); // supérieur ou égal
result->Hs(pStk1->GetVar(), pStk2->GetVar()); // higher of equal
break;
case ID_EQ:
result->Eq(pStk1->GetVar(), pStk2->GetVar()); // égal
result->Eq(pStk1->GetVar(), pStk2->GetVar()); // equal
break;
case ID_NE:
result->Ne(pStk1->GetVar(), pStk2->GetVar()); // différent
result->Ne(pStk1->GetVar(), pStk2->GetVar()); // not equal
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
return pStack->Return(pStk1); // transmet le résultat
pStk1->Return(pStk2); // frees the stack
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.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/.///////////////////////////////////////////////////////////////////////
// instruction if (condition) opération1 else opération2;
// * along with this program. If not, see http://www.gnu.org/licenses/.
///////////////////////////////////////////////////////////////////////
// instruction if (condition) operation1 else operation2;
#include "CBot.h"
// les divers constructeurs / destructeurs
// various constructors / destructors
CBotIf::CBotIf()
{
m_Condition =
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
}
CBotIf::~CBotIf()
{
delete m_Condition; // libère la condition
delete m_Block; // libère le bloc d'instruction1
delete m_BlockElse; // libère le bloc d'instruction2
delete m_Condition; // frees the condition
delete m_Block; // frees the block of instruction1
delete m_BlockElse; // frees the block of instruction2
}
// compilation (routine statique)
// appelé lorsque le token "if" a été trouvé
// compilation (static routine)
// called when the token "if" has been found
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
CBotIf* inst = new CBotIf(); // crée l'object
CBotIf* inst = new CBotIf(); // create the object
inst->SetToken( pp );
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() )
{
// 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))
{
// si oui, compile le bloc d'instruction qui suit
inst->m_BlockElse = CBotBlock::CompileBlkOrInst( p, pStk, TRUE );
// if so, compiles the following statement block
inst->m_BlockElse = CBotBlock::CompileBlkOrInst( p, pStk, true );
if (!pStk->IsOk())
{
// il n'y a pas de bloc correct après le else
// libère l'objet, et transmet l'erreur qui est sur la pile
// there is no correct block after the else
// frees the object, and transmits the error that is on the stack
delete inst;
return pStack->Return(NULL, pStk);
}
}
// rend l'object correct à qui le demande.
// return the corrent object to the application
return pStack->Return(inst, pStk);
}
}
// erreur, libère l'objet
// error, frees the object
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);
}
// 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
// ou le retrouve en cas de reprise
// if ( pile == EOX ) return TRUE;
CBotStack* pile = pj->AddStack(this); // adds an item to the stack
// or found in case of recovery
// 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 )
{
// évalue la condition
if ( !m_Condition->Execute(pile) ) return FALSE; // interrompu ici ?
// evaluates the condition
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() )
{
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
if (!pile->SetState(1)) return FALSE; // prêt pour la suite
// passes into the second state
if (!pile->SetState(1)) return false; // ready for further
}
// second état, évalue les instructions associées
// le résultat de la condition est sur la pile
// second state, evaluates the associated instructions
// 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
!m_Block->Execute(pile) ) return FALSE; // interrompu ici ?
if ( m_Block != NULL && // block may be absent
!m_Block->Execute(pile) ) return false; // interrupted here?
}
else
{
if ( m_BlockElse != NULL && // s'il existe un bloc alternatif
!m_BlockElse->Execute(pile) ) return FALSE; // interrompu ici
if ( m_BlockElse != NULL && // if there is an alternate block
!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);
}
void CBotIf :: RestoreState(CBotStack* &pj, BOOL bMain)
void CBotIf :: RestoreState(CBotStack* &pj, bool bMain)
{
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;
// 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 )
{
// évalue la condition
m_Condition->RestoreState(pile, bMain); // interrompu ici !
// evaluates the condition
m_Condition->RestoreState(pile, bMain); // interrupted here!
return;
}
// second état, évalue les instructions associées
// le résultat de la condition est sur la pile
// second state, evaluates the associated instructions
// 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
m_Block->RestoreState(pile, bMain); // interrompu ici !
if ( m_Block != NULL ) // block may be absent
m_Block->RestoreState(pile, bMain); // interrupted here!
}
else
{
if ( m_BlockElse != NULL ) // s'il existe un bloc alternatif
m_BlockElse->RestoreState(pile, bMain); // interrompu ici !
if ( m_BlockElse != NULL ) // if there is an alternate block
m_BlockElse->RestoreState(pile, bMain); // interrupted here!
}
}

View File

@ -12,8 +12,10 @@
// * 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/.//////////////////////////////////////////////////////////////////////
// gestion de base d'un programme CBot
// * along with this program. If not, see http://www.gnu.org/licenses/.
//////////////////////////////////////////////////////////////////////
// database management of CBoT program
#include "CBot.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;
Stop();
// delete m_pClass;
m_pClass->Purge(); // purge les anciennes définitions des classes
// mais sans détruire l'object
m_pClass->Purge(); // purge the old definitions of classes
// but without destroying the object
m_pClass = 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)
pUser = m_pInstance->m_pUserPtr;
// transforme le programme en Tokens
// transforms the program in Tokens
CBotToken* pBaseToken = CBotToken::CompileTokens(program, error);
if ( pBaseToken == NULL ) return FALSE;
if ( pBaseToken == NULL ) return false;
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);
// 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)
{
if ( IsOfType(p, ID_SEP) ) continue; // des point-virgules qui trainent
if ( IsOfType(p, ID_SEP) ) continue; // semicolons lurking
if ( p->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;
m_Prog = NULL;
delete pBaseToken;
return FALSE;
return false;
}
// 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 )
{
if ( IsOfType(p, ID_SEP) ) continue; // des point-virgules qui trainent
if ( IsOfType(p, ID_SEP) ) continue; // semicolons lurking
if ( p->GivType() == ID_CLASS ||
( p->GivType() == ID_PUBLIC && p->GivNext()->GivType() == ID_CLASS ))
{
m_bCompileClass = TRUE;
CBotClass::Compile(p, pStack); // complète la définition de la classe
m_bCompileClass = true;
CBotClass::Compile(p, pStack); // completes the definition of the class
}
else
{
m_bCompileClass = FALSE;
m_bCompileClass = false;
CBotFunction::Compile(p, pStack, next);
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();
}
}
// delete m_Prog; // la liste de la 1ère passe
// m_Prog = temp; // la liste de la seconde passe
// delete m_Prog; // the list of first pass
// m_Prog = temp; // list of the second pass
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
m_pStack->Delete();
@ -179,21 +181,21 @@ BOOL CBotProgram::Start(const char* name)
if ( m_pRun == NULL )
{
m_ErrorCode = TX_NORUN;
return FALSE;
return false;
}
#if STACKMEM
m_pStack = CBotStack::FirstStack();
#else
m_pStack = new CBotStack(NULL); // crée une pile d'exécution
m_pStack = new CBotStack(NULL); // creates an execution stack
#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;
while (p != NULL)
@ -202,15 +204,15 @@ BOOL CBotProgram::GetPosition(const char* name, int& start, int& stop, CBotGet m
p = p->m_next;
}
if ( p == NULL ) return FALSE;
if ( p == NULL ) return false;
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;
@ -218,13 +220,13 @@ BOOL CBotProgram::Run(void* pUser, int timer)
if (m_pInstance != NULL && m_pInstance->m_pUserPtr != NULL)
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);
m_pStack->SetBotCall(this); // bases pour les routines
m_pStack->SetBotCall(this); // bases for routines
#if STACKRUN
// reprend l'exécution sur le haut de la pile
// resumes execution on the top of the stack
ok = m_pStack->Execute();
if ( ok )
{
@ -235,7 +237,7 @@ BOOL CBotProgram::Run(void* pUser, int timer)
ppVar[2] = NULL;
ok = m_pRun->Execute(ppVar, m_pStack, m_pInstance);
#else
// revient sur l'exécution normale
// returns to normal execution
ok = m_pRun->Execute(NULL, m_pStack, m_pInstance);
#endif
}
@ -243,7 +245,7 @@ BOOL CBotProgram::Run(void* pUser, int timer)
ok = m_pRun->Execute(NULL, m_pStack, m_pInstance);
#endif
// terminé sur une erreur ?
// completed on a mistake?
if (!ok && !m_pStack->IsOk())
{
m_ErrorCode = m_pStack->GivError(m_ErrorStart, m_ErrorEnd);
@ -253,15 +255,15 @@ BOOL CBotProgram::Run(void* pUser, int timer)
delete m_pStack;
#endif
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;
error:
m_ErrorCode = TX_NORUN;
return TRUE;
return true;
}
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;
start = end = 0;
if (m_pStack == NULL) return FALSE;
if (m_pStack == NULL) return false;
m_pStack->GetRunPos(FunctionName, start, end);
return TRUE;
return true;
}
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);
}
void CBotProgram::SetTimer(int n)
{
CBotStack::SetTimer( n );
@ -321,7 +317,7 @@ long CBotProgram::GivIdent()
return m_Ident;
}
BOOL CBotProgram::GetError(int& code, int& start, int& end)
bool CBotProgram::GetError(int& code, int& start, int& end)
{
code = m_ErrorCode;
start = m_ErrorStart;
@ -329,7 +325,7 @@ BOOL CBotProgram::GetError(int& code, int& start, int& end)
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;
start = m_ErrorStart;
@ -346,7 +342,7 @@ CBotString CBotProgram::GivErrorText(int code)
if (TextError.IsEmpty())
{
char buf[100];
sprintf(buf, "Exception numéro %d.", code);
sprintf(buf, "Exception numéro %d.", code);
TextError = buf;
}
return TextError;
@ -358,34 +354,34 @@ CBotFunction* CBotProgram::GivFunctions()
return m_Prog;
}
BOOL CBotProgram::AddFunction(const char* name,
BOOL rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser),
bool CBotProgram::AddFunction(const char* name,
bool rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, 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);
}
BOOL WriteWord(FILE* pf, WORD w)
bool WriteWord(FILE* pf, unsigned short w)
{
size_t lg;
lg = fwrite(&w, sizeof( WORD ), 1, pf );
lg = fwrite(&w, sizeof( unsigned short ), 1, pf );
return (lg == 1);
}
BOOL ReadWord(FILE* pf, WORD& w)
bool ReadWord(FILE* pf, unsigned short& w)
{
size_t lg;
lg = fread(&w, sizeof( WORD ), 1, pf );
lg = fread(&w, sizeof( unsigned short ), 1, pf );
return (lg == 1);
}
BOOL WriteFloat(FILE* pf, float w)
bool WriteFloat(FILE* pf, float w)
{
size_t lg;
@ -394,7 +390,7 @@ BOOL WriteFloat(FILE* pf, float w)
return (lg == 1);
}
BOOL ReadFloat(FILE* pf, float& w)
bool ReadFloat(FILE* pf, float& w)
{
size_t lg;
@ -403,7 +399,7 @@ BOOL ReadFloat(FILE* pf, float& w)
return (lg == 1);
}
BOOL WriteLong(FILE* pf, long w)
bool WriteLong(FILE* pf, long w)
{
size_t lg;
@ -412,7 +408,7 @@ BOOL WriteLong(FILE* pf, long w)
return (lg == 1);
}
BOOL ReadLong(FILE* pf, long& w)
bool ReadLong(FILE* pf, long& w)
{
size_t lg;
@ -421,24 +417,24 @@ BOOL ReadLong(FILE* pf, long& w)
return (lg == 1);
}
BOOL WriteString(FILE* pf, CBotString s)
bool WriteString(FILE* pf, CBotString s)
{
size_t lg1, lg2;
lg1 = s.GivLength();
if (!WriteWord(pf, lg1)) return FALSE;
if (!WriteWord(pf, lg1)) return false;
lg2 = fwrite(s, 1, lg1, pf );
return (lg1 == lg2);
}
BOOL ReadString(FILE* pf, CBotString& s)
bool ReadString(FILE* pf, CBotString& s)
{
WORD w;
unsigned short w;
char buf[1000];
size_t lg1, lg2;
if (!ReadWord(pf, w)) return FALSE;
if (!ReadWord(pf, w)) return false;
lg1 = w;
lg2 = fread(buf, 1, lg1, pf );
buf[lg2] = 0;
@ -447,29 +443,29 @@ BOOL ReadString(FILE* pf, CBotString& s)
return (lg1 == lg2);
}
BOOL WriteType(FILE* pf, CBotTypResult type)
bool WriteType(FILE* pf, CBotTypResult type)
{
int typ = type.GivType();
if ( typ == CBotTypIntrinsic ) typ = CBotTypClass;
if ( !WriteWord(pf, typ) ) return FALSE;
if ( !WriteWord(pf, typ) ) return false;
if ( typ == CBotTypClass )
{
CBotClass* p = type.GivClass();
if ( !WriteString(pf, p->GivName()) ) return FALSE;
if ( !WriteString(pf, p->GivName()) ) return false;
}
if ( type.Eq( CBotTypArrayBody ) ||
type.Eq( CBotTypArrayPointer ) )
{
if ( !WriteWord(pf, type.GivLimite()) ) return FALSE;
if ( !WriteType(pf, type.GivTypElem()) ) return FALSE;
if ( !WriteWord(pf, type.GivLimite()) ) 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;
if ( !ReadWord(pf, w) ) return FALSE;
unsigned short w, ww;
if ( !ReadWord(pf, w) ) return false;
type.SetType(w);
if ( type.Eq( CBotTypIntrinsic ) )
@ -480,7 +476,7 @@ BOOL ReadType(FILE* pf, CBotTypResult& type)
if ( type.Eq( CBotTypClass ) )
{
CBotString s;
if ( !ReadString(pf, s) ) return FALSE;
if ( !ReadString(pf, s) ) return false;
type = CBotTypResult( w, s );
}
@ -488,54 +484,54 @@ BOOL ReadType(FILE* pf, CBotTypResult& type)
type.Eq( CBotTypArrayBody ) )
{
CBotTypResult r;
if ( !ReadWord(pf, ww) ) return FALSE;
if ( !ReadType(pf, r) ) return FALSE;
if ( !ReadWord(pf, ww) ) return false;
if ( !ReadType(pf, r) ) return false;
type = CBotTypResult( w, r );
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);
}
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 (!WriteWord( pf, 1)) return FALSE;
if (!WriteString( pf, m_pRun->GivName() )) return FALSE;
if (!m_pStack->SaveState(pf)) return FALSE;
if (!WriteWord( pf, 1)) return false;
if (!WriteString( pf, m_pRun->GivName() )) return false;
if (!m_pStack->SaveState(pf)) return false;
}
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;
Stop();
if (!ReadWord( pf, w )) return FALSE;
if ( w != CBOTVERSION ) return FALSE;
if (!ReadWord( pf, w )) return false;
if ( w != CBOTVERSION ) return false;
if (!ReadWord( pf, w )) return FALSE;
if ( w == 0 ) return TRUE;
if (!ReadWord( pf, w )) return false;
if ( w == 0 ) return true;
if (!ReadString( pf, s )) return FALSE;
if (!ReadString( pf, s )) return false;
Start(s); // point de reprise
#if STACKMEM
@ -545,14 +541,14 @@ BOOL CBotProgram::RestoreState(FILE* pf)
#endif
m_pStack = NULL;
// récupère la pile depuis l'enregistrement
// utilise un pointeur NULL (m_pStack) mais c'est ok comme ça
if (!m_pStack->RestoreState(pf, m_pStack)) return FALSE;
m_pStack->SetBotCall(this); // bases pour les routines
// retrieves the stack from the memory
// uses a NULL pointer (m_pStack) but it's ok like that
if (!m_pStack->RestoreState(pf, m_pStack)) return false;
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);
return TRUE;
return true;
}
int CBotProgram::GivVersion()
@ -566,7 +562,7 @@ int CBotProgram::GivVersion()
CBotCall* CBotCall::m_ListCalls = NULL;
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))
{
m_name = name;
@ -587,8 +583,8 @@ void CBotCall::Free()
delete CBotCall::m_ListCalls;
}
BOOL CBotCall::AddFunction(const char* name,
BOOL rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser),
bool CBotCall::AddFunction(const char* name,
bool rExec (CBotVar* pVar, CBotVar* pResult, int& Exception, void* pUser),
CBotTypResult rCompile (CBotVar* &pVar, void* pUser))
{
CBotCall* p = m_ListCalls;
@ -598,16 +594,16 @@ BOOL CBotCall::AddFunction(const char* name,
{
if ( p->GivName() == name )
{
// libère une fonction qu'on redéfini
// frees redefined function
if ( pp ) pp->m_next = p->m_next;
else m_ListCalls = p->m_next;
pp = p;
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;
continue;
}
pp = p; // pointeur précédent
pp = p; // previous pointer
p = p->m_next;
}
@ -616,18 +612,18 @@ BOOL CBotCall::AddFunction(const char* name,
if (p) p->m_next = pp;
else m_ListCalls = pp;
return TRUE;
return true;
}
// transforme le tableau de pointeurs aux variables
// en une liste de variables chaînées
CBotVar* MakeListVars(CBotVar** ppVars, BOOL bSetVal=FALSE)
// transforms the array of pointers to variables
// in a chained list of variables
CBotVar* MakeListVars(CBotVar** ppVars, bool bSetVal=false)
{
int i = 0;
CBotVar* pVar = NULL;
while( TRUE )
while( true )
{
ppVars[i];
if ( ppVars[i] == NULL ) break;
@ -637,7 +633,7 @@ CBotVar* MakeListVars(CBotVar** ppVars, BOOL bSetVal=FALSE)
else
if ( ppVars[i]->GivType() == CBotTypPointer )
pp->SetClass( ppVars[i]->GivClass());
// copier le pointeur selon indirection
// copy the pointer according to indirections
if (pVar == NULL) pVar = pp;
else pVar->AddNext(pp);
i++;
@ -645,8 +641,8 @@ CBotVar* MakeListVars(CBotVar** ppVars, BOOL bSetVal=FALSE)
return pVar;
}
// trouve un appel acceptable selon le nom de la procédure
// et les paramètres donnés
// is acceptable by a call procedure name
// and given parameters
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);
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 > 20 )
@ -686,16 +682,16 @@ void CBotCall::SetPUser(void* pUser)
m_pUser = pUser;
}
int CBotCall::CheckCall(const char* name)
bool CBotCall::CheckCall(const char* name)
{
CBotCall* p = m_ListCalls;
while ( p != NULL )
{
if ( name == p->GivName() ) return TRUE;
if ( name == p->GivName() ) return true;
p = p->m_next;
}
return FALSE;
return false;
}
@ -744,29 +740,29 @@ int CBotCall::DoCall(long& nIdent, CBotToken* token, CBotVar** ppVar, CBotStack*
fund:
#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;
// crée une variable pour le résultat
// creates a variable to the result
CBotVar* pResult = rettype.Eq(0) ? NULL : CBotVar::Create("", rettype);
CBotVar* pRes = pResult;
int Exception = 0;
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;
if (res == FALSE)
if (res == false)
{
if (Exception!=0)
{
pStack->SetError(Exception, token);
}
delete pResult;
return FALSE;
return false;
}
pStack->SetVar(pResult);
@ -775,19 +771,19 @@ fund:
pStack->SetError(TX_NORETVAL, token);
}
nIdent = pt->m_nFuncIdent;
return TRUE;
return true;
#else
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;
// crée une variable pour le résultat
// creates a variable to the result
CBotVar* pResult = rettype.Eq(0) ? NULL : CBotVar::Create("", rettype);
pile->SetVar( pVar );
@ -795,7 +791,7 @@ fund:
CBotStack* pile2 = pile->AddStack();
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 );
#endif
@ -804,7 +800,7 @@ fund:
#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;
@ -817,22 +813,22 @@ BOOL CBotCall::RestoreCall(long& nIdent, CBotToken* token, CBotVar** ppVar, CBot
nIdent = pt->m_nFuncIdent;
CBotStack* pile = pStack->RestoreStackEOX(pt);
if ( pile == NULL ) return TRUE;
if ( pile == NULL ) return true;
CBotStack* pile2 = pile->RestoreStack();
return TRUE;
return true;
}
pt = pt->m_next;
}
}
return FALSE;
return false;
}
BOOL CBotCall::Run(CBotStack* pStack)
bool CBotCall::Run(CBotStack* pStack)
{
CBotStack* pile = pStack->AddStackEOX(this);
if ( pile == EOX ) return TRUE;
if ( pile == EOX ) return true;
CBotVar* pVar = pile->GivVar();
CBotStack* pile2 = pile->AddStack();
@ -842,20 +838,20 @@ BOOL CBotCall::Run(CBotStack* pStack)
int Exception = 0;
int res = m_rExec(pVar, pResult, Exception, pStack->GivPUser());
if (res == FALSE)
if (res == false)
{
if (Exception!=0)
{
pStack->SetError(Exception);
}
if ( pResult != pRes ) delete pResult; // si résultat différent rendu
return FALSE;
if ( pResult != pRes ) delete pResult; // different result if made
return false;
}
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
@ -863,7 +859,7 @@ BOOL CBotCall::Run(CBotStack* pStack)
///////////////////////////////////////////////////////////////////////////////////////
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))
{
m_name = name;
@ -879,8 +875,8 @@ CBotCallMethode::~CBotCallMethode()
m_next = NULL;
}
// trouve un appel acceptable selon le nom de la procédure
// et les paramètres donnés
// is acceptable by a call procedure name
// and given parameters
CBotTypResult CBotCallMethode::CompileCall(const char* name, CBotVar* pThis,
CBotVar** ppVar, CBotCStack* pStack,
@ -893,7 +889,7 @@ CBotTypResult CBotCallMethode::CompileCall(const char* name, CBotVar* pThis,
{
if ( pt->m_name == name )
{
CBotVar* pVar = MakeListVars(ppVar, TRUE);
CBotVar* pVar = MakeListVars(ppVar, true);
CBotVar* pVar2 = pVar;
CBotTypResult r = pt->m_rComp(pThis, pVar2);
int ret = r.GivType();
@ -934,24 +930,24 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
{
CBotCallMethode* pt = this;
// recherche selon l'identificateur
// search by the identifier
if ( nIdent ) while ( pt != NULL )
{
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;
// puis appelle la routine externe au module
// then calls the routine external to the module
int Exception = 0;
int res = pt->m_rExec(pThis, pVar, pResult, Exception);
pStack->SetVar(pResult);
if (res == FALSE)
if (res == false)
{
if (Exception!=0)
{
@ -959,30 +955,30 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
pStack->SetError(Exception, pToken);
}
delete pVarToDelete;
return FALSE;
return false;
}
delete pVarToDelete;
return TRUE;
return true;
}
pt = pt->m_next;
}
// recherche selon le nom
// search by name
while ( pt != NULL )
{
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;
int Exception = 0;
int res = pt->m_rExec(pThis, pVar, pResult, Exception);
pStack->SetVar(pResult);
if (res == FALSE)
if (res == false)
{
if (Exception!=0)
{
@ -990,11 +986,11 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
pStack->SetError(Exception, pToken);
}
delete pVarToDelete;
return FALSE;
return false;
}
delete pVarToDelete;
nIdent = pt->m_nFuncIdent;
return TRUE;
return true;
}
pt = pt->m_next;
}
@ -1002,7 +998,7 @@ int CBotCallMethode::DoCall(long& nIdent, const char* name, CBotVar* pThis, CBot
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;
@ -1016,7 +1012,7 @@ BOOL rSizeOf( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
}
pResult->SetValInt(i);
return TRUE;
return true;
}
CBotTypResult cSizeOf( CBotVar* &pVar, void* pUser )
@ -1030,19 +1026,19 @@ CBotTypResult cSizeOf( CBotVar* &pVar, void* pUser )
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 );
return TRUE;
return true;
}
CBotTypResult cCBotDebug( CBotVar* &pVar, void* pUser )
{
// pas de paramètre
// no parameter
if ( pVar != NULL ) return CBotTypResult( TX_OVERPARAM );
// la fonction retourne un résultat "string"
// function returns a result "string"
return CBotTypResult( CBotTypString );
}
@ -1051,59 +1047,60 @@ CBotTypResult cCBotDebug( CBotVar* &pVar, void* pUser )
void CBotProgram::Init()
{
CBotToken::DefineNum( "CBotErrOpenPar", 5000) ; // manque la parenthèse ouvrante
CBotToken::DefineNum( "CBotErrClosePar", 5001) ; // manque la parenthèse fermante
CBotToken::DefineNum( "CBotErrNotBoolean", 5002) ; // l'expression doit être un boolean
CBotToken::DefineNum( "CBotErrUndefVar", 5003) ; // variable non déclarée
CBotToken::DefineNum( "CBotErrBadLeft", 5004) ; // assignation impossible ( 5 = ... )
CBotToken::DefineNum( "CBotErrNoTerminator", 5005) ;// point-virgule attendu
CBotToken::DefineNum( "CBotErrCaseOut", 5006) ; // case en dehors d'un switch
CBotToken::DefineNum( "CBotErrCloseBlock", 5008) ; // manque " } "
CBotToken::DefineNum( "CBotErrElseWhitoutIf", 5009) ;// else sans if correspondant
CBotToken::DefineNum( "CBotErrOpenBlock", 5010) ; // manque " { "
CBotToken::DefineNum( "CBotErrBadType1", 5011) ; // mauvais type pour l'assignation
CBotToken::DefineNum( "CBotErrRedefVar", 5012) ; // redéfinition de la variable
CBotToken::DefineNum( "CBotErrBadType2", 5013) ; // 2 opérandes de type incompatibles
CBotToken::DefineNum( "CBotErrUndefCall", 5014) ; // routine inconnue
CBotToken::DefineNum( "CBotErrNoDoubleDots", 5015) ;// " : " attendu
CBotToken::DefineNum( "CBotErrBreakOutside", 5017) ;// break en dehors d'une boucle
CBotToken::DefineNum( "CBotErrUndefLabel", 5019) ; // label inconnu
CBotToken::DefineNum( "CBotErrLabel", 5018) ; // label ne peut se mettre ici
CBotToken::DefineNum( "CBotErrNoCase", 5020) ; // manque " case "
CBotToken::DefineNum( "CBotErrBadNum", 5021) ; // nombre attendu
CBotToken::DefineNum( "CBotErrVoid", 5022) ; // " void " pas possible ici
CBotToken::DefineNum( "CBotErrNoType", 5023) ; // déclaration de type attendue
CBotToken::DefineNum( "CBotErrNoVar", 5024) ; // nom de variable attendu
CBotToken::DefineNum( "CBotErrNoFunc", 5025) ; // nom de fonction attendu
CBotToken::DefineNum( "CBotErrOverParam", 5026) ; // trop de paramètres
CBotToken::DefineNum( "CBotErrRedefFunc", 5027) ; // cette fonction existe déjà
CBotToken::DefineNum( "CBotErrLowParam", 5028) ; // pas assez de paramètres
CBotToken::DefineNum( "CBotErrBadParam", 5029) ; // mauvais types de paramètres
CBotToken::DefineNum( "CBotErrNbParam", 5030) ; // mauvais nombre de paramètres
CBotToken::DefineNum( "CBotErrUndefItem", 5031) ; // élément n'existe pas dans la classe
CBotToken::DefineNum( "CBotErrUndefClass", 5032) ; // variable n'est pas une classe
CBotToken::DefineNum( "CBotErrNoConstruct", 5033) ; // pas de constructeur approprié
CBotToken::DefineNum( "CBotErrRedefClass", 5034) ; // classe existe déjà
CBotToken::DefineNum( "CBotErrCloseIndex", 5035) ; // " ] " attendu
CBotToken::DefineNum( "CBotErrReserved", 5036) ; // mot réservé (par un DefineNum)
CBotToken::DefineNum( "CBotErrOpenPar", 5000) ; // missing the opening parenthesis
CBotToken::DefineNum( "CBotErrClosePar", 5001) ; // missing the closing parenthesis
CBotToken::DefineNum( "CBotErrNotBoolean", 5002) ; // expression must be a boolean
CBotToken::DefineNum( "CBotErrUndefVar", 5003) ; // undeclared variable
CBotToken::DefineNum( "CBotErrBadLeft", 5004) ; // impossible assignment (5 = ...)
CBotToken::DefineNum( "CBotErrNoTerminator", 5005) ;// semicolon expected
CBotToken::DefineNum( "CBotErrCaseOut", 5006) ; // case outside a switch
CBotToken::DefineNum( "CBotErrCloseBlock", 5008) ; // missing " } "
CBotToken::DefineNum( "CBotErrElseWhitoutIf", 5009) ;// else without matching if
CBotToken::DefineNum( "CBotErrOpenBlock", 5010) ; // missing " { "
CBotToken::DefineNum( "CBotErrBadType1", 5011) ; // wrong type for the assignment
CBotToken::DefineNum( "CBotErrRedefVar", 5012) ; // redefinition of the variable
CBotToken::DefineNum( "CBotErrBadType2", 5013) ; // two operands are incompatible
CBotToken::DefineNum( "CBotErrUndefCall", 5014) ; // routine unknown
CBotToken::DefineNum( "CBotErrNoDoubleDots", 5015) ;// " : " expected
CBotToken::DefineNum( "CBotErrBreakOutside", 5017) ;// break outside of a loop
CBotToken::DefineNum( "CBotErrUndefLabel", 5019) ; // unknown label
CBotToken::DefineNum( "CBotErrLabel", 5018) ; // label can not get here
CBotToken::DefineNum( "CBotErrNoCase", 5020) ; // missing " case "
CBotToken::DefineNum( "CBotErrBadNum", 5021) ; // expected number
CBotToken::DefineNum( "CBotErrVoid", 5022) ; // " void " not possble here
CBotToken::DefineNum( "CBotErrNoType", 5023) ; // type declaration expected
CBotToken::DefineNum( "CBotErrNoVar", 5024) ; // variable name expected
CBotToken::DefineNum( "CBotErrNoFunc", 5025) ; // expected function name
CBotToken::DefineNum( "CBotErrOverParam", 5026) ; // too many parameters
CBotToken::DefineNum( "CBotErrRedefFunc", 5027) ; // this function already exists
CBotToken::DefineNum( "CBotErrLowParam", 5028) ; // not enough parameters
CBotToken::DefineNum( "CBotErrBadParam", 5029) ; // mauvais types de paramètres
CBotToken::DefineNum( "CBotErrNbParam", 5030) ; // wrong number of parameters
CBotToken::DefineNum( "CBotErrUndefItem", 5031) ; // element does not exist in the class
CBotToken::DefineNum( "CBotErrUndefClass", 5032) ; // variable is not a class
CBotToken::DefineNum( "CBotErrNoConstruct", 5033) ; // no appropriate constructor
CBotToken::DefineNum( "CBotErrRedefClass", 5034) ; // Class already exists
CBotToken::DefineNum( "CBotErrCloseIndex", 5035) ; // " ] " expected
CBotToken::DefineNum( "CBotErrReserved", 5036) ; // reserved word (for a DefineNum)
// voici la liste des erreurs pouvant être retournées par le module
// pour l'exécution
// Here are the list of errors that can be returned by the module
// for the execution
CBotToken::DefineNum( "CBotErrZeroDiv", 6000) ; // division par zéro
CBotToken::DefineNum( "CBotErrNotInit", 6001) ; // variable non initialisée
CBotToken::DefineNum( "CBotErrBadThrow", 6002) ; // throw d'une valeur négative
CBotToken::DefineNum( "CBotErrNoRetVal", 6003) ; // fonction n'a pas retourné de résultat
CBotToken::DefineNum( "CBotErrNoRun", 6004) ; // Run() sans fonction active
CBotToken::DefineNum( "CBotErrUndefFunc", 6005) ; // appel d'une fonction qui n'existe plus
CBotToken::DefineNum( "CBotErrZeroDiv", 6000) ; // division by zero
CBotToken::DefineNum( "CBotErrNotInit", 6001) ; // uninitialized variable
CBotToken::DefineNum( "CBotErrBadThrow", 6002) ; // throw a negative value
CBotToken::DefineNum( "CBotErrNoRetVal", 6003) ; // function did not return results
CBotToken::DefineNum( "CBotErrNoRun", 6004) ; // active Run () without a function
CBotToken::DefineNum( "CBotErrUndefFunc", 6005) ; // Calling a function that no longer exists
CBotProgram::AddFunction("sizeof", rSizeOf, cSizeOf );
InitStringFunctions();
// une fonction juste pour les debug divers
// just a function for various debug
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.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see http://www.gnu.org/licenses/./////////////////////////////////////////////////////
// gestion de chaine
// basé sur le CString de MFC
// mais moins complet
// * along with this program. If not, see http://www.gnu.org/licenses/.
/////////////////////////////////////////////////////
//strings management
#include "CBot.h"
#include <string.h>
HINSTANCE CBotString::m_hInstance = (HINSTANCE)LoadLibrary("libCbot.dll"); // comment le récupérer autrement ??
#include <cstdlib>
#include <cstring>
#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()
{
m_ptr = NULL; // chaine vide
m_ptr = NULL;
m_lg = 0;
}
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)
{
m_lg = lstrlen( p );
m_lg = strlen(p);
m_ptr = NULL;
if (m_lg>0)
{
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)
{
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()
{
if (m_ptr == NULL) return 0;
return lstrlen( m_ptr );
return strlen( m_ptr );
}
CBotString CBotString::Left(int nCount) const
{
char chaine[2000];
char chain[2000];
int i;
for (i = 0; i < m_lg && i < nCount && i < 1999; i++)
size_t 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
{
char chaine[2000];
char chain[2000];
int i = m_lg - nCount;
if ( i < 0 ) i = 0;
int j;
for ( j = 0 ; i < m_lg && i < 1999; i++)
size_t j;
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
{
char chaine[2000];
char chain[2000];
int i;
for ( i = nFirst; i < m_lg && i < 1999 && i <= nFirst + nCount; i++)
size_t 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
{
char chaine[2000];
char chain[2000];
int i;
for ( i = nFirst; i < m_lg && i < 1999 ; i++)
size_t 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 i;
for (i = 0; i < m_lg; i++)
for (size_t i = 0; i < m_lg; ++i)
{
if (m_ptr[i] == c) return i;
}
return -1;
}
int CBotString::Find(LPCTSTR lpsz)
int CBotString::Find(const char * lpsz)
{
int i, j;
int l = lstrlen(lpsz);
int l = strlen(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;
}
@ -163,21 +254,21 @@ bad:;
int CBotString::ReverseFind(const char c)
{
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;
}
return -1;
}
int CBotString::ReverseFind(LPCTSTR lpsz)
int CBotString::ReverseFind(const char * lpsz)
{
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;
}
@ -195,7 +286,7 @@ CBotString CBotString::Mid(int start, int lg)
if ( lg < 0 ) lg = m_lg - start;
char* p = (char*)malloc(m_lg+1);
lstrcpy(p, m_ptr+start);
strcpy(p, m_ptr+start);
p[lg] = 0;
res = p;
@ -205,9 +296,7 @@ CBotString CBotString::Mid(int start, int lg)
void CBotString::MakeUpper()
{
int i;
for ( i = 0; i < m_lg && i < 1999 ; i++)
for (size_t i = 0; i < m_lg && i < 1999 ; ++i)
{
char c = m_ptr[i];
if ( c >= 'a' && c <= 'z' ) m_ptr[i] = c - 'a' + 'A';
@ -216,55 +305,48 @@ void CBotString::MakeUpper()
void CBotString::MakeLower()
{
int i;
for ( i = 0; i < m_lg && i < 1999 ; i++)
for (size_t i = 0; i < m_lg && i < 1999 ; ++i)
{
char c = m_ptr[i];
if ( c >= 'A' && c <= 'Z' ) m_ptr[i] = c - 'A' + 'a';
}
}
#define MAXSTRING 256
BOOL CBotString::LoadString(UINT id)
bool CBotString::LoadString(unsigned int id)
{
char buffer[MAXSTRING];
m_lg = ::LoadString( m_hInstance, id, buffer, MAXSTRING );
const char * str = NULL;
str = MapIdToString((EID)id);
if (m_ptr != NULL) free(m_ptr);
m_lg = strlen(str);
m_ptr = NULL;
if (m_lg > 0)
{
m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, buffer);
return TRUE;
strcpy(m_ptr, str);
return true;
}
return FALSE;
return false;
}
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_ptr = NULL;
if (m_lg > 0)
{
m_ptr = (char*)malloc(m_lg+1);
lstrcpy(m_ptr, stringSrc.m_ptr);
strcpy(m_ptr, stringSrc.m_ptr);
}
return *this;
}
CBotString operator+(const CBotString& string, LPCTSTR lpsz)
CBotString operator+(const CBotString& string, const char * lpsz)
{
CBotString s(string);
s += lpsz;
@ -275,11 +357,11 @@ const CBotString& CBotString::operator+(const CBotString& stringSrc)
{
char* p = (char*)malloc(m_lg+stringSrc.m_lg+1);
lstrcpy(p, m_ptr);
strcpy(p, m_ptr);
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_lg += stringSrc.m_lg;
@ -288,7 +370,7 @@ const CBotString& CBotString::operator+(const CBotString& stringSrc)
const CBotString& CBotString::operator=(const char ch)
{
if (m_ptr != NULL) free(m_ptr);
free(m_ptr);
m_lg = 1;
@ -301,17 +383,17 @@ const CBotString& CBotString::operator=(const char ch)
const CBotString& CBotString::operator=(const char* pString)
{
if (m_ptr != NULL) free(m_ptr);
free(m_ptr);
m_ptr = NULL;
if (pString != NULL)
{
m_lg = lstrlen(pString);
m_lg = strlen(pString);
if (m_lg != 0)
{
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);
if (m_ptr!=NULL) lstrcpy(p, m_ptr);
if (m_ptr!=NULL) strcpy(p, m_ptr);
p[m_lg++] = ch;
p[m_lg] = 0;
if (m_ptr != NULL) free(m_ptr);
free(m_ptr);
m_ptr = p;
@ -338,112 +420,122 @@ const CBotString& CBotString::operator+=(const CBotString& str)
{
char* p = (char*)malloc(m_lg+str.m_lg+1);
lstrcpy(p, m_ptr);
strcpy(p, m_ptr);
char* pp = p + m_lg;
lstrcpy(pp, str.m_ptr);
strcpy(pp, str.m_ptr);
m_lg = m_lg + str.m_lg;
if (m_ptr != NULL) free(m_ptr);
free(m_ptr);
m_ptr = p;
return *this;
}
BOOL CBotString::operator==(const CBotString& str)
bool CBotString::operator==(const CBotString& str)
{
return Compare(str) == 0;
}
BOOL CBotString::operator==(const char* p)
bool CBotString::operator==(const char* p)
{
return Compare(p) == 0;
}
BOOL CBotString::operator!=(const CBotString& str)
bool CBotString::operator!=(const CBotString& str)
{
return Compare(str) != 0;
}
BOOL CBotString::operator!=(const char* p)
bool CBotString::operator!=(const char* p)
{
return Compare(p) != 0;
}
BOOL CBotString::operator>(const CBotString& str)
bool CBotString::operator>(const CBotString& str)
{
return Compare(str) > 0;
}
BOOL CBotString::operator>(const char* p)
bool CBotString::operator>(const char* p)
{
return Compare(p) > 0;
}
BOOL CBotString::operator>=(const CBotString& str)
bool CBotString::operator>=(const CBotString& str)
{
return Compare(str) >= 0;
}
BOOL CBotString::operator>=(const char* p)
bool CBotString::operator>=(const char* p)
{
return Compare(p) >= 0;
}
BOOL CBotString::operator<(const CBotString& str)
bool CBotString::operator<(const CBotString& str)
{
return Compare(str) < 0;
}
BOOL CBotString::operator<(const char* p)
bool CBotString::operator<(const char* p)
{
return Compare(p) < 0;
}
BOOL CBotString::operator<=(const CBotString& str)
bool CBotString::operator<=(const CBotString& str)
{
return Compare(str) <= 0;
}
BOOL CBotString::operator<=(const char* p)
bool CBotString::operator<=(const char* p)
{
return Compare(p) <= 0;
}
BOOL CBotString::IsEmpty() const
bool CBotString::IsEmpty() const
{
return (m_lg == 0);
}
void CBotString::Empty()
{
if (m_ptr != NULL) free(m_ptr);
free(m_ptr);
m_ptr = NULL;
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;
}
int CBotString::Compare(LPCTSTR lpsz) const
int CBotString::Compare(const char * lpsz) const
{
char* p = m_ptr;
if (lpsz == NULL) lpsz = nilstring;
if (m_ptr == NULL) p = nilstring;
if (lpsz == NULL) lpsz = emptyString;
if (m_ptr == NULL) p = emptyString;
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()
{
@ -453,7 +545,7 @@ 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;
}
///////////////////////////////////////////////////////////////////////
// routines utilitaires
// utility routines
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)
{
@ -527,14 +618,14 @@ void CBotStringArray::SetSize(int nNewSize)
// shrink to nothing
DestructElements(m_pData, m_nSize);
delete[] (BYTE*)m_pData;
delete[] (unsigned char *)m_pData;
m_pData = NULL;
m_nSize = m_nMaxSize = 0;
}
else if (m_pData == NULL)
{
// 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);
@ -563,7 +654,7 @@ void CBotStringArray::SetSize(int nNewSize)
{
// heuristically determine growth when nGrowBy == 0
// (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;
if (nNewSize < m_nMaxSize + nGrowBy)
@ -571,7 +662,7 @@ void CBotStringArray::SetSize(int nNewSize)
else
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
memcpy(pNewData, m_pData, m_nSize * sizeof(CBotString));
@ -580,8 +671,8 @@ void CBotStringArray::SetSize(int nNewSize)
ConstructElements(&pNewData[m_nSize], nNewSize-m_nSize);
// Ret rid of old stuff (note: no destructors called)
delete[] (BYTE*)m_pData;
// Get rid of old stuff (note: no destructors called)
delete[] (unsigned char *)m_pData;
m_pData = pNewData;
m_nSize = nNewSize;
m_nMaxSize = nNewMax;
@ -599,5 +690,3 @@ CBotString& CBotStringArray::ElementAt(int nIndex)
return m_pData[nIndex];
}

View File

@ -12,29 +12,33 @@
// * 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/.//////////////////////////////////////////////////////////////////
// Gestion des Tokens
// le texte d'un programme est d'abord transformé
// en une suite de tokens pour facilité l'interprétation
// * along with this program. If not, see http://www.gnu.org/licenses/.
// 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 <cstdarg>
CBotStringArray CBotToken::m_ListKeyWords;
int CBotToken::m_ListIdKeyWords[200];
CBotStringArray CBotToken::m_ListKeyDefine;
long CBotToken::m_ListKeyNums[MAXDEFNUM];
// constructeurs
//! contructors
CBotToken::CBotToken()
{
m_next = 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;
}
@ -54,12 +58,13 @@ CBotToken::CBotToken(const CBotToken* pSrc)
if ( pSrc != NULL )
{
m_Text = pSrc->m_Text;
m_Sep = pSrc->m_Sep;
m_type = pSrc->m_type;
m_IdKeyWord = pSrc->m_IdKeyWord;
m_Text = pSrc->m_Text;
m_Sep = pSrc->m_Sep;
m_start = pSrc->m_start;
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)
{
m_Text = mot; // mot trouvé comme token
m_Sep = sep; // séparateurs qui suivent
m_Text = mot; // word (mot) found as token
m_Sep = sep; // separator
m_next = NULL;
m_prev = NULL;
m_start = start;
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;
}
@ -85,13 +90,13 @@ CBotToken::CBotToken(const char* mot, const char* sep)
m_next = 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;
}
CBotToken::~CBotToken()
{
delete m_next; // récursif
delete m_next; // recursive
m_next = NULL;
}
@ -188,168 +193,168 @@ void CBotToken::SetPos(int start, int end)
m_end = end;
}
BOOL CharInList(const char c, const char* list)
bool CharInList(const char c, const char* list)
{
int i = 0;
while (TRUE)
while (true)
{
if (c == list[i++]) return TRUE;
if (list[i] == 0) return FALSE;
if (c == list[i++]) return true;
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;
while (TRUE)
while (true)
{
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* sep2 = " \r\n\t"; // séparateurs pures
static char* sep3 = ",:()[]{}-+*/=;<>!~^|&%."; // séparateurs opérationnels
static char* num = "0123456789"; // le point (unique) est testé séparément
static char* sep2 = " \r\n\t"; // only separators
static char* sep3 = ",:()[]{}-+*/=;<>!~^|&%."; // operational separators
static char* num = "0123456789"; // point (single) is tested separately
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
// ne doit pas commencer par des séparateurs
// qui sont pris avec le token précédent
CBotToken* CBotToken::NextToken(char* &program, int& error, BOOL first)
// looking for the next token in a sentence
// do not start with separators
// which are made in the previous token
CBotToken* CBotToken::NextToken(char* &program, int& error, bool first)
{
CBotString mot; // le mot trouvé
CBotString sep; // les séparateurs qui le suivent
CBotString mot; // the word which is found
CBotString sep; // separators that are after
char c;
BOOL stop = first;
bool stop = first;
if (*program == 0) return NULL;
c = *(program++); // prochain caractère
c = *(program++); // next character
if (!first)
{
mot = c; // construit le mot
c = *(program++); // prochain caractère
mot = c; // built the word
c = *(program++); // next character
// cas particulier pour les chaînes de caractères
// special case for strings
if ( mot[0] == '\"' )
{
while (c != 0 && !CharInList(c, nch))
{
mot += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
if ( c == '\\' )
{
c = *(program++); // prochain caractère
c = *(program++); // next character
if ( c == 'n' ) c = '\n';
if ( c == 'r' ) c = '\r';
if ( c == 't' ) c = '\t';
mot += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
}
}
if ( c == '\"' )
{
mot += c; // chaîne complète
c = *(program++); // prochain caractère
mot += c; // string is complete
c = *(program++); // next character
}
stop = TRUE;
stop = true;
}
// cas particulier pour les nombres
// special case for numbers
if ( CharInList(mot[0], num ))
{
BOOL bdot = FALSE; // trouvé un point ?
BOOL bexp = FALSE; // trouvé un exposant ?
bool bdot = false; // found a point?
bool bexp = false; // found an exponent?
char* liste = num;
if (mot[0] == '0' && c == 'x') // valeur hexadécimale ?
if (mot[0] == '0' && c == 'x') // hexadecimal value?
{
mot += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
liste = hexnum;
}
cw:
while (c != 0 && CharInList(c, liste))
{
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' ) )
{
bexp = TRUE;
bexp = true;
mot += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
if ( c == '-' ||
c == '+' ) goto cc;
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;
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
c = *(program++); // prochain caractère
mot += c; // build the word
c = *(program++); // next character
}
stop = TRUE;
stop = true;
}
}
while (TRUE)
while (true)
{
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:
while (CharInList(c, sep2))
{
sep += c; // tous les séparateurs qui suivent
sep += c; // after all the separators
c = *(program++);
}
if (c == '/' && *program == '/') // un commentaire dans le tas ?
if (c == '/' && *program == '/') // comment on the heap?
{
while( c != '\n' && c != 0 )
{
sep += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
}
goto bis;
}
if (c == '/' && *program == '*') // un commentaire dans le tas ?
if (c == '/' && *program == '*') // comment on the heap?
{
while( c != 0 && (c != '*' || *program != '/'))
{
sep += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
}
if ( c != 0 )
{
sep += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
sep += c;
c = *(program++); // prochain caractère
c = *(program++); // next character
}
goto bis;
}
@ -364,13 +369,13 @@ bis:
token->m_IdKeyWord = GivKeyWords(mot);
if (token->m_IdKeyWord > 0) token->m_type = TokenTypKeyWord;
else GivKeyDefNum(mot, token) ; // traite les DefineNum
else GivKeyDefNum(mot, token) ; // treats DefineNum
return token;
}
mot += c; // construit le mot
c = *(program++); // prochain caractère
mot += c; // built the word
c = *(program++); // next character
}
}
@ -381,7 +386,7 @@ CBotToken* CBotToken::CompileTokens(const char* program, int& error)
int pos = 0;
error = 0;
prv = tokenbase = NextToken(p, error, TRUE);
prv = tokenbase = NextToken(p, error, true);
if (tokenbase == NULL) return NULL;
@ -393,24 +398,24 @@ CBotToken* CBotToken::CompileTokens(const char* program, int& error)
char* pp = p;
while (NULL != (nxt = NextToken(p, error)))
{
prv->m_next = nxt; // ajoute à la suite
prv->m_next = nxt; // added after
nxt->m_prev = prv;
prv = nxt; // avance
prv = nxt; // advance
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;
pos += nxt->m_Sep.GivLength();*/
pos += (p - pp); // taille totale
pos += (p - pp); // total size
nxt->m_end = pos - nxt->m_Sep.GivLength();
pp = p;
}
// ajoute un token comme terminateur
// ( utile pour avoir le précédent )
// adds a token as a terminator
// ( useful for the previous )
nxt = new CBotToken();
nxt->m_type = 0;
prv->m_next = nxt; // ajoute à la suite
prv->m_next = nxt; // added after
nxt->m_prev = prv;
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)
{
@ -431,7 +436,7 @@ int CBotToken::GivKeyWords(const char* w)
if (l == 0)
{
LoadKeyWords(); // prend la liste la première fois
LoadKeyWords(); // takes the list for the first time
l = m_ListKeyWords.GivSize();
}
@ -443,7 +448,7 @@ int CBotToken::GivKeyWords(const char* w)
return -1;
}
BOOL CBotToken::GivKeyDefNum(const char* w, CBotToken* &token)
bool CBotToken::GivKeyDefNum(const char* w, CBotToken* &token)
{
int i;
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_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()
{
CBotString s;
int i, n = 0;
i = TokenKeyWord;
i = TokenKeyWord; //start with keywords of the language
while (s.LoadString(i))
{
m_ListKeyWords.Add(s);
m_ListIdKeyWords[n++] = i++;
}
i = TokenKeyDeclare;
i = TokenKeyDeclare; //keywords of declarations
while (s.LoadString(i))
{
m_ListKeyWords.Add(s);
@ -483,14 +492,14 @@ void CBotToken::LoadKeyWords()
}
i = TokenKeyVal;
i = TokenKeyVal; //keywords of values
while (s.LoadString(i))
{
m_ListKeyWords.Add(s);
m_ListIdKeyWords[n++] = i++;
}
i = TokenKeyOp;
i = TokenKeyOp; //operators
while (s.LoadString(i))
{
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 l = m_ListKeyDefine.GivSize();
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_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 ||
p->GivType() == type2 )
{
p = p->GivNext();
return TRUE;
return true;
}
return FALSE;
return false;
}
// idem avec un nombre indéfini d'arguments
// il faut mettre un zéro comme dernier argument
BOOL IsOfTypeList(CBotToken* &p, int type1, ...)
// Same with any number of arguments
// There must be a zero as the last argument
bool IsOfTypeList(CBotToken* &p, int type1, ...)
{
int i = type1;
int max = 20;
@ -536,18 +544,18 @@ BOOL IsOfTypeList(CBotToken* &p, int type1, ...)
va_list marker;
va_start( marker, type1 ); /* Initialize variable arguments. */
while (TRUE)
while (true)
{
if (type == i)
{
p = p->GivNext();
va_end( marker ); /* Reset variable arguments. */
return TRUE;
return true;
}
if (--max == 0 || 0 == (i = va_arg( marker, int)))
{
va_end( marker ); /* Reset variable arguments. */
return FALSE;
return false;
}
}
}

View File

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

View File

@ -12,18 +12,20 @@
// * 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/.///////////////////////////////////////////////////
// expression du genre Opérande1 + Opérande2
// Opérande1 > Opérande2
// * along with this program. If not, see http://www.gnu.org/licenses/.
///////////////////////////////////////////////////
// expression of type Opérande1 + Opérande2
// Opérande1 > Opérande2
#include "CBot.h"
// divers constructeurs
// various constructors
CBotTwoOpExpr::CBotTwoOpExpr()
{
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
}
@ -37,7 +39,7 @@ CBotLogicExpr::CBotLogicExpr()
{
m_condition =
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
}
@ -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 FLOTANT ((1<<CBotTypFloat)|(1<<CBotTypDouble))
#define BOOLEEN (1<<CBotTypBoolean)
@ -57,9 +59,9 @@ CBotLogicExpr::~CBotLogicExpr()
#define POINTER (1<<CBotTypPointer)
#define INSTANCE (1<<CBotTypClass)
// liste des opérations (précéance)
// type acceptable, opérande
// le zéro termine un niveau de précéance
// list of operations (précéance)
// acceptable type, operand
// zero ends level \TODO précéance
static int ListOp[] =
{
@ -95,26 +97,26 @@ static int ListOp[] =
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++;
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);
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)
{
@ -122,25 +124,25 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
if ( pOperations == NULL ) pOperations = ListOp;
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) ?
CBotParExpr::Compile( p, pStk ) : // expression (...) à gauche
CBotTwoOpExpr::Compile( p, pStk, pOp ); // expression A * B à gauche
CBotParExpr::Compile( p, pStk ) : // expression (...) left
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();
if ( IsInList( TypeOp, pOperations, typemasque ) )
{
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) )
{
@ -150,7 +152,7 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
CBotLogicExpr* inst = new CBotLogicExpr();
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);
CBotToken* pp = p;
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);
}
pStk->SetType(type1); // le plus grand des 2 types
pStk->SetType(type1); // the greatest of 2 types
return pStack->Return(inst, pStk);
}
CBotTwoOpExpr* inst = new CBotTwoOpExpr(); // élément pour opération
inst->SetToken(p); // mémorise l'opération
CBotTwoOpExpr* inst = new CBotTwoOpExpr(); // element for operation
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 )) )
// 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) );
if ( TypeOp == ID_ADD && type1.Eq(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) )
{
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 )
{
@ -224,25 +226,25 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
case ID_LS:
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;
// spécial pour évaluer les opérations de même niveau de gauche à droite
while ( IsInList( p->GivType(), pOperations, typemasque ) ) // même(s) opération(s) suit ?
// special for evaluation of the operations of the same level from left to right
while ( IsInList( p->GivType(), pOperations, typemasque ) ) // same operation(s) follows?
{
TypeOp = p->GivType();
CBotTwoOpExpr* i = new CBotTwoOpExpr(); // élément pour opération
i->SetToken(p); // mémorise l'opération
i->m_leftop = inst; // opérande de gauche
CBotTwoOpExpr* i = new CBotTwoOpExpr(); // element for operation
i->SetToken(p); // stores the operation
i->m_leftop = inst; // left operand
type1 = TypeRes;
p = p->GivNext(); // avance à la suite
p = p->GivNext(); // advance after
i->m_rightop = CBotTwoOpExpr::Compile( p, pStk, pOp );
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);
delete i;
@ -256,96 +258,96 @@ CBotInstr* CBotTwoOpExpr::Compile(CBotToken* &p, CBotCStack* pStack, int* pOpera
CBotTypResult t(type1);
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));
// et rend l'object à qui l'a demandé
// and returns the requested object
return pStack->Return(inst, pStk);
}
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 inst;
// et transmet l'erreur qui se trouve sur la pile
// and transmits the error to the stack
return pStack->Return(NULL, pStk);
}
// si on n'a pas affaire à une opération + ou -
// rend à qui l'a demandé, l'opérande (de gauche) trouvé
// à la place de l'objet "addition"
// if we are not dealing with an operation + or -
// goes to that requested, the operand (left) found
// instead of the object "addition"
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 ( 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
// ou le retrouve en cas de reprise
// if ( pStk1 == EOX ) return TRUE;
CBotStack* pStk1 = pStack->AddStack(this); // adds an item to the stack
// or return in case of recovery
// 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
if ( (GivTokenType() == ID_LOG_AND || GivTokenType() == ID_TXT_AND ) && pStk1->GivVal() == FALSE )
// 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 )
{
CBotVar* res = CBotVar::Create( (CBotToken*)NULL, CBotTypBoolean);
res->SetValInt(FALSE);
res->SetValInt(false);
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);
res->SetValInt(TRUE);
res->SetValInt(true);
pStk1->SetVar(res);
return pStack->Return(pStk1); // transmet le résultat
return pStack->Return(pStk1); // transmits the result
}
// passe à l'étape suivante
pStk1->SetState(1); // prêt pour la suite
// passes to the next step
pStk1->SetState(1); // ready for further
}
// demande un peu plus de stack pour ne pas toucher le résultat de gauche
// qui se trouve sur la pile, justement.
// requires a little more stack to avoid touching the result
// of which is left on the stack, precisely
CBotStack* pStk2 = pStk1->AddStack(); // ajoute un élément à la pile
// ou le retrouve en cas de reprise
CBotStack* pStk2 = pStk1->AddStack(); // adds an item to the stack
// 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 ( !m_rightop->Execute(pStk2) ) return FALSE; // interrompu ici ?
if ( !m_rightop->Execute(pStk2) ) return false; // interrupted here?
pStk2->IncState();
}
CBotTypResult type1 = pStk1->GivTypResult(); // de quels types les résultats ?
CBotTypResult type1 = pStk1->GivTypResult(); // what kind of results?
CBotTypResult type2 = pStk2->GivTypResult();
CBotStack* pStk3 = pStk2->AddStack(this); // ajoute un élément à la pile
if ( pStk3->IfStep() ) return FALSE; // montre l'opération si step by step
CBotStack* pStk3 = pStk2->AddStack(this); // adds an item to the stack
if ( pStk3->IfStep() ) return false; // shows the operation if step by step
// crée une variable temporaire pour y mettre le résultat
// quel est le type du résultat ?
// creates a temporary variable to put the result
// what kind of result?
int TypeRes = MAX(type1.GivType(), type2.GivType());
if ( GivTokenType() == ID_ADD && type1.Eq(CBotTypString) )
@ -371,10 +373,10 @@ BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack)
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);
// 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());
if ( GivTokenType() == ID_ADD && type1.Eq(CBotTypString) )
@ -389,70 +391,70 @@ BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack)
else temp = CBotVar::Create( (CBotToken*)NULL, TypeRes );
int err = 0;
// fait l'opération selon la demande
// is a operation according to request
CBotVar* left = pStk1->GivVar();
CBotVar* right = pStk2->GivVar();
switch (GivTokenType())
{
case ID_ADD:
if ( !IsNan(left, right, &err) ) result->Add(left , right); // additionne
if ( !IsNan(left, right, &err) ) result->Add(left , right); // addition
break;
case ID_SUB:
if ( !IsNan(left, right, &err) ) result->Sub(left , right); // soustrait
if ( !IsNan(left, right, &err) ) result->Sub(left , right); // substraction
break;
case ID_MUL:
if ( !IsNan(left, right, &err) ) result->Mul(left , right); // multiplie
if ( !IsNan(left, right, &err) ) result->Mul(left , right); // multiplies
break;
case ID_POWER:
if ( !IsNan(left, right, &err) ) result->Power(left , right); // puissance
if ( !IsNan(left, right, &err) ) result->Power(left , right); // power
break;
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;
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;
case ID_LO:
if ( !IsNan(left, right, &err) )
result->SetValInt(temp->Lo(left , right)); // inférieur
result->SetValInt(temp->Lo(left , right)); // lower
break;
case ID_HI:
if ( !IsNan(left, right, &err) )
result->SetValInt(temp->Hi(left , right)); // supérieur
result->SetValInt(temp->Hi(left , right)); // top
break;
case ID_LS:
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;
case ID_HS:
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;
case ID_EQ:
if ( IsNan(left, right) )
result->SetValInt(left->GivInit() == right->GivInit()) ;
else
result->SetValInt(temp->Eq(left , right)); // égal
result->SetValInt(temp->Eq(left , right)); // equal
break;
case ID_NE:
if ( IsNan(left, right) )
result->SetValInt(left ->GivInit() != right->GivInit()) ;
else
result->SetValInt(temp->Ne(left , right)); // différent
result->SetValInt(temp->Ne(left , right)); // different
break;
case ID_TXT_AND:
case ID_LOG_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;
case ID_TXT_OR:
case ID_LOG_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;
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;
case ID_ASR:
if ( !IsNan(left, right, &err) ) result->ASR(left , right);
@ -468,68 +470,68 @@ BOOL CBotTwoOpExpr::Execute(CBotStack* &pStack)
}
delete temp;
pStk2->SetVar(result); // met le résultat sur la pile
if ( err ) pStk2->SetError(err, &m_token); // et l'erreur éventuelle (division par zéro)
pStk2->SetVar(result); // puts the result on the stack
if ( err ) pStk2->SetError(err, &m_token); // and the possible error (division by zero)
// pStk1->Return(pStk2); // libère la pile
return pStack->Return(pStk2); // transmet le résultat
// pStk1->Return(pStk2); // releases the stack
return pStack->Return(pStk2); // transmits the result
}
void CBotTwoOpExpr::RestoreState(CBotStack* &pStack, BOOL bMain)
void CBotTwoOpExpr::RestoreState(CBotStack* &pStack, bool bMain)
{
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;
// 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;
}
CBotStack* pStk2 = pStk1->RestoreStack(); // ajoute un élément à la pile
CBotStack* pStk2 = pStk1->RestoreStack(); // adds an item to the stack
if ( pStk2 == NULL ) return;
// 2e état, évalue l'opérande de droite
// second state, evaluates the right operand
if ( pStk2->GivState() == 0 )
{
m_rightop->RestoreState(pStk2, bMain); // interrompu ici !
m_rightop->RestoreState(pStk2, bMain); // interrupted here!
return;
}
}
BOOL CBotLogicExpr::Execute(CBotStack* &pStack)
bool CBotLogicExpr::Execute(CBotStack* &pStack)
{
CBotStack* pStk1 = pStack->AddStack(this); // ajoute un élément à la pile
// ou le retrouve en cas de reprise
// if ( pStk1 == EOX ) return TRUE;
CBotStack* pStk1 = pStack->AddStack(this); // adds an item to the stack
// or return in case of recovery
// if ( pStk1 == EOX ) return true;
if ( pStk1->GivState() == 0 )
{
if ( !m_condition->Execute(pStk1) ) return FALSE;
if (!pStk1->SetState(1)) return FALSE;
if ( !m_condition->Execute(pStk1) ) 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
{
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;
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->GivState() == 0 )
@ -538,7 +540,7 @@ void CBotLogicExpr::RestoreState(CBotStack* &pStack, BOOL bMain)
return;
}
if ( pStk1->GivVal() == TRUE )
if ( pStk1->GivVal() == true )
{
m_op1->RestoreState(pStk1, bMain);
}
@ -557,7 +559,7 @@ void t()
#endif
#if 01
void t(BOOL t)
void t(bool t)
{
int x;
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
CBotVar.cpp
CBotWhile.cpp
CBot.rc
)
add_library(CBot SHARED ${SOURCES})

View File

@ -12,13 +12,15 @@
// * 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/.// 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 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!
{
@ -35,110 +37,110 @@ void PrepareFilename(CBotString &filename) //DD!
pos = filename.ReverseFind('\\');
if ( pos > 0 )
{
filename = filename.Mid(pos+1); // enlève les dossiers
filename = filename.Mid(pos+1); // remove the records (files)??
}
pos = filename.ReverseFind('/');
if ( pos > 0 )
{
filename = filename.Mid(pos+1); // aussi ceux avec /
filename = filename.Mid(pos+1); // also those with /
}
pos = filename.ReverseFind(':');
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;
}
// constructeur de la classe
// reçois le nom du fichier en paramètre
// constructor of the class
// gets the filename as a parameter
// exécution
BOOL rfconstruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
bool rfconstruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{
CBotString mode;
// accepte sans paramètre
if ( pVar == NULL ) return TRUE;
// accepts no parameters
if ( pVar == NULL ) return true;
// qui doit être une chaîne de caractères
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return FALSE; }
// must be a string
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return false; }
CBotString filename = pVar->GivValString();
PrepareFilename(filename); //DR
// il peut y avoir un second paramètre
// there may be a second parameter
pVar = pVar->GivNext();
if ( pVar != NULL )
{
// récupère le mode
// recovers the mode
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
if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return FALSE; }
// no third parameter, only two or one possible
if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return false; }
}
// enregistre le nom du fichier
// save the file name
pVar = pThis->GivItem("filename");
pVar->SetValString(filename);
if ( ! mode.IsEmpty() )
{
// ouvre le ficher demandé
// open the called file
FILE* pFile = fopen( filename, mode );
if ( pFile == NULL ) { Exception = CBotErrFileOpen; return FALSE; }
if ( pFile == NULL ) { Exception = CBotErrFileOpen; return false; }
m_CompteurFileOpen ++;
// enregiste le canal du fichier
// save the handle of file
pVar = pThis->GivItem("handle");
pVar->SetValInt((long)pFile);
}
return TRUE;
return true;
}
// compilation
CBotTypResult cfconstruct (CBotVar* pThis, CBotVar* &pVar)
{
// accepte sans paramètre
// accepts no parameters
if ( pVar == NULL ) return CBotTypResult( 0 );
// qui doit être une chaine
// must be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString );
// il peut y avoir un second paramètre
// there may be a second parameter
pVar = pVar->GivNext();
if ( pVar != NULL )
{
// qui doit être une chaine
// must be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString );
// pas de 3e paramètre
// no third parameter
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 );
}
// destructeur de la classe
// destructor of the class
// exécution
BOOL rfdestruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
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");
// pas ouvert ? pas de problème
if ( pVar->GivInit() != IS_DEF) return TRUE;
// not open? no problem
if ( pVar->GivInit() != IS_DEF) return true;
FILE* pFile= (FILE*)pVar->GivValInt();
fclose(pFile);
@ -146,112 +148,112 @@ BOOL rfdestruct (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception
pVar->SetInit(IS_NAN);
return TRUE;
return true;
}
// méthode FILE :: open
// reçois le mode r/w en paramètre
// FILE :: open method
// get the r / w mode as a parameter
// exécution
BOOL rfopen (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
bool rfopen (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{
// il doit y avoir un paramètre
if ( pVar == NULL ) { Exception = CBotErrLowParam; return FALSE; }
// there must be a parameter
if ( pVar == NULL ) { Exception = CBotErrLowParam; return false; }
// qui doit être une chaîne de caractères
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return FALSE; }
// must be a string
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 )
{
// 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();
PrepareFilename(filename); //DR
// enregistre le nom du fichier
// saves the file name
CBotVar* pVar2 = pThis->GivItem("filename");
pVar2->SetValString(filename);
// paramètre suivant est le mode
// next parameter is the mode
pVar = pVar -> GivNext();
}
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
if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return FALSE; }
// No third parameter
if ( pVar->GivNext() != NULL ) { Exception = CBotErrOverParam; return false; }
// récupère l'élément "handle"
// retrieves the element "handle"
pVar = pThis->GivItem("handle");
// qui doit pas être initialisé
if ( pVar->GivInit() == IS_DEF) { Exception = CBotErrFileOpen; return FALSE; }
// which must not be initialized
if ( pVar->GivInit() == IS_DEF) { Exception = CBotErrFileOpen; return false; }
// reprend le nom du fichier
// contains filename
pVar = pThis->GivItem("filename");
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 );
if ( pFile == NULL ) //DR
{
pResult->SetValInt(FALSE); //DR
return TRUE; //DR
pResult->SetValInt(false); //DR
return true; //DR
}
m_CompteurFileOpen ++;
// enregiste le canal du fichier
// saves the handle of file
pVar = pThis->GivItem("handle");
pVar->SetValInt((long)pFile);
pResult->SetValInt(TRUE); //DR
return TRUE;
pResult->SetValInt(true); //DR
return true;
}
// compilation
CBotTypResult cfopen (CBotVar* pThis, CBotVar* &pVar)
{
// il doit y avoir un paramètre
// there must be a parameter
if ( pVar == NULL ) return CBotTypResult( CBotErrLowParam );
// qui doit être une chaine
// must be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString );
// il peut y avoir un second paramètre
// there may be a second parameter
pVar = pVar->GivNext();
if ( pVar != NULL )
{
// qui doit être une chaine
// must be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( CBotErrBadString );
// pas de 3e paramètre
// no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam );
}
// le résultat est de type bool
// the result is of type bool
return CBotTypResult(CBotTypBoolean); //DR
}
// méthode FILE :: close
// FILE :: close method
// exécution
BOOL rfclose (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
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;
// récupère l'élément "handle"
// retrieves the element "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();
fclose(pFile);
@ -259,75 +261,75 @@ BOOL rfclose (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
pVar->SetInit(IS_NAN);
return TRUE;
return true;
}
// compilation
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 );
// la fonction retourne un résultat "void"
// function returns a result "void"
return CBotTypResult( 0 );
}
// méthode FILE :: writeln
// FILE :: writeln method
// exécution
BOOL rfwrite (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
bool rfwrite (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{
// il doit y avoir un paramètre
if ( pVar == NULL ) { Exception = CBotErrLowParam; return FALSE; }
// there must be a parameter
if ( pVar == NULL ) { Exception = CBotErrLowParam; return false; }
// qui doit être une chaîne de caractères
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return FALSE; }
// must be a string
if ( pVar->GivType() != CBotTypString ) { Exception = CBotErrBadString; return false; }
CBotString param = pVar->GivValString();
// récupère l'élément "handle"
//retrieves the element "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();
int res = fputs(param+CBotString("\n"), pFile);
// en cas d'erreur génère une exception
if ( res < 0 ) { Exception = CBotErrWrite; return FALSE; }
// on error throws an exception
if ( res < 0 ) { Exception = CBotErrWrite; return false; }
return TRUE;
return true;
}
// compilation
CBotTypResult cfwrite (CBotVar* pThis, CBotVar* &pVar)
{
// il doit y avoir un paramètre
// there must be a parameter
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 );
// pas d'autre paramètre
// no other parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( CBotErrOverParam );
// la fonction retourne un résultat void
// function returns "void" result
return CBotTypResult( 0 );
}
// méthode FILE :: readln
// FILE :: readln method
// exécution
BOOL rfread (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
bool rfread (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{
// il ne doit pas y avoir de paramètre
if ( pVar != NULL ) { Exception = CBotErrOverParam; return FALSE; }
// there shouldn't be any parameter
if ( pVar != NULL ) { Exception = CBotErrOverParam; return false; }
// récupère l'élément "handle"
//retrieves the element "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();
@ -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;
// en cas d'erreur génère une exception
if ( ferror(pFile) ) { Exception = CBotErrRead; return FALSE; }
// on error throws an exception
if ( ferror(pFile) ) { Exception = CBotErrRead; return false; }
pResult->SetValString( chaine );
return TRUE;
return true;
}
// compilation
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 );
// la fonction retourne un résultat "string"
// function return "string" result
return CBotTypResult( CBotTypString );
}
// méthode FILE :: readln
// FILE :: readln method
// exécution
BOOL rfeof (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
// execution
bool rfeof (CBotVar* pThis, CBotVar* pVar, CBotVar* pResult, int& Exception)
{
// il ne doit pas y avoir de paramètre
if ( pVar != NULL ) { Exception = CBotErrOverParam; return FALSE; }
// there shouldn't be any parameter
if ( pVar != NULL ) { Exception = CBotErrOverParam; return false; }
// récupère l'élément "handle"
// retrieves the element "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();
pResult->SetValInt( feof( pFile ) );
return TRUE;
return true;
}
// compilation
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 );
// la fonction retourne un résultat booleen
// function return boolean result
return CBotTypResult( CBotTypBoolean );
}
@ -393,25 +395,25 @@ CBotTypResult cfeof (CBotVar* pThis, CBotVar* &pVar)
void InitClassFILE()
{
// crée une classe pour la gestion des fichiers
// l'utilisation en est la suivante:
// creates a class for file management
// the usage is as follows:
// file canal( "NomFichier.txt" )
// canal.open( "r" ); // ouvre en lecture
// s = canal.readln( ); // lit une ligne
// canal.close(); // referme le fichier
// canal.open( "r" ); // open reading
// s = canal.readln( ); // reads a line
// canal.close(); // closes the file
// crée la classe FILE
// create class FILE
m_pClassFILE = new CBotClass("file", NULL);
// ajoute le composant ".filename"
// add the component ".filename"
m_pClassFILE->AddItem("filename", CBotTypString);
// ajoute le composant ".handle"
// add the component ".handle"
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", rfdestruct, NULL );
// défini les méthodes associées
// defined associated methods
m_pClassFILE->AddFunction("open", rfopen, cfopen );
m_pClassFILE->AddFunction("close", rfclose, cfclose );
m_pClassFILE->AddFunction("writeln", rfwrite, cfwrite );
@ -421,6 +423,6 @@ void InitClassFILE()
m_pFuncFile = new CBotProgram( );
CBotStringArray 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.
// *
// * 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
// exécution
// gives the length of a chain
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// pas de second paramètre
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; }
// no second parameter
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();
// met la longueur sur la pile
// puts the length of the stack
pResult->SetValInt( s.GivLength() );
return TRUE;
return true;
}
// int xxx ( string )
@ -42,54 +44,54 @@ BOOL rStrLen( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cIntStr( CBotVar* &pVar, void* pUser )
{
// il faut un paramètre
// it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADPARAM );
// pas de second paramètre
// no second parameter
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 );
}
// donne la partie gauche d'une chaîne
// exécution
// gives the left side of a chain
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être un nombre
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; }
// which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre
// retrieves this number
int n = pVar->GivValInt();
// pas de 3e paramètre
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; }
// no third parameter
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return true; }
// prend la partie intéressante
// takes the interesting part
s = s.Left( n );
// la met sur la pile
// puts on the stack
pResult->SetValString( s );
return TRUE;
return true;
}
// string xxx ( string, int )
@ -97,175 +99,175 @@ BOOL rStrLeft( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cStrStrInt( CBotVar* &pVar, void* pUser )
{
// il faut un paramètre
// it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING );
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être un nombre
// which must be a number
if ( pVar->GivType() > CBotTypDouble )
return CBotTypResult( TX_BADNUM );
// pas de 3e paramètre
// no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est une string
// the end result is a string
return CBotTypResult( CBotTypString );
}
// donne la partie droite d'une chaîne
// exécution
// gives the right of a string
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être un nombre
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; }
// which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre
// retrieves this number
int n = pVar->GivValInt();
// pas de 3e paramètre
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; }
// no third parameter
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return true; }
// prend la partie intéressante
// takes the interesting part
s = s.Right( n );
// la met sur la pile
// puts on the stack
pResult->SetValString( s );
return TRUE;
return true;
}
// donne la partie centrale d'une chaîne
// exécution
// gives the central part of a chain
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être un nombre
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; }
// which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre
// retrieves this number
int n = pVar->GivValInt();
// 3e paramètre optionnel
// third parameter optional
if ( pVar->GivNext() != NULL )
{
pVar = pVar->GivNext();
// qui doit être un nombre
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return TRUE; }
// which must be a number
if ( pVar->GivType() > CBotTypDouble ) { ex = TX_BADNUM ; return true; }
// récupère ce nombre
// retrieves this number
int l = pVar->GivValInt();
// mais pas de 4e paramètre
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; }
// but no fourth parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
// prend la partie intéressante
// takes the interesting part
s = s.Mid( n, l );
}
else
{
// prend la partie intéressante
// takes the interesting part
s = s.Mid( n );
}
// la met sur la pile
// puts on the stack
pResult->SetValString( s );
return TRUE;
return true;
}
// donne la partie centrale d'une chaîne
// gives the central part of a chain
// compilation
CBotTypResult cStrStrIntInt( CBotVar* &pVar, void* pUser )
{
// il faut un paramètre
// it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING );
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être un nombre
// which must be a number
if ( pVar->GivType() > CBotTypDouble )
return CBotTypResult( TX_BADNUM );
// 3e paramètre optionnel
// third parameter optional
if ( pVar->GivNext() != NULL )
{
pVar = pVar->GivNext();
// qui doit être un nombre
// which must be a number
if ( pVar->GivType() > CBotTypDouble )
return CBotTypResult( TX_BADNUM );
// pas de 4e paramètre
// no fourth parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
}
// le résultat final est une string
// the end result is a string
return CBotTypResult( CBotTypString );
}
// donne le nombre contenu dans une chaîne
// exécution
// gives the number stored in a string
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// mais pas de 2e paramètre
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; }
// but no second parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
float val = GivNumFloat(s);
// la met la valeur sur la pile
// puts the value on the stack
pResult->SetValFloat( val );
return TRUE;
return true;
}
// float xxx ( string )
@ -273,53 +275,53 @@ BOOL rStrVal( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cFloatStr( CBotVar* &pVar, void* pUser )
{
// il faut un paramètre
// it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING );
// pas de 2e paramètre
// no second parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est un nombre
// the end result is a number
return CBotTypResult( CBotTypFloat );
}
// trouve une chaine dans une autre
// exécution
// find string in other
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return true; }
// récupère ce nombre
// retrieves this number
CBotString s2 = pVar->GivValString();
// pas de 3e paramètre
if ( pVar->GivNext() != NULL ) { ex = TX_OVERPARAM ; return TRUE; }
// no third parameter
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);
pResult->SetValInt( res );
if ( res < 0 ) pResult->SetInit( IS_NAN );
return TRUE;
return true;
}
// int xxx ( string, string )
@ -327,76 +329,76 @@ BOOL rStrFind( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cIntStrStr( CBotVar* &pVar, void* pUser )
{
// il faut un paramètre
// it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING );
// il faut un second paramètre
// it takes a second parameter
pVar = pVar->GivNext();
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING );
// pas de 3e paramètre
// no third parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est un nombre
// the end result is a number
return CBotTypResult( CBotTypInt );
}
// donne une chaine en majuscule
// exécution
// gives a string to uppercase
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// mais pas de 2e paramètre
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; }
// but no second parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
s.MakeUpper();
// la met la valeur sur la pile
// puts the value on the stack
pResult->SetValString( s );
return TRUE;
return true;
}
// donne une chaine en minuscules
// exécution
// gives a string to lowercase
// 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
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return TRUE; }
// it takes a parameter
if ( pVar == NULL ) { ex = TX_LOWPARAM ; return true; }
// qui doit être une string
if ( pVar->GivType() != CBotTypString ) { ex = TX_BADSTRING ; return TRUE; }
// to be a string
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();
// mais pas de 2e paramètre
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return TRUE; }
// but no second parameter
if ( pVar->GivNext() != NULL ){ ex = TX_OVERPARAM ; return true; }
s.MakeLower();
// la met la valeur sur la pile
// puts the value on the stack
pResult->SetValString( s );
return TRUE;
return true;
}
// string xxx ( string )
@ -404,17 +406,17 @@ BOOL rStrLower( CBotVar* pVar, CBotVar* pResult, int& ex, void* pUser )
CBotTypResult cStrStr( CBotVar* &pVar, void* pUser )
{
// il faut un paramètre
// it takes a parameter
if ( pVar == NULL ) return CBotTypResult( TX_LOWPARAM );
// qui doit être une string
// to be a string
if ( pVar->GivType() != CBotTypString )
return CBotTypResult( TX_BADSTRING );
// pas de 2e paramètre
// no second parameter
if ( pVar->GivNext() != NULL ) return CBotTypResult( TX_OVERPARAM );
// le résultat final est une string
// the end result is a string
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)
est a conserver tel quel, en dehors des vars sur la pile
for managing instances of a class.
il faut un autre type de variable pour garder les pointeurs
CBotTypPtClass par exemple
the object being created with CBotVar :: Create (name, pClasse)
is to keep as is, outside the vars on the stack
L'instance de la classe doit avoir un compteur d'utilisation
qui est le nombre d'objet de classe CBotTypPtClass qui y réfèrent.
Le compteur est décrémenté lorsque le pointeur est détruit,
l'objet supprimé lorsqu'il n'y a plus de pointeurs.
we need another type of variable to keep the pointers
For example CBotTypPtClass
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"
et peut retourner des pointeurs à cette instance par des routines genre FindRobot()
In the case of robots, Daniel creates an instance of class "Object"
and can return pointers to this proceeding by routines such FindRobot ()
Object FindRobot (int n) {}
pResult dans ce cas est un pointeur CBotTypPtClass
lorsqu'il a trouvé le robot concerné, il lui faudra faire
pResult in this case is a pointer CBotTypPtClass
when he found the robot concerned, it must make
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
est détruit également.
s'il reste des pointeurs à cet objet, et l'on risque la planté
when the robot is destroyed, the instance of the Object class corresponding
is also destroyed.
if there are pointers to that object, and we planted the risk
solution 1:
garder non pas le pointeur à l'objet directement, mais
un index dans une tables de pointeurs
Solution 1:
not keep the pointer to the object directly, but
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.
// *
// * 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}}
// Microsoft Developer Studio generated include file.
// Used by CBot.rc
//
#define ID_KEYWORDS 2000
#define ID_IF 2000
#define ID_ELSE 2001
#define ID_WHILE 2002
#define ID_DO 2003
#define ID_FOR 2004
#define ID_BREAK 2005
#define ID_CONTINUE 2006
#define ID_SWITCH 2007
#define ID_CASE 2008
#define ID_DEFAULT 2009
#define ID_TRY 2010
#define ID_THROW 2011
#define ID_CATCH 2012
#define ID_FINALLY 2013
#define ID_TXT_AND 2014
#define ID_TXT_OR 2015
#define ID_TXT_NOT 2016
#define ID_RETURN 2017
#define ID_CLASS 2018
#define ID_EXTENDS 2019
#define ID_SYNCHO 2020
#define ID_NEW 2021
#define ID_PUBLIC 2022
#define ID_EXTERN 2023
#define ID_FINAL 2024
#define ID_STATIC 2025
#define ID_PROTECTED 2026
#define ID_PRIVATE 2027
#define ID_REPEAT 2028
#define ID_DEBUGDD 2099
#define ID_INT 2100
#define ID_FLOAT 2101
#define ID_BOOLEAN 2102
#define ID_STRING 2103
#define ID_VOID 2104
#define ID_BOOL 2105
#define ID_TRUE 2200
#define ID_FALSE 2201
#define ID_NULL 2202
#define ID_NAN 2203
#define ID_OPENPAR 2300
#define ID_CLOSEPAR 2301
#define ID_OPBLK 2302
#define ID_CLBLK 2303
#define ID_SEP 2304
#define ID_COMMA 2305
#define ID_DOTS 2306
#define ID_DOT 2307
#define ID_OPBRK 2308
#define ID_CLBRK 2309
#define ID_DBLDOTS 2310
#define ID_LOGIC 2311
#define ID_ADD 2312
#define ID_SUB 2313
#define ID_MUL 2314
#define ID_DIV 2315
#define ID_ASS 2316
#define ID_ASSADD 2317
#define ID_ASSSUB 2318
#define ID_ASSMUL 2319
#define ID_ASSDIV 2320
#define ID_ASSOR 2321
#define ID_ASSAND 2322
#define ID_ASSXOR 2323
#define ID_ASSSL 2324
#define ID_ASSSR 2325
#define ID_ASSASR 2326
#define ID_SL 2327
#define ID_SR 2328
#define ID_ASR 2329
#define ID_INC 2330
#define ID_DEC 2331
#define ID_LO 2332
#define ID_HI 2333
#define ID_LS 2334
#define ID_HS 2335
#define ID_EQ 2336
#define ID_NE 2337
#define ID_AND 2338
#define ID_XOR 2339
#define ID_OR 2340
#define ID_LOG_AND 2341
#define ID_LOG_OR 2342
#define ID_LOG_NOT 2343
#define ID_NOT 2344
#define ID_MODULO 2345
#define ID_POWER 2346
#define ID_ASSMODULO 2347
#define TX_UNDEF 4000
#define TX_NAN 4001
// * along with this program. If not, see http://www.gnu.org/licenses/.
#pragma once
#ifndef _RESOURCE_H_
#define _RESOURCE_H_
enum EID
{
ID_IF = 2000,
ID_ELSE,
ID_WHILE,
ID_DO,
ID_FOR,
ID_BREAK,
ID_CONTINUE,
ID_SWITCH,
ID_CASE,
ID_DEFAULT,
ID_TRY,
ID_THROW,
ID_CATCH,
ID_FINALLY,
ID_TXT_AND,
ID_TXT_OR,
ID_TXT_NOT,
ID_RETURN,
ID_CLASS,
ID_EXTENDS,
ID_SYNCHO,
ID_NEW,
ID_PUBLIC,
ID_EXTERN,
ID_FINAL,
ID_STATIC,
ID_PROTECTED,
ID_PRIVATE,
ID_REPEAT,
ID_DEBUGDD,
ID_INT,
ID_FLOAT,
ID_BOOLEAN,
ID_STRING,
ID_VOID,
ID_BOOL,
ID_TRUE = 2200,
ID_FALSE,
ID_NULL,
ID_NAN,
ID_OPENPAR = 2300,
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,
TX_UNDEF = 4000,
TX_NAN,
ID_SUPER = 6000
};
#define TX_OPENPAR 5000
#define TX_CLOSEPAR 5001
#define TX_NOTBOOL 5002
@ -166,15 +173,5 @@
#define TX_NOTOPEN 6013
#define TX_ERRREAD 6014
#define TX_ERRWRITE 6015
#define ID_SUPER 62020
// Next default values for new objects
//
#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
#endif //_RESOURCE_H_

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