commit 7f7fb2fac8cb238ff4b841461ac24eb9c6e5f6f8 Author: Jordan Snelling Date: Tue Aug 21 13:18:59 2012 +0100 Add the entire Master Branch Just moved my data off of my ex4 partition, into my main Windows drive. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..2e62a4e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.cpp diff=cpp +*.h diff=cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..99ea36f --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +map/* +world/* +CMakeFiles/* +src/CMakeFiles/* +src/Makefile +src/cmake_config.h +src/cmake_install.cmake +src/jthread/CMakeFiles/* +src/jthread/Makefile +src/jthread/cmake_config.h +src/jthread/cmake_install.cmake +.*.swp +minetest.conf +bin/ +CMakeCache.txt +CPackConfig.cmake +CPackSourceConfig.cmake +Makefile +cmake_install.cmake +src/jthread/libjthread.a +debug.txt +bin/debug.txt +minetestmapper/map.png diff --git a/.hgignore b/.hgignore new file mode 100644 index 0000000..e4e0caa --- /dev/null +++ b/.hgignore @@ -0,0 +1,25 @@ +map/* +world/* +CMakeFiles/* +src/CMakeFiles/* +src/Makefile +src/cmake_config.h +src/cmake_install.cmake +src/jthread/CMakeFiles/* +src/jthread/Makefile +src/jthread/cmake_config.h +src/jthread/cmake_install.cmake +src/.*.swp +src/sqlite/libsqlite3.a +src/session.vim +util/uloste.png +minetest.conf +debug.txt +bin/ +CMakeCache.txt +CPackConfig.cmake +CPackSourceConfig.cmake +Makefile +cmake_install.cmake +src/jthread/libjthread.a +data_temp/* diff --git a/.hgtags b/.hgtags new file mode 100644 index 0000000..59f4d0e --- /dev/null +++ b/.hgtags @@ -0,0 +1 @@ +a519d683251105654d2a146ae7b91d3850b6504c 0.2.20110731_3 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..63ef5fd --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,120 @@ +cmake_minimum_required(VERSION 2.6) +if(${CMAKE_VERSION} STREQUAL "2.8.2") + # bug http://vtk.org/Bug/view.php?id=11020 + message( WARNING "CMake/CPack version 2.8.2 will not create working .deb packages!") +endif(${CMAKE_VERSION} STREQUAL "2.8.2") + +# This can be read from ${PROJECT_NAME} after project() is called +project(Minetest-Classic) + +set(VERSION_MAJOR 0) +set(VERSION_MINOR 2) +set(VERSION_PATCH DEV-SUN-29-JULY-2012) +set(VERSION_STRING "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") + +# Configuration options + +if(WIN32) + set(RUN_IN_PLACE 1 CACHE BOOL "Run directly in source directory structure") +else() + set(RUN_IN_PLACE 0 CACHE BOOL "Run directly in source directory structure") +endif() + +set(BUILD_CLIENT 1 CACHE BOOL "Build client") +if(WIN32) + set(BUILD_SERVER 0 CACHE BOOL "Build server") +else() + set(BUILD_SERVER 1 CACHE BOOL "Build server") +endif() + +set(WARN_ALL 1 CACHE BOOL "Enable -Wall for Release build") + +if(NOT CMAKE_BUILD_TYPE) + # Default to release + set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type: Debug or Release" FORCE) +endif() + +# Included stuff +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/") +include(${CMAKE_SOURCE_DIR}/cmake/Modules/misc.cmake) + +# This is done here so that relative search paths are more reasnable +find_package(Irrlicht) + +# +# Installation +# + +if(WIN32) + set(DATADIR "data") + set(BINDIR "bin") + set(DOCDIR "doc") + set(EXAMPLE_CONF_DIR ".") +elseif(APPLE) + # random placeholders + set(DATADIR "share/${PROJECT_NAME}") + set(BINDIR "bin") + set(DOCDIR "share/doc/${PROJECT_NAME}") + set(EXAMPLE_CONF_DIR ".") +elseif(UNIX) # Linux, BSD etc + set(DATADIR "share/${PROJECT_NAME}") + set(BINDIR "bin") + set(DOCDIR "share/doc/${PROJECT_NAME}") + set(EXAMPLE_CONF_DIR "share/doc/${PROJECT_NAME}") +endif() + +install(FILES "doc/README.txt" DESTINATION "${DOCDIR}") +install(FILES "doc/changelog.txt" DESTINATION "${DOCDIR}") +install(FILES "minetest.conf.example" DESTINATION "${DOCDIR}") + +# +# Subdirectories +# Be sure to add all relevant definitions above this +# + +add_subdirectory(src) + +# CPack + +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "An InfiniMiner/Minecraft inspired game") +set(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH}) +set(CPACK_PACKAGE_VENDOR "celeron55") +set(CPACK_PACKAGE_CONTACT "Perttu Ahola ") + +if(WIN32) + # For some reason these aren't copied otherwise + # NOTE: For some reason now it seems to work without these + #if(BUILD_CLIENT) + # install(FILES bin/minetest.exe DESTINATION bin) + #endif() + #if(BUILD_SERVER) + # install(FILES bin/minetestserver.exe DESTINATION bin) + #endif() + + set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION_STRING}-win32") + + set(CPACK_GENERATOR ZIP) + + # This might be needed for some installer + #set(CPACK_PACKAGE_EXECUTABLES bin/minetest.exe "Minetest" bin/minetestserver.exe "Minetest Server") +elseif(APPLE) + # TODO + # see http://cmake.org/Wiki/CMake:CPackPackageGenerators#Bundle_.28OSX_only.29 + # + set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION_STRING}-osx") + set(CPACK_PACKAGE_ICON "") + set(CPACK_BUNDLE_NAME ${PROJECT_NAME}) + set(CPACK_BUNDLE_ICON "") + set(CPACK_BUNDLE_PLIST "") + set(CPACK_BUNDLE_STARTUP_COMMAND "Contents/MacOS/${PROJECT_NAME}") + set(CPACK_GENERATOR "Bundle") +else() + set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION_STRING}-linux") + set(CPACK_GENERATOR TGZ) + set(CPACK_SOURCE_GENERATOR TGZ) +endif() + +include(CPack) + diff --git a/CMakeLists.txt~ b/CMakeLists.txt~ new file mode 100644 index 0000000..ec94768 --- /dev/null +++ b/CMakeLists.txt~ @@ -0,0 +1,120 @@ +cmake_minimum_required(VERSION 2.6) +if(${CMAKE_VERSION} STREQUAL "2.8.2") + # bug http://vtk.org/Bug/view.php?id=11020 + message( WARNING "CMake/CPack version 2.8.2 will not create working .deb packages!") +endif(${CMAKE_VERSION} STREQUAL "2.8.2") + +# This can be read from ${PROJECT_NAME} after project() is called +project(minetest) + +set(VERSION_MAJOR 0) +set(VERSION_MINOR 2) +set(VERSION_PATCH 20110922_1) +set(VERSION_STRING "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") + +# Configuration options + +if(WIN32) + set(RUN_IN_PLACE 1 CACHE BOOL "Run directly in source directory structure") +else() + set(RUN_IN_PLACE 0 CACHE BOOL "Run directly in source directory structure") +endif() + +set(BUILD_CLIENT 1 CACHE BOOL "Build client") +if(WIN32) + set(BUILD_SERVER 0 CACHE BOOL "Build server") +else() + set(BUILD_SERVER 1 CACHE BOOL "Build server") +endif() + +set(WARN_ALL 1 CACHE BOOL "Enable -Wall for Release build") + +if(NOT CMAKE_BUILD_TYPE) + # Default to release + set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type: Debug or Release" FORCE) +endif() + +# Included stuff +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/") +include(${CMAKE_SOURCE_DIR}/cmake/Modules/misc.cmake) + +# This is done here so that relative search paths are more reasnable +find_package(Irrlicht) + +# +# Installation +# + +if(WIN32) + set(DATADIR "data") + set(BINDIR "bin") + set(DOCDIR "doc") + set(EXAMPLE_CONF_DIR ".") +elseif(APPLE) + # random placeholders + set(DATADIR "share/${PROJECT_NAME}") + set(BINDIR "bin") + set(DOCDIR "share/doc/${PROJECT_NAME}") + set(EXAMPLE_CONF_DIR ".") +elseif(UNIX) # Linux, BSD etc + set(DATADIR "share/${PROJECT_NAME}") + set(BINDIR "bin") + set(DOCDIR "share/doc/${PROJECT_NAME}") + set(EXAMPLE_CONF_DIR "share/doc/${PROJECT_NAME}") +endif() + +install(FILES "doc/README.txt" DESTINATION "${DOCDIR}") +install(FILES "doc/changelog.txt" DESTINATION "${DOCDIR}") +install(FILES "minetest.conf.example" DESTINATION "${DOCDIR}") + +# +# Subdirectories +# Be sure to add all relevant definitions above this +# + +add_subdirectory(src) + +# CPack + +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "An InfiniMiner/Minecraft inspired game") +set(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH}) +set(CPACK_PACKAGE_VENDOR "celeron55") +set(CPACK_PACKAGE_CONTACT "Perttu Ahola ") + +if(WIN32) + # For some reason these aren't copied otherwise + # NOTE: For some reason now it seems to work without these + #if(BUILD_CLIENT) + # install(FILES bin/minetest.exe DESTINATION bin) + #endif() + #if(BUILD_SERVER) + # install(FILES bin/minetestserver.exe DESTINATION bin) + #endif() + + set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION_STRING}-win32") + + set(CPACK_GENERATOR ZIP) + + # This might be needed for some installer + #set(CPACK_PACKAGE_EXECUTABLES bin/minetest.exe "Minetest" bin/minetestserver.exe "Minetest Server") +elseif(APPLE) + # TODO + # see http://cmake.org/Wiki/CMake:CPackPackageGenerators#Bundle_.28OSX_only.29 + # + set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION_STRING}-osx") + set(CPACK_PACKAGE_ICON "") + set(CPACK_BUNDLE_NAME ${PROJECT_NAME}) + set(CPACK_BUNDLE_ICON "") + set(CPACK_BUNDLE_PLIST "") + set(CPACK_BUNDLE_STARTUP_COMMAND "Contents/MacOS/${PROJECT_NAME}") + set(CPACK_GENERATOR "Bundle") +else() + set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION_STRING}-linux") + set(CPACK_GENERATOR TGZ) + set(CPACK_SOURCE_GENERATOR TGZ) +endif() + +include(CPack) + diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..cbe29db --- /dev/null +++ b/README.txt @@ -0,0 +1,251 @@ +Minetest-c55 +--------------- +An InfiniMiner/Minecraft inspired game. +Copyright (c) 2010-2011 Perttu Ahola +(see source files for other contributors) + +Further documentation: +---------------------- +- Website: http://celeron.55.lt/~celeron55/minetest/ +- Wiki: http://celeron.55.lt/~celeron55/minetest/wiki/ +- Forum: http://celeron.55.lt/~celeron55/minetest/forum/ +- doc/ directory of source distribution + +This game is not finished: +-------------------------- +- Don't expect it to work as well as a finished game will. +- Please report any bugs to me. debug.txt is useful. + +Controls: +--------- +- See the in-game pause menu +- Settable in the configuration file, see the section below. + +Map directory: +-------------- +- Map is stored in a directory, which can be removed to generate a new map. +- There is a command-line option for it: --map-dir +- For a RUN_IN_PLACE build, it is located in: + ../world +- Otherwise something like this: + Windows: C:\Documents and Settings\user\Application Data\minetest\world + Linux: ~/.minetest/world + OS X: ~/Library/Application Support/minetest/world + +Configuration file: +------------------- +- An optional configuration file can be used. See minetest.conf.example. +- Path to file can be passed as a parameter to the executable: + --config +- Defaults: + - If built with -DRUN_IN_PLACE=1: + ../minetest.conf + ../../minetest.conf + - Otherwise something like this: + Windows: C:\Documents and Settings\user\Application Data\minetest\minetest.conf + Linux: ~/.minetest/minetest.conf + OS X: ~/Library/Application Support/minetest.conf + +Command-line options: +--------------------- +- Use --help + +Compiling on GNU/Linux: +----------------------- + +Install dependencies. Here's an example for Debian/Ubuntu: +$ apt-get install build-essential libirrlicht-dev cmake libbz2-dev libpng12-dev libjpeg8-dev libxxf86vm-dev libgl1-mesa-dev + +Download source, extract (this is the URL to the latest of source repository, which might not work at all times): +$ wget https://bitbucket.org/celeron55/minetest/get/tip.tar.gz +$ tar xf tip.tar.gz +$ cd minetest + +Build a version that runs directly from the source directory: +$ cmake . -DRUN_IN_PLACE=1 +$ make -j2 + +Run it: +$ cd bin +$ ./minetest + +- Use cmake . -LH to see all CMake options and their current state +- If you want to install it system-wide (or are making a distribution package), you will want to use -DRUN_IN_PLACE=0 +- You can build a bare server or a bare client by specifying -DBUILD_CLIENT=0 or -DBUILD_SERVER=0 +- You can select between Release and Debug build by -DCMAKE_BUILD_TYPE= + - Note that the Debug build is considerably slower + +Compiling on Windows: +--------------------- + +- You need: + * CMake: + http://www.cmake.org/cmake/resources/software.html + * MinGW or Visual Studio + http://www.mingw.org/ + http://msdn.microsoft.com/en-us/vstudio/default + * Irrlicht SDK 1.7: + http://irrlicht.sourceforge.net/downloads.html + * Zlib headers (zlib125.zip) + http://www.winimage.com/zLibDll/index.html + * Zlib library (zlibwapi.lib and zlibwapi.dll from zlib125dll.zip): + http://www.winimage.com/zLibDll/index.html + * gettext bibrary and tools: + http://gnuwin32.sourceforge.net/downlinks/gettext.php + * And, of course, Minetest-c55: + http://celeron.55.lt/~celeron55/minetest/download +- Steps: + - Select a directory called DIR hereafter in which you will operate. + - Make sure you have CMake and a compiler installed. + - Download all the other stuff to DIR and extract them into there. All those + packages contain a nice base directory in them, which should end up being + the direct subdirectories of DIR. + - You will end up with a directory structure like this (+=dir, -=file): + ----------------- + + DIR + - zlib-1.2.5.tar.gz + - zlib125dll.zip + - irrlicht-1.7.1.zip + - 110214175330.zip (or whatever, this is the minetest source) + + zlib-1.2.5 + - zlib.h + + win32 + ... + + zlib125dll + - readme.txt + + dll32 + ... + + irrlicht-1.7.1 + + lib + + include + ... + + gettext + +bin + +include + +lib + + minetest + + src + + doc + - CMakeLists.txt + ... + ----------------- + - Start up the CMake GUI + - Select "Browse Source..." and select DIR/minetest + - Now, if using MSVC: + - Select "Browse Build..." and select DIR/minetest-build + - Else if using MinGW: + - Select "Browse Build..." and select DIR/minetest + - Select "Configure" + - Select your compiler + - It will warn about missing stuff, ignore that at this point. (later don't) + - Make sure the configuration is as follows + (note that the versions may differ for you): + ----------------- + BUILD_CLIENT [X] + BUILD_SERVER [ ] + CMAKE_BUILD_TYPE Release + CMAKE_INSTALL_PREFIX DIR/minetest-install + IRRLICHT_SOURCE_DIR DIR/irrlicht-1.7.1 + RUN_IN_PLACE [X] + WARN_ALL [ ] + ZLIB_DLL DIR/zlib125dll/dll32/zlibwapi.dll + ZLIB_INCLUDE_DIR DIR/zlib-1.2.5 + ZLIB_LIBRARIES DIR/zlib125dll/dll32/zlibwapi.lib + GETTEXT_BIN_DIR DIR/gettext/bin + GETTEXT_INCLUDE_DIR DIR/gettext/include + GETTEXT_LIBRARIES DIR/gettext/lib/intl.lib + GETTEXT_MSGFMT DIR/gettext/bin/msgfmt + ----------------- + - Hit "Configure" + - Hit "Configure" once again 8) + - If something is still coloured red, you have a problem. + - Hit "Generate" + If using MSVC: + - Open the generated minetest.sln + - The project defaults to the "Debug" configuration. Make very sure to + select "Release", unless you want to debug some stuff (it's slower) + - Build the ALL_BUILD project + - Build the INSTALL project + - You should now have a working game with the executable in + DIR/minetest-install/bin/minetest.exe + - Additionally you may create a zip package by building the PACKAGE + project. + If using MinGW: + - Using the command line, browse to the build directory and run 'make' + (or mingw32-make or whatever it happens to be) + - You should now have a working game with the executable in + DIR/minetest/bin/minetest.exe + +License of Minetest-c55 +----------------------- + +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Irrlicht +--------------- + +This program uses the Irrlicht Engine. http://irrlicht.sourceforge.net/ + + The Irrlicht Engine License + +Copyright © 2002-2005 Nikolaus Gebhardt + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute +it freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + 3. This notice may not be removed or altered from any source + distribution. + + +JThread +--------------- + +This program uses the JThread library. License for JThread follows: + +Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + + diff --git a/cmake/Modules/FindGettextLib.cmake b/cmake/Modules/FindGettextLib.cmake new file mode 100644 index 0000000..5779b6b --- /dev/null +++ b/cmake/Modules/FindGettextLib.cmake @@ -0,0 +1,72 @@ +# Package finder for gettext libs and include files + +SET(CUSTOM_GETTEXT_PATH "${PROJECT_SOURCE_DIR}/../../gettext" + CACHE FILEPATH "path to custom gettext") + +# by default +SET(GETTEXT_FOUND FALSE) + +FIND_PATH(GETTEXT_INCLUDE_DIR + NAMES libintl.h + PATHS "${CUSTOM_GETTEXT_PATH}/include" + DOC "gettext include directory") + +FIND_PROGRAM(GETTEXT_MSGFMT + NAMES msgfmt + PATHS "${CUSTOM_GETTEXT_PATH}/bin" + DOC "path to msgfmt") + +# modern Linux, as well as Mac, seem to not need require special linking +# they do not because gettext is part of glibc +# TODO check the requirements on other BSDs and older Linux +IF (WIN32) + IF(MSVC) + SET(GETTEXT_LIB_NAMES + libintl.lib intl.lib libintl3.lib intl3.lib) + ELSE() + SET(GETTEXT_LIB_NAMES + libintl.dll.a intl.dll.a libintl3.dll.a intl3.dll.a) + ENDIF() + FIND_LIBRARY(GETTEXT_LIBRARY + NAMES ${GETTEXT_LIB_NAMES} + PATHS "${CUSTOM_GETTEXT_PATH}/lib" + DOC "gettext *intl*.lib") + FIND_FILE(GETTEXT_DLL + NAMES libintl.dll intl.dll libintl3.dll intl3.dll + PATHS "${CUSTOM_GETTEXT_PATH}/bin" "${CUSTOM_GETTEXT_PATH}/lib" + DOC "gettext *intl*.dll") + FIND_FILE(GETTEXT_ICONV_DLL + NAMES libiconv2.dll + PATHS "${CUSTOM_GETTEXT_PATH}/bin" "${CUSTOM_GETTEXT_PATH}/lib" + DOC "gettext *iconv*.lib") +ENDIF(WIN32) + +IF(GETTEXT_INCLUDE_DIR AND GETTEXT_MSGFMT) + IF (WIN32) + # in the Win32 case check also for the extra linking requirements + IF(GETTEXT_LIBRARY AND GETTEXT_DLL AND GETTEXT_ICONV_DLL) + SET(GETTEXT_FOUND TRUE) + ENDIF() + ELSE(WIN32) + # *BSD variants require special linkage as they don't use glibc + IF(${CMAKE_SYSTEM_NAME} MATCHES "BSD") + SET(GETTEXT_LIBRARY "intl") + ENDIF(${CMAKE_SYSTEM_NAME} MATCHES "BSD") + SET(GETTEXT_FOUND TRUE) + ENDIF(WIN32) +ENDIF() + +IF(GETTEXT_FOUND) + SET(GETTEXT_PO_PATH ${CMAKE_SOURCE_DIR}/po) + SET(GETTEXT_MO_BUILD_PATH ${CMAKE_BINARY_DIR}/locale//LC_MESSAGES) + SET(GETTEXT_MO_DEST_PATH ${DATADIR}/../locale//LC_MESSAGES) + FILE(GLOB GETTEXT_AVAILABLE_LOCALES RELATIVE ${GETTEXT_PO_PATH} "${GETTEXT_PO_PATH}/*") + LIST(REMOVE_ITEM GETTEXT_AVAILABLE_LOCALES minetest.pot) + MACRO(SET_MO_PATHS _buildvar _destvar _locale) + STRING(REPLACE "" ${_locale} ${_buildvar} ${GETTEXT_MO_BUILD_PATH}) + STRING(REPLACE "" ${_locale} ${_destvar} ${GETTEXT_MO_DEST_PATH}) + ENDMACRO(SET_MO_PATHS) +ELSE() + SET(GETTEXT_INCLUDE_DIR "") + SET(GETTEXT_LIBRARY "") +ENDIF() diff --git a/cmake/Modules/FindIrrlicht.cmake b/cmake/Modules/FindIrrlicht.cmake new file mode 100644 index 0000000..bd00422 --- /dev/null +++ b/cmake/Modules/FindIrrlicht.cmake @@ -0,0 +1,94 @@ +#FindIrrlicht.cmake + +set(IRRLICHT_SOURCE_DIR "" CACHE PATH "Path to irrlicht source directory (optional)") + +if( UNIX ) + # Unix +else( UNIX ) + # Windows +endif( UNIX ) + +# Find include directory + +if(NOT IRRLICHT_SOURCE_DIR STREQUAL "") + set(IRRLICHT_SOURCE_DIR_INCLUDE + "${IRRLICHT_SOURCE_DIR}/include" + ) + + set(IRRLICHT_LIBRARY_NAMES libIrrlicht.a Irrlicht Irrlicht.lib) + + if(WIN32) + if(MSVC) + set(IRRLICHT_SOURCE_DIR_LIBS "${IRRLICHT_SOURCE_DIR}/lib/Win32-visualstudio") + set(IRRLICHT_LIBRARY_NAMES Irrlicht.lib) + else() + set(IRRLICHT_SOURCE_DIR_LIBS "${IRRLICHT_SOURCE_DIR}/lib/Win32-gcc") + set(IRRLICHT_LIBRARY_NAMES libIrrlicht.a libIrrlicht.dll.a) + endif() + else() + set(IRRLICHT_SOURCE_DIR_LIBS "${IRRLICHT_SOURCE_DIR}/lib/Linux") + set(IRRLICHT_LIBRARY_NAMES libIrrlicht.a) + endif() + + FIND_PATH(IRRLICHT_INCLUDE_DIR NAMES irrlicht.h + PATHS + ${IRRLICHT_SOURCE_DIR_INCLUDE} + NO_DEFAULT_PATH + ) + + FIND_LIBRARY(IRRLICHT_LIBRARY NAMES ${IRRLICHT_LIBRARY_NAMES} + PATHS + ${IRRLICHT_SOURCE_DIR_LIBS} + NO_DEFAULT_PATH + ) + +else() + + FIND_PATH(IRRLICHT_INCLUDE_DIR NAMES irrlicht.h + PATHS + /usr/local/include/irrlicht + /usr/include/irrlicht + ) + + FIND_LIBRARY(IRRLICHT_LIBRARY NAMES libIrrlicht.a Irrlicht + PATHS + /usr/local/lib + /usr/lib + ) +endif() + +MESSAGE(STATUS "IRRLICHT_SOURCE_DIR = ${IRRLICHT_SOURCE_DIR}") +MESSAGE(STATUS "IRRLICHT_INCLUDE_DIR = ${IRRLICHT_INCLUDE_DIR}") +MESSAGE(STATUS "IRRLICHT_LIBRARY = ${IRRLICHT_LIBRARY}") + +# On windows, find the dll for installation +if(WIN32) + if(MSVC) + FIND_FILE(IRRLICHT_DLL NAMES Irrlicht.dll + PATHS + "${IRRLICHT_SOURCE_DIR}/bin/Win32-VisualStudio" + DOC "Path of the Irrlicht dll (for installation)" + ) + else() + FIND_FILE(IRRLICHT_DLL NAMES Irrlicht.dll + PATHS + "${IRRLICHT_SOURCE_DIR}/bin/Win32-gcc" + DOC "Path of the Irrlicht dll (for installation)" + ) + endif() + MESSAGE(STATUS "IRRLICHT_DLL = ${IRRLICHT_DLL}") +endif(WIN32) + +# handle the QUIETLY and REQUIRED arguments and set IRRLICHT_FOUND to TRUE if +# all listed variables are TRUE +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(IRRLICHT DEFAULT_MSG IRRLICHT_LIBRARY IRRLICHT_INCLUDE_DIR) + +IF(IRRLICHT_FOUND) + SET(IRRLICHT_LIBRARIES ${IRRLICHT_LIBRARY}) +ELSE(IRRLICHT_FOUND) + SET(IRRLICHT_LIBRARIES) +ENDIF(IRRLICHT_FOUND) + +MARK_AS_ADVANCED(IRRLICHT_LIBRARY IRRLICHT_INCLUDE_DIR IRRLICHT_DLL) + diff --git a/cmake/Modules/FindJthread.cmake b/cmake/Modules/FindJthread.cmake new file mode 100644 index 0000000..302a3c2 --- /dev/null +++ b/cmake/Modules/FindJthread.cmake @@ -0,0 +1,18 @@ +# Look for jthread, use our own if not found + +FIND_PATH(JTHREAD_INCLUDE_DIR jthread.h) + +FIND_LIBRARY(JTHREAD_LIBRARY NAMES jthread) + +IF(JTHREAD_LIBRARY AND JTHREAD_INCLUDE_DIR) + SET( JTHREAD_FOUND TRUE ) +ENDIF(JTHREAD_LIBRARY AND JTHREAD_INCLUDE_DIR) + +IF(JTHREAD_FOUND) + MESSAGE(STATUS "Found system jthread header file in ${JTHREAD_INCLUDE_DIR}") + MESSAGE(STATUS "Found system jthread library ${JTHREAD_LIBRARY}") +ELSE(JTHREAD_FOUND) + SET(JTHREAD_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/jthread) + SET(JTHREAD_LIBRARY jthread) + MESSAGE(STATUS "Using project jthread library") +ENDIF(JTHREAD_FOUND) diff --git a/cmake/Modules/FindSqlite3.cmake b/cmake/Modules/FindSqlite3.cmake new file mode 100644 index 0000000..ecce6e3 --- /dev/null +++ b/cmake/Modules/FindSqlite3.cmake @@ -0,0 +1,18 @@ +# Look for sqlite3, use our own if not found + +FIND_PATH(SQLITE3_INCLUDE_DIR sqlite3.h) + +FIND_LIBRARY(SQLITE3_LIBRARY NAMES sqlite3) + +IF(SQLITE3_LIBRARY AND SQLITE3_INCLUDE_DIR) + SET( SQLITE3_FOUND TRUE ) +ENDIF(SQLITE3_LIBRARY AND SQLITE3_INCLUDE_DIR) + +IF(SQLITE3_FOUND) + MESSAGE(STATUS "Found system sqlite3 header file in ${SQLITE3_INCLUDE_DIR}") + MESSAGE(STATUS "Found system sqlite3 library ${SQLITE3_LIBRARY}") +ELSE(SQLITE3_FOUND) + SET(SQLITE3_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/sqlite) + SET(SQLITE3_LIBRARY sqlite3) + MESSAGE(STATUS "Using project sqlite3 library") +ENDIF(SQLITE3_FOUND) diff --git a/cmake/Modules/misc.cmake b/cmake/Modules/misc.cmake new file mode 100644 index 0000000..0bd2e3f --- /dev/null +++ b/cmake/Modules/misc.cmake @@ -0,0 +1,21 @@ +# +# Random macros +# + +# Not used ATM + +MACRO (GETDATETIME RESULT) + IF (WIN32) + EXECUTE_PROCESS(COMMAND "cmd" /C echo %date% %time% OUTPUT_VARIABLE ${RESULT}) + string(REGEX REPLACE "\n" "" ${RESULT} "${${RESULT}}") + ELSEIF(UNIX) + EXECUTE_PROCESS(COMMAND "date" "+%Y-%m-%d_%H:%M:%S" OUTPUT_VARIABLE ${RESULT}) + string(REGEX REPLACE "\n" "" ${RESULT} "${${RESULT}}") + ELSE (WIN32) + MESSAGE(SEND_ERROR "date not implemented") + SET(${RESULT} "Unknown") + ENDIF (WIN32) + + string(REGEX REPLACE " " "_" ${RESULT} "${${RESULT}}") +ENDMACRO (GETDATETIME) + diff --git a/data/apple.png b/data/apple.png new file mode 100644 index 0000000..9593f28 Binary files /dev/null and b/data/apple.png differ diff --git a/data/apple_iron.png b/data/apple_iron.png new file mode 100644 index 0000000..2dffdf0 Binary files /dev/null and b/data/apple_iron.png differ diff --git a/data/book.png b/data/book.png new file mode 100644 index 0000000..176fb6a Binary files /dev/null and b/data/book.png differ diff --git a/data/bookshelf.png b/data/bookshelf.png new file mode 100644 index 0000000..5ecc50f Binary files /dev/null and b/data/bookshelf.png differ diff --git a/data/brick.png b/data/brick.png new file mode 100644 index 0000000..32d77f3 Binary files /dev/null and b/data/brick.png differ diff --git a/data/cactus_side.png b/data/cactus_side.png new file mode 100644 index 0000000..fc479fd Binary files /dev/null and b/data/cactus_side.png differ diff --git a/data/cactus_top.png b/data/cactus_top.png new file mode 100644 index 0000000..f9e68df Binary files /dev/null and b/data/cactus_top.png differ diff --git a/data/chest_front.png b/data/chest_front.png new file mode 100644 index 0000000..c5628af Binary files /dev/null and b/data/chest_front.png differ diff --git a/data/chest_side.png b/data/chest_side.png new file mode 100644 index 0000000..916dd78 Binary files /dev/null and b/data/chest_side.png differ diff --git a/data/chest_top.png b/data/chest_top.png new file mode 100644 index 0000000..58c7967 Binary files /dev/null and b/data/chest_top.png differ diff --git a/data/clay.png b/data/clay.png new file mode 100644 index 0000000..3557429 Binary files /dev/null and b/data/clay.png differ diff --git a/data/clay_brick.png b/data/clay_brick.png new file mode 100644 index 0000000..e36648e Binary files /dev/null and b/data/clay_brick.png differ diff --git a/data/cloud.png b/data/cloud.png new file mode 100644 index 0000000..24091a3 Binary files /dev/null and b/data/cloud.png differ diff --git a/data/cobble.png b/data/cobble.png new file mode 100644 index 0000000..7d04474 Binary files /dev/null and b/data/cobble.png differ diff --git a/data/cooked_rat.png b/data/cooked_rat.png new file mode 100644 index 0000000..daad3be Binary files /dev/null and b/data/cooked_rat.png differ diff --git a/data/crack.png b/data/crack.png new file mode 100644 index 0000000..4997839 Binary files /dev/null and b/data/crack.png differ diff --git a/data/fence.png b/data/fence.png new file mode 100644 index 0000000..0b99f0e Binary files /dev/null and b/data/fence.png differ diff --git a/data/firefly.png b/data/firefly.png new file mode 100644 index 0000000..40df7fa Binary files /dev/null and b/data/firefly.png differ diff --git a/data/fontlucida.png b/data/fontlucida.png new file mode 100644 index 0000000..c63fa02 Binary files /dev/null and b/data/fontlucida.png differ diff --git a/data/furnace_front.png b/data/furnace_front.png new file mode 100644 index 0000000..1620a27 Binary files /dev/null and b/data/furnace_front.png differ diff --git a/data/furnace_side.png b/data/furnace_side.png new file mode 100644 index 0000000..63cb162 Binary files /dev/null and b/data/furnace_side.png differ diff --git a/data/glass.png b/data/glass.png new file mode 100644 index 0000000..8598ce6 Binary files /dev/null and b/data/glass.png differ diff --git a/data/grass.png b/data/grass.png new file mode 100644 index 0000000..3610bb2 Binary files /dev/null and b/data/grass.png differ diff --git a/data/grass_footsteps.png b/data/grass_footsteps.png new file mode 100644 index 0000000..57e063d Binary files /dev/null and b/data/grass_footsteps.png differ diff --git a/data/grass_side.png b/data/grass_side.png new file mode 100644 index 0000000..4f4f680 Binary files /dev/null and b/data/grass_side.png differ diff --git a/data/gravel.png b/data/gravel.png new file mode 100644 index 0000000..f08666a Binary files /dev/null and b/data/gravel.png differ diff --git a/data/heart.png b/data/heart.png new file mode 100644 index 0000000..6bc183e Binary files /dev/null and b/data/heart.png differ diff --git a/data/junglegrass.png b/data/junglegrass.png new file mode 100644 index 0000000..eea87c0 Binary files /dev/null and b/data/junglegrass.png differ diff --git a/data/jungletree.png b/data/jungletree.png new file mode 100644 index 0000000..ccd20ac Binary files /dev/null and b/data/jungletree.png differ diff --git a/data/jungletree_top.png b/data/jungletree_top.png new file mode 100644 index 0000000..2a9b513 Binary files /dev/null and b/data/jungletree_top.png differ diff --git a/data/ladder.png b/data/ladder.png new file mode 100644 index 0000000..1105635 Binary files /dev/null and b/data/ladder.png differ diff --git a/data/lava.png b/data/lava.png new file mode 100644 index 0000000..cb02ada Binary files /dev/null and b/data/lava.png differ diff --git a/data/leaves.png b/data/leaves.png new file mode 100644 index 0000000..7a25126 Binary files /dev/null and b/data/leaves.png differ diff --git a/data/lump_of_clay.png b/data/lump_of_clay.png new file mode 100644 index 0000000..be0bab9 Binary files /dev/null and b/data/lump_of_clay.png differ diff --git a/data/lump_of_coal.png b/data/lump_of_coal.png new file mode 100644 index 0000000..bad901e Binary files /dev/null and b/data/lump_of_coal.png differ diff --git a/data/lump_of_iron.png b/data/lump_of_iron.png new file mode 100644 index 0000000..edb9310 Binary files /dev/null and b/data/lump_of_iron.png differ diff --git a/data/menulogo.png b/data/menulogo.png new file mode 100644 index 0000000..76595c4 Binary files /dev/null and b/data/menulogo.png differ diff --git a/data/mese.png b/data/mese.png new file mode 100644 index 0000000..4c876cd Binary files /dev/null and b/data/mese.png differ diff --git a/data/mineral_coal.png b/data/mineral_coal.png new file mode 100644 index 0000000..3ff9692 Binary files /dev/null and b/data/mineral_coal.png differ diff --git a/data/mineral_iron.png b/data/mineral_iron.png new file mode 100644 index 0000000..51b15d9 Binary files /dev/null and b/data/mineral_iron.png differ diff --git a/data/mossycobble.png b/data/mossycobble.png new file mode 100644 index 0000000..fad1b33 Binary files /dev/null and b/data/mossycobble.png differ diff --git a/data/mud.png b/data/mud.png new file mode 100644 index 0000000..7cb9c89 Binary files /dev/null and b/data/mud.png differ diff --git a/data/nc_back.png b/data/nc_back.png new file mode 100644 index 0000000..f09f416 Binary files /dev/null and b/data/nc_back.png differ diff --git a/data/nc_front.png b/data/nc_front.png new file mode 100644 index 0000000..cad9eda Binary files /dev/null and b/data/nc_front.png differ diff --git a/data/nc_rb.png b/data/nc_rb.png new file mode 100644 index 0000000..7ebc993 Binary files /dev/null and b/data/nc_rb.png differ diff --git a/data/nc_side.png b/data/nc_side.png new file mode 100644 index 0000000..f954045 Binary files /dev/null and b/data/nc_side.png differ diff --git a/data/oerkki1.png b/data/oerkki1.png new file mode 100644 index 0000000..33cbac9 Binary files /dev/null and b/data/oerkki1.png differ diff --git a/data/oerkki1_damaged.png b/data/oerkki1_damaged.png new file mode 100644 index 0000000..9b77738 Binary files /dev/null and b/data/oerkki1_damaged.png differ diff --git a/data/paper.png b/data/paper.png new file mode 100644 index 0000000..ae5c06b Binary files /dev/null and b/data/paper.png differ diff --git a/data/papyrus.png b/data/papyrus.png new file mode 100644 index 0000000..bf0dec7 Binary files /dev/null and b/data/papyrus.png differ diff --git a/data/player.png b/data/player.png new file mode 100644 index 0000000..90adf97 Binary files /dev/null and b/data/player.png differ diff --git a/data/player_back.png b/data/player_back.png new file mode 100644 index 0000000..530aa75 Binary files /dev/null and b/data/player_back.png differ diff --git a/data/rail.png b/data/rail.png new file mode 100644 index 0000000..18176d9 Binary files /dev/null and b/data/rail.png differ diff --git a/data/rail_crossing.png b/data/rail_crossing.png new file mode 100644 index 0000000..9846405 Binary files /dev/null and b/data/rail_crossing.png differ diff --git a/data/rail_curved.png b/data/rail_curved.png new file mode 100644 index 0000000..62afa3d Binary files /dev/null and b/data/rail_curved.png differ diff --git a/data/rail_t_junction.png b/data/rail_t_junction.png new file mode 100644 index 0000000..9985f63 Binary files /dev/null and b/data/rail_t_junction.png differ diff --git a/data/rat.png b/data/rat.png new file mode 100644 index 0000000..d1a0e2a Binary files /dev/null and b/data/rat.png differ diff --git a/data/sand.png b/data/sand.png new file mode 100644 index 0000000..15101a7 Binary files /dev/null and b/data/sand.png differ diff --git a/data/sandstone.png b/data/sandstone.png new file mode 100644 index 0000000..c4759b4 Binary files /dev/null and b/data/sandstone.png differ diff --git a/data/scorched_stuff.png b/data/scorched_stuff.png new file mode 100644 index 0000000..9ced2fb Binary files /dev/null and b/data/scorched_stuff.png differ diff --git a/data/sign.png b/data/sign.png new file mode 100644 index 0000000..2e0b3cb Binary files /dev/null and b/data/sign.png differ diff --git a/data/sign_back.png b/data/sign_back.png new file mode 100644 index 0000000..779e4bc Binary files /dev/null and b/data/sign_back.png differ diff --git a/data/sign_wall.png b/data/sign_wall.png new file mode 100644 index 0000000..06eac1e Binary files /dev/null and b/data/sign_wall.png differ diff --git a/data/skybox1.png b/data/skybox1.png new file mode 100644 index 0000000..9801d5f Binary files /dev/null and b/data/skybox1.png differ diff --git a/data/skybox1_dawn.png b/data/skybox1_dawn.png new file mode 100644 index 0000000..9711c47 Binary files /dev/null and b/data/skybox1_dawn.png differ diff --git a/data/skybox1_night.png b/data/skybox1_night.png new file mode 100644 index 0000000..32e43a6 Binary files /dev/null and b/data/skybox1_night.png differ diff --git a/data/skybox2.png b/data/skybox2.png new file mode 100644 index 0000000..a8c94b4 Binary files /dev/null and b/data/skybox2.png differ diff --git a/data/skybox2_dawn.png b/data/skybox2_dawn.png new file mode 100644 index 0000000..a761dff Binary files /dev/null and b/data/skybox2_dawn.png differ diff --git a/data/skybox2_night.png b/data/skybox2_night.png new file mode 100644 index 0000000..beb07a9 Binary files /dev/null and b/data/skybox2_night.png differ diff --git a/data/skybox3.png b/data/skybox3.png new file mode 100644 index 0000000..2776ec7 Binary files /dev/null and b/data/skybox3.png differ diff --git a/data/skybox3_dawn.png b/data/skybox3_dawn.png new file mode 100644 index 0000000..22c8cbe Binary files /dev/null and b/data/skybox3_dawn.png differ diff --git a/data/skybox3_night.png b/data/skybox3_night.png new file mode 100644 index 0000000..bb50978 Binary files /dev/null and b/data/skybox3_night.png differ diff --git a/data/steel_block.png b/data/steel_block.png new file mode 100644 index 0000000..8e20200 Binary files /dev/null and b/data/steel_block.png differ diff --git a/data/steel_ingot.png b/data/steel_ingot.png new file mode 100644 index 0000000..f6c9414 Binary files /dev/null and b/data/steel_ingot.png differ diff --git a/data/stick.png b/data/stick.png new file mode 100644 index 0000000..2d31797 Binary files /dev/null and b/data/stick.png differ diff --git a/data/stone.png b/data/stone.png new file mode 100644 index 0000000..cad0dbe Binary files /dev/null and b/data/stone.png differ diff --git a/data/tool_mesepick.png b/data/tool_mesepick.png new file mode 100644 index 0000000..a1f3812 Binary files /dev/null and b/data/tool_mesepick.png differ diff --git a/data/tool_steelaxe.png b/data/tool_steelaxe.png new file mode 100644 index 0000000..390dbb0 Binary files /dev/null and b/data/tool_steelaxe.png differ diff --git a/data/tool_steelpick.png b/data/tool_steelpick.png new file mode 100644 index 0000000..7982daf Binary files /dev/null and b/data/tool_steelpick.png differ diff --git a/data/tool_steelshovel.png b/data/tool_steelshovel.png new file mode 100644 index 0000000..ed84138 Binary files /dev/null and b/data/tool_steelshovel.png differ diff --git a/data/tool_steelsword.png b/data/tool_steelsword.png new file mode 100644 index 0000000..a745812 Binary files /dev/null and b/data/tool_steelsword.png differ diff --git a/data/tool_stoneaxe.png b/data/tool_stoneaxe.png new file mode 100644 index 0000000..0c5414a Binary files /dev/null and b/data/tool_stoneaxe.png differ diff --git a/data/tool_stonepick.png b/data/tool_stonepick.png new file mode 100644 index 0000000..b34de6f Binary files /dev/null and b/data/tool_stonepick.png differ diff --git a/data/tool_stoneshovel.png b/data/tool_stoneshovel.png new file mode 100644 index 0000000..ba52431 Binary files /dev/null and b/data/tool_stoneshovel.png differ diff --git a/data/tool_stonesword.png b/data/tool_stonesword.png new file mode 100644 index 0000000..8f8191f Binary files /dev/null and b/data/tool_stonesword.png differ diff --git a/data/tool_woodaxe.png b/data/tool_woodaxe.png new file mode 100644 index 0000000..34f54ef Binary files /dev/null and b/data/tool_woodaxe.png differ diff --git a/data/tool_woodpick.png b/data/tool_woodpick.png new file mode 100644 index 0000000..ea728cc Binary files /dev/null and b/data/tool_woodpick.png differ diff --git a/data/tool_woodshovel.png b/data/tool_woodshovel.png new file mode 100644 index 0000000..649ab4c Binary files /dev/null and b/data/tool_woodshovel.png differ diff --git a/data/tool_woodsword.png b/data/tool_woodsword.png new file mode 100644 index 0000000..d6c6be3 Binary files /dev/null and b/data/tool_woodsword.png differ diff --git a/data/torch.png b/data/torch.png new file mode 100644 index 0000000..7a953c2 Binary files /dev/null and b/data/torch.png differ diff --git a/data/torch_on_ceiling.png b/data/torch_on_ceiling.png new file mode 100644 index 0000000..6965d38 Binary files /dev/null and b/data/torch_on_ceiling.png differ diff --git a/data/torch_on_floor.png b/data/torch_on_floor.png new file mode 100644 index 0000000..76d1dd5 Binary files /dev/null and b/data/torch_on_floor.png differ diff --git a/data/tree.png b/data/tree.png new file mode 100644 index 0000000..65abfc2 Binary files /dev/null and b/data/tree.png differ diff --git a/data/tree_top.png b/data/tree_top.png new file mode 100644 index 0000000..2cdd94f Binary files /dev/null and b/data/tree_top.png differ diff --git a/data/treeprop.png b/data/treeprop.png new file mode 100644 index 0000000..77ea4d6 Binary files /dev/null and b/data/treeprop.png differ diff --git a/data/unknown_block.png b/data/unknown_block.png new file mode 100644 index 0000000..a27cb8c Binary files /dev/null and b/data/unknown_block.png differ diff --git a/data/water.png b/data/water.png new file mode 100644 index 0000000..e5f8cdc Binary files /dev/null and b/data/water.png differ diff --git a/data/wood.png b/data/wood.png new file mode 100644 index 0000000..57c1d7c Binary files /dev/null and b/data/wood.png differ diff --git a/data/wool_black.png b/data/wool_black.png new file mode 100644 index 0000000..f22e3bb Binary files /dev/null and b/data/wool_black.png differ diff --git a/data/wool_blue.png b/data/wool_blue.png new file mode 100644 index 0000000..826d397 Binary files /dev/null and b/data/wool_blue.png differ diff --git a/data/wool_brown.png b/data/wool_brown.png new file mode 100644 index 0000000..0dcee4b Binary files /dev/null and b/data/wool_brown.png differ diff --git a/data/wool_cyan.png b/data/wool_cyan.png new file mode 100644 index 0000000..372ef45 Binary files /dev/null and b/data/wool_cyan.png differ diff --git a/data/wool_dark_grey.png b/data/wool_dark_grey.png new file mode 100644 index 0000000..c15bec4 Binary files /dev/null and b/data/wool_dark_grey.png differ diff --git a/data/wool_green.png b/data/wool_green.png new file mode 100644 index 0000000..a1a0c42 Binary files /dev/null and b/data/wool_green.png differ diff --git a/data/wool_grey.png b/data/wool_grey.png new file mode 100644 index 0000000..86e647c Binary files /dev/null and b/data/wool_grey.png differ diff --git a/data/wool_orange.png b/data/wool_orange.png new file mode 100644 index 0000000..2a76cf9 Binary files /dev/null and b/data/wool_orange.png differ diff --git a/data/wool_pink.png b/data/wool_pink.png new file mode 100644 index 0000000..6d59544 Binary files /dev/null and b/data/wool_pink.png differ diff --git a/data/wool_purple.png b/data/wool_purple.png new file mode 100644 index 0000000..c4da6ae Binary files /dev/null and b/data/wool_purple.png differ diff --git a/data/wool_red.png b/data/wool_red.png new file mode 100644 index 0000000..ab4dd64 Binary files /dev/null and b/data/wool_red.png differ diff --git a/data/wool_white.png b/data/wool_white.png new file mode 100644 index 0000000..6a9daef Binary files /dev/null and b/data/wool_white.png differ diff --git a/data/wool_yellow.png b/data/wool_yellow.png new file mode 100644 index 0000000..5c5d72f Binary files /dev/null and b/data/wool_yellow.png differ diff --git a/doc/README.txt b/doc/README.txt new file mode 100644 index 0000000..645e2a5 --- /dev/null +++ b/doc/README.txt @@ -0,0 +1,238 @@ +Minetest-c55 +--------------- +An InfiniMiner/Minecraft inspired game. +Copyright (c) 2010-2011 Perttu Ahola + +Further documentation: +---------------------- +- Website: http://celeron.55.lt/~celeron55/minetest/ +- Wiki: http://celeron.55.lt/~celeron55/minetest/wiki/ +- Forum: http://celeron.55.lt/~celeron55/minetest/forum/ + +This is a development version: +------------------------------ +- Don't expect it to work as well as a finished game will. +- Please report any bugs to me. That way I can fix them to the next release. + - debug.txt is useful when the game crashes. + +Controls: +--------- +- See the in-game pause menu +- Settable in the configuration file, see the section below. + +Map directory: +-------------- +- Map is stored in a directory, which can be removed to generate a new map. +- There is a command-line option for it: --map-dir +- For a RUN_IN_PLACE build, it is located in: + ../map +- Otherwise something like this: + Windows: C:\Documents and Settings\user\Application Data\minetest\map + Linux: ~/.minetest/map + OS X: ~/Library/Application Support/minetest/map + +Configuration file: +------------------- +- An optional configuration file can be used. See minetest.conf.example. +- Path to file can be passed as a parameter to the executable: + --config +- Defaults: + - If built with -DRUN_IN_PLACE=1: + ../minetest.conf + ../../minetest.conf + - Otherwise something like this: + Windows: C:\Documents and Settings\user\Application Data\minetest\minetest.conf + Linux: ~/.minetest/minetest.conf + OS X: ~/Library/Application Support/minetest.conf + +Command-line options: +--------------------- +- Use --help + +Compiling on GNU/Linux: +----------------------- + +Install dependencies. Here's an example for Debian/Ubuntu: +$ apt-get install build-essential libirrlicht-dev cmake libbz2-dev libpng12-dev libjpeg8-dev libxxf86vm-dev libgl1-mesa-dev + +Download source, extract (this is the URL to the latest of source repository, which might not work at all times): +$ wget https://bitbucket.org/celeron55/minetest/get/tip.tar.gz +$ tar xf tip.tar.gz +$ cd minetest + +Build a version that runs directly from the source directory: +$ cmake . -DRUN_IN_PLACE=1 +$ make -j2 + +Run it: +$ cd bin +$ ./minetest + +- Use cmake . -LH to see all CMake options and their current state +- If you want to install it system-wide (or are making a distribution package), you will want to use -DRUN_IN_PLACE=0 +- You can build a bare server or a bare client by specifying -DBUILD_CLIENT=0 or -DBUILD_SERVER=0 +- You can select between Release and Debug build by -DCMAKE_BUILD_TYPE= + - Note that the Debug build is considerably slower + +Compiling on Windows: +--------------------- + +- You need: + * CMake: + http://www.cmake.org/cmake/resources/software.html + * MinGW or Visual Studio + http://www.mingw.org/ + http://msdn.microsoft.com/en-us/vstudio/default + * Irrlicht SDK 1.7: + http://irrlicht.sourceforge.net/downloads.html + * Zlib headers (zlib125.zip) + http://www.winimage.com/zLibDll/index.html + * Zlib library (zlibwapi.lib and zlibwapi.dll from zlib125dll.zip): + http://www.winimage.com/zLibDll/index.html + * And, of course, Minetest-c55: + http://celeron.55.lt/~celeron55/minetest/download +- Steps: + - Select a directory called DIR hereafter in which you will operate. + - Make sure you have CMake and a compiler installed. + - Download all the other stuff to DIR and extract them into there. All those + packages contain a nice base directory in them, which should end up being + the direct subdirectories of DIR. + - You will end up with a directory structure like this (+=dir, -=file): + ----------------- + + DIR + - zlib-1.2.5.tar.gz + - zlib125dll.zip + - irrlicht-1.7.1.zip + - 110214175330.zip (or whatever, this is the minetest source) + + zlib-1.2.5 + - zlib.h + + win32 + ... + + zlib125dll + - readme.txt + + dll32 + ... + + irrlicht-1.7.1 + + lib + + include + ... + + minetest + + src + + doc + - CMakeLists.txt + ... + ----------------- + - Start up the CMake GUI + - Select "Browse Source..." and select DIR/minetest + - Now, if using MSVC: + - Select "Browse Build..." and select DIR/minetest-build + - Else if using MinGW: + - Select "Browse Build..." and select DIR/minetest + - Select "Configure" + - Select your compiler + - It will warn about missing stuff, ignore that at this point. (later don't) + - Make sure the configuration is as follows + (note that the versions may differ for you): + ----------------- + BUILD_CLIENT [X] + BUILD_SERVER [ ] + CMAKE_BUILD_TYPE Release + CMAKE_INSTALL_PREFIX DIR/minetest-install + IRRLICHT_SOURCE_DIR DIR/irrlicht-1.7.1 + RUN_IN_PLACE [X] + WARN_ALL [ ] + ZLIB_DLL DIR/zlib125dll/dll32/zlibwapi.dll + ZLIB_INCLUDE_DIR DIR/zlib-1.2.5 + ZLIB_LIBRARIES DIR/zlib125dll/dll32/zlibwapi.lib + ----------------- + - Hit "Configure" + - Hit "Generate" + If using MSVC: + - Open the generated minetest.sln + - The project defaults to the "Debug" configuration. Make very sure to + select "Release", unless you want to debug some stuff (it's slower) + - Build the ALL_BUILD project + - Build the INSTALL project + - You should now have a working game with the executable in + DIR/minetest-install/bin/minetest.exe + - Additionally you may create a zip package by building the PACKAGE + project. + If using MinGW: + - Using the command line, browse to the build directory and run 'make' + (or mingw32-make or whatever it happens to be) + - You should now have a working game with the executable in + DIR/minetest/bin/minetest.exe + +License of Minetest-c55 +----------------------- + +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Irrlicht +--------------- + +This program uses the Irrlicht Engine. http://irrlicht.sourceforge.net/ + + The Irrlicht Engine License + +Copyright © 2002-2005 Nikolaus Gebhardt + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute +it freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + 3. This notice may not be removed or altered from any source + distribution. + + +JThread +--------------- + +This program uses the JThread library. License for JThread follows: + +Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + + diff --git a/doc/changelog.txt b/doc/changelog.txt new file mode 100644 index 0000000..745b6a9 --- /dev/null +++ b/doc/changelog.txt @@ -0,0 +1,121 @@ +Minetest-c55 changelog +---------------------- +This should contain all the major changes. +For minor stuff, refer to the commit log of the repository. + +0.2.20110922_2: +- Move PLATFORM_LIBS around to make sqlite3 link with libdl on some distros +- sectors2sqlite.py and minetestmapper.py fixes + +0.2.20110922_1: +- Make client report a newer version number to the server than 2011-07-31 does and make server disallow old clients + +0.2.20110922: +- Map is saved in an SQLite database file (by Queatz) +- Ladders (MarkTraceur) +- Lava +- Apple trees (sfan5) +- Slightly better looking inventory with transparency +- /me chat command (Oblomov) +- Using chosen map seed possible through fixed_map_seed configuration option (kahrl) +- Fix the long-existed PeerNotFound loop bug +- Some translations and localization-related fixes +- Lots of small fixes + +2011-07-31_3: +- Fixes a bug that made the server to deny non-empty passwords from players connecting the first time + +2011-07-31_2: +- Fixes a bug that caused the server to always read an empty password from the client when a client connected. + +2011-07-31: +- A number of small fixes, build system stuff and such (refer to version control log) +- Map generator no longer crashes at generation limit +- Fixed mapgen producing lots of cut-down trees +- Some minor tweaks in map generator (some contributed) +- Volumetric clouds (contributed) +- Icon added (graphic contributed) +- Key configuration menu (contributed) +- Decorative blocks and items: bookshelf, sandstone, cactus, clay, brick, papyrus, rail, paper, book (contributed) +- Jungles! +- Hotbar is a bit smaller +- Health is now enabled by default; You can now eat cooked rats to heal yourself. +- Finally added sword textures, altough sword is still of no use +- Creative mode now preserves normal mode inventory + +2011-07-04: +- Many small fixes +- Code reorganizing to aid further development +- Renewed map generator + +2011-06-02: +- Password crash on windows fixed +- Optimized server CPU usage a lot +- Furnaces now work also while players are not near to them + +2011-05-29: +- Optimized smooth lighting +- A number of small fixes +- Added clouds and simple skyboxes +- The glass block added +- Added key configuration to config file +- Player privileges on server +- Slightly updated map format +- Player passwords +- All textures first searched from texture_path +- Map directory ("map") has been renamed to "world" (just rename it to load an old world) +- Mouse inversion (invert_mouse) +- Grass doesn't grow immediately anymore +- Fence added + +2011-04-24: +- Smooth lighting with simple ambient occlusion +- Updated main menu + +2011-04-23_0_test: +- Small bug fixes +- Item drop multiplication fixed +- HP added +- Added A simple monster which spawns to dark places at map generation time +- Some code refactoring and cleaning (possibly new bugs) + +2011-04-11: +- Fixed crafting a bit + +2011-04-10_0: +- Asynchronous map generation +- New object system + +2011-04-06: +- Mesh update of node addition/removal is now done asynchronously on client, removing frametime spike +- Node addition/removal is sent directly only to clients that are closer than 100 nodes to the modification. For the others, the modified blocks are set unsent. (and are re-sent when applicable) + +2011-04-05: +- Made furnace usable +- Added cobblestone +- Added wood, stone and steel tools: pickaxes, shovels and axes +- Incremented to version 0.0.2 + +2011-04-04: +- Cleaned client to be completely synchronous, except for the mesh calculation, which is now done with queues in a separate thread. +- Added node metadata support +- Added chests + +2011-02-17: +- Added better handling of textures. Now many file extensions are searched. Also too large textures are not put on the texture atlas, and the construction of the texture atlas is stopped when it is full. + +2011-02-16: +- Better handling of Ctrl-C on POSIX systems + +2011-02-15: +- Fixed a problem of not saving and loading the "lighting expired" value of MapBlocks properly. This caused high server CPU usage. +- Ctrl-C handling on POSIX systems +- Added simple command support to server +- Added settings enable_texture_atlas and texture_path + +2011-02-14: +- Created changelog.txt +- Added sneaking/crouching +- Modified the looks of the hotbar and cleaned code +- Added code to allow generating 3D cube images for inventory + diff --git a/doc/gpl-2.0.txt b/doc/gpl-2.0.txt new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/doc/gpl-2.0.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/doc/mapformat.txt b/doc/mapformat.txt new file mode 100644 index 0000000..a024180 --- /dev/null +++ b/doc/mapformat.txt @@ -0,0 +1,89 @@ +I'll try to quickly document the newest block format in here (might contain +errors). Refer to the mapgen or minetestmapper script for the directory +structure and file naming. There are two sector namings possible, +sector/XXXXZZZZ and sector/XXX/ZZZ. + +There also exists files map_meta.txt and chunk_meta, that are used by the +generator. If they are not found or invalid, the generator will currently +behave quite strangely. + +The MapBlock file format (sectors2/XXX/ZZZ/YYYY): +------------------------------------------------- + +NOTE: Byte order is MSB first. + +u8 version +- map format version number, this one is version 17 + +u8 flags +- Flag bitmasks: + - 0x01: is_underground: Should be set to 0 if there will be no light + obstructions above the block. If/when sunlight of a block is updated and + there is no block above it, this value is checked for determining whether + sunlight comes from the top. + - 0x02: day_night_differs: Whether the lighting of the block is different on + day and night. Only blocks that have this bit set are updated when day + transforms to night. + - 0x04: lighting_expired: If true, lighting is invalid and should be updated. + If you can't calculate lighting in your generator properly, you could try + setting this 1 to everything and setting the uppermost block in every + sector as is_underground=0. I am quite sure it doesn't work properly, + though. + +zlib-compressed map data: +- content: + u8[4096]: content types + u8[4096]: param1 values + u8[4096]: param2 values + +zlib-compressed node metadata +- content: + u16 version (=1) + u16 count of metadata + foreach count: + u16 position (= p.Z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + p.Y*MAP_BLOCKSIZE + p.X) + u16 type_id + u16 content_size + u8[content_size] misc. stuff contained in the metadata + +u16 mapblockobject_count +- always write as 0. +- if read != 0, just fail. + +foreach mapblockobject_count: + - deprecated, should not be used. Length of this data can only be known by + properly parsing it. Just hope not to run into any of this. + +u8 static object version: +- currently 0 + +u16 static_object_count + +foreach static_object_count: + u8 type (object type-id) + s32 pos_x * 1000 + s32 pos_y * 1000 + s32 pos_z * 1000 + u16 data_size + u8[data_size] data + +u32 timestamp +- Timestamp when last saved, as seconds from starting the game. +- 0xffffffff = invalid/unknown timestamp, nothing will be done with the time + difference when loaded (recommended) + +Node metadata format: +--------------------- + +Sign metadata: + u16 string_len + u8[string_len] string + +Furnace metadata: + TBD + +Chest metadata: + TBD + +// END + diff --git a/doc/protocol.txt b/doc/protocol.txt new file mode 100644 index 0000000..82dca59 --- /dev/null +++ b/doc/protocol.txt @@ -0,0 +1,72 @@ +Minetest-c55 protocol (incomplete, early draft): +Updated 2011-06-18 + +A custom protocol over UDP. +Integers are big endian. +Refer to connection.{h,cpp} for further reference. + +Initialization: +- A dummy reliable packet with peer_id=PEER_ID_INEXISTENT=0 is sent to the server: + - Actually this can be sent without the reliable packet header, too, i guess, + but the sequence number in the header allows the sender to re-send the + packet without accidentally getting a double initialization. + - Packet content: + # Basic header + u32 protocol_id = PROTOCOL_ID = 0x4f457403 + u16 sender_peer_id = PEER_ID_INEXISTENT = 0 + u8 channel = 0 + # Reliable packet header + u8 type = TYPE_RELIABLE = 3 + u16 seqnum = SEQNUM_INITIAL = 65500 + # Original packet header + u8 type = TYPE_ORIGINAL = 1 + # And no actual payload. +- Server responds with something like this: + - Packet content: + # Basic header + u32 protocol_id = PROTOCOL_ID = 0x4f457403 + u16 sender_peer_id = PEER_ID_INEXISTENT = 0 + u8 channel = 0 + # Reliable packet header + u8 type = TYPE_RELIABLE = 3 + u16 seqnum = SEQNUM_INITIAL = 65500 + # Control packet header + u8 type = TYPE_CONTROL = 0 + u8 controltype = CONTROLTYPE_SET_PEER_ID = 1 + u16 peer_id_new = assigned peer id to client (other than 0 or 1) +- Then the connection can be disconnected by sending: + - Packet content: + # Basic header + u32 protocol_id = PROTOCOL_ID = 0x4f457403 + u16 sender_peer_id = whatever was gotten in CONTROLTYPE_SET_PEER_ID + u8 channel = 0 + # Control packet header + u8 type = TYPE_CONTROL = 0 + u8 controltype = CONTROLTYPE_DISCO = 3 + +- Here's a quick untested connect-disconnect done in PHP: +# host: ip of server (use gethostbyname(hostname) to get from a dns name) +# port: port of server +function check_if_minetestserver_up($host, $port) +{ + $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); + $timeout = array("sec" => 1, "usec" => 0); + socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout); + $buf = "\x4f\x45\x74\x03\x00\x00\x00\x03\xff\xdc\x01"; + socket_sendto($socket, $buf, strlen($buf), 0, $host, $port); + $buf = socket_read($socket, 1000); + if($buf != "") + { + # We got a reply! read the peer id from it. + $peer_id = substr($buf, 9, 2); + + # Disconnect + $buf = "\x4f\x45\x74\x03".$peer_id."\x00\x00\x03"; + socket_sendto($socket, $buf, strlen($buf), 0, $host, $port); + socket_close($socket); + + return true; + } + return false; +} + diff --git a/locale/da/LC_MESSAGES/minetest.mo b/locale/da/LC_MESSAGES/minetest.mo new file mode 100644 index 0000000..fe4e3dd Binary files /dev/null and b/locale/da/LC_MESSAGES/minetest.mo differ diff --git a/locale/de/LC_MESSAGES/minetest.mo b/locale/de/LC_MESSAGES/minetest.mo new file mode 100644 index 0000000..192a78a Binary files /dev/null and b/locale/de/LC_MESSAGES/minetest.mo differ diff --git a/locale/fr/LC_MESSAGES/minetest.mo b/locale/fr/LC_MESSAGES/minetest.mo new file mode 100644 index 0000000..213d630 Binary files /dev/null and b/locale/fr/LC_MESSAGES/minetest.mo differ diff --git a/locale/it/LC_MESSAGES/minetest.mo b/locale/it/LC_MESSAGES/minetest.mo new file mode 100644 index 0000000..3be4f30 Binary files /dev/null and b/locale/it/LC_MESSAGES/minetest.mo differ diff --git a/minetest-icon-24x24.png b/minetest-icon-24x24.png new file mode 100644 index 0000000..4d587c4 Binary files /dev/null and b/minetest-icon-24x24.png differ diff --git a/minetest-icon.ico b/minetest-icon.ico new file mode 100644 index 0000000..82af67b Binary files /dev/null and b/minetest-icon.ico differ diff --git a/minetest-icon.svg b/minetest-icon.svg new file mode 100644 index 0000000..46c9ac7 --- /dev/null +++ b/minetest-icon.svg @@ -0,0 +1,183 @@ + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/minetest.conf.example b/minetest.conf.example new file mode 100644 index 0000000..c47ac77 --- /dev/null +++ b/minetest.conf.example @@ -0,0 +1,143 @@ +# This file is read by default from: +# ../minetest.conf +# ../../minetest.conf +# Any other path can be chosen by passing the path as a parameter +# to the program, eg. "minetest.exe --config ../minetest.conf.example" +# +# By default, all the settings are commented and not functional. +# Uncomment settings by removing the preceding #. +# +# Further documentation: +# http://celeron.55.lt/~celeron55/minetest/wiki/doku.php +# +# NOTE: This file might not be up-to-date, refer to the +# defaultsettings.cpp file for an up-to-date list: +# https://bitbucket.org/celeron55/minetest/src/tip/src/defaultsettings.cpp +# +# A vim command to convert most of defaultsettings.cpp to conf file format: +# :'<,'>s/\tg_settings\.setDefault("\([^"]*\)", "\([^"]*\)");.*/#\1 = \2/g + +# +# Client and server +# + +# Network port (UDP) +#port = +# Name of player; on a server this is the main admin +#name = + +# +# Client stuff +# + +# Key mappings +# See http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3 +#keymap_forward = KEY_KEY_W +#keymap_backward = KEY_KEY_S +#keymap_left = KEY_KEY_A +#keymap_right = KEY_KEY_D +#keymap_jump = KEY_SPACE +#keymap_sneak = KEY_LSHIFT +#keymap_inventory = KEY_KEY_I +#keymap_chat = KEY_KEY_T +#keymap_rangeselect = KEY_KEY_R +#keymap_freemove = KEY_KEY_K +#keymap_fastmove = KEY_KEY_J +#keymap_frametime_graph = KEY_F1 +#keymap_screenshot = KEY_F12 +# Some (temporary) keys for debugging +#keymap_special1 = KEY_KEY_E +#keymap_print_debug_stacks = KEY_KEY_P + +# The desired FPS +#wanted_fps = 30 +# If FPS would go higher than this, limit it by sleeping +# (to not waste CPU power for no benefit) +#fps_max = 60 +# The allowed adjustment range for the automatic rendering range adjustment +#viewing_range_nodes_max = 300 +#viewing_range_nodes_min = 25 +# Initial window size +screenW# = 800 +screenH# = 600 +# Address to connect to (#blank = start local server) +#address = +# Enable random user input, for testing +#random_input = false +# Timeout for client to remove unused map data from memory +#client_unload_unused_data_timeout = 600 +# Whether to fog out the end of the visible area +#enable_fog = true +# Enable a bit lower water surface; disable for speed (not quite optimized) +#new_style_water = false +# Enable nice leaves; disable for speed +#new_style_leaves = true +# Enable smooth lighting with simple ambient occlusion; +# disable for speed or for different looks. +#smooth_lighting = true +# Whether to draw a frametime graph (for debugging frametime) +#frametime_graph = false +# Enable combining mainly used textures to a bigger one for improved speed +# disable if it causes graphics glitches. +#enable_texture_atlas = true +# Path to texture directory. All textures are first searched from here. +#texture_path = +# Video back-end. +# Possible values: null, software, burningsvideo, direct3d8, direct3d9, opengl +#video_driver = opengl +# Unobstructed movement without physics, downwards key is keymap_special1 +#free_move = false +# Continuous forward movement (for testing) +#continuous_forward = false +# Fast movement (keymap_special1) +#fast_move = false +# Invert mouse +#invert_mouse = false +# FarMesh thingy +#enable_farmesh = false +#farmesh_trees = true +#farmesh_distance = 40 +# Enable/disable clouds +#enable_clouds = true +# Don't draw stone (for testing) +#invisible_stone = false +# Path for screenshots +#screenshot_path = . + +# +# Server stuff +# + +# Map directory (everything in the world is stored here) +#map-#dir = /custom/map +# Message of the Day +#motd = Welcome to this awesome Minetest server! +# Set to true to enable creative mode (unlimited inventory) +#creative_mode = false +#enable_damage = false +# Gives some stuff to players at the beginning +#give_initial_stuff = false +#default_password = +# Available privileges: build, teleport, settime, privs, shout +#default_privs = build, shout + +# Set to true to enable experimental features or stuff that is tested +# (varies from version to version, usually not useful at all) +#enable_experimental = false +# Profiler data print interval. #0 = disable. +#profiler_print_interval = 0 +#enable_mapgen_debug_info = false +# Player and object positions are sent at intervals specified by this +#objectdata_interval = 0.2 +#active_object_range = 2 +#max_simultaneous_block_sends_per_client = 2 +#max_simultaneous_block_sends_server_total = 8 +#max_block_send_distance = 8 +#max_block_generate_distance = 8 +#time_send_interval = 20 +# Length of day/night cycle. 72=20min, 360=4min, 1=24hour +#time_speed = 72 +#server_unload_unused_data_timeout = 60 +#server_map_save_interval = 60 +#full_block_send_enable_min_time_from_building = 2.0 + diff --git a/misc/map.cpp b/misc/map.cpp new file mode 100644 index 0000000..78a849f --- /dev/null +++ b/misc/map.cpp @@ -0,0 +1,6393 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "map.h" +#include "main.h" +#include "jmutexautolock.h" +#include "client.h" +#include "filesys.h" +#include "utility.h" +#include "voxel.h" +#include "porting.h" +#include "mineral.h" +#include "noise.h" +#include "serverobject.h" + +/* + Map +*/ + +Map::Map(std::ostream &dout): + m_dout(dout), + m_sector_cache(NULL) +{ + /*m_sector_mutex.Init(); + assert(m_sector_mutex.IsInitialized());*/ +} + +Map::~Map() +{ + /* + Free all MapSectors + */ + core::map::Iterator i = m_sectors.getIterator(); + for(; i.atEnd() == false; i++) + { + MapSector *sector = i.getNode()->getValue(); + delete sector; + } +} + +void Map::addEventReceiver(MapEventReceiver *event_receiver) +{ + m_event_receivers.insert(event_receiver, false); +} + +void Map::removeEventReceiver(MapEventReceiver *event_receiver) +{ + if(m_event_receivers.find(event_receiver) == NULL) + return; + m_event_receivers.remove(event_receiver); +} + +void Map::dispatchEvent(MapEditEvent *event) +{ + for(core::map::Iterator + i = m_event_receivers.getIterator(); + i.atEnd()==false; i++) + { + MapEventReceiver* event_receiver = i.getNode()->getKey(); + event_receiver->onMapEditEvent(event); + } +} + +MapSector * Map::getSectorNoGenerateNoExNoLock(v2s16 p) +{ + if(m_sector_cache != NULL && p == m_sector_cache_p){ + MapSector * sector = m_sector_cache; + // Reset inactivity timer + sector->usage_timer = 0.0; + return sector; + } + + core::map::Node *n = m_sectors.find(p); + + if(n == NULL) + return NULL; + + MapSector *sector = n->getValue(); + + // Cache the last result + m_sector_cache_p = p; + m_sector_cache = sector; + + // Reset inactivity timer + sector->usage_timer = 0.0; + return sector; +} + +MapSector * Map::getSectorNoGenerateNoEx(v2s16 p) +{ + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + + return getSectorNoGenerateNoExNoLock(p); +} + +MapSector * Map::getSectorNoGenerate(v2s16 p) +{ + MapSector *sector = getSectorNoGenerateNoEx(p); + if(sector == NULL) + throw InvalidPositionException(); + + return sector; +} + +MapBlock * Map::getBlockNoCreate(v3s16 p3d) +{ + v2s16 p2d(p3d.X, p3d.Z); + MapSector * sector = getSectorNoGenerate(p2d); + + MapBlock *block = sector->getBlockNoCreate(p3d.Y); + + return block; +} + +MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d) +{ + try + { + v2s16 p2d(p3d.X, p3d.Z); + MapSector * sector = getSectorNoGenerate(p2d); + MapBlock *block = sector->getBlockNoCreate(p3d.Y); + return block; + } + catch(InvalidPositionException &e) + { + return NULL; + } +} + +/*MapBlock * Map::getBlockCreate(v3s16 p3d) +{ + v2s16 p2d(p3d.X, p3d.Z); + MapSector * sector = getSectorCreate(p2d); + assert(sector); + MapBlock *block = sector->getBlockNoCreate(p3d.Y); + if(block) + return block; + block = sector->createBlankBlock(p3d.Y); + return block; +}*/ + +bool Map::isNodeUnderground(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + try{ + MapBlock * block = getBlockNoCreate(blockpos); + return block->getIsUnderground(); + } + catch(InvalidPositionException &e) + { + return false; + } +} + +/* + Goes recursively through the neighbours of the node. + + Alters only transparent nodes. + + If the lighting of the neighbour is lower than the lighting of + the node was (before changing it to 0 at the step before), the + lighting of the neighbour is set to 0 and then the same stuff + repeats for the neighbour. + + The ending nodes of the routine are stored in light_sources. + This is useful when a light is removed. In such case, this + routine can be called for the light node and then again for + light_sources to re-light the area without the removed light. + + values of from_nodes are lighting values. +*/ +void Map::unspreadLight(enum LightBank bank, + core::map & from_nodes, + core::map & light_sources, + core::map & modified_blocks) +{ + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + if(from_nodes.size() == 0) + return; + + u32 blockchangecount = 0; + + core::map unlighted_nodes; + core::map::Iterator j; + j = from_nodes.getIterator(); + + /* + Initialize block cache + */ + v3s16 blockpos_last; + MapBlock *block = NULL; + // Cache this a bit, too + bool block_checked_in_modified = false; + + for(; j.atEnd() == false; j++) + { + v3s16 pos = j.getNode()->getKey(); + v3s16 blockpos = getNodeBlockPos(pos); + + // Only fetch a new block if the block position has changed + try{ + if(block == NULL || blockpos != blockpos_last){ + block = getBlockNoCreate(blockpos); + blockpos_last = blockpos; + + block_checked_in_modified = false; + blockchangecount++; + } + } + catch(InvalidPositionException &e) + { + continue; + } + + if(block->isDummy()) + continue; + + // Calculate relative position in block + v3s16 relpos = pos - blockpos_last * MAP_BLOCKSIZE; + + // Get node straight from the block + MapNode n = block->getNode(relpos); + + u8 oldlight = j.getNode()->getValue(); + + // Loop through 6 neighbors + for(u16 i=0; i<6; i++) + { + // Get the position of the neighbor node + v3s16 n2pos = pos + dirs[i]; + + // Get the block where the node is located + v3s16 blockpos = getNodeBlockPos(n2pos); + + try + { + // Only fetch a new block if the block position has changed + try{ + if(block == NULL || blockpos != blockpos_last){ + block = getBlockNoCreate(blockpos); + blockpos_last = blockpos; + + block_checked_in_modified = false; + blockchangecount++; + } + } + catch(InvalidPositionException &e) + { + continue; + } + + // Calculate relative position in block + v3s16 relpos = n2pos - blockpos * MAP_BLOCKSIZE; + // Get node straight from the block + MapNode n2 = block->getNode(relpos); + + bool changed = false; + + //TODO: Optimize output by optimizing light_sources? + + /* + If the neighbor is dimmer than what was specified + as oldlight (the light of the previous node) + */ + if(n2.getLight(bank) < oldlight) + { + /* + And the neighbor is transparent and it has some light + */ + if(n2.light_propagates() && n2.getLight(bank) != 0) + { + /* + Set light to 0 and add to queue + */ + + u8 current_light = n2.getLight(bank); + n2.setLight(bank, 0); + block->setNode(relpos, n2); + + unlighted_nodes.insert(n2pos, current_light); + changed = true; + + /* + Remove from light_sources if it is there + NOTE: This doesn't happen nearly at all + */ + /*if(light_sources.find(n2pos)) + { + std::cout<<"Removed from light_sources"< 0) + unspreadLight(bank, unlighted_nodes, light_sources, modified_blocks); +} + +/* + A single-node wrapper of the above +*/ +void Map::unLightNeighbors(enum LightBank bank, + v3s16 pos, u8 lightwas, + core::map & light_sources, + core::map & modified_blocks) +{ + core::map from_nodes; + from_nodes.insert(pos, lightwas); + + unspreadLight(bank, from_nodes, light_sources, modified_blocks); +} + +/* + Lights neighbors of from_nodes, collects all them and then + goes on recursively. +*/ +void Map::spreadLight(enum LightBank bank, + core::map & from_nodes, + core::map & modified_blocks) +{ + const v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + if(from_nodes.size() == 0) + return; + + u32 blockchangecount = 0; + + core::map lighted_nodes; + core::map::Iterator j; + j = from_nodes.getIterator(); + + /* + Initialize block cache + */ + v3s16 blockpos_last; + MapBlock *block = NULL; + // Cache this a bit, too + bool block_checked_in_modified = false; + + for(; j.atEnd() == false; j++) + //for(; j != from_nodes.end(); j++) + { + v3s16 pos = j.getNode()->getKey(); + //v3s16 pos = *j; + //dstream<<"pos=("<isDummy()) + continue; + + // Calculate relative position in block + v3s16 relpos = pos - blockpos_last * MAP_BLOCKSIZE; + + // Get node straight from the block + MapNode n = block->getNode(relpos); + + u8 oldlight = n.getLight(bank); + u8 newlight = diminish_light(oldlight); + + // Loop through 6 neighbors + for(u16 i=0; i<6; i++){ + // Get the position of the neighbor node + v3s16 n2pos = pos + dirs[i]; + + // Get the block where the node is located + v3s16 blockpos = getNodeBlockPos(n2pos); + + try + { + // Only fetch a new block if the block position has changed + try{ + if(block == NULL || blockpos != blockpos_last){ + block = getBlockNoCreate(blockpos); + blockpos_last = blockpos; + + block_checked_in_modified = false; + blockchangecount++; + } + } + catch(InvalidPositionException &e) + { + continue; + } + + // Calculate relative position in block + v3s16 relpos = n2pos - blockpos * MAP_BLOCKSIZE; + // Get node straight from the block + MapNode n2 = block->getNode(relpos); + + bool changed = false; + /* + If the neighbor is brighter than the current node, + add to list (it will light up this node on its turn) + */ + if(n2.getLight(bank) > undiminish_light(oldlight)) + { + lighted_nodes.insert(n2pos, true); + //lighted_nodes.push_back(n2pos); + changed = true; + } + /* + If the neighbor is dimmer than how much light this node + would spread on it, add to list + */ + if(n2.getLight(bank) < newlight) + { + if(n2.light_propagates()) + { + n2.setLight(bank, newlight); + block->setNode(relpos, n2); + lighted_nodes.insert(n2pos, true); + //lighted_nodes.push_back(n2pos); + changed = true; + } + } + + // Add to modified_blocks + if(changed == true && block_checked_in_modified == false) + { + // If the block is not found in modified_blocks, add. + if(modified_blocks.find(blockpos) == NULL) + { + modified_blocks.insert(blockpos, block); + } + block_checked_in_modified = true; + } + } + catch(InvalidPositionException &e) + { + continue; + } + } + } + + /*dstream<<"spreadLight(): Changed block " + < 0) + spreadLight(bank, lighted_nodes, modified_blocks); +} + +/* + A single-node source variation of the above. +*/ +void Map::lightNeighbors(enum LightBank bank, + v3s16 pos, + core::map & modified_blocks) +{ + core::map from_nodes; + from_nodes.insert(pos, true); + spreadLight(bank, from_nodes, modified_blocks); +} + +v3s16 Map::getBrightestNeighbour(enum LightBank bank, v3s16 p) +{ + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + u8 brightest_light = 0; + v3s16 brightest_pos(0,0,0); + bool found_something = false; + + // Loop through 6 neighbors + for(u16 i=0; i<6; i++){ + // Get the position of the neighbor node + v3s16 n2pos = p + dirs[i]; + MapNode n2; + try{ + n2 = getNode(n2pos); + } + catch(InvalidPositionException &e) + { + continue; + } + if(n2.getLight(bank) > brightest_light || found_something == false){ + brightest_light = n2.getLight(bank); + brightest_pos = n2pos; + found_something = true; + } + } + + if(found_something == false) + throw InvalidPositionException(); + + return brightest_pos; +} + +/* + Propagates sunlight down from a node. + Starting point gets sunlight. + + Returns the lowest y value of where the sunlight went. + + Mud is turned into grass in where the sunlight stops. +*/ +s16 Map::propagateSunlight(v3s16 start, + core::map & modified_blocks) +{ + s16 y = start.Y; + for(; ; y--) + { + v3s16 pos(start.X, y, start.Z); + + v3s16 blockpos = getNodeBlockPos(pos); + MapBlock *block; + try{ + block = getBlockNoCreate(blockpos); + } + catch(InvalidPositionException &e) + { + break; + } + + v3s16 relpos = pos - blockpos*MAP_BLOCKSIZE; + MapNode n = block->getNode(relpos); + + if(n.sunlight_propagates()) + { + n.setLight(LIGHTBANK_DAY, LIGHT_SUN); + block->setNode(relpos, n); + + modified_blocks.insert(blockpos, block); + } + else + { + // Turn mud into grass + if(n.d == CONTENT_MUD) + { + n.d = CONTENT_GRASS; + block->setNode(relpos, n); + modified_blocks.insert(blockpos, block); + } + + // Sunlight goes no further + break; + } + } + return y + 1; +} + +void Map::updateLighting(enum LightBank bank, + core::map & a_blocks, + core::map & modified_blocks) +{ + /*m_dout< blocks_to_update; + + core::map light_sources; + + core::map unlight_from; + + core::map::Iterator i; + i = a_blocks.getIterator(); + for(; i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + + for(;;) + { + // Don't bother with dummy blocks. + if(block->isDummy()) + break; + + v3s16 pos = block->getPos(); + modified_blocks.insert(pos, block); + + blocks_to_update.insert(pos, block); + + /* + Clear all light from block + */ + for(s16 z=0; zgetNode(v3s16(x,y,z)); + u8 oldlight = n.getLight(bank); + n.setLight(bank, 0); + block->setNode(v3s16(x,y,z), n); + + // Collect borders for unlighting + if(x==0 || x == MAP_BLOCKSIZE-1 + || y==0 || y == MAP_BLOCKSIZE-1 + || z==0 || z == MAP_BLOCKSIZE-1) + { + v3s16 p_map = p + v3s16( + MAP_BLOCKSIZE*pos.X, + MAP_BLOCKSIZE*pos.Y, + MAP_BLOCKSIZE*pos.Z); + unlight_from.insert(p_map, oldlight); + } + } + catch(InvalidPositionException &e) + { + /* + This would happen when dealing with a + dummy block. + */ + //assert(0); + dstream<<"updateLighting(): InvalidPositionException" + <propagateSunlight(light_sources); + + // If bottom is valid, we're done. + if(bottom_valid) + break; + } + else if(bank == LIGHTBANK_NIGHT) + { + // For night lighting, sunlight is not propagated + break; + } + else + { + // Invalid lighting bank + assert(0); + } + + /*dstream<<"Bottom for sunlight-propagated block (" + <::Iterator i; + i = blocks_to_update.getIterator(); + for(; i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + v3s16 p = block->getPos(); + + // Add all surrounding blocks + vmanip.initialEmerge(p - v3s16(1,1,1), p + v3s16(1,1,1)); + + /* + Add all surrounding blocks that have up-to-date lighting + NOTE: This doesn't quite do the job (not everything + appropriate is lighted) + */ + /*for(s16 z=-1; z<=1; z++) + for(s16 y=-1; y<=1; y++) + for(s16 x=-1; x<=1; x++) + { + v3s16 p(x,y,z); + MapBlock *block = getBlockNoCreateNoEx(p); + if(block == NULL) + continue; + if(block->isDummy()) + continue; + if(block->getLightingExpired()) + continue; + vmanip.initialEmerge(p, p); + }*/ + + // Lighting of block will be updated completely + block->setLightingExpired(false); + } + + { + //TimeTaker timer("unSpreadLight"); + vmanip.unspreadLight(bank, unlight_from, light_sources); + } + { + //TimeTaker timer("spreadLight"); + vmanip.spreadLight(bank, light_sources); + } + { + //TimeTaker timer("blitBack"); + vmanip.blitBack(modified_blocks); + } + /*dstream<<"emerge_time="< & a_blocks, + core::map & modified_blocks) +{ + updateLighting(LIGHTBANK_DAY, a_blocks, modified_blocks); + updateLighting(LIGHTBANK_NIGHT, a_blocks, modified_blocks); + + /* + Update information about whether day and night light differ + */ + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } +} + +/* + This is called after changing a node from transparent to opaque. + The lighting value of the node should be left as-is after changing + other values. This sets the lighting value to 0. +*/ +void Map::addNodeAndUpdate(v3s16 p, MapNode n, + core::map &modified_blocks) +{ + /*PrintInfo(m_dout); + m_dout< light_sources; + + /* + If there is a node at top and it doesn't have sunlight, + there has not been any sunlight going down. + + Otherwise there probably is. + */ + try{ + MapNode topnode = getNode(toppos); + + if(topnode.getLight(LIGHTBANK_DAY) != LIGHT_SUN) + node_under_sunlight = false; + } + catch(InvalidPositionException &e) + { + } + + /* + If the new node doesn't propagate sunlight and there is + grass below, change it to mud + */ + if(content_features(n.d).sunlight_propagates == false) + { + try{ + MapNode bottomnode = getNode(bottompos); + + if(bottomnode.d == CONTENT_GRASS + || bottomnode.d == CONTENT_GRASS_FOOTSTEPS) + { + bottomnode.d = CONTENT_MUD; + setNode(bottompos, bottomnode); + } + } + catch(InvalidPositionException &e) + { + } + } + + /* + If the new node is mud and it is under sunlight, change it + to grass + */ + if(n.d == CONTENT_MUD && node_under_sunlight) + { + n.d = CONTENT_GRASS; + } + + /* + Remove all light that has come out of this node + */ + + enum LightBank banks[] = + { + LIGHTBANK_DAY, + LIGHTBANK_NIGHT + }; + for(s32 i=0; i<2; i++) + { + enum LightBank bank = banks[i]; + + u8 lightwas = getNode(p).getLight(bank); + + // Add the block of the added node to modified_blocks + v3s16 blockpos = getNodeBlockPos(p); + MapBlock * block = getBlockNoCreate(blockpos); + assert(block != NULL); + modified_blocks.insert(blockpos, block); + + assert(isValidPosition(p)); + + // Unlight neighbours of node. + // This means setting light of all consequent dimmer nodes + // to 0. + // This also collects the nodes at the border which will spread + // light again into this. + unLightNeighbors(bank, p, lightwas, light_sources, modified_blocks); + + n.setLight(bank, 0); + } + + /* + If node lets sunlight through and is under sunlight, it has + sunlight too. + */ + if(node_under_sunlight && content_features(n.d).sunlight_propagates) + { + n.setLight(LIGHTBANK_DAY, LIGHT_SUN); + } + + /* + Set the node on the map + */ + + setNode(p, n); + + /* + Add intial metadata + */ + + NodeMetadata *meta_proto = content_features(n.d).initial_metadata; + if(meta_proto) + { + NodeMetadata *meta = meta_proto->clone(); + setNodeMetadata(p, meta); + } + + /* + If node is under sunlight and doesn't let sunlight through, + take all sunlighted nodes under it and clear light from them + and from where the light has been spread. + TODO: This could be optimized by mass-unlighting instead + of looping + */ + if(node_under_sunlight && !content_features(n.d).sunlight_propagates) + { + s16 y = p.Y - 1; + for(;; y--){ + //m_dout<::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } + + /* + Add neighboring liquid nodes and the node itself if it is + liquid (=water node was added) to transform queue. + */ + v3s16 dirs[7] = { + v3s16(0,0,0), // self + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<7; i++) + { + try + { + + v3s16 p2 = p + dirs[i]; + + MapNode n2 = getNode(p2); + if(content_liquid(n2.d)) + { + m_transforming_liquid.push_back(p2); + } + + }catch(InvalidPositionException &e) + { + } + } +} + +/* +*/ +void Map::removeNodeAndUpdate(v3s16 p, + core::map &modified_blocks) +{ + /*PrintInfo(m_dout); + m_dout< light_sources; + + enum LightBank banks[] = + { + LIGHTBANK_DAY, + LIGHTBANK_NIGHT + }; + for(s32 i=0; i<2; i++) + { + enum LightBank bank = banks[i]; + + /* + Unlight neighbors (in case the node is a light source) + */ + unLightNeighbors(bank, p, + getNode(p).getLight(bank), + light_sources, modified_blocks); + } + + /* + Remove node metadata + */ + + removeNodeMetadata(p); + + /* + Remove the node. + This also clears the lighting. + */ + + MapNode n; + n.d = replace_material; + setNode(p, n); + + for(s32 i=0; i<2; i++) + { + enum LightBank bank = banks[i]; + + /* + Recalculate lighting + */ + spreadLight(bank, light_sources, modified_blocks); + } + + // Add the block of the removed node to modified_blocks + v3s16 blockpos = getNodeBlockPos(p); + MapBlock * block = getBlockNoCreate(blockpos); + assert(block != NULL); + modified_blocks.insert(blockpos, block); + + /* + If the removed node was under sunlight, propagate the + sunlight down from it and then light all neighbors + of the propagated blocks. + */ + if(node_under_sunlight) + { + s16 ybottom = propagateSunlight(p, modified_blocks); + /*m_dout< ybottom="<= ybottom; y--) + { + v3s16 p2(p.X, y, p.Z); + /*m_dout<::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } + + /* + Add neighboring liquid nodes to transform queue. + */ + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<6; i++) + { + try + { + + v3s16 p2 = p + dirs[i]; + + MapNode n2 = getNode(p2); + if(content_liquid(n2.d)) + { + m_transforming_liquid.push_back(p2); + } + + }catch(InvalidPositionException &e) + { + } + } +} + +bool Map::addNodeWithEvent(v3s16 p, MapNode n) +{ + MapEditEvent event; + event.type = MEET_ADDNODE; + event.p = p; + event.n = n; + + bool succeeded = true; + try{ + core::map modified_blocks; + addNodeAndUpdate(p, n, modified_blocks); + + // Copy modified_blocks to event + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + event.modified_blocks.insert(i.getNode()->getKey(), false); + } + } + catch(InvalidPositionException &e){ + succeeded = false; + } + + dispatchEvent(&event); + + return succeeded; +} + +bool Map::removeNodeWithEvent(v3s16 p) +{ + MapEditEvent event; + event.type = MEET_REMOVENODE; + event.p = p; + + bool succeeded = true; + try{ + core::map modified_blocks; + removeNodeAndUpdate(p, modified_blocks); + + // Copy modified_blocks to event + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + event.modified_blocks.insert(i.getNode()->getKey(), false); + } + } + catch(InvalidPositionException &e){ + succeeded = false; + } + + dispatchEvent(&event); + + return succeeded; +} + +bool Map::dayNightDiffed(v3s16 blockpos) +{ + try{ + v3s16 p = blockpos + v3s16(0,0,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + // Leading edges + try{ + v3s16 p = blockpos + v3s16(-1,0,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,-1,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,0,-1); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + // Trailing edges + try{ + v3s16 p = blockpos + v3s16(1,0,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,1,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,0,1); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + + return false; +} + +/* + Updates usage timers +*/ +void Map::timerUpdate(float dtime) +{ + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + + core::map::Iterator si; + + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + sector->usage_timer += dtime; + } +} + +void Map::deleteSectors(core::list &list, bool only_blocks) +{ + /* + Wait for caches to be removed before continuing. + + This disables the existence of caches while locked + */ + //SharedPtr cachelock(m_blockcachelock.waitCaches()); + + core::list::Iterator j; + for(j=list.begin(); j!=list.end(); j++) + { + MapSector *sector = m_sectors[*j]; + if(only_blocks) + { + sector->deleteBlocks(); + } + else + { + /* + If sector is in sector cache, remove it from there + */ + if(m_sector_cache == sector) + { + m_sector_cache = NULL; + } + /* + Remove from map and delete + */ + m_sectors.remove(*j); + delete sector; + } + } +} + +u32 Map::deleteUnusedSectors(float timeout, bool only_blocks, + core::list *deleted_blocks) +{ + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + + core::list sector_deletion_queue; + core::map::Iterator i = m_sectors.getIterator(); + for(; i.atEnd() == false; i++) + { + MapSector *sector = i.getNode()->getValue(); + /* + Delete sector from memory if it hasn't been used in a long time + */ + if(sector->usage_timer > timeout) + { + sector_deletion_queue.push_back(i.getNode()->getKey()); + + if(deleted_blocks != NULL) + { + // Collect positions of blocks of sector + MapSector *sector = i.getNode()->getValue(); + core::list blocks; + sector->getBlocks(blocks); + for(core::list::Iterator i = blocks.begin(); + i != blocks.end(); i++) + { + deleted_blocks->push_back((*i)->getPos()); + } + } + } + } + deleteSectors(sector_deletion_queue, only_blocks); + return sector_deletion_queue.getSize(); +} + +void Map::PrintInfo(std::ostream &out) +{ + out<<"Map: "; +} + +#define WATER_DROP_BOOST 4 + +void Map::transformLiquids(core::map & modified_blocks) +{ + DSTACK(__FUNCTION_NAME); + //TimeTaker timer("transformLiquids()"); + + u32 loopcount = 0; + u32 initial_size = m_transforming_liquid.size(); + + /*if(initial_size != 0) + dstream<<"transformLiquids(): initial_size="<= 7 - WATER_DROP_BOOST) + new_liquid_level = 7; + else + new_liquid_level = n2_liquid_level + WATER_DROP_BOOST; + } + else if(n2_liquid_level > 0) + { + new_liquid_level = n2_liquid_level - 1; + } + + if(new_liquid_level > new_liquid_level_max) + new_liquid_level_max = new_liquid_level; + } + + }catch(InvalidPositionException &e) + { + } + } //for + + /* + If liquid level should be something else, update it and + add all the neighboring water nodes to the transform queue. + */ + if(new_liquid_level_max != liquid_level) + { + if(new_liquid_level_max == -1) + { + // Remove water alltoghether + n0.d = CONTENT_AIR; + n0.param2 = 0; + setNode(p0, n0); + } + else + { + n0.param2 = new_liquid_level_max; + setNode(p0, n0); + } + + // Block has been modified + { + v3s16 blockpos = getNodeBlockPos(p0); + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block != NULL) + modified_blocks.insert(blockpos, block); + } + + /* + Add neighboring non-source liquid nodes to transform queue. + */ + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<6; i++) + { + try + { + + v3s16 p2 = p0 + dirs[i]; + + MapNode n2 = getNode(p2); + if(content_flowing_liquid(n2.d)) + { + m_transforming_liquid.push_back(p2); + } + + }catch(InvalidPositionException &e) + { + } + } + } + } + + // Get a new one from queue if the node has turned into non-water + if(content_liquid(n0.d) == false) + continue; + + /* + Flow water from this node + */ + v3s16 dirs_to[5] = { + v3s16(0,-1,0), // bottom + v3s16(0,0,1), // back + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<5; i++) + { + try + { + + bool to_bottom = (i == 0); + + // If liquid is at lowest possible height, it's not going + // anywhere except down + if(liquid_level == 0 && to_bottom == false) + continue; + + u8 liquid_next_level = 0; + // If going to bottom + if(to_bottom) + { + //liquid_next_level = 7; + if(liquid_level >= 7 - WATER_DROP_BOOST) + liquid_next_level = 7; + else + liquid_next_level = liquid_level + WATER_DROP_BOOST; + } + else + liquid_next_level = liquid_level - 1; + + bool n2_changed = false; + bool flowed = false; + + v3s16 p2 = p0 + dirs_to[i]; + + MapNode n2 = getNode(p2); + //dstream<<"[1] n2.param="<<(int)n2.param< liquid_level) + { + n2.param2 = liquid_next_level; + setNode(p2, n2); + + n2_changed = true; + flowed = true; + } + } + } + else if(n2.d == CONTENT_AIR) + { + n2.d = nonsource_c; + n2.param2 = liquid_next_level; + setNode(p2, n2); + + n2_changed = true; + flowed = true; + } + + //dstream<<"[2] n2.param="<<(int)n2.param<= 100000) + if(loopcount >= initial_size * 1) + break; + } + //dstream<<"Map::transformLiquids(): loopcount="<m_node_metadata.get(p_rel); + return meta; +} + +void Map::setNodeMetadata(v3s16 p, NodeMetadata *meta) +{ + v3s16 blockpos = getNodeBlockPos(p); + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + { + dstream<<"WARNING: Map::setNodeMetadata(): Block not found" + <m_node_metadata.set(p_rel, meta); +} + +void Map::removeNodeMetadata(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + { + dstream<<"WARNING: Map::removeNodeMetadata(): Block not found" + <m_node_metadata.remove(p_rel); +} + +void Map::nodeMetadataStep(float dtime, + core::map &changed_blocks) +{ + /* + NOTE: + Currently there is no way to ensure that all the necessary + blocks are loaded when this is run. (They might get unloaded) + NOTE: ^- Actually, that might not be so. In a quick test it + reloaded a block with a furnace when I walked back to it from + a distance. + */ + core::map::Iterator si; + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + core::list< MapBlock * > sectorblocks; + sector->getBlocks(sectorblocks); + core::list< MapBlock * >::Iterator i; + for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++) + { + MapBlock *block = *i; + bool changed = block->m_node_metadata.step(dtime); + if(changed) + changed_blocks[block->getPos()] = block; + } + } +} + +/* + ServerMap +*/ + +ServerMap::ServerMap(std::string savedir): + Map(dout_server), + m_seed(0), + m_map_metadata_changed(true) +{ + dstream<<__FUNCTION_NAME<::Iterator i = m_chunks.getIterator(); + for(; i.atEnd() == false; i++) + { + MapChunk *chunk = i.getNode()->getValue(); + delete chunk; + } +} + +/* + Some helper functions for the map generator +*/ + +s16 find_ground_level(VoxelManipulator &vmanip, v2s16 p2d) +{ + v3s16 em = vmanip.m_area.getExtent(); + s16 y_nodes_max = vmanip.m_area.MaxEdge.Y; + s16 y_nodes_min = vmanip.m_area.MinEdge.Y; + u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y)); + s16 y; + for(y=y_nodes_max; y>=y_nodes_min; y--) + { + MapNode &n = vmanip.m_data[i]; + if(content_walkable(n.d)) + break; + + vmanip.m_area.add_y(em, i, -1); + } + if(y >= y_nodes_min) + return y; + else + return y_nodes_min; +} + +s16 find_ground_level_clever(VoxelManipulator &vmanip, v2s16 p2d) +{ + v3s16 em = vmanip.m_area.getExtent(); + s16 y_nodes_max = vmanip.m_area.MaxEdge.Y; + s16 y_nodes_min = vmanip.m_area.MinEdge.Y; + u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y)); + s16 y; + for(y=y_nodes_max; y>=y_nodes_min; y--) + { + MapNode &n = vmanip.m_data[i]; + if(content_walkable(n.d) + && n.d != CONTENT_TREE + && n.d != CONTENT_LEAVES) + break; + + vmanip.m_area.add_y(em, i, -1); + } + if(y >= y_nodes_min) + return y; + else + return y_nodes_min; +} + +void make_tree(VoxelManipulator &vmanip, v3s16 p0) +{ + MapNode treenode(CONTENT_TREE); + MapNode leavesnode(CONTENT_LEAVES); + + s16 trunk_h = myrand_range(3, 6); + v3s16 p1 = p0; + for(s16 ii=0; ii leaves_d(new u8[leaves_a.getVolume()]); + Buffer leaves_d(leaves_a.getVolume()); + for(s32 i=0; i0, 0->1, 1->0 +double contour(double v) +{ + v = fabs(v); + if(v >= 1.0) + return 0.0; + return (1.0-v); +}*/ + +/* + Noise functions. Make sure seed is mangled differently in each one. +*/ + +// This affects the shape of the contour +#define CAVE_NOISE_SCALE 10.0 + +NoiseParams get_cave_noise1_params(u64 seed) +{ + return NoiseParams(NOISE_PERLIN_CONTOUR, seed+52534, 5, 0.7, + 200, CAVE_NOISE_SCALE); +} + +NoiseParams get_cave_noise2_params(u64 seed) +{ + return NoiseParams(NOISE_PERLIN_CONTOUR_FLIP_YZ, seed+10325, 5, 0.7, + 200, CAVE_NOISE_SCALE); +} + +#define CAVE_NOISE_THRESHOLD (2.5/CAVE_NOISE_SCALE) + +bool is_cave(u64 seed, v3s16 p) +{ + double d1 = noise3d_param(get_cave_noise1_params(seed), p.X,p.Y,p.Z); + double d2 = noise3d_param(get_cave_noise2_params(seed), p.X,p.Y,p.Z); + return d1*d2 > CAVE_NOISE_THRESHOLD; +} + +// Amount of trees per area in nodes +double tree_amount_2d(u64 seed, v2s16 p) +{ + double noise = noise2d_perlin( + 0.5+(float)p.X/250, 0.5+(float)p.Y/250, + seed+2, 5, 0.66); + double zeroval = -0.3; + if(noise < zeroval) + return 0; + else + return 0.04 * (noise-zeroval) / (1.0-zeroval); +} + +#define AVERAGE_MUD_AMOUNT 4 + +double base_rock_level_2d(u64 seed, v2s16 p) +{ + // The base ground level + double base = (double)WATER_LEVEL - (double)AVERAGE_MUD_AMOUNT + + 20. * noise2d_perlin( + 0.5+(float)p.X/500., 0.5+(float)p.Y/500., + (seed>>32)+654879876, 6, 0.6); + + /*// A bit hillier one + double base2 = WATER_LEVEL - 4.0 + 40. * noise2d_perlin( + 0.5+(float)p.X/250., 0.5+(float)p.Y/250., + (seed>>27)+90340, 6, 0.69); + if(base2 > base) + base = base2;*/ +#if 1 + // Higher ground level + double higher = (double)WATER_LEVEL + 25. + 35. * noise2d_perlin( + 0.5+(float)p.X/250., 0.5+(float)p.Y/250., + seed+85039, 5, 0.69); + //higher = 30; // For debugging + + // Limit higher to at least base + if(higher < base) + higher = base; + + // Steepness factor of cliffs + double b = 1.0 + 1.0 * noise2d_perlin( + 0.5+(float)p.X/250., 0.5+(float)p.Y/250., + seed-932, 7, 0.7); + b = rangelim(b, 0.0, 1000.0); + b = pow(b, 5); + b *= 7; + b = rangelim(b, 3.0, 1000.0); + //dstream<<"b="<sectorpos_bigbase.X*MAP_BLOCKSIZE, + y_nodes_min, + data->sectorpos_bigbase.Y*MAP_BLOCKSIZE + ); + v3f maxpos_f = minpos_f + v3f( + data->sectorpos_bigbase_size*MAP_BLOCKSIZE, + y_nodes_max-y_nodes_min, + data->sectorpos_bigbase_size*MAP_BLOCKSIZE + ); + //v3f samplelength_f = v3f(4.0, 4.0, 4.0); + + TimeTaker timer("noisebuf.create"); + + noisebuf_cave.create(get_cave_noise1_params(data->seed), + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y, maxpos_f.Z, + 4, 4, 4); + + noisebuf_cave.multiply(get_cave_noise2_params(data->seed)); + + /*noisebuf1.create(data->seed+25104, 6, 0.60, 200.0, false, + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y, maxpos_f.Z, + samplelength_f.X, samplelength_f.Y, samplelength_f.Z);*/ + /*noisebuf1.create(data->seed+25104, 3, 0.60, 25.0, false, + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y, maxpos_f.Z, + samplelength_f.X, samplelength_f.Y, samplelength_f.Z); + noisebuf2.create(data->seed+25105, 4, 0.50, 200.0, false, + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y, maxpos_f.Z, + samplelength_f.X, samplelength_f.Y, samplelength_f.Z);*/ + } + +#if 0 + for(s16 x=0; xsectorpos_bigbase_size*MAP_BLOCKSIZE; x++) + for(s16 z=0; zsectorpos_bigbase_size*MAP_BLOCKSIZE; z++) + { + // Node position + v2s16 p2d = data->sectorpos_bigbase*MAP_BLOCKSIZE + v2s16(x,z); + + // Ground height at this point + float surface_y_f = 0.0; + + // Use perlin noise for ground height + surface_y_f = base_rock_level_2d(data->seed, p2d); + //surface_y_f = base_rock_level_2d(data->seed, p2d); + + // Convert to integer + s16 surface_y = (s16)surface_y_f; + + // Log it + if(surface_y > stone_surface_max_y) + stone_surface_max_y = surface_y; + + /* + Fill ground with stone + */ + { + // Use fast index incrementing + v3s16 em = data->vmanip.m_area.getExtent(); + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_nodes_min, p2d.Y)); + for(s16 y=y_nodes_min; y<=y_nodes_max; y++) + { + // Skip if already generated. + // This is done here because there might be a cave at + // any point in ground, which could look like it + // wasn't generated. + if(data->vmanip.m_data[i].d != CONTENT_AIR) + break; + + /*s16 noiseval = 50.0 * noise3d_perlin( + 0.5+(float)p2d.X/100.0, + 0.5+(float)y/100.0, + 0.5+(float)p2d.Y/100.0, + data->seed+123, 5, 0.5);*/ + double noiseval = 64.0 * noisebuf1.get(p2d.X, y, p2d.Y); + /*double noiseval = 30.0 * noisebuf1.get(p2d.X, y, p2d.Y); + noiseval *= MYMAX(0, -0.2 + noisebuf2.get(p2d.X, y, p2d.Y));*/ + + //if(y < surface_y + noiseval) + if(noiseval > 0) + //if(noiseval > y) + data->vmanip.m_data[i].d = CONTENT_STONE; + + data->vmanip.m_area.add_y(em, i, 1); + } + } + } +#endif + +#if 1 + for(s16 x=0; xsectorpos_bigbase_size*MAP_BLOCKSIZE; x++) + for(s16 z=0; zsectorpos_bigbase_size*MAP_BLOCKSIZE; z++) + { + // Node position + v2s16 p2d = data->sectorpos_bigbase*MAP_BLOCKSIZE + v2s16(x,z); + + /* + Skip of already generated + */ + /*{ + v3s16 p(p2d.X, y_nodes_min, p2d.Y); + if(data->vmanip.m_data[data->vmanip.m_area.index(p)].d != CONTENT_AIR) + continue; + }*/ + +#define CAVE_TEST 0 + +#if CAVE_TEST + /* + Fill ground with stone + */ + { + // Use fast index incrementing + v3s16 em = data->vmanip.m_area.getExtent(); + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_nodes_min, p2d.Y)); + for(s16 y=y_nodes_min; y<=y_nodes_max; y++) + { + // Skip if already generated. + // This is done here because there might be a cave at + // any point in ground, which could look like it + // wasn't generated. + if(data->vmanip.m_data[i].d != CONTENT_AIR) + break; + + //if(is_cave(data->seed, v3s16(p2d.X, y, p2d.Y))) + if(noisebuf_cave.get(p2d.X,y,p2d.Y) > CAVE_NOISE_THRESHOLD) + { + data->vmanip.m_data[i].d = CONTENT_STONE; + } + else + { + data->vmanip.m_data[i].d = CONTENT_AIR; + } + + data->vmanip.m_area.add_y(em, i, 1); + } + } +#else + // Ground height at this point + float surface_y_f = 0.0; + + // Use perlin noise for ground height + surface_y_f = base_rock_level_2d(data->seed, p2d); + + // Convert to integer + s16 surface_y = (s16)surface_y_f; + + // Log it + if(surface_y > stone_surface_max_y) + stone_surface_max_y = surface_y; + + /* + Fill ground with stone + */ + { + // Use fast index incrementing + v3s16 em = data->vmanip.m_area.getExtent(); + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_nodes_min, p2d.Y)); + for(s16 y=y_nodes_min; yvmanip.m_data[i].d != CONTENT_AIR) + break; + + //if(is_cave(data->seed, v3s16(p2d.X, y, p2d.Y))) + if(noisebuf_cave.get(p2d.X,y,p2d.Y) > CAVE_NOISE_THRESHOLD) + { + // Set tunnel flag + data->vmanip.m_flags[i] |= VMANIP_FLAG_DUNGEON; + // Is now air + data->vmanip.m_data[i].d = CONTENT_AIR; + } + else + { + data->vmanip.m_data[i].d = CONTENT_STONE; + } + + data->vmanip.m_area.add_y(em, i, 1); + } + } +#endif // !CAVE_TEST + } +#endif + + }//timer1 + + /* + Randomize some parameters + */ + + //s32 stone_obstacle_count = 0; + /*s32 stone_obstacle_count = + rangelim((1.0+noise2d(data->seed+897, + data->sectorpos_base.X, data->sectorpos_base.Y))/2.0 * 30, 0, 100000);*/ + + //s16 stone_obstacle_max_height = 0; + /*s16 stone_obstacle_max_height = + rangelim((1.0+noise2d(data->seed+5902, + data->sectorpos_base.X, data->sectorpos_base.Y))/2.0 * 30, 0, 100000);*/ + + // Set to 0 to disable everything but lighting +#if 1 + + /* + Loop this part, it will make stuff look older and newer nicely + */ + const u32 age_loops = 2; + for(u32 i_age=0; i_age caves_count); + + if(bruise_surface) + { + min_tunnel_diameter = 5; + max_tunnel_diameter = myrand_range(10, 20); + /*min_tunnel_diameter = MYMAX(0, stone_surface_max_y/6); + max_tunnel_diameter = myrand_range(MYMAX(0, stone_surface_max_y/6), MYMAX(0, stone_surface_max_y/2));*/ + + /*s16 tunnel_rou = rangelim(25*(0.5+1.0*noise2d(data->seed+42, + data->sectorpos_base.X, data->sectorpos_base.Y)), 0, 15);*/ + + tunnel_routepoints = 5; + } + else + { + } + + // Allowed route area size in nodes + v3s16 ar( + data->sectorpos_base_size*MAP_BLOCKSIZE, + h_blocks*MAP_BLOCKSIZE, + data->sectorpos_base_size*MAP_BLOCKSIZE + ); + + // Area starting point in nodes + v3s16 of( + data->sectorpos_base.X*MAP_BLOCKSIZE, + data->y_blocks_min*MAP_BLOCKSIZE, + data->sectorpos_base.Y*MAP_BLOCKSIZE + ); + + // Allow a bit more + //(this should be more than the maximum radius of the tunnel) + //s16 insure = 5; // Didn't work with max_d = 20 + s16 insure = 10; + s16 more = data->max_spread_amount - max_tunnel_diameter/2 - insure; + ar += v3s16(1,0,1) * more * 2; + of -= v3s16(1,0,1) * more; + + s16 route_y_min = 0; + // Allow half a diameter + 7 over stone surface + s16 route_y_max = -of.Y + stone_surface_max_y + max_tunnel_diameter/2 + 7; + + /*// If caves, don't go through surface too often + if(bruise_surface == false) + route_y_max -= myrand_range(0, max_tunnel_diameter*2);*/ + + // Limit maximum to area + route_y_max = rangelim(route_y_max, 0, ar.Y-1); + + if(bruise_surface) + { + /*// Minimum is at y=0 + route_y_min = -of.Y - 0;*/ + // Minimum is at y=max_tunnel_diameter/4 + //route_y_min = -of.Y + max_tunnel_diameter/4; + //s16 min = -of.Y + max_tunnel_diameter/4; + s16 min = -of.Y + 0; + route_y_min = myrand_range(min, min + max_tunnel_diameter); + route_y_min = rangelim(route_y_min, 0, route_y_max); + } + + /*dstream<<"route_y_min = "<vmanip.m_area.index(p); + data->vmanip.m_data[i] = airnode; + + if(bruise_surface == false) + { + // Set tunnel flag + data->vmanip.m_flags[i] |= VMANIP_FLAG_DUNGEON; + } + } + } + } + } + + orp = rp; + } + + } + + }//timer1 +#endif + +#if 1 + { + // 46ms @cs=8 + //TimeTaker timer1("ore veins"); + + /* + Make ore veins + */ + for(u32 jj=0; jjsectorpos_base_size*MAP_BLOCKSIZE, + h_blocks*MAP_BLOCKSIZE, + data->sectorpos_base_size*MAP_BLOCKSIZE + ); + + // Area starting point in nodes + v3s16 of( + data->sectorpos_base.X*MAP_BLOCKSIZE, + data->y_blocks_min*MAP_BLOCKSIZE, + data->sectorpos_base.Y*MAP_BLOCKSIZE + ); + + // Allow a bit more + //(this should be more than the maximum radius of the tunnel) + s16 insure = 3; + s16 more = data->max_spread_amount - max_vein_diameter/2 - insure; + ar += v3s16(1,0,1) * more * 2; + of -= v3s16(1,0,1) * more; + + // Randomize starting position + v3f orp( + (float)(myrand()%ar.X)+0.5, + (float)(myrand()%ar.Y)+0.5, + (float)(myrand()%ar.Z)+0.5 + ); + + // Randomize mineral + u8 mineral; + if(myrand()%3 != 0) + mineral = MINERAL_COAL; + else + mineral = MINERAL_IRON; + + /* + Generate some vein starting from orp + */ + + for(u16 j=0; j<2; j++) + { + /*v3f rp( + (float)(myrand()%ar.X)+0.5, + (float)(myrand()%ar.Y)+0.5, + (float)(myrand()%ar.Z)+0.5 + ); + v3f vec = rp - orp;*/ + + v3s16 maxlen(5, 5, 5); + v3f vec( + (float)(myrand()%(maxlen.X*2))-(float)maxlen.X, + (float)(myrand()%(maxlen.Y*2))-(float)maxlen.Y, + (float)(myrand()%(maxlen.Z*2))-(float)maxlen.Z + ); + v3f rp = orp + vec; + if(rp.X < 0) + rp.X = 0; + else if(rp.X >= ar.X) + rp.X = ar.X; + if(rp.Y < 0) + rp.Y = 0; + else if(rp.Y >= ar.Y) + rp.Y = ar.Y; + if(rp.Z < 0) + rp.Z = 0; + else if(rp.Z >= ar.Z) + rp.Z = ar.Z; + vec = rp - orp; + + // Randomize size + s16 min_d = 0; + s16 max_d = max_vein_diameter; + s16 rs = myrand_range(min_d, max_d); + + for(float f=0; f<1.0; f+=1.0/vec.getLength()) + { + v3f fp = orp + vec * f; + v3s16 cp(fp.X, fp.Y, fp.Z); + s16 d0 = -rs/2; + s16 d1 = d0 + rs - 1; + for(s16 z0=d0; z0<=d1; z0++) + { + s16 si = rs - abs(z0); + for(s16 x0=-si; x0<=si-1; x0++) + { + s16 si2 = rs - abs(x0); + for(s16 y0=-si2+1; y0<=si2-1; y0++) + { + // Don't put mineral to every place + if(myrand()%5 != 0) + continue; + + s16 z = cp.Z + z0; + s16 y = cp.Y + y0; + s16 x = cp.X + x0; + v3s16 p(x,y,z); + /*if(isInArea(p, ar) == false) + continue;*/ + // Check only height + if(y < 0 || y >= ar.Y) + continue; + p += of; + + assert(data->vmanip.m_area.contains(p)); + + // Just set it to air, it will be changed to + // water afterwards + u32 i = data->vmanip.m_area.index(p); + MapNode *n = &data->vmanip.m_data[i]; + if(n->d == CONTENT_STONE) + n->param = mineral; + } + } + } + } + + orp = rp; + } + + } + + }//timer1 +#endif + +#if 1 + { + // 15ms @cs=8 + TimeTaker timer1("add mud"); + + /* + Add mud to the central chunk + */ + + for(s16 x=0; xsectorpos_base_size*MAP_BLOCKSIZE; x++) + for(s16 z=0; zsectorpos_base_size*MAP_BLOCKSIZE; z++) + { + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + // Randomize mud amount + s16 mud_add_amount = get_mud_add_amount(data->seed, p2d) / 2.0; + + // Find ground level + s16 surface_y = find_ground_level_clever(data->vmanip, p2d); + + /* + If topmost node is grass, change it to mud. + It might be if it was flown to there from a neighboring + chunk and then converted. + */ + { + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, surface_y, p2d.Y)); + MapNode *n = &data->vmanip.m_data[i]; + if(n->d == CONTENT_GRASS) + *n = MapNode(CONTENT_MUD); + //n->d = CONTENT_MUD; + } + + /* + Add mud on ground + */ + { + s16 mudcount = 0; + v3s16 em = data->vmanip.m_area.getExtent(); + s16 y_start = surface_y+1; + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y)); + for(s16 y=y_start; y<=y_nodes_max; y++) + { + if(mudcount >= mud_add_amount) + break; + + MapNode &n = data->vmanip.m_data[i]; + n = MapNode(CONTENT_MUD); + //n.d = CONTENT_MUD; + mudcount++; + + data->vmanip.m_area.add_y(em, i, 1); + } + } + + } + + }//timer1 +#endif + +#if 1 + { + // 340ms @cs=8 + TimeTaker timer1("flow mud"); + + /* + Flow mud away from steep edges + */ + + // Limit area by 1 because mud is flown into neighbors. + s16 mudflow_minpos = 0-data->max_spread_amount+1; + s16 mudflow_maxpos = data->sectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount-2; + + // Iterate a few times + for(s16 k=0; k<3; k++) + { + + for(s16 x=mudflow_minpos; + x<=mudflow_maxpos; + x++) + for(s16 z=mudflow_minpos; + z<=mudflow_maxpos; + z++) + { + // Invert coordinates every 2nd iteration + if(k%2 == 0) + { + x = mudflow_maxpos - (x-mudflow_minpos); + z = mudflow_maxpos - (z-mudflow_minpos); + } + + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + v3s16 em = data->vmanip.m_area.getExtent(); + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y)); + s16 y=y_nodes_max; + + for(;; y--) + { + MapNode *n = NULL; + // Find mud + for(; y>=y_nodes_min; y--) + { + n = &data->vmanip.m_data[i]; + //if(content_walkable(n->d)) + // break; + if(n->d == CONTENT_MUD || n->d == CONTENT_GRASS) + break; + + data->vmanip.m_area.add_y(em, i, -1); + } + + // Stop if out of area + //if(data->vmanip.m_area.contains(i) == false) + if(y < y_nodes_min) + break; + + /*// If not mud, do nothing to it + MapNode *n = &data->vmanip.m_data[i]; + if(n->d != CONTENT_MUD && n->d != CONTENT_GRASS) + continue;*/ + + /* + Don't flow it if the stuff under it is not mud + */ + { + u32 i2 = i; + data->vmanip.m_area.add_y(em, i2, -1); + // Cancel if out of area + if(data->vmanip.m_area.contains(i2) == false) + continue; + MapNode *n2 = &data->vmanip.m_data[i2]; + if(n2->d != CONTENT_MUD && n2->d != CONTENT_GRASS) + continue; + } + + // Make it exactly mud + n->d = CONTENT_MUD; + + /*s16 recurse_count = 0; + mudflow_recurse:*/ + + v3s16 dirs4[4] = { + v3s16(0,0,1), // back + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(-1,0,0), // left + }; + + // Theck that upper is air or doesn't exist. + // Cancel dropping if upper keeps it in place + u32 i3 = i; + data->vmanip.m_area.add_y(em, i3, 1); + if(data->vmanip.m_area.contains(i3) == true + && content_walkable(data->vmanip.m_data[i3].d) == true) + { + continue; + } + + // Drop mud on side + + for(u32 di=0; di<4; di++) + { + v3s16 dirp = dirs4[di]; + u32 i2 = i; + // Move to side + data->vmanip.m_area.add_p(em, i2, dirp); + // Fail if out of area + if(data->vmanip.m_area.contains(i2) == false) + continue; + // Check that side is air + MapNode *n2 = &data->vmanip.m_data[i2]; + if(content_walkable(n2->d)) + continue; + // Check that under side is air + data->vmanip.m_area.add_y(em, i2, -1); + if(data->vmanip.m_area.contains(i2) == false) + continue; + n2 = &data->vmanip.m_data[i2]; + if(content_walkable(n2->d)) + continue; + /*// Check that under that is air (need a drop of 2) + data->vmanip.m_area.add_y(em, i2, -1); + if(data->vmanip.m_area.contains(i2) == false) + continue; + n2 = &data->vmanip.m_data[i2]; + if(content_walkable(n2->d)) + continue;*/ + // Loop further down until not air + do{ + data->vmanip.m_area.add_y(em, i2, -1); + // Fail if out of area + if(data->vmanip.m_area.contains(i2) == false) + continue; + n2 = &data->vmanip.m_data[i2]; + }while(content_walkable(n2->d) == false); + // Loop one up so that we're in air + data->vmanip.m_area.add_y(em, i2, 1); + n2 = &data->vmanip.m_data[i2]; + + // Move mud to new place + *n2 = *n; + // Set old place to be air + *n = MapNode(CONTENT_AIR); + + // Done + break; + } + } + } + + } + + }//timer1 +#endif + +#if 1 + { + // 50ms @cs=8 + TimeTaker timer1("add water"); + + /* + Add water to the central chunk (and a bit more) + */ + + for(s16 x=0-data->max_spread_amount; + xsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount; + x++) + for(s16 z=0-data->max_spread_amount; + zsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount; + z++) + { + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + // Find ground level + //s16 surface_y = find_ground_level(data->vmanip, p2d); + + /* + If ground level is over water level, skip. + NOTE: This leaves caves near water without water, + which looks especially crappy when the nearby water + won't start flowing either for some reason + */ + /*if(surface_y > WATER_LEVEL) + continue;*/ + + /* + Add water on ground + */ + { + v3s16 em = data->vmanip.m_area.getExtent(); + u8 light = LIGHT_MAX; + // Start at global water surface level + s16 y_start = WATER_LEVEL; + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y)); + MapNode *n = &data->vmanip.m_data[i]; + + for(s16 y=y_start; y>=y_nodes_min; y--) + { + n = &data->vmanip.m_data[i]; + + // Stop when there is no water and no air + if(n->d != CONTENT_AIR && n->d != CONTENT_WATERSOURCE + && n->d != CONTENT_WATER) + { + + break; + } + + // Make water only not in caves + if(!(data->vmanip.m_flags[i]&VMANIP_FLAG_DUNGEON)) + { + n->d = CONTENT_WATERSOURCE; + //n->setLight(LIGHTBANK_DAY, light); + + // Add to transforming liquid queue (in case it'd + // start flowing) + v3s16 p = v3s16(p2d.X, y, p2d.Y); + data->transforming_liquid.push_back(p); + } + + // Next one + data->vmanip.m_area.add_y(em, i, -1); + if(light > 0) + light--; + } + } + + } + + }//timer1 +#endif + + } // Aging loop + /*********************** + END OF AGING LOOP + ************************/ + +#if 1 + { + //TimeTaker timer1("convert mud to sand"); + + /* + Convert mud to sand + */ + + //s16 mud_add_amount = myrand_range(2, 4); + //s16 mud_add_amount = 0; + + /*for(s16 x=0; xsectorpos_base_size*MAP_BLOCKSIZE; x++) + for(s16 z=0; zsectorpos_base_size*MAP_BLOCKSIZE; z++)*/ + for(s16 x=0-data->max_spread_amount+1; + xsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount-1; + x++) + for(s16 z=0-data->max_spread_amount+1; + zsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount-1; + z++) + { + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + // Determine whether to have sand here + double sandnoise = noise2d_perlin( + 0.5+(float)p2d.X/500, 0.5+(float)p2d.Y/500, + data->seed+59420, 3, 0.50); + + bool have_sand = (sandnoise > -0.15); + + if(have_sand == false) + continue; + + // Find ground level + s16 surface_y = find_ground_level_clever(data->vmanip, p2d); + + if(surface_y > WATER_LEVEL + 2) + continue; + + { + v3s16 em = data->vmanip.m_area.getExtent(); + s16 y_start = surface_y; + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y)); + u32 not_sand_counter = 0; + for(s16 y=y_start; y>=y_nodes_min; y--) + { + MapNode *n = &data->vmanip.m_data[i]; + if(n->d == CONTENT_MUD || n->d == CONTENT_GRASS) + { + n->d = CONTENT_SAND; + } + else + { + not_sand_counter++; + if(not_sand_counter > 3) + break; + } + + data->vmanip.m_area.add_y(em, i, -1); + } + } + + } + + }//timer1 +#endif + +#if 1 + { + // 1ms @cs=8 + //TimeTaker timer1("generate trees"); + + /* + Generate some trees + */ + { + // Divide area into parts + s16 div = 8; + s16 sidelen = data->sectorpos_base_size*MAP_BLOCKSIZE / div; + double area = sidelen * sidelen; + for(s16 x0=0; x0sectorpos_base.X*MAP_BLOCKSIZE + sidelen/2 + sidelen*x0, + data->sectorpos_base.Y*MAP_BLOCKSIZE + sidelen/2 + sidelen*z0 + ); + // Minimum edge of part of division + v2s16 p2d_min( + data->sectorpos_base.X*MAP_BLOCKSIZE + sidelen*x0, + data->sectorpos_base.Y*MAP_BLOCKSIZE + sidelen*z0 + ); + // Maximum edge of part of division + v2s16 p2d_max( + data->sectorpos_base.X*MAP_BLOCKSIZE + sidelen + sidelen*x0 - 1, + data->sectorpos_base.Y*MAP_BLOCKSIZE + sidelen + sidelen*z0 - 1 + ); + // Amount of trees + u32 tree_count = area * tree_amount_2d(data->seed, p2d_center); + // Put trees in random places on part of division + for(u32 i=0; ivmanip, v2s16(x,z)); + // Don't make a tree under water level + if(y < WATER_LEVEL) + continue; + // Don't make a tree so high that it doesn't fit + if(y > y_nodes_max - 6) + continue; + v3s16 p(x,y,z); + /* + Trees grow only on mud and grass + */ + { + u32 i = data->vmanip.m_area.index(v3s16(p)); + MapNode *n = &data->vmanip.m_data[i]; + if(n->d != CONTENT_MUD && n->d != CONTENT_GRASS) + continue; + } + p.Y++; + // Make a tree + make_tree(data->vmanip, p); + } + } + /*u32 tree_max = relative_area / 60; + //u32 count = myrand_range(0, tree_max); + for(u32 i=0; isectorpos_base_size*MAP_BLOCKSIZE-1); + s16 z = myrand_range(0, data->sectorpos_base_size*MAP_BLOCKSIZE-1); + x += data->sectorpos_base.X*MAP_BLOCKSIZE; + z += data->sectorpos_base.Y*MAP_BLOCKSIZE; + s16 y = find_ground_level(data->vmanip, v2s16(x,z)); + // Don't make a tree under water level + if(y < WATER_LEVEL) + continue; + v3s16 p(x,y+1,z); + // Make a tree + make_tree(data->vmanip, p); + }*/ + } + + }//timer1 +#endif + +#if 1 + { + // 19ms @cs=8 + //TimeTaker timer1("grow grass"); + + /* + Grow grass + */ + + /*for(s16 x=0-4; xsectorpos_base_size*MAP_BLOCKSIZE+4; x++) + for(s16 z=0-4; zsectorpos_base_size*MAP_BLOCKSIZE+4; z++)*/ + for(s16 x=0-data->max_spread_amount; + xsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount; + x++) + for(s16 z=0-data->max_spread_amount; + zsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount; + z++) + { + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + /* + Find the lowest surface to which enough light ends up + to make grass grow. + + Basically just wait until not air and not leaves. + */ + s16 surface_y = 0; + { + v3s16 em = data->vmanip.m_area.getExtent(); + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y)); + s16 y; + // Go to ground level + for(y=y_nodes_max; y>=y_nodes_min; y--) + { + MapNode &n = data->vmanip.m_data[i]; + if(n.d != CONTENT_AIR + && n.d != CONTENT_LEAVES) + break; + data->vmanip.m_area.add_y(em, i, -1); + } + if(y >= y_nodes_min) + surface_y = y; + else + surface_y = y_nodes_min; + } + + u32 i = data->vmanip.m_area.index(p2d.X, surface_y, p2d.Y); + MapNode *n = &data->vmanip.m_data[i]; + if(n->d == CONTENT_MUD) + n->d = CONTENT_GRASS; + } + + }//timer1 +#endif + +#endif // Disable all but lighting + + /* + Initial lighting (sunlight) + */ + + core::map light_sources; + + { + // 750ms @cs=8, can't optimize more + TimeTaker timer1("initial lighting"); + + // NOTE: This is no used... umm... for some reason! +#if 0 + /* + Go through the edges and add all nodes that have light to light_sources + */ + + // Four edges + for(s16 i=0; i<4; i++) + // Edge length + for(s16 j=lighting_min_d; + j<=lighting_max_d; + j++) + { + s16 x; + s16 z; + // +-X + if(i == 0 || i == 1) + { + x = (i==0) ? lighting_min_d : lighting_max_d; + if(i == 0) + z = lighting_min_d; + else + z = lighting_max_d; + } + // +-Z + else + { + z = (i==0) ? lighting_min_d : lighting_max_d; + if(i == 0) + x = lighting_min_d; + else + x = lighting_max_d; + } + + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + { + v3s16 em = data->vmanip.m_area.getExtent(); + s16 y_start = y_nodes_max; + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y)); + for(s16 y=y_start; y>=y_nodes_min; y--) + { + MapNode *n = &data->vmanip.m_data[i]; + if(n->getLight(LIGHTBANK_DAY) != 0) + { + light_sources.insert(v3s16(p2d.X, y, p2d.Y), true); + } + //NOTE: This is broken, at least the index has to + // be incremented + } + } + } +#endif + +#if 1 + /* + Go through the edges and apply sunlight to them, not caring + about neighbors + */ + + // Four edges + for(s16 i=0; i<4; i++) + // Edge length + for(s16 j=lighting_min_d; + j<=lighting_max_d; + j++) + { + s16 x; + s16 z; + // +-X + if(i == 0 || i == 1) + { + x = (i==0) ? lighting_min_d : lighting_max_d; + if(i == 0) + z = lighting_min_d; + else + z = lighting_max_d; + } + // +-Z + else + { + z = (i==0) ? lighting_min_d : lighting_max_d; + if(i == 0) + x = lighting_min_d; + else + x = lighting_max_d; + } + + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + // Loop from top to down + { + u8 light = LIGHT_SUN; + v3s16 em = data->vmanip.m_area.getExtent(); + s16 y_start = y_nodes_max; + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y)); + for(s16 y=y_start; y>=y_nodes_min; y--) + { + MapNode *n = &data->vmanip.m_data[i]; + if(light_propagates_content(n->d) == false) + { + light = 0; + } + else if(light != LIGHT_SUN + || sunlight_propagates_content(n->d) == false) + { + if(light > 0) + light--; + } + + n->setLight(LIGHTBANK_DAY, light); + n->setLight(LIGHTBANK_NIGHT, 0); + + if(light != 0) + { + // Insert light source + light_sources.insert(v3s16(p2d.X, y, p2d.Y), true); + } + + // Increment index by y + data->vmanip.m_area.add_y(em, i, -1); + } + } + } +#endif + + /*for(s16 x=0; xsectorpos_base_size*MAP_BLOCKSIZE; x++) + for(s16 z=0; zsectorpos_base_size*MAP_BLOCKSIZE; z++)*/ + /*for(s16 x=0-data->max_spread_amount+1; + xsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount-1; + x++) + for(s16 z=0-data->max_spread_amount+1; + zsectorpos_base_size*MAP_BLOCKSIZE+data->max_spread_amount-1; + z++)*/ +#if 1 + /* + This has to be 1 smaller than the actual area, because + neighboring nodes are checked. + */ + for(s16 x=lighting_min_d+1; + x<=lighting_max_d-1; + x++) + for(s16 z=lighting_min_d+1; + z<=lighting_max_d-1; + z++) + { + // Node position in 2d + v2s16 p2d = data->sectorpos_base*MAP_BLOCKSIZE + v2s16(x,z); + + /* + Apply initial sunlight + */ + { + u8 light = LIGHT_SUN; + bool add_to_sources = false; + v3s16 em = data->vmanip.m_area.getExtent(); + s16 y_start = y_nodes_max; + u32 i = data->vmanip.m_area.index(v3s16(p2d.X, y_start, p2d.Y)); + for(s16 y=y_start; y>=y_nodes_min; y--) + { + MapNode *n = &data->vmanip.m_data[i]; + + if(light_propagates_content(n->d) == false) + { + light = 0; + } + else if(light != LIGHT_SUN + || sunlight_propagates_content(n->d) == false) + { + if(light > 0) + light--; + } + + // This doesn't take much time + if(add_to_sources == false) + { + /* + Check sides. If side is not air or water, start + adding to light_sources. + */ + v3s16 dirs4[4] = { + v3s16(0,0,1), // back + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(-1,0,0), // left + }; + for(u32 di=0; di<4; di++) + { + v3s16 dirp = dirs4[di]; + u32 i2 = i; + data->vmanip.m_area.add_p(em, i2, dirp); + MapNode *n2 = &data->vmanip.m_data[i2]; + if( + n2->d != CONTENT_AIR + && n2->d != CONTENT_WATERSOURCE + && n2->d != CONTENT_WATER + ){ + add_to_sources = true; + break; + } + } + } + + n->setLight(LIGHTBANK_DAY, light); + n->setLight(LIGHTBANK_NIGHT, 0); + + // This doesn't take much time + if(light != 0 && add_to_sources) + { + // Insert light source + light_sources.insert(v3s16(p2d.X, y, p2d.Y), true); + } + + // Increment index by y + data->vmanip.m_area.add_y(em, i, -1); + } + } + } +#endif + + }//timer1 + + // Spread light around + { + TimeTaker timer("makeChunk() spreadLight"); + data->vmanip.spreadLight(LIGHTBANK_DAY, light_sources); + } + + /* + Generation ended + */ + + timer_generate.stop(); +} + +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### +//################################################################### + +void ServerMap::initChunkMake(ChunkMakeData &data, v2s16 chunkpos) +{ + if(m_chunksize == 0) + { + data.no_op = true; + return; + } + + data.no_op = false; + + // The distance how far into the neighbors the generator is allowed to go. + s16 max_spread_amount_sectors = 2; + assert(max_spread_amount_sectors <= m_chunksize); + s16 max_spread_amount = max_spread_amount_sectors * MAP_BLOCKSIZE; + + s16 y_blocks_min = -4; + s16 y_blocks_max = 3; + + v2s16 sectorpos_base = chunk_to_sector(chunkpos); + s16 sectorpos_base_size = m_chunksize; + + v2s16 sectorpos_bigbase = + sectorpos_base - v2s16(1,1) * max_spread_amount_sectors; + s16 sectorpos_bigbase_size = + sectorpos_base_size + 2 * max_spread_amount_sectors; + + data.seed = m_seed; + data.chunkpos = chunkpos; + data.y_blocks_min = y_blocks_min; + data.y_blocks_max = y_blocks_max; + data.sectorpos_base = sectorpos_base; + data.sectorpos_base_size = sectorpos_base_size; + data.sectorpos_bigbase = sectorpos_bigbase; + data.sectorpos_bigbase_size = sectorpos_bigbase_size; + data.max_spread_amount = max_spread_amount; + + /* + Create the whole area of this and the neighboring chunks + */ + { + TimeTaker timer("initChunkMake() create area"); + + for(s16 x=0; xsetLightingExpired(true); + // Lighting will be calculated + block->setLightingExpired(false); + + /* + Block gets sunlight if this is true. + + This should be set to true when the top side of a block + is completely exposed to the sky. + + Actually this doesn't matter now because the + initial lighting is done here. + */ + block->setIsUnderground(y != y_blocks_max); + } + } + } + + /* + Now we have a big empty area. + + Make a ManualMapVoxelManipulator that contains this and the + neighboring chunks + */ + + v3s16 bigarea_blocks_min( + sectorpos_bigbase.X, + y_blocks_min, + sectorpos_bigbase.Y + ); + v3s16 bigarea_blocks_max( + sectorpos_bigbase.X + sectorpos_bigbase_size - 1, + y_blocks_max, + sectorpos_bigbase.Y + sectorpos_bigbase_size - 1 + ); + + data.vmanip.setMap(this); + // Add the area + { + TimeTaker timer("initChunkMake() initialEmerge"); + data.vmanip.initialEmerge(bigarea_blocks_min, bigarea_blocks_max); + } + +} + +MapChunk* ServerMap::finishChunkMake(ChunkMakeData &data, + core::map &changed_blocks) +{ + if(data.no_op) + return NULL; + + /* + Blit generated stuff to map + */ + { + // 70ms @cs=8 + //TimeTaker timer("generateChunkRaw() blitBackAll"); + data.vmanip.blitBackAll(&changed_blocks); + } + + /* + Update day/night difference cache of the MapBlocks + */ + { + for(core::map::Iterator i = changed_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } + } + + /* + Copy transforming liquid information + */ + while(data.transforming_liquid.size() > 0) + { + v3s16 p = data.transforming_liquid.pop_front(); + m_transforming_liquid.push_back(p); + } + + /* + Add random objects to blocks + */ + { + for(s16 x=0; xsetIsVolatile(true); + if(chunk->getGenLevel() > GENERATED_PARTLY) + chunk->setGenLevel(GENERATED_PARTLY); + } + + /* + Set central chunk non-volatile + */ + MapChunk *chunk = getChunk(data.chunkpos); + assert(chunk); + // Set non-volatile + //chunk->setIsVolatile(false); + chunk->setGenLevel(GENERATED_FULLY); + + /* + Save changed parts of map + */ + save(true); + + return chunk; +} + +#if 0 +// NOTE: Deprecated +MapChunk* ServerMap::generateChunkRaw(v2s16 chunkpos, + core::map &changed_blocks, + bool force) +{ + DSTACK(__FUNCTION_NAME); + + /* + Don't generate if already fully generated + */ + if(force == false) + { + MapChunk *chunk = getChunk(chunkpos); + if(chunk != NULL && chunk->getGenLevel() == GENERATED_FULLY) + { + dstream<<"generateChunkRaw(): Chunk " + <<"("< &changed_blocks) +{ + dstream<<"generateChunk(): Generating chunk " + <<"("<getGenLevel() == GENERATED_FULLY) + continue; + generateChunkRaw(chunkpos0, changed_blocks); + } + + assert(chunkNonVolatile(chunkpos1)); + + MapChunk *chunk = getChunk(chunkpos1); + return chunk; +} +#endif + +ServerMapSector * ServerMap::createSector(v2s16 p2d) +{ + DSTACK("%s: p2d=(%d,%d)", + __FUNCTION_NAME, + p2d.X, p2d.Y); + + /* + Check if it exists already in memory + */ + ServerMapSector *sector = (ServerMapSector*)getSectorNoGenerateNoEx(p2d); + if(sector != NULL) + return sector; + + /* + Try to load it from disk (with blocks) + */ + if(loadSectorFull(p2d) == true) + { + ServerMapSector *sector = (ServerMapSector*)getSectorNoGenerateNoEx(p2d); + if(sector == NULL) + { + dstream<<"ServerMap::createSector(): loadSectorFull didn't make a sector"< MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p2d.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p2d.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + throw InvalidPositionException("createSector(): pos. over limit"); + + /* + Generate blank sector + */ + + sector = new ServerMapSector(this, p2d); + + // Sector position on map in nodes + v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; + + /* + Insert to container + */ + m_sectors.insert(p2d, sector); + + return sector; +} + +#if 0 +MapSector * ServerMap::emergeSector(v2s16 p2d, + core::map &changed_blocks) +{ + DSTACK("%s: p2d=(%d,%d)", + __FUNCTION_NAME, + p2d.X, p2d.Y); + + /* + Check chunk status + */ + v2s16 chunkpos = sector_to_chunk(p2d); + /*bool chunk_nonvolatile = false; + MapChunk *chunk = getChunk(chunkpos); + if(chunk && chunk->getIsVolatile() == false) + chunk_nonvolatile = true;*/ + bool chunk_nonvolatile = chunkNonVolatile(chunkpos); + + /* + If chunk is not fully generated, generate chunk + */ + if(chunk_nonvolatile == false) + { + // Generate chunk and neighbors + generateChunk(chunkpos, changed_blocks); + } + + /* + Return sector if it exists now + */ + MapSector *sector = getSectorNoGenerateNoEx(p2d); + if(sector != NULL) + return sector; + + /* + Try to load it from disk + */ + if(loadSectorFull(p2d) == true) + { + MapSector *sector = getSectorNoGenerateNoEx(p2d); + if(sector == NULL) + { + dstream<<"ServerMap::emergeSector(): loadSectorFull didn't make a sector"< &changed_blocks, + core::map &lighting_invalidated_blocks +) +{ + DSTACK("%s: p=(%d,%d,%d)", + __FUNCTION_NAME, + p.X, p.Y, p.Z); + + // If chunks are disabled + /*if(m_chunksize == 0) + { + dstream<<"ServerMap::generateBlock(): Chunks disabled -> " + <<"not generating."<createBlankBlockNoInsert(block_y); + } + else + { + // Remove the block so that nobody can get a half-generated one. + sector->removeBlock(block); + // Allocate the block to contain the generated data + block->unDummify(); + } + +#if 0 + /* + Generate a completely empty block + */ + for(s16 z0=0; z0setNode(v3s16(x0,y0,z0), n); + } + } +#else + /* + Generate a proper block + */ + + u8 water_material = CONTENT_WATERSOURCE; + + s32 lowest_ground_y = 32767; + s32 highest_ground_y = -32768; + + for(s16 z0=0; z0getPos()] = block; + }*/ + + // DEBUG: Always update lighting + //lighting_invalidated_blocks[block->getPos()] = block; + + /* + Add some minerals + */ + + if(some_part_underground) + { + s16 underground_level = (lowest_ground_y/MAP_BLOCKSIZE - block_y)+1; + + /* + Add meseblocks + */ + for(s16 i=0; igetNode(cp+g_27dirs[i]).d == CONTENT_STONE) + if(myrand()%8 == 0) + block->setNode(cp+g_27dirs[i], n); + } + } + } + + /* + Add coal + */ + u16 coal_amount = 30; + u16 coal_rareness = 60 / coal_amount; + if(coal_rareness == 0) + coal_rareness = 1; + if(myrand()%coal_rareness == 0) + { + u16 a = myrand() % 16; + u16 amount = coal_amount * a*a*a / 1000; + for(s16 i=0; igetNode(cp+g_27dirs[i]).d == CONTENT_STONE) + if(myrand()%8 == 0) + block->setNode(cp+g_27dirs[i], n); + } + } + } + + /* + Add iron + */ + //TODO: change to iron_amount or whatever + u16 iron_amount = 15; + u16 iron_rareness = 60 / iron_amount; + if(iron_rareness == 0) + iron_rareness = 1; + if(myrand()%iron_rareness == 0) + { + u16 a = myrand() % 16; + u16 amount = iron_amount * a*a*a / 1000; + for(s16 i=0; igetNode(cp+g_27dirs[i]).d == CONTENT_STONE) + if(myrand()%8 == 0) + block->setNode(cp+g_27dirs[i], n); + } + } + } + } + + /* + Create a few rats in empty blocks underground + */ + if(completely_underground) + { + //for(u16 i=0; i<2; i++) + { + v3s16 cp( + (myrand()%(MAP_BLOCKSIZE-2))+1, + (myrand()%(MAP_BLOCKSIZE-2))+1, + (myrand()%(MAP_BLOCKSIZE-2))+1 + ); + + // Check that the place is empty + //if(!is_ground_content(block->getNode(cp).d)) + if(1) + { + RatObject *obj = new RatObject(NULL, -1, intToFloat(cp, BS)); + block->addObject(obj); + } + } + } + +#endif // end of proper block generation + + /* + Add block to sector. + */ + sector->insertBlock(block); + + // Lighting is invalid after generation. + block->setLightingExpired(true); + +#if 0 + /* + Debug information + */ + dstream + <<"lighting_invalidated_blocks.size()" + <<", has_caves" + <<", completely_ug" + <<", some_part_ug" + <<" "< MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + throw InvalidPositionException("createBlock(): pos. over limit"); + + v2s16 p2d(p.X, p.Z); + s16 block_y = p.Y; + /* + This will create or load a sector if not found in memory. + If block exists on disk, it will be loaded. + + NOTE: On old save formats, this will be slow, as it generates + lighting on blocks for them. + */ + ServerMapSector *sector; + try{ + sector = (ServerMapSector*)createSector(p2d); + assert(sector->getId() == MAPSECTOR_SERVER); + } + catch(InvalidPositionException &e) + { + dstream<<"createBlock: createSector() failed"<getBlockNoCreateNoEx(block_y); + if(block) + return block; + // Create blank + block = sector->createBlankBlock(block_y); + return block; +} + +MapBlock * ServerMap::emergeBlock( + v3s16 p, + bool only_from_disk, + core::map &changed_blocks, + core::map &lighting_invalidated_blocks +) +{ + DSTACK("%s: p=(%d,%d,%d), only_from_disk=%d", + __FUNCTION_NAME, + p.X, p.Y, p.Z, only_from_disk); + + /* + Do not generate over-limit + */ + if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + throw InvalidPositionException("emergeBlock(): pos. over limit"); + + v2s16 p2d(p.X, p.Z); + s16 block_y = p.Y; + /* + This will create or load a sector if not found in memory. + If block exists on disk, it will be loaded. + */ + ServerMapSector *sector; + try{ + sector = (ServerMapSector*)emergeSector(p2d, changed_blocks); + assert(sector->getId() == MAPSECTOR_SERVER); + } + catch(InvalidPositionException &e) + { + dstream<<"emergeBlock: emergeSector() failed: " + <getBlockNoCreateNoEx(block_y); + + if(block == NULL) + { + does_not_exist = true; + } + else if(block->isDummy() == true) + { + does_not_exist = true; + } + else if(block->getLightingExpired()) + { + lighting_expired = true; + } + else + { + // Valid block + //dstream<<"emergeBlock(): Returning already valid block"<insertBlock(block); + } + // Done. + return block; + } + + //dstream<<"Not found on disk, generating."< making one"< light_sources; + bool black_air_left = false; + bool bottom_invalid = + block->propagateSunlight(light_sources, true, + &black_air_left, true); + + // If sunlight didn't reach everywhere and part of block is + // above ground, lighting has to be properly updated + //if(black_air_left && some_part_underground) + if(black_air_left) + { + lighting_invalidated_blocks[block->getPos()] = block; + } + + if(bottom_invalid) + { + lighting_invalidated_blocks[block->getPos()] = block; + } + } + + return block; +} + +s16 ServerMap::findGroundLevel(v2s16 p2d) +{ + /* + Uh, just do something random... + */ + // Find existing map from top to down + s16 max=63; + s16 min=-64; + v3s16 p(p2d.X, max, p2d.Y); + for(; p.Y>min; p.Y--) + { + MapNode n = getNodeNoEx(p); + if(n.d != CONTENT_IGNORE) + break; + } + if(p.Y == min) + goto plan_b; + // If this node is not air, go to plan b + if(getNodeNoEx(p).d != CONTENT_AIR) + goto plan_b; + // Search existing walkable and return it + for(; p.Y>min; p.Y--) + { + MapNode n = getNodeNoEx(p); + if(content_walkable(n.d) && n.d != CONTENT_IGNORE) + return p.Y; + } + // Move to plan b +plan_b: + /* + Plan B: Get from map generator perlin noise function + */ + // This won't work if proper generation is disabled + if(m_chunksize == 0) + return WATER_LEVEL+2; + double level = base_rock_level_2d(m_seed, p2d) + AVERAGE_MUD_AMOUNT; + return (s16)level; +} + +void ServerMap::createDir(std::string path) +{ + if(fs::CreateDir(path) == false) + { + m_dout<::Iterator i = m_sectors.getIterator(); + for(; i.atEnd() == false; i++) + { + ServerMapSector *sector = (ServerMapSector*)i.getNode()->getValue(); + assert(sector->getId() == MAPSECTOR_SERVER); + + if(sector->differs_from_disk || only_changed == false) + { + saveSectorMeta(sector); + sector_meta_count++; + } + core::list blocks; + sector->getBlocks(blocks); + core::list::Iterator j; + for(j=blocks.begin(); j!=blocks.end(); j++) + { + MapBlock *block = *j; + if(block->getChangedFlag() || only_changed == false) + { + saveBlock(block); + block_count++; + + /*dstream<<"ServerMap: Written block (" + <getPos().X<<"," + <getPos().Y<<"," + <getPos().Z<<")" + < list = fs::GetDirListing(m_savedir+"/sectors/"); + + dstream<::iterator i; + for(i=list.begin(); i!=list.end(); i++) + { + if(counter > printed_counter + 10) + { + dstream<dir == false) + continue; + try{ + sector = loadSectorMeta(i->name); + } + catch(InvalidFilenameException &e) + { + // This catches unknown crap in directory + } + + std::vector list2 = fs::GetDirListing + (m_savedir+"/sectors/"+i->name); + std::vector::iterator i2; + for(i2=list2.begin(); i2!=list2.end(); i2++) + { + // We want files + if(i2->dir) + continue; + try{ + loadBlock(i->name, i2->name, sector); + } + catch(InvalidFilenameException &e) + { + // This catches unknown crap in directory + } + } + } + dstream<::Iterator + i = m_chunks.getIterator(); + i.atEnd()==false; i++) + { + v2s16 p = i.getNode()->getKey(); + MapChunk *chunk = i.getNode()->getValue(); + // Write position + writeV2S16(buf, p); + os.write((char*)buf, 4); + // Write chunk data + chunk->serialize(os, version); + } + + setChunksNonModified(); +} + +void ServerMap::loadChunkMeta() +{ + DSTACK(__FUNCTION_NAME); + + dstream<<"INFO: ServerMap::loadChunkMeta(): Loading chunk metadata" + <deSerialize(is, version); + m_chunks.insert(p, chunk); + } +} + +void ServerMap::saveSectorMeta(ServerMapSector *sector) +{ + DSTACK(__FUNCTION_NAME); + // Format used for writing + u8 version = SER_FMT_VER_HIGHEST; + // Get destination + v2s16 pos = sector->getPos(); + createDir(m_savedir); + createDir(m_savedir+"/sectors"); + std::string dir = getSectorDir(pos); + createDir(dir); + + std::string fullpath = dir + "/meta"; + std::ofstream o(fullpath.c_str(), std::ios_base::binary); + if(o.good() == false) + throw FileNotGoodException("Cannot open sector metafile"); + + sector->serialize(o, version); + + sector->differs_from_disk = false; +} + +MapSector* ServerMap::loadSectorMeta(std::string dirname) +{ + DSTACK(__FUNCTION_NAME); + // Get destination + v2s16 p2d = getSectorPos(dirname); + std::string dir = m_savedir + "/sectors/" + dirname; + + ServerMapSector *sector = NULL; + + std::string fullpath = dir + "/meta"; + std::ifstream is(fullpath.c_str(), std::ios_base::binary); + if(is.good() == false) + { + // If the directory exists anyway, it probably is in some old + // format. Just go ahead and create the sector. + if(fs::PathExists(dir)) + { + dstream<<"ServerMap::loadSectorMeta(): Sector metafile " + <differs_from_disk = false; + + return sector; +} + +bool ServerMap::loadSectorFull(v2s16 p2d) +{ + DSTACK(__FUNCTION_NAME); + std::string sectorsubdir = getSectorSubDir(p2d); + + MapSector *sector = NULL; + + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + + try{ + sector = loadSectorMeta(sectorsubdir); + } + catch(InvalidFilenameException &e) + { + return false; + } + catch(FileNotGoodException &e) + { + return false; + } + catch(std::exception &e) + { + return false; + } + + /* + Load blocks + */ + std::vector list2 = fs::GetDirListing + (m_savedir+"/sectors/"+sectorsubdir); + std::vector::iterator i2; + for(i2=list2.begin(); i2!=list2.end(); i2++) + { + // We want files + if(i2->dir) + continue; + try{ + loadBlock(sectorsubdir, i2->name, sector); + } + catch(InvalidFilenameException &e) + { + // This catches unknown crap in directory + } + } + return true; +} + +void ServerMap::saveBlock(MapBlock *block) +{ + DSTACK(__FUNCTION_NAME); + /* + Dummy blocks are not written + */ + if(block->isDummy()) + { + /*v3s16 p = block->getPos(); + dstream<<"ServerMap::saveBlock(): WARNING: Not writing dummy block " + <<"("<getPos(); + v2s16 p2d(p3d.X, p3d.Z); + createDir(m_savedir); + createDir(m_savedir+"/sectors"); + std::string dir = getSectorDir(p2d); + createDir(dir); + + // Block file is map/sectors/xxxxxxxx/xxxx + char cc[5]; + snprintf(cc, 5, "%.4x", (unsigned int)p3d.Y&0xffff); + std::string fullpath = dir + "/" + cc; + std::ofstream o(fullpath.c_str(), std::ios_base::binary); + if(o.good() == false) + throw FileNotGoodException("Cannot open block data"); + + /* + [0] u8 serialization version + [1] data + */ + o.write((char*)&version, 1); + + block->serialize(o, version); + + /* + Versions up from 9 have block objects. + */ + if(version >= 9) + { + block->serializeObjects(o, version); + } + + /* + Versions up from 15 have static objects. + */ + if(version >= 15) + { + block->m_static_objects.serialize(o); + } + + // We just wrote it to the disk + block->resetChangedFlag(); +} + +void ServerMap::loadBlock(std::string sectordir, std::string blockfile, MapSector *sector) +{ + DSTACK(__FUNCTION_NAME); + + // Block file is map/sectors/xxxxxxxx/xxxx + std::string fullpath = m_savedir+"/sectors/"+sectordir+"/"+blockfile; + try{ + + std::ifstream is(fullpath.c_str(), std::ios_base::binary); + if(is.good() == false) + throw FileNotGoodException("Cannot open block file"); + + v3s16 p3d = getBlockPos(sectordir, blockfile); + v2s16 p2d(p3d.X, p3d.Z); + + assert(sector->getPos() == p2d); + + u8 version = SER_FMT_VER_INVALID; + is.read((char*)&version, 1); + + if(is.fail()) + throw SerializationError("ServerMap::loadBlock(): Failed" + " to read MapBlock version"); + + /*u32 block_size = MapBlock::serializedLength(version); + SharedBuffer data(block_size); + is.read((char*)*data, block_size);*/ + + // This will always return a sector because we're the server + //MapSector *sector = emergeSector(p2d); + + MapBlock *block = NULL; + bool created_new = false; + try{ + block = sector->getBlockNoCreate(p3d.Y); + } + catch(InvalidPositionException &e) + { + block = sector->createBlankBlockNoInsert(p3d.Y); + created_new = true; + } + + // deserialize block data + block->deSerialize(is, version); + + /* + Versions up from 9 have block objects. + */ + if(version >= 9) + { + block->updateObjects(is, version, NULL, 0); + } + + /* + Versions up from 15 have static objects. + */ + if(version >= 15) + { + block->m_static_objects.deSerialize(is); + } + + if(created_new) + sector->insertBlock(block); + + /* + Convert old formats to new and save + */ + + // Save old format blocks in new format + if(version < SER_FMT_VER_HIGHEST) + { + saveBlock(block); + } + + // We just loaded it from the disk, so it's up-to-date. + block->resetChangedFlag(); + + } + catch(SerializationError &e) + { + dstream<<"WARNING: Invalid block data on disk " + "(SerializationError). Ignoring. " + "A new one will be generated." + <(-BS*1000000,-BS*1000000,-BS*1000000, + BS*1000000,BS*1000000,BS*1000000); +} + +ClientMap::~ClientMap() +{ + /*JMutexAutoLock lock(mesh_mutex); + + if(mesh != NULL) + { + mesh->drop(); + mesh = NULL; + }*/ +} + +MapSector * ClientMap::emergeSector(v2s16 p2d) +{ + DSTACK(__FUNCTION_NAME); + // Check that it doesn't exist already + try{ + return getSectorNoGenerate(p2d); + } + catch(InvalidPositionException &e) + { + } + + // Create a sector + ClientMapSector *sector = new ClientMapSector(this, p2d); + + { + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + m_sectors.insert(p2d, sector); + } + + return sector; +} + +void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is) +{ + DSTACK(__FUNCTION_NAME); + ClientMapSector *sector = NULL; + + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + + core::map::Node *n = m_sectors.find(p2d); + + if(n != NULL) + { + sector = (ClientMapSector*)n->getValue(); + assert(sector->getId() == MAPSECTOR_CLIENT); + } + else + { + sector = new ClientMapSector(this, p2d); + { + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + m_sectors.insert(p2d, sector); + } + } + + sector->deSerialize(is); +} + +void ClientMap::OnRegisterSceneNode() +{ + if(IsVisible) + { + SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); + SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT); + } + + ISceneNode::OnRegisterSceneNode(); +} + +void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) +{ + //m_dout<getDayNightRatio(); + + m_camera_mutex.Lock(); + v3f camera_position = m_camera_position; + v3f camera_direction = m_camera_direction; + m_camera_mutex.Unlock(); + + /* + Get all blocks and draw all visible ones + */ + + v3s16 cam_pos_nodes( + camera_position.X / BS, + camera_position.Y / BS, + camera_position.Z / BS); + + v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1); + + v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d; + v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d; + + // Take a fair amount as we will be dropping more out later + v3s16 p_blocks_min = getNodeBlockPos(p_nodes_min) - v3s16(1,1,1); + v3s16 p_blocks_max = getNodeBlockPos(p_nodes_max) + v3s16(1,1,1); + + u32 vertex_count = 0; + + // For limiting number of mesh updates per frame + u32 mesh_update_count = 0; + + u32 blocks_would_have_drawn = 0; + u32 blocks_drawn = 0; + + //NOTE: The sectors map should be locked but we're not doing it + // because it'd cause too much delays + + int timecheck_counter = 0; + core::map::Iterator si; + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + { + timecheck_counter++; + if(timecheck_counter > 50) + { + timecheck_counter = 0; + int time2 = time(0); + if(time2 > time1 + 4) + { + dstream<<"ClientMap::renderMap(): " + "Rendering takes ages, returning." + <getValue(); + v2s16 sp = sector->getPos(); + + if(m_control.range_all == false) + { + if(sp.X < p_blocks_min.X + || sp.X > p_blocks_max.X + || sp.Y < p_blocks_min.Z + || sp.Y > p_blocks_max.Z) + continue; + } + + core::list< MapBlock * > sectorblocks; + sector->getBlocks(sectorblocks); + + /* + Draw blocks + */ + + core::list< MapBlock * >::Iterator i; + for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++) + { + MapBlock *block = *i; + + /* + Compare block position to camera position, skip + if not seen on display + */ + + float range = 100000 * BS; + if(m_control.range_all == false) + range = m_control.wanted_range * BS; + + float d = 0.0; + if(isBlockInSight(block->getPos(), camera_position, + camera_direction, range, &d) == false) + { + continue; + } + + // This is ugly (spherical distance limit?) + /*if(m_control.range_all == false && + d - 0.5*BS*MAP_BLOCKSIZE > range) + continue;*/ + +#if 1 + /* + Update expired mesh (used for day/night change) + + It doesn't work exactly like it should now with the + tasked mesh update but whatever. + */ + + bool mesh_expired = false; + + { + JMutexAutoLock lock(block->mesh_mutex); + + mesh_expired = block->getMeshExpired(); + + // Mesh has not been expired and there is no mesh: + // block has no content + if(block->mesh == NULL && mesh_expired == false) + continue; + } + + f32 faraway = BS*50; + //f32 faraway = m_control.wanted_range * BS; + + /* + This has to be done with the mesh_mutex unlocked + */ + // Pretty random but this should work somewhat nicely + if(mesh_expired && ( + (mesh_update_count < 3 + && (d < faraway || mesh_update_count < 2) + ) + || + (m_control.range_all && mesh_update_count < 20) + ) + ) + /*if(mesh_expired && mesh_update_count < 6 + && (d < faraway || mesh_update_count < 3))*/ + { + mesh_update_count++; + + // Mesh has been expired: generate new mesh + //block->updateMesh(daynight_ratio); + m_client->addUpdateMeshTask(block->getPos()); + + mesh_expired = false; + } + +#endif + /* + Draw the faces of the block + */ + { + JMutexAutoLock lock(block->mesh_mutex); + + scene::SMesh *mesh = block->mesh; + + if(mesh == NULL) + continue; + + blocks_would_have_drawn++; + if(blocks_drawn >= m_control.wanted_max_blocks + && m_control.range_all == false + && d > m_control.wanted_min_range * BS) + continue; + blocks_drawn++; + + u32 c = mesh->getMeshBufferCount(); + + for(u32 i=0; igetMeshBuffer(i); + const video::SMaterial& material = buf->getMaterial(); + video::IMaterialRenderer* rnd = + driver->getMaterialRenderer(material.MaterialType); + bool transparent = (rnd && rnd->isTransparent()); + // Render transparent on transparent pass and likewise. + if(transparent == is_transparent_pass) + { + /* + This *shouldn't* hurt too much because Irrlicht + doesn't change opengl textures if the old + material is set again. + */ + driver->setMaterial(buf->getMaterial()); + driver->drawMeshBuffer(buf); + vertex_count += buf->getVertexCount(); + } + } + } + } // foreach sectorblocks + } + + m_control.blocks_drawn = blocks_drawn; + m_control.blocks_would_have_drawn = blocks_would_have_drawn; + + /*dstream<<"renderMap(): is_transparent_pass="< *affected_blocks) +{ + bool changed = false; + /* + Add it to all blocks touching it + */ + v3s16 dirs[7] = { + v3s16(0,0,0), // this + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + // Relative position of requested node + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + if(blockref->setTempMod(relpos, mod)) + { + changed = true; + } + } + if(changed && affected_blocks!=NULL) + { + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + affected_blocks->insert(blockpos, blockref); + } + } + return changed; +} + +bool ClientMap::clearTempMod(v3s16 p, + core::map *affected_blocks) +{ + bool changed = false; + v3s16 dirs[7] = { + v3s16(0,0,0), // this + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + // Relative position of requested node + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + if(blockref->clearTempMod(relpos)) + { + changed = true; + } + } + if(changed && affected_blocks!=NULL) + { + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + affected_blocks->insert(blockpos, blockref); + } + } + return changed; +} + +void ClientMap::expireMeshes(bool only_daynight_diffed) +{ + TimeTaker timer("expireMeshes()"); + + core::map::Iterator si; + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + + core::list< MapBlock * > sectorblocks; + sector->getBlocks(sectorblocks); + + core::list< MapBlock * >::Iterator i; + for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++) + { + MapBlock *block = *i; + + if(only_daynight_diffed && dayNightDiffed(block->getPos()) == false) + { + continue; + } + + { + JMutexAutoLock lock(block->mesh_mutex); + if(block->mesh != NULL) + { + /*block->mesh->drop(); + block->mesh = NULL;*/ + block->setMeshExpired(true); + } + } + } + } +} + +void ClientMap::updateMeshes(v3s16 blockpos, u32 daynight_ratio) +{ + assert(mapType() == MAPTYPE_CLIENT); + + try{ + v3s16 p = blockpos + v3s16(0,0,0); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} + // Leading edge + try{ + v3s16 p = blockpos + v3s16(-1,0,0); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,-1,0); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,0,-1); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} +} + +#if 0 +/* + Update mesh of block in which the node is, and if the node is at the + leading edge, update the appropriate leading blocks too. +*/ +void ClientMap::updateNodeMeshes(v3s16 nodepos, u32 daynight_ratio) +{ + v3s16 dirs[4] = { + v3s16(0,0,0), + v3s16(-1,0,0), + v3s16(0,-1,0), + v3s16(0,0,-1), + }; + v3s16 blockposes[4]; + for(u32 i=0; i<4; i++) + { + v3s16 np = nodepos + dirs[i]; + blockposes[i] = getNodeBlockPos(np); + // Don't update mesh of block if it has been done already + bool already_updated = false; + for(u32 j=0; jupdateMesh(daynight_ratio); + } +} +#endif + +void ClientMap::PrintInfo(std::ostream &out) +{ + out<<"ClientMap: "; +} + +#endif // !SERVER + +/* + MapVoxelManipulator +*/ + +MapVoxelManipulator::MapVoxelManipulator(Map *map) +{ + m_map = map; +} + +MapVoxelManipulator::~MapVoxelManipulator() +{ + /*dstream<<"MapVoxelManipulator: blocks: "<::Node *n; + n = m_loaded_blocks.find(p); + if(n != NULL) + continue; + + bool block_data_inexistent = false; + try + { + TimeTaker timer1("emerge load", &emerge_load_time); + + /*dstream<<"Loading block (caller_id="<getBlockNoCreate(p); + if(block->isDummy()) + block_data_inexistent = true; + else + block->copyTo(*this); + } + catch(InvalidPositionException &e) + { + block_data_inexistent = true; + } + + if(block_data_inexistent) + { + VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + // Fill with VOXELFLAG_INEXISTENT + for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) + for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) + { + s32 i = m_area.index(a.MinEdge.X,y,z); + memset(&m_flags[i], VOXELFLAG_INEXISTENT, MAP_BLOCKSIZE); + } + } + + m_loaded_blocks.insert(p, !block_data_inexistent); + } + + //dstream<<"emerge done"< & modified_blocks) +{ + if(m_area.getExtent() == v3s16(0,0,0)) + return; + + //TimeTaker timer1("blitBack"); + + /*dstream<<"blitBack(): m_loaded_blocks.size()=" + <getBlockNoCreate(blockpos); + blockpos_last = blockpos; + block_checked_in_modified = false; + } + + // Calculate relative position in block + v3s16 relpos = p - blockpos * MAP_BLOCKSIZE; + + // Don't continue if nothing has changed here + if(block->getNode(relpos) == n) + continue; + + //m_map->setNode(m_area.MinEdge + p, n); + block->setNode(relpos, n); + + /* + Make sure block is in modified_blocks + */ + if(block_checked_in_modified == false) + { + modified_blocks[blockpos] = block; + block_checked_in_modified = true; + } + } + catch(InvalidPositionException &e) + { + } + } +} + +ManualMapVoxelManipulator::ManualMapVoxelManipulator(Map *map): + MapVoxelManipulator(map), + m_create_area(false) +{ +} + +ManualMapVoxelManipulator::~ManualMapVoxelManipulator() +{ +} + +void ManualMapVoxelManipulator::emerge(VoxelArea a, s32 caller_id) +{ + // Just create the area so that it can be pointed to + VoxelManipulator::emerge(a, caller_id); +} + +void ManualMapVoxelManipulator::initialEmerge( + v3s16 blockpos_min, v3s16 blockpos_max) +{ + TimeTaker timer1("initialEmerge", &emerge_time); + + // Units of these are MapBlocks + v3s16 p_min = blockpos_min; + v3s16 p_max = blockpos_max; + + VoxelArea block_area_nodes + (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + + u32 size_MB = block_area_nodes.getVolume()*4/1000000; + if(size_MB >= 1) + { + dstream<<"initialEmerge: area: "; + block_area_nodes.print(dstream); + dstream<<" ("<::Node *n; + n = m_loaded_blocks.find(p); + if(n != NULL) + continue; + + bool block_data_inexistent = false; + try + { + TimeTaker timer1("emerge load", &emerge_load_time); + + MapBlock *block = m_map->getBlockNoCreate(p); + if(block->isDummy()) + block_data_inexistent = true; + else + block->copyTo(*this); + } + catch(InvalidPositionException &e) + { + block_data_inexistent = true; + } + + if(block_data_inexistent) + { + /* + Mark area inexistent + */ + VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + // Fill with VOXELFLAG_INEXISTENT + for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) + for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) + { + s32 i = m_area.index(a.MinEdge.X,y,z); + memset(&m_flags[i], VOXELFLAG_INEXISTENT, MAP_BLOCKSIZE); + } + } + + m_loaded_blocks.insert(p, !block_data_inexistent); + } +} + +void ManualMapVoxelManipulator::blitBackAll( + core::map * modified_blocks) +{ + if(m_area.getExtent() == v3s16(0,0,0)) + return; + + /* + Copy data of all blocks + */ + for(core::map::Iterator + i = m_loaded_blocks.getIterator(); + i.atEnd() == false; i++) + { + bool existed = i.getNode()->getValue(); + if(existed == false) + continue; + v3s16 p = i.getNode()->getKey(); + MapBlock *block = m_map->getBlockNoCreateNoEx(p); + if(block == NULL) + { + dstream<<"WARNING: "<<__FUNCTION_NAME + <<": got NULL block " + <<"("<copyFrom(*this); + + if(modified_blocks) + modified_blocks->insert(p, block); + } +} + +//END diff --git a/misc/noise.cpp b/misc/noise.cpp new file mode 100644 index 0000000..e7923da --- /dev/null +++ b/misc/noise.cpp @@ -0,0 +1,410 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include +#include "noise.h" +#include +#include "debug.h" + +#define NOISE_MAGIC_X 1619 +#define NOISE_MAGIC_Y 31337 +#define NOISE_MAGIC_Z 52591 +#define NOISE_MAGIC_SEED 1013 + +double cos_lookup[16] = { + 1.0,0.9238,0.7071,0.3826,0,-0.3826,-0.7071,-0.9238, + 1.0,-0.9238,-0.7071,-0.3826,0,0.3826,0.7071,0.9238 +}; + +double dotProduct(double vx, double vy, double wx, double wy){ + return vx*wx+vy*wy; +} + +double easeCurve(double t){ + return 6*pow(t,5)-15*pow(t,4)+10*pow(t,3); +} + +double linearInterpolation(double x0, double x1, double t){ + return x0+(x1-x0)*t; +} + +double biLinearInterpolation(double x0y0, double x1y0, double x0y1, double x1y1, double x, double y){ + double tx = easeCurve(x); + double ty = easeCurve(y); + /*double tx = x; + double ty = y;*/ + double u = linearInterpolation(x0y0,x1y0,tx); + double v = linearInterpolation(x0y1,x1y1,tx); + return linearInterpolation(u,v,ty); +} + +double triLinearInterpolation( + double v000, double v100, double v010, double v110, + double v001, double v101, double v011, double v111, + double x, double y, double z) +{ + /*double tx = easeCurve(x); + double ty = easeCurve(y); + double tz = easeCurve(z);*/ + double tx = x; + double ty = y; + double tz = z; + return( + v000*(1-tx)*(1-ty)*(1-tz) + + v100*tx*(1-ty)*(1-tz) + + v010*(1-tx)*ty*(1-tz) + + v110*tx*ty*(1-tz) + + v001*(1-tx)*(1-ty)*tz + + v101*tx*(1-ty)*tz + + v011*(1-tx)*ty*tz + + v111*tx*ty*tz + ); +} + +double noise2d(int x, int y, int seed) +{ + int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + + NOISE_MAGIC_SEED * seed) & 0x7fffffff; + n = (n>>13)^n; + n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff; + return 1.0 - (double)n/1073741824; +} + +double noise3d(int x, int y, int z, int seed) +{ + int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z + + NOISE_MAGIC_SEED * seed) & 0x7fffffff; + n = (n>>13)^n; + n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff; + return 1.0 - (double)n/1073741824; +} + +#if 0 +double noise2d_gradient(double x, double y, int seed) +{ + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + // Calculate random cosine lookup table indices for the integer corners. + // They are looked up as unit vector gradients from the lookup table. + int n00 = (int)((noise2d(x0, y0, seed)+1)*8); + int n10 = (int)((noise2d(x0+1, y0, seed)+1)*8); + int n01 = (int)((noise2d(x0, y0+1, seed)+1)*8); + int n11 = (int)((noise2d(x0+1, y0+1, seed)+1)*8); + // Make a dot product for the gradients and the positions, to get the values + double s = dotProduct(cos_lookup[n00], cos_lookup[(n00+12)%16], xl, yl); + double u = dotProduct(-cos_lookup[n10], cos_lookup[(n10+12)%16], 1.-xl, yl); + double v = dotProduct(cos_lookup[n01], -cos_lookup[(n01+12)%16], xl, 1.-yl); + double w = dotProduct(-cos_lookup[n11], -cos_lookup[(n11+12)%16], 1.-xl, 1.-yl); + // Interpolate between the values + return biLinearInterpolation(s,u,v,w,xl,yl); +} +#endif + +#if 1 +double noise2d_gradient(double x, double y, int seed) +{ + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + // Get values for corners of cube + double v00 = noise2d(x0, y0, seed); + double v10 = noise2d(x0+1, y0, seed); + double v01 = noise2d(x0, y0+1, seed); + double v11 = noise2d(x0+1, y0+1, seed); + // Interpolate + return biLinearInterpolation(v00,v10,v01,v11,xl,yl); +} +#endif + +double noise3d_gradient(double x, double y, double z, int seed) +{ + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + int z0 = (z > 0.0 ? (int)z : (int)z - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + double zl = z - (double)z0; + // Get values for corners of cube + double v000 = noise3d(x0, y0, z0, seed); + double v100 = noise3d(x0+1, y0, z0, seed); + double v010 = noise3d(x0, y0+1, z0, seed); + double v110 = noise3d(x0+1, y0+1, z0, seed); + double v001 = noise3d(x0, y0, z0+1, seed); + double v101 = noise3d(x0+1, y0, z0+1, seed); + double v011 = noise3d(x0, y0+1, z0+1, seed); + double v111 = noise3d(x0+1, y0+1, z0+1, seed); + // Interpolate + return triLinearInterpolation(v000,v100,v010,v110,v001,v101,v011,v111,xl,yl,zl); +} + +double noise2d_perlin(double x, double y, int seed, + int octaves, double persistence) +{ + double a = 0; + double f = 1.0; + double g = 1.0; + for(int i=0; i0, 0->1, 1->0 +double contour(double v) +{ + v = fabs(v); + if(v >= 1.0) + return 0.0; + return (1.0-v); +} + +double noise3d_param(const NoiseParams ¶m, double x, double y, double z) +{ + double s = param.pos_scale; + x /= s; + y /= s; + z /= s; + + if(param.type == NOISE_PERLIN) + { + return param.noise_scale*noise3d_perlin(x,y,z, param.seed, + param.octaves, + param.persistence); + } + else if(param.type == NOISE_PERLIN_ABS) + { + return param.noise_scale*noise3d_perlin_abs(x,y,z, param.seed, + param.octaves, + param.persistence); + } + else if(param.type == NOISE_PERLIN_CONTOUR) + { + return contour(param.noise_scale*noise3d_perlin(x,y,z, + param.seed, param.octaves, + param.persistence)); + } + else if(param.type == NOISE_PERLIN_CONTOUR_FLIP_YZ) + { + return contour(param.noise_scale*noise3d_perlin(x,z,y, + param.seed, param.octaves, + param.persistence)); + } + else assert(0); +} + +/* + NoiseBuffer +*/ + +NoiseBuffer::NoiseBuffer(): + m_data(NULL) +{ +} + +NoiseBuffer::~NoiseBuffer() +{ + clear(); +} + +void NoiseBuffer::clear() +{ + if(m_data) + delete[] m_data; + m_data = NULL; + m_size_x = 0; + m_size_y = 0; + m_size_z = 0; +} + +void NoiseBuffer::create(const NoiseParams ¶m, + double first_x, double first_y, double first_z, + double last_x, double last_y, double last_z, + double samplelength_x, double samplelength_y, double samplelength_z) +{ + clear(); + + m_start_x = first_x - samplelength_x; + m_start_y = first_y - samplelength_y; + m_start_z = first_z - samplelength_z; + m_samplelength_x = samplelength_x; + m_samplelength_y = samplelength_y; + m_samplelength_z = samplelength_z; + + m_size_x = (last_x - m_start_x)/samplelength_x + 2; + m_size_y = (last_y - m_start_y)/samplelength_y + 2; + m_size_z = (last_z - m_start_z)/samplelength_z + 2; + + m_data = new double[m_size_x*m_size_y*m_size_z]; + + for(int x=0; x= 0); + assert(i < m_size_x*m_size_y*m_size_z); + m_data[i] = d; +} + +void NoiseBuffer::intMultiply(int x, int y, int z, double d) +{ + int i = m_size_x*m_size_y*z + m_size_x*y + x; + assert(i >= 0); + assert(i < m_size_x*m_size_y*m_size_z); + m_data[i] = m_data[i] * d; +} + +double NoiseBuffer::intGet(int x, int y, int z) +{ + int i = m_size_x*m_size_y*z + m_size_x*y + x; + assert(i >= 0); + assert(i < m_size_x*m_size_y*m_size_z); + return m_data[i]; +} + +double NoiseBuffer::get(double x, double y, double z) +{ + x -= m_start_x; + y -= m_start_y; + z -= m_start_z; + x /= m_samplelength_x; + y /= m_samplelength_y; + z /= m_samplelength_z; + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + int z0 = (z > 0.0 ? (int)z : (int)z - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + double zl = z - (double)z0; + // Get values for corners of cube + double v000 = intGet(x0, y0, z0); + double v100 = intGet(x0+1, y0, z0); + double v010 = intGet(x0, y0+1, z0); + double v110 = intGet(x0+1, y0+1, z0); + double v001 = intGet(x0, y0, z0+1); + double v101 = intGet(x0+1, y0, z0+1); + double v011 = intGet(x0, y0+1, z0+1); + double v111 = intGet(x0+1, y0+1, z0+1); + // Interpolate + return triLinearInterpolation(v000,v100,v010,v110,v001,v101,v011,v111,xl,yl,zl); +} + diff --git a/misc/noise.h b/misc/noise.h new file mode 100644 index 0000000..59ca1bf --- /dev/null +++ b/misc/noise.h @@ -0,0 +1,108 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef NOISE_HEADER +#define NOISE_HEADER + +double easeCurve(double t); + +// Return value: -1 ... 1 +double noise2d(int x, int y, int seed); +double noise3d(int x, int y, int z, int seed); + +double noise2d_gradient(double x, double y, int seed); +double noise3d_gradient(double x, double y, double z, int seed); + +double noise2d_perlin(double x, double y, int seed, + int octaves, double persistence); + +double noise2d_perlin_abs(double x, double y, int seed, + int octaves, double persistence); + +double noise3d_perlin(double x, double y, double z, int seed, + int octaves, double persistence); + +double noise3d_perlin_abs(double x, double y, double z, int seed, + int octaves, double persistence); + +enum NoiseType +{ + NOISE_PERLIN, + NOISE_PERLIN_ABS, + NOISE_PERLIN_CONTOUR, + NOISE_PERLIN_CONTOUR_FLIP_YZ +}; + +struct NoiseParams +{ + NoiseType type; + int seed; + int octaves; + double persistence; + double pos_scale; + double noise_scale; // Useful for contour noises + + NoiseParams(NoiseType type_=NOISE_PERLIN, int seed_=0, + int octaves_=3, double persistence_=0.5, + double pos_scale_=100.0, double noise_scale_=1.0): + type(type_), + seed(seed_), + octaves(octaves_), + persistence(persistence_), + pos_scale(pos_scale_), + noise_scale(noise_scale_) + { + } +}; + +double noise3d_param(const NoiseParams ¶m, double x, double y, double z); + +class NoiseBuffer +{ +public: + NoiseBuffer(); + ~NoiseBuffer(); + + void clear(); + void create(const NoiseParams ¶m, + double first_x, double first_y, double first_z, + double last_x, double last_y, double last_z, + double samplelength_x, double samplelength_y, double samplelength_z); + void multiply(const NoiseParams ¶m); + // Deprecated + void create(int seed, int octaves, double persistence, + bool abs, + double first_x, double first_y, double first_z, + double last_x, double last_y, double last_z, + double samplelength_x, double samplelength_y, double samplelength_z); + + void intSet(int x, int y, int z, double d); + void intMultiply(int x, int y, int z, double d); + double intGet(int x, int y, int z); + double get(double x, double y, double z); + +private: + double *m_data; + double m_start_x, m_start_y, m_start_z; + double m_samplelength_x, m_samplelength_y, m_samplelength_z; + int m_size_x, m_size_y, m_size_z; +}; + +#endif + diff --git a/old/Makefile.bak b/old/Makefile.bak new file mode 100644 index 0000000..8ba03f9 --- /dev/null +++ b/old/Makefile.bak @@ -0,0 +1,90 @@ +# Makefile for Irrlicht Examples +# It's usually sufficient to change just the target name and source file list +# and be sure that CXX is set to a valid compiler +SOURCE_FILES = porting.cpp guiMessageMenu.cpp materials.cpp guiTextInputMenu.cpp guiInventoryMenu.cpp irrlichtwrapper.cpp guiPauseMenu.cpp defaultsettings.cpp mapnode.cpp tile.cpp voxel.cpp mapblockobject.cpp inventory.cpp debug.cpp serialization.cpp light.cpp filesys.cpp connection.cpp environment.cpp client.cpp server.cpp socket.cpp mapblock.cpp mapsector.cpp heightmap.cpp map.cpp player.cpp utility.cpp main.cpp test.cpp + +DEBUG_TARGET = debugtest +DEBUG_SOURCES = $(addprefix src/, $(SOURCE_FILES)) +DEBUG_BUILD_DIR = debugbuild +DEBUG_OBJECTS = $(addprefix $(DEBUG_BUILD_DIR)/, $(SOURCE_FILES:.cpp=.o)) + +FAST_TARGET = fasttest +FAST_SOURCES = $(addprefix src/, $(SOURCE_FILES)) +FAST_BUILD_DIR = fastbuild +FAST_OBJECTS = $(addprefix $(FAST_BUILD_DIR)/, $(SOURCE_FILES:.cpp=.o)) + +SERVER_TARGET = server +SERVER_SOURCE_FILES = porting.cpp materials.cpp defaultsettings.cpp mapnode.cpp voxel.cpp mapblockobject.cpp inventory.cpp debug.cpp serialization.cpp light.cpp filesys.cpp connection.cpp environment.cpp server.cpp socket.cpp mapblock.cpp mapsector.cpp heightmap.cpp map.cpp player.cpp utility.cpp servermain.cpp test.cpp +SERVER_SOURCES = $(addprefix src/, $(SERVER_SOURCE_FILES)) +SERVER_BUILD_DIR = serverbuild +SERVER_OBJECTS = $(addprefix $(SERVER_BUILD_DIR)/, $(SERVER_SOURCE_FILES:.cpp=.o)) + +IRRLICHTPATH = ../irrlicht/irrlicht-1.7.1 +JTHREADPATH = ../jthread/jthread-1.2.1 + + +all: fast + +ifeq ($(HOSTTYPE), x86_64) +LIBSELECT=64 +endif + +debug: CXXFLAGS = -Wall -g -O1 +debug: CPPFLAGS = -I$(IRRLICHTPATH)/include -I/usr/X11R6/include -I$(JTHREADPATH)/src -DDEBUG -DRUN_IN_PLACE +debug: LDFLAGS = -L/usr/X11R6/lib$(LIBSELECT) -L$(IRRLICHTPATH)/lib/Linux -L$(JTHREADPATH)/src/.libs -lIrrlicht -lGL -lXxf86vm -lXext -lX11 -ljthread -lz + +fast: CXXFLAGS = -O3 -ffast-math -Wall -fomit-frame-pointer -pipe -funroll-loops -mtune=i686 +fast: CPPFLAGS = -I$(IRRLICHTPATH)/include -I/usr/X11R6/include -I$(JTHREADPATH)/src -DUNITTEST_DISABLE -DRUN_IN_PLACE +fast: LDFLAGS = -L/usr/X11R6/lib$(LIBSELECT) -L$(IRRLICHTPATH)/lib/Linux -L$(JTHREADPATH)/src/.libs -lIrrlicht -lGL -lXxf86vm -lXext -lX11 -ljthread -lz + +server: CXXFLAGS = -O3 -ffast-math -Wall -fomit-frame-pointer -pipe -funroll-loops -mtune=i686 +server: CPPFLAGS = -I$(IRRLICHTPATH)/include -I/usr/X11R6/include -I$(JTHREADPATH)/src -DSERVER -DUNITTEST_DISABLE -DRUN_IN_PLACE +server: LDFLAGS = -L$(JTHREADPATH)/src/.libs -ljthread -lz -lpthread + +DEBUG_DESTPATH = bin/$(DEBUG_TARGET) +FAST_DESTPATH = bin/$(FAST_TARGET) +SERVER_DESTPATH = bin/$(SERVER_TARGET) + +# Build commands + +debug: $(DEBUG_BUILD_DIR) $(DEBUG_DESTPATH) +fast: $(FAST_BUILD_DIR) $(FAST_DESTPATH) +server: $(SERVER_BUILD_DIR) $(SERVER_DESTPATH) + +$(DEBUG_BUILD_DIR): + mkdir -p $(DEBUG_BUILD_DIR) +$(FAST_BUILD_DIR): + mkdir -p $(FAST_BUILD_DIR) +$(SERVER_BUILD_DIR): + mkdir -p $(SERVER_BUILD_DIR) + +$(DEBUG_DESTPATH): $(DEBUG_OBJECTS) + $(CXX) -o $@ $(DEBUG_OBJECTS) $(LDFLAGS) + +$(FAST_DESTPATH): $(FAST_OBJECTS) + $(CXX) -o $@ $(FAST_OBJECTS) $(LDFLAGS) + +$(SERVER_DESTPATH): $(SERVER_OBJECTS) + $(CXX) -o $@ $(SERVER_OBJECTS) $(LDFLAGS) + +$(DEBUG_BUILD_DIR)/%.o: src/%.cpp + $(CXX) -c -o $@ $< $(CPPFLAGS) $(CXXFLAGS) + +$(FAST_BUILD_DIR)/%.o: src/%.cpp + $(CXX) -c -o $@ $< $(CPPFLAGS) $(CXXFLAGS) + +$(SERVER_BUILD_DIR)/%.o: src/%.cpp + $(CXX) -c -o $@ $< $(CPPFLAGS) $(CXXFLAGS) + +clean: clean_debug clean_fast clean_server + +clean_debug: + @$(RM) $(DEBUG_OBJECTS) $(DEBUG_DESTPATH) + +clean_fast: + @$(RM) $(FAST_OBJECTS) $(FAST_DESTPATH) + +clean_server: + @$(RM) $(SERVER_OBJECTS) $(SERVER_DESTPATH) + +.PHONY: all all_win32 clean clean_debug clean_win32 clean_fast clean_server diff --git a/old/minetest.sln b/old/minetest.sln new file mode 100644 index 0000000..d1f144c --- /dev/null +++ b/old/minetest.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual C++ Express 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minetest", "minetest.vcproj", "{AE3BF173-1D74-4294-AAB8-5A0ACDE9990D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AE3BF173-1D74-4294-AAB8-5A0ACDE9990D}.Debug|Win32.ActiveCfg = Debug|Win32 + {AE3BF173-1D74-4294-AAB8-5A0ACDE9990D}.Debug|Win32.Build.0 = Debug|Win32 + {AE3BF173-1D74-4294-AAB8-5A0ACDE9990D}.Release|Win32.ActiveCfg = Release|Win32 + {AE3BF173-1D74-4294-AAB8-5A0ACDE9990D}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/old/minetest.vcproj b/old/minetest.vcproj new file mode 100644 index 0000000..8973c9a --- /dev/null +++ b/old/minetest.vcproj @@ -0,0 +1,424 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/po/da/minetest.po b/po/da/minetest.po new file mode 100644 index 0000000..b64b5d8 --- /dev/null +++ b/po/da/minetest.po @@ -0,0 +1,486 @@ +# German translations for minetest-c55 package. +# Copyright (C) 2011 celeron +# This file is distributed under the same license as the minetest-c55 package. +# Frederik Helth , 2011. +# +msgid "" +msgstr "" +"Project-Id-Version: 0.0.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-08-02 12:36+0200\n" +"PO-Revision-Date: 2011-08-02 00:31+0100\n" +"Last-Translator: Frederik Helth \n" +"Language-Team: \n" +"Language: da\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: src/guiKeyChangeMenu.cpp:84 +msgid "KEYBINDINGS" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:94 +msgid "Forward" +msgstr "Frem" + +#: src/guiKeyChangeMenu.cpp:111 +msgid "Backward" +msgstr "Tilbage" + +#: src/guiKeyChangeMenu.cpp:127 src/guiKeyChangeMenu.h:38 +msgid "Left" +msgstr "Venstre" + +#: src/guiKeyChangeMenu.cpp:142 src/guiKeyChangeMenu.h:38 +msgid "Right" +msgstr "Højre" + +#: src/guiKeyChangeMenu.cpp:158 +msgid "Use" +msgstr "Brug" + +#: src/guiKeyChangeMenu.cpp:173 +msgid "Sneak" +msgstr "Snig" + +#: src/guiKeyChangeMenu.cpp:189 +msgid "Jump" +msgstr "Hop" + +#: src/guiKeyChangeMenu.cpp:204 +msgid "Inventory" +msgstr "Ting" + +#: src/guiKeyChangeMenu.cpp:220 +msgid "Chat" +msgstr "Chat" + +#: src/guiKeyChangeMenu.cpp:236 +msgid "Toggle fly" +msgstr "Flyvning" + +#: src/guiKeyChangeMenu.cpp:251 +msgid "Toggle fast" +msgstr "Hurtig flyvning" + +#: src/guiKeyChangeMenu.cpp:266 +msgid "Range select" +msgstr "Afstands load" + +#: src/guiKeyChangeMenu.cpp:283 +msgid "Print stacks" +msgstr "Print stykker" + +#: src/guiKeyChangeMenu.cpp:298 +msgid "Save" +msgstr "Gem" + +#: src/guiKeyChangeMenu.cpp:304 src/guiKeyChangeMenu.h:33 +msgid "Cancel" +msgstr "Afslut" + +#: src/guiKeyChangeMenu.cpp:537 src/guiKeyChangeMenu.cpp:542 +#: src/guiKeyChangeMenu.cpp:547 src/guiKeyChangeMenu.cpp:552 +#: src/guiKeyChangeMenu.cpp:557 src/guiKeyChangeMenu.cpp:562 +#: src/guiKeyChangeMenu.cpp:567 src/guiKeyChangeMenu.cpp:572 +#: src/guiKeyChangeMenu.cpp:577 src/guiKeyChangeMenu.cpp:582 +#: src/guiKeyChangeMenu.cpp:587 src/guiKeyChangeMenu.cpp:592 +#: src/guiKeyChangeMenu.cpp:597 +msgid "press Key" +msgstr "Tryk knap" + +#: src/guiKeyChangeMenu.h:33 +msgid "Left Button" +msgstr "Venstre Knap" + +#: src/guiKeyChangeMenu.h:33 +msgid "Middle Button" +msgstr "Midt Knap" + +#: src/guiKeyChangeMenu.h:33 +msgid "Right Button" +msgstr "Højre Knap" + +#: src/guiKeyChangeMenu.h:33 +msgid "X Button 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Back" +msgstr "Tilbage" + +#: src/guiKeyChangeMenu.h:34 +msgid "Clear" +msgstr "Rens" + +#: src/guiKeyChangeMenu.h:34 +msgid "Return" +msgstr "Tilbage" + +#: src/guiKeyChangeMenu.h:34 +msgid "Tab" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "X Button 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Capital" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Control" +msgstr "Kontrol" + +#: src/guiKeyChangeMenu.h:35 +msgid "Kana" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Pause" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Convert" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Escape" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Final" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Junja" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Kanji" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Nonconvert" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Accept" +msgstr "Accepter" + +#: src/guiKeyChangeMenu.h:37 +msgid "End" +msgstr "Slut" + +#: src/guiKeyChangeMenu.h:37 +msgid "Home" +msgstr "Hjem" + +#: src/guiKeyChangeMenu.h:37 +msgid "Mode Change" +msgstr "Mode skift" + +#: src/guiKeyChangeMenu.h:37 +msgid "Next" +msgstr "Næste" + +#: src/guiKeyChangeMenu.h:37 +msgid "Priot" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Space" +msgstr "Mellemrum" + +#: src/guiKeyChangeMenu.h:38 +msgid "Down" +msgstr "Ned" + +#: src/guiKeyChangeMenu.h:38 +msgid "Execute" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Print" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Select" +msgstr "Vælge" + +#: src/guiKeyChangeMenu.h:38 +msgid "Up" +msgstr "Op" + +#: src/guiKeyChangeMenu.h:39 +msgid "Delete" +msgstr "Slet" + +#: src/guiKeyChangeMenu.h:39 +msgid "Help" +msgstr "Hjælp" + +#: src/guiKeyChangeMenu.h:39 +msgid "Insert" +msgstr "Indset" + +#: src/guiKeyChangeMenu.h:39 +msgid "Snapshot" +msgstr "Screenshot" + +#: src/guiKeyChangeMenu.h:42 +msgid "Left Windows" +msgstr "Venstre windows" + +#: src/guiKeyChangeMenu.h:43 +msgid "Apps" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 0" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Right Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Sleep" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 3" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 4" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 5" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 6" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 7" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad *" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad +" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad -" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad /" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 8" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 9" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Num Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Scroll Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Left Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Right Shight" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Comma" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Minus" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Period" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Plus" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "Attn" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "CrSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Erase OEF" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "ExSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "OEM Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "PA1" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Play" +msgstr "Spil" + +#: src/guiKeyChangeMenu.h:58 +msgid "Zoom" +msgstr "" + +#: src/guiMainMenu.cpp:181 +msgid "Name/Password" +msgstr "Navn/kodeord" + +#: src/guiMainMenu.cpp:206 +msgid "Address/Port" +msgstr "Adresse/port" + +#: src/guiMainMenu.cpp:228 +msgid "Leave address blank to start a local server." +msgstr "Lad black for at spille localt" + +#: src/guiMainMenu.cpp:235 +msgid "Fancy trees" +msgstr "Fancy trær" + +#: src/guiMainMenu.cpp:241 +msgid "Smooth Lighting" +msgstr "" + +#: src/guiMainMenu.cpp:249 +msgid "Start Game / Connect" +msgstr "Start spil" + +#: src/guiMainMenu.cpp:258 +msgid "Change keys" +msgstr "Indstillinger" + +#: src/guiMainMenu.cpp:281 +msgid "Creative Mode" +msgstr "Kreativ mode" + +#: src/guiMainMenu.cpp:287 +msgid "Enable Damage" +msgstr "Tag imod skade" + +#: src/guiMainMenu.cpp:295 +msgid "Delete map" +msgstr "Slet mappen" + +#: src/guiMessageMenu.cpp:94 src/guiTextInputMenu.cpp:112 +msgid "Proceed" +msgstr "Fortsæt" + +#: src/guiPasswordChange.cpp:103 +msgid "Old Password" +msgstr "Gamle kodeord" + +#: src/guiPasswordChange.cpp:120 +msgid "New Password" +msgstr "Nye kodeord" + +#: src/guiPasswordChange.cpp:136 +msgid "Confirm Password" +msgstr "Gentag kodeord" + +#: src/guiPasswordChange.cpp:153 +msgid "Change" +msgstr "Skift" + +#: src/guiPasswordChange.cpp:162 +msgid "Passwords do not match!" +msgstr "Kodeordne matcher ikke hinanden!" + +#: src/guiPauseMenu.cpp:111 +msgid "Continue" +msgstr "Fortsæt" + +#: src/guiPauseMenu.cpp:118 +msgid "Change Password" +msgstr "Skift kodeord" + +#: src/guiPauseMenu.cpp:125 +msgid "Disconnect" +msgstr "Logud" + +#: src/guiPauseMenu.cpp:132 +msgid "Exit to OS" +msgstr "Afslut til OS" + +#: src/guiPauseMenu.cpp:139 +msgid "" +"Default Controls:\n" +"- WASD: Walk\n" +"- Mouse left: dig/hit\n" +"- Mouse right: place/use\n" +"- Mouse wheel: select item\n" +"- 0...9: select item\n" +"- Shift: sneak\n" +"- R: Toggle viewing all loaded chunks\n" +"- I: Inventory menu\n" +"- ESC: This menu\n" +"- T: Chat\n" +msgstr "" diff --git a/po/de/minetest.po b/po/de/minetest.po new file mode 100644 index 0000000..4b22855 --- /dev/null +++ b/po/de/minetest.po @@ -0,0 +1,498 @@ +# German translations for minetest-c55 package. +# Copyright (C) 2011 celeron +# This file is distributed under the same license as the minetest-c55 package. +# Constantin Wenger , 2011. +# +msgid "" +msgstr "" +"Project-Id-Version: 0.0.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-08-02 12:36+0200\n" +"PO-Revision-Date: 2011-08-02 11:54+0100\n" +"Last-Translator: Constantin Wenger \n" +"Language-Team: Deutsch <>\n" +"Language: de\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n!=1);\n" + +#: src/guiKeyChangeMenu.cpp:84 +msgid "KEYBINDINGS" +msgstr "TASTEN EINST." + +#: src/guiKeyChangeMenu.cpp:94 +msgid "Forward" +msgstr "Vorwärts" + +#: src/guiKeyChangeMenu.cpp:111 +msgid "Backward" +msgstr "Rückwärts" + +#: src/guiKeyChangeMenu.cpp:127 src/guiKeyChangeMenu.h:38 +msgid "Left" +msgstr "Links" + +#: src/guiKeyChangeMenu.cpp:142 src/guiKeyChangeMenu.h:38 +msgid "Right" +msgstr "Rechts" + +#: src/guiKeyChangeMenu.cpp:158 +msgid "Use" +msgstr "Benutzen" + +#: src/guiKeyChangeMenu.cpp:173 +msgid "Sneak" +msgstr "Kriechen" + +#: src/guiKeyChangeMenu.cpp:189 +msgid "Jump" +msgstr "Springen" + +#: src/guiKeyChangeMenu.cpp:204 +msgid "Inventory" +msgstr "Inventar" + +#: src/guiKeyChangeMenu.cpp:220 +msgid "Chat" +msgstr "Chat" + +#: src/guiKeyChangeMenu.cpp:236 +msgid "Toggle fly" +msgstr "Fliegen umsch." + +#: src/guiKeyChangeMenu.cpp:251 +msgid "Toggle fast" +msgstr "Speed umsch." + +#: src/guiKeyChangeMenu.cpp:266 +msgid "Range select" +msgstr "Entfernung wählen" + +#: src/guiKeyChangeMenu.cpp:283 +msgid "Print stacks" +msgstr "Stack ausgeben" + +#: src/guiKeyChangeMenu.cpp:298 +msgid "Save" +msgstr "Speichern" + +#: src/guiKeyChangeMenu.cpp:304 src/guiKeyChangeMenu.h:33 +msgid "Cancel" +msgstr "Abbrechen" + +#: src/guiKeyChangeMenu.cpp:537 src/guiKeyChangeMenu.cpp:542 +#: src/guiKeyChangeMenu.cpp:547 src/guiKeyChangeMenu.cpp:552 +#: src/guiKeyChangeMenu.cpp:557 src/guiKeyChangeMenu.cpp:562 +#: src/guiKeyChangeMenu.cpp:567 src/guiKeyChangeMenu.cpp:572 +#: src/guiKeyChangeMenu.cpp:577 src/guiKeyChangeMenu.cpp:582 +#: src/guiKeyChangeMenu.cpp:587 src/guiKeyChangeMenu.cpp:592 +#: src/guiKeyChangeMenu.cpp:597 +msgid "press Key" +msgstr "Taste drücken" + +#: src/guiKeyChangeMenu.h:33 +msgid "Left Button" +msgstr "linke Taste" + +#: src/guiKeyChangeMenu.h:33 +msgid "Middle Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Right Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "X Button 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Back" +msgstr "Rücktaste" + +#: src/guiKeyChangeMenu.h:34 +msgid "Clear" +msgstr "löschen" + +#: src/guiKeyChangeMenu.h:34 +msgid "Return" +msgstr "Return" + +#: src/guiKeyChangeMenu.h:34 +msgid "Tab" +msgstr "Tab" + +#: src/guiKeyChangeMenu.h:34 +msgid "X Button 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Capital" +msgstr "Feststellen" + +#: src/guiKeyChangeMenu.h:35 +msgid "Control" +msgstr "Strg" + +#: src/guiKeyChangeMenu.h:35 +msgid "Kana" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Menu" +msgstr "Menü" + +#: src/guiKeyChangeMenu.h:35 +msgid "Pause" +msgstr "Pause" + +#: src/guiKeyChangeMenu.h:35 +msgid "Shift" +msgstr "Umsch." + +#: src/guiKeyChangeMenu.h:36 +msgid "Convert" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Escape" +msgstr "Escape" + +#: src/guiKeyChangeMenu.h:36 +msgid "Final" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Junja" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Kanji" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Nonconvert" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Accept" +msgstr "Annehmen" + +#: src/guiKeyChangeMenu.h:37 +msgid "End" +msgstr "Ende" + +#: src/guiKeyChangeMenu.h:37 +msgid "Home" +msgstr "Pos1" + +#: src/guiKeyChangeMenu.h:37 +msgid "Mode Change" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Next" +msgstr "Bild runter" + +#: src/guiKeyChangeMenu.h:37 +msgid "Priot" +msgstr "Bild hoch" + +#: src/guiKeyChangeMenu.h:37 +msgid "Space" +msgstr "Leertaste" + +#: src/guiKeyChangeMenu.h:38 +msgid "Down" +msgstr "Runter" + +#: src/guiKeyChangeMenu.h:38 +msgid "Execute" +msgstr "Ausführen" + +#: src/guiKeyChangeMenu.h:38 +msgid "Print" +msgstr "Druck" + +#: src/guiKeyChangeMenu.h:38 +msgid "Select" +msgstr "Select" + +#: src/guiKeyChangeMenu.h:38 +msgid "Up" +msgstr "Hoch" + +#: src/guiKeyChangeMenu.h:39 +msgid "Delete" +msgstr "Entf" + +#: src/guiKeyChangeMenu.h:39 +msgid "Help" +msgstr "Hilfe" + +#: src/guiKeyChangeMenu.h:39 +msgid "Insert" +msgstr "Einfg" + +#: src/guiKeyChangeMenu.h:39 +msgid "Snapshot" +msgstr "Schnapschuss" + +#: src/guiKeyChangeMenu.h:42 +msgid "Left Windows" +msgstr "Win links" + +#: src/guiKeyChangeMenu.h:43 +msgid "Apps" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 0" +msgstr "Ziffernblock 0" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 1" +msgstr "Ziffernblock 1" + +#: src/guiKeyChangeMenu.h:43 +msgid "Right Windows" +msgstr "Win rechts" + +#: src/guiKeyChangeMenu.h:43 +msgid "Sleep" +msgstr "Schlaf" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 2" +msgstr "Ziffernblock 2" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 3" +msgstr "Ziffernblock 3" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 4" +msgstr "Ziffernblock 4" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 5" +msgstr "Ziffernblock 5" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 6" +msgstr "Ziffernblock 6" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 7" +msgstr "Ziffernblock 7" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad *" +msgstr "Ziffernblock *" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad +" +msgstr "Ziffernblock +" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad -" +msgstr "Ziffernblock -" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad /" +msgstr "Ziffernblock /" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 8" +msgstr "Ziffernblock 8" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 9" +msgstr "Ziffernblock 9" + +#: src/guiKeyChangeMenu.h:49 +msgid "Num Lock" +msgstr "Num" + +#: src/guiKeyChangeMenu.h:49 +msgid "Scroll Lock" +msgstr "Rollen" + +#: src/guiKeyChangeMenu.h:50 +msgid "Left Shift" +msgstr "Umsch. links" + +#: src/guiKeyChangeMenu.h:50 +msgid "Right Shight" +msgstr "Umsch. rechts" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Control" +msgstr "Strg links" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Menu" +msgstr "Alt" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Control" +msgstr "Strg rechts" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Menu" +msgstr "Alt Gr" + +#: src/guiKeyChangeMenu.h:53 +msgid "Comma" +msgstr "Komma" + +#: src/guiKeyChangeMenu.h:53 +msgid "Minus" +msgstr "Minus" + +#: src/guiKeyChangeMenu.h:53 +msgid "Period" +msgstr "Punkt" + +#: src/guiKeyChangeMenu.h:53 +msgid "Plus" +msgstr "Plus" + +#: src/guiKeyChangeMenu.h:57 +msgid "Attn" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "CrSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Erase OEF" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "ExSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "OEM Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "PA1" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Play" +msgstr "Play" + +#: src/guiKeyChangeMenu.h:58 +msgid "Zoom" +msgstr "Zoom" + +#: src/guiMainMenu.cpp:181 +msgid "Name/Password" +msgstr "Name/Passwort" + +#: src/guiMainMenu.cpp:206 +msgid "Address/Port" +msgstr "Adresse / Port" + +#: src/guiMainMenu.cpp:228 +msgid "Leave address blank to start a local server." +msgstr "Lasse die Adresse frei um einen eigenen Server zu starten" + +#: src/guiMainMenu.cpp:235 +msgid "Fancy trees" +msgstr "Schöne Bäume" + +#: src/guiMainMenu.cpp:241 +msgid "Smooth Lighting" +msgstr "Besseres Licht" + +#: src/guiMainMenu.cpp:249 +msgid "Start Game / Connect" +msgstr "Spiel starten / Verbinden" + +#: src/guiMainMenu.cpp:258 +msgid "Change keys" +msgstr "Tasten ändern" + +#: src/guiMainMenu.cpp:281 +msgid "Creative Mode" +msgstr "Kreativitätsmodus" + +#: src/guiMainMenu.cpp:287 +msgid "Enable Damage" +msgstr "Schaden einschalten" + +#: src/guiMainMenu.cpp:295 +msgid "Delete map" +msgstr "Karte löschen" + +#: src/guiMessageMenu.cpp:94 src/guiTextInputMenu.cpp:112 +msgid "Proceed" +msgstr "Fortsetzen" + +#: src/guiPasswordChange.cpp:103 +msgid "Old Password" +msgstr "Altes Passwort" + +#: src/guiPasswordChange.cpp:120 +msgid "New Password" +msgstr "Neues Passwort" + +#: src/guiPasswordChange.cpp:136 +msgid "Confirm Password" +msgstr "Passwort wiederholen" + +#: src/guiPasswordChange.cpp:153 +msgid "Change" +msgstr "Ändern" + +#: src/guiPasswordChange.cpp:162 +msgid "Passwords do not match!" +msgstr "Passwörter passen nicht zusammen" + +#: src/guiPauseMenu.cpp:111 +msgid "Continue" +msgstr "Weiter" + +#: src/guiPauseMenu.cpp:118 +msgid "Change Password" +msgstr "Passwort ändern" + +#: src/guiPauseMenu.cpp:125 +msgid "Disconnect" +msgstr "Verbindung trennen" + +#: src/guiPauseMenu.cpp:132 +msgid "Exit to OS" +msgstr "Programm beenden" + +#: src/guiPauseMenu.cpp:139 +#, fuzzy +msgid "" +"Default Controls:\n" +"- WASD: Walk\n" +"- Mouse left: dig/hit\n" +"- Mouse right: place/use\n" +"- Mouse wheel: select item\n" +"- 0...9: select item\n" +"- Shift: sneak\n" +"- R: Toggle viewing all loaded chunks\n" +"- I: Inventory menu\n" +"- ESC: This menu\n" +"- T: Chat\n" +msgstr "" +"Tastenkürzel:\n" +"- WASD: Gehen\n" +"- linke Maustaste: Blöcke aufnehmen \n" +"- rechte Maustaste: Blöche ablegen\n" +"- Mausrad: Item auswählen\n" +"- 0...9: Item auswählen\n" +"- Shift: ducken\n" +"- R: alle geladenen Blöcke anzeigen (wechseln)\n" +"- I: Inventarmenü\n" +"- T: Chat\n" diff --git a/po/fr/minetest.po b/po/fr/minetest.po new file mode 100644 index 0000000..52a02c2 --- /dev/null +++ b/po/fr/minetest.po @@ -0,0 +1,500 @@ +# French translations for minetest-c55 package. +# Copyright (C) 2011 celeron +# This file is distributed under the same license as the minetest-c55 package. +# Cyriaque 'Cisoun' Skrapits , 2011 +# +msgid "" +msgstr "" +"Project-Id-Version: 0.0.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-08-02 12:36+0200\n" +"PO-Revision-Date: 2011-07-21 15:48+0200\n" +"Last-Translator: Cyriaque 'Cisoun' Skrapits \n" +"Language-Team: Français <>\n" +"Language: fr\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n!=1);\n" + +#: src/guiKeyChangeMenu.cpp:84 +msgid "KEYBINDINGS" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:94 +msgid "Forward" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:111 +msgid "Backward" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:127 src/guiKeyChangeMenu.h:38 +msgid "Left" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:142 src/guiKeyChangeMenu.h:38 +msgid "Right" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:158 +msgid "Use" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:173 +msgid "Sneak" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:189 +msgid "Jump" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:204 +msgid "Inventory" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:220 +msgid "Chat" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:236 +msgid "Toggle fly" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:251 +msgid "Toggle fast" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:266 +msgid "Range select" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:283 +msgid "Print stacks" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:298 +msgid "Save" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:304 src/guiKeyChangeMenu.h:33 +msgid "Cancel" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:537 src/guiKeyChangeMenu.cpp:542 +#: src/guiKeyChangeMenu.cpp:547 src/guiKeyChangeMenu.cpp:552 +#: src/guiKeyChangeMenu.cpp:557 src/guiKeyChangeMenu.cpp:562 +#: src/guiKeyChangeMenu.cpp:567 src/guiKeyChangeMenu.cpp:572 +#: src/guiKeyChangeMenu.cpp:577 src/guiKeyChangeMenu.cpp:582 +#: src/guiKeyChangeMenu.cpp:587 src/guiKeyChangeMenu.cpp:592 +#: src/guiKeyChangeMenu.cpp:597 +msgid "press Key" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Left Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Middle Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Right Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "X Button 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Back" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Return" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Tab" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "X Button 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Capital" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Kana" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Pause" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Convert" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Escape" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Final" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Junja" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Kanji" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Nonconvert" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Accept" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "End" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Home" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +#, fuzzy +msgid "Mode Change" +msgstr "Changer" + +#: src/guiKeyChangeMenu.h:37 +msgid "Next" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Priot" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Space" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Down" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Execute" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Print" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Select" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Up" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +#, fuzzy +msgid "Delete" +msgstr "Supprimer carte" + +#: src/guiKeyChangeMenu.h:39 +msgid "Help" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Insert" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Snapshot" +msgstr "" + +#: src/guiKeyChangeMenu.h:42 +msgid "Left Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Apps" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 0" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Right Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Sleep" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 3" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 4" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 5" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 6" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 7" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad *" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad +" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad -" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad /" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 8" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 9" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Num Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Scroll Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Left Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Right Shight" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Comma" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Minus" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Period" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Plus" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "Attn" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "CrSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Erase OEF" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "ExSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "OEM Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "PA1" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Play" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Zoom" +msgstr "" + +#: src/guiMainMenu.cpp:181 +msgid "Name/Password" +msgstr "Nom / MdP" + +#: src/guiMainMenu.cpp:206 +msgid "Address/Port" +msgstr "Adresse / Port" + +#: src/guiMainMenu.cpp:228 +msgid "Leave address blank to start a local server." +msgstr "Laisser l'adresse vide pour lancer un serveur local." + +#: src/guiMainMenu.cpp:235 +msgid "Fancy trees" +msgstr "Arbres spéciaux" + +#: src/guiMainMenu.cpp:241 +msgid "Smooth Lighting" +msgstr "Lumière douce" + +#: src/guiMainMenu.cpp:249 +msgid "Start Game / Connect" +msgstr "Démarrer / Connecter" + +#: src/guiMainMenu.cpp:258 +msgid "Change keys" +msgstr "Changer touches" + +#: src/guiMainMenu.cpp:281 +msgid "Creative Mode" +msgstr "Mode créatif" + +#: src/guiMainMenu.cpp:287 +msgid "Enable Damage" +msgstr "Activer blessures" + +#: src/guiMainMenu.cpp:295 +msgid "Delete map" +msgstr "Supprimer carte" + +#: src/guiMessageMenu.cpp:94 src/guiTextInputMenu.cpp:112 +msgid "Proceed" +msgstr "OK" + +#: src/guiPasswordChange.cpp:103 +msgid "Old Password" +msgstr "Ancien mot de passe" + +#: src/guiPasswordChange.cpp:120 +msgid "New Password" +msgstr "Nouveau mot de passe" + +#: src/guiPasswordChange.cpp:136 +msgid "Confirm Password" +msgstr "Confirmer mot de passe" + +#: src/guiPasswordChange.cpp:153 +msgid "Change" +msgstr "Changer" + +#: src/guiPasswordChange.cpp:162 +msgid "Passwords do not match!" +msgstr "Mauvaise correspondance!" + +#: src/guiPauseMenu.cpp:111 +msgid "Continue" +msgstr "Continuer" + +#: src/guiPauseMenu.cpp:118 +msgid "Change Password" +msgstr "Changer mot de passe" + +#: src/guiPauseMenu.cpp:125 +msgid "Disconnect" +msgstr "Déconnection" + +#: src/guiPauseMenu.cpp:132 +msgid "Exit to OS" +msgstr "Quitter le jeu" + +#: src/guiPauseMenu.cpp:139 +#, fuzzy +msgid "" +"Default Controls:\n" +"- WASD: Walk\n" +"- Mouse left: dig/hit\n" +"- Mouse right: place/use\n" +"- Mouse wheel: select item\n" +"- 0...9: select item\n" +"- Shift: sneak\n" +"- R: Toggle viewing all loaded chunks\n" +"- I: Inventory menu\n" +"- ESC: This menu\n" +"- T: Chat\n" +msgstr "" +"Touches:\n" +"- WASD: Marcher\n" +"- Clic gauche: Creuser bloc\n" +"- Clic droite: Insérer bloc\n" +"- Roulette: Sélection élément\n" +"- 0...9: Sélection élément\n" +"- Shift: S'accroupir\n" +"- R: Active la vue de tous les blocs\n" +"- I: Inventaire\n" +"- T: Chat\n" diff --git a/po/it/minetest.po b/po/it/minetest.po new file mode 100644 index 0000000..6410d2c --- /dev/null +++ b/po/it/minetest.po @@ -0,0 +1,499 @@ +# Italian translations for minetest package. +# Copyright (C) 2011 THE minetest'S COPYRIGHT HOLDER +# This file is distributed under the same license as the minetest package. +# Giuseppe Bilotta , 2011. +# +msgid "" +msgstr "" +"Project-Id-Version: minetest\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-08-02 12:36+0200\n" +"PO-Revision-Date: 2011-07-24 18:56+0200\n" +"Last-Translator: Giuseppe Bilotta \n" +"Language-Team: Italian\n" +"Language: it\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: src/guiKeyChangeMenu.cpp:84 +msgid "KEYBINDINGS" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:94 +msgid "Forward" +msgstr "Avanti" + +#: src/guiKeyChangeMenu.cpp:111 +msgid "Backward" +msgstr "Indietro" + +#: src/guiKeyChangeMenu.cpp:127 src/guiKeyChangeMenu.h:38 +msgid "Left" +msgstr "Sinistra" + +#: src/guiKeyChangeMenu.cpp:142 src/guiKeyChangeMenu.h:38 +msgid "Right" +msgstr "Destra" + +#: src/guiKeyChangeMenu.cpp:158 +msgid "Use" +msgstr "Usa" + +#: src/guiKeyChangeMenu.cpp:173 +msgid "Sneak" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:189 +msgid "Jump" +msgstr "Salta" + +#: src/guiKeyChangeMenu.cpp:204 +msgid "Inventory" +msgstr "Invetario" + +#: src/guiKeyChangeMenu.cpp:220 +msgid "Chat" +msgstr "Parla" + +#: src/guiKeyChangeMenu.cpp:236 +msgid "Toggle fly" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:251 +msgid "Toggle fast" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:266 +msgid "Range select" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:283 +msgid "Print stacks" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:298 +msgid "Save" +msgstr "Salva" + +#: src/guiKeyChangeMenu.cpp:304 src/guiKeyChangeMenu.h:33 +msgid "Cancel" +msgstr "Annulla" + +#: src/guiKeyChangeMenu.cpp:537 src/guiKeyChangeMenu.cpp:542 +#: src/guiKeyChangeMenu.cpp:547 src/guiKeyChangeMenu.cpp:552 +#: src/guiKeyChangeMenu.cpp:557 src/guiKeyChangeMenu.cpp:562 +#: src/guiKeyChangeMenu.cpp:567 src/guiKeyChangeMenu.cpp:572 +#: src/guiKeyChangeMenu.cpp:577 src/guiKeyChangeMenu.cpp:582 +#: src/guiKeyChangeMenu.cpp:587 src/guiKeyChangeMenu.cpp:592 +#: src/guiKeyChangeMenu.cpp:597 +msgid "press Key" +msgstr "premi tasto" + +#: src/guiKeyChangeMenu.h:33 +msgid "Left Button" +msgstr "Tasto sinistro" + +#: src/guiKeyChangeMenu.h:33 +msgid "Middle Button" +msgstr "Tasto centrale" + +#: src/guiKeyChangeMenu.h:33 +msgid "Right Button" +msgstr "Tasto destro" + +#: src/guiKeyChangeMenu.h:33 +msgid "X Button 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Back" +msgstr "Indietro" + +#: src/guiKeyChangeMenu.h:34 +msgid "Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Return" +msgstr "Invio" + +#: src/guiKeyChangeMenu.h:34 +msgid "Tab" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "X Button 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Capital" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Kana" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Pause" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Convert" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Escape" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Final" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Junja" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Kanji" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Nonconvert" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Accept" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "End" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Home" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Mode Change" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Next" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Priot" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Space" +msgstr "Spazio" + +#: src/guiKeyChangeMenu.h:38 +msgid "Down" +msgstr "Giù" + +#: src/guiKeyChangeMenu.h:38 +msgid "Execute" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Print" +msgstr "Stampa" + +#: src/guiKeyChangeMenu.h:38 +msgid "Select" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Up" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Delete" +msgstr "Cancella" + +#: src/guiKeyChangeMenu.h:39 +msgid "Help" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Insert" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Snapshot" +msgstr "" + +#: src/guiKeyChangeMenu.h:42 +msgid "Left Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Apps" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 0" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Right Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Sleep" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 3" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 4" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 5" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 6" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 7" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad *" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad +" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad -" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad /" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 8" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 9" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Num Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Scroll Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Left Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Right Shight" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Comma" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Minus" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Period" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Plus" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "Attn" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "CrSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Erase OEF" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "ExSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "OEM Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "PA1" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Play" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Zoom" +msgstr "" + +#: src/guiMainMenu.cpp:181 +msgid "Name/Password" +msgstr "Nome/Password" + +#: src/guiMainMenu.cpp:206 +msgid "Address/Port" +msgstr "Indirizzo/Porta" + +#: src/guiMainMenu.cpp:228 +msgid "Leave address blank to start a local server." +msgstr "Lascia vuoto l'indirizzo per avviare un server locale" + +#: src/guiMainMenu.cpp:235 +msgid "Fancy trees" +msgstr "Alberi strani" + +#: src/guiMainMenu.cpp:241 +msgid "Smooth Lighting" +msgstr "" + +#: src/guiMainMenu.cpp:249 +msgid "Start Game / Connect" +msgstr "Avvia Gioco / Connetti" + +#: src/guiMainMenu.cpp:258 +msgid "Change keys" +msgstr "Modifica tasti" + +#: src/guiMainMenu.cpp:281 +msgid "Creative Mode" +msgstr "Modalità creativa" + +#: src/guiMainMenu.cpp:287 +msgid "Enable Damage" +msgstr "Attiva Danno" + +#: src/guiMainMenu.cpp:295 +msgid "Delete map" +msgstr "Cancella mappa" + +#: src/guiMessageMenu.cpp:94 src/guiTextInputMenu.cpp:112 +msgid "Proceed" +msgstr "Procedi" + +#: src/guiPasswordChange.cpp:103 +msgid "Old Password" +msgstr "Vecchia password" + +#: src/guiPasswordChange.cpp:120 +msgid "New Password" +msgstr "Nuova password" + +#: src/guiPasswordChange.cpp:136 +msgid "Confirm Password" +msgstr "Conferma password" + +#: src/guiPasswordChange.cpp:153 +msgid "Change" +msgstr "Modifica" + +#: src/guiPasswordChange.cpp:162 +msgid "Passwords do not match!" +msgstr "Le password non corrispondono!" + +#: src/guiPauseMenu.cpp:111 +msgid "Continue" +msgstr "Continua" + +#: src/guiPauseMenu.cpp:118 +msgid "Change Password" +msgstr "Cambia password" + +#: src/guiPauseMenu.cpp:125 +msgid "Disconnect" +msgstr "Disconnetti" + +#: src/guiPauseMenu.cpp:132 +msgid "Exit to OS" +msgstr "Esci al S.O." + +#: src/guiPauseMenu.cpp:139 +#, fuzzy +msgid "" +"Default Controls:\n" +"- WASD: Walk\n" +"- Mouse left: dig/hit\n" +"- Mouse right: place/use\n" +"- Mouse wheel: select item\n" +"- 0...9: select item\n" +"- Shift: sneak\n" +"- R: Toggle viewing all loaded chunks\n" +"- I: Inventory menu\n" +"- ESC: This menu\n" +"- T: Chat\n" +msgstr "" +"Tasti:\n" +"- WASD: Cammina\n" +"- Mouse left: scava blocchi\n" +"- Mouse right: piazza blocchi\n" +"- Mouse wheel: seleziona oggetto\n" +"- 0...9: seleziona oggetto\n" +"- Shift: furtivo\n" +"- R: (Dis)attiva motra tutti i blocchi caricati\n" +"- I: Inventario\n" +"- ESC: Questo menu\n" +"- T: Parla\n" diff --git a/po/minetest.pot b/po/minetest.pot new file mode 100644 index 0000000..b4ae8ee --- /dev/null +++ b/po/minetest.pot @@ -0,0 +1,487 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: minetest\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2011-08-02 12:36+0200\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=CHARSET\n" +"Content-Transfer-Encoding: 8bit\n" + +#: src/guiKeyChangeMenu.cpp:84 +msgid "KEYBINDINGS" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:94 +msgid "Forward" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:111 +msgid "Backward" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:127 src/guiKeyChangeMenu.h:38 +msgid "Left" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:142 src/guiKeyChangeMenu.h:38 +msgid "Right" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:158 +msgid "Use" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:173 +msgid "Sneak" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:189 +msgid "Jump" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:204 +msgid "Inventory" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:220 +msgid "Chat" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:236 +msgid "Toggle fly" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:251 +msgid "Toggle fast" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:266 +msgid "Range select" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:283 +msgid "Print stacks" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:298 +msgid "Save" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:304 src/guiKeyChangeMenu.h:33 +msgid "Cancel" +msgstr "" + +#: src/guiKeyChangeMenu.cpp:537 src/guiKeyChangeMenu.cpp:542 +#: src/guiKeyChangeMenu.cpp:547 src/guiKeyChangeMenu.cpp:552 +#: src/guiKeyChangeMenu.cpp:557 src/guiKeyChangeMenu.cpp:562 +#: src/guiKeyChangeMenu.cpp:567 src/guiKeyChangeMenu.cpp:572 +#: src/guiKeyChangeMenu.cpp:577 src/guiKeyChangeMenu.cpp:582 +#: src/guiKeyChangeMenu.cpp:587 src/guiKeyChangeMenu.cpp:592 +#: src/guiKeyChangeMenu.cpp:597 +msgid "press Key" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Left Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Middle Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "Right Button" +msgstr "" + +#: src/guiKeyChangeMenu.h:33 +msgid "X Button 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Back" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Return" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "Tab" +msgstr "" + +#: src/guiKeyChangeMenu.h:34 +msgid "X Button 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Capital" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Kana" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Pause" +msgstr "" + +#: src/guiKeyChangeMenu.h:35 +msgid "Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Convert" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Escape" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Final" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Junja" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Kanji" +msgstr "" + +#: src/guiKeyChangeMenu.h:36 +msgid "Nonconvert" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Accept" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "End" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Home" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Mode Change" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Next" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Priot" +msgstr "" + +#: src/guiKeyChangeMenu.h:37 +msgid "Space" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Down" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Execute" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Print" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Select" +msgstr "" + +#: src/guiKeyChangeMenu.h:38 +msgid "Up" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Delete" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Help" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Insert" +msgstr "" + +#: src/guiKeyChangeMenu.h:39 +msgid "Snapshot" +msgstr "" + +#: src/guiKeyChangeMenu.h:42 +msgid "Left Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Apps" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 0" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Numpad 1" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Right Windows" +msgstr "" + +#: src/guiKeyChangeMenu.h:43 +msgid "Sleep" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 2" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 3" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 4" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 5" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 6" +msgstr "" + +#: src/guiKeyChangeMenu.h:44 +msgid "Numpad 7" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad *" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad +" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad -" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad /" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 8" +msgstr "" + +#: src/guiKeyChangeMenu.h:45 +msgid "Numpad 9" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Num Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:49 +msgid "Scroll Lock" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Left Shift" +msgstr "" + +#: src/guiKeyChangeMenu.h:50 +msgid "Right Shight" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Left Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Control" +msgstr "" + +#: src/guiKeyChangeMenu.h:51 +msgid "Right Menu" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Comma" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Minus" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Period" +msgstr "" + +#: src/guiKeyChangeMenu.h:53 +msgid "Plus" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "Attn" +msgstr "" + +#: src/guiKeyChangeMenu.h:57 +msgid "CrSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Erase OEF" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "ExSel" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "OEM Clear" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "PA1" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Play" +msgstr "" + +#: src/guiKeyChangeMenu.h:58 +msgid "Zoom" +msgstr "" + +#: src/guiMainMenu.cpp:181 +msgid "Name/Password" +msgstr "" + +#: src/guiMainMenu.cpp:206 +msgid "Address/Port" +msgstr "" + +#: src/guiMainMenu.cpp:228 +msgid "Leave address blank to start a local server." +msgstr "" + +#: src/guiMainMenu.cpp:235 +msgid "Fancy trees" +msgstr "" + +#: src/guiMainMenu.cpp:241 +msgid "Smooth Lighting" +msgstr "" + +#: src/guiMainMenu.cpp:249 +msgid "Start Game / Connect" +msgstr "" + +#: src/guiMainMenu.cpp:258 +msgid "Change keys" +msgstr "" + +#: src/guiMainMenu.cpp:281 +msgid "Creative Mode" +msgstr "" + +#: src/guiMainMenu.cpp:287 +msgid "Enable Damage" +msgstr "" + +#: src/guiMainMenu.cpp:295 +msgid "Delete map" +msgstr "" + +#: src/guiMessageMenu.cpp:94 src/guiTextInputMenu.cpp:112 +msgid "Proceed" +msgstr "" + +#: src/guiPasswordChange.cpp:103 +msgid "Old Password" +msgstr "" + +#: src/guiPasswordChange.cpp:120 +msgid "New Password" +msgstr "" + +#: src/guiPasswordChange.cpp:136 +msgid "Confirm Password" +msgstr "" + +#: src/guiPasswordChange.cpp:153 +msgid "Change" +msgstr "" + +#: src/guiPasswordChange.cpp:162 +msgid "Passwords do not match!" +msgstr "" + +#: src/guiPauseMenu.cpp:111 +msgid "Continue" +msgstr "" + +#: src/guiPauseMenu.cpp:118 +msgid "Change Password" +msgstr "" + +#: src/guiPauseMenu.cpp:125 +msgid "Disconnect" +msgstr "" + +#: src/guiPauseMenu.cpp:132 +msgid "Exit to OS" +msgstr "" + +#: src/guiPauseMenu.cpp:139 +msgid "" +"Default Controls:\n" +"- WASD: Walk\n" +"- Mouse left: dig/hit\n" +"- Mouse right: place/use\n" +"- Mouse wheel: select item\n" +"- 0...9: select item\n" +"- Shift: sneak\n" +"- R: Toggle viewing all loaded chunks\n" +"- I: Inventory menu\n" +"- ESC: This menu\n" +"- T: Chat\n" +msgstr "" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..c18bb64 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,352 @@ +project(minetest) +cmake_minimum_required( VERSION 2.6 ) + +if(RUN_IN_PLACE) + add_definitions ( -DRUN_IN_PLACE ) +endif(RUN_IN_PLACE) + +# user-visible option to enable/disable gettext usage +OPTION(ENABLE_GETTEXT "Use GetText for internationalization" ON) + +# this is only set to 1 if gettext is enabled _and_ available +set(USE_GETTEXT 0) + +find_package(GettextLib) + +if(GETTEXT_FOUND AND ENABLE_GETTEXT) + message(STATUS "gettext include path: ${GETTEXT_INCLUDE_DIR}") + message(STATUS "gettext msgfmt path: ${GETTEXT_MSGFMT}") + if(WIN32) + message(STATUS "gettext library: ${GETTEXT_LIBRARY}") + message(STATUS "gettext dll: ${GETTEXT_DLL}") + message(STATUS "gettext iconv dll: ${GETTEXT_ICONV_DLL}") + endif() + set(USE_GETTEXT 1) + message(STATUS "GetText enabled; locales found: ${GETTEXT_AVAILABLE_LOCALES}") +elseif(GETTEXT_FOUND AND NOT ENABLE_GETTEXT) + MESSAGE(STATUS "GetText found but disabled;") +else(GETTEXT_FOUND AND ENABLE_GETTEXT) + message(STATUS "GetText disabled") +endif(GETTEXT_FOUND AND ENABLE_GETTEXT) + +if(NOT MSVC) + set(USE_GPROF 0 CACHE BOOL "Use -pg flag for g++") +endif() + +# Use cmake_config.h +add_definitions ( -DUSE_CMAKE_CONFIG_H ) + +if(WIN32) + # Windows + if(MSVC) # MSVC Specifics + # Surpress some useless warnings + add_definitions ( /D "_CRT_SECURE_NO_DEPRECATE" /W1 ) + else() # Probably MinGW = GCC + set(PLATFORM_LIBS ws2_32.lib) + endif() + # Zlib stuff + set(ZLIB_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/../../zlib/zlib-1.2.5" + CACHE PATH "Zlib include directory") + set(ZLIB_LIBRARIES "${PROJECT_SOURCE_DIR}/../../zlib125dll/dll32/zlibwapi.lib" + CACHE FILEPATH "Path to zlibwapi.lib") + set(ZLIB_DLL "${PROJECT_SOURCE_DIR}/../../zlib125dll/dll32/zlibwapi.dll" + CACHE FILEPATH "Path to zlibwapi.dll (for installation)") + set(IRRLICHT_SOURCE_DIR "${PROJECT_SOURCE_DIR}/../../irrlicht-1.7.2" + CACHE PATH "irrlicht dir") +else() + # Unix probably + if(BUILD_CLIENT) + find_package(X11 REQUIRED) + find_package(OpenGL REQUIRED) + find_package(JPEG REQUIRED) + find_package(BZip2 REQUIRED) + find_package(PNG REQUIRED) + if(APPLE) + FIND_LIBRARY(CARBON_LIB Carbon) + FIND_LIBRARY(COCOA_LIB Cocoa) + FIND_LIBRARY(IOKIT_LIB IOKit) + mark_as_advanced( + CARBON_LIB + COCOA_LIB + IOKIT_LIB + ) + SET(CLIENT_PLATFORM_LIBS ${CLIENT_PLATFORM_LIBS} ${CARBON_LIB} ${COCOA_LIB} ${IOKIT_LIB}) + endif(APPLE) + endif(BUILD_CLIENT) + find_package(ZLIB REQUIRED) + set(PLATFORM_LIBS -lpthread ${CMAKE_DL_LIBS}) + #set(CLIENT_PLATFORM_LIBS -lXxf86vm) + # This way Xxf86vm is found on OpenBSD too + find_library(XXF86VM_LIBRARY Xxf86vm) + set(CLIENT_PLATFORM_LIBS ${CLIENT_PLATFORM_LIBS} ${XXF86VM_LIBRARY}) +endif() + +find_package(Jthread REQUIRED) +find_package(Sqlite3 REQUIRED) + +configure_file( + "${PROJECT_SOURCE_DIR}/cmake_config.h.in" + "${PROJECT_BINARY_DIR}/cmake_config.h" +) + +set(common_SRCS + content_sao.cpp + mapgen.cpp + content_inventory.cpp + content_nodemeta.cpp + content_craft.cpp + content_mapblock.cpp + content_mapnode.cpp + auth.cpp + collision.cpp + nodemetadata.cpp + serverobject.cpp + noise.cpp + mineral.cpp + porting.cpp + materials.cpp + defaultsettings.cpp + mapnode.cpp + voxel.cpp + mapblockobject.cpp + inventory.cpp + debug.cpp + serialization.cpp + light.cpp + filesys.cpp + connection.cpp + environment.cpp + server.cpp + servercommand.cpp + socket.cpp + mapblock.cpp + mapsector.cpp + map.cpp + player.cpp + utility.cpp + test.cpp + sha1.cpp + base64.cpp + ban.cpp +) + +# This gives us the icon +if(WIN32 AND MSVC) + set(common_SRCS ${common_SRCS} winresource.rc) +endif() + +# Client sources +set(minetest_SRCS + ${common_SRCS} + content_cao.cpp + mapblock_mesh.cpp + farmesh.cpp + keycode.cpp + clouds.cpp + clientobject.cpp + guiMainMenu.cpp + guiKeyChangeMenu.cpp + guiMessageMenu.cpp + guiTextInputMenu.cpp + guiInventoryMenu.cpp + guiPauseMenu.cpp + guiPasswordChange.cpp + client.cpp + tile.cpp + game.cpp + main.cpp +) + +# Server sources +set(minetestserver_SRCS + ${common_SRCS} + servermain.cpp +) + +include_directories( + ${PROJECT_BINARY_DIR} + ${IRRLICHT_INCLUDE_DIR} + ${ZLIB_INCLUDE_DIR} + ${CMAKE_BUILD_TYPE} + ${PNG_INCLUDE_DIR} + ${GETTEXT_INCLUDE_DIR} + ${JTHREAD_INCLUDE_DIR} + ${SQLITE3_INCLUDE_DIR} +) + +set(EXECUTABLE_OUTPUT_PATH "${CMAKE_SOURCE_DIR}/bin") + +if(BUILD_CLIENT) + add_executable(${PROJECT_NAME} ${minetest_SRCS}) + target_link_libraries( + ${PROJECT_NAME} + ${ZLIB_LIBRARIES} + ${IRRLICHT_LIBRARY} + ${OPENGL_LIBRARIES} + ${JPEG_LIBRARIES} + ${BZIP2_LIBRARIES} + ${PNG_LIBRARIES} + ${X11_LIBRARIES} + ${GETTEXT_LIBRARY} + ${JTHREAD_LIBRARY} + ${SQLITE3_LIBRARY} + ${PLATFORM_LIBS} + ${CLIENT_PLATFORM_LIBS} + ) +endif(BUILD_CLIENT) + +if(BUILD_SERVER) + add_executable(${PROJECT_NAME}server ${minetestserver_SRCS}) + target_link_libraries( + ${PROJECT_NAME}server + ${ZLIB_LIBRARIES} + ${JTHREAD_LIBRARY} + ${SQLITE3_LIBRARY} + ${PLATFORM_LIBS} + ) +endif(BUILD_SERVER) + +# +# Set some optimizations and tweaks +# + +include(CheckCXXCompilerFlag) + +if(MSVC) + # Visual Studio + + # EHa enables SEH exceptions (used for catching segfaults) + set(CMAKE_CXX_FLAGS_RELEASE "/EHa /MD /O2 /Ob2 /Oi /Ot /Oy /GL /FD /MT /GS- /arch:SSE /fp:fast /D NDEBUG /D _HAS_ITERATOR_DEBUGGING=0 /TP") + #set(CMAKE_EXE_LINKER_FLAGS_RELEASE "/LTCG /NODEFAULTLIB:\"libcmtd.lib\" /NODEFAULTLIB:\"libcmt.lib\"") + set(CMAKE_EXE_LINKER_FLAGS_RELEASE "/LTCG") + + # Debug build doesn't catch exceptions by itself + # Add some optimizations because otherwise it's VERY slow + set(CMAKE_CXX_FLAGS_DEBUG "/MDd /Zi /Ob0 /Od /RTC1") + + if(BUILD_SERVER) + set_target_properties(${PROJECT_NAME}server PROPERTIES + COMPILE_DEFINITIONS "SERVER") + endif(BUILD_SERVER) + +else() + # Probably GCC + + if(WARN_ALL) + set(RELEASE_WARNING_FLAGS "-Wall") + else() + set(RELEASE_WARNING_FLAGS "") + endif() + + if(NOT APPLE AND NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + CHECK_CXX_COMPILER_FLAG("-Wno-unused-but-set-variable" HAS_UNUSED_BUT_SET_VARIABLE_WARNING) + if(HAS_UNUSED_BUT_SET_VARIABLE_WARNING) + set(WARNING_FLAGS "${WARNING_FLAGS} -Wno-unused-but-set-variable") + endif(HAS_UNUSED_BUT_SET_VARIABLE_WARNING) + endif() + + if(APPLE) + set(CMAKE_OSX_ARCHITECTURES i386 CACHE STRING "do not build for 64-bit" FORCE) + set(ARCH i386) + endif() + + set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG ${RELEASE_WARNING_FLAGS} ${WARNING_FLAGS} -O3 -ffast-math -Wall -fomit-frame-pointer -pipe -funroll-loops") + set(CMAKE_CXX_FLAGS_DEBUG "-g -O1 -Wall ${WARNING_FLAGS}") + + if(USE_GPROF) + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -pg") + endif() + + if(BUILD_SERVER) + set_target_properties(${PROJECT_NAME}server PROPERTIES + COMPILE_DEFINITIONS "SERVER") + endif(BUILD_SERVER) + +endif() + +#MESSAGE(STATUS "CMAKE_CXX_FLAGS_RELEASE=${CMAKE_CXX_FLAGS_RELEASE}") +#MESSAGE(STATUS "CMAKE_CXX_FLAGS_DEBUG=${CMAKE_CXX_FLAGS_DEBUG}") + +# +# Installation +# + +# Example configuration file +install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/../minetest.conf.example" DESTINATION ${EXAMPLE_CONF_DIR}) + +if(BUILD_CLIENT) + install(TARGETS ${PROJECT_NAME} DESTINATION ${BINDIR}) + + file(GLOB images "${CMAKE_CURRENT_SOURCE_DIR}/../data/*.png") + + install(FILES ${images} DESTINATION ${DATADIR}) + + if(USE_GETTEXT) + foreach(LOCALE ${GETTEXT_AVAILABLE_LOCALES}) + set_mo_paths(MO_BUILD_PATH MO_DEST_PATH ${LOCALE}) + set(MO_BUILD_PATH "${MO_BUILD_PATH}/${PROJECT_NAME}.mo") + install(FILES ${MO_BUILD_PATH} DESTINATION ${MO_DEST_PATH}) + endforeach(LOCALE ${GETTEXT_AVAILABLE_LOCALES}) + endif() + + if(WIN32) + if(DEFINED IRRLICHT_DLL) + install(FILES ${IRRLICHT_DLL} DESTINATION ${BINDIR}) + endif() + if(DEFINED ZLIB_DLL) + install(FILES ${ZLIB_DLL} DESTINATION ${BINDIR}) + endif() + if(USE_GETTEXT) + if(DEFINED GETTEXT_DLL) + install(FILES ${GETTEXT_DLL} DESTINATION ${BINDIR}) + endif() + if(DEFINED GETTEXT_ICONV_DLL) + install(FILES ${GETTEXT_ICONV_DLL} DESTINATION ${BINDIR}) + endif() + endif(USE_GETTEXT) + endif() +endif(BUILD_CLIENT) + +if(BUILD_SERVER) + install(TARGETS ${PROJECT_NAME}server DESTINATION ${BINDIR}) +endif(BUILD_SERVER) + +if (USE_GETTEXT) + set(MO_FILES) + + foreach(LOCALE ${GETTEXT_AVAILABLE_LOCALES}) + set(PO_FILE_PATH "${GETTEXT_PO_PATH}/${LOCALE}/minetest.po") + set_mo_paths(MO_BUILD_PATH MO_DEST_PATH ${LOCALE}) + set(MO_FILE_PATH "${MO_BUILD_PATH}/${PROJECT_NAME}.mo") + + add_custom_command(OUTPUT ${MO_BUILD_PATH} + COMMAND ${CMAKE_COMMAND} -E make_directory ${MO_BUILD_PATH} + COMMENT "mo-update [${LOCALE}]: Creating locale directory.") + + add_custom_command( + OUTPUT ${MO_FILE_PATH} + COMMAND ${GETTEXT_MSGFMT} -o ${MO_FILE_PATH} ${PO_FILE_PATH} + DEPENDS ${MO_BUILD_PATH} ${PO_FILE_PATH} + WORKING_DIRECTORY "${GETTEXT_PO_PATH}/${LOCALE}" + COMMENT "mo-update [${LOCALE}]: Creating mo file." + ) + + set(MO_FILES ${MO_FILES} ${MO_FILE_PATH}) + endforeach(LOCALE ${GETTEXT_AVAILABLE_LOCALES}) + + add_custom_target(translations ALL COMMENT "mo update" DEPENDS ${MO_FILES}) +endif(USE_GETTEXT) + +# Subdirectories + +if (JTHREAD_FOUND) +else (JTHREAD_FOUND) + add_subdirectory(jthread) +endif (JTHREAD_FOUND) + +if (SQLITE3_FOUND) +else (SQLITE3_FOUND) +add_subdirectory(sqlite) +endif (SQLITE3_FOUND) + +#end diff --git a/src/activeobject.h b/src/activeobject.h new file mode 100644 index 0000000..09ee23a --- /dev/null +++ b/src/activeobject.h @@ -0,0 +1,70 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef ACTIVEOBJECT_HEADER +#define ACTIVEOBJECT_HEADER + +#include "common_irrlicht.h" +#include + +#define ACTIVEOBJECT_TYPE_INVALID 0 +// Other types are defined in content_object.h + +struct ActiveObjectMessage +{ + ActiveObjectMessage(u16 id_, bool reliable_=true, std::string data_=""): + id(id_), + reliable(reliable_), + datastring(data_) + {} + + u16 id; + bool reliable; + std::string datastring; +}; + +/* + Parent class for ServerActiveObject and ClientActiveObject +*/ +class ActiveObject +{ +public: + ActiveObject(u16 id): + m_id(id) + { + } + + u16 getId() + { + return m_id; + } + + void setId(u16 id) + { + m_id = id; + } + + virtual u8 getType() const = 0; + +protected: + u16 m_id; // 0 is invalid, "no id" +}; + +#endif + diff --git a/src/auth.cpp b/src/auth.cpp new file mode 100644 index 0000000..dc74041 --- /dev/null +++ b/src/auth.cpp @@ -0,0 +1,268 @@ +/* +Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "auth.h" +#include +#include +//#include "main.h" // for g_settings +#include +#include "strfnd.h" +#include "debug.h" + +// Convert a privileges value into a human-readable string, +// with each component separated by a comma. +std::string privsToString(u64 privs) +{ + std::ostringstream os(std::ios_base::binary); + if(privs & PRIV_BUILD) + os<<"build,"; + if(privs & PRIV_TELEPORT) + os<<"teleport,"; + if(privs & PRIV_SETTIME) + os<<"settime,"; + if(privs & PRIV_PRIVS) + os<<"privs,"; + if(privs & PRIV_SHOUT) + os<<"shout,"; + if(privs & PRIV_BAN) + os<<"ban,"; + if(os.tellp()) + { + // Drop the trailing comma. (Why on earth can't + // you truncate a C++ stream anyway???) + std::string tmp = os.str(); + return tmp.substr(0, tmp.length() -1); + } + return os.str(); +} + +// Converts a comma-seperated list of privilege values into a +// privileges value. The reverse of privsToString(). Returns +// PRIV_INVALID if there is anything wrong with the input. +u64 stringToPrivs(std::string str) +{ + u64 privs=0; + Strfnd f(str); + while(f.atend() == false) + { + std::string s = trim(f.next(",")); + if(s == "build") + privs |= PRIV_BUILD; + else if(s == "teleport") + privs |= PRIV_TELEPORT; + else if(s == "settime") + privs |= PRIV_SETTIME; + else if(s == "privs") + privs |= PRIV_PRIVS; + else if(s == "shout") + privs |= PRIV_SHOUT; + else if(s == "ban") + privs |= PRIV_BAN; + else + return PRIV_INVALID; + } + return privs; +} + +AuthManager::AuthManager(const std::string &authfilepath): + m_authfilepath(authfilepath), + m_modified(false) +{ + m_mutex.Init(); + + try{ + load(); + } + catch(SerializationError &e) + { + dstream<<"WARNING: AuthManager: creating " + <::Iterator + i = m_authdata.getIterator(); + i.atEnd()==false; i++) + { + std::string name = i.getNode()->getKey(); + if(name == "") + continue; + AuthData ad = i.getNode()->getValue(); + os<::Node *n; + n = m_authdata.find(username); + if(n == NULL) + return false; + return true; +} + +void AuthManager::set(const std::string &username, AuthData ad) +{ + JMutexAutoLock lock(m_mutex); + + m_authdata[username] = ad; + + m_modified = true; +} + +void AuthManager::add(const std::string &username) +{ + JMutexAutoLock lock(m_mutex); + + m_authdata[username] = AuthData(); + + m_modified = true; +} + +std::string AuthManager::getPassword(const std::string &username) +{ + JMutexAutoLock lock(m_mutex); + + core::map::Node *n; + n = m_authdata.find(username); + if(n == NULL) + throw AuthNotFoundException(""); + + return n->getValue().pwd; +} + +void AuthManager::setPassword(const std::string &username, + const std::string &password) +{ + JMutexAutoLock lock(m_mutex); + + core::map::Node *n; + n = m_authdata.find(username); + if(n == NULL) + throw AuthNotFoundException(""); + + AuthData ad = n->getValue(); + ad.pwd = password; + n->setValue(ad); + + m_modified = true; +} + +u64 AuthManager::getPrivs(const std::string &username) +{ + JMutexAutoLock lock(m_mutex); + + core::map::Node *n; + n = m_authdata.find(username); + if(n == NULL) + throw AuthNotFoundException(""); + + return n->getValue().privs; +} + +void AuthManager::setPrivs(const std::string &username, u64 privs) +{ + JMutexAutoLock lock(m_mutex); + + core::map::Node *n; + n = m_authdata.find(username); + if(n == NULL) + throw AuthNotFoundException(""); + + AuthData ad = n->getValue(); + ad.privs = privs; + n->setValue(ad); + + m_modified = true; +} + +bool AuthManager::isModified() +{ + JMutexAutoLock lock(m_mutex); + return m_modified; +} + + diff --git a/src/auth.h b/src/auth.h new file mode 100644 index 0000000..5ea697a --- /dev/null +++ b/src/auth.h @@ -0,0 +1,102 @@ +/* +Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef AUTH_HEADER +#define AUTH_HEADER + +#include +#include +#include +#include "common_irrlicht.h" +#include "exceptions.h" + +// Player privileges. These form a bitmask stored in the privs field +// of the player, and define things they're allowed to do. See also +// the static methods Player::privsToString and stringToPrivs that +// convert these to human-readable form. +const u64 PRIV_BUILD = 1; // Can build - i.e. modify the world +const u64 PRIV_TELEPORT = 2; // Can teleport +const u64 PRIV_SETTIME = 4; // Can set the time +const u64 PRIV_PRIVS = 8; // Can grant and revoke privileges +const u64 PRIV_SERVER = 16; // Can manage the server (e.g. shutodwn + // ,settings) +const u64 PRIV_SHOUT = 32; // Can broadcast chat messages to all + // players +const u64 PRIV_BAN = 64; // Can ban players + +// Default privileges - these can be overriden for new players using the +// config option "default_privs" - however, this value still applies for +// players that existed before the privileges system was added. +const u64 PRIV_DEFAULT = PRIV_BUILD|PRIV_SHOUT; +const u64 PRIV_ALL = 0x7FFFFFFFFFFFFFFFULL; +const u64 PRIV_INVALID = 0x8000000000000000ULL; + +// Convert a privileges value into a human-readable string, +// with each component separated by a comma. +std::string privsToString(u64 privs); + +// Converts a comma-seperated list of privilege values into a +// privileges value. The reverse of privsToString(). Returns +// PRIV_INVALID if there is anything wrong with the input. +u64 stringToPrivs(std::string str); + +struct AuthData +{ + std::string pwd; + u64 privs; + + AuthData(): + privs(PRIV_DEFAULT) + { + } +}; + +class AuthNotFoundException : public BaseException +{ +public: + AuthNotFoundException(const char *s): + BaseException(s) + {} +}; + +class AuthManager +{ +public: + AuthManager(const std::string &authfilepath); + ~AuthManager(); + void load(); + void save(); + bool exists(const std::string &username); + void set(const std::string &username, AuthData ad); + void add(const std::string &username); + std::string getPassword(const std::string &username); + void setPassword(const std::string &username, + const std::string &password); + u64 getPrivs(const std::string &username); + void setPrivs(const std::string &username, u64 privs); + bool isModified(); +private: + JMutex m_mutex; + std::string m_authfilepath; + core::map m_authdata; + bool m_modified; +}; + +#endif + diff --git a/src/ban.cpp b/src/ban.cpp new file mode 100644 index 0000000..3989762 --- /dev/null +++ b/src/ban.cpp @@ -0,0 +1,163 @@ +/* +Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "ban.h" +#include +#include +#include +#include +#include "strfnd.h" +#include "debug.h" + +BanManager::BanManager(const std::string &banfilepath): + m_banfilepath(banfilepath), + m_modified(false) +{ + m_mutex.Init(); + try{ + load(); + } + catch(SerializationError &e) + { + dstream<<"WARNING: BanManager: creating " + <::iterator + i = m_ips.begin(); + i != m_ips.end(); i++) + { + os<first<<"|"<second<<"\n"; + } + m_modified = false; +} + +bool BanManager::isIpBanned(const std::string &ip) +{ + JMutexAutoLock lock(m_mutex); + return m_ips.find(ip) != m_ips.end(); +} + +std::string BanManager::getBanDescription(const std::string &ip_or_name) +{ + JMutexAutoLock lock(m_mutex); + std::string s = ""; + for(std::map::iterator + i = m_ips.begin(); + i != m_ips.end(); i++) + { + if(i->first == ip_or_name || i->second == ip_or_name + || ip_or_name == "") + s += i->first + "|" + i->second + ", "; + } + s = s.substr(0, s.size()-2); + return s; +} + +std::string BanManager::getBanName(const std::string &ip) +{ + JMutexAutoLock lock(m_mutex); + std::map::iterator i = m_ips.find(ip); + if(i == m_ips.end()) + return ""; + return i->second; +} + +void BanManager::add(const std::string &ip, const std::string &name) +{ + JMutexAutoLock lock(m_mutex); + m_ips[ip] = name; + m_modified = true; +} + +void BanManager::remove(const std::string &ip_or_name) +{ + JMutexAutoLock lock(m_mutex); + //m_ips.erase(m_ips.find(ip)); + // Find out all ip-name pairs that match the ip or name + std::set ips_to_delete; + for(std::map::iterator + i = m_ips.begin(); + i != m_ips.end(); i++) + { + if(i->first == ip_or_name || i->second == ip_or_name) + ips_to_delete.insert(i->first); + } + // Erase them + for(std::set::iterator + i = ips_to_delete.begin(); + i != ips_to_delete.end(); i++) + { + m_ips.erase(*i); + } + m_modified = true; +} + + +bool BanManager::isModified() +{ + JMutexAutoLock lock(m_mutex); + return m_modified; +} + diff --git a/src/ban.h b/src/ban.h new file mode 100644 index 0000000..8fdcf4c --- /dev/null +++ b/src/ban.h @@ -0,0 +1,52 @@ +/* +Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef BAN_HEADER +#define BAN_HEADER + +#include +#include +#include +#include +#include "common_irrlicht.h" +#include "exceptions.h" + +class BanManager +{ +public: + BanManager(const std::string &bannfilepath); + ~BanManager(); + void load(); + void save(); + bool isIpBanned(const std::string &ip); + // Supplying ip_or_name = "" lists all bans. + std::string getBanDescription(const std::string &ip_or_name); + std::string getBanName(const std::string &ip); + void add(const std::string &ip, const std::string &name); + void remove(const std::string &ip_or_name); + bool isModified(); +private: + JMutex m_mutex; + std::string m_banfilepath; + std::map m_ips; + bool m_modified; + +}; + +#endif diff --git a/src/base64.cpp b/src/base64.cpp new file mode 100644 index 0000000..0dfba50 --- /dev/null +++ b/src/base64.cpp @@ -0,0 +1,124 @@ +/* + base64.cpp and base64.h + + Copyright (C) 2004-2008 René Nyffenegger + + This source code is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this source code must not be misrepresented; you must not + claim that you wrote the original source code. If you use this source code + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original source code. + + 3. This notice may not be removed or altered from any source distribution. + + René Nyffenegger rene.nyffenegger@adp-gmbh.ch + +*/ + +#include "base64.h" +#include + +static const std::string base64_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + +static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { + std::string ret; + int i = 0; + int j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (in_len--) { + char_array_3[i++] = *(bytes_to_encode++); + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for(i = 0; (i <4) ; i++) + ret += base64_chars[char_array_4[i]]; + i = 0; + } + } + + if (i) + { + for(j = i; j < 3; j++) + char_array_3[j] = '\0'; + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (j = 0; (j < i + 1); j++) + ret += base64_chars[char_array_4[j]]; + + // Don't pad it with = + /*while((i++ < 3)) + ret += '=';*/ + + } + + return ret; + +} + +std::string base64_decode(std::string const& encoded_string) { + int in_len = encoded_string.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; in_++; + if (i ==4) { + for (i = 0; i <4; i++) + char_array_4[i] = base64_chars.find(char_array_4[i]); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; (i < 3); i++) + ret += char_array_3[i]; + i = 0; + } + } + + if (i) { + for (j = i; j <4; j++) + char_array_4[j] = 0; + + for (j = 0; j <4; j++) + char_array_4[j] = base64_chars.find(char_array_4[j]); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + } + + return ret; +} diff --git a/src/base64.h b/src/base64.h new file mode 100644 index 0000000..65d5db8 --- /dev/null +++ b/src/base64.h @@ -0,0 +1,4 @@ +#include + +std::string base64_encode(unsigned char const* , unsigned int len); +std::string base64_decode(std::string const& s); diff --git a/src/client.cpp b/src/client.cpp new file mode 100644 index 0000000..fcc5a0a --- /dev/null +++ b/src/client.cpp @@ -0,0 +1,2348 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "client.h" +#include "utility.h" +#include +#include "clientserver.h" +#include "jmutexautolock.h" +#include "main.h" +#include +#include "porting.h" +#include "mapsector.h" +#include "mapblock_mesh.h" +#include "mapblock.h" + +/* + QueuedMeshUpdate +*/ + +QueuedMeshUpdate::QueuedMeshUpdate(): + p(-1337,-1337,-1337), + data(NULL), + ack_block_to_server(false) +{ +} + +QueuedMeshUpdate::~QueuedMeshUpdate() +{ + if(data) + delete data; +} + +/* + MeshUpdateQueue +*/ + +MeshUpdateQueue::MeshUpdateQueue() +{ + m_mutex.Init(); +} + +MeshUpdateQueue::~MeshUpdateQueue() +{ + JMutexAutoLock lock(m_mutex); + + core::list::Iterator i; + for(i=m_queue.begin(); i!=m_queue.end(); i++) + { + QueuedMeshUpdate *q = *i; + delete q; + } +} + +/* + peer_id=0 adds with nobody to send to +*/ +void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server) +{ + DSTACK(__FUNCTION_NAME); + + assert(data); + + JMutexAutoLock lock(m_mutex); + + /* + Find if block is already in queue. + If it is, update the data and quit. + */ + core::list::Iterator i; + for(i=m_queue.begin(); i!=m_queue.end(); i++) + { + QueuedMeshUpdate *q = *i; + if(q->p == p) + { + if(q->data) + delete q->data; + q->data = data; + if(ack_block_to_server) + q->ack_block_to_server = true; + return; + } + } + + /* + Add the block + */ + QueuedMeshUpdate *q = new QueuedMeshUpdate; + q->p = p; + q->data = data; + q->ack_block_to_server = ack_block_to_server; + m_queue.push_back(q); +} + +// Returned pointer must be deleted +// Returns NULL if queue is empty +QueuedMeshUpdate * MeshUpdateQueue::pop() +{ + JMutexAutoLock lock(m_mutex); + + core::list::Iterator i = m_queue.begin(); + if(i == m_queue.end()) + return NULL; + QueuedMeshUpdate *q = *i; + m_queue.erase(i); + return q; +} + +/* + MeshUpdateThread +*/ + +void * MeshUpdateThread::Thread() +{ + ThreadStarted(); + + DSTACK(__FUNCTION_NAME); + + BEGIN_DEBUG_EXCEPTION_HANDLER + + while(getRun()) + { + /*// Wait for output queue to flush. + // Allow 2 in queue, this makes less frametime jitter. + // Umm actually, there is no much difference + if(m_queue_out.size() >= 2) + { + sleep_ms(3); + continue; + }*/ + + QueuedMeshUpdate *q = m_queue_in.pop(); + if(q == NULL) + { + sleep_ms(3); + continue; + } + + ScopeProfiler sp(&g_profiler, "mesh make"); + + scene::SMesh *mesh_new = NULL; + mesh_new = makeMapBlockMesh(q->data); + + MeshUpdateResult r; + r.p = q->p; + r.mesh = mesh_new; + r.ack_block_to_server = q->ack_block_to_server; + + /*dstream<<"MeshUpdateThread: Processed " + <<"("<p.X<<","<p.Y<<","<p.Z<<")" + <getSceneManager()->getRootSceneNode(), + device->getSceneManager(), 666), + device->getSceneManager() + ), + m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this), + m_device(device), + camera_position(0,0,0), + camera_direction(0,0,1), + m_server_ser_ver(SER_FMT_VER_INVALID), + m_inventory_updated(false), + m_time_of_day(0), + m_map_seed(0), + m_password(password), + m_access_denied(false) +{ + m_packetcounter_timer = 0.0; + //m_delete_unused_sectors_timer = 0.0; + m_connection_reinit_timer = 0.0; + m_avg_rtt_timer = 0.0; + m_playerpos_send_timer = 0.0; + m_ignore_damage_timer = 0.0; + + //m_env_mutex.Init(); + //m_con_mutex.Init(); + + m_mesh_update_thread.Start(); + + /* + Add local player + */ + { + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + Player *player = new LocalPlayer(); + + player->updateName(playername); + + m_env.addPlayer(player); + + // Initialize player in the inventory context + m_inventory_context.current_player = player; + } +} + +Client::~Client() +{ + { + //JMutexAutoLock conlock(m_con_mutex); //bulk comment-out + m_con.Disconnect(); + } + + m_mesh_update_thread.setRun(false); + while(m_mesh_update_thread.IsRunning()) + sleep_ms(100); +} + +void Client::connect(Address address) +{ + DSTACK(__FUNCTION_NAME); + //JMutexAutoLock lock(m_con_mutex); //bulk comment-out + m_con.setTimeoutMs(0); + m_con.Connect(address); +} + +bool Client::connectedAndInitialized() +{ + //JMutexAutoLock lock(m_con_mutex); //bulk comment-out + + if(m_con.Connected() == false) + return false; + + if(m_server_ser_ver == SER_FMT_VER_INVALID) + return false; + + return true; +} + +void Client::step(float dtime) +{ + DSTACK(__FUNCTION_NAME); + + // Limit a bit + if(dtime > 2.0) + dtime = 2.0; + + if(m_ignore_damage_timer > dtime) + m_ignore_damage_timer -= dtime; + else + m_ignore_damage_timer = 0.0; + + //dstream<<"Client steps "< deleted_blocks; + + float delete_unused_sectors_timeout = + g_settings.getFloat("client_delete_unused_sectors_timeout"); + + // Delete sector blocks + /*u32 num = m_env.getMap().unloadUnusedData + (delete_unused_sectors_timeout, + true, &deleted_blocks);*/ + + // Delete whole sectors + m_env.getMap().unloadUnusedData + (delete_unused_sectors_timeout, + &deleted_blocks); + + if(deleted_blocks.size() > 0) + { + /*dstream<::Iterator i = deleted_blocks.begin(); + core::list sendlist; + for(;;) + { + if(sendlist.size() == 255 || i == deleted_blocks.end()) + { + if(sendlist.size() == 0) + break; + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + u32 replysize = 2+1+6*sendlist.size(); + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_DELETEDBLOCKS); + reply[2] = sendlist.size(); + u32 k = 0; + for(core::list::Iterator + j = sendlist.begin(); + j != sendlist.end(); j++) + { + writeV3S16(&reply[2+1+6*k], *j); + k++; + } + m_con.Send(PEER_ID_SERVER, 1, reply, true); + + if(i == deleted_blocks.end()) + break; + + sendlist.clear(); + } + + sendlist.push_back(*i); + i++; + } + } + } + } +#endif + + if(connected == false) + { + float &counter = m_connection_reinit_timer; + counter -= dtime; + if(counter <= 0.0) + { + counter = 2.0; + + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + Player *myplayer = m_env.getLocalPlayer(); + assert(myplayer != NULL); + + // Send TOSERVER_INIT + // [0] u16 TOSERVER_INIT + // [2] u8 SER_FMT_VER_HIGHEST + // [3] u8[20] player_name + // [23] u8[28] password (new in some version) + // [51] u16 client network protocol version (new in some version) + SharedBuffer data(2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2); + writeU16(&data[0], TOSERVER_INIT); + writeU8(&data[2], SER_FMT_VER_HIGHEST); + + memset((char*)&data[3], 0, PLAYERNAME_SIZE); + snprintf((char*)&data[3], PLAYERNAME_SIZE, "%s", myplayer->getName()); + + /*dstream<<"Client: sending initial password hash: \""< deleted_blocks; + m_env.getMap().timerUpdate(map_timer_and_unload_dtime, + g_settings.getFloat("client_unload_unused_data_timeout"), + &deleted_blocks); + + /*if(deleted_blocks.size() > 0) + dstream<<"Client: Unloaded "<::Iterator i = deleted_blocks.begin(); + core::list sendlist; + for(;;) + { + if(sendlist.size() == 255 || i == deleted_blocks.end()) + { + if(sendlist.size() == 0) + break; + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + u32 replysize = 2+1+6*sendlist.size(); + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_DELETEDBLOCKS); + reply[2] = sendlist.size(); + u32 k = 0; + for(core::list::Iterator + j = sendlist.begin(); + j != sendlist.end(); j++) + { + writeV3S16(&reply[2+1+6*k], *j); + k++; + } + m_con.Send(PEER_ID_SERVER, 1, reply, true); + + if(i == deleted_blocks.end()) + break; + + sendlist.clear(); + } + + sendlist.push_back(*i); + i++; + } + } + + /* + Handle environment + */ + { + // 0ms + //JMutexAutoLock lock(m_env_mutex); //bulk comment-out + + // Control local player (0ms) + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + player->applyControl(dtime); + + //TimeTaker envtimer("env step", m_device); + // Step environment + m_env.step(dtime); + + /* + Handle active blocks + NOTE: These old objects are DEPRECATED. TODO: Remove + */ + for(core::map::Iterator + i = m_active_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + + MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(p); + if(block == NULL) + continue; + + // Step MapBlockObjects + block->stepObjects(dtime, false, m_env.getDayNightRatio()); + } + + /* + Get events + */ + for(;;) + { + ClientEnvEvent event = m_env.getClientEvent(); + if(event.type == CEE_NONE) + { + break; + } + else if(event.type == CEE_PLAYER_DAMAGE) + { + if(m_ignore_damage_timer <= 0) + { + u8 damage = event.player_damage.amount; + sendDamage(damage); + + // Add to ClientEvent queue + ClientEvent event; + event.type = CE_PLAYER_DAMAGE; + event.player_damage.amount = damage; + m_client_event_queue.push_back(event); + } + } + } + } + + /* + Print some info + */ + { + float &counter = m_avg_rtt_timer; + counter += dtime; + if(counter >= 10) + { + counter = 0.0; + //JMutexAutoLock lock(m_con_mutex); //bulk comment-out + // connectedAndInitialized() is true, peer exists. + con::Peer *peer = m_con.GetPeer(PEER_ID_SERVER); + dstream< 0) + { + MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_front(); + MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p); + if(block) + { + block->replaceMesh(r.mesh); + } + if(r.ack_block_to_server) + { + /*dstream<<"Client: ACK block ("< reply(replysize); + writeU16(&reply[0], TOSERVER_GOTBLOCKS); + reply[2] = 1; + writeV3S16(&reply[3], r.p); + // Send as reliable + m_con.Send(PEER_ID_SERVER, 1, reply, true); + } + } + } +} + +// Virtual methods from con::PeerHandler +void Client::peerAdded(con::Peer *peer) +{ + derr_client<<"Client::peerAdded(): peer->id=" + <id<= 2+1+6) + playerpos_s16 = readV3S16(&data[2+1]); + v3f playerpos_f = intToFloat(playerpos_s16, BS) - v3f(0, BS/2, 0); + + { //envlock + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + // Set player position + Player *player = m_env.getLocalPlayer(); + assert(player != NULL); + player->setPosition(playerpos_f); + } + + if(datasize >= 2+1+6+8) + { + // Get map seed + m_map_seed = readU64(&data[2+1+6]); + dstream<<"Client: received map seed: "< reply(replysize); + writeU16(&reply[0], TOSERVER_INIT2); + // Send as reliable + m_con.Send(PEER_ID_SERVER, 1, reply, true); + + return; + } + + if(command == TOCLIENT_ACCESS_DENIED) + { + // The server didn't like our password. Note, this needs + // to be processed even if the serialisation format has + // not been agreed yet, the same as TOCLIENT_INIT. + m_access_denied = true; + m_access_denied_reason = L"Unknown"; + if(datasize >= 4) + { + std::string datastring((char*)&data[2], datasize-2); + std::istringstream is(datastring, std::ios_base::binary); + m_access_denied_reason = deSerializeWideString(is); + } + return; + } + + if(ser_version == SER_FMT_VER_INVALID) + { + dout_client<getPos() == p2d); + + //TimeTaker timer("MapBlock deSerialize"); + // 0ms + + block = sector->getBlockNoCreateNoEx(p.Y); + if(block) + { + /* + Update an existing block + */ + //dstream<<"Updating"<deSerialize(istr, ser_version); + } + else + { + /* + Create a new block + */ + //dstream<<"Creating new"<deSerialize(istr, ser_version); + sector->insertBlock(block); + + //DEBUG + /*NodeMod mod; + mod.type = NODEMOD_CHANGECONTENT; + mod.param = CONTENT_MESE; + block->setTempMod(v3s16(8,10,8), mod); + block->setTempMod(v3s16(8,9,8), mod); + block->setTempMod(v3s16(8,8,8), mod); + block->setTempMod(v3s16(8,7,8), mod); + block->setTempMod(v3s16(8,6,8), mod);*/ + } + +#if 0 + /* + Acknowledge block + */ + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + u32 replysize = 2+1+6; + SharedBuffer reply(replysize); + writeU16(&reply[0], TOSERVER_GOTBLOCKS); + reply[2] = 1; + writeV3S16(&reply[3], p); + // Send as reliable + m_con.Send(PEER_ID_SERVER, 1, reply, true); +#endif + + /* + Update Mesh of this block and blocks at x-, y- and z-. + Environment should not be locked as it interlocks with the + main thread, from which is will want to retrieve textures. + */ + + //m_env.getClientMap().updateMeshes(block->getPos(), getDayNightRatio()); + /* + Add it to mesh update queue and set it to be acknowledged after update. + */ + //std::cerr<<"Adding mesh update task for received block"<isLocal()) + { + start += player_size; + continue; + } + + v3s32 ps = readV3S32(&data[start+2]); + v3s32 ss = readV3S32(&data[start+2+12]); + s32 pitch_i = readS32(&data[start+2+12+12]); + s32 yaw_i = readS32(&data[start+2+12+12+4]); + /*dstream<<"Client: got " + <<"pitch_i="< players_alive; + for(u32 i=0; iupdateName((char*)&data[start+2]); + + start += item_size; + } + + /* + Remove those players from the environment that + weren't listed by the server. + */ + //dstream< players = m_env.getPlayers(); + core::list::Iterator ip; + for(ip=players.begin(); ip!=players.end(); ip++) + { + // Ingore local player + if((*ip)->isLocal()) + continue; + + // Warn about a special case + if((*ip)->peer_id == 0) + { + dstream<::Iterator i; + for(i=players_alive.begin(); i!=players_alive.end(); i++) + { + if((*ip)->peer_id == *i) + { + is_alive = true; + break; + } + } + /*dstream<peer_id) + <<" is_alive="<peer_id + <peer_id); + } + } //envlock + } + else if(command == TOCLIENT_SECTORMETA) + { + dstream<<"Client received DEPRECATED TOCLIENT_SECTORMETA"<inventory.deSerialize(is); + //t1.stop(); + + m_inventory_updated = true; + + //dstream<<"Client got player inventory:"<inventory.print(dstream); + } + } + //DEBUG + else if(command == TOCLIENT_OBJECTDATA) + //else if(0) + { + // Strip command word and create a stringstream + std::string datastring((char*)&data[2], datasize-2); + std::istringstream is(datastring, std::ios_base::binary); + + { //envlock + + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + u8 buf[12]; + + /* + Read players + */ + + is.read((char*)buf, 2); + u16 playercount = readU16(buf); + + for(u16 i=0; iisLocal()) + { + continue; + } + + f32 pitch = (f32)pitch_i / 100.0; + f32 yaw = (f32)yaw_i / 100.0; + v3f position((f32)p_i.X/100., (f32)p_i.Y/100., (f32)p_i.Z/100.); + v3f speed((f32)s_i.X/100., (f32)s_i.Y/100., (f32)s_i.Z/100.); + + player->setPosition(position); + player->setSpeed(speed); + player->setPitch(pitch); + player->setYaw(yaw); + } + + /* + Read block objects + NOTE: Deprecated stuff here, TODO: Remove + */ + + // Read active block count + is.read((char*)buf, 2); + u16 blockcount = readU16(buf); + + // Initialize delete queue with all active blocks + core::map abs_to_delete; + for(core::map::Iterator + i = m_active_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + /*dstream<<"adding " + <<"("<updateObjects(is, m_server_ser_ver, + m_device->getSceneManager(), m_env.getDayNightRatio()); + } + + /*dstream<<"Final delete queue size: "<::Iterator + i = abs_to_delete.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + try + { + MapBlock *block = m_env.getMap().getBlockNoCreate(p); + + // Clear objects + block->clearObjects(); + // Remove from active blocks list + m_active_blocks.remove(p); + } + catch(InvalidPositionException &e) + { + dstream<<"WARNAING: Client: " + <<"Couldn't clear objects of active->inactive" + <<" block " + <<"("<hp = hp; + } + else if(command == TOCLIENT_MOVE_PLAYER) + { + std::string datastring((char*)&data[2], datasize-2); + std::istringstream is(datastring, std::ios_base::binary); + Player *player = m_env.getLocalPlayer(); + assert(player != NULL); + v3f pos = readV3F1000(is); + f32 pitch = readF1000(is); + f32 yaw = readF1000(is); + player->setPosition(pos); + /*player->setPitch(pitch); + player->setYaw(yaw);*/ + + dstream<<"Client got TOCLIENT_MOVE_PLAYER" + <<" pos=("<isLocal()) { + dout_client<inventory.getList("main"); + std::string itemstring(deSerializeString(is)); + if (itemstring.empty()) { + inv->deleteItem(0); + dout_client<changeItem(0, InventoryItem::deSerialize(iss)); + dout_client<getWieldItem()->serialize(dout_client); + dout_client< data, bool reliable) +{ + //JMutexAutoLock lock(m_con_mutex); //bulk comment-out + m_con.Send(PEER_ID_SERVER, channelnum, data, reliable); +} + +void Client::groundAction(u8 action, v3s16 nodepos_undersurface, + v3s16 nodepos_oversurface, u16 item) +{ + if(connectedAndInitialized() == false){ + dout_client< data(datasize); + writeU16(&data[0], TOSERVER_GROUND_ACTION); + writeU8(&data[2], action); + writeV3S16(&data[3], nodepos_undersurface); + writeV3S16(&data[9], nodepos_oversurface); + writeU16(&data[15], item); + Send(0, data, true); +} + +void Client::clickObject(u8 button, v3s16 blockpos, s16 id, u16 item) +{ + if(connectedAndInitialized() == false){ + dout_client< data(datasize); + writeU16(&data[0], TOSERVER_CLICK_OBJECT); + writeU8(&data[2], button); + writeV3S16(&data[3], blockpos); + writeS16(&data[9], id); + writeU16(&data[11], item); + Send(0, data, true); +} + +void Client::clickActiveObject(u8 button, u16 id, u16 item) +{ + if(connectedAndInitialized() == false){ + dout_client< data(datasize); + writeU16(&data[0], TOSERVER_CLICK_ACTIVEOBJECT); + writeU8(&data[2], button); + writeU16(&data[3], id); + writeU16(&data[5], item); + Send(0, data, true); +} + +void Client::sendSignText(v3s16 blockpos, s16 id, std::string text) +{ + /* + u16 command + v3s16 blockpos + s16 id + u16 textlen + textdata + */ + std::ostringstream os(std::ios_base::binary); + u8 buf[12]; + + // Write command + writeU16(buf, TOSERVER_SIGNTEXT); + os.write((char*)buf, 2); + + // Write blockpos + writeV3S16(buf, blockpos); + os.write((char*)buf, 6); + + // Write id + writeS16(buf, id); + os.write((char*)buf, 2); + + u16 textlen = text.size(); + // Write text length + writeS16(buf, textlen); + os.write((char*)buf, 2); + + // Write text + os.write((char*)text.c_str(), textlen); + + // Make data buffer + std::string s = os.str(); + SharedBuffer data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + +void Client::sendSignNodeText(v3s16 p, std::string text) +{ + /* + u16 command + v3s16 p + u16 textlen + textdata + */ + std::ostringstream os(std::ios_base::binary); + u8 buf[12]; + + // Write command + writeU16(buf, TOSERVER_SIGNNODETEXT); + os.write((char*)buf, 2); + + // Write p + writeV3S16(buf, p); + os.write((char*)buf, 6); + + u16 textlen = text.size(); + // Write text length + writeS16(buf, textlen); + os.write((char*)buf, 2); + + // Write text + os.write((char*)text.c_str(), textlen); + + // Make data buffer + std::string s = os.str(); + SharedBuffer data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + +void Client::sendInventoryAction(InventoryAction *a) +{ + std::ostringstream os(std::ios_base::binary); + u8 buf[12]; + + // Write command + writeU16(buf, TOSERVER_INVENTORY_ACTION); + os.write((char*)buf, 2); + + a->serialize(os); + + // Make data buffer + std::string s = os.str(); + SharedBuffer data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + +void Client::sendChatMessage(const std::wstring &message) +{ + std::ostringstream os(std::ios_base::binary); + u8 buf[12]; + + // Write command + writeU16(buf, TOSERVER_CHAT_MESSAGE); + os.write((char*)buf, 2); + + // Write length + writeU16(buf, message.size()); + os.write((char*)buf, 2); + + // Write string + for(u32 i=0; i data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + +void Client::sendChangePassword(const std::wstring oldpassword, + const std::wstring newpassword) +{ + Player *player = m_env.getLocalPlayer(); + if(player == NULL) + return; + + std::string playername = player->getName(); + std::string oldpwd = translatePassword(playername, oldpassword); + std::string newpwd = translatePassword(playername, newpassword); + + std::ostringstream os(std::ios_base::binary); + u8 buf[2+PASSWORD_SIZE*2]; + /* + [0] u16 TOSERVER_PASSWORD + [2] u8[28] old password + [30] u8[28] new password + */ + + writeU16(buf, TOSERVER_PASSWORD); + for(u32 i=0;i data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + + +void Client::sendDamage(u8 damage) +{ + DSTACK(__FUNCTION_NAME); + std::ostringstream os(std::ios_base::binary); + + writeU16(os, TOSERVER_DAMAGE); + writeU8(os, damage); + + // Make data buffer + std::string s = os.str(); + SharedBuffer data((u8*)s.c_str(), s.size()); + // Send as reliable + Send(0, data, true); +} + +void Client::sendPlayerPos() +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + Player *myplayer = m_env.getLocalPlayer(); + if(myplayer == NULL) + return; + + u16 our_peer_id; + { + //JMutexAutoLock lock(m_con_mutex); //bulk comment-out + our_peer_id = m_con.GetPeerID(); + } + + // Set peer id if not set already + if(myplayer->peer_id == PEER_ID_INEXISTENT) + myplayer->peer_id = our_peer_id; + // Check that an existing peer_id is the same as the connection's + assert(myplayer->peer_id == our_peer_id); + + v3f pf = myplayer->getPosition(); + v3s32 position(pf.X*100, pf.Y*100, pf.Z*100); + v3f sf = myplayer->getSpeed(); + v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100); + s32 pitch = myplayer->getPitch() * 100; + s32 yaw = myplayer->getYaw() * 100; + + /* + Format: + [0] u16 command + [2] v3s32 position*100 + [2+12] v3s32 speed*100 + [2+12+12] s32 pitch*100 + [2+12+12+4] s32 yaw*100 + */ + + SharedBuffer data(2+12+12+4+4); + writeU16(&data[0], TOSERVER_PLAYERPOS); + writeV3S32(&data[2], position); + writeV3S32(&data[2+12], speed); + writeS32(&data[2+12+12], pitch); + writeS32(&data[2+12+12+4], yaw); + + // Send as unreliable + Send(0, data, false); +} + +void Client::sendPlayerItem(u16 item) +{ + Player *myplayer = m_env.getLocalPlayer(); + if(myplayer == NULL) + return; + + u16 our_peer_id = m_con.GetPeerID(); + + // Set peer id if not set already + if(myplayer->peer_id == PEER_ID_INEXISTENT) + myplayer->peer_id = our_peer_id; + // Check that an existing peer_id is the same as the connection's + assert(myplayer->peer_id == our_peer_id); + + SharedBuffer data(2+2); + writeU16(&data[0], TOSERVER_PLAYERITEM); + writeU16(&data[2], item); + + // Send as reliable + Send(0, data, true); +} + +void Client::removeNode(v3s16 p) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + core::map modified_blocks; + + try + { + //TimeTaker t("removeNodeAndUpdate", m_device); + m_env.getMap().removeNodeAndUpdate(p, modified_blocks); + } + catch(InvalidPositionException &e) + { + } + + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + //m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio()); + addUpdateMeshTaskWithEdge(p); + } +} + +void Client::addNode(v3s16 p, MapNode n) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + TimeTaker timer1("Client::addNode()"); + + core::map modified_blocks; + + try + { + //TimeTaker timer3("Client::addNode(): addNodeAndUpdate"); + m_env.getMap().addNodeAndUpdate(p, n, modified_blocks); + } + catch(InvalidPositionException &e) + {} + + //TimeTaker timer2("Client::addNode(): updateMeshes"); + + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + //m_env.getClientMap().updateMeshes(p, m_env.getDayNightRatio()); + addUpdateMeshTaskWithEdge(p); + } +} + +void Client::updateCamera(v3f pos, v3f dir) +{ + m_env.getClientMap().updateCamera(pos, dir); + camera_position = pos; + camera_direction = dir; +} + +MapNode Client::getNode(v3s16 p) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + return m_env.getMap().getNode(p); +} + +NodeMetadata* Client::getNodeMetadata(v3s16 p) +{ + return m_env.getMap().getNodeMetadata(p); +} + +v3f Client::getPlayerPosition(v3f *eye_position) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + if (eye_position) + *eye_position = player->getEyePosition(); + return player->getPosition(); +} + +void Client::setPlayerControl(PlayerControl &control) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + player->control = control; +} + +void Client::selectPlayerItem(u16 item) +{ + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + + player->wieldItem(item); + + sendPlayerItem(item); +} + +// Returns true if the inventory of the local player has been +// updated from the server. If it is true, it is set to false. +bool Client::getLocalInventoryUpdated() +{ + // m_inventory_updated is behind envlock + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + bool updated = m_inventory_updated; + m_inventory_updated = false; + return updated; +} + +// Copies the inventory of the local player to parameter +void Client::getLocalInventory(Inventory &dst) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + Player *player = m_env.getLocalPlayer(); + assert(player != NULL); + dst = player->inventory; +} + +InventoryContext *Client::getInventoryContext() +{ + return &m_inventory_context; +} + +Inventory* Client::getInventory(InventoryContext *c, std::string id) +{ + if(id == "current_player") + { + assert(c->current_player); + return &(c->current_player->inventory); + } + + Strfnd fn(id); + std::string id0 = fn.next(":"); + + if(id0 == "nodemeta") + { + v3s16 p; + p.X = stoi(fn.next(",")); + p.Y = stoi(fn.next(",")); + p.Z = stoi(fn.next(",")); + NodeMetadata* meta = getNodeMetadata(p); + if(meta) + return meta->getInventory(); + dstream<<"nodemeta at ("< shootline_on_map + ) +{ + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + + core::array objects; + + for(core::map::Iterator + i = m_active_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + + MapBlock *block = NULL; + try + { + block = m_env.getMap().getBlockNoCreate(p); + } + catch(InvalidPositionException &e) + { + continue; + } + + // Calculate from_pos relative to block + v3s16 block_pos_i_on_map = block->getPosRelative(); + v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS); + v3f from_pos_f_on_block = from_pos_f_on_map - block_pos_f_on_map; + + block->getObjects(from_pos_f_on_block, max_d, objects); + //block->getPseudoObjects(from_pos_f_on_block, max_d, objects); + } + + //dstream<<"Collected "<getBlock(); + + // Calculate shootline relative to block + v3s16 block_pos_i_on_map = block->getPosRelative(); + v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map, BS); + core::line3d shootline_on_block( + shootline_on_map.start - block_pos_f_on_map, + shootline_on_map.end - block_pos_f_on_map + ); + + if(obj->isSelected(shootline_on_block)) + { + //dstream<<"Returning selected object"< shootline_on_map + ) +{ + core::array objects; + + m_env.getActiveObjects(from_pos_f_on_map, max_d, objects); + + //dstream<<"Collected "< *selection_box = obj->getSelectionBox(); + if(selection_box == NULL) + continue; + + v3f pos = obj->getPosition(); + + core::aabbox3d offsetted_box( + selection_box->MinEdge + pos, + selection_box->MaxEdge + pos + ); + + if(offsetted_box.intersectsWithLine(shootline_on_map)) + { + //dstream<<"Returning selected object"<fill(getDayNightRatio(), b); + } + + // Debug wait + //while(m_mesh_update_thread.m_queue_in.size() > 0) sleep_ms(10); + + // Add task to queue + m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server); + + /*dstream<<"Mesh update input queue size is " + <replaceMesh(mesh_new); + delete data; + } +#endif + + /* + Mark mesh as non-expired at this point so that it can already + be marked as expired again if the data changes + */ + b->setMeshExpired(false); +} + +void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server) +{ + /*{ + v3s16 p = blockpos; + dstream<<"Client::addUpdateMeshTaskWithEdge(): " + <<"("< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CLIENT_HEADER +#define CLIENT_HEADER + +#ifndef SERVER + +#include "connection.h" +#include "environment.h" +#include "common_irrlicht.h" +#include "jmutex.h" +#include +#include "clientobject.h" +#include "utility.h" // For IntervalLimiter + +struct MeshMakeData; + +class ClientNotReadyException : public BaseException +{ +public: + ClientNotReadyException(const char *s): + BaseException(s) + {} +}; + +struct QueuedMeshUpdate +{ + v3s16 p; + MeshMakeData *data; + bool ack_block_to_server; + + QueuedMeshUpdate(); + ~QueuedMeshUpdate(); +}; + +/* + A thread-safe queue of mesh update tasks +*/ +class MeshUpdateQueue +{ +public: + MeshUpdateQueue(); + + ~MeshUpdateQueue(); + + /* + peer_id=0 adds with nobody to send to + */ + void addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server); + + // Returned pointer must be deleted + // Returns NULL if queue is empty + QueuedMeshUpdate * pop(); + + u32 size() + { + JMutexAutoLock lock(m_mutex); + return m_queue.size(); + } + +private: + core::list m_queue; + JMutex m_mutex; +}; + +struct MeshUpdateResult +{ + v3s16 p; + scene::SMesh *mesh; + bool ack_block_to_server; + + MeshUpdateResult(): + p(-1338,-1338,-1338), + mesh(NULL), + ack_block_to_server(false) + { + } +}; + +class MeshUpdateThread : public SimpleThread +{ +public: + + MeshUpdateThread() + { + } + + void * Thread(); + + MeshUpdateQueue m_queue_in; + + MutexedQueue m_queue_out; +}; + +enum ClientEventType +{ + CE_NONE, + CE_PLAYER_DAMAGE, + CE_PLAYER_FORCE_MOVE +}; + +struct ClientEvent +{ + ClientEventType type; + union{ + struct{ + } none; + struct{ + u8 amount; + } player_damage; + struct{ + f32 pitch; + f32 yaw; + } player_force_move; + }; +}; + +class Client : public con::PeerHandler, public InventoryManager +{ +public: + /* + NOTE: Nothing is thread-safe here. + */ + + Client( + IrrlichtDevice *device, + const char *playername, + std::string password, + MapDrawControl &control + ); + + ~Client(); + /* + The name of the local player should already be set when + calling this, as it is sent in the initialization. + */ + void connect(Address address); + /* + returns true when + m_con.Connected() == true + AND m_server_ser_ver != SER_FMT_VER_INVALID + throws con::PeerNotFoundException if connection has been deleted, + eg. timed out. + */ + bool connectedAndInitialized(); + /* + Stuff that references the environment is valid only as + long as this is not called. (eg. Players) + If this throws a PeerNotFoundException, the connection has + timed out. + */ + void step(float dtime); + + // Called from updater thread + // Returns dtime + //float asyncStep(); + + void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id); + // Returns true if something was received + bool AsyncProcessPacket(); + bool AsyncProcessData(); + void Send(u16 channelnum, SharedBuffer data, bool reliable); + + // Pops out a packet from the packet queue + //IncomingPacket getPacket(); + + void groundAction(u8 action, v3s16 nodepos_undersurface, + v3s16 nodepos_oversurface, u16 item); + void clickObject(u8 button, v3s16 blockpos, s16 id, u16 item); + void clickActiveObject(u8 button, u16 id, u16 item); + + void sendSignText(v3s16 blockpos, s16 id, std::string text); + void sendSignNodeText(v3s16 p, std::string text); + void sendInventoryAction(InventoryAction *a); + void sendChatMessage(const std::wstring &message); + void sendChangePassword(const std::wstring oldpassword, + const std::wstring newpassword); + void sendDamage(u8 damage); + + // locks envlock + void removeNode(v3s16 p); + // locks envlock + void addNode(v3s16 p, MapNode n); + + void updateCamera(v3f pos, v3f dir); + + // Returns InvalidPositionException if not found + MapNode getNode(v3s16 p); + // Wrapper to Map + NodeMetadata* getNodeMetadata(v3s16 p); + + // Get the player position, and optionally put the + // eye position in *eye_position + v3f getPlayerPosition(v3f *eye_position=NULL); + + void setPlayerControl(PlayerControl &control); + + void selectPlayerItem(u16 item); + + // Returns true if the inventory of the local player has been + // updated from the server. If it is true, it is set to false. + bool getLocalInventoryUpdated(); + // Copies the inventory of the local player to parameter + void getLocalInventory(Inventory &dst); + + InventoryContext *getInventoryContext(); + + Inventory* getInventory(InventoryContext *c, std::string id); + void inventoryAction(InventoryAction *a); + + // Gets closest object pointed by the shootline + // Returns NULL if not found + MapBlockObject * getSelectedObject( + f32 max_d, + v3f from_pos_f_on_map, + core::line3d shootline_on_map + ); + + // Gets closest object pointed by the shootline + // Returns NULL if not found + ClientActiveObject * getSelectedActiveObject( + f32 max_d, + v3f from_pos_f_on_map, + core::line3d shootline_on_map + ); + + // Prints a line or two of info + void printDebugInfo(std::ostream &os); + + u32 getDayNightRatio(); + + u16 getHP(); + + void setTempMod(v3s16 p, NodeMod mod); + void clearTempMod(v3s16 p); + + float getAvgRtt() + { + //JMutexAutoLock lock(m_con_mutex); //bulk comment-out + con::Peer *peer = m_con.GetPeerNoEx(PEER_ID_SERVER); + if(peer == NULL) + return 0.0; + return peer->avg_rtt; + } + + bool getChatMessage(std::wstring &message) + { + if(m_chat_queue.size() == 0) + return false; + message = m_chat_queue.pop_front(); + return true; + } + + void addChatMessage(const std::wstring &message) + { + if (message[0] == L'/') { + m_chat_queue.push_back( + (std::wstring)L"issued command: "+message); + return; + } + + //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out + LocalPlayer *player = m_env.getLocalPlayer(); + assert(player != NULL); + std::wstring name = narrow_to_wide(player->getName()); + m_chat_queue.push_back( + (std::wstring)L"<"+name+L"> "+message); + } + + u64 getMapSeed(){ return m_map_seed; } + + void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false); + // Including blocks at appropriate edges + void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false); + + // Get event from queue. CE_NONE is returned if queue is empty. + ClientEvent getClientEvent(); + + inline bool accessDenied() + { + return m_access_denied; + } + + inline std::wstring accessDeniedReason() + { + return m_access_denied_reason; + } + + /* + This should only be used for calling the special drawing stuff in + ClientEnvironment + */ + ClientEnvironment * getEnv() + { + return &m_env; + } + +private: + + // Virtual methods from con::PeerHandler + void peerAdded(con::Peer *peer); + void deletingPeer(con::Peer *peer, bool timeout); + + void ReceiveAll(); + void Receive(); + + void sendPlayerPos(); + // This sends the player's current name etc to the server + void sendPlayerInfo(); + // Send the item number 'item' as player item to the server + void sendPlayerItem(u16 item); + + float m_packetcounter_timer; + float m_connection_reinit_timer; + float m_avg_rtt_timer; + float m_playerpos_send_timer; + float m_ignore_damage_timer; // Used after server moves player + IntervalLimiter m_map_timer_and_unload_interval; + + MeshUpdateThread m_mesh_update_thread; + + ClientEnvironment m_env; + + con::Connection m_con; + + IrrlichtDevice *m_device; + + v3f camera_position; + v3f camera_direction; + + // Server serialization version + u8 m_server_ser_ver; + + // This is behind m_env_mutex. + bool m_inventory_updated; + + core::map m_active_blocks; + + PacketCounter m_packetcounter; + + // Received from the server. 0-23999 + u32 m_time_of_day; + + // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT + //s32 m_daynight_i; + //u32 m_daynight_ratio; + + Queue m_chat_queue; + + // The seed returned by the server in TOCLIENT_INIT is stored here + u64 m_map_seed; + + std::string m_password; + bool m_access_denied; + std::wstring m_access_denied_reason; + + InventoryContext m_inventory_context; + + Queue m_client_event_queue; + + friend class FarMesh; +}; + +#endif // !SERVER + +#endif // !CLIENT_HEADER + diff --git a/src/clientobject.cpp b/src/clientobject.cpp new file mode 100644 index 0000000..bec9f46 --- /dev/null +++ b/src/clientobject.cpp @@ -0,0 +1,66 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "clientobject.h" +#include "debug.h" +#include "porting.h" +#include "constants.h" + +/* + ClientActiveObject +*/ + +ClientActiveObject::ClientActiveObject(u16 id): + ActiveObject(id) +{ +} + +ClientActiveObject::~ClientActiveObject() +{ + removeFromScene(); +} + +ClientActiveObject* ClientActiveObject::create(u8 type) +{ + // Find factory function + core::map::Node *n; + n = m_types.find(type); + if(n == NULL) + { + // If factory is not found, just return. + dstream<<"WARNING: ClientActiveObject: No factory for type=" + <getValue(); + ClientActiveObject *object = (*f)(); + return object; +} + +void ClientActiveObject::registerType(u16 type, Factory f) +{ + core::map::Node *n; + n = m_types.find(type); + if(n) + return; + m_types.insert(type, f); +} + + diff --git a/src/clientobject.h b/src/clientobject.h new file mode 100644 index 0000000..c906484 --- /dev/null +++ b/src/clientobject.h @@ -0,0 +1,99 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CLIENTOBJECT_HEADER +#define CLIENTOBJECT_HEADER + +#include "common_irrlicht.h" +#include "activeobject.h" + +/* + +Some planning +------------- + +* Client receives a network packet with information of added objects + in it +* Client supplies the information to its ClientEnvironment +* The environment adds the specified objects to itself + +*/ + +class ClientEnvironment; + +class ClientActiveObject : public ActiveObject +{ +public: + ClientActiveObject(u16 id); + virtual ~ClientActiveObject(); + + virtual void addToScene(scene::ISceneManager *smgr){} + virtual void removeFromScene(){} + // 0 <= light_at_pos <= LIGHT_SUN + virtual void updateLight(u8 light_at_pos){} + virtual v3s16 getLightPosition(){return v3s16(0,0,0);} + virtual core::aabbox3d* getSelectionBox(){return NULL;} + virtual core::aabbox3d* getCollisionBox(){return NULL;} + virtual v3f getPosition(){return v3f(0,0,0);} + + // Step object in time + virtual void step(float dtime, ClientEnvironment *env){} + + // Process a message sent by the server side object + virtual void processMessage(const std::string &data){} + + virtual std::string infoText() {return "";} + + /* + This takes the return value of + ServerActiveObject::getClientInitializationData + */ + virtual void initialize(const std::string &data){} + + // Create a certain type of ClientActiveObject + static ClientActiveObject* create(u8 type); + +protected: + // Used for creating objects based on type + typedef ClientActiveObject* (*Factory)(); + static void registerType(u16 type, Factory f); +private: + // Used for creating objects based on type + static core::map m_types; +}; + +struct DistanceSortedActiveObject +{ + ClientActiveObject *obj; + f32 d; + + DistanceSortedActiveObject(ClientActiveObject *a_obj, f32 a_d) + { + obj = a_obj; + d = a_d; + } + + bool operator < (DistanceSortedActiveObject &other) + { + return d < other.d; + } +}; + +#endif + diff --git a/src/clientserver.h b/src/clientserver.h new file mode 100644 index 0000000..9d31927 --- /dev/null +++ b/src/clientserver.h @@ -0,0 +1,335 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CLIENTSERVER_HEADER +#define CLIENTSERVER_HEADER + +#include "utility.h" + +#define PROTOCOL_ID 0x4f457403 + +#define PASSWORD_SIZE 28 // Maximum password length. Allows for + // base64-encoded SHA-1 (27+\0). + +enum ToClientCommand +{ + TOCLIENT_INIT = 0x10, + /* + Server's reply to TOSERVER_INIT. + Sent second after connected. + + [0] u16 TOSERVER_INIT + [2] u8 deployed version + [3] v3s16 player's position + v3f(0,BS/2,0) floatToInt'd + [12] u64 map seed (new as of 2011-02-27) + + NOTE: The position in here is deprecated; position is + explicitly sent afterwards + */ + + TOCLIENT_BLOCKDATA = 0x20, //TODO: Multiple blocks + TOCLIENT_ADDNODE = 0x21, + TOCLIENT_REMOVENODE = 0x22, + + TOCLIENT_PLAYERPOS = 0x23, // Obsolete + /* + [0] u16 command + // Followed by an arbitary number of these: + // Number is determined from packet length. + [N] u16 peer_id + [N+2] v3s32 position*100 + [N+2+12] v3s32 speed*100 + [N+2+12+12] s32 pitch*100 + [N+2+12+12+4] s32 yaw*100 + */ + + TOCLIENT_PLAYERINFO = 0x24, + /* + [0] u16 command + // Followed by an arbitary number of these: + // Number is determined from packet length. + [N] u16 peer_id + [N] char[20] name + */ + + TOCLIENT_OPT_BLOCK_NOT_FOUND = 0x25, // Obsolete + + TOCLIENT_SECTORMETA = 0x26, // Obsolete + /* + [0] u16 command + [2] u8 sector count + [3...] v2s16 pos + sector metadata + */ + + TOCLIENT_INVENTORY = 0x27, + /* + [0] u16 command + [2] serialized inventory + */ + + TOCLIENT_OBJECTDATA = 0x28, + /* + Sent as unreliable. + + u16 command + u16 number of player positions + for each player: + u16 peer_id + v3s32 position*100 + v3s32 speed*100 + s32 pitch*100 + s32 yaw*100 + u16 count of blocks + for each block: + v3s16 blockpos + block objects + */ + + TOCLIENT_TIME_OF_DAY = 0x29, + /* + u16 command + u16 time (0-23999) + */ + + TOCLIENT_CHAT_MESSAGE = 0x30, + /* + u16 command + u16 length + wstring message + */ + + TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD = 0x31, + /* + u16 command + u16 count of removed objects + for all removed objects { + u16 id + } + u16 count of added objects + for all added objects { + u16 id + u8 type + u32 initialization data length + string initialization data + } + */ + + TOCLIENT_ACTIVE_OBJECT_MESSAGES = 0x32, + /* + u16 command + for all objects + { + u16 id + u16 message length + string message + } + */ + + TOCLIENT_HP = 0x33, + /* + u16 command + u8 hp + */ + + TOCLIENT_MOVE_PLAYER = 0x34, + /* + u16 command + v3f1000 player position + f1000 player pitch + f1000 player yaw + */ + + TOCLIENT_ACCESS_DENIED = 0x35, + /* + u16 command + u16 reason_length + wstring reason + */ + + TOCLIENT_PLAYERITEM = 0x36, + /* + u16 command + u16 count of player items + for all player items { + u16 peer id + u16 length of serialized item + string serialized item + } + */ +}; + +enum ToServerCommand +{ + TOSERVER_INIT=0x10, + /* + Sent first after connected. + + [0] u16 TOSERVER_INIT + [2] u8 SER_FMT_VER_HIGHEST + [3] u8[20] player_name + [23] u8[28] password (new in some version) + [51] u16 client network protocol version (new in some version) + */ + + TOSERVER_INIT2 = 0x11, + /* + Sent as an ACK for TOCLIENT_INIT. + After this, the server can send data. + + [0] u16 TOSERVER_INIT2 + */ + + TOSERVER_GETBLOCK=0x20, // Obsolete + TOSERVER_ADDNODE = 0x21, // Obsolete + TOSERVER_REMOVENODE = 0x22, // Obsolete + + TOSERVER_PLAYERPOS = 0x23, + /* + [0] u16 command + [2] v3s32 position*100 + [2+12] v3s32 speed*100 + [2+12+12] s32 pitch*100 + [2+12+12+4] s32 yaw*100 + */ + + TOSERVER_GOTBLOCKS = 0x24, + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + + TOSERVER_DELETEDBLOCKS = 0x25, + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + + TOSERVER_ADDNODE_FROM_INVENTORY = 0x26, // Obsolete + /* + [0] u16 command + [2] v3s16 pos + [8] u16 i + */ + + TOSERVER_CLICK_OBJECT = 0x27, + /* + length: 13 + [0] u16 command + [2] u8 button (0=left, 1=right) + [3] v3s16 blockpos + [9] s16 id + [11] u16 item + */ + + TOSERVER_GROUND_ACTION = 0x28, + /* + length: 17 + [0] u16 command + [2] u8 action + [3] v3s16 nodepos_undersurface + [9] v3s16 nodepos_abovesurface + [15] u16 item + actions: + 0: start digging (from undersurface) + 1: place block (to abovesurface) + 2: stop digging (all parameters ignored) + 3: digging completed + */ + + TOSERVER_RELEASE = 0x29, // Obsolete + + TOSERVER_SIGNTEXT = 0x30, // Old signs + /* + u16 command + v3s16 blockpos + s16 id + u16 textlen + textdata + */ + + TOSERVER_INVENTORY_ACTION = 0x31, + /* + See InventoryAction in inventory.h + */ + + TOSERVER_CHAT_MESSAGE = 0x32, + /* + u16 command + u16 length + wstring message + */ + + TOSERVER_SIGNNODETEXT = 0x33, + /* + u16 command + v3s16 p + u16 textlen + textdata + */ + + TOSERVER_CLICK_ACTIVEOBJECT = 0x34, + /* + length: 7 + [0] u16 command + [2] u8 button (0=left, 1=right) + [3] u16 id + [5] u16 item + */ + + TOSERVER_DAMAGE = 0x35, + /* + u16 command + u8 amount + */ + + TOSERVER_PASSWORD=0x36, + /* + Sent to change password. + + [0] u16 TOSERVER_PASSWORD + [2] u8[28] old password + [30] u8[28] new password + */ + + TOSERVER_PLAYERITEM=0x37, + /* + Sent to change selected item. + + [0] u16 TOSERVER_PLAYERITEM + [2] u16 item + */ + +}; + +inline SharedBuffer makePacket_TOCLIENT_TIME_OF_DAY(u16 time) +{ + SharedBuffer data(2+2); + writeU16(&data[0], TOCLIENT_TIME_OF_DAY); + writeU16(&data[2], time); + return data; +} + +#endif + diff --git a/src/clouds.cpp b/src/clouds.cpp new file mode 100644 index 0000000..d754cc1 --- /dev/null +++ b/src/clouds.cpp @@ -0,0 +1,221 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "clouds.h" +#include "noise.h" +#include "constants.h" +#include "debug.h" + +Clouds::Clouds( + scene::ISceneNode* parent, + scene::ISceneManager* mgr, + s32 id, + float cloud_y, + u32 seed +): + scene::ISceneNode(parent, mgr, id), + m_cloud_y(cloud_y), + m_seed(seed), + m_camera_pos(0,0), + m_time(0) +{ + dstream<<__FUNCTION_NAME<(-BS*1000000,cloud_y-BS,-BS*1000000, + BS*1000000,cloud_y+BS,BS*1000000); + +} + +Clouds::~Clouds() +{ + dstream<<__FUNCTION_NAME<registerNodeForRendering(this, scene::ESNRP_TRANSPARENT); + SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); + } + + ISceneNode::OnRegisterSceneNode(); +} + +#define MYROUND(x) (x > 0.0 ? (int)x : (int)x - 1) + +void Clouds::render() +{ + video::IVideoDriver* driver = SceneManager->getVideoDriver(); + + /*if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT) + return;*/ + if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID) + return; + + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); + driver->setMaterial(m_material); + + /* + Clouds move from X+ towards X- + */ + + const s16 cloud_radius_i = 12; + const float cloud_size = BS*48; + const v2f cloud_speed(-BS*2, 0); + + // Position of cloud noise origin in world coordinates + v2f world_cloud_origin_pos_f = m_time*cloud_speed; + // Position of cloud noise origin from the camera + v2f cloud_origin_from_camera_f = world_cloud_origin_pos_f - m_camera_pos; + // The center point of drawing in the noise + v2f center_of_drawing_in_noise_f = -cloud_origin_from_camera_f; + // The integer center point of drawing in the noise + v2s16 center_of_drawing_in_noise_i( + MYROUND(center_of_drawing_in_noise_f.X / cloud_size), + MYROUND(center_of_drawing_in_noise_f.Y / cloud_size) + ); + // The world position of the integer center point of drawing in the noise + v2f world_center_of_drawing_in_noise_f = v2f( + center_of_drawing_in_noise_i.X * cloud_size, + center_of_drawing_in_noise_i.Y * cloud_size + ) + world_cloud_origin_pos_f; + + for(s16 zi=-cloud_radius_i; zidrawVertexPrimitiveList(v, 4, indices, 2, + video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT); + } + + } +} + +void Clouds::step(float dtime) +{ + m_time += dtime; +} + +void Clouds::update(v2f camera_p, float brightness) +{ + m_camera_pos = camera_p; + m_brightness = brightness; +} + diff --git a/src/clouds.h b/src/clouds.h new file mode 100644 index 0000000..5986137 --- /dev/null +++ b/src/clouds.h @@ -0,0 +1,83 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CLOUDS_HEADER +#define CLOUDS_HEADER + +#include "common_irrlicht.h" +#include + +class Clouds : public scene::ISceneNode +{ +public: + Clouds( + scene::ISceneNode* parent, + scene::ISceneManager* mgr, + s32 id, + float cloud_y, + u32 seed + ); + + ~Clouds(); + + /* + ISceneNode methods + */ + + virtual void OnRegisterSceneNode(); + + virtual void render(); + + virtual const core::aabbox3d& getBoundingBox() const + { + return m_box; + } + + virtual u32 getMaterialCount() const + { + return 1; + } + + virtual video::SMaterial& getMaterial(u32 i) + { + return m_material; + } + + /* + Other stuff + */ + + void step(float dtime); + + void update(v2f camera_p, float brightness); + +private: + video::SMaterial m_material; + core::aabbox3d m_box; + float m_cloud_y; + float m_brightness; + u32 m_seed; + v2f m_camera_pos; + float m_time; +}; + + + +#endif + diff --git a/src/cmake_config.h.in b/src/cmake_config.h.in new file mode 100644 index 0000000..7cbb11f --- /dev/null +++ b/src/cmake_config.h.in @@ -0,0 +1,18 @@ +// Filled in by the build system + +#ifndef CMAKE_CONFIG_H +#define CMAKE_CONFIG_H + +#define PROJECT_NAME "@PROJECT_NAME@" +#define INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@" +#define VERSION_STRING "@VERSION_STRING@" +#define USE_GETTEXT @USE_GETTEXT@ +#ifdef NDEBUG + #define BUILD_TYPE "Release" +#else + #define BUILD_TYPE "Debug" +#endif +#define BUILD_INFO "VER="VERSION_STRING" RUN_IN_PLACE=@RUN_IN_PLACE@ USE_GETTEXT=@USE_GETTEXT@ INSTALL_PREFIX=@CMAKE_INSTALL_PREFIX@ BUILD_TYPE="BUILD_TYPE + +#endif + diff --git a/src/collision.cpp b/src/collision.cpp new file mode 100644 index 0000000..3d322cf --- /dev/null +++ b/src/collision.cpp @@ -0,0 +1,240 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "collision.h" +#include "mapblock.h" +#include "map.h" + +collisionMoveResult collisionMoveSimple(Map *map, f32 pos_max_d, + const core::aabbox3d &box_0, + f32 dtime, v3f &pos_f, v3f &speed_f) +{ + collisionMoveResult result; + + v3f oldpos_f = pos_f; + v3s16 oldpos_i = floatToInt(oldpos_f, BS); + + /* + Calculate new position + */ + pos_f += speed_f * dtime; + + /* + Collision detection + */ + + // position in nodes + v3s16 pos_i = floatToInt(pos_f, BS); + + /* + Collision uncertainty radius + Make it a bit larger than the maximum distance of movement + */ + f32 d = pos_max_d * 1.1; + // A fairly large value in here makes moving smoother + //f32 d = 0.15*BS; + + // This should always apply, otherwise there are glitches + assert(d > pos_max_d); + + /* + Calculate collision box + */ + core::aabbox3d box = box_0; + box.MaxEdge += pos_f; + box.MinEdge += pos_f; + core::aabbox3d oldbox = box_0; + oldbox.MaxEdge += oldpos_f; + oldbox.MinEdge += oldpos_f; + + /* + If the object lies on a walkable node, this is set to true. + */ + result.touching_ground = false; + + /* + Go through every node around the object + TODO: Calculate the range of nodes that need to be checked + */ + for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++) + for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++) + for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++) + { + try{ + // Object collides into walkable nodes + MapNode n = map->getNode(v3s16(x,y,z)); + if(content_features(n).walkable == false) + continue; + } + catch(InvalidPositionException &e) + { + // Doing nothing here will block the object from + // walking over map borders + } + + core::aabbox3d nodebox = getNodeBox(v3s16(x,y,z), BS); + + /* + See if the object is touching ground. + + Object touches ground if object's minimum Y is near node's + maximum Y and object's X-Z-area overlaps with the node's + X-Z-area. + + Use 0.15*BS so that it is easier to get on a node. + */ + if( + //fabs(nodebox.MaxEdge.Y-box.MinEdge.Y) < d + fabs(nodebox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS + && nodebox.MaxEdge.X-d > box.MinEdge.X + && nodebox.MinEdge.X+d < box.MaxEdge.X + && nodebox.MaxEdge.Z-d > box.MinEdge.Z + && nodebox.MinEdge.Z+d < box.MaxEdge.Z + ){ + result.touching_ground = true; + } + + // If object doesn't intersect with node, ignore node. + if(box.intersectsWithBox(nodebox) == false) + continue; + + /* + Go through every axis + */ + v3f dirs[3] = { + v3f(0,0,1), // back-front + v3f(0,1,0), // top-bottom + v3f(1,0,0), // right-left + }; + for(u16 i=0; i<3; i++) + { + /* + Calculate values along the axis + */ + f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]); + f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]); + f32 objectmax = box.MaxEdge.dotProduct(dirs[i]); + f32 objectmin = box.MinEdge.dotProduct(dirs[i]); + f32 objectmax_old = oldbox.MaxEdge.dotProduct(dirs[i]); + f32 objectmin_old = oldbox.MinEdge.dotProduct(dirs[i]); + + /* + Check collision for the axis. + Collision happens when object is going through a surface. + */ + bool negative_axis_collides = + (nodemax > objectmin && nodemax <= objectmin_old + d + && speed_f.dotProduct(dirs[i]) < 0); + bool positive_axis_collides = + (nodemin < objectmax && nodemin >= objectmax_old - d + && speed_f.dotProduct(dirs[i]) > 0); + bool main_axis_collides = + negative_axis_collides || positive_axis_collides; + + /* + Check overlap of object and node in other axes + */ + bool other_axes_overlap = true; + for(u16 j=0; j<3; j++) + { + if(j == i) + continue; + f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]); + f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]); + f32 objectmax = box.MaxEdge.dotProduct(dirs[j]); + f32 objectmin = box.MinEdge.dotProduct(dirs[j]); + if(!(nodemax - d > objectmin && nodemin + d < objectmax)) + { + other_axes_overlap = false; + break; + } + } + + /* + If this is a collision, revert the pos_f in the main + direction. + */ + if(other_axes_overlap && main_axis_collides) + { + speed_f -= speed_f.dotProduct(dirs[i]) * dirs[i]; + pos_f -= pos_f.dotProduct(dirs[i]) * dirs[i]; + pos_f += oldpos_f.dotProduct(dirs[i]) * dirs[i]; + } + + } + } // xyz + + return result; +} + +collisionMoveResult collisionMovePrecise(Map *map, f32 pos_max_d, + const core::aabbox3d &box_0, + f32 dtime, v3f &pos_f, v3f &speed_f) +{ + collisionMoveResult final_result; + + // Maximum time increment (for collision detection etc) + // time = distance / speed + f32 dtime_max_increment = pos_max_d / speed_f.getLength(); + + // Maximum time increment is 10ms or lower + if(dtime_max_increment > 0.01) + dtime_max_increment = 0.01; + + // Don't allow overly huge dtime + if(dtime > 2.0) + dtime = 2.0; + + f32 dtime_downcount = dtime; + + u32 loopcount = 0; + do + { + loopcount++; + + f32 dtime_part; + if(dtime_downcount > dtime_max_increment) + { + dtime_part = dtime_max_increment; + dtime_downcount -= dtime_part; + } + else + { + dtime_part = dtime_downcount; + /* + Setting this to 0 (no -=dtime_part) disables an infinite loop + when dtime_part is so small that dtime_downcount -= dtime_part + does nothing + */ + dtime_downcount = 0; + } + + collisionMoveResult result = collisionMoveSimple(map, pos_max_d, + box_0, dtime_part, pos_f, speed_f); + + if(result.touching_ground) + final_result.touching_ground = true; + } + while(dtime_downcount > 0.001); + + + return final_result; +} + + diff --git a/src/collision.h b/src/collision.h new file mode 100644 index 0000000..6d167bb --- /dev/null +++ b/src/collision.h @@ -0,0 +1,58 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef COLLISION_HEADER +#define COLLISION_HEADER + +#include "common_irrlicht.h" + +class Map; + +struct collisionMoveResult +{ + bool touching_ground; + + collisionMoveResult(): + touching_ground(false) + {} +}; + +// Moves using a single iteration; speed should not exceed pos_max_d/dtime +collisionMoveResult collisionMoveSimple(Map *map, f32 pos_max_d, + const core::aabbox3d &box_0, + f32 dtime, v3f &pos_f, v3f &speed_f); + +// Moves using as many iterations as needed +collisionMoveResult collisionMovePrecise(Map *map, f32 pos_max_d, + const core::aabbox3d &box_0, + f32 dtime, v3f &pos_f, v3f &speed_f); + +enum CollisionType +{ + COLLISION_FALL +}; + +struct CollisionInfo +{ + CollisionType t; + f32 speed; +}; + +#endif + diff --git a/src/common_irrlicht.h b/src/common_irrlicht.h new file mode 100644 index 0000000..7ce5d8d --- /dev/null +++ b/src/common_irrlicht.h @@ -0,0 +1,49 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef COMMON_IRRLICHT_HEADER +#define COMMON_IRRLICHT_HEADER + +#define endSceneX(d){d->draw2DLine(v2s32(0,0),v2s32(1,0),\ +video::SColor(255,30,30,30));d->endScene();} + +#include +using namespace irr; +typedef core::vector3df v3f; +typedef core::vector3d v3s16; +typedef core::vector3d v3s32; + +typedef core::vector2d v2f; +typedef core::vector2d v2s16; +typedef core::vector2d v2s32; +typedef core::vector2d v2u32; +typedef core::vector2d v2f32; + +#ifdef _MSC_VER + // Windows + typedef unsigned long long u64; +#else + // Posix + #include + typedef uint64_t u64; + //typedef unsigned long long u64; +#endif + +#endif + diff --git a/src/config.h b/src/config.h new file mode 100644 index 0000000..54b89a0 --- /dev/null +++ b/src/config.h @@ -0,0 +1,35 @@ +/* + If CMake is used, includes the cmake-generated cmake_config.h. + Otherwise use default values +*/ + +#ifndef CONFIG_H +#define CONFIG_H + +#ifdef USE_CMAKE_CONFIG_H + #include "cmake_config.h" +#else + #define PROJECT_NAME "minetest" + + //#define INSTALL_PREFIX "" + #define VERSION_STRING "unknown" + #ifdef NDEBUG + #define BUILD_TYPE "Release" + #else + #define BUILD_TYPE "Debug" + #endif + #ifdef RUN_IN_PLACE + #define RUN_IN_PLACE_BOOLSTRING "1" + #else + #define RUN_IN_PLACE_BOOLSTRING "0" + #endif + #if USE_GETTEXT + #define USE_GETTEXT_BOOLSTRING "1" + #else + #define USE_GETTEXT_BOOLSTRING "0" + #endif + + #define BUILD_INFO "NON-CMAKE RUN_IN_PLACE="RUN_IN_PLACE_BOOLSTRING" USE_GETTEXT="USE_GETTEXT_BOOLSTRING" BUILD_TYPE="BUILD_TYPE +#endif +#endif + diff --git a/src/connection.cpp b/src/connection.cpp new file mode 100644 index 0000000..89cb7dd --- /dev/null +++ b/src/connection.cpp @@ -0,0 +1,1379 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "connection.h" +#include "main.h" +#include "serialization.h" + +namespace con +{ + +BufferedPacket makePacket(Address &address, u8 *data, u32 datasize, + u32 protocol_id, u16 sender_peer_id, u8 channel) +{ + u32 packet_size = datasize + BASE_HEADER_SIZE; + BufferedPacket p(packet_size); + p.address = address; + + writeU32(&p.data[0], protocol_id); + writeU16(&p.data[4], sender_peer_id); + writeU8(&p.data[6], channel); + + memcpy(&p.data[BASE_HEADER_SIZE], data, datasize); + + return p; +} + +BufferedPacket makePacket(Address &address, SharedBuffer &data, + u32 protocol_id, u16 sender_peer_id, u8 channel) +{ + return makePacket(address, *data, data.getSize(), + protocol_id, sender_peer_id, channel); +} + +SharedBuffer makeOriginalPacket( + SharedBuffer data) +{ + u32 header_size = 1; + u32 packet_size = data.getSize() + header_size; + SharedBuffer b(packet_size); + + writeU8(&b[0], TYPE_ORIGINAL); + + memcpy(&b[header_size], *data, data.getSize()); + + return b; +} + +core::list > makeSplitPacket( + SharedBuffer data, + u32 chunksize_max, + u16 seqnum) +{ + // Chunk packets, containing the TYPE_SPLIT header + core::list > chunks; + + u32 chunk_header_size = 7; + u32 maximum_data_size = chunksize_max - chunk_header_size; + u32 start = 0; + u32 end = 0; + u32 chunk_num = 0; + do{ + end = start + maximum_data_size - 1; + if(end > data.getSize() - 1) + end = data.getSize() - 1; + + u32 payload_size = end - start + 1; + u32 packet_size = chunk_header_size + payload_size; + + SharedBuffer chunk(packet_size); + + writeU8(&chunk[0], TYPE_SPLIT); + writeU16(&chunk[1], seqnum); + // [3] u16 chunk_count is written at next stage + writeU16(&chunk[5], chunk_num); + memcpy(&chunk[chunk_header_size], &data[start], payload_size); + + chunks.push_back(chunk); + + start = end + 1; + chunk_num++; + } + while(end != data.getSize() - 1); + + u16 chunk_count = chunks.getSize(); + + core::list >::Iterator i = chunks.begin(); + for(; i != chunks.end(); i++) + { + // Write chunk_count + writeU16(&((*i)[3]), chunk_count); + } + + return chunks; +} + +core::list > makeAutoSplitPacket( + SharedBuffer data, + u32 chunksize_max, + u16 &split_seqnum) +{ + u32 original_header_size = 1; + core::list > list; + if(data.getSize() + original_header_size > chunksize_max) + { + list = makeSplitPacket(data, chunksize_max, split_seqnum); + split_seqnum++; + return list; + } + else + { + list.push_back(makeOriginalPacket(data)); + } + return list; +} + +SharedBuffer makeReliablePacket( + SharedBuffer data, + u16 seqnum) +{ + /*dstream<<"BEGIN SharedBuffer makeReliablePacket()"< makeReliablePacket()"<::Iterator i; + i = m_list.begin(); + for(; i != m_list.end(); i++) + { + u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); + dout_con<::Iterator i; + i = m_list.begin(); + for(; i != m_list.end(); i++) + { + u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); + /*dout_con<<"findPacket(): finding seqnum="<::Iterator i = m_list.begin(); + m_list.erase(i); + return p; +} +BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum) +{ + RPBSearchResult r = findPacket(seqnum); + if(r == notFound()){ + dout_con<<"Not found"<= BASE_HEADER_SIZE+3); + u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]); + assert(type == TYPE_RELIABLE); + u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]); + + // Find the right place for the packet and insert it there + + // If list is empty, just add it + if(m_list.empty()) + { + m_list.push_back(p); + // Done. + return; + } + // Otherwise find the right place + core::list::Iterator i; + i = m_list.begin(); + // Find the first packet in the list which has a higher seqnum + for(; i != m_list.end(); i++){ + u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); + if(s == seqnum){ + throw AlreadyExistsException("Same seqnum in list"); + } + if(seqnum_higher(s, seqnum)){ + break; + } + } + // If we're at the end of the list, add the packet to the + // end of the list + if(i == m_list.end()) + { + m_list.push_back(p); + // Done. + return; + } + // Insert before i + m_list.insert_before(i, p); +} + +void ReliablePacketBuffer::incrementTimeouts(float dtime) +{ + core::list::Iterator i; + i = m_list.begin(); + for(; i != m_list.end(); i++){ + i->time += dtime; + i->totaltime += dtime; + } +} + +void ReliablePacketBuffer::resetTimedOuts(float timeout) +{ + core::list::Iterator i; + i = m_list.begin(); + for(; i != m_list.end(); i++){ + if(i->time >= timeout) + i->time = 0.0; + } +} + +bool ReliablePacketBuffer::anyTotaltimeReached(float timeout) +{ + core::list::Iterator i; + i = m_list.begin(); + for(; i != m_list.end(); i++){ + if(i->totaltime >= timeout) + return true; + } + return false; +} + +core::list ReliablePacketBuffer::getTimedOuts(float timeout) +{ + core::list timed_outs; + core::list::Iterator i; + i = m_list.begin(); + for(; i != m_list.end(); i++) + { + if(i->time >= timeout) + timed_outs.push_back(*i); + } + return timed_outs; +} + +/* + IncomingSplitBuffer +*/ + +IncomingSplitBuffer::~IncomingSplitBuffer() +{ + core::map::Iterator i; + i = m_buf.getIterator(); + for(; i.atEnd() == false; i++) + { + delete i.getNode()->getValue(); + } +} +/* + This will throw a GotSplitPacketException when a full + split packet is constructed. +*/ +SharedBuffer IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable) +{ + u32 headersize = BASE_HEADER_SIZE + 7; + assert(p.data.getSize() >= headersize); + u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]); + assert(type == TYPE_SPLIT); + u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]); + u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]); + u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]); + + // Add if doesn't exist + if(m_buf.find(seqnum) == NULL) + { + IncomingSplitPacket *sp = new IncomingSplitPacket(); + sp->chunk_count = chunk_count; + sp->reliable = reliable; + m_buf[seqnum] = sp; + } + + IncomingSplitPacket *sp = m_buf[seqnum]; + + // TODO: These errors should be thrown or something? Dunno. + if(chunk_count != sp->chunk_count) + derr_con<<"Connection: WARNING: chunk_count="<chunk_count="<chunk_count + <reliable) + derr_con<<"Connection: WARNING: reliable="<reliable="<reliable + <chunks.find(chunk_num) != NULL) + throw AlreadyExistsException("Chunk already in buffer"); + + // Cut chunk data out of packet + u32 chunkdatasize = p.data.getSize() - headersize; + SharedBuffer chunkdata(chunkdatasize); + memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize); + + // Set chunk data in buffer + sp->chunks[chunk_num] = chunkdata; + + // If not all chunks are received, return empty buffer + if(sp->allReceived() == false) + return SharedBuffer(); + + // Calculate total size + u32 totalsize = 0; + core::map >::Iterator i; + i = sp->chunks.getIterator(); + for(; i.atEnd() == false; i++) + { + totalsize += i.getNode()->getValue().getSize(); + } + + SharedBuffer fulldata(totalsize); + + // Copy chunks to data buffer + u32 start = 0; + for(u32 chunk_i=0; chunk_ichunk_count; + chunk_i++) + { + SharedBuffer buf = sp->chunks[chunk_i]; + u16 chunkdatasize = buf.getSize(); + memcpy(&fulldata[start], *buf, chunkdatasize); + start += chunkdatasize;; + } + + // Remove sp from buffer + m_buf.remove(seqnum); + delete sp; + + return fulldata; +} +void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout) +{ + core::list remove_queue; + core::map::Iterator i; + i = m_buf.getIterator(); + for(; i.atEnd() == false; i++) + { + IncomingSplitPacket *p = i.getNode()->getValue(); + // Reliable ones are not removed by timeout + if(p->reliable == true) + continue; + p->time += dtime; + if(p->time >= timeout) + remove_queue.push_back(i.getNode()->getKey()); + } + core::list::Iterator j; + j = remove_queue.begin(); + for(; j != remove_queue.end(); j++) + { + dout_con<<"NOTE: Removing timed out unreliable split packet" + < RESEND_TIMEOUT_MAX) + timeout = RESEND_TIMEOUT_MAX; + resend_timeout = timeout; +} + +/* + Connection +*/ + +Connection::Connection( + u32 protocol_id, + u32 max_packet_size, + float timeout, + PeerHandler *peerhandler +) +{ + assert(peerhandler != NULL); + + m_protocol_id = protocol_id; + m_max_packet_size = max_packet_size; + m_timeout = timeout; + m_peer_id = PEER_ID_INEXISTENT; + //m_waiting_new_peer_id = false; + m_indentation = 0; + m_peerhandler = peerhandler; +} + +Connection::~Connection() +{ + // Clear peers + core::map::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + delete peer; + } +} + +void Connection::Serve(unsigned short port) +{ + m_socket.Bind(port); + m_peer_id = PEER_ID_SERVER; +} + +void Connection::Connect(Address address) +{ + core::map::Node *node = m_peers.find(PEER_ID_SERVER); + if(node != NULL){ + throw ConnectionException("Already connected to a server"); + } + + Peer *peer = new Peer(PEER_ID_SERVER, address); + m_peers.insert(peer->id, peer); + m_peerhandler->peerAdded(peer); + + m_socket.Bind(0); + + // Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT + m_peer_id = PEER_ID_INEXISTENT; + SharedBuffer data(0); + Send(PEER_ID_SERVER, 0, data, true); + + //m_waiting_new_peer_id = true; +} + +void Connection::Disconnect() +{ + // Create and send DISCO packet + SharedBuffer data(2); + writeU8(&data[0], TYPE_CONTROL); + writeU8(&data[1], CONTROLTYPE_DISCO); + + // Send to all + core::map::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + SendAsPacket(peer->id, 0, data, false); + } +} + +bool Connection::Connected() +{ + if(m_peers.size() != 1) + return false; + + core::map::Node *node = m_peers.find(PEER_ID_SERVER); + if(node == NULL) + return false; + + if(m_peer_id == PEER_ID_INEXISTENT) + return false; + + return true; +} + +SharedBuffer Channel::ProcessPacket( + SharedBuffer packetdata, + Connection *con, + u16 peer_id, + u8 channelnum, + bool reliable) +{ + IndentationRaiser iraiser(&(con->m_indentation)); + + if(packetdata.getSize() < 1) + throw InvalidIncomingDataException("packetdata.getSize() < 1"); + + u8 type = readU8(&packetdata[0]); + + if(type == TYPE_CONTROL) + { + if(packetdata.getSize() < 2) + throw InvalidIncomingDataException("packetdata.getSize() < 2"); + + u8 controltype = readU8(&packetdata[1]); + + if(controltype == CONTROLTYPE_ACK) + { + if(packetdata.getSize() < 4) + throw InvalidIncomingDataException + ("packetdata.getSize() < 4 (ACK header size)"); + + u16 seqnum = readU16(&packetdata[2]); + con->PrintInfo(); + dout_con<<"Got CONTROLTYPE_ACK: channelnum=" + <<((int)channelnum&0xff)<<", peer_id="<PrintInfo(); + outgoing_reliables.print(); + dout_con<PrintInfo(derr_con); + derr_con<<"WARNING: ACKed packet not " + "in outgoing queue" + <PrintInfo(); + dout_con<<"Got new peer id: "<GetPeerID() != PEER_ID_INEXISTENT) + { + con->PrintInfo(derr_con); + derr_con<<"WARNING: Not changing" + " existing peer id."<SetPeerID(peer_id_new); + } + throw ProcessedSilentlyException("Got a SET_PEER_ID"); + } + else if(controltype == CONTROLTYPE_PING) + { + // Just ignore it, the incoming data already reset + // the timeout counter + con->PrintInfo(); + dout_con<<"PING"<PrintInfo(); + dout_con<<"DISCO: Removing peer "<<(peer_id)<deletePeer(peer_id, false) == false) + { + con->PrintInfo(derr_con); + derr_con<<"DISCO: Peer not found"<PrintInfo(derr_con); + derr_con<<"INVALID TYPE_CONTROL: invalid controltype=" + <<((int)controltype&0xff)<PrintInfo(); + dout_con<<"RETURNING TYPE_ORIGINAL to user" + < payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE); + memcpy(*payload, &packetdata[ORIGINAL_HEADER_SIZE], payload.getSize()); + return payload; + } + else if(type == TYPE_SPLIT) + { + // We have to create a packet again for buffering + // This isn't actually too bad an idea. + BufferedPacket packet = makePacket( + con->GetPeer(peer_id)->address, + packetdata, + con->GetProtocolID(), + peer_id, + channelnum); + // Buffer the packet + SharedBuffer data = incoming_splits.insert(packet, reliable); + if(data.getSize() != 0) + { + con->PrintInfo(); + dout_con<<"RETURNING TYPE_SPLIT: Constructed full data, " + <<"size="<PrintInfo(); + dout_con<<"BUFFERED TYPE_SPLIT"<PrintInfo(); + if(is_future_packet) + dout_con<<"BUFFERING"; + else if(is_old_packet) + dout_con<<"OLD"; + else + dout_con<<"RECUR"; + dout_con<<" TYPE_RELIABLE seqnum="< reply(4); + writeU8(&reply[0], TYPE_CONTROL); + writeU8(&reply[1], CONTROLTYPE_ACK); + writeU16(&reply[2], seqnum); + con->SendAsPacket(peer_id, channelnum, reply, false); + + //if(seqnum_higher(seqnum, next_incoming_seqnum)) + if(is_future_packet) + { + /*con->PrintInfo(); + dout_con<<"Buffering reliable packet (seqnum=" + <GetPeer(peer_id)->address, + packetdata, + con->GetProtocolID(), + peer_id, + channelnum); + try{ + incoming_reliables.insert(packet); + + /*con->PrintInfo(); + dout_con<<"INCOMING: "; + incoming_reliables.print(); + dout_con< payload(packetdata.getSize() - RELIABLE_HEADER_SIZE); + memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize()); + + return ProcessPacket(payload, con, peer_id, channelnum, true); + } + else + { + con->PrintInfo(derr_con); + derr_con<<"Got invalid type="<<((int)type&0xff)< Channel::CheckIncomingBuffers(Connection *con, + u16 &peer_id) +{ + u16 firstseqnum = 0; + // Clear old packets from start of buffer + try{ + for(;;){ + firstseqnum = incoming_reliables.getFirstSeqnum(); + if(seqnum_higher(next_incoming_seqnum, firstseqnum)) + incoming_reliables.popFirst(); + else + break; + } + // This happens if all packets are old + }catch(con::NotFoundException) + {} + + if(incoming_reliables.empty() == false) + { + if(firstseqnum == next_incoming_seqnum) + { + BufferedPacket p = incoming_reliables.popFirst(); + + peer_id = readPeerId(*p.data); + u8 channelnum = readChannel(*p.data); + u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]); + + con->PrintInfo(); + dout_con<<"UNBUFFERING TYPE_RELIABLE" + <<" seqnum="< Connection::GetFromBuffers(u16 &peer_id) +{ + core::map::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + for(u16 i=0; ichannels[i]; + try{ + SharedBuffer resultdata = channel->CheckIncomingBuffers + (this, peer_id); + + return resultdata; + } + catch(NoIncomingDataException &e) + { + } + catch(InvalidIncomingDataException &e) + { + } + catch(ProcessedSilentlyException &e) + { + } + } + } + throw NoIncomingDataException("No relevant data in buffers"); +} + +u32 Connection::Receive(u16 &peer_id, u8 *data, u32 datasize) +{ + /* + Receive a packet from the network + */ + + // TODO: We can not know how many layers of header there are. + // For now, just assume there are no other than the base headers. + u32 packet_maxsize = datasize + BASE_HEADER_SIZE; + Buffer packetdata(packet_maxsize); + + for(;;) + { + try + { + /* + Check if some buffer has relevant data + */ + try{ + SharedBuffer resultdata = GetFromBuffers(peer_id); + + if(datasize < resultdata.getSize()) + throw InvalidIncomingDataException + ("Buffer too small for received data"); + + memcpy(data, *resultdata, resultdata.getSize()); + return resultdata.getSize(); + } + catch(NoIncomingDataException &e) + { + } + + Address sender; + + s32 received_size = m_socket.Receive(sender, *packetdata, packet_maxsize); + + if(received_size < 0) + throw NoIncomingDataException("No incoming data"); + if(received_size < BASE_HEADER_SIZE) + throw InvalidIncomingDataException("No full header received"); + if(readU32(&packetdata[0]) != m_protocol_id) + throw InvalidIncomingDataException("Invalid protocol id"); + + peer_id = readPeerId(*packetdata); + u8 channelnum = readChannel(*packetdata); + if(channelnum > CHANNEL_COUNT-1){ + PrintInfo(derr_con); + derr_con<<"Receive(): Invalid channel "<::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + if(peer->has_sent_with_id) + continue; + if(peer->address == sender) + break; + } + + /* + If no peer was found with the same address and port, + we shall assume it is a new peer and create an entry. + */ + if(j.atEnd()) + { + // Pass on to adding the peer + } + // Else: A peer was found. + else + { + Peer *peer = j.getNode()->getValue(); + peer_id = peer->id; + PrintInfo(derr_con); + derr_con<<"WARNING: Assuming unknown peer to be " + <<"peer_id="<getValue(); + + // Validate peer address + if(peer->address != sender) + { + PrintInfo(derr_con); + derr_con<<"Peer "<timeout_counter = 0.0; + + Channel *channel = &(peer->channels[channelnum]); + + // Throw the received packet to channel->processPacket() + + // Make a new SharedBuffer from the data without the base headers + SharedBuffer strippeddata(received_size - BASE_HEADER_SIZE); + memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE], + strippeddata.getSize()); + + try{ + // Process it (the result is some data with no headers made by us) + SharedBuffer resultdata = channel->ProcessPacket + (strippeddata, this, peer_id, channelnum); + + PrintInfo(); + dout_con<<"ProcessPacket returned data of size " + < data, bool reliable) +{ + core::map::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + Send(peer->id, channelnum, data, reliable); + } +} + +void Connection::Send(u16 peer_id, u8 channelnum, + SharedBuffer data, bool reliable) +{ + assert(channelnum < CHANNEL_COUNT); + + Peer *peer = GetPeerNoEx(peer_id); + if(peer == NULL) + return; + Channel *channel = &(peer->channels[channelnum]); + + u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE; + if(reliable) + chunksize_max -= RELIABLE_HEADER_SIZE; + + core::list > originals; + originals = makeAutoSplitPacket(data, chunksize_max, + channel->next_outgoing_split_seqnum); + + core::list >::Iterator i; + i = originals.begin(); + for(; i != originals.end(); i++) + { + SharedBuffer original = *i; + + SendAsPacket(peer_id, channelnum, original, reliable); + } +} + +void Connection::SendAsPacket(u16 peer_id, u8 channelnum, + SharedBuffer data, bool reliable) +{ + Peer *peer = GetPeer(peer_id); + Channel *channel = &(peer->channels[channelnum]); + + if(reliable) + { + u16 seqnum = channel->next_outgoing_seqnum; + channel->next_outgoing_seqnum++; + + SharedBuffer reliable = makeReliablePacket(data, seqnum); + + // Add base headers and make a packet + BufferedPacket p = makePacket(peer->address, reliable, + m_protocol_id, m_peer_id, channelnum); + + try{ + // Buffer the packet + channel->outgoing_reliables.insert(p); + } + catch(AlreadyExistsException &e) + { + PrintInfo(derr_con); + derr_con<<"WARNING: Going to send a reliable packet " + "seqnum="<address, data, + m_protocol_id, m_peer_id, channelnum); + + // Send the packet + RawSend(p); + } +} + +void Connection::RawSend(const BufferedPacket &packet) +{ + m_socket.Send(packet.address, *packet.data, packet.data.getSize()); +} + +void Connection::RunTimeouts(float dtime) +{ + core::list timeouted_peers; + core::map::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + + /* + Check peer timeout + */ + peer->timeout_counter += dtime; + if(peer->timeout_counter > m_timeout) + { + PrintInfo(derr_con); + derr_con<<"RunTimeouts(): Peer "<id + <<" has timed out." + <<" (source=peer->timeout_counter)" + <id); + // Don't bother going through the buffers of this one + continue; + } + + float resend_timeout = peer->resend_timeout; + for(u16 i=0; i timed_outs; + core::list::Iterator j; + + Channel *channel = &peer->channels[i]; + + // Remove timed out incomplete unreliable split packets + channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout); + + // Increment reliable packet times + channel->outgoing_reliables.incrementTimeouts(dtime); + + // Check reliable packet total times, remove peer if + // over timeout. + if(channel->outgoing_reliables.anyTotaltimeReached(m_timeout)) + { + PrintInfo(derr_con); + derr_con<<"RunTimeouts(): Peer "<id + <<" has timed out." + <<" (source=reliable packet totaltime)" + <id); + goto nextpeer; + } + + // Re-send timed out outgoing reliables + + timed_outs = channel-> + outgoing_reliables.getTimedOuts(resend_timeout); + + channel->outgoing_reliables.resetTimedOuts(resend_timeout); + + j = timed_outs.begin(); + for(; j != timed_outs.end(); j++) + { + u16 peer_id = readPeerId(*(j->data)); + u8 channel = readChannel(*(j->data)); + u16 seqnum = readU16(&(j->data[BASE_HEADER_SIZE+1])); + + PrintInfo(derr_con); + derr_con<<"RE-SENDING timed-out RELIABLE to "; + j->address.print(&derr_con); + derr_con<<"(t/o="<::Node *node = m_peers.find(peer_id); + + if(node == NULL){ + // Peer not found + throw PeerNotFoundException("GetPeer: Peer not found (possible timeout)"); + } + + // Error checking + assert(node->getValue()->id == peer_id); + + return node->getValue(); +} + +Peer* Connection::GetPeerNoEx(u16 peer_id) +{ + core::map::Node *node = m_peers.find(peer_id); + + if(node == NULL){ + return NULL; + } + + // Error checking + assert(node->getValue()->id == peer_id); + + return node->getValue(); +} + +core::list Connection::GetPeers() +{ + core::list list; + core::map::Iterator j; + j = m_peers.getIterator(); + for(; j.atEnd() == false; j++) + { + Peer *peer = j.getNode()->getValue(); + list.push_back(peer); + } + return list; +} + +bool Connection::deletePeer(u16 peer_id, bool timeout) +{ + if(m_peers.find(peer_id) == NULL) + return false; + m_peerhandler->deletingPeer(m_peers[peer_id], timeout); + delete m_peers[peer_id]; + m_peers.remove(peer_id); + return true; +} + +void Connection::PrintInfo(std::ostream &out) +{ + out< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONNECTION_HEADER +#define CONNECTION_HEADER + +#include +#include +#include "debug.h" +#include "common_irrlicht.h" +#include "socket.h" +#include "utility.h" +#include "exceptions.h" +#include "constants.h" + +namespace con +{ + +/* + Exceptions +*/ +class NotFoundException : public BaseException +{ +public: + NotFoundException(const char *s): + BaseException(s) + {} +}; + +class PeerNotFoundException : public BaseException +{ +public: + PeerNotFoundException(const char *s): + BaseException(s) + {} +}; + +class ConnectionException : public BaseException +{ +public: + ConnectionException(const char *s): + BaseException(s) + {} +}; + +/*class ThrottlingException : public BaseException +{ +public: + ThrottlingException(const char *s): + BaseException(s) + {} +};*/ + +class InvalidIncomingDataException : public BaseException +{ +public: + InvalidIncomingDataException(const char *s): + BaseException(s) + {} +}; + +class InvalidOutgoingDataException : public BaseException +{ +public: + InvalidOutgoingDataException(const char *s): + BaseException(s) + {} +}; + +class NoIncomingDataException : public BaseException +{ +public: + NoIncomingDataException(const char *s): + BaseException(s) + {} +}; + +class ProcessedSilentlyException : public BaseException +{ +public: + ProcessedSilentlyException(const char *s): + BaseException(s) + {} +}; + +inline u16 readPeerId(u8 *packetdata) +{ + return readU16(&packetdata[4]); +} +inline u8 readChannel(u8 *packetdata) +{ + return readU8(&packetdata[6]); +} + +#define SEQNUM_MAX 65535 +inline bool seqnum_higher(u16 higher, u16 lower) +{ + if(lower > higher && lower - higher > SEQNUM_MAX/2){ + return true; + } + return (higher > lower); +} + +struct BufferedPacket +{ + BufferedPacket(u8 *a_data, u32 a_size): + data(a_data, a_size), time(0.0), totaltime(0.0) + {} + BufferedPacket(u32 a_size): + data(a_size), time(0.0), totaltime(0.0) + {} + SharedBuffer data; // Data of the packet, including headers + float time; // Seconds from buffering the packet or re-sending + float totaltime; // Seconds from buffering the packet + Address address; // Sender or destination +}; + +// This adds the base headers to the data and makes a packet out of it +BufferedPacket makePacket(Address &address, u8 *data, u32 datasize, + u32 protocol_id, u16 sender_peer_id, u8 channel); +BufferedPacket makePacket(Address &address, SharedBuffer &data, + u32 protocol_id, u16 sender_peer_id, u8 channel); + +// Add the TYPE_ORIGINAL header to the data +SharedBuffer makeOriginalPacket( + SharedBuffer data); + +// Split data in chunks and add TYPE_SPLIT headers to them +core::list > makeSplitPacket( + SharedBuffer data, + u32 chunksize_max, + u16 seqnum); + +// Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet +// Increments split_seqnum if a split packet is made +core::list > makeAutoSplitPacket( + SharedBuffer data, + u32 chunksize_max, + u16 &split_seqnum); + +// Add the TYPE_RELIABLE header to the data +SharedBuffer makeReliablePacket( + SharedBuffer data, + u16 seqnum); + +struct IncomingSplitPacket +{ + IncomingSplitPacket() + { + time = 0.0; + reliable = false; + } + // Key is chunk number, value is data without headers + core::map > chunks; + u32 chunk_count; + float time; // Seconds from adding + bool reliable; // If true, isn't deleted on timeout + + bool allReceived() + { + return (chunks.size() == chunk_count); + } +}; + +/* +=== NOTES === + +A packet is sent through a channel to a peer with a basic header: +TODO: Should we have a receiver_peer_id also? + Header (7 bytes): + [0] u32 protocol_id + [4] u16 sender_peer_id + [6] u8 channel +sender_peer_id: + Unique to each peer. + value 0 is reserved for making new connections + value 1 is reserved for server +channel: + The lower the number, the higher the priority is. + Only channels 0, 1 and 2 exist. +*/ +#define BASE_HEADER_SIZE 7 +#define PEER_ID_INEXISTENT 0 +#define PEER_ID_SERVER 1 +#define CHANNEL_COUNT 3 +/* +Packet types: + +CONTROL: This is a packet used by the protocol. +- When this is processed, nothing is handed to the user. + Header (2 byte): + [0] u8 type + [1] u8 controltype +controltype and data description: + CONTROLTYPE_ACK + [2] u16 seqnum + CONTROLTYPE_SET_PEER_ID + [2] u16 peer_id_new + CONTROLTYPE_PING + - There is no actual reply, but this can be sent in a reliable + packet to get a reply + CONTROLTYPE_DISCO +*/ +#define TYPE_CONTROL 0 +#define CONTROLTYPE_ACK 0 +#define CONTROLTYPE_SET_PEER_ID 1 +#define CONTROLTYPE_PING 2 +#define CONTROLTYPE_DISCO 3 +/* +ORIGINAL: This is a plain packet with no control and no error +checking at all. +- When this is processed, it is directly handed to the user. + Header (1 byte): + [0] u8 type +*/ +#define TYPE_ORIGINAL 1 +#define ORIGINAL_HEADER_SIZE 1 +/* +SPLIT: These are sequences of packets forming one bigger piece of +data. +- When processed and all the packet_nums 0...packet_count-1 are + present (this should be buffered), the resulting data shall be + directly handed to the user. +- If the data fails to come up in a reasonable time, the buffer shall + be silently discarded. +- These can be sent as-is or atop of a RELIABLE packet stream. + Header (7 bytes): + [0] u8 type + [1] u16 seqnum + [3] u16 chunk_count + [5] u16 chunk_num +*/ +#define TYPE_SPLIT 2 +/* +RELIABLE: Delivery of all RELIABLE packets shall be forced by ACKs, +and they shall be delivered in the same order as sent. This is done +with a buffer in the receiving and transmitting end. +- When this is processed, the contents of each packet is recursively + processed as packets. + Header (3 bytes): + [0] u8 type + [1] u16 seqnum + +*/ +#define TYPE_RELIABLE 3 +#define RELIABLE_HEADER_SIZE 3 +//#define SEQNUM_INITIAL 0x10 +#define SEQNUM_INITIAL 65500 + +/* + A buffer which stores reliable packets and sorts them internally + for fast access to the smallest one. +*/ + +typedef core::list::Iterator RPBSearchResult; + +class ReliablePacketBuffer +{ +public: + + void print(); + bool empty(); + u32 size(); + RPBSearchResult findPacket(u16 seqnum); + RPBSearchResult notFound(); + u16 getFirstSeqnum(); + BufferedPacket popFirst(); + BufferedPacket popSeqnum(u16 seqnum); + void insert(BufferedPacket &p); + void incrementTimeouts(float dtime); + void resetTimedOuts(float timeout); + bool anyTotaltimeReached(float timeout); + core::list getTimedOuts(float timeout); + +private: + core::list m_list; +}; + +/* + A buffer for reconstructing split packets +*/ + +class IncomingSplitBuffer +{ +public: + ~IncomingSplitBuffer(); + /* + Returns a reference counted buffer of length != 0 when a full split + packet is constructed. If not, returns one of length 0. + */ + SharedBuffer insert(BufferedPacket &p, bool reliable); + + void removeUnreliableTimedOuts(float dtime, float timeout); + +private: + // Key is seqnum + core::map m_buf; +}; + +class Connection; + +struct Channel +{ + Channel(); + ~Channel(); + /* + Processes a packet with the basic header stripped out. + Parameters: + packetdata: Data in packet (with no base headers) + con: The connection to which the channel is associated + (used for sending back stuff (ACKs)) + peer_id: peer id of the sender of the packet in question + channelnum: channel on which the packet was sent + reliable: true if recursing into a reliable packet + */ + SharedBuffer ProcessPacket( + SharedBuffer packetdata, + Connection *con, + u16 peer_id, + u8 channelnum, + bool reliable=false); + + // Returns next data from a buffer if possible + // throws a NoIncomingDataException if no data is available + // If found, sets peer_id + SharedBuffer CheckIncomingBuffers(Connection *con, + u16 &peer_id); + + u16 next_outgoing_seqnum; + u16 next_incoming_seqnum; + u16 next_outgoing_split_seqnum; + + // This is for buffering the incoming packets that are coming in + // the wrong order + ReliablePacketBuffer incoming_reliables; + // This is for buffering the sent packets so that the sender can + // re-send them if no ACK is received + ReliablePacketBuffer outgoing_reliables; + + IncomingSplitBuffer incoming_splits; +}; + +class Peer; + +class PeerHandler +{ +public: + PeerHandler() + { + } + virtual ~PeerHandler() + { + } + + /* + This is called after the Peer has been inserted into the + Connection's peer container. + */ + virtual void peerAdded(Peer *peer) = 0; + /* + This is called before the Peer has been removed from the + Connection's peer container. + */ + virtual void deletingPeer(Peer *peer, bool timeout) = 0; +}; + +class Peer +{ +public: + + Peer(u16 a_id, Address a_address); + virtual ~Peer(); + + /* + Calculates avg_rtt and resend_timeout. + + rtt=-1 only recalculates resend_timeout + */ + void reportRTT(float rtt); + + Channel channels[CHANNEL_COUNT]; + + // Address of the peer + Address address; + // Unique id of the peer + u16 id; + // Seconds from last receive + float timeout_counter; + // Ping timer + float ping_timer; + // This is changed dynamically + float resend_timeout; + // Updated when an ACK is received + float avg_rtt; + // This is set to true when the peer has actually sent something + // with the id we have given to it + bool has_sent_with_id; + +private: +}; + +class Connection +{ +public: + Connection( + u32 protocol_id, + u32 max_packet_size, + float timeout, + PeerHandler *peerhandler + ); + ~Connection(); + void setTimeoutMs(int timeout){ m_socket.setTimeoutMs(timeout); } + // Start being a server + void Serve(unsigned short port); + // Connect to a server + void Connect(Address address); + bool Connected(); + + void Disconnect(); + + // Sets peer_id + SharedBuffer GetFromBuffers(u16 &peer_id); + + // The peer_id of sender is stored in peer_id + // Return value: I guess this always throws an exception or + // actually gets data + // May call PeerHandler methods + u32 Receive(u16 &peer_id, u8 *data, u32 datasize); + + // These will automatically package the data as an original or split + void SendToAll(u8 channelnum, SharedBuffer data, bool reliable); + void Send(u16 peer_id, u8 channelnum, SharedBuffer data, bool reliable); + // Send data as a packet; it will be wrapped in base header and + // optionally to a reliable packet. + void SendAsPacket(u16 peer_id, u8 channelnum, + SharedBuffer data, bool reliable); + // Sends a raw packet + void RawSend(const BufferedPacket &packet); + + // May call PeerHandler methods + void RunTimeouts(float dtime); + + // Can throw a PeerNotFoundException + Peer* GetPeer(u16 peer_id); + // returns NULL if failed + Peer* GetPeerNoEx(u16 peer_id); + core::list GetPeers(); + + // Calls PeerHandler::deletingPeer + // Returns false if peer was not found + bool deletePeer(u16 peer_id, bool timeout); + + void SetPeerID(u16 id){ m_peer_id = id; } + u16 GetPeerID(){ return m_peer_id; } + u32 GetProtocolID(){ return m_protocol_id; } + + // For debug printing + void PrintInfo(std::ostream &out); + void PrintInfo(); + u16 m_indentation; + +private: + u32 m_protocol_id; + float m_timeout; + PeerHandler *m_peerhandler; + core::map m_peers; + u16 m_peer_id; + //bool m_waiting_new_peer_id; + u32 m_max_packet_size; + UDPSocket m_socket; +}; + +} // namespace + +#endif + diff --git a/src/constants.h b/src/constants.h new file mode 100644 index 0000000..1af5f1f --- /dev/null +++ b/src/constants.h @@ -0,0 +1,110 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONSTANTS_HEADER +#define CONSTANTS_HEADER + +/* + All kinds of constants. + + Cross-platform compatibility crap should go in porting.h. +*/ + +//#define HAXMODE 0 + +#define DEBUGFILE "debug.txt" + +// Define for simulating the quirks of sending through internet. +// Causes the socket class to deliberately drop random packets. +// This disables unit testing of socket and connection. +#define INTERNET_SIMULATOR 0 + +#define CONNECTION_TIMEOUT 30 + +#define RESEND_TIMEOUT_MIN 0.333 +#define RESEND_TIMEOUT_MAX 3.0 +// resend_timeout = avg_rtt * this +#define RESEND_TIMEOUT_FACTOR 4 + +#define PI 3.14159 + +// This is the same as in minecraft and everything else +#define FOV_ANGLE (PI/2.5) + +// The absolute working limit is (2^15 - viewing_range). +// I really don't want to make every algorithm to check if it's +// going near the limit or not, so this is lower. +#define MAP_GENERATION_LIMIT (31000) + +// Size of node in rendering units +#define BS 10 + +#define MAP_BLOCKSIZE 16 +/* + This makes mesh updates too slow, as many meshes are updated during + the main loop (related to TempMods and day/night) +*/ +//#define MAP_BLOCKSIZE 32 + +// Sectors are split to SECTOR_HEIGHTMAP_SPLIT^2 heightmaps +#define SECTOR_HEIGHTMAP_SPLIT (MAP_BLOCKSIZE/8) + +// Time after building, during which the following limit +// is in use +//#define FULL_BLOCK_SEND_ENABLE_MIN_TIME_FROM_BUILDING 2.0 +// This many blocks are sent when player is building +#define LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS 0 +// Override for the previous one when distance of block +// is very low +#define BLOCK_SEND_DISABLE_LIMITS_MAX_D 1 + +#define PLAYER_INVENTORY_SIZE (8*4) + +#define SIGN_TEXT_MAX_LENGTH 50 + +// Whether to catch all std::exceptions. +// Assert will be called on such an event. +// In debug mode, leave these for the debugger and don't catch them. +#ifdef NDEBUG + #define CATCH_UNHANDLED_EXCEPTIONS 1 +#else + #define CATCH_UNHANDLED_EXCEPTIONS 0 +#endif + +/* + Collecting active blocks is stopped after object data + size reaches this +*/ +#define MAX_OBJECTDATA_SIZE 450 + +/* + This is good to be a bit different than 0 so that water level + is not between two MapBlocks +*/ +#define WATER_LEVEL 1 + +// Length of cracking animation in count of images +#define CRACK_ANIMATION_LENGTH 5 + +// Some stuff needed by old code moved to here from heightmap.h +#define GROUNDHEIGHT_NOTFOUND_SETVALUE (-10e6) +#define GROUNDHEIGHT_VALID_MINVALUE ( -9e6) + +#endif + diff --git a/src/content_cao.cpp b/src/content_cao.cpp new file mode 100644 index 0000000..dfeaea8 --- /dev/null +++ b/src/content_cao.cpp @@ -0,0 +1,912 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_cao.h" +#include "tile.h" +#include "environment.h" + +core::map ClientActiveObject::m_types; + +/* + TestCAO +*/ + +// Prototype +TestCAO proto_TestCAO; + +TestCAO::TestCAO(): + ClientActiveObject(0), + m_node(NULL), + m_position(v3f(0,10*BS,0)) +{ + ClientActiveObject::registerType(getType(), create); +} + +TestCAO::~TestCAO() +{ +} + +ClientActiveObject* TestCAO::create() +{ + return new TestCAO(); +} + +void TestCAO::addToScene(scene::ISceneManager *smgr) +{ + if(m_node != NULL) + return; + + video::IVideoDriver* driver = smgr->getVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("rat.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + updateNodePos(); +} + +void TestCAO::removeFromScene() +{ + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; +} + +void TestCAO::updateLight(u8 light_at_pos) +{ +} + +v3s16 TestCAO::getLightPosition() +{ + return floatToInt(m_position, BS); +} + +void TestCAO::updateNodePos() +{ + if(m_node == NULL) + return; + + m_node->setPosition(m_position); + //m_node->setRotation(v3f(0, 45, 0)); +} + +void TestCAO::step(float dtime, ClientEnvironment *env) +{ + if(m_node) + { + v3f rot = m_node->getRotation(); + //dstream<<"dtime="<>cmd; + if(cmd == 0) + { + v3f newpos; + is>>newpos.X; + is>>newpos.Y; + is>>newpos.Z; + m_position = newpos; + updateNodePos(); + } +} + +/* + ItemCAO +*/ + +#include "inventory.h" + +// Prototype +ItemCAO proto_ItemCAO; + +ItemCAO::ItemCAO(): + ClientActiveObject(0), + m_selection_box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.), + m_node(NULL), + m_position(v3f(0,10*BS,0)) +{ + ClientActiveObject::registerType(getType(), create); +} + +ItemCAO::~ItemCAO() +{ +} + +ClientActiveObject* ItemCAO::create() +{ + return new ItemCAO(); +} + +void ItemCAO::addToScene(scene::ISceneManager *smgr) +{ + if(m_node != NULL) + return; + + video::IVideoDriver* driver = smgr->getVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),*/ + video::S3DVertex(BS/3.,0,0, 0,0,0, c, 0,1), + video::S3DVertex(-BS/3.,0,0, 0,0,0, c, 1,1), + video::S3DVertex(-BS/3.,0+BS*2./3.,0, 0,0,0, c, 1,0), + video::S3DVertex(BS/3.,0+BS*2./3.,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + //buf->getMaterial().setTexture(0, NULL); + // Initialize with the stick texture + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("stick.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + // Set it to use the materials of the meshbuffers directly. + // This is needed for changing the texture in the future + m_node->setReadOnlyMaterials(true); + updateNodePos(); +} + +void ItemCAO::removeFromScene() +{ + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; +} + +void ItemCAO::updateLight(u8 light_at_pos) +{ + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + if(mesh == NULL) + return; + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(m_position); +} + +void ItemCAO::step(float dtime, ClientEnvironment *env) +{ + if(m_node) + { + /*v3f rot = m_node->getRotation(); + rot.Y += dtime * 120; + m_node->setRotation(rot);*/ + LocalPlayer *player = env->getLocalPlayer(); + assert(player); + v3f rot = m_node->getRotation(); + rot.Y = 180.0 - (player->getYaw()); + m_node->setRotation(rot); + } +} + +void ItemCAO::processMessage(const std::string &data) +{ + dstream<<"ItemCAO: Got message"<getMesh(); + + if(mesh == NULL) + return; + + scene::IMeshBuffer *buf = mesh->getMeshBuffer(0); + + if(buf == NULL) + return; + + // Create an inventory item to see what is its image + std::istringstream is(m_inventorystring, std::ios_base::binary); + video::ITexture *texture = NULL; + try{ + InventoryItem *item = NULL; + item = InventoryItem::deSerialize(is); + dstream<<__FUNCTION_NAME<<": m_inventorystring=\"" + < item="<getImage(); + delete item; + } + } + catch(SerializationError &e) + { + dstream<<"WARNING: "<<__FUNCTION_NAME + <<": error deSerializing inventorystring \"" + <getMaterial().setTexture(0, texture); + +} + +/* + RatCAO +*/ + +#include "inventory.h" + +// Prototype +RatCAO proto_RatCAO; + +RatCAO::RatCAO(): + ClientActiveObject(0), + m_selection_box(-BS/3.,0.0,-BS/3., BS/3.,BS/2.,BS/3.), + m_node(NULL), + m_position(v3f(0,10*BS,0)), + m_yaw(0) +{ + ClientActiveObject::registerType(getType(), create); +} + +RatCAO::~RatCAO() +{ +} + +ClientActiveObject* RatCAO::create() +{ + return new RatCAO(); +} + +void RatCAO::addToScene(scene::ISceneManager *smgr) +{ + if(m_node != NULL) + return; + + video::IVideoDriver* driver = smgr->getVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + //buf->getMaterial().setTexture(0, NULL); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("rat.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + // Set it to use the materials of the meshbuffers directly. + // This is needed for changing the texture in the future + m_node->setReadOnlyMaterials(true); + updateNodePos(); +} + +void RatCAO::removeFromScene() +{ + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; +} + +void RatCAO::updateLight(u8 light_at_pos) +{ + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + if(mesh == NULL) + return; + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(m_position); + m_node->setPosition(pos_translator.vect_show); + + v3f rot = m_node->getRotation(); + rot.Y = 180.0 - m_yaw; + m_node->setRotation(rot); +} + +void RatCAO::step(float dtime, ClientEnvironment *env) +{ + pos_translator.translate(dtime); + updateNodePos(); +} + +void RatCAO::processMessage(const std::string &data) +{ + //dstream<<"RatCAO: Got message"<getVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2-BS,0,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2+BS,0,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2+BS,BS*2,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2-BS,BS*2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + //buf->getMaterial().setTexture(0, NULL); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("oerkki1.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + // Set it to use the materials of the meshbuffers directly. + // This is needed for changing the texture in the future + m_node->setReadOnlyMaterials(true); + updateNodePos(); +} + +void Oerkki1CAO::removeFromScene() +{ + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; +} + +void Oerkki1CAO::updateLight(u8 light_at_pos) +{ + if(m_node == NULL) + return; + + if(light_at_pos <= 2) + { + m_node->setVisible(false); + return; + } + + m_node->setVisible(true); + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + if(mesh == NULL) + return; + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(m_position); + m_node->setPosition(pos_translator.vect_show); + + v3f rot = m_node->getRotation(); + rot.Y = 180.0 - m_yaw + 90.0; + m_node->setRotation(rot); +} + +void Oerkki1CAO::step(float dtime, ClientEnvironment *env) +{ + pos_translator.translate(dtime); + updateNodePos(); + + LocalPlayer *player = env->getLocalPlayer(); + assert(player); + + v3f playerpos = player->getPosition(); + v2f playerpos_2d(playerpos.X,playerpos.Z); + v2f objectpos_2d(m_position.X,m_position.Z); + + if(fabs(m_position.Y - playerpos.Y) < 3.0*BS && + objectpos_2d.getDistanceFrom(playerpos_2d) < 1.5*BS) + { + if(m_attack_interval.step(dtime, 0.5)) + { + env->damageLocalPlayer(2); + } + } + + if(m_damage_visual_timer > 0) + { + if(!m_damage_texture_enabled) + { + // Enable damage texture + if(m_node) + { + video::IVideoDriver* driver = + m_node->getSceneManager()->getVideoDriver(); + + scene::IMesh *mesh = m_node->getMesh(); + if(mesh == NULL) + return; + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + buf->getMaterial().setTexture(0, driver->getTexture( + getTexturePath("oerkki1_damaged.png").c_str())); + } + } + m_damage_texture_enabled = true; + } + m_damage_visual_timer -= dtime; + } + else + { + if(m_damage_texture_enabled) + { + // Disable damage texture + if(m_node) + { + video::IVideoDriver* driver = + m_node->getSceneManager()->getVideoDriver(); + + scene::IMesh *mesh = m_node->getMesh(); + if(mesh == NULL) + return; + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + buf->getMaterial().setTexture(0, driver->getTexture( + getTexturePath("oerkki1.png").c_str())); + } + } + m_damage_texture_enabled = false; + } + } +} + +void Oerkki1CAO::processMessage(const std::string &data) +{ + //dstream<<"Oerkki1CAO: Got message"<getVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(0,0,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, 1,0), + video::S3DVertex(0,BS/2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + //buf->getMaterial().setTexture(0, NULL); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("firefly.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + // Set it to use the materials of the meshbuffers directly. + // This is needed for changing the texture in the future + m_node->setReadOnlyMaterials(true); + updateNodePos(); +} + +void FireflyCAO::removeFromScene() +{ + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; +} + +void FireflyCAO::updateLight(u8 light_at_pos) +{ + if(m_node == NULL) + return; + + u8 li = 255; + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + if(mesh == NULL) + return; + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(m_position); + m_node->setPosition(pos_translator.vect_show); + + v3f rot = m_node->getRotation(); + rot.Y = 180.0 - m_yaw; + m_node->setRotation(rot); +} + +void FireflyCAO::step(float dtime, ClientEnvironment *env) +{ + pos_translator.translate(dtime); + updateNodePos(); +} + +void FireflyCAO::processMessage(const std::string &data) +{ + //dstream<<"FireflyCAO: Got message"< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_CAO_HEADER +#define CONTENT_CAO_HEADER + +#include "clientobject.h" +#include "content_object.h" +#include "utility.h" // For IntervalLimiter + +/* + SmoothTranslator +*/ + +struct SmoothTranslator +{ + v3f vect_old; + f32 anim_counter; + f32 anim_time; + f32 anim_time_counter; + v3f vect_show; + v3f vect_aim; + + SmoothTranslator(): + vect_old(0,0,0), + anim_counter(0), + anim_time(0), + anim_time_counter(0), + vect_show(0,0,0), + vect_aim(0,0,0) + {} + + void init(v3f vect) + { + vect_old = vect; + vect_show = vect; + vect_aim = vect; + } + + void update(v3f vect_new) + { + vect_old = vect_show; + vect_aim = vect_new; + if(anim_time < 0.001 || anim_time > 1.0) + anim_time = anim_time_counter; + else + anim_time = anim_time * 0.9 + anim_time_counter * 0.1; + anim_time_counter = 0; + anim_counter = 0; + } + + void translate(f32 dtime) + { + anim_time_counter = anim_time_counter + dtime; + anim_counter = anim_counter + dtime; + v3f vect_move = vect_aim - vect_old; + f32 moveratio = 1.0; + if(anim_time > 0.001) + moveratio = anim_time_counter / anim_time; + // Move a bit less than should, to avoid oscillation + moveratio = moveratio * 0.8; + if(moveratio > 1.5) + moveratio = 1.5; + vect_show = vect_old + vect_move * moveratio; + } +}; + + +/* + TestCAO +*/ + +class TestCAO : public ClientActiveObject +{ +public: + TestCAO(); + virtual ~TestCAO(); + + u8 getType() const + { + return ACTIVEOBJECT_TYPE_TEST; + } + + static ClientActiveObject* create(); + + void addToScene(scene::ISceneManager *smgr); + void removeFromScene(); + void updateLight(u8 light_at_pos); + v3s16 getLightPosition(); + void updateNodePos(); + + void step(float dtime, ClientEnvironment *env); + + void processMessage(const std::string &data); + +private: + scene::IMeshSceneNode *m_node; + v3f m_position; +}; + +/* + ItemCAO +*/ + +class ItemCAO : public ClientActiveObject +{ +public: + ItemCAO(); + virtual ~ItemCAO(); + + u8 getType() const + { + return ACTIVEOBJECT_TYPE_ITEM; + } + + static ClientActiveObject* create(); + + void addToScene(scene::ISceneManager *smgr); + void removeFromScene(); + void updateLight(u8 light_at_pos); + v3s16 getLightPosition(); + void updateNodePos(); + + void step(float dtime, ClientEnvironment *env); + + void processMessage(const std::string &data); + + void initialize(const std::string &data); + + core::aabbox3d* getSelectionBox() + {return &m_selection_box;} + v3f getPosition() + {return m_position;} + +private: + core::aabbox3d m_selection_box; + scene::IMeshSceneNode *m_node; + v3f m_position; + std::string m_inventorystring; +}; + +/* + RatCAO +*/ + +class RatCAO : public ClientActiveObject +{ +public: + RatCAO(); + virtual ~RatCAO(); + + u8 getType() const + { + return ACTIVEOBJECT_TYPE_RAT; + } + + static ClientActiveObject* create(); + + void addToScene(scene::ISceneManager *smgr); + void removeFromScene(); + void updateLight(u8 light_at_pos); + v3s16 getLightPosition(); + void updateNodePos(); + + void step(float dtime, ClientEnvironment *env); + + void processMessage(const std::string &data); + + void initialize(const std::string &data); + + core::aabbox3d* getSelectionBox() + {return &m_selection_box;} + v3f getPosition() + {return pos_translator.vect_show;} + //{return m_position;} + +private: + core::aabbox3d m_selection_box; + scene::IMeshSceneNode *m_node; + v3f m_position; + float m_yaw; + SmoothTranslator pos_translator; +}; + +/* + Oerkki1CAO +*/ + +class Oerkki1CAO : public ClientActiveObject +{ +public: + Oerkki1CAO(); + virtual ~Oerkki1CAO(); + + u8 getType() const + { + return ACTIVEOBJECT_TYPE_OERKKI1; + } + + static ClientActiveObject* create(); + + void addToScene(scene::ISceneManager *smgr); + void removeFromScene(); + void updateLight(u8 light_at_pos); + v3s16 getLightPosition(); + void updateNodePos(); + + void step(float dtime, ClientEnvironment *env); + + void processMessage(const std::string &data); + + void initialize(const std::string &data); + + core::aabbox3d* getSelectionBox() + {return &m_selection_box;} + v3f getPosition() + {return pos_translator.vect_show;} + //{return m_position;} + +private: + IntervalLimiter m_attack_interval; + core::aabbox3d m_selection_box; + scene::IMeshSceneNode *m_node; + v3f m_position; + float m_yaw; + SmoothTranslator pos_translator; + float m_damage_visual_timer; + bool m_damage_texture_enabled; +}; + +/* + FireflyCAO +*/ + +class FireflyCAO : public ClientActiveObject +{ +public: + FireflyCAO(); + virtual ~FireflyCAO(); + + u8 getType() const + { + return ACTIVEOBJECT_TYPE_FIREFLY; + } + + static ClientActiveObject* create(); + + void addToScene(scene::ISceneManager *smgr); + void removeFromScene(); + void updateLight(u8 light_at_pos); + v3s16 getLightPosition(); + void updateNodePos(); + + void step(float dtime, ClientEnvironment *env); + + void processMessage(const std::string &data); + + void initialize(const std::string &data); + + core::aabbox3d* getSelectionBox() + {return &m_selection_box;} + v3f getPosition() + {return m_position;} + +private: + core::aabbox3d m_selection_box; + scene::IMeshSceneNode *m_node; + v3f m_position; + float m_yaw; + SmoothTranslator pos_translator; +}; + + +#endif + diff --git a/src/content_craft.cpp b/src/content_craft.cpp new file mode 100644 index 0000000..2ce9bae --- /dev/null +++ b/src/content_craft.cpp @@ -0,0 +1,758 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_craft.h" +#include "inventory.h" +#include "content_mapnode.h" +#include "player.h" +#include "mapnode.h" // For content_t + +/* + items: actually *items[9] + return value: allocates a new item, or returns NULL. +*/ +InventoryItem *craft_get_result(InventoryItem **items) +{ + // Wood + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_TREE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOD, 4); + } + } + + // Stick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + if(checkItemCombination(items, specs)) + { + return new CraftItem("Stick", 4); + } + } + + // Fence + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[5] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[6] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[8] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_FENCE, 2); + } + } + + // Sign + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + //return new MapBlockObjectItem("Sign"); + return new MaterialItem(CONTENT_SIGN_WALL, 1); + } + } + + // Torch + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + specs[3] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_TORCH, 4); + } + } + + // Wooden pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WPick", 0); + } + } + + // Stone pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STPick", 0); + } + } + + // Steel pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[2] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelPick", 0); + } + } + + // Mese pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("MesePick", 0); + } + } + + // Wooden shovel + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WShovel", 0); + } + } + + // Stone shovel + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STShovel", 0); + } + } + + // Steel shovel + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelShovel", 0); + } + } + + // Wooden axe + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WAxe", 0); + } + } + + // Stone axe + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STAxe", 0); + } + } + + // Steel axe + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelAxe", 0); + } + } + + // Wooden sword + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WSword", 0); + } + } + + // Stone sword + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STSword", 0); + } + } + + // Steel sword + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelSword", 0); + } + } + + // Rail + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[2] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[5] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[6] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[8] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_RAIL, 15); + } + } + + // Chest + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[8] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_CHEST, 1); + } + } + + // Furnace + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[8] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_FURNACE, 1); + } + } + + // Steel block + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[2] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[5] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[6] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[8] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_STEEL, 1); + } + } + + // Sandstone + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_SANDSTONE, 1); + } + } + + // Clay + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + specs[4] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + specs[6] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + specs[7] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_CLAY, 1); + } + } + + // Brick + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_CRAFT, "clay_brick"); + specs[4] = ItemSpec(ITEM_CRAFT, "clay_brick"); + specs[6] = ItemSpec(ITEM_CRAFT, "clay_brick"); + specs[7] = ItemSpec(ITEM_CRAFT, "clay_brick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_BRICK, 1); + } + } + + // Paper + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS); + if(checkItemCombination(items, specs)) + { + return new CraftItem("paper", 1); + } + } + + // Book + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "paper"); + specs[4] = ItemSpec(ITEM_CRAFT, "paper"); + specs[7] = ItemSpec(ITEM_CRAFT, "paper"); + if(checkItemCombination(items, specs)) + { + return new CraftItem("book", 1); + } + } + + // Book shelf + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_CRAFT, "book"); + specs[4] = ItemSpec(ITEM_CRAFT, "book"); + specs[5] = ItemSpec(ITEM_CRAFT, "book"); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[8] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_BOOKSHELF, 1); + } + } + + // Ladder + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[2] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[3] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[5] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[6] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[8] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_LADDER, 1); + } + } + + // Iron Apple + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "apple"); + specs[5] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + if(checkItemCombination(items, specs)) + { + return new CraftItem("apple_iron", 1); + } + } + //W + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_LIGHT_GREY, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_LIGHT_GREY); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_DARK_GREY, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_DARK_GREY); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BLACK, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_CRAFT, "apple"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_RED, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_YELLOW, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_RED); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_YELLOW); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_ORANGE, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_MUD); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BROWN, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_LEAVES); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_GREEN, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_JUNGLETREE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_CYAN, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_RED); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_CYAN); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_PURPLE, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_CYAN); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_PURPLE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BLUE, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BLUE, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_RED); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_PINK, 4); + } + } + + return NULL; +} + +void craft_set_creative_inventory(Player *player) +{ + player->resetInventory(); + + // Give some good tools + { + InventoryItem *item = new ToolItem("MesePick", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelPick", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelAxe", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelShovel", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + + /* + Give materials + */ + + // CONTENT_IGNORE-terminated list + content_t material_items[] = { + CONTENT_TORCH, + CONTENT_COBBLE, + CONTENT_MUD, + CONTENT_STONE, + CONTENT_SAND, + CONTENT_SANDSTONE, + CONTENT_CLAY, + CONTENT_BRICK, + CONTENT_TREE, + CONTENT_LEAVES, + CONTENT_CACTUS, + CONTENT_PAPYRUS, + CONTENT_BOOKSHELF, + CONTENT_GLASS, + CONTENT_FENCE, + CONTENT_RAIL, + CONTENT_MESE, + CONTENT_WATERSOURCE, + CONTENT_CLOUD, + CONTENT_CHEST, + CONTENT_FURNACE, + CONTENT_SIGN_WALL, + CONTENT_LAVASOURCE, + CONTENT_IGNORE + }; + + content_t *mip = material_items; + for(u16 i=0; iinventory.addItem("main", item); + + mip++; + } + +#if 0 + assert(USEFUL_CONTENT_COUNT <= PLAYER_INVENTORY_SIZE); + + // add torch first + InventoryItem *item = new MaterialItem(CONTENT_TORCH, 1); + player->inventory.addItem("main", item); + + // Then others + for(u16 i=0; iinventory.addItem("main", item); + } +#endif + + /*// Sign + { + InventoryItem *item = new MapBlockObjectItem("Sign Example text"); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + }*/ +} + +void craft_give_initial_stuff(Player *player) +{ + { + InventoryItem *item = new ToolItem("SteelPick", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_TORCH, 99); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelAxe", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelShovel", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_COBBLE, 99); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + /*{ + InventoryItem *item = new MaterialItem(CONTENT_MESE, 6); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_COALSTONE, 6); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_WOOD, 6); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new CraftItem("Stick", 4); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("WPick", 32000); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("STPick", 32000); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + }*/ + /*// and some signs + for(u16 i=0; i<4; i++) + { + InventoryItem *item = new MapBlockObjectItem("Sign Example text"); + bool r = player->inventory.addItem("main", item); + assert(r == true); + }*/ + /*// Give some other stuff + { + InventoryItem *item = new MaterialItem(CONTENT_TREE, 999); + bool r = player->inventory.addItem("main", item); + assert(r == true); + }*/ +} + diff --git a/src/content_craft.cpp~ b/src/content_craft.cpp~ new file mode 100644 index 0000000..2ce9bae --- /dev/null +++ b/src/content_craft.cpp~ @@ -0,0 +1,758 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_craft.h" +#include "inventory.h" +#include "content_mapnode.h" +#include "player.h" +#include "mapnode.h" // For content_t + +/* + items: actually *items[9] + return value: allocates a new item, or returns NULL. +*/ +InventoryItem *craft_get_result(InventoryItem **items) +{ + // Wood + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_TREE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOD, 4); + } + } + + // Stick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + if(checkItemCombination(items, specs)) + { + return new CraftItem("Stick", 4); + } + } + + // Fence + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[5] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[6] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[8] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_FENCE, 2); + } + } + + // Sign + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + //return new MapBlockObjectItem("Sign"); + return new MaterialItem(CONTENT_SIGN_WALL, 1); + } + } + + // Torch + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + specs[3] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_TORCH, 4); + } + } + + // Wooden pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WPick", 0); + } + } + + // Stone pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STPick", 0); + } + } + + // Steel pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[2] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelPick", 0); + } + } + + // Mese pick + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("MesePick", 0); + } + } + + // Wooden shovel + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WShovel", 0); + } + } + + // Stone shovel + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STShovel", 0); + } + } + + // Steel shovel + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelShovel", 0); + } + } + + // Wooden axe + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WAxe", 0); + } + } + + // Stone axe + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STAxe", 0); + } + } + + // Steel axe + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelAxe", 0); + } + } + + // Wooden sword + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("WSword", 0); + } + } + + // Stone sword + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("STSword", 0); + } + } + + // Steel sword + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new ToolItem("SteelSword", 0); + } + } + + // Rail + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[2] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[5] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[6] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[8] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_RAIL, 15); + } + } + + // Chest + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[8] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_CHEST, 1); + } + } + + // Furnace + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + specs[8] = ItemSpec(ITEM_MATERIAL, CONTENT_COBBLE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_FURNACE, 1); + } + } + + // Steel block + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[2] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[5] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[6] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[8] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_STEEL, 1); + } + } + + // Sandstone + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_SANDSTONE, 1); + } + } + + // Clay + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + specs[4] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + specs[6] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + specs[7] = ItemSpec(ITEM_CRAFT, "lump_of_clay"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_CLAY, 1); + } + } + + // Brick + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_CRAFT, "clay_brick"); + specs[4] = ItemSpec(ITEM_CRAFT, "clay_brick"); + specs[6] = ItemSpec(ITEM_CRAFT, "clay_brick"); + specs[7] = ItemSpec(ITEM_CRAFT, "clay_brick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_BRICK, 1); + } + } + + // Paper + { + ItemSpec specs[9]; + specs[3] = ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS); + specs[4] = ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS); + specs[5] = ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS); + if(checkItemCombination(items, specs)) + { + return new CraftItem("paper", 1); + } + } + + // Book + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "paper"); + specs[4] = ItemSpec(ITEM_CRAFT, "paper"); + specs[7] = ItemSpec(ITEM_CRAFT, "paper"); + if(checkItemCombination(items, specs)) + { + return new CraftItem("book", 1); + } + } + + // Book shelf + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[2] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[3] = ItemSpec(ITEM_CRAFT, "book"); + specs[4] = ItemSpec(ITEM_CRAFT, "book"); + specs[5] = ItemSpec(ITEM_CRAFT, "book"); + specs[6] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[7] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + specs[8] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOD); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_BOOKSHELF, 1); + } + } + + // Ladder + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[2] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[3] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[4] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[5] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[6] = ItemSpec(ITEM_CRAFT, "Stick"); + specs[8] = ItemSpec(ITEM_CRAFT, "Stick"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_LADDER, 1); + } + } + + // Iron Apple + { + ItemSpec specs[9]; + specs[1] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[3] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[4] = ItemSpec(ITEM_CRAFT, "apple"); + specs[5] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + specs[7] = ItemSpec(ITEM_CRAFT, "steel_ingot"); + if(checkItemCombination(items, specs)) + { + return new CraftItem("apple_iron", 1); + } + } + //W + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_LIGHT_GREY, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_LIGHT_GREY); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_DARK_GREY, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_DARK_GREY); + specs[1] = ItemSpec(ITEM_CRAFT, "lump_of_coal"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BLACK, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_CRAFT, "apple"); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_RED, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_SAND); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_YELLOW, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_RED); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_YELLOW); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_ORANGE, 4); + } + } + /// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_MUD); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BROWN, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_LEAVES); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_GREEN, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_JUNGLETREE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_CYAN, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_RED); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_CYAN); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_PURPLE, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_CYAN); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_PURPLE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BLUE, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_MESE); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_BLUE, 4); + } + } + //// + { + ItemSpec specs[9]; + specs[0] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL_RED); + specs[1] = ItemSpec(ITEM_MATERIAL, CONTENT_WOOL); + if(checkItemCombination(items, specs)) + { + return new MaterialItem(CONTENT_WOOL_PINK, 4); + } + } + + return NULL; +} + +void craft_set_creative_inventory(Player *player) +{ + player->resetInventory(); + + // Give some good tools + { + InventoryItem *item = new ToolItem("MesePick", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelPick", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelAxe", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelShovel", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + + /* + Give materials + */ + + // CONTENT_IGNORE-terminated list + content_t material_items[] = { + CONTENT_TORCH, + CONTENT_COBBLE, + CONTENT_MUD, + CONTENT_STONE, + CONTENT_SAND, + CONTENT_SANDSTONE, + CONTENT_CLAY, + CONTENT_BRICK, + CONTENT_TREE, + CONTENT_LEAVES, + CONTENT_CACTUS, + CONTENT_PAPYRUS, + CONTENT_BOOKSHELF, + CONTENT_GLASS, + CONTENT_FENCE, + CONTENT_RAIL, + CONTENT_MESE, + CONTENT_WATERSOURCE, + CONTENT_CLOUD, + CONTENT_CHEST, + CONTENT_FURNACE, + CONTENT_SIGN_WALL, + CONTENT_LAVASOURCE, + CONTENT_IGNORE + }; + + content_t *mip = material_items; + for(u16 i=0; iinventory.addItem("main", item); + + mip++; + } + +#if 0 + assert(USEFUL_CONTENT_COUNT <= PLAYER_INVENTORY_SIZE); + + // add torch first + InventoryItem *item = new MaterialItem(CONTENT_TORCH, 1); + player->inventory.addItem("main", item); + + // Then others + for(u16 i=0; iinventory.addItem("main", item); + } +#endif + + /*// Sign + { + InventoryItem *item = new MapBlockObjectItem("Sign Example text"); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + }*/ +} + +void craft_give_initial_stuff(Player *player) +{ + { + InventoryItem *item = new ToolItem("SteelPick", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_TORCH, 99); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelAxe", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("SteelShovel", 0); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_COBBLE, 99); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + /*{ + InventoryItem *item = new MaterialItem(CONTENT_MESE, 6); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_COALSTONE, 6); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new MaterialItem(CONTENT_WOOD, 6); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new CraftItem("Stick", 4); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("WPick", 32000); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + } + { + InventoryItem *item = new ToolItem("STPick", 32000); + void* r = player->inventory.addItem("main", item); + assert(r == NULL); + }*/ + /*// and some signs + for(u16 i=0; i<4; i++) + { + InventoryItem *item = new MapBlockObjectItem("Sign Example text"); + bool r = player->inventory.addItem("main", item); + assert(r == true); + }*/ + /*// Give some other stuff + { + InventoryItem *item = new MaterialItem(CONTENT_TREE, 999); + bool r = player->inventory.addItem("main", item); + assert(r == true); + }*/ +} + diff --git a/src/content_craft.h b/src/content_craft.h new file mode 100644 index 0000000..7a8b465 --- /dev/null +++ b/src/content_craft.h @@ -0,0 +1,38 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_CRAFT_HEADER +#define CONTENT_CRAFT_HEADER + +class InventoryItem; +class Player; + +/* + items: actually *items[9] + return value: allocates a new item, or returns NULL. +*/ +InventoryItem *craft_get_result(InventoryItem **items); + +void craft_set_creative_inventory(Player *player); + +// Called when give_initial_stuff setting is used +void craft_give_initial_stuff(Player *player); + +#endif + diff --git a/src/content_inventory.cpp b/src/content_inventory.cpp new file mode 100644 index 0000000..59997ee --- /dev/null +++ b/src/content_inventory.cpp @@ -0,0 +1,151 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_inventory.h" +#include "inventory.h" +#include "content_mapnode.h" +//#include "serverobject.h" +#include "content_sao.h" + +bool item_material_is_cookable(content_t content) +{ + if(content == CONTENT_TREE) + return true; + else if(content == CONTENT_COBBLE) + return true; + else if(content == CONTENT_SAND) + return true; + return false; +} + +InventoryItem* item_material_create_cook_result(content_t content) +{ + if(content == CONTENT_TREE) + return new CraftItem("lump_of_coal", 1); + else if(content == CONTENT_COBBLE) + return new MaterialItem(CONTENT_STONE, 1); + else if(content == CONTENT_SAND) + return new MaterialItem(CONTENT_GLASS, 1); + return NULL; +} + +std::string item_craft_get_image_name(const std::string &subname) +{ + if(subname == "Stick") + return "stick.png"; + else if(subname == "paper") + return "paper.png"; + else if(subname == "book") + return "book.png"; + else if(subname == "lump_of_coal") + return "lump_of_coal.png"; + else if(subname == "lump_of_iron") + return "lump_of_iron.png"; + else if(subname == "lump_of_clay") + return "lump_of_clay.png"; + else if(subname == "steel_ingot") + return "steel_ingot.png"; + else if(subname == "clay_brick") + return "clay_brick.png"; + else if(subname == "rat") + return "rat.png"; + else if(subname == "cooked_rat") + return "cooked_rat.png"; + else if(subname == "scorched_stuff") + return "scorched_stuff.png"; + else if(subname == "firefly") + return "firefly.png"; + else if(subname == "apple") + return "apple.png"; + else if(subname == "apple_iron") + return "apple_iron.png"; + else + return "cloud.png"; // just something +} + +ServerActiveObject* item_craft_create_object(const std::string &subname, + ServerEnvironment *env, u16 id, v3f pos) +{ + if(subname == "rat") + { + ServerActiveObject *obj = new RatSAO(env, id, pos); + return obj; + } + else if(subname == "firefly") + { + ServerActiveObject *obj = new FireflySAO(env, id, pos); + return obj; + } + + return NULL; +} + +s16 item_craft_get_drop_count(const std::string &subname) +{ + if(subname == "rat" || subname == "firefly") + return 1; + + return -1; +} + +bool item_craft_is_cookable(const std::string &subname) +{ + if(subname == "lump_of_iron" || subname == "lump_of_clay" || subname == "rat" || subname == "cooked_rat") + return true; + + return false; +} + +InventoryItem* item_craft_create_cook_result(const std::string &subname) +{ + if(subname == "lump_of_iron") + return new CraftItem("steel_ingot", 1); + else if(subname == "lump_of_clay") + return new CraftItem("clay_brick", 1); + else if(subname == "rat") + return new CraftItem("cooked_rat", 1); + else if(subname == "cooked_rat") + return new CraftItem("scorched_stuff", 1); + + return NULL; +} + +bool item_craft_is_eatable(const std::string &subname) +{ + if(subname == "cooked_rat") + return true; + else if(subname == "apple") + return true; + else if(subname == "apple_iron") + return true; + return false; +} + +s16 item_craft_eat_hp_change(const std::string &subname) +{ + if(subname == "cooked_rat") + return 6; // 3 hearts + else if(subname == "apple") + return 4; // 2 hearts + else if(subname == "apple_iron") + return 8; // 4 hearts + return 0; +} + + diff --git a/src/content_inventory.h b/src/content_inventory.h new file mode 100644 index 0000000..91550bb --- /dev/null +++ b/src/content_inventory.h @@ -0,0 +1,44 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_INVENTORY_HEADER +#define CONTENT_INVENTORY_HEADER + +#include "common_irrlicht.h" // For u8, s16 +#include +#include "mapnode.h" // For content_t + +class InventoryItem; +class ServerActiveObject; +class ServerEnvironment; + +bool item_material_is_cookable(content_t content); +InventoryItem* item_material_create_cook_result(content_t content); + +std::string item_craft_get_image_name(const std::string &subname); +ServerActiveObject* item_craft_create_object(const std::string &subname, + ServerEnvironment *env, u16 id, v3f pos); +s16 item_craft_get_drop_count(const std::string &subname); +bool item_craft_is_cookable(const std::string &subname); +InventoryItem* item_craft_create_cook_result(const std::string &subname); +bool item_craft_is_eatable(const std::string &subname); +s16 item_craft_eat_hp_change(const std::string &subname); + +#endif + diff --git a/src/content_mapblock.cpp b/src/content_mapblock.cpp new file mode 100644 index 0000000..1cc37b9 --- /dev/null +++ b/src/content_mapblock.cpp @@ -0,0 +1,1269 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_mapblock.h" +#include "content_mapnode.h" +#include "main.h" // For g_settings and g_texturesource +#include "mineral.h" +#include "mapblock_mesh.h" // For MapBlock_LightColor() + +#ifndef SERVER +// Create a cuboid. +// material - the material to use (for all 6 faces) +// collector - the MeshCollector for the resulting polygons +// pa - texture atlas pointer for the material +// c - vertex colour - used for all +// pos - the position of the centre of the cuboid +// rz,ry,rz - the radius of the cuboid in each dimension +// txc - texture coordinates - this is a list of texture coordinates +// for the opposite corners of each face - therefore, there +// should be (2+2)*6=24 values in the list. Alternatively, pass +// NULL to use the entire texture for each face. The order of +// the faces in the list is top-backi-right-front-left-bottom +// If you specified 0,0,1,1 for each face, that would be the +// same as passing NULL. +void makeCuboid(video::SMaterial &material, MeshCollector *collector, + AtlasPointer* pa, video::SColor &c, + v3f &pos, f32 rx, f32 ry, f32 rz, f32* txc) +{ + f32 tu0=pa->x0(); + f32 tu1=pa->x1(); + f32 tv0=pa->y0(); + f32 tv1=pa->y1(); + f32 txus=tu1-tu0; + f32 txvs=tv1-tv0; + + video::S3DVertex v[4] = + { + video::S3DVertex(0,0,0, 0,0,0, c, tu0, tv1), + video::S3DVertex(0,0,0, 0,0,0, c, tu1, tv1), + video::S3DVertex(0,0,0, 0,0,0, c, tu1, tv0), + video::S3DVertex(0,0,0, 0,0,0, c, tu0, tv0) + }; + + for(int i=0;i<6;i++) + { + switch(i) + { + case 0: // top + v[0].Pos.X=-rx; v[0].Pos.Y= ry; v[0].Pos.Z=-rz; + v[1].Pos.X=-rx; v[1].Pos.Y= ry; v[1].Pos.Z= rz; + v[2].Pos.X= rx; v[2].Pos.Y= ry; v[2].Pos.Z= rz; + v[3].Pos.X= rx; v[3].Pos.Y= ry, v[3].Pos.Z=-rz; + break; + case 1: // back + v[0].Pos.X=-rx; v[0].Pos.Y= ry; v[0].Pos.Z=-rz; + v[1].Pos.X= rx; v[1].Pos.Y= ry; v[1].Pos.Z=-rz; + v[2].Pos.X= rx; v[2].Pos.Y=-ry; v[2].Pos.Z=-rz; + v[3].Pos.X=-rx; v[3].Pos.Y=-ry, v[3].Pos.Z=-rz; + break; + case 2: //right + v[0].Pos.X= rx; v[0].Pos.Y= ry; v[0].Pos.Z=-rz; + v[1].Pos.X= rx; v[1].Pos.Y= ry; v[1].Pos.Z= rz; + v[2].Pos.X= rx; v[2].Pos.Y=-ry; v[2].Pos.Z= rz; + v[3].Pos.X= rx; v[3].Pos.Y=-ry, v[3].Pos.Z=-rz; + break; + case 3: // front + v[0].Pos.X= rx; v[0].Pos.Y= ry; v[0].Pos.Z= rz; + v[1].Pos.X=-rx; v[1].Pos.Y= ry; v[1].Pos.Z= rz; + v[2].Pos.X=-rx; v[2].Pos.Y=-ry; v[2].Pos.Z= rz; + v[3].Pos.X= rx; v[3].Pos.Y=-ry, v[3].Pos.Z= rz; + break; + case 4: // left + v[0].Pos.X=-rx; v[0].Pos.Y= ry; v[0].Pos.Z= rz; + v[1].Pos.X=-rx; v[1].Pos.Y= ry; v[1].Pos.Z=-rz; + v[2].Pos.X=-rx; v[2].Pos.Y=-ry; v[2].Pos.Z=-rz; + v[3].Pos.X=-rx; v[3].Pos.Y=-ry, v[3].Pos.Z= rz; + break; + case 5: // bottom + v[0].Pos.X= rx; v[0].Pos.Y=-ry; v[0].Pos.Z= rz; + v[1].Pos.X=-rx; v[1].Pos.Y=-ry; v[1].Pos.Z= rz; + v[2].Pos.X=-rx; v[2].Pos.Y=-ry; v[2].Pos.Z=-rz; + v[3].Pos.X= rx; v[3].Pos.Y=-ry, v[3].Pos.Z=-rz; + break; + } + + if(txc!=NULL) + { + v[0].TCoords.X=tu0+txus*txc[0]; v[0].TCoords.Y=tv0+txvs*txc[3]; + v[1].TCoords.X=tu0+txus*txc[2]; v[1].TCoords.Y=tv0+txvs*txc[3]; + v[2].TCoords.X=tu0+txus*txc[2]; v[2].TCoords.Y=tv0+txvs*txc[1]; + v[3].TCoords.X=tu0+txus*txc[0]; v[3].TCoords.Y=tv0+txvs*txc[1]; + txc+=4; + } + + for(u16 i=0; i<4; i++) + v[i].Pos += pos; + u16 indices[] = {0,1,2,2,3,0}; + collector->append(material, v, 4, indices, 6); + + } + +} +#endif + +#ifndef SERVER +void mapblock_mesh_generate_special(MeshMakeData *data, + MeshCollector &collector) +{ + // 0ms + //TimeTaker timer("mapblock_mesh_generate_special()"); + + /* + Some settings + */ + bool new_style_water = g_settings.getBool("new_style_water"); + bool new_style_leaves = g_settings.getBool("new_style_leaves"); + //bool smooth_lighting = g_settings.getBool("smooth_lighting"); + bool invisible_stone = g_settings.getBool("invisible_stone"); + + float node_liquid_level = 1.0; + if(new_style_water) + node_liquid_level = 0.85; + + v3s16 blockpos_nodes = data->m_blockpos*MAP_BLOCKSIZE; + + // New-style leaves material + video::SMaterial material_leaves1; + material_leaves1.setFlag(video::EMF_LIGHTING, false); + //material_leaves1.setFlag(video::EMF_BACK_FACE_CULLING, false); + material_leaves1.setFlag(video::EMF_BILINEAR_FILTER, false); + material_leaves1.setFlag(video::EMF_FOG_ENABLE, true); + material_leaves1.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer pa_leaves1 = g_texturesource->getTexture( + g_texturesource->getTextureId("leaves.png")); + material_leaves1.setTexture(0, pa_leaves1.atlas); + + // Glass material + video::SMaterial material_glass; + material_glass.setFlag(video::EMF_LIGHTING, false); + material_glass.setFlag(video::EMF_BILINEAR_FILTER, false); + material_glass.setFlag(video::EMF_FOG_ENABLE, true); + material_glass.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer pa_glass = g_texturesource->getTexture( + g_texturesource->getTextureId("glass.png")); + material_glass.setTexture(0, pa_glass.atlas); + + // Wood material + video::SMaterial material_wood; + material_wood.setFlag(video::EMF_LIGHTING, false); + material_wood.setFlag(video::EMF_BILINEAR_FILTER, false); + material_wood.setFlag(video::EMF_FOG_ENABLE, true); + material_wood.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer pa_wood = g_texturesource->getTexture( + g_texturesource->getTextureId("wood.png")); + material_wood.setTexture(0, pa_wood.atlas); + + // General ground material for special output + // Texture is modified just before usage + video::SMaterial material_general; + material_general.setFlag(video::EMF_LIGHTING, false); + material_general.setFlag(video::EMF_BILINEAR_FILTER, false); + material_general.setFlag(video::EMF_FOG_ENABLE, true); + material_general.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + + + // Papyrus material + video::SMaterial material_papyrus; + material_papyrus.setFlag(video::EMF_LIGHTING, false); + material_papyrus.setFlag(video::EMF_BILINEAR_FILTER, false); + material_papyrus.setFlag(video::EMF_FOG_ENABLE, true); + material_papyrus.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer pa_papyrus = g_texturesource->getTexture( + g_texturesource->getTextureId("papyrus.png")); + material_papyrus.setTexture(0, pa_papyrus.atlas); + + // Apple material + video::SMaterial material_apple; + material_apple.setFlag(video::EMF_LIGHTING, false); + material_apple.setFlag(video::EMF_BILINEAR_FILTER, false); + material_apple.setFlag(video::EMF_FOG_ENABLE, true); + material_apple.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer pa_apple = g_texturesource->getTexture( + g_texturesource->getTextureId("apple.png")); + material_apple.setTexture(0, pa_apple.atlas); + + // junglegrass material + video::SMaterial material_junglegrass; + material_junglegrass.setFlag(video::EMF_LIGHTING, false); + material_junglegrass.setFlag(video::EMF_BILINEAR_FILTER, false); + material_junglegrass.setFlag(video::EMF_FOG_ENABLE, true); + material_junglegrass.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer pa_junglegrass = g_texturesource->getTexture( + g_texturesource->getTextureId("junglegrass.png")); + material_junglegrass.setTexture(0, pa_junglegrass.atlas); + + for(s16 z=0; zm_vmanip.getNodeNoEx(blockpos_nodes+p); + + /* + Add torches to mesh + */ + if(n.getContent() == CONTENT_TORCH) + { + video::SColor c(255,255,255,255); + + // Wall at X+ of node + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, 0,0), + }; + + v3s16 dir = unpackDir(n.param2); + + for(s32 i=0; i<4; i++) + { + if(dir == v3s16(1,0,0)) + vertices[i].Pos.rotateXZBy(0); + if(dir == v3s16(-1,0,0)) + vertices[i].Pos.rotateXZBy(180); + if(dir == v3s16(0,0,1)) + vertices[i].Pos.rotateXZBy(90); + if(dir == v3s16(0,0,-1)) + vertices[i].Pos.rotateXZBy(-90); + if(dir == v3s16(0,-1,0)) + vertices[i].Pos.rotateXZBy(45); + if(dir == v3s16(0,1,0)) + vertices[i].Pos.rotateXZBy(-45); + + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + // Set material + video::SMaterial material; + material.setFlag(video::EMF_LIGHTING, false); + material.setFlag(video::EMF_BACK_FACE_CULLING, false); + material.setFlag(video::EMF_BILINEAR_FILTER, false); + //material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + material.MaterialType + = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + + if(dir == v3s16(0,-1,0)) + material.setTexture(0, + g_texturesource->getTextureRaw("torch_on_floor.png")); + else if(dir == v3s16(0,1,0)) + material.setTexture(0, + g_texturesource->getTextureRaw("torch_on_ceiling.png")); + // For backwards compatibility + else if(dir == v3s16(0,0,0)) + material.setTexture(0, + g_texturesource->getTextureRaw("torch_on_floor.png")); + else + material.setTexture(0, + g_texturesource->getTextureRaw("torch.png")); + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material, vertices, 4, indices, 6); + } + /* + Signs on walls + */ + else if(n.getContent() == CONTENT_SIGN_WALL) + { + u8 l = decode_light(n.getLightBlend(data->m_daynight_ratio)); + video::SColor c = MapBlock_LightColor(255, l); + + float d = (float)BS/16; + // Wall at X+ of node + video::S3DVertex vertices[4] = + { + video::S3DVertex(BS/2-d,-BS/2,-BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2-d,-BS/2,BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2-d,BS/2,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(BS/2-d,BS/2,-BS/2, 0,0,0, c, 0,0), + }; + + v3s16 dir = unpackDir(n.param2); + + for(s32 i=0; i<4; i++) + { + if(dir == v3s16(1,0,0)) + vertices[i].Pos.rotateXZBy(0); + if(dir == v3s16(-1,0,0)) + vertices[i].Pos.rotateXZBy(180); + if(dir == v3s16(0,0,1)) + vertices[i].Pos.rotateXZBy(90); + if(dir == v3s16(0,0,-1)) + vertices[i].Pos.rotateXZBy(-90); + if(dir == v3s16(0,-1,0)) + vertices[i].Pos.rotateXYBy(-90); + if(dir == v3s16(0,1,0)) + vertices[i].Pos.rotateXYBy(90); + + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + // Set material + video::SMaterial material; + material.setFlag(video::EMF_LIGHTING, false); + material.setFlag(video::EMF_BACK_FACE_CULLING, false); + material.setFlag(video::EMF_BILINEAR_FILTER, false); + material.setFlag(video::EMF_FOG_ENABLE, true); + //material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + material.MaterialType + = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + + material.setTexture(0, + g_texturesource->getTextureRaw("sign_wall.png")); + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material, vertices, 4, indices, 6); + } + /* + Add flowing liquid to mesh + */ + else if(content_features(n).liquid_type == LIQUID_FLOWING) + { + assert(content_features(n).special_material); + video::SMaterial &liquid_material = + *content_features(n).special_material; + assert(content_features(n).special_atlas); + AtlasPointer &pa_liquid1 = + *content_features(n).special_atlas; + + bool top_is_same_liquid = false; + MapNode ntop = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y+1,z)); + content_t c_flowing = content_features(n).liquid_alternative_flowing; + content_t c_source = content_features(n).liquid_alternative_source; + if(ntop.getContent() == c_flowing || ntop.getContent() == c_source) + top_is_same_liquid = true; + + u8 l = 0; + // Use the light of the node on top if possible + if(content_features(ntop).param_type == CPT_LIGHT) + l = decode_light(ntop.getLightBlend(data->m_daynight_ratio)); + // Otherwise use the light of this node (the liquid) + else + l = decode_light(n.getLightBlend(data->m_daynight_ratio)); + video::SColor c = MapBlock_LightColor( + content_features(n).vertex_alpha, l); + + // Neighbor liquid levels (key = relative position) + // Includes current node + core::map neighbor_levels; + core::map neighbor_contents; + core::map neighbor_flags; + const u8 neighborflag_top_is_same_liquid = 0x01; + v3s16 neighbor_dirs[9] = { + v3s16(0,0,0), + v3s16(0,0,1), + v3s16(0,0,-1), + v3s16(1,0,0), + v3s16(-1,0,0), + v3s16(1,0,1), + v3s16(-1,0,-1), + v3s16(1,0,-1), + v3s16(-1,0,1), + }; + for(u32 i=0; i<9; i++) + { + content_t content = CONTENT_AIR; + float level = -0.5 * BS; + u8 flags = 0; + // Check neighbor + v3s16 p2 = p + neighbor_dirs[i]; + MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + if(n2.getContent() != CONTENT_IGNORE) + { + content = n2.getContent(); + + if(n2.getContent() == c_source) + level = (-0.5+node_liquid_level) * BS; + else if(n2.getContent() == c_flowing) + level = (-0.5 + ((float)(n2.param2&LIQUID_LEVEL_MASK) + + 0.5) / 8.0 * node_liquid_level) * BS; + + // Check node above neighbor. + // NOTE: This doesn't get executed if neighbor + // doesn't exist + p2.Y += 1; + n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + if(n2.getContent() == c_source || + n2.getContent() == c_flowing) + flags |= neighborflag_top_is_same_liquid; + } + + neighbor_levels.insert(neighbor_dirs[i], level); + neighbor_contents.insert(neighbor_dirs[i], content); + neighbor_flags.insert(neighbor_dirs[i], flags); + } + + // Corner heights (average between four liquids) + f32 corner_levels[4]; + + v3s16 halfdirs[4] = { + v3s16(0,0,0), + v3s16(1,0,0), + v3s16(1,0,1), + v3s16(0,0,1), + }; + for(u32 i=0; i<4; i++) + { + v3s16 cornerdir = halfdirs[i]; + float cornerlevel = 0; + u32 valid_count = 0; + u32 air_count = 0; + for(u32 j=0; j<4; j++) + { + v3s16 neighbordir = cornerdir - halfdirs[j]; + content_t content = neighbor_contents[neighbordir]; + // If top is liquid, draw starting from top of node + if(neighbor_flags[neighbordir] & + neighborflag_top_is_same_liquid) + { + cornerlevel = 0.5*BS; + valid_count = 1; + break; + } + // Source is always the same height + else if(content == c_source) + { + cornerlevel = (-0.5+node_liquid_level)*BS; + valid_count = 1; + break; + } + // Flowing liquid has level information + else if(content == c_flowing) + { + cornerlevel += neighbor_levels[neighbordir]; + valid_count++; + } + else if(content == CONTENT_AIR) + { + air_count++; + } + } + if(air_count >= 2) + cornerlevel = -0.5*BS; + else if(valid_count > 0) + cornerlevel /= valid_count; + corner_levels[i] = cornerlevel; + } + + /* + Generate sides + */ + + v3s16 side_dirs[4] = { + v3s16(1,0,0), + v3s16(-1,0,0), + v3s16(0,0,1), + v3s16(0,0,-1), + }; + s16 side_corners[4][2] = { + {1, 2}, + {3, 0}, + {2, 3}, + {0, 1}, + }; + for(u32 i=0; i<4; i++) + { + v3s16 dir = side_dirs[i]; + + /* + If our topside is liquid and neighbor's topside + is liquid, don't draw side face + */ + if(top_is_same_liquid && + neighbor_flags[dir] & neighborflag_top_is_same_liquid) + continue; + + content_t neighbor_content = neighbor_contents[dir]; + + // Don't draw face if neighbor is not air or liquid + if(neighbor_content != CONTENT_AIR + && content_liquid(neighbor_content) == false) + continue; + + bool neighbor_is_same_liquid = (neighbor_content == c_source + || neighbor_content == c_flowing); + + // Don't draw any faces if neighbor same is liquid and top is + // same liquid + if(neighbor_is_same_liquid == true + && top_is_same_liquid == false) + continue; + + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,0),*/ + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x0(), pa_liquid1.y1()), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x1(), pa_liquid1.y1()), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x1(), pa_liquid1.y0()), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x0(), pa_liquid1.y0()), + }; + + /* + If our topside is liquid, set upper border of face + at upper border of node + */ + if(top_is_same_liquid) + { + vertices[2].Pos.Y = 0.5*BS; + vertices[3].Pos.Y = 0.5*BS; + } + /* + Otherwise upper position of face is corner levels + */ + else + { + vertices[2].Pos.Y = corner_levels[side_corners[i][0]]; + vertices[3].Pos.Y = corner_levels[side_corners[i][1]]; + } + + /* + If neighbor is liquid, lower border of face is corner + liquid levels + */ + if(neighbor_is_same_liquid) + { + vertices[0].Pos.Y = corner_levels[side_corners[i][1]]; + vertices[1].Pos.Y = corner_levels[side_corners[i][0]]; + } + /* + If neighbor is not liquid, lower border of face is + lower border of node + */ + else + { + vertices[0].Pos.Y = -0.5*BS; + vertices[1].Pos.Y = -0.5*BS; + } + + for(s32 j=0; j<4; j++) + { + if(dir == v3s16(0,0,1)) + vertices[j].Pos.rotateXZBy(0); + if(dir == v3s16(0,0,-1)) + vertices[j].Pos.rotateXZBy(180); + if(dir == v3s16(-1,0,0)) + vertices[j].Pos.rotateXZBy(90); + if(dir == v3s16(1,0,-0)) + vertices[j].Pos.rotateXZBy(-90); + + // Do this to not cause glitches when two liquids are + // side-by-side + if(neighbor_is_same_liquid == false){ + vertices[j].Pos.X *= 0.98; + vertices[j].Pos.Z *= 0.98; + } + + vertices[j].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(liquid_material, vertices, 4, indices, 6); + } + + /* + Generate top side, if appropriate + */ + + if(top_is_same_liquid == false) + { + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,0),*/ + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x0(), pa_liquid1.y1()), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x1(), pa_liquid1.y1()), + video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c, + pa_liquid1.x1(), pa_liquid1.y0()), + video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c, + pa_liquid1.x0(), pa_liquid1.y0()), + }; + + // This fixes a strange bug + s32 corner_resolve[4] = {3,2,1,0}; + + for(s32 i=0; i<4; i++) + { + //vertices[i].Pos.Y += liquid_level; + //vertices[i].Pos.Y += neighbor_levels[v3s16(0,0,0)]; + s32 j = corner_resolve[i]; + vertices[i].Pos.Y += corner_levels[j]; + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(liquid_material, vertices, 4, indices, 6); + } + } + /* + Add water sources to mesh if using new style + */ + else if(content_features(n).liquid_type == LIQUID_SOURCE + && new_style_water) + { + assert(content_features(n).special_material); + video::SMaterial &liquid_material = + *content_features(n).special_material; + assert(content_features(n).special_atlas); + AtlasPointer &pa_liquid1 = + *content_features(n).special_atlas; + + bool top_is_air = false; + MapNode n = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y+1,z)); + if(n.getContent() == CONTENT_AIR) + top_is_air = true; + + if(top_is_air == false) + continue; + + u8 l = decode_light(n.getLightBlend(data->m_daynight_ratio)); + video::SColor c = MapBlock_LightColor( + content_features(n).vertex_alpha, l); + + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, 0,0),*/ + video::S3DVertex(-BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x0(), pa_liquid1.y1()), + video::S3DVertex(BS/2,0,BS/2, 0,0,0, c, + pa_liquid1.x1(), pa_liquid1.y1()), + video::S3DVertex(BS/2,0,-BS/2, 0,0,0, c, + pa_liquid1.x1(), pa_liquid1.y0()), + video::S3DVertex(-BS/2,0,-BS/2, 0,0,0, c, + pa_liquid1.x0(), pa_liquid1.y0()), + }; + + for(s32 i=0; i<4; i++) + { + vertices[i].Pos.Y += (-0.5+node_liquid_level)*BS; + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(liquid_material, vertices, 4, indices, 6); + } + /* + Add leaves if using new style + */ + else if(n.getContent() == CONTENT_LEAVES && new_style_leaves) + { + /*u8 l = decode_light(n.getLightBlend(data->m_daynight_ratio));*/ + u8 l = decode_light(undiminish_light(n.getLightBlend(data->m_daynight_ratio))); + video::SColor c = MapBlock_LightColor(255, l); + + for(u32 j=0; j<6; j++) + { + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(-BS/2,-BS/2,BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/2,BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/2,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/2,BS/2, 0,0,0, c, 0,0),*/ + video::S3DVertex(-BS/2,-BS/2,BS/2, 0,0,0, c, + pa_leaves1.x0(), pa_leaves1.y1()), + video::S3DVertex(BS/2,-BS/2,BS/2, 0,0,0, c, + pa_leaves1.x1(), pa_leaves1.y1()), + video::S3DVertex(BS/2,BS/2,BS/2, 0,0,0, c, + pa_leaves1.x1(), pa_leaves1.y0()), + video::S3DVertex(-BS/2,BS/2,BS/2, 0,0,0, c, + pa_leaves1.x0(), pa_leaves1.y0()), + }; + + if(j == 0) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(0); + } + else if(j == 1) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(180); + } + else if(j == 2) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-90); + } + else if(j == 3) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(90); + } + else if(j == 4) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateYZBy(-90); + } + else if(j == 5) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateYZBy(90); + } + + for(u16 i=0; i<4; i++) + { + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_leaves1, vertices, 4, indices, 6); + } + } + /* + Add glass + */ + else if(n.getContent() == CONTENT_GLASS) + { + u8 l = decode_light(undiminish_light(n.getLightBlend(data->m_daynight_ratio))); + video::SColor c = MapBlock_LightColor(255, l); + + for(u32 j=0; j<6; j++) + { + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2,BS/2, 0,0,0, c, + pa_glass.x0(), pa_glass.y1()), + video::S3DVertex(BS/2,-BS/2,BS/2, 0,0,0, c, + pa_glass.x1(), pa_glass.y1()), + video::S3DVertex(BS/2,BS/2,BS/2, 0,0,0, c, + pa_glass.x1(), pa_glass.y0()), + video::S3DVertex(-BS/2,BS/2,BS/2, 0,0,0, c, + pa_glass.x0(), pa_glass.y0()), + }; + + if(j == 0) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(0); + } + else if(j == 1) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(180); + } + else if(j == 2) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-90); + } + else if(j == 3) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(90); + } + else if(j == 4) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateYZBy(-90); + } + else if(j == 5) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateYZBy(90); + } + + for(u16 i=0; i<4; i++) + { + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_glass, vertices, 4, indices, 6); + } + } + /* + Add fence + */ + else if(n.getContent() == CONTENT_FENCE) + { + u8 l = decode_light(undiminish_light(n.getLightBlend(data->m_daynight_ratio))); + video::SColor c = MapBlock_LightColor(255, l); + + const f32 post_rad=(f32)BS/10; + const f32 bar_rad=(f32)BS/20; + const f32 bar_len=(f32)(BS/2)-post_rad; + + // The post - always present + v3f pos = intToFloat(p+blockpos_nodes, BS); + f32 postuv[24]={ + 0.4,0.4,0.6,0.6, + 0.35,0,0.65,1, + 0.35,0,0.65,1, + 0.35,0,0.65,1, + 0.35,0,0.65,1, + 0.4,0.4,0.6,0.6}; + makeCuboid(material_wood, &collector, + &pa_wood, c, pos, + post_rad,BS/2,post_rad, postuv); + + // Now a section of fence, +X, if there's a post there + v3s16 p2 = p; + p2.X++; + MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + if(n2.getContent() == CONTENT_FENCE) + { + pos = intToFloat(p+blockpos_nodes, BS); + pos.X += BS/2; + pos.Y += BS/4; + f32 xrailuv[24]={ + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6}; + makeCuboid(material_wood, &collector, + &pa_wood, c, pos, + bar_len,bar_rad,bar_rad, xrailuv); + + pos.Y -= BS/2; + makeCuboid(material_wood, &collector, + &pa_wood, c, pos, + bar_len,bar_rad,bar_rad, xrailuv); + } + + // Now a section of fence, +Z, if there's a post there + p2 = p; + p2.Z++; + n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + p2); + if(n2.getContent() == CONTENT_FENCE) + { + pos = intToFloat(p+blockpos_nodes, BS); + pos.Z += BS/2; + pos.Y += BS/4; + f32 zrailuv[24]={ + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6, + 0,0.4,1,0.6}; + makeCuboid(material_wood, &collector, + &pa_wood, c, pos, + bar_rad,bar_rad,bar_len, zrailuv); + pos.Y -= BS/2; + makeCuboid(material_wood, &collector, + &pa_wood, c, pos, + bar_rad,bar_rad,bar_len, zrailuv); + + } + + } +#if 1 + /* + Add stones with minerals if stone is invisible + */ + else if(n.getContent() == CONTENT_STONE && invisible_stone && n.getMineral() != MINERAL_NONE) + { + for(u32 j=0; j<6; j++) + { + // NOTE: Hopefully g_6dirs[j] is the right direction... + v3s16 dir = g_6dirs[j]; + /*u8 l = 0; + MapNode n2 = data->m_vmanip.getNodeNoEx(blockpos_nodes + dir); + if(content_features(n2).param_type == CPT_LIGHT) + l = decode_light(n2.getLightBlend(data->m_daynight_ratio)); + else + l = 255;*/ + u8 l = 255; + video::SColor c = MapBlock_LightColor(255, l); + + // Get the right texture + TileSpec ts = n.getTile(dir); + AtlasPointer ap = ts.texture; + material_general.setTexture(0, ap.atlas); + + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(-BS/2,-BS/2,BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/2,BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/2,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/2,BS/2, 0,0,0, c, 0,0),*/ + video::S3DVertex(-BS/2,-BS/2,BS/2, 0,0,0, c, + ap.x0(), ap.y1()), + video::S3DVertex(BS/2,-BS/2,BS/2, 0,0,0, c, + ap.x1(), ap.y1()), + video::S3DVertex(BS/2,BS/2,BS/2, 0,0,0, c, + ap.x1(), ap.y0()), + video::S3DVertex(-BS/2,BS/2,BS/2, 0,0,0, c, + ap.x0(), ap.y0()), + }; + + if(j == 0) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(0); + } + else if(j == 1) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(180); + } + else if(j == 2) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-90); + } + else if(j == 3) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(90); + } + else if(j == 4) + + for(u16 i=0; i<4; i++) + { + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_general, vertices, 4, indices, 6); + } + } +#endif + else if(n.getContent() == CONTENT_PAPYRUS) + { + u8 l = decode_light(undiminish_light(n.getLightBlend(data->m_daynight_ratio))); + video::SColor c = MapBlock_LightColor(255, l); + + for(u32 j=0; j<4; j++) + { + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, + pa_papyrus.x0(), pa_papyrus.y1()), + video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, + pa_papyrus.x1(), pa_papyrus.y1()), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, + pa_papyrus.x1(), pa_papyrus.y0()), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, + pa_papyrus.x0(), pa_papyrus.y0()), + }; + + if(j == 0) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(45); + } + else if(j == 1) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-45); + } + else if(j == 2) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(135); + } + else if(j == 3) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-135); + } + + for(u16 i=0; i<4; i++) + { + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_papyrus, vertices, 4, indices, 6); + } + } + else if(n.getContent() == CONTENT_JUNGLEGRASS) + { + u8 l = decode_light(undiminish_light(n.getLightBlend(data->m_daynight_ratio))); + video::SColor c = MapBlock_LightColor(255, l); + + for(u32 j=0; j<4; j++) + { + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, + pa_papyrus.x0(), pa_papyrus.y1()), + video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, + pa_papyrus.x1(), pa_papyrus.y1()), + video::S3DVertex(BS/2,BS/1,0, 0,0,0, c, + pa_papyrus.x1(), pa_papyrus.y0()), + video::S3DVertex(-BS/2,BS/1,0, 0,0,0, c, + pa_papyrus.x0(), pa_papyrus.y0()), + }; + + if(j == 0) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(45); + } + else if(j == 1) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-45); + } + else if(j == 2) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(135); + } + else if(j == 3) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-135); + } + + for(u16 i=0; i<4; i++) + { + vertices[i].Pos *= 1.3; + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_junglegrass, vertices, 4, indices, 6); + } + } + else if(n.getContent() == CONTENT_RAIL) + { + u8 l = decode_light(n.getLightBlend(data->m_daynight_ratio)); + video::SColor c = MapBlock_LightColor(255, l); + + bool is_rail_x [] = { false, false }; /* x-1, x+1 */ + bool is_rail_z [] = { false, false }; /* z-1, z+1 */ + + MapNode n_minus_x = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x-1,y,z)); + MapNode n_plus_x = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x+1,y,z)); + MapNode n_minus_z = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y,z-1)); + MapNode n_plus_z = data->m_vmanip.getNodeNoEx(blockpos_nodes + v3s16(x,y,z+1)); + + if(n_minus_x.getContent() == CONTENT_RAIL) + is_rail_x[0] = true; + if(n_plus_x.getContent() == CONTENT_RAIL) + is_rail_x[1] = true; + if(n_minus_z.getContent() == CONTENT_RAIL) + is_rail_z[0] = true; + if(n_plus_z.getContent() == CONTENT_RAIL) + is_rail_z[1] = true; + + float d = (float)BS/16; + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2+d,-BS/2, 0,0,0, c, + 0, 1), + video::S3DVertex(BS/2,-BS/2+d,-BS/2, 0,0,0, c, + 1, 1), + video::S3DVertex(BS/2,-BS/2+d,BS/2, 0,0,0, c, + 1, 0), + video::S3DVertex(-BS/2,-BS/2+d,BS/2, 0,0,0, c, + 0, 0), + }; + + video::SMaterial material_rail; + material_rail.setFlag(video::EMF_LIGHTING, false); + material_rail.setFlag(video::EMF_BACK_FACE_CULLING, false); + material_rail.setFlag(video::EMF_BILINEAR_FILTER, false); + material_rail.setFlag(video::EMF_FOG_ENABLE, true); + material_rail.MaterialType + = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + + int adjacencies = is_rail_x[0] + is_rail_x[1] + is_rail_z[0] + is_rail_z[1]; + + // Assign textures + if(adjacencies < 2) + material_rail.setTexture(0, g_texturesource->getTextureRaw("rail.png")); + else if(adjacencies == 2) + { + if((is_rail_x[0] && is_rail_x[1]) || (is_rail_z[0] && is_rail_z[1])) + material_rail.setTexture(0, g_texturesource->getTextureRaw("rail.png")); + else + material_rail.setTexture(0, g_texturesource->getTextureRaw("rail_curved.png")); + } + else if(adjacencies == 3) + material_rail.setTexture(0, g_texturesource->getTextureRaw("rail_t_junction.png")); + else if(adjacencies == 4) + material_rail.setTexture(0, g_texturesource->getTextureRaw("rail_crossing.png")); + + // Rotate textures + int angle = 0; + + if(adjacencies == 1) + { + if(is_rail_x[0] || is_rail_x[1]) + angle = 90; + } + else if(adjacencies == 2) + { + if(is_rail_x[0] && is_rail_x[1]) + angle = 90; + else if(is_rail_x[0] && is_rail_z[0]) + angle = 270; + else if(is_rail_x[0] && is_rail_z[1]) + angle = 180; + else if(is_rail_x[1] && is_rail_z[1]) + angle = 90; + } + else if(adjacencies == 3) + { + if(!is_rail_x[0]) + angle=0; + if(!is_rail_x[1]) + angle=180; + if(!is_rail_z[0]) + angle=90; + if(!is_rail_z[1]) + angle=270; + } + + if(angle != 0) { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(angle); + } + + for(s32 i=0; i<4; i++) + { + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + collector.append(material_rail, vertices, 4, indices, 6); + } + else if (n.getContent() == CONTENT_LADDER) { + u8 l = decode_light(n.getLightBlend(data->m_daynight_ratio)); + video::SColor c(255,l,l,l); + + float d = (float)BS/16; + + // Assume wall is at X+ + video::S3DVertex vertices[4] = + { + video::S3DVertex(BS/2-d,-BS/2,-BS/2, 0,0,0, c, 0,1), + video::S3DVertex(BS/2-d,-BS/2,BS/2, 0,0,0, c, 1,1), + video::S3DVertex(BS/2-d,BS/2,BS/2, 0,0,0, c, 1,0), + video::S3DVertex(BS/2-d,BS/2,-BS/2, 0,0,0, c, 0,0), + }; + + v3s16 dir = unpackDir(n.param2); + + for(s32 i=0; i<4; i++) + { + if(dir == v3s16(1,0,0)) + vertices[i].Pos.rotateXZBy(0); + if(dir == v3s16(-1,0,0)) + vertices[i].Pos.rotateXZBy(180); + if(dir == v3s16(0,0,1)) + vertices[i].Pos.rotateXZBy(90); + if(dir == v3s16(0,0,-1)) + vertices[i].Pos.rotateXZBy(-90); + if(dir == v3s16(0,-1,0)) + vertices[i].Pos.rotateXYBy(-90); + if(dir == v3s16(0,1,0)) + vertices[i].Pos.rotateXYBy(90); + + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + video::SMaterial material_ladder; + material_ladder.setFlag(video::EMF_LIGHTING, false); + material_ladder.setFlag(video::EMF_BACK_FACE_CULLING, false); + material_ladder.setFlag(video::EMF_BILINEAR_FILTER, false); + material_ladder.setFlag(video::EMF_FOG_ENABLE, true); + material_ladder.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + material_ladder.setTexture(0, g_texturesource->getTextureRaw("ladder.png")); + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_ladder, vertices, 4, indices, 6); + } + else if(n.getContent() == CONTENT_APPLE) + { + u8 l = decode_light(undiminish_light(n.getLightBlend(data->m_daynight_ratio))); + video::SColor c = MapBlock_LightColor(255, l); + + for(u32 j=0; j<4; j++) + { + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, + pa_apple.x0(), pa_apple.y1()), + video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, + pa_apple.x1(), pa_apple.y1()), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, + pa_apple.x1(), pa_apple.y0()), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, + pa_apple.x0(), pa_apple.y0()), + }; + + if(j == 0) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(45); + } + else if(j == 1) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-45); + } + else if(j == 2) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(135); + } + else if(j == 3) + { + for(u16 i=0; i<4; i++) + vertices[i].Pos.rotateXZBy(-135); + } + + for(u16 i=0; i<4; i++) + { + vertices[i].Pos += intToFloat(p + blockpos_nodes, BS); + } + + u16 indices[] = {0,1,2,2,3,0}; + // Add to mesh collector + collector.append(material_apple, vertices, 4, indices, 6); + } + } + } +} +#endif + diff --git a/src/content_mapblock.h b/src/content_mapblock.h new file mode 100644 index 0000000..4384220 --- /dev/null +++ b/src/content_mapblock.h @@ -0,0 +1,31 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_MAPBLOCK_HEADER +#define CONTENT_MAPBLOCK_HEADER + +#ifndef SERVER + #include "mapblock_mesh.h" + #include "utility.h" +void mapblock_mesh_generate_special(MeshMakeData *data, + MeshCollector &collector); +#endif + +#endif + diff --git a/src/content_mapnode.cpp b/src/content_mapnode.cpp new file mode 100644 index 0000000..a50a372 --- /dev/null +++ b/src/content_mapnode.cpp @@ -0,0 +1,806 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// For g_settings +#include "main.h" + +#include "content_mapnode.h" +#include "mapnode.h" +#include "content_nodemeta.h" + +#define WATER_ALPHA 160 + +#define WATER_VISC 1 +#define LAVA_VISC 7 + +// TODO: Get rid of these and set up some attributes like toughness, +// fluffyness, and a funciton to calculate time and durability loss +// (and sound? and whatever else) from them +void setStoneLikeDiggingProperties(DiggingPropertiesList &list, float toughness); +void setDirtLikeDiggingProperties(DiggingPropertiesList &list, float toughness); +void setWoodLikeDiggingProperties(DiggingPropertiesList &list, float toughness); + +/* + A conversion table for backwards compatibility. + Maps <=v19 content types to current ones. + Should never be touched. +*/ +content_t trans_table_19[21][2] = { + {CONTENT_GRASS, 1}, + {CONTENT_TREE, 4}, + {CONTENT_LEAVES, 5}, + {CONTENT_GRASS_FOOTSTEPS, 6}, + {CONTENT_MESE, 7}, + {CONTENT_MUD, 8}, + {CONTENT_CLOUD, 10}, + {CONTENT_COALSTONE, 11}, + {CONTENT_WOOD, 12}, + {CONTENT_SAND, 13}, + {CONTENT_COBBLE, 18}, + {CONTENT_STEEL, 19}, + {CONTENT_GLASS, 20}, + {CONTENT_MOSSYCOBBLE, 22}, + {CONTENT_GRAVEL, 23}, + {CONTENT_SANDSTONE, 24}, + {CONTENT_CACTUS, 25}, + {CONTENT_BRICK, 26}, + {CONTENT_CLAY, 27}, + {CONTENT_PAPYRUS, 28}, + {CONTENT_BOOKSHELF, 29}, +}; + +MapNode mapnode_translate_from_internal(MapNode n_from, u8 version) +{ + MapNode result = n_from; + if(version <= 19) + { + content_t c_from = n_from.getContent(); + for(u32 i=0; isetAllTextures("stone.png"); + f->setInventoryTextureCube("stone.png", "stone.png", "stone.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_COBBLE)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 1.0); + if(invisible_stone) + f->solidness = 0; // For debugging, hides regular stone + + i = CONTENT_GRASS; + f = &content_features(i); + f->setAllTextures("mud.png^grass_side.png"); + f->setTexture(0, "grass.png"); + f->setTexture(1, "mud.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_MUD)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_GRASS_FOOTSTEPS; + f = &content_features(i); + f->setAllTextures("mud.png^grass_side.png"); + f->setTexture(0, "grass_footsteps.png"); + f->setTexture(1, "mud.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_MUD)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_MUD; + f = &content_features(i); + f->setAllTextures("mud.png"); + f->setInventoryTextureCube("mud.png", "mud.png", "mud.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_SAND; + f = &content_features(i); + f->setAllTextures("sand.png"); + f->setInventoryTextureCube("sand.png", "sand.png", "sand.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_GRAVEL; + f = &content_features(i); + f->setAllTextures("gravel.png"); + f->setInventoryTextureCube("gravel.png", "gravel.png", "gravel.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.75); + + i = CONTENT_SANDSTONE; + f = &content_features(i); + f->setAllTextures("sandstone.png"); + f->setInventoryTextureCube("sandstone.png", "sandstone.png", "sandstone.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_SAND)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_CLAY; + f = &content_features(i); + f->setAllTextures("clay.png"); + f->setInventoryTextureCube("clay.png", "clay.png", "clay.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("CraftItem lump_of_clay 4"); + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_BRICK; + f = &content_features(i); + f->setAllTextures("brick.png"); + f->setInventoryTextureCube("brick.png", "brick.png", "brick.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("CraftItem clay_brick 4"); + setStoneLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_TREE; + f = &content_features(i); + f->setAllTextures("tree.png"); + f->setTexture(0, "tree_top.png"); + f->setTexture(1, "tree_top.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_JUNGLETREE; + f = &content_features(i); + f->setAllTextures("jungletree.png"); + f->setTexture(0, "jungletree_top.png"); + f->setTexture(1, "jungletree_top.png"); + f->param_type = CPT_MINERAL; + //f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_JUNGLEGRASS; + f = &content_features(i); + f->setInventoryTexture("junglegrass.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + //f->is_ground_content = true; + f->air_equivalent = false; // grass grows underneath + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + setWoodLikeDiggingProperties(f->digging_properties, 0.10); + + i = CONTENT_LEAVES; + f = &content_features(i); + f->light_propagates = true; + //f->param_type = CPT_MINERAL; + f->param_type = CPT_LIGHT; + //f->is_ground_content = true; + if(new_style_leaves) + { + f->solidness = 0; // drawn separately, makes no faces + f->setInventoryTextureCube("leaves.png", "leaves.png", "leaves.png"); + } + else + { + f->setAllTextures("[noalpha:leaves.png"); + } + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.15); + + i = CONTENT_CACTUS; + f = &content_features(i); + f->setAllTextures("cactus_side.png"); + f->setTexture(0, "cactus_top.png"); + f->setTexture(1, "cactus_top.png"); + f->setInventoryTextureCube("cactus_top.png", "cactus_side.png", "cactus_side.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_PAPYRUS; + f = &content_features(i); + f->setInventoryTexture("papyrus.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + setWoodLikeDiggingProperties(f->digging_properties, 0.25); + + i = CONTENT_BOOKSHELF; + f = &content_features(i); + f->setAllTextures("bookshelf.png"); + f->setTexture(0, "wood.png"); + f->setTexture(1, "wood.png"); + // FIXME: setInventoryTextureCube() only cares for the first texture + f->setInventoryTextureCube("bookshelf.png", "bookshelf.png", "bookshelf.png"); + //f->setInventoryTextureCube("wood.png", "bookshelf.png", "bookshelf.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_GLASS; + f = &content_features(i); + f->light_propagates = true; + f->sunlight_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->setInventoryTextureCube("glass.png", "glass.png", "glass.png"); + setWoodLikeDiggingProperties(f->digging_properties, 0.15); + + i = CONTENT_FENCE; + f = &content_features(i); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->air_equivalent = true; // grass grows underneath + f->setInventoryTexture("fence.png"); + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_RAIL; + f = &content_features(i); + f->setInventoryTexture("rail.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->air_equivalent = true; // grass grows underneath + f->walkable = false; + setDirtLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_LADDER; + f = &content_features(i); + f->setInventoryTexture("ladder.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem ")+itos(i)+" 1"; + f->wall_mounted = true; + f->solidness = 0; + f->air_equivalent = true; + f->walkable = false; + f->climbable = true; + setWoodLikeDiggingProperties(f->digging_properties, 0.5); + + // Deprecated + i = CONTENT_COALSTONE; + f = &content_features(i); + f->setAllTextures("stone.png^mineral_coal.png"); + f->is_ground_content = true; + setStoneLikeDiggingProperties(f->digging_properties, 1.5); + + i = CONTENT_WOOD; + f = &content_features(i); + f->setAllTextures("wood.png"); + f->setInventoryTextureCube("wood.png", "wood.png", "wood.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_MESE; + f = &content_features(i); + f->setAllTextures("mese.png"); + f->setInventoryTextureCube("mese.png", "mese.png", "mese.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 0.5); + + i = CONTENT_CLOUD; + f = &content_features(i); + f->setAllTextures("cloud.png"); + f->setInventoryTextureCube("cloud.png", "cloud.png", "cloud.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + + i = CONTENT_AIR; + f = &content_features(i); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->air_equivalent = true; + + i = CONTENT_WATER; + f = &content_features(i); + f->setInventoryTextureCube("water.png", "water.png", "water.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->solidness = 0; // Drawn separately, makes no faces + f->visual_solidness = 1; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_FLOWING; + f->liquid_alternative_flowing = CONTENT_WATER; + f->liquid_alternative_source = CONTENT_WATERSOURCE; + f->liquid_viscosity = WATER_VISC; + f->vertex_alpha = WATER_ALPHA; + if(f->special_material == NULL && g_texturesource) + { + // Flowing water material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + AtlasPointer *pa_water1 = new AtlasPointer(g_texturesource->getTexture( + g_texturesource->getTextureId("water.png"))); + f->special_material->setTexture(0, pa_water1->atlas); + f->special_atlas = pa_water1; + } + + i = CONTENT_WATERSOURCE; + f = &content_features(i); + //f->setInventoryTexture("water.png"); + f->setInventoryTextureCube("water.png", "water.png", "water.png"); + if(new_style_water) + { + f->solidness = 0; // drawn separately, makes no faces + } + else // old style + { + f->solidness = 1; + + TileSpec t; + if(g_texturesource) + t.texture = g_texturesource->getTexture("water.png"); + + t.alpha = WATER_ALPHA; + t.material_type = MATERIAL_ALPHA_VERTEX; + t.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; + f->setAllTiles(t); + } + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_SOURCE; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->liquid_alternative_flowing = CONTENT_WATER; + f->liquid_alternative_source = CONTENT_WATERSOURCE; + f->liquid_viscosity = WATER_VISC; + f->vertex_alpha = WATER_ALPHA; + if(f->special_material == NULL && g_texturesource) + { + // Flowing water material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + AtlasPointer *pa_water1 = new AtlasPointer(g_texturesource->getTexture( + g_texturesource->getTextureId("water.png"))); + f->special_material->setTexture(0, pa_water1->atlas); + f->special_atlas = pa_water1; + } + + i = CONTENT_LAVA; + f = &content_features(i); + f->setInventoryTextureCube("lava.png", "lava.png", "lava.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = false; + f->light_source = LIGHT_MAX-1; + f->solidness = 0; // Drawn separately, makes no faces + f->visual_solidness = 2; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_FLOWING; + f->liquid_alternative_flowing = CONTENT_LAVA; + f->liquid_alternative_source = CONTENT_LAVASOURCE; + f->liquid_viscosity = LAVA_VISC; + f->damage_per_second = 4*2; + if(f->special_material == NULL && g_texturesource) + { + // Flowing lava material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer *pa_lava1 = new AtlasPointer( + g_texturesource->getTexture( + g_texturesource->getTextureId("lava.png"))); + f->special_material->setTexture(0, pa_lava1->atlas); + f->special_atlas = pa_lava1; + } + + i = CONTENT_LAVASOURCE; + f = &content_features(i); + f->setInventoryTextureCube("lava.png", "lava.png", "lava.png"); + if(new_style_water) + { + f->solidness = 0; // drawn separately, makes no faces + } + else // old style + { + f->solidness = 2; + + TileSpec t; + if(g_texturesource) + t.texture = g_texturesource->getTexture("lava.png"); + + //t.alpha = 255; + //t.material_type = MATERIAL_ALPHA_VERTEX; + //t.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; + f->setAllTiles(t); + } + f->param_type = CPT_LIGHT; + f->light_propagates = false; + f->light_source = LIGHT_MAX-1; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_SOURCE; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->liquid_alternative_flowing = CONTENT_LAVA; + f->liquid_alternative_source = CONTENT_LAVASOURCE; + f->liquid_viscosity = LAVA_VISC; + f->damage_per_second = 4*2; + if(f->special_material == NULL && g_texturesource) + { + // Flowing lava material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer *pa_lava1 = new AtlasPointer( + g_texturesource->getTexture( + g_texturesource->getTextureId("lava.png"))); + f->special_material->setTexture(0, pa_lava1->atlas); + f->special_atlas = pa_lava1; + } + + i = CONTENT_TORCH; + f = &content_features(i); + f->setInventoryTexture("torch_on_floor.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + f->wall_mounted = true; + f->air_equivalent = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->light_source = LIGHT_MAX-1; + f->digging_properties.set("", DiggingProperties(true, 0.0, 0)); + + i = CONTENT_SIGN_WALL; + f = &content_features(i); + f->setInventoryTexture("sign_wall.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + f->wall_mounted = true; + f->air_equivalent = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + if(f->initial_metadata == NULL) + f->initial_metadata = new SignNodeMetadata("Some sign"); + f->digging_properties.set("", DiggingProperties(true, 0.5, 0)); + + i = CONTENT_CHEST; + f = &content_features(i); + f->param_type = CPT_FACEDIR_SIMPLE; + f->setAllTextures("chest_side.png"); + f->setTexture(0, "chest_top.png"); + f->setTexture(1, "chest_top.png"); + f->setTexture(5, "chest_front.png"); // Z- + f->setInventoryTexture("chest_top.png"); + //f->setInventoryTextureCube("chest_top.png", "chest_side.png", "chest_side.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + if(f->initial_metadata == NULL) + f->initial_metadata = new ChestNodeMetadata(); + setWoodLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_FURNACE; + f = &content_features(i); + f->param_type = CPT_FACEDIR_SIMPLE; + f->setAllTextures("furnace_side.png"); + f->setTexture(5, "furnace_front.png"); // Z- + f->setInventoryTexture("furnace_front.png"); + //f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_COBBLE)+" 6"; + if(f->initial_metadata == NULL) + f->initial_metadata = new FurnaceNodeMetadata(); + setStoneLikeDiggingProperties(f->digging_properties, 3.0); + + i = CONTENT_COBBLE; + f = &content_features(i); + f->setAllTextures("cobble.png"); + f->setInventoryTextureCube("cobble.png", "cobble.png", "cobble.png"); + f->param_type = CPT_NONE; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 0.9); + + i = CONTENT_MOSSYCOBBLE; + f = &content_features(i); + f->setAllTextures("mossycobble.png"); + f->setInventoryTextureCube("mossycobble.png", "mossycobble.png", "mossycobble.png"); + f->param_type = CPT_NONE; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 0.8); + + i = CONTENT_STEEL; + f = &content_features(i); + f->setAllTextures("steel_block.png"); + f->setInventoryTextureCube("steel_block.png", "steel_block.png", + "steel_block.png"); + f->param_type = CPT_NONE; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 5.0); + + i = CONTENT_NC; + f = &content_features(i); + f->param_type = CPT_FACEDIR_SIMPLE; + f->setAllTextures("nc_side.png"); + f->setTexture(5, "nc_front.png"); // Z- + f->setTexture(4, "nc_back.png"); // Z+ + f->setInventoryTexture("nc_front.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 3.0); + + i = CONTENT_NC_RB; + f = &content_features(i); + f->setAllTextures("nc_rb.png"); + f->setInventoryTexture("nc_rb.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 3.0); + + i = CONTENT_APPLE; + f = &content_features(i); + f->setInventoryTexture("apple.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + f->air_equivalent = true; + f->dug_item = std::string("CraftItem apple 1"); + f->digging_properties.set("", DiggingProperties(true, 0.0, 0)); + + i = CONTENT_WOOL; + f = &content_features(i); + f->setAllTextures("wool_white.png"); + f->setInventoryTextureCube("wool_white.png", "wool_white.png", "wool_white.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_LIGHT_GREY; + f = &content_features(i); + f->setAllTextures("wool_grey.png"); + f->setInventoryTextureCube("wool_grey.png", "wool_grey.png", "wool_grey.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_DARK_GREY; + f = &content_features(i); + f->setAllTextures("wool_dark_grey.png"); + f->setInventoryTextureCube("wool_dark_grey.png", "wool_dark_grey.png", "wool_dark_grey.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_BLACK; + f = &content_features(i); + f->setAllTextures("wool_black.png"); + f->setInventoryTextureCube("wool_black.png", "wool_black.png", "wool_black.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_RED; + f = &content_features(i); + f->setAllTextures("wool_red.png"); + f->setInventoryTextureCube("wool_red.png", "wool_red.png", "wool_red.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_ORANGE; + f = &content_features(i); + f->setAllTextures("wool_orange.png"); + f->setInventoryTextureCube("wool_orange.png", "wool_orange.png", "wool_orange.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_YELLOW; + f = &content_features(i); + f->setAllTextures("wool_yellow.png"); + f->setInventoryTextureCube("wool_yellow.png", "wool_yellow.png", "wool_yellow.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_GREEN; + f = &content_features(i); + f->setAllTextures("wool_green.png"); + f->setInventoryTextureCube("wool_green.png", "wool_green.png", "wool_green.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_BROWN; + f = &content_features(i); + f->setAllTextures("wool_brown.png"); + f->setInventoryTextureCube("wool_brown.png", "wool_brown.png", "wool_brown.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_CYAN; + f = &content_features(i); + f->setAllTextures("wool_cyan.png"); + f->setInventoryTextureCube("wool_cyan.png", "wool_cyan.png", "wool_cyan.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_BLUE; + f = &content_features(i); + f->setAllTextures("wool_blue.png"); + f->setInventoryTextureCube("wool_blue.png", "wool_blue.png", "wool_blue.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_PURPLE; + f = &content_features(i); + f->setAllTextures("wool_purple.png"); + f->setInventoryTextureCube("wool_purple.png", "wool_purple.png", "wool_purple.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_PINK; + f = &content_features(i); + f->setAllTextures("wool_pink.png"); + f->setInventoryTextureCube("wool_pink.png", "wool_pink.png", "wool_pink.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + + // NOTE: Remember to add frequently used stuff to the texture atlas in tile.cpp + + + /* + Add MesePick to everything + */ + for(u16 i=0; i<=MAX_CONTENT; i++) + { + content_features(i).digging_properties.set("MesePick", + DiggingProperties(true, 0.0, 65535./1337)); + } + +} + +void setStoneLikeDiggingProperties(DiggingPropertiesList &list, float toughness) +{ + list.set("", + DiggingProperties(true, 15.0*toughness, 0)); + + list.set("WPick", + DiggingProperties(true, 1.3*toughness, 65535./30.*toughness)); + list.set("STPick", + DiggingProperties(true, 0.75*toughness, 65535./100.*toughness)); + list.set("SteelPick", + DiggingProperties(true, 0.50*toughness, 65535./333.*toughness)); + + /*list.set("MesePick", + DiggingProperties(true, 0.0*toughness, 65535./20.*toughness));*/ +} + +void setDirtLikeDiggingProperties(DiggingPropertiesList &list, float toughness) +{ + list.set("", + DiggingProperties(true, 0.75*toughness, 0)); + + list.set("WShovel", + DiggingProperties(true, 0.4*toughness, 65535./50.*toughness)); + list.set("STShovel", + DiggingProperties(true, 0.2*toughness, 65535./150.*toughness)); + list.set("SteelShovel", + DiggingProperties(true, 0.15*toughness, 65535./400.*toughness)); +} + +void setWoodLikeDiggingProperties(DiggingPropertiesList &list, float toughness) +{ + list.set("", + DiggingProperties(true, 3.0*toughness, 0)); + + list.set("WAxe", + DiggingProperties(true, 1.5*toughness, 65535./30.*toughness)); + list.set("STAxe", + DiggingProperties(true, 0.75*toughness, 65535./100.*toughness)); + list.set("SteelAxe", + DiggingProperties(true, 0.5*toughness, 65535./333.*toughness)); +} + + diff --git a/src/content_mapnode.cpp~ b/src/content_mapnode.cpp~ new file mode 100644 index 0000000..a50a372 --- /dev/null +++ b/src/content_mapnode.cpp~ @@ -0,0 +1,806 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// For g_settings +#include "main.h" + +#include "content_mapnode.h" +#include "mapnode.h" +#include "content_nodemeta.h" + +#define WATER_ALPHA 160 + +#define WATER_VISC 1 +#define LAVA_VISC 7 + +// TODO: Get rid of these and set up some attributes like toughness, +// fluffyness, and a funciton to calculate time and durability loss +// (and sound? and whatever else) from them +void setStoneLikeDiggingProperties(DiggingPropertiesList &list, float toughness); +void setDirtLikeDiggingProperties(DiggingPropertiesList &list, float toughness); +void setWoodLikeDiggingProperties(DiggingPropertiesList &list, float toughness); + +/* + A conversion table for backwards compatibility. + Maps <=v19 content types to current ones. + Should never be touched. +*/ +content_t trans_table_19[21][2] = { + {CONTENT_GRASS, 1}, + {CONTENT_TREE, 4}, + {CONTENT_LEAVES, 5}, + {CONTENT_GRASS_FOOTSTEPS, 6}, + {CONTENT_MESE, 7}, + {CONTENT_MUD, 8}, + {CONTENT_CLOUD, 10}, + {CONTENT_COALSTONE, 11}, + {CONTENT_WOOD, 12}, + {CONTENT_SAND, 13}, + {CONTENT_COBBLE, 18}, + {CONTENT_STEEL, 19}, + {CONTENT_GLASS, 20}, + {CONTENT_MOSSYCOBBLE, 22}, + {CONTENT_GRAVEL, 23}, + {CONTENT_SANDSTONE, 24}, + {CONTENT_CACTUS, 25}, + {CONTENT_BRICK, 26}, + {CONTENT_CLAY, 27}, + {CONTENT_PAPYRUS, 28}, + {CONTENT_BOOKSHELF, 29}, +}; + +MapNode mapnode_translate_from_internal(MapNode n_from, u8 version) +{ + MapNode result = n_from; + if(version <= 19) + { + content_t c_from = n_from.getContent(); + for(u32 i=0; isetAllTextures("stone.png"); + f->setInventoryTextureCube("stone.png", "stone.png", "stone.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_COBBLE)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 1.0); + if(invisible_stone) + f->solidness = 0; // For debugging, hides regular stone + + i = CONTENT_GRASS; + f = &content_features(i); + f->setAllTextures("mud.png^grass_side.png"); + f->setTexture(0, "grass.png"); + f->setTexture(1, "mud.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_MUD)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_GRASS_FOOTSTEPS; + f = &content_features(i); + f->setAllTextures("mud.png^grass_side.png"); + f->setTexture(0, "grass_footsteps.png"); + f->setTexture(1, "mud.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_MUD)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_MUD; + f = &content_features(i); + f->setAllTextures("mud.png"); + f->setInventoryTextureCube("mud.png", "mud.png", "mud.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_SAND; + f = &content_features(i); + f->setAllTextures("sand.png"); + f->setInventoryTextureCube("sand.png", "sand.png", "sand.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_GRAVEL; + f = &content_features(i); + f->setAllTextures("gravel.png"); + f->setInventoryTextureCube("gravel.png", "gravel.png", "gravel.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.75); + + i = CONTENT_SANDSTONE; + f = &content_features(i); + f->setAllTextures("sandstone.png"); + f->setInventoryTextureCube("sandstone.png", "sandstone.png", "sandstone.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_SAND)+" 1"; + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_CLAY; + f = &content_features(i); + f->setAllTextures("clay.png"); + f->setInventoryTextureCube("clay.png", "clay.png", "clay.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("CraftItem lump_of_clay 4"); + setDirtLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_BRICK; + f = &content_features(i); + f->setAllTextures("brick.png"); + f->setInventoryTextureCube("brick.png", "brick.png", "brick.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("CraftItem clay_brick 4"); + setStoneLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_TREE; + f = &content_features(i); + f->setAllTextures("tree.png"); + f->setTexture(0, "tree_top.png"); + f->setTexture(1, "tree_top.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_JUNGLETREE; + f = &content_features(i); + f->setAllTextures("jungletree.png"); + f->setTexture(0, "jungletree_top.png"); + f->setTexture(1, "jungletree_top.png"); + f->param_type = CPT_MINERAL; + //f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_JUNGLEGRASS; + f = &content_features(i); + f->setInventoryTexture("junglegrass.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + //f->is_ground_content = true; + f->air_equivalent = false; // grass grows underneath + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + setWoodLikeDiggingProperties(f->digging_properties, 0.10); + + i = CONTENT_LEAVES; + f = &content_features(i); + f->light_propagates = true; + //f->param_type = CPT_MINERAL; + f->param_type = CPT_LIGHT; + //f->is_ground_content = true; + if(new_style_leaves) + { + f->solidness = 0; // drawn separately, makes no faces + f->setInventoryTextureCube("leaves.png", "leaves.png", "leaves.png"); + } + else + { + f->setAllTextures("[noalpha:leaves.png"); + } + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.15); + + i = CONTENT_CACTUS; + f = &content_features(i); + f->setAllTextures("cactus_side.png"); + f->setTexture(0, "cactus_top.png"); + f->setTexture(1, "cactus_top.png"); + f->setInventoryTextureCube("cactus_top.png", "cactus_side.png", "cactus_side.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_PAPYRUS; + f = &content_features(i); + f->setInventoryTexture("papyrus.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + setWoodLikeDiggingProperties(f->digging_properties, 0.25); + + i = CONTENT_BOOKSHELF; + f = &content_features(i); + f->setAllTextures("bookshelf.png"); + f->setTexture(0, "wood.png"); + f->setTexture(1, "wood.png"); + // FIXME: setInventoryTextureCube() only cares for the first texture + f->setInventoryTextureCube("bookshelf.png", "bookshelf.png", "bookshelf.png"); + //f->setInventoryTextureCube("wood.png", "bookshelf.png", "bookshelf.png"); + f->param_type = CPT_MINERAL; + f->is_ground_content = true; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_GLASS; + f = &content_features(i); + f->light_propagates = true; + f->sunlight_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->setInventoryTextureCube("glass.png", "glass.png", "glass.png"); + setWoodLikeDiggingProperties(f->digging_properties, 0.15); + + i = CONTENT_FENCE; + f = &content_features(i); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->air_equivalent = true; // grass grows underneath + f->setInventoryTexture("fence.png"); + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_RAIL; + f = &content_features(i); + f->setInventoryTexture("rail.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->solidness = 0; // drawn separately, makes no faces + f->air_equivalent = true; // grass grows underneath + f->walkable = false; + setDirtLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_LADDER; + f = &content_features(i); + f->setInventoryTexture("ladder.png"); + f->light_propagates = true; + f->param_type = CPT_LIGHT; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem ")+itos(i)+" 1"; + f->wall_mounted = true; + f->solidness = 0; + f->air_equivalent = true; + f->walkable = false; + f->climbable = true; + setWoodLikeDiggingProperties(f->digging_properties, 0.5); + + // Deprecated + i = CONTENT_COALSTONE; + f = &content_features(i); + f->setAllTextures("stone.png^mineral_coal.png"); + f->is_ground_content = true; + setStoneLikeDiggingProperties(f->digging_properties, 1.5); + + i = CONTENT_WOOD; + f = &content_features(i); + f->setAllTextures("wood.png"); + f->setInventoryTextureCube("wood.png", "wood.png", "wood.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_MESE; + f = &content_features(i); + f->setAllTextures("mese.png"); + f->setInventoryTextureCube("mese.png", "mese.png", "mese.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 0.5); + + i = CONTENT_CLOUD; + f = &content_features(i); + f->setAllTextures("cloud.png"); + f->setInventoryTextureCube("cloud.png", "cloud.png", "cloud.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + + i = CONTENT_AIR; + f = &content_features(i); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->air_equivalent = true; + + i = CONTENT_WATER; + f = &content_features(i); + f->setInventoryTextureCube("water.png", "water.png", "water.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->solidness = 0; // Drawn separately, makes no faces + f->visual_solidness = 1; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_FLOWING; + f->liquid_alternative_flowing = CONTENT_WATER; + f->liquid_alternative_source = CONTENT_WATERSOURCE; + f->liquid_viscosity = WATER_VISC; + f->vertex_alpha = WATER_ALPHA; + if(f->special_material == NULL && g_texturesource) + { + // Flowing water material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + AtlasPointer *pa_water1 = new AtlasPointer(g_texturesource->getTexture( + g_texturesource->getTextureId("water.png"))); + f->special_material->setTexture(0, pa_water1->atlas); + f->special_atlas = pa_water1; + } + + i = CONTENT_WATERSOURCE; + f = &content_features(i); + //f->setInventoryTexture("water.png"); + f->setInventoryTextureCube("water.png", "water.png", "water.png"); + if(new_style_water) + { + f->solidness = 0; // drawn separately, makes no faces + } + else // old style + { + f->solidness = 1; + + TileSpec t; + if(g_texturesource) + t.texture = g_texturesource->getTexture("water.png"); + + t.alpha = WATER_ALPHA; + t.material_type = MATERIAL_ALPHA_VERTEX; + t.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; + f->setAllTiles(t); + } + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_SOURCE; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->liquid_alternative_flowing = CONTENT_WATER; + f->liquid_alternative_source = CONTENT_WATERSOURCE; + f->liquid_viscosity = WATER_VISC; + f->vertex_alpha = WATER_ALPHA; + if(f->special_material == NULL && g_texturesource) + { + // Flowing water material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + AtlasPointer *pa_water1 = new AtlasPointer(g_texturesource->getTexture( + g_texturesource->getTextureId("water.png"))); + f->special_material->setTexture(0, pa_water1->atlas); + f->special_atlas = pa_water1; + } + + i = CONTENT_LAVA; + f = &content_features(i); + f->setInventoryTextureCube("lava.png", "lava.png", "lava.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = false; + f->light_source = LIGHT_MAX-1; + f->solidness = 0; // Drawn separately, makes no faces + f->visual_solidness = 2; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_FLOWING; + f->liquid_alternative_flowing = CONTENT_LAVA; + f->liquid_alternative_source = CONTENT_LAVASOURCE; + f->liquid_viscosity = LAVA_VISC; + f->damage_per_second = 4*2; + if(f->special_material == NULL && g_texturesource) + { + // Flowing lava material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer *pa_lava1 = new AtlasPointer( + g_texturesource->getTexture( + g_texturesource->getTextureId("lava.png"))); + f->special_material->setTexture(0, pa_lava1->atlas); + f->special_atlas = pa_lava1; + } + + i = CONTENT_LAVASOURCE; + f = &content_features(i); + f->setInventoryTextureCube("lava.png", "lava.png", "lava.png"); + if(new_style_water) + { + f->solidness = 0; // drawn separately, makes no faces + } + else // old style + { + f->solidness = 2; + + TileSpec t; + if(g_texturesource) + t.texture = g_texturesource->getTexture("lava.png"); + + //t.alpha = 255; + //t.material_type = MATERIAL_ALPHA_VERTEX; + //t.material_flags &= ~MATERIAL_FLAG_BACKFACE_CULLING; + f->setAllTiles(t); + } + f->param_type = CPT_LIGHT; + f->light_propagates = false; + f->light_source = LIGHT_MAX-1; + f->walkable = false; + f->pointable = false; + f->diggable = false; + f->buildable_to = true; + f->liquid_type = LIQUID_SOURCE; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->liquid_alternative_flowing = CONTENT_LAVA; + f->liquid_alternative_source = CONTENT_LAVASOURCE; + f->liquid_viscosity = LAVA_VISC; + f->damage_per_second = 4*2; + if(f->special_material == NULL && g_texturesource) + { + // Flowing lava material + f->special_material = new video::SMaterial; + f->special_material->setFlag(video::EMF_LIGHTING, false); + f->special_material->setFlag(video::EMF_BACK_FACE_CULLING, false); + f->special_material->setFlag(video::EMF_BILINEAR_FILTER, false); + f->special_material->setFlag(video::EMF_FOG_ENABLE, true); + f->special_material->MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + AtlasPointer *pa_lava1 = new AtlasPointer( + g_texturesource->getTexture( + g_texturesource->getTextureId("lava.png"))); + f->special_material->setTexture(0, pa_lava1->atlas); + f->special_atlas = pa_lava1; + } + + i = CONTENT_TORCH; + f = &content_features(i); + f->setInventoryTexture("torch_on_floor.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + f->wall_mounted = true; + f->air_equivalent = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->light_source = LIGHT_MAX-1; + f->digging_properties.set("", DiggingProperties(true, 0.0, 0)); + + i = CONTENT_SIGN_WALL; + f = &content_features(i); + f->setInventoryTexture("sign_wall.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + f->wall_mounted = true; + f->air_equivalent = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + if(f->initial_metadata == NULL) + f->initial_metadata = new SignNodeMetadata("Some sign"); + f->digging_properties.set("", DiggingProperties(true, 0.5, 0)); + + i = CONTENT_CHEST; + f = &content_features(i); + f->param_type = CPT_FACEDIR_SIMPLE; + f->setAllTextures("chest_side.png"); + f->setTexture(0, "chest_top.png"); + f->setTexture(1, "chest_top.png"); + f->setTexture(5, "chest_front.png"); // Z- + f->setInventoryTexture("chest_top.png"); + //f->setInventoryTextureCube("chest_top.png", "chest_side.png", "chest_side.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + if(f->initial_metadata == NULL) + f->initial_metadata = new ChestNodeMetadata(); + setWoodLikeDiggingProperties(f->digging_properties, 1.0); + + i = CONTENT_FURNACE; + f = &content_features(i); + f->param_type = CPT_FACEDIR_SIMPLE; + f->setAllTextures("furnace_side.png"); + f->setTexture(5, "furnace_front.png"); // Z- + f->setInventoryTexture("furnace_front.png"); + //f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + f->dug_item = std::string("MaterialItem2 ")+itos(CONTENT_COBBLE)+" 6"; + if(f->initial_metadata == NULL) + f->initial_metadata = new FurnaceNodeMetadata(); + setStoneLikeDiggingProperties(f->digging_properties, 3.0); + + i = CONTENT_COBBLE; + f = &content_features(i); + f->setAllTextures("cobble.png"); + f->setInventoryTextureCube("cobble.png", "cobble.png", "cobble.png"); + f->param_type = CPT_NONE; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 0.9); + + i = CONTENT_MOSSYCOBBLE; + f = &content_features(i); + f->setAllTextures("mossycobble.png"); + f->setInventoryTextureCube("mossycobble.png", "mossycobble.png", "mossycobble.png"); + f->param_type = CPT_NONE; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 0.8); + + i = CONTENT_STEEL; + f = &content_features(i); + f->setAllTextures("steel_block.png"); + f->setInventoryTextureCube("steel_block.png", "steel_block.png", + "steel_block.png"); + f->param_type = CPT_NONE; + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 5.0); + + i = CONTENT_NC; + f = &content_features(i); + f->param_type = CPT_FACEDIR_SIMPLE; + f->setAllTextures("nc_side.png"); + f->setTexture(5, "nc_front.png"); // Z- + f->setTexture(4, "nc_back.png"); // Z+ + f->setInventoryTexture("nc_front.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 3.0); + + i = CONTENT_NC_RB; + f = &content_features(i); + f->setAllTextures("nc_rb.png"); + f->setInventoryTexture("nc_rb.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setStoneLikeDiggingProperties(f->digging_properties, 3.0); + + i = CONTENT_APPLE; + f = &content_features(i); + f->setInventoryTexture("apple.png"); + f->param_type = CPT_LIGHT; + f->light_propagates = true; + f->sunlight_propagates = true; + f->solidness = 0; // drawn separately, makes no faces + f->walkable = false; + f->air_equivalent = true; + f->dug_item = std::string("CraftItem apple 1"); + f->digging_properties.set("", DiggingProperties(true, 0.0, 0)); + + i = CONTENT_WOOL; + f = &content_features(i); + f->setAllTextures("wool_white.png"); + f->setInventoryTextureCube("wool_white.png", "wool_white.png", "wool_white.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_LIGHT_GREY; + f = &content_features(i); + f->setAllTextures("wool_grey.png"); + f->setInventoryTextureCube("wool_grey.png", "wool_grey.png", "wool_grey.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_DARK_GREY; + f = &content_features(i); + f->setAllTextures("wool_dark_grey.png"); + f->setInventoryTextureCube("wool_dark_grey.png", "wool_dark_grey.png", "wool_dark_grey.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_BLACK; + f = &content_features(i); + f->setAllTextures("wool_black.png"); + f->setInventoryTextureCube("wool_black.png", "wool_black.png", "wool_black.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_RED; + f = &content_features(i); + f->setAllTextures("wool_red.png"); + f->setInventoryTextureCube("wool_red.png", "wool_red.png", "wool_red.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_ORANGE; + f = &content_features(i); + f->setAllTextures("wool_orange.png"); + f->setInventoryTextureCube("wool_orange.png", "wool_orange.png", "wool_orange.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_YELLOW; + f = &content_features(i); + f->setAllTextures("wool_yellow.png"); + f->setInventoryTextureCube("wool_yellow.png", "wool_yellow.png", "wool_yellow.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_GREEN; + f = &content_features(i); + f->setAllTextures("wool_green.png"); + f->setInventoryTextureCube("wool_green.png", "wool_green.png", "wool_green.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_BROWN; + f = &content_features(i); + f->setAllTextures("wool_brown.png"); + f->setInventoryTextureCube("wool_brown.png", "wool_brown.png", "wool_brown.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_CYAN; + f = &content_features(i); + f->setAllTextures("wool_cyan.png"); + f->setInventoryTextureCube("wool_cyan.png", "wool_cyan.png", "wool_cyan.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_BLUE; + f = &content_features(i); + f->setAllTextures("wool_blue.png"); + f->setInventoryTextureCube("wool_blue.png", "wool_blue.png", "wool_blue.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_PURPLE; + f = &content_features(i); + f->setAllTextures("wool_purple.png"); + f->setInventoryTextureCube("wool_purple.png", "wool_purple.png", "wool_purple.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + i = CONTENT_WOOL_PINK; + f = &content_features(i); + f->setAllTextures("wool_pink.png"); + f->setInventoryTextureCube("wool_pink.png", "wool_pink.png", "wool_pink.png"); + f->is_ground_content = true; + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + setWoodLikeDiggingProperties(f->digging_properties, 0.75); + + + // NOTE: Remember to add frequently used stuff to the texture atlas in tile.cpp + + + /* + Add MesePick to everything + */ + for(u16 i=0; i<=MAX_CONTENT; i++) + { + content_features(i).digging_properties.set("MesePick", + DiggingProperties(true, 0.0, 65535./1337)); + } + +} + +void setStoneLikeDiggingProperties(DiggingPropertiesList &list, float toughness) +{ + list.set("", + DiggingProperties(true, 15.0*toughness, 0)); + + list.set("WPick", + DiggingProperties(true, 1.3*toughness, 65535./30.*toughness)); + list.set("STPick", + DiggingProperties(true, 0.75*toughness, 65535./100.*toughness)); + list.set("SteelPick", + DiggingProperties(true, 0.50*toughness, 65535./333.*toughness)); + + /*list.set("MesePick", + DiggingProperties(true, 0.0*toughness, 65535./20.*toughness));*/ +} + +void setDirtLikeDiggingProperties(DiggingPropertiesList &list, float toughness) +{ + list.set("", + DiggingProperties(true, 0.75*toughness, 0)); + + list.set("WShovel", + DiggingProperties(true, 0.4*toughness, 65535./50.*toughness)); + list.set("STShovel", + DiggingProperties(true, 0.2*toughness, 65535./150.*toughness)); + list.set("SteelShovel", + DiggingProperties(true, 0.15*toughness, 65535./400.*toughness)); +} + +void setWoodLikeDiggingProperties(DiggingPropertiesList &list, float toughness) +{ + list.set("", + DiggingProperties(true, 3.0*toughness, 0)); + + list.set("WAxe", + DiggingProperties(true, 1.5*toughness, 65535./30.*toughness)); + list.set("STAxe", + DiggingProperties(true, 0.75*toughness, 65535./100.*toughness)); + list.set("SteelAxe", + DiggingProperties(true, 0.5*toughness, 65535./333.*toughness)); +} + + diff --git a/src/content_mapnode.h b/src/content_mapnode.h new file mode 100644 index 0000000..f8b4344 --- /dev/null +++ b/src/content_mapnode.h @@ -0,0 +1,107 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_MAPNODE_HEADER +#define CONTENT_MAPNODE_HEADER + +#include "mapnode.h" + +void content_mapnode_init(); + +extern content_t trans_table_19[21][2]; + +MapNode mapnode_translate_from_internal(MapNode n_from, u8 version); +MapNode mapnode_translate_to_internal(MapNode n_from, u8 version); + +/* + Node content type IDs + Ranges: +*/ + +// 0x000...0x07f (0...127): param2 is fully usable +// 126 and 127 are reserved. +// Use these sparingly, only when the extra space in param2 might be needed. +// Add a space when there is unused space between numbers. +#define CONTENT_STONE 0 + +#define CONTENT_WATER 2 +#define CONTENT_TORCH 3 + +#define CONTENT_WATERSOURCE 9 + +#define CONTENT_SIGN_WALL 14 +#define CONTENT_CHEST 15 +#define CONTENT_FURNACE 16 + +#define CONTENT_FENCE 21 + +#define CONTENT_RAIL 30 +#define CONTENT_LADDER 31 +#define CONTENT_LAVA 32 +#define CONTENT_LAVASOURCE 33 + +//Wool Defs. + +#define CONTENT_WOOL 70 +#define CONTENT_WOOL_LIGHT_GREY 71 +#define CONTENT_WOOL_DARK_GREY 72 +#define CONTENT_WOOL_BLACK 73 +#define CONTENT_WOOL_RED 74 +#define CONTENT_WOOL_ORANGE 75 +#define CONTENT_WOOL_YELLOW 76 +#define CONTENT_WOOL_GREEN 82 +#define CONTENT_WOOL_CYAN 77 +#define CONTENT_WOOL_BLUE 78 +#define CONTENT_WOOL_PURPLE 79 +#define CONTENT_WOOL_PINK 80 +#define CONTENT_WOOL_BROWN 81 + + +// 0x800...0xfff (2048...4095): higher 4 bytes of param2 are not usable +#define CONTENT_GRASS 0x800 //1 +#define CONTENT_TREE 0x801 //4 +#define CONTENT_LEAVES 0x802 //5 +#define CONTENT_GRASS_FOOTSTEPS 0x803 //6 +#define CONTENT_MESE 0x804 //7 +#define CONTENT_MUD 0x805 //8 +// Pretty much useless, clouds won't be drawn this way +#define CONTENT_CLOUD 0x806 //10 +#define CONTENT_COALSTONE 0x807 //11 +#define CONTENT_WOOD 0x808 //12 +#define CONTENT_SAND 0x809 //13 +#define CONTENT_COBBLE 0x80a //18 +#define CONTENT_STEEL 0x80b //19 +#define CONTENT_GLASS 0x80c //20 +#define CONTENT_MOSSYCOBBLE 0x80d //22 +#define CONTENT_GRAVEL 0x80e //23 +#define CONTENT_SANDSTONE 0x80f //24 +#define CONTENT_CACTUS 0x810 //25 +#define CONTENT_BRICK 0x811 //26 +#define CONTENT_CLAY 0x812 //27 +#define CONTENT_PAPYRUS 0x813 //28 +#define CONTENT_BOOKSHELF 0x814 //29 +#define CONTENT_JUNGLETREE 0x815 +#define CONTENT_JUNGLEGRASS 0x816 +#define CONTENT_NC 0x817 +#define CONTENT_NC_RB 0x818 +#define CONTENT_APPLE 0x819 + + +#endif + diff --git a/src/content_mapnode.h~ b/src/content_mapnode.h~ new file mode 100644 index 0000000..39ac7bd --- /dev/null +++ b/src/content_mapnode.h~ @@ -0,0 +1,107 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_MAPNODE_HEADER +#define CONTENT_MAPNODE_HEADER + +#include "mapnode.h" + +void content_mapnode_init(); + +extern content_t trans_table_19[21][2]; + +MapNode mapnode_translate_from_internal(MapNode n_from, u8 version); +MapNode mapnode_translate_to_internal(MapNode n_from, u8 version); + +/* + Node content type IDs + Ranges: +*/ + +// 0x000...0x07f (0...127): param2 is fully usable +// 126 and 127 are reserved. +// Use these sparingly, only when the extra space in param2 might be needed. +// Add a space when there is unused space between numbers. +#define CONTENT_STONE 0 + +#define CONTENT_WATER 2 +#define CONTENT_TORCH 3 + +#define CONTENT_WATERSOURCE 9 + +#define CONTENT_SIGN_WALL 14 +#define CONTENT_CHEST 15 +#define CONTENT_FURNACE 16 + +#define CONTENT_FENCE 21 + +#define CONTENT_RAIL 30 +#define CONTENT_LADDER 31 +#define CONTENT_LAVA 32 +#define CONTENT_LAVASOURCE 33 + +//Wool Defs. + +#define CONTENT_WOOL 70 +#define CONTENT_WOOL_LIGHT_GREY 71 +#define CONTENT_WOOL_DARK_GREY 72 +#define CONTENT_WOOL_BLACK 73 +#define CONTENT_WOOL_RED 74 +#define CONTENT_WOOL_ORANGE 75 +#define CONTENT_WOOL_YELLOW 76 +#define CONTENT_WOOL_GREEN82 +#define CONTENT_WOOL_CYAN 77 +#define CONTENT_WOOL_BLUE 78 +#define CONTENT_WOOL_PURPLE 79 +#define CONTENT_WOOL_PINK 80 +#define CONTENT_WOOL_BROWN 81 + + +// 0x800...0xfff (2048...4095): higher 4 bytes of param2 are not usable +#define CONTENT_GRASS 0x800 //1 +#define CONTENT_TREE 0x801 //4 +#define CONTENT_LEAVES 0x802 //5 +#define CONTENT_GRASS_FOOTSTEPS 0x803 //6 +#define CONTENT_MESE 0x804 //7 +#define CONTENT_MUD 0x805 //8 +// Pretty much useless, clouds won't be drawn this way +#define CONTENT_CLOUD 0x806 //10 +#define CONTENT_COALSTONE 0x807 //11 +#define CONTENT_WOOD 0x808 //12 +#define CONTENT_SAND 0x809 //13 +#define CONTENT_COBBLE 0x80a //18 +#define CONTENT_STEEL 0x80b //19 +#define CONTENT_GLASS 0x80c //20 +#define CONTENT_MOSSYCOBBLE 0x80d //22 +#define CONTENT_GRAVEL 0x80e //23 +#define CONTENT_SANDSTONE 0x80f //24 +#define CONTENT_CACTUS 0x810 //25 +#define CONTENT_BRICK 0x811 //26 +#define CONTENT_CLAY 0x812 //27 +#define CONTENT_PAPYRUS 0x813 //28 +#define CONTENT_BOOKSHELF 0x814 //29 +#define CONTENT_JUNGLETREE 0x815 +#define CONTENT_JUNGLEGRASS 0x816 +#define CONTENT_NC 0x817 +#define CONTENT_NC_RB 0x818 +#define CONTENT_APPLE 0x819 + + +#endif + diff --git a/src/content_nodemeta.cpp b/src/content_nodemeta.cpp new file mode 100644 index 0000000..1552c8e --- /dev/null +++ b/src/content_nodemeta.cpp @@ -0,0 +1,411 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_nodemeta.h" +#include "inventory.h" +#include "content_mapnode.h" + +/* + SignNodeMetadata +*/ + +// Prototype +SignNodeMetadata proto_SignNodeMetadata(""); + +SignNodeMetadata::SignNodeMetadata(std::string text): + m_text(text) +{ + NodeMetadata::registerType(typeId(), create); +} +u16 SignNodeMetadata::typeId() const +{ + return CONTENT_SIGN_WALL; +} +NodeMetadata* SignNodeMetadata::create(std::istream &is) +{ + std::string text = deSerializeString(is); + return new SignNodeMetadata(text); +} +NodeMetadata* SignNodeMetadata::clone() +{ + return new SignNodeMetadata(m_text); +} +void SignNodeMetadata::serializeBody(std::ostream &os) +{ + os<addList("0", 8*4); +} +ChestNodeMetadata::~ChestNodeMetadata() +{ + delete m_inventory; +} +u16 ChestNodeMetadata::typeId() const +{ + return CONTENT_CHEST; +} +NodeMetadata* ChestNodeMetadata::create(std::istream &is) +{ + ChestNodeMetadata *d = new ChestNodeMetadata(); + d->m_inventory->deSerialize(is); + return d; +} +NodeMetadata* ChestNodeMetadata::clone() +{ + ChestNodeMetadata *d = new ChestNodeMetadata(); + *d->m_inventory = *m_inventory; + return d; +} +void ChestNodeMetadata::serializeBody(std::ostream &os) +{ + m_inventory->serialize(os); +} +std::string ChestNodeMetadata::infoText() +{ + return "Chest"; +} +bool ChestNodeMetadata::nodeRemovalDisabled() +{ + /* + Disable removal if chest contains something + */ + InventoryList *list = m_inventory->getList("0"); + if(list == NULL) + return false; + if(list->getUsedSlots() == 0) + return false; + return true; +} +std::string ChestNodeMetadata::getInventoryDrawSpecString() +{ + return + "invsize[8,9;]" + "list[current_name;0;0,0;8,4;]" + "list[current_player;main;0,5;8,4;]"; +} + +/* + FurnaceNodeMetadata +*/ + +// Prototype +FurnaceNodeMetadata proto_FurnaceNodeMetadata; + +FurnaceNodeMetadata::FurnaceNodeMetadata() +{ + NodeMetadata::registerType(typeId(), create); + + m_inventory = new Inventory(); + m_inventory->addList("fuel", 1); + m_inventory->addList("src", 1); + m_inventory->addList("dst", 4); + + m_step_accumulator = 0; + m_fuel_totaltime = 0; + m_fuel_time = 0; + m_src_totaltime = 0; + m_src_time = 0; +} +FurnaceNodeMetadata::~FurnaceNodeMetadata() +{ + delete m_inventory; +} +u16 FurnaceNodeMetadata::typeId() const +{ + return CONTENT_FURNACE; +} +NodeMetadata* FurnaceNodeMetadata::clone() +{ + FurnaceNodeMetadata *d = new FurnaceNodeMetadata(); + *d->m_inventory = *m_inventory; + return d; +} +NodeMetadata* FurnaceNodeMetadata::create(std::istream &is) +{ + FurnaceNodeMetadata *d = new FurnaceNodeMetadata(); + + d->m_inventory->deSerialize(is); + + int temp; + is>>temp; + d->m_fuel_totaltime = (float)temp/10; + is>>temp; + d->m_fuel_time = (float)temp/10; + + return d; +} +void FurnaceNodeMetadata::serializeBody(std::ostream &os) +{ + m_inventory->serialize(os); + os<= m_fuel_totaltime) + { + const InventoryList *src_list = m_inventory->getList("src"); + assert(src_list); + const InventoryItem *src_item = src_list->getItem(0); + + if(src_item && src_item->isCookable()) { + InventoryList *dst_list = m_inventory->getList("dst"); + if(!dst_list->roomForCookedItem(src_item)) + return "Furnace is overloaded"; + return "Furnace is out of fuel"; + } + else + return "Furnace is inactive"; + } + else + { + std::string s = "Furnace is active"; + // Do this so it doesn't always show (0%) for weak fuel + if(m_fuel_totaltime > 3) { + s += " ("; + s += itos(m_fuel_time/m_fuel_totaltime*100); + s += "%)"; + } + return s; + } +} +bool FurnaceNodeMetadata::nodeRemovalDisabled() +{ + /* + Disable removal if furnace is not empty + */ + InventoryList *list[3] = {m_inventory->getList("src"), + m_inventory->getList("dst"), m_inventory->getList("fuel")}; + + for(int i = 0; i < 3; i++) { + if(list[i] == NULL) + continue; + if(list[i]->getUsedSlots() == 0) + continue; + return true; + } + return false; + +} +void FurnaceNodeMetadata::inventoryModified() +{ + dstream<<"Furnace inventory modification callback"< 60.0) + dstream<<"Furnace stepping a long time ("< interval) + { + m_step_accumulator -= interval; + dtime = interval; + + //dstream<<"Furnace step dtime="<getList("dst"); + assert(dst_list); + + InventoryList *src_list = m_inventory->getList("src"); + assert(src_list); + InventoryItem *src_item = src_list->getItem(0); + + bool room_available = false; + + if(src_item && src_item->isCookable()) + room_available = dst_list->roomForCookedItem(src_item); + + // Start only if there are free slots in dst, so that it can + // accomodate any result item + if(room_available) + { + m_src_totaltime = 3; + } + else + { + m_src_time = 0; + m_src_totaltime = 0; + } + + /* + If fuel is burning, increment the burn counters. + If item finishes cooking, move it to result. + */ + if(m_fuel_time < m_fuel_totaltime) + { + //dstream<<"Furnace is active"<= m_src_totaltime && m_src_totaltime > 0.001 + && src_item) + { + InventoryItem *cookresult = src_item->createCookResult(); + dst_list->addItem(cookresult); + src_list->decrementMaterials(1); + m_src_time = 0; + m_src_totaltime = 0; + } + changed = true; + + // If the fuel was not used up this step, just keep burning it + if(m_fuel_time < m_fuel_totaltime) + continue; + } + + /* + Get the source again in case it has all burned + */ + src_item = src_list->getItem(0); + + /* + If there is no source item, or the source item is not cookable, + or the furnace is still cooking, or the furnace became overloaded, stop loop. + */ + if(src_item == NULL || !room_available || m_fuel_time < m_fuel_totaltime || + dst_list->roomForCookedItem(src_item) == false) + { + m_step_accumulator = 0; + break; + } + + //dstream<<"Furnace is out of fuel"<getList("fuel"); + assert(fuel_list); + const InventoryItem *fuel_item = fuel_list->getItem(0); + + if(ItemSpec(ITEM_MATERIAL, CONTENT_TREE).checkItem(fuel_item)) + { + m_fuel_totaltime = 30; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_JUNGLETREE).checkItem(fuel_item)) + { + m_fuel_totaltime = 30; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_FENCE).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/2; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_WOOD).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/4; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_BOOKSHELF).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/4; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_LEAVES).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/16; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_PAPYRUS).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/32; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_JUNGLEGRASS).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/32; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_MATERIAL, CONTENT_CACTUS).checkItem(fuel_item)) + { + m_fuel_totaltime = 30/4; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_CRAFT, "Stick").checkItem(fuel_item)) + { + m_fuel_totaltime = 30/4/4; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else if(ItemSpec(ITEM_CRAFT, "lump_of_coal").checkItem(fuel_item)) + { + m_fuel_totaltime = 40; + m_fuel_time = 0; + fuel_list->decrementMaterials(1); + changed = true; + } + else + { + //dstream<<"No fuel found"< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_NODEMETA_HEADER +#define CONTENT_NODEMETA_HEADER + +#include "nodemetadata.h" + +class Inventory; + +class SignNodeMetadata : public NodeMetadata +{ +public: + SignNodeMetadata(std::string text); + //~SignNodeMetadata(); + + virtual u16 typeId() const; + static NodeMetadata* create(std::istream &is); + virtual NodeMetadata* clone(); + virtual void serializeBody(std::ostream &os); + virtual std::string infoText(); + + std::string getText(){ return m_text; } + void setText(std::string t){ m_text = t; } + +private: + std::string m_text; +}; + +class ChestNodeMetadata : public NodeMetadata +{ +public: + ChestNodeMetadata(); + ~ChestNodeMetadata(); + + virtual u16 typeId() const; + static NodeMetadata* create(std::istream &is); + virtual NodeMetadata* clone(); + virtual void serializeBody(std::ostream &os); + virtual std::string infoText(); + virtual Inventory* getInventory() {return m_inventory;} + virtual bool nodeRemovalDisabled(); + virtual std::string getInventoryDrawSpecString(); + +private: + Inventory *m_inventory; +}; + +class FurnaceNodeMetadata : public NodeMetadata +{ +public: + FurnaceNodeMetadata(); + ~FurnaceNodeMetadata(); + + virtual u16 typeId() const; + virtual NodeMetadata* clone(); + static NodeMetadata* create(std::istream &is); + virtual void serializeBody(std::ostream &os); + virtual std::string infoText(); + virtual Inventory* getInventory() {return m_inventory;} + virtual void inventoryModified(); + virtual bool step(float dtime); + virtual bool nodeRemovalDisabled(); + virtual std::string getInventoryDrawSpecString(); + +private: + Inventory *m_inventory; + float m_step_accumulator; + float m_fuel_totaltime; + float m_fuel_time; + float m_src_totaltime; + float m_src_time; +}; + + +#endif + diff --git a/src/content_object.h b/src/content_object.h new file mode 100644 index 0000000..47f93d7 --- /dev/null +++ b/src/content_object.h @@ -0,0 +1,30 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_OBJECT_HEADER +#define CONTENT_OBJECT_HEADER + +#define ACTIVEOBJECT_TYPE_TEST 1 +#define ACTIVEOBJECT_TYPE_ITEM 2 +#define ACTIVEOBJECT_TYPE_RAT 3 +#define ACTIVEOBJECT_TYPE_OERKKI1 4 +#define ACTIVEOBJECT_TYPE_FIREFLY 5 + +#endif + diff --git a/src/content_sao.cpp b/src/content_sao.cpp new file mode 100644 index 0000000..0bb518c --- /dev/null +++ b/src/content_sao.cpp @@ -0,0 +1,888 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "content_sao.h" +#include "collision.h" +#include "environment.h" + +core::map ServerActiveObject::m_types; + +/* + TestSAO +*/ + +// Prototype +TestSAO proto_TestSAO(NULL, 0, v3f(0,0,0)); + +TestSAO::TestSAO(ServerEnvironment *env, u16 id, v3f pos): + ServerActiveObject(env, id, pos), + m_timer1(0), + m_age(0) +{ + ServerActiveObject::registerType(getType(), create); +} + +ServerActiveObject* TestSAO::create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data) +{ + return new TestSAO(env, id, pos); +} + +void TestSAO::step(float dtime, bool send_recommended) +{ + m_age += dtime; + if(m_age > 10) + { + m_removed = true; + return; + } + + m_base_position.Y += dtime * BS * 2; + if(m_base_position.Y > 8*BS) + m_base_position.Y = 2*BS; + + if(send_recommended == false) + return; + + m_timer1 -= dtime; + if(m_timer1 < 0.0) + { + m_timer1 += 0.125; + //dstream<<"TestSAO: id="< box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.); + collisionMoveResult moveresult; + // Apply gravity + m_speed_f += v3f(0, -dtime*9.81*BS, 0); + // Maximum movement without glitches + f32 pos_max_d = BS*0.25; + // Limit speed + if(m_speed_f.getLength()*dtime > pos_max_d) + m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime); + v3f pos_f = getBasePosition(); + v3f pos_f_old = pos_f; + moveresult = collisionMoveSimple(&m_env->getMap(), pos_max_d, + box, dtime, pos_f, m_speed_f); + + if(send_recommended == false) + return; + + if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS) + { + setBasePosition(pos_f); + m_last_sent_position = pos_f; + + std::ostringstream os(std::ios::binary); + char buf[6]; + // command (0 = update position) + buf[0] = 0; + os.write(buf, 1); + // pos + writeS32((u8*)buf, m_base_position.X*1000); + os.write(buf, 4); + writeS32((u8*)buf, m_base_position.Y*1000); + os.write(buf, 4); + writeS32((u8*)buf, m_base_position.Z*1000); + os.write(buf, 4); + // create message and add to list + ActiveObjectMessage aom(getId(), false, os.str()); + m_messages_out.push_back(aom); + } +} + +std::string ItemSAO::getClientInitializationData() +{ + std::ostringstream os(std::ios::binary); + char buf[6]; + // version + buf[0] = 0; + os.write(buf, 1); + // pos + writeS32((u8*)buf, m_base_position.X*1000); + os.write(buf, 4); + writeS32((u8*)buf, m_base_position.Y*1000); + os.write(buf, 4); + writeS32((u8*)buf, m_base_position.Z*1000); + os.write(buf, 4); + // inventorystring + os< item="<use(m_env, player); + + if(to_be_deleted) + m_removed = true; + else + // Reflect changes to the item here + m_inventorystring = item->getItemString(); + + delete item; +} + +/* + RatSAO +*/ + +// Prototype +RatSAO proto_RatSAO(NULL, 0, v3f(0,0,0)); + +RatSAO::RatSAO(ServerEnvironment *env, u16 id, v3f pos): + ServerActiveObject(env, id, pos), + m_is_active(false), + m_speed_f(0,0,0) +{ + ServerActiveObject::registerType(getType(), create); + + m_oldpos = v3f(0,0,0); + m_last_sent_position = v3f(0,0,0); + m_yaw = myrand_range(0,PI*2); + m_counter1 = 0; + m_counter2 = 0; + m_age = 0; + m_touching_ground = false; +} + +ServerActiveObject* RatSAO::create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data) +{ + std::istringstream is(data, std::ios::binary); + char buf[1]; + // read version + is.read(buf, 1); + u8 version = buf[0]; + // check if version is supported + if(version != 0) + return NULL; + return new RatSAO(env, id, pos); +} + +void RatSAO::step(float dtime, bool send_recommended) +{ + assert(m_env); + + if(m_is_active == false) + { + if(m_inactive_interval.step(dtime, 0.5)==false) + return; + } + + /* + The AI + */ + + /*m_age += dtime; + if(m_age > 60) + { + // Die + m_removed = true; + return; + }*/ + + // Apply gravity + m_speed_f.Y -= dtime*9.81*BS; + + /* + Move around if some player is close + */ + bool player_is_close = false; + // Check connected players + core::list players = m_env->getPlayers(true); + core::list::Iterator i; + for(i = players.begin(); + i != players.end(); i++) + { + Player *player = *i; + v3f playerpos = player->getPosition(); + if(m_base_position.getDistanceFrom(playerpos) < BS*10.0) + { + player_is_close = true; + break; + } + } + + m_is_active = player_is_close; + + if(player_is_close == false) + { + m_speed_f.X = 0; + m_speed_f.Z = 0; + } + else + { + // Move around + v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI)); + f32 speed = 2*BS; + m_speed_f.X = speed * dir.X; + m_speed_f.Z = speed * dir.Z; + + if(m_touching_ground && (m_oldpos - m_base_position).getLength() + < dtime*speed/2) + { + m_counter1 -= dtime; + if(m_counter1 < 0.0) + { + m_counter1 += 1.0; + m_speed_f.Y = 5.0*BS; + } + } + + { + m_counter2 -= dtime; + if(m_counter2 < 0.0) + { + m_counter2 += (float)(myrand()%100)/100*3.0; + m_yaw += ((float)(myrand()%200)-100)/100*180; + m_yaw = wrapDegrees(m_yaw); + } + } + } + + m_oldpos = m_base_position; + + /* + Move it, with collision detection + */ + + core::aabbox3d box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.); + collisionMoveResult moveresult; + // Maximum movement without glitches + f32 pos_max_d = BS*0.25; + // Limit speed + if(m_speed_f.getLength()*dtime > pos_max_d) + m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime); + v3f pos_f = getBasePosition(); + v3f pos_f_old = pos_f; + moveresult = collisionMoveSimple(&m_env->getMap(), pos_max_d, + box, dtime, pos_f, m_speed_f); + m_touching_ground = moveresult.touching_ground; + + setBasePosition(pos_f); + + if(send_recommended == false) + return; + + if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS) + { + m_last_sent_position = pos_f; + + std::ostringstream os(std::ios::binary); + // command (0 = update position) + writeU8(os, 0); + // pos + writeV3F1000(os, m_base_position); + // yaw + writeF1000(os, m_yaw); + // create message and add to list + ActiveObjectMessage aom(getId(), false, os.str()); + m_messages_out.push_back(aom); + } +} + +std::string RatSAO::getClientInitializationData() +{ + std::ostringstream os(std::ios::binary); + // version + writeU8(os, 0); + // pos + writeV3F1000(os, m_base_position); + return os.str(); +} + +std::string RatSAO::getStaticData() +{ + //dstream<<__FUNCTION_NAME< max_increase) + dl = max_increase; + + v3f d = d_wanted.normalize() * dl; + + speed.X += d.X; + speed.Z += d.Z; + speed.Y = target_speed.Y; +} + +// Prototype +Oerkki1SAO proto_Oerkki1SAO(NULL, 0, v3f(0,0,0)); + +Oerkki1SAO::Oerkki1SAO(ServerEnvironment *env, u16 id, v3f pos): + ServerActiveObject(env, id, pos), + m_is_active(false), + m_speed_f(0,0,0) +{ + ServerActiveObject::registerType(getType(), create); + + m_oldpos = v3f(0,0,0); + m_last_sent_position = v3f(0,0,0); + m_yaw = 0; + m_counter1 = 0; + m_counter2 = 0; + m_age = 0; + m_touching_ground = false; + m_hp = 20; + m_after_jump_timer = 0; +} + +ServerActiveObject* Oerkki1SAO::create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data) +{ + std::istringstream is(data, std::ios::binary); + // read version + u8 version = readU8(is); + // read hp + u8 hp = readU8(is); + // check if version is supported + if(version != 0) + return NULL; + Oerkki1SAO *o = new Oerkki1SAO(env, id, pos); + o->m_hp = hp; + return o; +} + +void Oerkki1SAO::step(float dtime, bool send_recommended) +{ + assert(m_env); + + if(m_is_active == false) + { + if(m_inactive_interval.step(dtime, 0.5)==false) + return; + } + + /* + The AI + */ + + m_age += dtime; + if(m_age > 120) + { + // Die + m_removed = true; + return; + } + + m_after_jump_timer -= dtime; + + v3f old_speed = m_speed_f; + + // Apply gravity + m_speed_f.Y -= dtime*9.81*BS; + + /* + Move around if some player is close + */ + bool player_is_close = false; + bool player_is_too_close = false; + v3f near_player_pos; + // Check connected players + core::list players = m_env->getPlayers(true); + core::list::Iterator i; + for(i = players.begin(); + i != players.end(); i++) + { + Player *player = *i; + v3f playerpos = player->getPosition(); + f32 dist = m_base_position.getDistanceFrom(playerpos); + if(dist < BS*1.45) + { + player_is_too_close = true; + near_player_pos = playerpos; + break; + } + else if(dist < BS*15.0) + { + player_is_close = true; + near_player_pos = playerpos; + } + } + + m_is_active = player_is_close; + + v3f target_speed = m_speed_f; + + if(!player_is_close) + { + target_speed = v3f(0,0,0); + } + else + { + // Move around + + v3f ndir = near_player_pos - m_base_position; + ndir.Y = 0; + ndir.normalize(); + + f32 nyaw = 180./PI*atan2(ndir.Z,ndir.X); + if(nyaw < m_yaw - 180) + nyaw += 360; + else if(nyaw > m_yaw + 180) + nyaw -= 360; + m_yaw = 0.95*m_yaw + 0.05*nyaw; + m_yaw = wrapDegrees(m_yaw); + + f32 speed = 2*BS; + + if((m_touching_ground || m_after_jump_timer > 0.0) + && !player_is_too_close) + { + v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI)); + target_speed.X = speed * dir.X; + target_speed.Z = speed * dir.Z; + } + + if(m_touching_ground && (m_oldpos - m_base_position).getLength() + < dtime*speed/2) + { + m_counter1 -= dtime; + if(m_counter1 < 0.0) + { + m_counter1 += 0.2; + // Jump + target_speed.Y = 5.0*BS; + m_after_jump_timer = 1.0; + } + } + + { + m_counter2 -= dtime; + if(m_counter2 < 0.0) + { + m_counter2 += (float)(myrand()%100)/100*3.0; + //m_yaw += ((float)(myrand()%200)-100)/100*180; + m_yaw += ((float)(myrand()%200)-100)/100*90; + m_yaw = wrapDegrees(m_yaw); + } + } + } + + if((m_speed_f - target_speed).getLength() > BS*4 || player_is_too_close) + accelerate_xz(m_speed_f, target_speed, dtime*BS*8); + else + accelerate_xz(m_speed_f, target_speed, dtime*BS*4); + + m_oldpos = m_base_position; + + /* + Move it, with collision detection + */ + + core::aabbox3d box(-BS/3.,0.0,-BS/3., BS/3.,BS*5./3.,BS/3.); + collisionMoveResult moveresult; + // Maximum movement without glitches + f32 pos_max_d = BS*0.25; + /*// Limit speed + if(m_speed_f.getLength()*dtime > pos_max_d) + m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);*/ + v3f pos_f = getBasePosition(); + v3f pos_f_old = pos_f; + moveresult = collisionMovePrecise(&m_env->getMap(), pos_max_d, + box, dtime, pos_f, m_speed_f); + m_touching_ground = moveresult.touching_ground; + + // Do collision damage + float tolerance = BS*12; + float factor = BS*0.5; + v3f speed_diff = old_speed - m_speed_f; + // Increase effect in X and Z + speed_diff.X *= 2; + speed_diff.Z *= 2; + float vel = speed_diff.getLength(); + if(vel > tolerance) + { + f32 damage_f = (vel - tolerance)/BS*factor; + u16 damage = (u16)(damage_f+0.5); + doDamage(damage); + } + + setBasePosition(pos_f); + + if(send_recommended == false && m_speed_f.getLength() < 3.0*BS) + return; + + if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS) + { + m_last_sent_position = pos_f; + + std::ostringstream os(std::ios::binary); + // command (0 = update position) + writeU8(os, 0); + // pos + writeV3F1000(os, m_base_position); + // yaw + writeF1000(os, m_yaw); + // create message and add to list + ActiveObjectMessage aom(getId(), false, os.str()); + m_messages_out.push_back(aom); + } +} + +std::string Oerkki1SAO::getClientInitializationData() +{ + std::ostringstream os(std::ios::binary); + // version + writeU8(os, 0); + // pos + writeV3F1000(os, m_base_position); + return os.str(); +} + +std::string Oerkki1SAO::getStaticData() +{ + //dstream<<__FUNCTION_NAME< players = m_env->getPlayers(true); + core::list::Iterator i; + for(i = players.begin(); + i != players.end(); i++) + { + Player *player = *i; + v3f playerpos = player->getPosition(); + if(m_base_position.getDistanceFrom(playerpos) < BS*10.0) + { + player_is_close = true; + break; + } + } + + m_is_active = player_is_close; + + if(player_is_close == false) + { + m_speed_f.X = 0; + m_speed_f.Z = 0; + } + else + { + // Move around + v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI)); + f32 speed = BS/2; + m_speed_f.X = speed * dir.X; + m_speed_f.Z = speed * dir.Z; + + if(m_touching_ground && (m_oldpos - m_base_position).getLength() + < dtime*speed/2) + { + m_counter1 -= dtime; + if(m_counter1 < 0.0) + { + m_counter1 += 1.0; + m_speed_f.Y = 5.0*BS; + } + } + + { + m_counter2 -= dtime; + if(m_counter2 < 0.0) + { + m_counter2 += (float)(myrand()%100)/100*3.0; + m_yaw += ((float)(myrand()%200)-100)/100*180; + m_yaw = wrapDegrees(m_yaw); + } + } + } + + m_oldpos = m_base_position; + + /* + Move it, with collision detection + */ + + core::aabbox3d box(-BS/3.,-BS*2/3.0,-BS/3., BS/3.,BS*4./3.,BS/3.); + collisionMoveResult moveresult; + // Maximum movement without glitches + f32 pos_max_d = BS*0.25; + // Limit speed + if(m_speed_f.getLength()*dtime > pos_max_d) + m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime); + v3f pos_f = getBasePosition(); + v3f pos_f_old = pos_f; + moveresult = collisionMoveSimple(&m_env->getMap(), pos_max_d, + box, dtime, pos_f, m_speed_f); + m_touching_ground = moveresult.touching_ground; + + setBasePosition(pos_f); + + if(send_recommended == false) + return; + + if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS) + { + m_last_sent_position = pos_f; + + std::ostringstream os(std::ios::binary); + // command (0 = update position) + writeU8(os, 0); + // pos + writeV3F1000(os, m_base_position); + // yaw + writeF1000(os, m_yaw); + // create message and add to list + ActiveObjectMessage aom(getId(), false, os.str()); + m_messages_out.push_back(aom); + } +} + +std::string FireflySAO::getClientInitializationData() +{ + std::ostringstream os(std::ios::binary); + // version + writeU8(os, 0); + // pos + writeV3F1000(os, m_base_position); + return os.str(); +} + +std::string FireflySAO::getStaticData() +{ + //dstream<<__FUNCTION_NAME< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef CONTENT_SAO_HEADER +#define CONTENT_SAO_HEADER + +#include "serverobject.h" +#include "content_object.h" + +class TestSAO : public ServerActiveObject +{ +public: + TestSAO(ServerEnvironment *env, u16 id, v3f pos); + u8 getType() const + {return ACTIVEOBJECT_TYPE_TEST;} + static ServerActiveObject* create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + void step(float dtime, bool send_recommended); +private: + float m_timer1; + float m_age; +}; + +class ItemSAO : public ServerActiveObject +{ +public: + ItemSAO(ServerEnvironment *env, u16 id, v3f pos, + const std::string inventorystring); + u8 getType() const + {return ACTIVEOBJECT_TYPE_ITEM;} + static ServerActiveObject* create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + void step(float dtime, bool send_recommended); + std::string getClientInitializationData(); + std::string getStaticData(); + InventoryItem* createInventoryItem(); + InventoryItem* createPickedUpItem(){return createInventoryItem();} + void rightClick(Player *player); +private: + std::string m_inventorystring; + v3f m_speed_f; + v3f m_last_sent_position; + IntervalLimiter m_move_interval; +}; + +class RatSAO : public ServerActiveObject +{ +public: + RatSAO(ServerEnvironment *env, u16 id, v3f pos); + u8 getType() const + {return ACTIVEOBJECT_TYPE_RAT;} + static ServerActiveObject* create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + void step(float dtime, bool send_recommended); + std::string getClientInitializationData(); + std::string getStaticData(); + InventoryItem* createPickedUpItem(); +private: + bool m_is_active; + IntervalLimiter m_inactive_interval; + v3f m_speed_f; + v3f m_oldpos; + v3f m_last_sent_position; + float m_yaw; + float m_counter1; + float m_counter2; + float m_age; + bool m_touching_ground; +}; + +class Oerkki1SAO : public ServerActiveObject +{ +public: + Oerkki1SAO(ServerEnvironment *env, u16 id, v3f pos); + u8 getType() const + {return ACTIVEOBJECT_TYPE_OERKKI1;} + static ServerActiveObject* create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + void step(float dtime, bool send_recommended); + std::string getClientInitializationData(); + std::string getStaticData(); + InventoryItem* createPickedUpItem(){return NULL;} + u16 punch(const std::string &toolname, v3f dir); +private: + void doDamage(u16 d); + + bool m_is_active; + IntervalLimiter m_inactive_interval; + v3f m_speed_f; + v3f m_oldpos; + v3f m_last_sent_position; + float m_yaw; + float m_counter1; + float m_counter2; + float m_age; + bool m_touching_ground; + u8 m_hp; + float m_after_jump_timer; +}; + +class FireflySAO : public ServerActiveObject +{ +public: + FireflySAO(ServerEnvironment *env, u16 id, v3f pos); + u8 getType() const + {return ACTIVEOBJECT_TYPE_FIREFLY;} + static ServerActiveObject* create(ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + void step(float dtime, bool send_recommended); + std::string getClientInitializationData(); + std::string getStaticData(); + InventoryItem* createPickedUpItem(); +private: + bool m_is_active; + IntervalLimiter m_inactive_interval; + v3f m_speed_f; + v3f m_oldpos; + v3f m_last_sent_position; + float m_yaw; + float m_counter1; + float m_counter2; + float m_age; + bool m_touching_ground; +}; + +#endif + diff --git a/src/debug.cpp b/src/debug.cpp new file mode 100644 index 0000000..befd73a --- /dev/null +++ b/src/debug.cpp @@ -0,0 +1,231 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + + +#include "debug.h" +#include +#include + +/* + Debug output +*/ + +FILE *g_debugstreams[DEBUGSTREAM_COUNT] = {stderr, NULL}; + +void debugstreams_init(bool disable_stderr, const char *filename) +{ + if(disable_stderr) + g_debugstreams[0] = NULL; + else + g_debugstreams[0] = stderr; + + if(filename) + g_debugstreams[1] = fopen(filename, "a"); + + if(g_debugstreams[1]) + { + fprintf(g_debugstreams[1], "\n\n-------------\n"); + fprintf(g_debugstreams[1], " Separator \n"); + fprintf(g_debugstreams[1], "-------------\n\n"); + } + + DEBUGPRINT("Debug streams initialized, disable_stderr=%d\n", + disable_stderr); +} + +void debugstreams_deinit() +{ + if(g_debugstreams[1] != NULL) + fclose(g_debugstreams[1]); +} + +Debugbuf debugbuf(false); +std::ostream dstream(&debugbuf); +Debugbuf debugbuf_no_stderr(true); +std::ostream dstream_no_stderr(&debugbuf_no_stderr); +Nullstream dummyout; + +/* + Assert +*/ + +void assert_fail(const char *assertion, const char *file, + unsigned int line, const char *function) +{ + DEBUGPRINT("\nIn thread %lx:\n" + "%s:%d: %s: Assertion '%s' failed.\n", + (unsigned long)get_current_thread_id(), + file, line, function, assertion); + + debug_stacks_print(); + + if(g_debugstreams[1]) + fclose(g_debugstreams[1]); + + abort(); +} + +/* + DebugStack +*/ + +DebugStack::DebugStack(threadid_t id) +{ + threadid = id; + stack_i = 0; + stack_max_i = 0; + memset(stack, 0, DEBUG_STACK_SIZE*DEBUG_STACK_TEXT_SIZE); +} + +void DebugStack::print(FILE *file, bool everything) +{ + fprintf(file, "DEBUG STACK FOR THREAD %lx:\n", + (unsigned long)threadid); + + for(int i=0; i g_debug_stacks; +JMutex g_debug_stacks_mutex; + +void debug_stacks_init() +{ + g_debug_stacks_mutex.Init(); +} + +void debug_stacks_print() +{ + JMutexAutoLock lock(g_debug_stacks_mutex); + + DEBUGPRINT("Debug stacks:\n"); + + for(core::map::Iterator + i = g_debug_stacks.getIterator(); + i.atEnd() == false; i++) + { + DebugStack *stack = i.getNode()->getValue(); + + for(int i=0; iprint(g_debugstreams[i], true); + } + } +} + +DebugStacker::DebugStacker(const char *text) +{ + threadid_t threadid = get_current_thread_id(); + + JMutexAutoLock lock(g_debug_stacks_mutex); + + core::map::Node *n; + n = g_debug_stacks.find(threadid); + if(n != NULL) + { + m_stack = n->getValue(); + } + else + { + /*DEBUGPRINT("Creating new debug stack for thread %x\n", + (unsigned int)threadid);*/ + m_stack = new DebugStack(threadid); + g_debug_stacks.insert(threadid, m_stack); + } + + if(m_stack->stack_i >= DEBUG_STACK_SIZE) + { + m_overflowed = true; + } + else + { + m_overflowed = false; + + snprintf(m_stack->stack[m_stack->stack_i], + DEBUG_STACK_TEXT_SIZE, "%s", text); + m_stack->stack_i++; + if(m_stack->stack_i > m_stack->stack_max_i) + m_stack->stack_max_i = m_stack->stack_i; + } +} + +DebugStacker::~DebugStacker() +{ + JMutexAutoLock lock(g_debug_stacks_mutex); + + if(m_overflowed == true) + return; + + m_stack->stack_i--; + + if(m_stack->stack_i == 0) + { + threadid_t threadid = m_stack->threadid; + /*DEBUGPRINT("Deleting debug stack for thread %x\n", + (unsigned int)threadid);*/ + delete m_stack; + g_debug_stacks.remove(threadid); + } +} + + +#ifdef _MSC_VER +#if CATCH_UNHANDLED_EXCEPTIONS == 1 +void se_trans_func(unsigned int u, EXCEPTION_POINTERS* pExp) +{ + dstream<<"In trans_func.\n"; + if(u == EXCEPTION_ACCESS_VIOLATION) + { + PEXCEPTION_RECORD r = pExp->ExceptionRecord; + dstream<<"Access violation at "<ExceptionAddress + <<" write?="<ExceptionInformation[0] + <<" address="<ExceptionInformation[1] + < + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef DEBUG_HEADER +#define DEBUG_HEADER + +#include +#include +#include +#include +#include "common_irrlicht.h" +#include "threads.h" +#include "gettime.h" +#include "constants.h" +#include "exceptions.h" + +#ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN + #include + #ifdef _MSC_VER + #include + #endif +#else +#endif + +/* + Debug output +*/ + +#define DTIME (getTimestamp()+": ") + +#define DEBUGSTREAM_COUNT 2 + +extern FILE *g_debugstreams[DEBUGSTREAM_COUNT]; + +extern void debugstreams_init(bool disable_stderr, const char *filename); +extern void debugstreams_deinit(); + +#define DEBUGPRINT(...)\ +{\ + for(int i=0; i g_debug_stacks; +extern JMutex g_debug_stacks_mutex; + +extern void debug_stacks_init(); +extern void debug_stacks_print(); + +class DebugStacker +{ +public: + DebugStacker(const char *text); + ~DebugStacker(); + +private: + DebugStack *m_stack; + bool m_overflowed; +}; + +#define DSTACK(msg)\ + DebugStacker __debug_stacker(msg); + +#define DSTACKF(...)\ + char __buf[DEBUG_STACK_TEXT_SIZE];\ + snprintf(__buf,\ + DEBUG_STACK_TEXT_SIZE, __VA_ARGS__);\ + DebugStacker __debug_stacker(__buf); + +/* + Packet counter +*/ + +class PacketCounter +{ +public: + PacketCounter() + { + } + + void add(u16 command) + { + core::map::Node *n = m_packets.find(command); + if(n == NULL) + { + m_packets[command] = 1; + } + else + { + n->setValue(n->getValue()+1); + } + } + + void clear() + { + for(core::map::Iterator + i = m_packets.getIterator(); + i.atEnd() == false; i++) + { + i.getNode()->setValue(0); + } + } + + void print(std::ostream &o) + { + for(core::map::Iterator + i = m_packets.getIterator(); + i.atEnd() == false; i++) + { + o<<"cmd "<getKey() + <<" count "<getValue() + < m_packets; +}; + +/* + These should be put into every thread +*/ + +#if CATCH_UNHANDLED_EXCEPTIONS == 1 + #define BEGIN_PORTABLE_DEBUG_EXCEPTION_HANDLER try{ + #define END_PORTABLE_DEBUG_EXCEPTION_HANDLER\ + }catch(std::exception &e){\ + dstream< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "utility.h" + +extern Settings g_settings; + +void set_default_settings() +{ + // Client and server + + g_settings.setDefault("port", ""); + g_settings.setDefault("name", ""); + g_settings.setDefault("footprints", "false"); + + // Client stuff + + g_settings.setDefault("keymap_forward", "KEY_KEY_W"); + g_settings.setDefault("keymap_backward", "KEY_KEY_S"); + g_settings.setDefault("keymap_left", "KEY_KEY_A"); + g_settings.setDefault("keymap_right", "KEY_KEY_D"); + g_settings.setDefault("keymap_jump", "KEY_SPACE"); + g_settings.setDefault("keymap_sneak", "KEY_LSHIFT"); + g_settings.setDefault("keymap_inventory", "KEY_KEY_I"); + g_settings.setDefault("keymap_chat", "KEY_KEY_T"); + g_settings.setDefault("keymap_cmd", "/"); + g_settings.setDefault("keymap_rangeselect", "KEY_KEY_R"); + g_settings.setDefault("keymap_freemove", "KEY_KEY_K"); + g_settings.setDefault("keymap_fastmove", "KEY_KEY_J"); + g_settings.setDefault("keymap_frametime_graph", "KEY_F1"); + g_settings.setDefault("keymap_screenshot", "KEY_F12"); + // Some (temporary) keys for debugging + g_settings.setDefault("keymap_special1", "KEY_KEY_E"); + g_settings.setDefault("keymap_print_debug_stacks", "KEY_KEY_P"); + + g_settings.setDefault("wanted_fps", "30"); + g_settings.setDefault("fps_max", "60"); + g_settings.setDefault("viewing_range_nodes_max", "300"); + g_settings.setDefault("viewing_range_nodes_min", "15"); + g_settings.setDefault("screenW", "800"); + g_settings.setDefault("screenH", "600"); + g_settings.setDefault("address", ""); + g_settings.setDefault("random_input", "false"); + g_settings.setDefault("client_unload_unused_data_timeout", "600"); + g_settings.setDefault("enable_fog", "true"); + g_settings.setDefault("new_style_water", "false"); + g_settings.setDefault("new_style_leaves", "true"); + g_settings.setDefault("smooth_lighting", "true"); + g_settings.setDefault("frametime_graph", "false"); + g_settings.setDefault("enable_texture_atlas", "true"); + g_settings.setDefault("texture_path", ""); + g_settings.setDefault("video_driver", "opengl"); + g_settings.setDefault("free_move", "false"); + g_settings.setDefault("continuous_forward", "false"); + g_settings.setDefault("fast_move", "false"); + g_settings.setDefault("invert_mouse", "false"); + g_settings.setDefault("enable_farmesh", "false"); + g_settings.setDefault("enable_clouds", "true"); + g_settings.setDefault("invisible_stone", "false"); + g_settings.setDefault("screenshot_path", "."); + + // Server stuff + g_settings.setDefault("motd", ""); + g_settings.setDefault("enable_experimental", "false"); + g_settings.setDefault("creative_mode", "false"); + g_settings.setDefault("enable_damage", "true"); + g_settings.setDefault("give_initial_stuff", "false"); + g_settings.setDefault("default_password", ""); + g_settings.setDefault("default_privs", "build, shout"); + g_settings.setDefault("profiler_print_interval", "0"); + g_settings.setDefault("enable_mapgen_debug_info", "false"); + g_settings.setDefault("fixed_map_seed", ""); + + g_settings.setDefault("objectdata_interval", "0.2"); + g_settings.setDefault("active_object_range", "2"); + //g_settings.setDefault("max_simultaneous_block_sends_per_client", "1"); + // This causes frametime jitter on client side, or does it? + g_settings.setDefault("max_simultaneous_block_sends_per_client", "2"); + g_settings.setDefault("max_simultaneous_block_sends_server_total", "8"); + g_settings.setDefault("max_block_send_distance", "8"); + g_settings.setDefault("max_block_generate_distance", "8"); + g_settings.setDefault("time_send_interval", "20"); + g_settings.setDefault("time_speed", "96"); + g_settings.setDefault("server_unload_unused_data_timeout", "60"); + g_settings.setDefault("server_map_save_interval", "60"); + g_settings.setDefault("full_block_send_enable_min_time_from_building", "2.0"); + //g_settings.setDefault("dungeon_rarity", "0.025"); +} + diff --git a/src/environment.cpp b/src/environment.cpp new file mode 100644 index 0000000..8103b71 --- /dev/null +++ b/src/environment.cpp @@ -0,0 +1,1968 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "environment.h" +#include "filesys.h" +#include "porting.h" +#include "collision.h" +#include "content_mapnode.h" +#include "mapblock.h" +#include "serverobject.h" +#include "content_sao.h" + +Environment::Environment(): + m_time_of_day(9000) +{ +} + +Environment::~Environment() +{ + // Deallocate players + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + delete (*i); + } +} + +void Environment::addPlayer(Player *player) +{ + DSTACK(__FUNCTION_NAME); + /* + Check that peer_ids are unique. + Also check that names are unique. + Exception: there can be multiple players with peer_id=0 + */ + // If peer id is non-zero, it has to be unique. + if(player->peer_id != 0) + assert(getPlayer(player->peer_id) == NULL); + // Name has to be unique. + assert(getPlayer(player->getName()) == NULL); + // Add. + m_players.push_back(player); +} + +void Environment::removePlayer(u16 peer_id) +{ + DSTACK(__FUNCTION_NAME); +re_search: + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + if(player->peer_id != peer_id) + continue; + + delete player; + m_players.erase(i); + // See if there is an another one + // (shouldn't be, but just to be sure) + goto re_search; + } +} + +Player * Environment::getPlayer(u16 peer_id) +{ + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + if(player->peer_id == peer_id) + return player; + } + return NULL; +} + +Player * Environment::getPlayer(const char *name) +{ + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + if(strcmp(player->getName(), name) == 0) + return player; + } + return NULL; +} + +Player * Environment::getRandomConnectedPlayer() +{ + core::list connected_players = getPlayers(true); + u32 chosen_one = myrand() % connected_players.size(); + u32 j = 0; + for(core::list::Iterator + i = connected_players.begin(); + i != connected_players.end(); i++) + { + if(j == chosen_one) + { + Player *player = *i; + return player; + } + j++; + } + return NULL; +} + +Player * Environment::getNearestConnectedPlayer(v3f pos) +{ + core::list connected_players = getPlayers(true); + f32 nearest_d = 0; + Player *nearest_player = NULL; + for(core::list::Iterator + i = connected_players.begin(); + i != connected_players.end(); i++) + { + Player *player = *i; + f32 d = player->getPosition().getDistanceFrom(pos); + if(d < nearest_d || nearest_player == NULL) + { + nearest_d = d; + nearest_player = player; + } + } + return nearest_player; +} + +core::list Environment::getPlayers() +{ + return m_players; +} + +core::list Environment::getPlayers(bool ignore_disconnected) +{ + core::list newlist; + for(core::list::Iterator + i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + + if(ignore_disconnected) + { + // Ignore disconnected players + if(player->peer_id == 0) + continue; + } + + newlist.push_back(player); + } + return newlist; +} + +void Environment::printPlayers(std::ostream &o) +{ + o<<"Players in environment:"<::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + o<<"Player peer_id="<peer_id< &list) +{ + v3s16 p; + for(p.X=p0.X-r; p.X<=p0.X+r; p.X++) + for(p.Y=p0.Y-r; p.Y<=p0.Y+r; p.Y++) + for(p.Z=p0.Z-r; p.Z<=p0.Z+r; p.Z++) + { + // Set in list + list[p] = true; + } +} + +void ActiveBlockList::update(core::list &active_positions, + s16 radius, + core::map &blocks_removed, + core::map &blocks_added) +{ + /* + Create the new list + */ + core::map newlist; + for(core::list::Iterator i = active_positions.begin(); + i != active_positions.end(); i++) + { + fillRadiusBlock(*i, radius, newlist); + } + + /* + Find out which blocks on the old list are not on the new list + */ + // Go through old list + for(core::map::Iterator i = m_list.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + // If not on new list, it's been removed + if(newlist.find(p) == NULL) + blocks_removed.insert(p, true); + } + + /* + Find out which blocks on the new list are not on the old list + */ + // Go through new list + for(core::map::Iterator i = newlist.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + // If not on old list, it's been added + if(m_list.find(p) == NULL) + blocks_added.insert(p, true); + } + + /* + Update m_list + */ + m_list.clear(); + for(core::map::Iterator i = newlist.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + m_list.insert(p, true); + } +} + +/* + ServerEnvironment +*/ + +ServerEnvironment::ServerEnvironment(ServerMap *map, Server *server): + m_map(map), + m_server(server), + m_random_spawn_timer(3), + m_send_recommended_timer(0), + m_game_time(0), + m_game_time_fraction_counter(0) +{ +} + +ServerEnvironment::~ServerEnvironment() +{ + // Clear active block list. + // This makes the next one delete all active objects. + m_active_blocks.clear(); + + // Convert all objects to static and delete the active objects + deactivateFarObjects(true); + + // Drop/delete map + m_map->drop(); +} + +void ServerEnvironment::serializePlayers(const std::string &savedir) +{ + std::string players_path = savedir + "/players"; + fs::CreateDir(players_path); + + core::map saved_players; + + std::vector player_files = fs::GetDirListing(players_path); + for(u32 i=0; iserialize(os); + saved_players.insert(player, true); + } + } + + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + if(saved_players.find(player) != NULL) + { + /*dstream<<"Player "<getName() + <<" was already saved."<getName(); + // Don't save unnamed player + if(playername == "") + { + //dstream<<"Not saving unnamed player."<getName()<<" to " + <serialize(os); + saved_players.insert(player, true); + } + } + + //dstream<<"Saved "< saved_players; + + std::vector player_files = fs::GetDirListing(players_path); + for(u32 i=0; ideSerialize(is); + } + + if(newplayer) + addPlayer(player); + } +} + +void ServerEnvironment::saveMeta(const std::string &savedir) +{ + std::string path = savedir + "/env_meta.txt"; + + // Open file and serialize + std::ofstream os(path.c_str(), std::ios_base::binary); + if(os.good() == false) + { + dstream<<"WARNING: ServerEnvironment::saveMeta(): Failed to open " + <getNodeNoEx(p); + if(n.getContent() == CONTENT_IGNORE) + continue; + if(content_features(n).liquid_type != LIQUID_NONE) + continue; + if(content_features(n).walkable) + { + last_node_walkable = true; + continue; + } + if(last_node_walkable) + { + // If block contains light information + if(content_features(n).param_type == CPT_LIGHT) + { + if(n.getLight(LIGHTBANK_DAY) <= 5) + { + if(myrand() % 1000 == 0) + { + v3f pos_f = intToFloat(p+block->getPosRelative(), BS); + pos_f.Y -= BS*0.4; + ServerActiveObject *obj = new Oerkki1SAO(NULL,0,pos_f); + std::string data = obj->getStaticData(); + StaticObject s_obj(obj->getType(), + obj->getBasePosition(), data); + // Add one + block->m_static_objects.insert(0, s_obj); + delete obj; + block->setChangedFlag(); + } + } + } + } + last_node_walkable = false; + } + } +} +#endif + +void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime) +{ + // Get time difference + u32 dtime_s = 0; + u32 stamp = block->getTimestamp(); + if(m_game_time > stamp && stamp != BLOCK_TIMESTAMP_UNDEFINED) + dtime_s = m_game_time - block->getTimestamp(); + dtime_s += additional_dtime; + + // Set current time as timestamp (and let it set ChangedFlag) + block->setTimestamp(m_game_time); + + //dstream<<"Block is "<m_node_metadata.step((float)dtime_s); + if(changed) + { + MapEditEvent event; + event.type = MEET_BLOCK_NODE_METADATA_CHANGED; + event.p = block->getPos(); + m_map->dispatchEvent(&event); + + block->setChangedFlag(); + } + + // TODO: Do something + // TODO: Implement usage of ActiveBlockModifier + + // Here's a quick demonstration + v3s16 p0; + for(p0.X=0; p0.XgetPosRelative(); + MapNode n = block->getNodeNoEx(p0); +#if 1 + // Test something: + // Convert all mud under proper day lighting to grass + if(n.getContent() == CONTENT_MUD) + { + if(dtime_s > 300) + { + MapNode n_top = block->getNodeNoEx(p0+v3s16(0,1,0)); + if(content_features(n_top).air_equivalent && + n_top.getLight(LIGHTBANK_DAY) >= 13) + { + n.setContent(CONTENT_GRASS); + m_map->addNodeWithEvent(p, n); + } + } + } +#endif + } +} + +void ServerEnvironment::step(float dtime) +{ + DSTACK(__FUNCTION_NAME); + + //TimeTaker timer("ServerEnv step"); + + // Get some settings + bool footprints = g_settings.getBool("footprints"); + + /* + Increment game time + */ + { + m_game_time_fraction_counter += dtime; + u32 inc_i = (u32)m_game_time_fraction_counter; + m_game_time += inc_i; + m_game_time_fraction_counter -= (float)inc_i; + } + + /* + Handle players + */ + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + + // Ignore disconnected players + if(player->peer_id == 0) + continue; + + v3f playerpos = player->getPosition(); + + // Move + player->move(dtime, *m_map, 100*BS); + + /* + Add footsteps to grass + */ + if(footprints) + { + // Get node that is at BS/4 under player + v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS); + try{ + MapNode n = m_map->getNode(bottompos); + if(n.getContent() == CONTENT_GRASS) + { + n.setContent(CONTENT_GRASS_FOOTSTEPS); + m_map->setNode(bottompos, n); + } + } + catch(InvalidPositionException &e) + { + } + } + } + + /* + Manage active block list + */ + if(m_active_blocks_management_interval.step(dtime, 2.0)) + { + /* + Get player block positions + */ + core::list players_blockpos; + for(core::list::Iterator + i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + // Ignore disconnected players + if(player->peer_id == 0) + continue; + v3s16 blockpos = getNodeBlockPos( + floatToInt(player->getPosition(), BS)); + players_blockpos.push_back(blockpos); + } + + /* + Update list of active blocks, collecting changes + */ + const s16 active_block_range = 5; + core::map blocks_removed; + core::map blocks_added; + m_active_blocks.update(players_blockpos, active_block_range, + blocks_removed, blocks_added); + + /* + Handle removed blocks + */ + + // Convert active objects that are no more in active blocks to static + deactivateFarObjects(false); + + for(core::map::Iterator + i = blocks_removed.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + + /*dstream<<"Server: Block ("<getBlockNoCreateNoEx(p); + if(block==NULL) + continue; + + // Set current time as timestamp (and let it set ChangedFlag) + block->setTimestamp(m_game_time); + } + + /* + Handle added blocks + */ + + for(core::map::Iterator + i = blocks_added.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + + /*dstream<<"Server: Block ("<getBlockNoCreateNoEx(p); + if(block==NULL) + continue; + + activateBlock(block); + } + } + + /* + Mess around in active blocks + */ + if(m_active_blocks_nodemetadata_interval.step(dtime, 1.0)) + { + float dtime = 1.0; + + for(core::map::Iterator + i = m_active_blocks.m_list.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + + /*dstream<<"Server: Block ("<getBlockNoCreateNoEx(p); + if(block==NULL) + continue; + + // Reset block usage timer + block->resetUsageTimer(); + + // Set current time as timestamp + block->setTimestampNoChangedFlag(m_game_time); + + // Run node metadata + bool changed = block->m_node_metadata.step(dtime); + if(changed) + { + MapEditEvent event; + event.type = MEET_BLOCK_NODE_METADATA_CHANGED; + event.p = p; + m_map->dispatchEvent(&event); + + block->setChangedFlag(); + } + } + } + if(m_active_blocks_test_interval.step(dtime, 10.0)) + { + //float dtime = 10.0; + + for(core::map::Iterator + i = m_active_blocks.m_list.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + + /*dstream<<"Server: Block ("<getBlockNoCreateNoEx(p); + if(block==NULL) + continue; + + // Set current time as timestamp + block->setTimestampNoChangedFlag(m_game_time); + + /* + Do stuff! + + Note that map modifications should be done using the event- + making map methods so that the server gets information + about them. + + Reading can be done quickly directly from the block. + + Everything should bind to inside this single content + searching loop to keep things fast. + */ + // TODO: Implement usage of ActiveBlockModifier + + // Find out how many objects the block contains + u32 active_object_count = block->m_static_objects.m_active.size(); + // Find out how many objects this and all the neighbors contain + u32 active_object_count_wider = 0; + for(s16 x=-1; x<=1; x++) + for(s16 y=-1; y<=1; y++) + for(s16 z=-1; z<=1; z++) + { + MapBlock *block = m_map->getBlockNoCreateNoEx(p+v3s16(x,y,z)); + if(block==NULL) + continue; + active_object_count_wider += + block->m_static_objects.m_active.size(); + } + + v3s16 p0; + for(p0.X=0; p0.XgetPosRelative(); + MapNode n = block->getNodeNoEx(p0); + + /* + Test something: + Convert mud under proper lighting to grass + */ + if(n.getContent() == CONTENT_MUD) + { + if(myrand()%20 == 0) + { + MapNode n_top = m_map->getNodeNoEx(p+v3s16(0,1,0)); + if(content_features(n_top).air_equivalent && + n_top.getLightBlend(getDayNightRatio()) >= 13) + { + n.setContent(CONTENT_GRASS); + m_map->addNodeWithEvent(p, n); + } + } + } + /* + Convert grass into mud if under something else than air + */ + if(n.getContent() == CONTENT_GRASS) + { + //if(myrand()%20 == 0) + { + MapNode n_top = m_map->getNodeNoEx(p+v3s16(0,1,0)); + if(content_features(n_top).air_equivalent == false) + { + n.setContent(CONTENT_MUD); + m_map->addNodeWithEvent(p, n); + } + } + } + /* + Rats spawn around regular trees + */ + if(n.getContent() == CONTENT_TREE || + n.getContent() == CONTENT_JUNGLETREE) + { + if(myrand()%200 == 0 && active_object_count_wider == 0) + { + v3s16 p1 = p + v3s16(myrand_range(-2, 2), + 0, myrand_range(-2, 2)); + MapNode n1 = m_map->getNodeNoEx(p1); + MapNode n1b = m_map->getNodeNoEx(p1+v3s16(0,-1,0)); + if(n1b.getContent() == CONTENT_GRASS && + n1.getContent() == CONTENT_AIR) + { + v3f pos = intToFloat(p1, BS); + ServerActiveObject *obj = new RatSAO(this, 0, pos); + addActiveObject(obj); + } + } + } + } + } + } + + /* + Step active objects + */ + { + //TimeTaker timer("Step active objects"); + + // This helps the objects to send data at the same time + bool send_recommended = false; + m_send_recommended_timer += dtime; + if(m_send_recommended_timer > 0.15) + { + m_send_recommended_timer = 0; + send_recommended = true; + } + + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + ServerActiveObject* obj = i.getNode()->getValue(); + // Don't step if is to be removed or stored statically + if(obj->m_removed || obj->m_pending_deactivation) + continue; + // Step object + obj->step(dtime, send_recommended); + // Read messages from object + while(obj->m_messages_out.size() > 0) + { + m_active_object_messages.push_back( + obj->m_messages_out.pop_front()); + } + } + } + + /* + Manage active objects + */ + if(m_object_management_interval.step(dtime, 0.5)) + { + /* + Remove objects that satisfy (m_removed && m_known_by_count==0) + */ + removeRemovedObjects(); + } + + if(g_settings.getBool("enable_experimental")) + { + + /* + TEST CODE + */ +#if 1 + m_random_spawn_timer -= dtime; + if(m_random_spawn_timer < 0) + { + //m_random_spawn_timer += myrand_range(2.0, 20.0); + //m_random_spawn_timer += 2.0; + m_random_spawn_timer += 200.0; + + /* + Find some position + */ + + /*v2s16 p2d(myrand_range(-5,5), myrand_range(-5,5)); + s16 y = 1 + getServerMap().findGroundLevel(p2d); + v3f pos(p2d.X*BS,y*BS,p2d.Y*BS);*/ + + Player *player = getRandomConnectedPlayer(); + v3f pos(0,0,0); + if(player) + pos = player->getPosition(); + pos += v3f( + myrand_range(-3,3)*BS, + 0, + myrand_range(-3,3)*BS + ); + + /* + Create a ServerActiveObject + */ + + //TestSAO *obj = new TestSAO(this, 0, pos); + //ServerActiveObject *obj = new ItemSAO(this, 0, pos, "CraftItem Stick 1"); + //ServerActiveObject *obj = new RatSAO(this, 0, pos); + //ServerActiveObject *obj = new Oerkki1SAO(this, 0, pos); + ServerActiveObject *obj = new FireflySAO(this, 0, pos); + addActiveObject(obj); + } +#endif + + } // enable_experimental +} + +ServerActiveObject* ServerEnvironment::getActiveObject(u16 id) +{ + core::map::Node *n; + n = m_active_objects.find(id); + if(n == NULL) + return NULL; + return n->getValue(); +} + +bool isFreeServerActiveObjectId(u16 id, + core::map &objects) +{ + if(id == 0) + return false; + + for(core::map::Iterator + i = objects.getIterator(); + i.atEnd()==false; i++) + { + if(i.getNode()->getKey() == id) + return false; + } + return true; +} + +u16 getFreeServerActiveObjectId( + core::map &objects) +{ + u16 new_id = 1; + for(;;) + { + if(isFreeServerActiveObjectId(new_id, objects)) + return new_id; + + if(new_id == 65535) + return 0; + + new_id++; + } +} + +u16 ServerEnvironment::addActiveObject(ServerActiveObject *object) +{ + assert(object); + u16 id = addActiveObjectRaw(object, true); + return id; +} + +/* + Finds out what new objects have been added to + inside a radius around a position +*/ +void ServerEnvironment::getAddedActiveObjects(v3s16 pos, s16 radius, + core::map ¤t_objects, + core::map &added_objects) +{ + v3f pos_f = intToFloat(pos, BS); + f32 radius_f = radius * BS; + /* + Go through the object list, + - discard m_removed objects, + - discard objects that are too far away, + - discard objects that are found in current_objects. + - add remaining objects to added_objects + */ + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + u16 id = i.getNode()->getKey(); + // Get object + ServerActiveObject *object = i.getNode()->getValue(); + if(object == NULL) + continue; + // Discard if removed + if(object->m_removed) + continue; + // Discard if too far + f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f); + if(distance_f > radius_f) + continue; + // Discard if already on current_objects + core::map::Node *n; + n = current_objects.find(id); + if(n != NULL) + continue; + // Add to added_objects + added_objects.insert(id, false); + } +} + +/* + Finds out what objects have been removed from + inside a radius around a position +*/ +void ServerEnvironment::getRemovedActiveObjects(v3s16 pos, s16 radius, + core::map ¤t_objects, + core::map &removed_objects) +{ + v3f pos_f = intToFloat(pos, BS); + f32 radius_f = radius * BS; + /* + Go through current_objects; object is removed if: + - object is not found in m_active_objects (this is actually an + error condition; objects should be set m_removed=true and removed + only after all clients have been informed about removal), or + - object has m_removed=true, or + - object is too far away + */ + for(core::map::Iterator + i = current_objects.getIterator(); + i.atEnd()==false; i++) + { + u16 id = i.getNode()->getKey(); + ServerActiveObject *object = getActiveObject(id); + if(object == NULL) + { + dstream<<"WARNING: ServerEnvironment::getRemovedActiveObjects():" + <<" object in current_objects is NULL"<m_removed == false) + { + f32 distance_f = object->getBasePosition().getDistanceFrom(pos_f); + /*dstream<<"removed == false" + <<"distance_f = "<setId(new_id); + } + if(isFreeServerActiveObjectId(object->getId(), m_active_objects) == false) + { + dstream<<"WARNING: ServerEnvironment::addActiveObjectRaw(): " + <<"id is not free ("<getId()<<")"<getId(), object); + + // Add static object to active static list of the block + v3f objectpos = object->getBasePosition(); + std::string staticdata = object->getStaticData(); + StaticObject s_obj(object->getType(), objectpos, staticdata); + // Add to the block where the object is located in + v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS)); + MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos); + if(block) + { + block->m_static_objects.m_active.insert(object->getId(), s_obj); + object->m_static_exists = true; + object->m_static_block = blockpos; + + if(set_changed) + block->setChangedFlag(); + } + else{ + dstream<<"WARNING: ServerEnv: Could not find a block for " + <<"storing newly added static active object"<getId(); +} + +/* + Remove objects that satisfy (m_removed && m_known_by_count==0) +*/ +void ServerEnvironment::removeRemovedObjects() +{ + core::list objects_to_remove; + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + u16 id = i.getNode()->getKey(); + ServerActiveObject* obj = i.getNode()->getValue(); + // This shouldn't happen but check it + if(obj == NULL) + { + dstream<<"WARNING: NULL object found in ServerEnvironment" + <<" while finding removed objects. id="<m_removed == false && obj->m_pending_deactivation == false) + continue; + + /* + Delete static data from block if is marked as removed + */ + if(obj->m_static_exists && obj->m_removed) + { + MapBlock *block = m_map->getBlockNoCreateNoEx(obj->m_static_block); + if(block) + { + block->m_static_objects.remove(id); + block->setChangedFlag(); + } + } + + // If m_known_by_count > 0, don't actually remove. + if(obj->m_known_by_count > 0) + continue; + + // Delete + delete obj; + // Id to be removed from m_active_objects + objects_to_remove.push_back(id); + } + // Remove references from m_active_objects + for(core::list::Iterator i = objects_to_remove.begin(); + i != objects_to_remove.end(); i++) + { + m_active_objects.remove(*i); + } +} + +/* + Convert stored objects from blocks near the players to active. +*/ +void ServerEnvironment::activateObjects(MapBlock *block) +{ + if(block==NULL) + return; + // Ignore if no stored objects (to not set changed flag) + if(block->m_static_objects.m_stored.size() == 0) + return; + // A list for objects that couldn't be converted to static for some + // reason. They will be stored back. + core::list new_stored; + // Loop through stored static objects + for(core::list::Iterator + i = block->m_static_objects.m_stored.begin(); + i != block->m_static_objects.m_stored.end(); i++) + { + /*dstream<<"INFO: Server: Creating an active object from " + <<"static data"<m_static_objects.m_stored.clear(); + // Add leftover failed stuff to stored list + for(core::list::Iterator + i = new_stored.begin(); + i != new_stored.end(); i++) + { + StaticObject &s_obj = *i; + block->m_static_objects.m_stored.push_back(s_obj); + } + // Block has been modified + // NOTE: No it has not really. Save I/O here. + //block->setChangedFlag(); +} + +/* + Convert objects that are not in active blocks to static. + + If m_known_by_count != 0, active object is not deleted, but static + data is still updated. + + If force_delete is set, active object is deleted nevertheless. It + shall only be set so in the destructor of the environment. +*/ +void ServerEnvironment::deactivateFarObjects(bool force_delete) +{ + core::list objects_to_remove; + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + ServerActiveObject* obj = i.getNode()->getValue(); + u16 id = i.getNode()->getKey(); + v3f objectpos = obj->getBasePosition(); + + // This shouldn't happen but check it + if(obj == NULL) + { + dstream<<"WARNING: NULL object found in ServerEnvironment" + <m_static_exists) + { + MapBlock *block = m_map->getBlockNoCreateNoEx + (obj->m_static_block); + if(block) + { + block->m_static_objects.remove(id); + oldblock = block; + } + } + // Create new static object + std::string staticdata = obj->getStaticData(); + StaticObject s_obj(obj->getType(), objectpos, staticdata); + // Add to the block where the object is located in + v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS)); + // Get or generate the block + MapBlock *block = m_map->emergeBlock(blockpos); + + /*MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos); + if(block == NULL) + { + // Block not found. Is the old block still ok? + if(oldblock) + block = oldblock; + // Load from disk or generate + else + block = m_map->emergeBlock(blockpos); + }*/ + + if(block) + { + block->m_static_objects.insert(0, s_obj); + block->setChangedFlag(); + obj->m_static_exists = true; + obj->m_static_block = block->getPos(); + } + else{ + dstream<<"WARNING: ServerEnv: Could not find or generate " + <<"a block for storing static object"<m_static_exists = false; + continue; + } + + /* + Delete active object if not known by some client, + else set pending deactivation + */ + + // If known by some client, don't delete. + if(obj->m_known_by_count > 0 && force_delete == false) + { + obj->m_pending_deactivation = true; + continue; + } + + /*dstream<<"INFO: Server: Stored static data. Deleting object." + <::Iterator i = objects_to_remove.begin(); + i != objects_to_remove.end(); i++) + { + m_active_objects.remove(*i); + } +} + + +#ifndef SERVER + +/* + ClientEnvironment +*/ + +ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr): + m_map(map), + m_smgr(smgr) +{ + assert(m_map); + assert(m_smgr); +} + +ClientEnvironment::~ClientEnvironment() +{ + // delete active objects + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + delete i.getNode()->getValue(); + } + + // Drop/delete map + m_map->drop(); +} + +void ClientEnvironment::addPlayer(Player *player) +{ + DSTACK(__FUNCTION_NAME); + /* + It is a failure if player is local and there already is a local + player + */ + assert(!(player->isLocal() == true && getLocalPlayer() != NULL)); + + Environment::addPlayer(player); +} + +LocalPlayer * ClientEnvironment::getLocalPlayer() +{ + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + if(player->isLocal()) + return (LocalPlayer*)player; + } + return NULL; +} + +void ClientEnvironment::step(float dtime) +{ + DSTACK(__FUNCTION_NAME); + + // Get some settings + bool free_move = g_settings.getBool("free_move"); + bool footprints = g_settings.getBool("footprints"); + + // Get local player + LocalPlayer *lplayer = getLocalPlayer(); + assert(lplayer); + // collision info queue + core::list player_collisions; + + /* + Get the speed the player is going + */ + bool is_climbing = lplayer->is_climbing; + + /* + Check if the player is frozen (don't apply physics) + */ + bool is_frozen = lplayer->is_frozen; + + f32 player_speed = 0.001; // just some small value + player_speed = lplayer->getSpeed().getLength(); + + /* + Maximum position increment + */ + //f32 position_max_increment = 0.05*BS; + f32 position_max_increment = 0.1*BS; + + // Maximum time increment (for collision detection etc) + // time = distance / speed + f32 dtime_max_increment = position_max_increment / player_speed; + + // Maximum time increment is 10ms or lower + if(dtime_max_increment > 0.01) + dtime_max_increment = 0.01; + + // Don't allow overly huge dtime + if(dtime > 0.5) + dtime = 0.5; + + f32 dtime_downcount = dtime; + + /* + Stuff that has a maximum time increment + */ + + u32 loopcount = 0; + do + { + loopcount++; + + f32 dtime_part; + if(dtime_downcount > dtime_max_increment) + { + dtime_part = dtime_max_increment; + dtime_downcount -= dtime_part; + } + else + { + dtime_part = dtime_downcount; + /* + Setting this to 0 (no -=dtime_part) disables an infinite loop + when dtime_part is so small that dtime_downcount -= dtime_part + does nothing + */ + dtime_downcount = 0; + } + + /* + Handle local player + */ + + { + v3f lplayerpos = lplayer->getPosition(); + + // Apply physics + if(free_move == false && is_climbing == false && is_frozen == false) + { + // Gravity + v3f speed = lplayer->getSpeed(); + if(lplayer->swimming_up == false) + speed.Y -= 9.81 * BS * dtime_part * 2; + + // Water resistance + if(lplayer->in_water_stable || lplayer->in_water) + { + f32 max_down = 2.0*BS; + if(speed.Y < -max_down) speed.Y = -max_down; + + f32 max = 2.5*BS; + if(speed.getLength() > max) + { + speed = speed / speed.getLength() * max; + } + } + + lplayer->setSpeed(speed); + } + + /* + Move the lplayer. + This also does collision detection. + */ + lplayer->move(dtime_part, *m_map, position_max_increment, + &player_collisions); + } + } + while(dtime_downcount > 0.001); + + //std::cout<<"Looped "<::Iterator + i = player_collisions.begin(); + i != player_collisions.end(); i++) + { + CollisionInfo &info = *i; + if(info.t == COLLISION_FALL) + { + //f32 tolerance = BS*10; // 2 without damage + f32 tolerance = BS*12; // 3 without damage + f32 factor = 1; + if(info.speed > tolerance) + { + f32 damage_f = (info.speed - tolerance)/BS*factor; + u16 damage = (u16)(damage_f+0.5); + if(lplayer->hp > damage) + lplayer->hp -= damage; + else + lplayer->hp = 0; + + ClientEnvEvent event; + event.type = CEE_PLAYER_DAMAGE; + event.player_damage.amount = damage; + m_client_event_queue.push_back(event); + } + } + } + + /* + A quick draft of lava damage + */ + if(m_lava_hurt_interval.step(dtime, 1.0)) + { + v3f pf = lplayer->getPosition(); + + // Feet, middle and head + v3s16 p1 = floatToInt(pf + v3f(0, BS*0.1, 0), BS); + MapNode n1 = m_map->getNodeNoEx(p1); + v3s16 p2 = floatToInt(pf + v3f(0, BS*0.8, 0), BS); + MapNode n2 = m_map->getNodeNoEx(p2); + v3s16 p3 = floatToInt(pf + v3f(0, BS*1.6, 0), BS); + MapNode n3 = m_map->getNodeNoEx(p2); + + u32 damage_per_second = 0; + damage_per_second = MYMAX(damage_per_second, + content_features(n1).damage_per_second); + damage_per_second = MYMAX(damage_per_second, + content_features(n2).damage_per_second); + damage_per_second = MYMAX(damage_per_second, + content_features(n3).damage_per_second); + + if(damage_per_second != 0) + { + ClientEnvEvent event; + event.type = CEE_PLAYER_DAMAGE; + event.player_damage.amount = damage_per_second; + m_client_event_queue.push_back(event); + } + } + + /* + Stuff that can be done in an arbitarily large dtime + */ + for(core::list::Iterator i = m_players.begin(); + i != m_players.end(); i++) + { + Player *player = *i; + v3f playerpos = player->getPosition(); + + /* + Handle non-local players + */ + if(player->isLocal() == false) + { + // Move + player->move(dtime, *m_map, 100*BS); + + // Update lighting on remote players on client + u8 light = LIGHT_MAX; + try{ + // Get node at head + v3s16 p = player->getLightPosition(); + MapNode n = m_map->getNode(p); + light = n.getLightBlend(getDayNightRatio()); + } + catch(InvalidPositionException &e) {} + player->updateLight(light); + } + + /* + Add footsteps to grass + */ + if(footprints) + { + // Get node that is at BS/4 under player + v3s16 bottompos = floatToInt(playerpos + v3f(0,-BS/4,0), BS); + try{ + MapNode n = m_map->getNode(bottompos); + if(n.getContent() == CONTENT_GRASS) + { + n.setContent(CONTENT_GRASS_FOOTSTEPS); + m_map->setNode(bottompos, n); + // Update mesh on client + if(m_map->mapType() == MAPTYPE_CLIENT) + { + v3s16 p_blocks = getNodeBlockPos(bottompos); + MapBlock *b = m_map->getBlockNoCreate(p_blocks); + //b->updateMesh(getDayNightRatio()); + b->setMeshExpired(true); + } + } + } + catch(InvalidPositionException &e) + { + } + } + } + + /* + Step active objects and update lighting of them + */ + + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + ClientActiveObject* obj = i.getNode()->getValue(); + // Step object + obj->step(dtime, this); + + if(m_active_object_light_update_interval.step(dtime, 0.21)) + { + // Update lighting + //u8 light = LIGHT_MAX; + u8 light = 0; + try{ + // Get node at head + v3s16 p = obj->getLightPosition(); + MapNode n = m_map->getNode(p); + light = n.getLightBlend(getDayNightRatio()); + } + catch(InvalidPositionException &e) {} + obj->updateLight(light); + } + } +} + +void ClientEnvironment::updateMeshes(v3s16 blockpos) +{ + m_map->updateMeshes(blockpos, getDayNightRatio()); +} + +void ClientEnvironment::expireMeshes(bool only_daynight_diffed) +{ + m_map->expireMeshes(only_daynight_diffed); +} + +ClientActiveObject* ClientEnvironment::getActiveObject(u16 id) +{ + core::map::Node *n; + n = m_active_objects.find(id); + if(n == NULL) + return NULL; + return n->getValue(); +} + +bool isFreeClientActiveObjectId(u16 id, + core::map &objects) +{ + if(id == 0) + return false; + + for(core::map::Iterator + i = objects.getIterator(); + i.atEnd()==false; i++) + { + if(i.getNode()->getKey() == id) + return false; + } + return true; +} + +u16 getFreeClientActiveObjectId( + core::map &objects) +{ + u16 new_id = 1; + for(;;) + { + if(isFreeClientActiveObjectId(new_id, objects)) + return new_id; + + if(new_id == 65535) + return 0; + + new_id++; + } +} + +u16 ClientEnvironment::addActiveObject(ClientActiveObject *object) +{ + assert(object); + if(object->getId() == 0) + { + u16 new_id = getFreeClientActiveObjectId(m_active_objects); + if(new_id == 0) + { + dstream<<"WARNING: ClientEnvironment::addActiveObject(): " + <<"no free ids available"<setId(new_id); + } + if(isFreeClientActiveObjectId(object->getId(), m_active_objects) == false) + { + dstream<<"WARNING: ClientEnvironment::addActiveObject(): " + <<"id is not free ("<getId()<<")"<getId(), object); + object->addToScene(m_smgr); + return object->getId(); +} + +void ClientEnvironment::addActiveObject(u16 id, u8 type, + const std::string &init_data) +{ + ClientActiveObject* obj = ClientActiveObject::create(type); + if(obj == NULL) + { + dstream<<"WARNING: ClientEnvironment::addActiveObject(): " + <<"id="<setId(id); + + addActiveObject(obj); + + obj->initialize(init_data); +} + +void ClientEnvironment::removeActiveObject(u16 id) +{ + dstream<<"ClientEnvironment::removeActiveObject(): " + <<"id="<removeFromScene(); + delete obj; + m_active_objects.remove(id); +} + +void ClientEnvironment::processActiveObjectMessage(u16 id, + const std::string &data) +{ + ClientActiveObject* obj = getActiveObject(id); + if(obj == NULL) + { + dstream<<"WARNING: ClientEnvironment::processActiveObjectMessage():" + <<" got message for id="<processMessage(data); +} + +/* + Callbacks for activeobjects +*/ + +void ClientEnvironment::damageLocalPlayer(u8 damage) +{ + LocalPlayer *lplayer = getLocalPlayer(); + assert(lplayer); + + if(lplayer->hp > damage) + lplayer->hp -= damage; + else + lplayer->hp = 0; + + ClientEnvEvent event; + event.type = CEE_PLAYER_DAMAGE; + event.player_damage.amount = damage; + m_client_event_queue.push_back(event); +} + +/* + Client likes to call these +*/ + +void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d, + core::array &dest) +{ + for(core::map::Iterator + i = m_active_objects.getIterator(); + i.atEnd()==false; i++) + { + ClientActiveObject* obj = i.getNode()->getValue(); + + f32 d = (obj->getPosition() - origin).getLength(); + + if(d > max_d) + continue; + + DistanceSortedActiveObject dso(obj, d); + + dest.push_back(dso); + } +} + +ClientEnvEvent ClientEnvironment::getClientEvent() +{ + if(m_client_event_queue.size() == 0) + { + ClientEnvEvent event; + event.type = CEE_NONE; + return event; + } + return m_client_event_queue.pop_front(); +} + +void ClientEnvironment::drawPostFx(video::IVideoDriver* driver, v3f camera_pos) +{ + /*LocalPlayer *player = getLocalPlayer(); + assert(player); + v3f pos_f = player->getPosition() + v3f(0,BS*1.625,0);*/ + v3f pos_f = camera_pos; + v3s16 p_nodes = floatToInt(pos_f, BS); + MapNode n = m_map->getNodeNoEx(p_nodes); + if(n.getContent() == CONTENT_WATER || n.getContent() == CONTENT_WATERSOURCE) + { + v2u32 ss = driver->getScreenSize(); + core::rect rect(0,0, ss.X, ss.Y); + driver->draw2DRectangle(video::SColor(64, 100, 100, 200), rect); + } + else if(content_features(n).solidness == 2 && + g_settings.getBool("free_move") == false) + { + v2u32 ss = driver->getScreenSize(); + core::rect rect(0,0, ss.X, ss.Y); + driver->draw2DRectangle(video::SColor(255, 0, 0, 0), rect); + } +} + +#endif // #ifndef SERVER + + diff --git a/src/environment.h b/src/environment.h new file mode 100644 index 0000000..d9248d2 --- /dev/null +++ b/src/environment.h @@ -0,0 +1,425 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef ENVIRONMENT_HEADER +#define ENVIRONMENT_HEADER + +/* + This class is the game's environment. + It contains: + - The map + - Players + - Other objects + - The current time in the game (actually it only contains the brightness) + - etc. +*/ + +#include +#include "common_irrlicht.h" +#include "player.h" +#include "map.h" +#include +#include "utility.h" +#include "activeobject.h" + +class Server; +class ActiveBlockModifier; +class ServerActiveObject; + +class Environment +{ +public: + // Environment will delete the map passed to the constructor + Environment(); + virtual ~Environment(); + + /* + Step everything in environment. + - Move players + - Step mobs + - Run timers of map + */ + virtual void step(f32 dtime) = 0; + + virtual Map & getMap() = 0; + + virtual void addPlayer(Player *player); + void removePlayer(u16 peer_id); + Player * getPlayer(u16 peer_id); + Player * getPlayer(const char *name); + Player * getRandomConnectedPlayer(); + Player * getNearestConnectedPlayer(v3f pos); + core::list getPlayers(); + core::list getPlayers(bool ignore_disconnected); + void printPlayers(std::ostream &o); + + //void setDayNightRatio(u32 r); + u32 getDayNightRatio(); + + // 0-23999 + virtual void setTimeOfDay(u32 time) + { + m_time_of_day = time; + } + + u32 getTimeOfDay() + { + return m_time_of_day; + } + +protected: + // peer_ids in here should be unique, except that there may be many 0s + core::list m_players; + // Brightness + //u32 m_daynight_ratio; + // Time of day in milli-hours (0-23999); determines day and night + u32 m_time_of_day; +}; + +/* + List of active blocks, used by ServerEnvironment +*/ + +class ActiveBlockList +{ +public: + void update(core::list &active_positions, + s16 radius, + core::map &blocks_removed, + core::map &blocks_added); + + bool contains(v3s16 p){ + return (m_list.find(p) != NULL); + } + + void clear(){ + m_list.clear(); + } + + core::map m_list; + +private: +}; + +/* + The server-side environment. + + This is not thread-safe. Server uses an environment mutex. +*/ + +class ServerEnvironment : public Environment +{ +public: + ServerEnvironment(ServerMap *map, Server *server); + ~ServerEnvironment(); + + Map & getMap() + { + return *m_map; + } + + ServerMap & getServerMap() + { + return *m_map; + } + + Server * getServer() + { + return m_server; + } + + void step(f32 dtime); + + /* + Save players + */ + void serializePlayers(const std::string &savedir); + void deSerializePlayers(const std::string &savedir); + + /* + Save and load time of day and game timer + */ + void saveMeta(const std::string &savedir); + void loadMeta(const std::string &savedir); + + /* + External ActiveObject interface + ------------------------------------------- + */ + + ServerActiveObject* getActiveObject(u16 id); + + /* + Add an active object to the environment. + Environment handles deletion of object. + Object may be deleted by environment immediately. + If id of object is 0, assigns a free id to it. + Returns the id of the object. + Returns 0 if not added and thus deleted. + */ + u16 addActiveObject(ServerActiveObject *object); + + /* + Find out what new objects have been added to + inside a radius around a position + */ + void getAddedActiveObjects(v3s16 pos, s16 radius, + core::map ¤t_objects, + core::map &added_objects); + + /* + Find out what new objects have been removed from + inside a radius around a position + */ + void getRemovedActiveObjects(v3s16 pos, s16 radius, + core::map ¤t_objects, + core::map &removed_objects); + + /* + Get the next message emitted by some active object. + Returns a message with id=0 if no messages are available. + */ + ActiveObjectMessage getActiveObjectMessage(); + + /* + Activate objects and dynamically modify for the dtime determined + from timestamp and additional_dtime + */ + void activateBlock(MapBlock *block, u32 additional_dtime=0); + + /* + ActiveBlockModifiers (TODO) + ------------------------------------------- + */ + + void addActiveBlockModifier(ActiveBlockModifier *abm); + +private: + + /* + Internal ActiveObject interface + ------------------------------------------- + */ + + /* + Add an active object to the environment. + + Called by addActiveObject. + + Object may be deleted by environment immediately. + If id of object is 0, assigns a free id to it. + Returns the id of the object. + Returns 0 if not added and thus deleted. + */ + u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed); + + /* + Remove all objects that satisfy (m_removed && m_known_by_count==0) + */ + void removeRemovedObjects(); + + /* + Convert stored objects from block to active + */ + void activateObjects(MapBlock *block); + + /* + Convert objects that are not in active blocks to static. + + If m_known_by_count != 0, active object is not deleted, but static + data is still updated. + + If force_delete is set, active object is deleted nevertheless. It + shall only be set so in the destructor of the environment. + */ + void deactivateFarObjects(bool force_delete); + + /* + Member variables + */ + + // The map + ServerMap *m_map; + // Pointer to server (which is handling this environment) + Server *m_server; + // Active object list + core::map m_active_objects; + // Outgoing network message buffer for active objects + Queue m_active_object_messages; + // Some timers + float m_random_spawn_timer; // used for experimental code + float m_send_recommended_timer; + IntervalLimiter m_object_management_interval; + // List of active blocks + ActiveBlockList m_active_blocks; + IntervalLimiter m_active_blocks_management_interval; + IntervalLimiter m_active_blocks_test_interval; + IntervalLimiter m_active_blocks_nodemetadata_interval; + // Time from the beginning of the game in seconds. + // Incremented in step(). + u32 m_game_time; + // A helper variable for incrementing the latter + float m_game_time_fraction_counter; +}; + +/* + Active block modifier interface. + + These are fed into ServerEnvironment at initialization time; + ServerEnvironment handles deleting them. +*/ + +class ActiveBlockModifier +{ +public: + ActiveBlockModifier(){}; + virtual ~ActiveBlockModifier(){}; + + //virtual core::list update(ServerEnvironment *env) = 0; + virtual u32 getTriggerContentCount(){ return 1;} + virtual u8 getTriggerContent(u32 i) = 0; + virtual float getActiveInterval() = 0; + // chance of (1 / return value), 0 is disallowed + virtual u32 getActiveChance() = 0; + // This is called usually at interval for 1/chance of the nodes + virtual void triggerEvent(ServerEnvironment *env, v3s16 p) = 0; +}; + +#ifndef SERVER + +#include "clientobject.h" + +/* + The client-side environment. + + This is not thread-safe. + Must be called from main (irrlicht) thread (uses the SceneManager) + Client uses an environment mutex. +*/ + +enum ClientEnvEventType +{ + CEE_NONE, + CEE_PLAYER_DAMAGE +}; + +struct ClientEnvEvent +{ + ClientEnvEventType type; + union { + struct{ + } none; + struct{ + u8 amount; + } player_damage; + }; +}; + +class ClientEnvironment : public Environment +{ +public: + ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr); + ~ClientEnvironment(); + + Map & getMap() + { + return *m_map; + } + + ClientMap & getClientMap() + { + return *m_map; + } + + void step(f32 dtime); + + virtual void addPlayer(Player *player); + LocalPlayer * getLocalPlayer(); + + void updateMeshes(v3s16 blockpos); + void expireMeshes(bool only_daynight_diffed); + + void setTimeOfDay(u32 time) + { + u32 old_dr = getDayNightRatio(); + + Environment::setTimeOfDay(time); + + if(getDayNightRatio() != old_dr) + { + dout_client< expiring meshes"< &dest); + + // Get event from queue. CEE_NONE is returned if queue is empty. + ClientEnvEvent getClientEvent(); + + // Post effects + void drawPostFx(video::IVideoDriver* driver, v3f camera_pos); + +private: + ClientMap *m_map; + scene::ISceneManager *m_smgr; + core::map m_active_objects; + Queue m_client_event_queue; + IntervalLimiter m_active_object_light_update_interval; + IntervalLimiter m_lava_hurt_interval; +}; + +#endif + +#endif + diff --git a/src/exceptions.h b/src/exceptions.h new file mode 100644 index 0000000..40a0db4 --- /dev/null +++ b/src/exceptions.h @@ -0,0 +1,175 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef EXCEPTIONS_HEADER +#define EXCEPTIONS_HEADER + +#include + +class BaseException : public std::exception +{ +public: + BaseException(const char *s) + { + m_s = s; + } + virtual const char * what() const throw() + { + return m_s; + } + const char *m_s; +}; + +class AsyncQueuedException : public BaseException +{ +public: + AsyncQueuedException(const char *s): + BaseException(s) + {} +}; + +class NotImplementedException : public BaseException +{ +public: + NotImplementedException(const char *s): + BaseException(s) + {} +}; + +class AlreadyExistsException : public BaseException +{ +public: + AlreadyExistsException(const char *s): + BaseException(s) + {} +}; + +class VersionMismatchException : public BaseException +{ +public: + VersionMismatchException(const char *s): + BaseException(s) + {} +}; + +class FileNotGoodException : public BaseException +{ +public: + FileNotGoodException(const char *s): + BaseException(s) + {} +}; + +class SerializationError : public BaseException +{ +public: + SerializationError(const char *s): + BaseException(s) + {} +}; + +class LoadError : public BaseException +{ +public: + LoadError(const char *s): + BaseException(s) + {} +}; + +class ContainerFullException : public BaseException +{ +public: + ContainerFullException(const char *s): + BaseException(s) + {} +}; + +class SettingNotFoundException : public BaseException +{ +public: + SettingNotFoundException(const char *s): + BaseException(s) + {} +}; + +class InvalidFilenameException : public BaseException +{ +public: + InvalidFilenameException(const char *s): + BaseException(s) + {} +}; + +class ProcessingLimitException : public BaseException +{ +public: + ProcessingLimitException(const char *s): + BaseException(s) + {} +}; + +class CommandLineError : public BaseException +{ +public: + CommandLineError(const char *s): + BaseException(s) + {} +}; + +class ItemNotFoundException : public BaseException +{ +public: + ItemNotFoundException(const char *s): + BaseException(s) + {} +}; + +/* + Some "old-style" interrupts: +*/ + +class InvalidPositionException : public BaseException +{ +public: + InvalidPositionException(): + BaseException("Somebody tried to get/set something in a nonexistent position.") + {} + InvalidPositionException(const char *s): + BaseException(s) + {} +}; + +class TargetInexistentException : public std::exception +{ + virtual const char * what() const throw() + { + return "Somebody tried to refer to something that doesn't exist."; + } +}; + +class NullPointerException : public std::exception +{ + virtual const char * what() const throw() + { + return "NullPointerException"; + } +}; + +#endif + diff --git a/src/farmesh.cpp b/src/farmesh.cpp new file mode 100644 index 0000000..8f91e3a --- /dev/null +++ b/src/farmesh.cpp @@ -0,0 +1,414 @@ +/* +Part of Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* + A quick messy implementation of terrain rendering for a long + distance according to map seed +*/ + +#include "farmesh.h" +#include "constants.h" +#include "debug.h" +#include "noise.h" +#include "map.h" +#include "client.h" + +#include "mapgen.h" + +FarMesh::FarMesh( + scene::ISceneNode* parent, + scene::ISceneManager* mgr, + s32 id, + u64 seed, + Client *client +): + scene::ISceneNode(parent, mgr, id), + m_seed(seed), + m_camera_pos(0,0), + m_time(0), + m_client(client), + m_render_range(20*MAP_BLOCKSIZE) +{ + dstream<<__FUNCTION_NAME<getVideoDriver(); + + m_materials[0].setFlag(video::EMF_LIGHTING, false); + m_materials[0].setFlag(video::EMF_BACK_FACE_CULLING, true); + //m_materials[0].setFlag(video::EMF_BACK_FACE_CULLING, false); + m_materials[0].setFlag(video::EMF_BILINEAR_FILTER, false); + m_materials[0].setFlag(video::EMF_FOG_ENABLE, false); + //m_materials[0].setFlag(video::EMF_ANTI_ALIASING, true); + //m_materials[0].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; + m_materials[0].setFlag(video::EMF_FOG_ENABLE, true); + + m_materials[1].setFlag(video::EMF_LIGHTING, false); + m_materials[1].setFlag(video::EMF_BACK_FACE_CULLING, false); + m_materials[1].setFlag(video::EMF_BILINEAR_FILTER, false); + m_materials[1].setFlag(video::EMF_FOG_ENABLE, false); + m_materials[1].setTexture + (0, driver->getTexture(getTexturePath("treeprop.png").c_str())); + m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + m_materials[1].setFlag(video::EMF_FOG_ENABLE, true); + + m_box = core::aabbox3d(-BS*1000000,-BS*31000,-BS*1000000, + BS*1000000,BS*31000,BS*1000000); + +} + +FarMesh::~FarMesh() +{ + dstream<<__FUNCTION_NAME<registerNodeForRendering(this, scene::ESNRP_TRANSPARENT); + SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); + //SceneManager->registerNodeForRendering(this, scene::ESNRP_SKY_BOX); + } + + ISceneNode::OnRegisterSceneNode(); +} + +#define MYROUND(x) (x > 0.0 ? (int)x : (int)x - 1) + +// Temporary hack +struct HeightPoint +{ + float gh; // ground height + float ma; // mud amount + float have_sand; + float tree_amount; +}; +core::map g_heights; + +HeightPoint ground_height(u64 seed, v2s16 p2d) +{ + core::map::Node *n = g_heights.find(p2d); + if(n) + return n->getValue(); + HeightPoint hp; + s16 level = mapgen::find_ground_level_from_noise(seed, p2d, 3); + hp.gh = (level-4)*BS; + hp.ma = (4)*BS; + /*hp.gh = BS*base_rock_level_2d(seed, p2d); + hp.ma = BS*get_mud_add_amount(seed, p2d);*/ + hp.have_sand = mapgen::get_have_sand(seed, p2d); + if(hp.gh > BS*WATER_LEVEL) + hp.tree_amount = mapgen::tree_amount_2d(seed, p2d); + else + hp.tree_amount = 0; + // No mud has been added if mud amount is less than 1 + if(hp.ma < 1.0*BS) + hp.ma = 0.0; + //hp.gh -= BS*3; // Lower a bit so that it is not that much in the way + g_heights[p2d] = hp; + return hp; +} + +void FarMesh::render() +{ + video::IVideoDriver* driver = SceneManager->getVideoDriver(); + + /*if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_TRANSPARENT) + return;*/ + if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SOLID) + return; + /*if(SceneManager->getSceneNodeRenderPass() != scene::ESNRP_SKY_BOX) + return;*/ + + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); + + //const s16 grid_radius_i = 12; + //const float grid_size = BS*50; + const s16 grid_radius_i = m_render_range/MAP_BLOCKSIZE; + const float grid_size = BS*MAP_BLOCKSIZE; + const v2f grid_speed(-BS*0, 0); + + // Position of grid noise origin in world coordinates + v2f world_grid_origin_pos_f(0,0); + // Position of grid noise origin from the camera + v2f grid_origin_from_camera_f = world_grid_origin_pos_f - m_camera_pos; + // The center point of drawing in the noise + v2f center_of_drawing_in_noise_f = -grid_origin_from_camera_f; + // The integer center point of drawing in the noise + v2s16 center_of_drawing_in_noise_i( + MYROUND(center_of_drawing_in_noise_f.X / grid_size), + MYROUND(center_of_drawing_in_noise_f.Y / grid_size) + ); + // The world position of the integer center point of drawing in the noise + v2f world_center_of_drawing_in_noise_f = v2f( + center_of_drawing_in_noise_i.X * grid_size, + center_of_drawing_in_noise_i.Y * grid_size + ) + world_grid_origin_pos_f; + + for(s16 zi=-grid_radius_i; zi -dd && zi < dd && xi > -dd && xi < dd) + continue;*/ + + v2s16 p_in_noise_i( + xi+center_of_drawing_in_noise_i.X, + zi+center_of_drawing_in_noise_i.Y + ); + + // If sector was drawn, don't draw it this way + if(m_client->m_env.getClientMap().sectorWasDrawn(p_in_noise_i)) + continue; + + /*if((p_in_noise_i.X + p_in_noise_i.Y)%2==0) + continue;*/ + /*if((p_in_noise_i.X/2 + p_in_noise_i.Y/2)%2==0) + continue;*/ + + v2f p0 = v2f(xi,zi)*grid_size + world_center_of_drawing_in_noise_f; + + /*double noise[4]; + double d = 100*BS; + noise[0] = d*noise2d_perlin( + (float)(p_in_noise_i.X+0)*grid_size/BS/100, + (float)(p_in_noise_i.Y+0)*grid_size/BS/100, + m_seed, 3, 0.5); + + noise[1] = d*noise2d_perlin( + (float)(p_in_noise_i.X+0)*grid_size/BS/100, + (float)(p_in_noise_i.Y+1)*grid_size/BS/100, + m_seed, 3, 0.5); + + noise[2] = d*noise2d_perlin( + (float)(p_in_noise_i.X+1)*grid_size/BS/100, + (float)(p_in_noise_i.Y+1)*grid_size/BS/100, + m_seed, 3, 0.5); + + noise[3] = d*noise2d_perlin( + (float)(p_in_noise_i.X+1)*grid_size/BS/100, + (float)(p_in_noise_i.Y+0)*grid_size/BS/100, + m_seed, 3, 0.5);*/ + + HeightPoint hps[5]; + hps[0] = ground_height(m_seed, v2s16( + (p_in_noise_i.X+0)*grid_size/BS, + (p_in_noise_i.Y+0)*grid_size/BS)); + hps[1] = ground_height(m_seed, v2s16( + (p_in_noise_i.X+0)*grid_size/BS, + (p_in_noise_i.Y+1)*grid_size/BS)); + hps[2] = ground_height(m_seed, v2s16( + (p_in_noise_i.X+1)*grid_size/BS, + (p_in_noise_i.Y+1)*grid_size/BS)); + hps[3] = ground_height(m_seed, v2s16( + (p_in_noise_i.X+1)*grid_size/BS, + (p_in_noise_i.Y+0)*grid_size/BS)); + v2s16 centerpoint( + (p_in_noise_i.X+0)*grid_size/BS+MAP_BLOCKSIZE/2, + (p_in_noise_i.Y+0)*grid_size/BS+MAP_BLOCKSIZE/2); + hps[4] = ground_height(m_seed, centerpoint); + + float noise[5]; + float h_min = BS*65535; + float h_max = -BS*65536; + float ma_avg = 0; + float h_avg = 0; + u32 have_sand_count = 0; + float tree_amount_avg = 0; + for(u32 i=0; i<5; i++) + { + noise[i] = hps[i].gh + hps[i].ma; + if(noise[i] < h_min) + h_min = noise[i]; + if(noise[i] > h_max) + h_max = noise[i]; + ma_avg += hps[i].ma; + h_avg += noise[i]; + if(hps[i].have_sand) + have_sand_count++; + tree_amount_avg += hps[i].tree_amount; + } + ma_avg /= 5.0; + h_avg /= 5.0; + tree_amount_avg /= 5.0; + + float steepness = (h_max - h_min)/grid_size; + + float light_f = noise[0]+noise[1]-noise[2]-noise[3]; + light_f /= 100; + if(light_f < -1.0) light_f = -1.0; + if(light_f > 1.0) light_f = 1.0; + //light_f += 1.0; + //light_f /= 2.0; + + v2f p1 = p0 + v2f(1,1)*grid_size; + + bool ground_is_sand = false; + bool ground_is_rock = false; + bool ground_is_mud = false; + video::SColor c; + // Detect water + if(h_avg < WATER_LEVEL*BS && h_max < (WATER_LEVEL+5)*BS) + { + //c = video::SColor(255,59,86,146); + //c = video::SColor(255,82,120,204); + c = video::SColor(255,74,105,170); + + /*// Set to water level + for(u32 i=0; i<4; i++) + { + if(noise[i] < BS*WATER_LEVEL) + noise[i] = BS*WATER_LEVEL; + }*/ + light_f = 0; + } + // Steep cliffs + else if(steepness > 2.0) + { + c = video::SColor(255,128,128,128); + ground_is_rock = true; + } + // Basic ground + else + { + if(ma_avg < 2.0*BS) + { + c = video::SColor(255,128,128,128); + ground_is_rock = true; + } + else + { + if(h_avg <= 2.5*BS && have_sand_count >= 2) + { + c = video::SColor(255,210,194,156); + ground_is_sand = true; + } + else + { + /*// Trees if there are over 0.01 trees per MapNode + if(tree_amount_avg > 0.01) + c = video::SColor(255,50,128,50); + else + c = video::SColor(255,107,134,51);*/ + c = video::SColor(255,107,134,51); + ground_is_mud = true; + } + } + } + + // Set to water level + for(u32 i=0; i<4; i++) + { + if(noise[i] < BS*WATER_LEVEL) + noise[i] = BS*WATER_LEVEL; + } + + float b = m_brightness + light_f*0.1*m_brightness; + if(b < 0) b = 0; + if(b > 2) b = 2; + + c = video::SColor(255, b*c.getRed(), b*c.getGreen(), b*c.getBlue()); + + driver->setMaterial(m_materials[0]); + + video::S3DVertex vertices[4] = + { + video::S3DVertex(p0.X,noise[0],p0.Y, 0,0,0, c, 0,1), + video::S3DVertex(p0.X,noise[1],p1.Y, 0,0,0, c, 1,1), + video::S3DVertex(p1.X,noise[2],p1.Y, 0,0,0, c, 1,0), + video::S3DVertex(p1.X,noise[3],p0.Y, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + driver->drawVertexPrimitiveList(vertices, 4, indices, 2, + video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT); + + // Add some trees if appropriate + if(tree_amount_avg >= 0.0065 && steepness < 1.4 + && ground_is_mud == true) + { + driver->setMaterial(m_materials[1]); + + float b = m_brightness; + c = video::SColor(255, b*255, b*255, b*255); + + { + video::S3DVertex vertices[4] = + { + video::S3DVertex(p0.X,noise[0],p0.Y, + 0,0,0, c, 0,1), + video::S3DVertex(p0.X,noise[0]+BS*MAP_BLOCKSIZE,p0.Y, + 0,0,0, c, 0,0), + video::S3DVertex(p1.X,noise[2]+BS*MAP_BLOCKSIZE,p1.Y, + 0,0,0, c, 1,0), + video::S3DVertex(p1.X,noise[2],p1.Y, + 0,0,0, c, 1,1), + }; + u16 indices[] = {0,1,2,2,3,0}; + driver->drawVertexPrimitiveList(vertices, 4, indices, 2, + video::EVT_STANDARD, scene::EPT_TRIANGLES, + video::EIT_16BIT); + } + { + video::S3DVertex vertices[4] = + { + video::S3DVertex(p1.X,noise[3],p0.Y, + 0,0,0, c, 0,1), + video::S3DVertex(p1.X,noise[3]+BS*MAP_BLOCKSIZE,p0.Y, + 0,0,0, c, 0,0), + video::S3DVertex(p0.X,noise[1]+BS*MAP_BLOCKSIZE,p1.Y, + 0,0,0, c, 1,0), + video::S3DVertex(p0.X,noise[1],p1.Y, + 0,0,0, c, 1,1), + }; + u16 indices[] = {0,1,2,2,3,0}; + driver->drawVertexPrimitiveList(vertices, 4, indices, 2, + video::EVT_STANDARD, scene::EPT_TRIANGLES, + video::EIT_16BIT); + } + } + } + + //driver->clearZBuffer(); +} + +void FarMesh::step(float dtime) +{ + m_time += dtime; +} + +void FarMesh::update(v2f camera_p, float brightness, s16 render_range) +{ + m_camera_pos = camera_p; + m_brightness = brightness; + m_render_range = render_range; +} + + diff --git a/src/farmesh.h b/src/farmesh.h new file mode 100644 index 0000000..0a30a8a --- /dev/null +++ b/src/farmesh.h @@ -0,0 +1,85 @@ +/* +Part of Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef FARMESH_HEADER +#define FARMESH_HEADER + +/* + A quick messy implementation of terrain rendering for a long + distance according to map seed +*/ + +#include "common_irrlicht.h" + +#define FARMESH_MATERIAL_COUNT 2 + +class Client; + +class FarMesh : public scene::ISceneNode +{ +public: + FarMesh( + scene::ISceneNode* parent, + scene::ISceneManager* mgr, + s32 id, + u64 seed, + Client *client + ); + + ~FarMesh(); + + /* + ISceneNode methods + */ + + virtual void OnRegisterSceneNode(); + + virtual void render(); + + virtual const core::aabbox3d& getBoundingBox() const + { + return m_box; + } + + virtual u32 getMaterialCount() const; + + virtual video::SMaterial& getMaterial(u32 i); + + /* + Other stuff + */ + + void step(float dtime); + + void update(v2f camera_p, float brightness, s16 render_range); + +private: + video::SMaterial m_materials[FARMESH_MATERIAL_COUNT]; + core::aabbox3d m_box; + float m_cloud_y; + float m_brightness; + u64 m_seed; + v2f m_camera_pos; + float m_time; + Client *m_client; + s16 m_render_range; +}; + +#endif + diff --git a/src/filesys.cpp b/src/filesys.cpp new file mode 100644 index 0000000..8aa10ba --- /dev/null +++ b/src/filesys.cpp @@ -0,0 +1,313 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "filesys.h" +#include "strfnd.h" +#include +#include + +namespace fs +{ + +#ifdef _WIN32 // WINDOWS + +#define _WIN32_WINNT 0x0501 +#include +#include +#include +#include +#include +#include + +#define BUFSIZE MAX_PATH + +std::vector GetDirListing(std::string pathstring) +{ + std::vector listing; + + WIN32_FIND_DATA FindFileData; + HANDLE hFind = INVALID_HANDLE_VALUE; + DWORD dwError; + LPTSTR DirSpec; + INT retval; + + DirSpec = (LPTSTR) malloc (BUFSIZE); + + if( DirSpec == NULL ) + { + printf( "Insufficient memory available\n" ); + retval = 1; + goto Cleanup; + } + + // Check that the input is not larger than allowed. + if (pathstring.size() > (BUFSIZE - 2)) + { + _tprintf(TEXT("Input directory is too large.\n")); + retval = 3; + goto Cleanup; + } + + //_tprintf (TEXT("Target directory is %s.\n"), pathstring.c_str()); + + sprintf(DirSpec, "%s", (pathstring + "\\*").c_str()); + + // Find the first file in the directory. + hFind = FindFirstFile(DirSpec, &FindFileData); + + if (hFind == INVALID_HANDLE_VALUE) + { + _tprintf (TEXT("Invalid file handle. Error is %u.\n"), + GetLastError()); + retval = (-1); + } + else + { + // NOTE: + // Be very sure to not include '..' in the results, it will + // result in an epic failure when deleting stuff. + + DirListNode node; + node.name = FindFileData.cFileName; + node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; + if(node.name != "." && node.name != "..") + listing.push_back(node); + + // List all the other files in the directory. + while (FindNextFile(hFind, &FindFileData) != 0) + { + DirListNode node; + node.name = FindFileData.cFileName; + node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; + if(node.name != "." && node.name != "..") + listing.push_back(node); + } + + dwError = GetLastError(); + FindClose(hFind); + if (dwError != ERROR_NO_MORE_FILES) + { + _tprintf (TEXT("FindNextFile error. Error is %u.\n"), + dwError); + retval = (-1); + goto Cleanup; + } + } + retval = 0; + +Cleanup: + free(DirSpec); + + if(retval != 0) listing.clear(); + + //for(unsigned int i=0; i +#include +#include +#include +#include + +std::vector GetDirListing(std::string pathstring) +{ + std::vector listing; + + DIR *dp; + struct dirent *dirp; + if((dp = opendir(pathstring.c_str())) == NULL) { + //std::cout<<"Error("<d_name[0]!='.'){ + DirListNode node; + node.name = dirp->d_name; + if(dirp->d_type == DT_DIR) node.dir = true; + else node.dir = false; + if(node.name != "." && node.name != "..") + listing.push_back(node); + } + } + closedir(dp); + + return listing; +} + +bool CreateDir(std::string path) +{ + int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); + if(r == 0) + { + return true; + } + else + { + // If already exists, return true + if(errno == EEXIST) + return true; + return false; + } +} + +bool PathExists(std::string path) +{ + struct stat st; + return (stat(path.c_str(),&st) == 0); +} + +bool RecursiveDelete(std::string path) +{ + /* + Execute the 'rm' command directly, by fork() and execve() + */ + + std::cerr<<"Removing \""< list = GetDirListing(path); + for(unsigned int i=0; i tocreate; + std::string basepath = path; + while(!PathExists(basepath)) + { + tocreate.push_back(basepath); + pos = basepath.rfind('/'); + if(pos == std::string::npos) + return false; + basepath = basepath.substr(0,pos); + } + for(int i=tocreate.size()-1;i>=0;i--) + CreateDir(tocreate[i]); + return true; +} + +} // namespace fs + diff --git a/src/filesys.h b/src/filesys.h new file mode 100644 index 0000000..b74b34f --- /dev/null +++ b/src/filesys.h @@ -0,0 +1,56 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef FILESYS_HEADER +#define FILESYS_HEADER + +#include +#include +#include "exceptions.h" + +namespace fs +{ + +struct DirListNode +{ + std::string name; + bool dir; +}; + +std::vector GetDirListing(std::string path); + +// Returns true if already exists +bool CreateDir(std::string path); + +// Create all directories on the given path that don't already exist. +bool CreateAllDirs(std::string path); + +bool PathExists(std::string path); + +// Only pass full paths to this one. True on success. +// NOTE: The WIN32 version returns always true. +bool RecursiveDelete(std::string path); + +// Only pass full paths to this one. True on success. +bool RecursiveDeleteContent(std::string path); + +}//fs + +#endif + diff --git a/src/game.cpp b/src/game.cpp new file mode 100644 index 0000000..dc3ed24 --- /dev/null +++ b/src/game.cpp @@ -0,0 +1,2435 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "common_irrlicht.h" +#include "game.h" +#include "client.h" +#include "server.h" +#include "guiPauseMenu.h" +#include "guiPasswordChange.h" +#include "guiInventoryMenu.h" +#include "guiTextInputMenu.h" +#include "materials.h" +#include "config.h" +#include "clouds.h" +#include "farmesh.h" +#include "mapblock.h" + +/* + TODO: Move content-aware stuff to separate file by adding properties + and virtual interfaces +*/ +#include "content_mapnode.h" +#include "content_nodemeta.h" + +/* + Setting this to 1 enables a special camera mode that forces + the renderers to think that the camera statically points from + the starting place to a static direction. + + This allows one to move around with the player and see what + is actually drawn behind solid things and behind the player. +*/ +#define FIELD_OF_VIEW_TEST 0 + + +MapDrawControl draw_control; + +// Chat data +struct ChatLine +{ + ChatLine(): + age(0.0) + { + } + ChatLine(const std::wstring &a_text): + age(0.0), + text(a_text) + { + } + float age; + std::wstring text; +}; + +/* + Inventory stuff +*/ + +// Inventory actions from the menu are buffered here before sending +Queue inventory_action_queue; +// This is a copy of the inventory that the client's environment has +Inventory local_inventory; + +u16 g_selected_item = 0; + +/* + Text input system +*/ + +struct TextDestSign : public TextDest +{ + TextDestSign(v3s16 blockpos, s16 id, Client *client) + { + m_blockpos = blockpos; + m_id = id; + m_client = client; + } + void gotText(std::wstring text) + { + std::string ntext = wide_to_narrow(text); + dstream<<"Changing text of a sign object: " + <sendSignText(m_blockpos, m_id, ntext); + } + + v3s16 m_blockpos; + s16 m_id; + Client *m_client; +}; + +struct TextDestChat : public TextDest +{ + TextDestChat(Client *client) + { + m_client = client; + } + void gotText(std::wstring text) + { + // Discard empty line + if(text == L"") + return; + + // Send to others + m_client->sendChatMessage(text); + // Show locally + m_client->addChatMessage(text); + } + + Client *m_client; +}; + +struct TextDestSignNode : public TextDest +{ + TextDestSignNode(v3s16 p, Client *client) + { + m_p = p; + m_client = client; + } + void gotText(std::wstring text) + { + std::string ntext = wide_to_narrow(text); + dstream<<"Changing text of a sign node: " + <sendSignNodeText(m_p, ntext); + } + + v3s16 m_p; + Client *m_client; +}; + +/* + Render distance feedback loop +*/ +void updateViewingRange(f32 frametime_in, Client *client) +{ + if(draw_control.range_all == true) + return; + + static f32 added_frametime = 0; + static s16 added_frames = 0; + + added_frametime += frametime_in; + added_frames += 1; + + // Actually this counter kind of sucks because frametime is busytime + static f32 counter = 0; + counter -= frametime_in; + if(counter > 0) + return; + //counter = 0.1; + counter = 0.2; + + /*dstream<<__FUNCTION_NAME + <<": Collected "< range_max) + new_range = range_max; + + /*dstream<<"new_range="<getList("main"); + if(mainlist == NULL) + { + dstream<<"WARNING: draw_hotbar(): mainlist == NULL"< barrect(0,0,width,height); + barrect += pos; + video::SColor bgcolor(255,128,128,128); + driver->draw2DRectangle(bgcolor, barrect, NULL);*/ + + core::rect imgrect(0,0,imgsize,imgsize); + + for(s32 i=0; igetItem(i); + + core::rect rect = imgrect + pos + + v2s32(padding+i*(imgsize+padding*2), padding); + + if(g_selected_item == i) + { + video::SColor c_outside(255,255,0,0); + //video::SColor c_outside(255,0,0,0); + //video::SColor c_inside(255,192,192,192); + s32 x1 = rect.UpperLeftCorner.X; + s32 y1 = rect.UpperLeftCorner.Y; + s32 x2 = rect.LowerRightCorner.X; + s32 y2 = rect.LowerRightCorner.Y; + // Black base borders + driver->draw2DRectangle(c_outside, + core::rect( + v2s32(x1 - padding, y1 - padding), + v2s32(x2 + padding, y1) + ), NULL); + driver->draw2DRectangle(c_outside, + core::rect( + v2s32(x1 - padding, y2), + v2s32(x2 + padding, y2 + padding) + ), NULL); + driver->draw2DRectangle(c_outside, + core::rect( + v2s32(x1 - padding, y1), + v2s32(x1, y2) + ), NULL); + driver->draw2DRectangle(c_outside, + core::rect( + v2s32(x2, y1), + v2s32(x2 + padding, y2) + ), NULL); + /*// Light inside borders + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x1 - padding/2, y1 - padding/2), + v2s32(x2 + padding/2, y1) + ), NULL); + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x1 - padding/2, y2), + v2s32(x2 + padding/2, y2 + padding/2) + ), NULL); + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x1 - padding/2, y1), + v2s32(x1, y2) + ), NULL); + driver->draw2DRectangle(c_inside, + core::rect( + v2s32(x2, y1), + v2s32(x2 + padding/2, y2) + ), NULL); + */ + } + + video::SColor bgcolor2(128,0,0,0); + driver->draw2DRectangle(bgcolor2, rect, NULL); + + if(item != NULL) + { + drawInventoryItem(driver, font, item, rect, NULL); + } + } + + /* + Draw hearts + */ + { + video::ITexture *heart_texture = + driver->getTexture(getTexturePath("heart.png").c_str()); + v2s32 p = pos + v2s32(0, -20); + for(s32 i=0; i rect(0,0,16,16); + rect += p; + driver->draw2DImage(heart_texture, rect, + core::rect(core::position2d(0,0), + core::dimension2di(heart_texture->getOriginalSize())), + NULL, colors, true); + p += v2s32(16,0); + } + if(halfheartcount % 2 == 1) + { + const video::SColor color(255,255,255,255); + const video::SColor colors[] = {color,color,color,color}; + core::rect rect(0,0,16/2,16); + rect += p; + core::dimension2di srcd(heart_texture->getOriginalSize()); + srcd.Width /= 2; + driver->draw2DImage(heart_texture, rect, + core::rect(core::position2d(0,0), srcd), + NULL, colors, true); + p += v2s32(16,0); + } + } +} + +/* + Find what the player is pointing at +*/ +void getPointedNode(Client *client, v3f player_position, + v3f camera_direction, v3f camera_position, + bool &nodefound, core::line3d shootline, + v3s16 &nodepos, v3s16 &neighbourpos, + core::aabbox3d &nodehilightbox, + f32 d) +{ + f32 mindistance = BS * 1001; + + v3s16 pos_i = floatToInt(player_position, BS); + + /*std::cout<<"pos_i=("<0 ? a : 1); + s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1); + s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1); + + for(s16 y = ystart; y <= yend; y++) + for(s16 z = zstart; z <= zend; z++) + for(s16 x = xstart; x <= xend; x++) + { + MapNode n; + try + { + n = client->getNode(v3s16(x,y,z)); + if(content_pointable(n.getContent()) == false) + continue; + } + catch(InvalidPositionException &e) + { + continue; + } + + v3s16 np(x,y,z); + v3f npf = intToFloat(np, BS); + + f32 d = 0.01; + + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + /* + Meta-objects + */ + if(n.getContent() == CONTENT_TORCH) + { + v3s16 dir = unpackDir(n.param2); + v3f dir_f = v3f(dir.X, dir.Y, dir.Z); + dir_f *= BS/2 - BS/6 - BS/20; + v3f cpf = npf + dir_f; + f32 distance = (cpf - camera_position).getLength(); + + core::aabbox3d box; + + // bottom + if(dir == v3s16(0,-1,0)) + { + box = core::aabbox3d( + npf - v3f(BS/6, BS/2, BS/6), + npf + v3f(BS/6, -BS/2+BS/3*2, BS/6) + ); + } + // top + else if(dir == v3s16(0,1,0)) + { + box = core::aabbox3d( + npf - v3f(BS/6, -BS/2+BS/3*2, BS/6), + npf + v3f(BS/6, BS/2, BS/6) + ); + } + // side + else + { + box = core::aabbox3d( + cpf - v3f(BS/6, BS/3, BS/6), + cpf + v3f(BS/6, BS/3, BS/6) + ); + } + + if(distance < mindistance) + { + if(box.intersectsWithLine(shootline)) + { + nodefound = true; + nodepos = np; + neighbourpos = np; + mindistance = distance; + nodehilightbox = box; + } + } + } + else if(n.getContent() == CONTENT_SIGN_WALL) + { + v3s16 dir = unpackDir(n.param2); + v3f dir_f = v3f(dir.X, dir.Y, dir.Z); + dir_f *= BS/2 - BS/6 - BS/20; + v3f cpf = npf + dir_f; + f32 distance = (cpf - camera_position).getLength(); + + v3f vertices[4] = + { + v3f(BS*0.42,-BS*0.35,-BS*0.4), + v3f(BS*0.49, BS*0.35, BS*0.4), + }; + + for(s32 i=0; i<2; i++) + { + if(dir == v3s16(1,0,0)) + vertices[i].rotateXZBy(0); + if(dir == v3s16(-1,0,0)) + vertices[i].rotateXZBy(180); + if(dir == v3s16(0,0,1)) + vertices[i].rotateXZBy(90); + if(dir == v3s16(0,0,-1)) + vertices[i].rotateXZBy(-90); + if(dir == v3s16(0,-1,0)) + vertices[i].rotateXYBy(-90); + if(dir == v3s16(0,1,0)) + vertices[i].rotateXYBy(90); + + vertices[i] += npf; + } + + core::aabbox3d box; + + box = core::aabbox3d(vertices[0]); + box.addInternalPoint(vertices[1]); + + if(distance < mindistance) + { + if(box.intersectsWithLine(shootline)) + { + nodefound = true; + nodepos = np; + neighbourpos = np; + mindistance = distance; + nodehilightbox = box; + } + } + } + + else if(n.getContent() == CONTENT_LADDER) + { + v3s16 dir = unpackDir(n.param2); + v3f dir_f = v3f(dir.X, dir.Y, dir.Z); + dir_f *= BS/2 - BS/6 - BS/20; + v3f cpf = npf + dir_f; + f32 distance = (cpf - camera_position).getLength(); + + v3f vertices[4] = + { + v3f(BS*0.42,-BS/2,-BS/2), + v3f(BS*0.49, BS/2, BS/2), + }; + + for(s32 i=0; i<2; i++) + { + if(dir == v3s16(1,0,0)) + vertices[i].rotateXZBy(0); + if(dir == v3s16(-1,0,0)) + vertices[i].rotateXZBy(180); + if(dir == v3s16(0,0,1)) + vertices[i].rotateXZBy(90); + if(dir == v3s16(0,0,-1)) + vertices[i].rotateXZBy(-90); + if(dir == v3s16(0,-1,0)) + vertices[i].rotateXYBy(-90); + if(dir == v3s16(0,1,0)) + vertices[i].rotateXYBy(90); + + vertices[i] += npf; + } + + core::aabbox3d box; + + box = core::aabbox3d(vertices[0]); + box.addInternalPoint(vertices[1]); + + if(distance < mindistance) + { + if(box.intersectsWithLine(shootline)) + { + nodefound = true; + nodepos = np; + neighbourpos = np; + mindistance = distance; + nodehilightbox = box; + } + } + } + else if(n.getContent() == CONTENT_RAIL) + { + v3s16 dir = unpackDir(n.param0); + v3f dir_f = v3f(dir.X, dir.Y, dir.Z); + dir_f *= BS/2 - BS/6 - BS/20; + v3f cpf = npf + dir_f; + f32 distance = (cpf - camera_position).getLength(); + + float d = (float)BS/16; + v3f vertices[4] = + { + v3f(BS/2, -BS/2+d, -BS/2), + v3f(-BS/2, -BS/2, BS/2), + }; + + for(s32 i=0; i<2; i++) + { + vertices[i] += npf; + } + + core::aabbox3d box; + + box = core::aabbox3d(vertices[0]); + box.addInternalPoint(vertices[1]); + + if(distance < mindistance) + { + if(box.intersectsWithLine(shootline)) + { + nodefound = true; + nodepos = np; + neighbourpos = np; + mindistance = distance; + nodehilightbox = box; + } + } + } + /* + Regular blocks + */ + else + { + for(u16 i=0; i<6; i++) + { + v3f dir_f = v3f(dirs[i].X, + dirs[i].Y, dirs[i].Z); + v3f centerpoint = npf + dir_f * BS/2; + f32 distance = + (centerpoint - camera_position).getLength(); + + if(distance < mindistance) + { + core::CMatrix4 m; + m.buildRotateFromTo(v3f(0,0,1), dir_f); + + // This is the back face + v3f corners[2] = { + v3f(BS/2, BS/2, BS/2), + v3f(-BS/2, -BS/2, BS/2+d) + }; + + for(u16 j=0; j<2; j++) + { + m.rotateVect(corners[j]); + corners[j] += npf; + } + + core::aabbox3d facebox(corners[0]); + facebox.addInternalPoint(corners[1]); + + if(facebox.intersectsWithLine(shootline)) + { + nodefound = true; + nodepos = np; + neighbourpos = np + dirs[i]; + mindistance = distance; + + //nodehilightbox = facebox; + + const float d = 0.502; + core::aabbox3d nodebox + (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d); + v3f nodepos_f = intToFloat(nodepos, BS); + nodebox.MinEdge += nodepos_f; + nodebox.MaxEdge += nodepos_f; + nodehilightbox = nodebox; + } + } // if distance < mindistance + } // for dirs + } // regular block + } // for coords +} + +void update_skybox(video::IVideoDriver* driver, + scene::ISceneManager* smgr, scene::ISceneNode* &skybox, + float brightness) +{ + if(skybox) + { + skybox->remove(); + } + + /*// Disable skybox if FarMesh is enabled + if(g_settings.getBool("enable_farmesh")) + return;*/ + + if(brightness >= 0.5) + { + skybox = smgr->addSkyBoxSceneNode( + driver->getTexture(getTexturePath("skybox2.png").c_str()), + driver->getTexture(getTexturePath("skybox3.png").c_str()), + driver->getTexture(getTexturePath("skybox1.png").c_str()), + driver->getTexture(getTexturePath("skybox1.png").c_str()), + driver->getTexture(getTexturePath("skybox1.png").c_str()), + driver->getTexture(getTexturePath("skybox1.png").c_str())); + } + else if(brightness >= 0.2) + { + skybox = smgr->addSkyBoxSceneNode( + driver->getTexture(getTexturePath("skybox2_dawn.png").c_str()), + driver->getTexture(getTexturePath("skybox3_dawn.png").c_str()), + driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()), + driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()), + driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()), + driver->getTexture(getTexturePath("skybox1_dawn.png").c_str())); + } + else + { + skybox = smgr->addSkyBoxSceneNode( + driver->getTexture(getTexturePath("skybox2_night.png").c_str()), + driver->getTexture(getTexturePath("skybox3_night.png").c_str()), + driver->getTexture(getTexturePath("skybox1_night.png").c_str()), + driver->getTexture(getTexturePath("skybox1_night.png").c_str()), + driver->getTexture(getTexturePath("skybox1_night.png").c_str()), + driver->getTexture(getTexturePath("skybox1_night.png").c_str())); + } +} + +/* + Draws a screen with a single text on it. + Text will be removed when the screen is drawn the next time. +*/ +/*gui::IGUIStaticText **/ +void draw_load_screen(const std::wstring &text, + video::IVideoDriver* driver, gui::IGUIFont* font) +{ + v2u32 screensize = driver->getScreenSize(); + const wchar_t *loadingtext = text.c_str(); + core::vector2d textsize_u = font->getDimension(loadingtext); + core::vector2d textsize(textsize_u.X,textsize_u.Y); + core::vector2d center(screensize.X/2, screensize.Y/2); + core::rect textrect(center - textsize/2, center + textsize/2); + + gui::IGUIStaticText *guitext = guienv->addStaticText( + loadingtext, textrect, false, false); + guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + + driver->beginScene(true, true, video::SColor(255,0,0,0)); + guienv->drawAll(); + driver->endScene(); + + guitext->remove(); + + //return guitext; +} + +void the_game( + bool &kill, + bool random_input, + InputHandler *input, + IrrlichtDevice *device, + gui::IGUIFont* font, + std::string map_dir, + std::string playername, + std::string password, + std::string address, + u16 port, + std::wstring &error_message, + std::string configpath +) +{ + video::IVideoDriver* driver = device->getVideoDriver(); + scene::ISceneManager* smgr = device->getSceneManager(); + + // Calculate text height using the font + u32 text_height = font->getDimension(L"Random test string").Height; + + v2u32 screensize(0,0); + v2u32 last_screensize(0,0); + screensize = driver->getScreenSize(); + + const s32 hotbar_itemcount = 8; + //const s32 hotbar_imagesize = 36; + //const s32 hotbar_imagesize = 64; + s32 hotbar_imagesize = 48; + + // The color of the sky + + //video::SColor skycolor = video::SColor(255,140,186,250); + + video::SColor bgcolor_bright = video::SColor(255,170,200,230); + + /* + Draw "Loading" screen + */ + /*gui::IGUIStaticText *gui_loadingtext = */ + //draw_load_screen(L"Loading and connecting...", driver, font); + + draw_load_screen(L"Loading...", driver, font); + + /* + Create server. + SharedPtr will delete it when it goes out of scope. + */ + SharedPtr server; + if(address == ""){ + draw_load_screen(L"Creating server...", driver, font); + std::cout<start(port); + } + + /* + Create client + */ + + draw_load_screen(L"Creating client...", driver, font); + std::cout<remove(); + return; + } + + /* + Attempt to connect to the server + */ + + dstream<= 10.0) + { + break; + } + + std::wostringstream ss; + ss<beginScene(true, true, video::SColor(255,0,0,0)); + guienv->drawAll(); + driver->endScene();*/ + + // Update client and server + + client.step(0.1); + + if(server != NULL) + server->step(0.1); + + // Delay a bit + sleep_ms(100); + time_counter += 0.1; + } + } + catch(con::PeerNotFoundException &e) + {} + + if(could_connect == false) + { + if(client.accessDenied()) + { + error_message = L"Access denied. Reason: " + +client.accessDeniedReason(); + std::cout<remove(); + return; + } + + /* + Create skybox + */ + float old_brightness = 1.0; + scene::ISceneNode* skybox = NULL; + update_skybox(driver, smgr, skybox, 1.0); + + /* + Create the camera node + */ + + scene::ICameraSceneNode* camera = smgr->addCameraSceneNode( + 0, // Camera parent + v3f(BS*100, BS*2, BS*100), // Look from + v3f(BS*100+1, BS*2, BS*100), // Look to + -1 // Camera ID + ); + + if(camera == NULL) + { + error_message = L"Failed to create the camera node"; + return; + } + + camera->setFOV(FOV_ANGLE); + + // Just so big a value that everything rendered is visible + camera->setFarValue(100000*BS); + + f32 camera_yaw = 0; // "right/left" + f32 camera_pitch = 0; // "up/down" + + /* + Clouds + */ + + float cloud_height = BS*100; + Clouds *clouds = NULL; + if(g_settings.getBool("enable_clouds")) + { + clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, + cloud_height, time(0)); + } + + /* + FarMesh + */ + + FarMesh *farmesh = NULL; + if(g_settings.getBool("enable_farmesh")) + { + farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client); + } + + /* + Move into game + */ + + //gui_loadingtext->remove(); + + /* + Add some gui stuff + */ + + // First line of debug text + gui::IGUIStaticText *guitext = guienv->addStaticText( + L"Minetest-c55", + core::rect(5, 5, 795, 5+text_height), + false, false); + // Second line of debug text + gui::IGUIStaticText *guitext2 = guienv->addStaticText( + L"", + core::rect(5, 5+(text_height+5)*1, 795, (5+text_height)*2), + false, false); + + // At the middle of the screen + // Object infos are shown in this + gui::IGUIStaticText *guitext_info = guienv->addStaticText( + L"", + core::rect(0,0,400,text_height+5) + v2s32(100,200), + false, false); + + // Chat text + gui::IGUIStaticText *guitext_chat = guienv->addStaticText( + L"", + core::rect(0,0,0,0), + //false, false); // Disable word wrap as of now + false, true); + //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0)); + core::list chat_lines; + + /*GUIQuickInventory *quick_inventory = new GUIQuickInventory + (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/ + /*GUIQuickInventory *quick_inventory = new GUIQuickInventory + (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/ + + // Test the text input system + /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr, + NULL))->drop();*/ + /*GUIMessageMenu *menu = + new GUIMessageMenu(guienv, guiroot, -1, + &g_menumgr, + L"Asd"); + menu->drop();*/ + + // Launch pause menu + (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback, + &g_menumgr))->drop(); + + // Enable texts + /*guitext2->setVisible(true); + guitext_info->setVisible(true); + guitext_chat->setVisible(true);*/ + + //s32 guitext_chat_pad_bottom = 70; + + /* + Some statistics are collected in these + */ + u32 drawtime = 0; + u32 beginscenetime = 0; + u32 scenetime = 0; + u32 endscenetime = 0; + + // A test + //throw con::PeerNotFoundException("lol"); + + core::list frametime_log; + + float damage_flash_timer = 0; + s16 farmesh_range = 20*MAP_BLOCKSIZE; + + bool invert_mouse = g_settings.getBool("invert_mouse"); + + /* + Main loop + */ + + bool first_loop_after_window_activation = true; + + // TODO: Convert the static interval timers to these + // Interval limiter for profiler + IntervalLimiter m_profiler_interval; + + // Time is in milliseconds + // NOTE: getRealTime() causes strange problems in wine (imprecision?) + // NOTE: So we have to use getTime() and call run()s between them + u32 lasttime = device->getTimer()->getTime(); + + while(device->run() && kill == false) + { + //std::cerr<<"frame"<disconnect_requested) + { + g_gamecallback->disconnect_requested = false; + break; + } + + if(g_gamecallback->changepassword_requested) + { + (new GUIPasswordChange(guienv, guiroot, -1, + &g_menumgr, &client))->drop(); + g_gamecallback->changepassword_requested = false; + } + + /* + Process TextureSource's queue + */ + ((TextureSource*)g_texturesource)->processQueue(); + + /* + Random calculations + */ + last_screensize = screensize; + screensize = driver->getScreenSize(); + v2s32 displaycenter(screensize.X/2,screensize.Y/2); + //bool screensize_changed = screensize != last_screensize; + + // Resize hotbar + if(screensize.Y <= 800) + hotbar_imagesize = 32; + else if(screensize.Y <= 1280) + hotbar_imagesize = 48; + else + hotbar_imagesize = 64; + + // Hilight boxes collected during the loop and displayed + core::list< core::aabbox3d > hilightboxes; + + // Info text + std::wstring infotext; + + // When screen size changes, update positions and sizes of stuff + /*if(screensize_changed) + { + v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing); + quick_inventory->updatePosition(pos); + }*/ + + //TimeTaker //timer1("//timer1"); + + // Time of frame without fps limit + float busytime; + u32 busytime_u32; + { + // not using getRealTime is necessary for wine + u32 time = device->getTimer()->getTime(); + if(time > lasttime) + busytime_u32 = time - lasttime; + else + busytime_u32 = 0; + busytime = busytime_u32 / 1000.0; + } + + //std::cout<<"busytime_u32="<getTimer()->getTime() + device->run(); + + /* + Viewing range + */ + + updateViewingRange(busytime, &client); + + /* + FPS limiter + */ + + { + float fps_max = g_settings.getFloat("fps_max"); + u32 frametime_min = 1000./fps_max; + + if(busytime_u32 < frametime_min) + { + u32 sleeptime = frametime_min - busytime_u32; + device->sleep(sleeptime); + } + } + + // Necessary for device->getTimer()->getTime() + device->run(); + + /* + Time difference calculation + */ + f32 dtime; // in seconds + + u32 time = device->getTimer()->getTime(); + if(time > lasttime) + dtime = (time - lasttime) / 1000.0; + else + dtime = 0; + lasttime = time; + + /* + Log frametime for visualization + */ + frametime_log.push_back(dtime); + if(frametime_log.size() > 100) + { + core::list::Iterator i = frametime_log.begin(); + frametime_log.erase(i); + } + + /* + Visualize frametime in terminal + */ + /*for(u32 i=0; i jitter1_max) + jitter1_max = dtime_jitter1; + counter += dtime; + if(counter > 0.0) + { + counter -= 3.0; + dtime_jitter1_max_sample = jitter1_max; + dtime_jitter1_max_fraction + = dtime_jitter1_max_sample / (dtime_avg1+0.001); + jitter1_max = 0.0; + } + } + + /* + Busytime average and jitter calculation + */ + + static f32 busytime_avg1 = 0.0; + busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02; + f32 busytime_jitter1 = busytime - busytime_avg1; + + static f32 busytime_jitter1_max_sample = 0.0; + static f32 busytime_jitter1_min_sample = 0.0; + { + static f32 jitter1_max = 0.0; + static f32 jitter1_min = 0.0; + static f32 counter = 0.0; + if(busytime_jitter1 > jitter1_max) + jitter1_max = busytime_jitter1; + if(busytime_jitter1 < jitter1_min) + jitter1_min = busytime_jitter1; + counter += dtime; + if(counter > 0.0){ + counter -= 3.0; + busytime_jitter1_max_sample = jitter1_max; + busytime_jitter1_min_sample = jitter1_min; + jitter1_max = 0.0; + jitter1_min = 0.0; + } + } + + /* + Debug info for client + */ + { + static float counter = 0.0; + counter -= dtime; + if(counter < 0) + { + counter = 30.0; + client.printDebugInfo(std::cout); + } + } + + /* + Profiler + */ + float profiler_print_interval = + g_settings.getFloat("profiler_print_interval"); + if(profiler_print_interval != 0) + { + if(m_profiler_interval.step(0.030, profiler_print_interval)) + { + dstream<<"Profiler:"<isWindowActive() == false || noMenuActive() == false) + { + input->clear(); + } + + // Input handler step() (used by the random input generator) + input->step(dtime); + + /* + Launch menus according to keys + */ + if(input->wasKeyDown(getKeySetting("keymap_inventory"))) + { + dstream< draw_spec; + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", "current_player", "main", + v2s32(0, 3), v2s32(8, 4))); + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", "current_player", "craft", + v2s32(3, 0), v2s32(3, 3))); + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", "current_player", "craftresult", + v2s32(7, 1), v2s32(1, 1))); + + menu->setDrawSpec(draw_spec); + + menu->drop(); + } + else if(input->wasKeyDown(EscapeKey)) + { + dstream<drop(); + + // Move mouse cursor on top of the disconnect button + input->setMousePos(displaycenter.X, displaycenter.Y+25); + } + else if(input->wasKeyDown(getKeySetting("keymap_chat"))) + { + TextDest *dest = new TextDestChat(&client); + + (new GUITextInputMenu(guienv, guiroot, -1, + &g_menumgr, dest, + L""))->drop(); + } + else if(input->wasKeyDown(getKeySetting("keymap_cmd"))) + { + TextDest *dest = new TextDestChat(&client); + + (new GUITextInputMenu(guienv, guiroot, -1, + &g_menumgr, dest, + L"/"))->drop(); + } + else if(input->wasKeyDown(getKeySetting("keymap_freemove"))) + { + if(g_settings.getBool("free_move")) + { + g_settings.set("free_move","false"); + chat_lines.push_back(ChatLine(L"free_move disabled")); + } + else + { + g_settings.set("free_move","true"); + chat_lines.push_back(ChatLine(L"free_move enabled")); + } + } + else if(input->wasKeyDown(getKeySetting("keymap_fastmove"))) + { + if(g_settings.getBool("fast_move")) + { + g_settings.set("fast_move","false"); + chat_lines.push_back(ChatLine(L"fast_move disabled")); + } + else + { + g_settings.set("fast_move","true"); + chat_lines.push_back(ChatLine(L"fast_move enabled")); + } + } + else if(input->wasKeyDown(getKeySetting("keymap_frametime_graph"))) + { + if(g_settings.getBool("frametime_graph")) + { + g_settings.set("frametime_graph","false"); + chat_lines.push_back(ChatLine(L"frametime_graph disabled")); + } + else + { + g_settings.set("frametime_graph","true"); + chat_lines.push_back(ChatLine(L"frametime_graph enabled")); + } + } + else if(input->wasKeyDown(getKeySetting("keymap_screenshot"))) + { + irr::video::IImage* const image = driver->createScreenShot(); + if (image) { + irr::c8 filename[256]; + snprintf(filename, 256, "%s/screenshot_%u.png", + g_settings.get("screenshot_path").c_str(), + device->getTimer()->getRealTime()); + if (driver->writeImageToFile(image, filename)) { + std::wstringstream sstr; + sstr<<"Saved screenshot to '"<drop(); + } + } + + // Item selection with mouse wheel + { + s32 wheel = input->getMouseWheel(); + u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1, + hotbar_itemcount-1); + + if(wheel < 0) + { + if(g_selected_item < max_item) + g_selected_item++; + else + g_selected_item = 0; + } + else if(wheel > 0) + { + if(g_selected_item > 0) + g_selected_item--; + else + g_selected_item = max_item; + } + } + + // Item selection + for(u16 i=0; i<10; i++) + { + const KeyPress *kp = NumberKey + (i + 1) % 10; + if(input->wasKeyDown(*kp)) + { + if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount) + { + g_selected_item = i; + + dstream<wasKeyDown(getKeySetting("keymap_rangeselect"))) + { + if(draw_control.range_all) + { + draw_control.range_all = false; + dstream<wasKeyDown(getKeySetting("keymap_print_debug_stacks"))) + { + dstream<<"-----------------------------------------" + <isKeyDown(getKeySetting("keymap_forward")), + input->isKeyDown(getKeySetting("keymap_backward")), + input->isKeyDown(getKeySetting("keymap_left")), + input->isKeyDown(getKeySetting("keymap_right")), + input->isKeyDown(getKeySetting("keymap_jump")), + input->isKeyDown(getKeySetting("keymap_special1")), + input->isKeyDown(getKeySetting("keymap_sneak")), + camera_pitch, + camera_yaw + ); + client.setPlayerControl(control); + } + + /* + Run server + */ + + if(server != NULL) + { + //TimeTaker timer("server->step(dtime)"); + server->step(dtime); + } + + /* + Process environment + */ + + { + //TimeTaker timer("client.step(dtime)"); + client.step(dtime); + //client.step(dtime_avg1); + } + + // Read client events + for(;;) + { + ClientEvent event = client.getClientEvent(); + if(event.type == CE_NONE) + { + break; + } + else if(event.type == CE_PLAYER_DAMAGE) + { + //u16 damage = event.player_damage.amount; + //dstream<<"Player damage: "<isWindowActive() && noMenuActive()) || random_input) + { + if(!random_input) + { + // Mac OSX gets upset if this is set every frame + if(device->getCursorControl()->isVisible()) + device->getCursorControl()->setVisible(false); + } + + if(first_loop_after_window_activation){ + //std::cout<<"window active, first loop"<getMousePos().X - displaycenter.X; + s32 dy = input->getMousePos().Y - displaycenter.Y; + if(invert_mouse) + dy = -dy; + //std::cout<<"window active, pos difference "<isKeyDown(irr::KEY_UP)) + dy -= dtime * keyspeed; + if(input->isKeyDown(irr::KEY_DOWN)) + dy += dtime * keyspeed; + if(input->isKeyDown(irr::KEY_LEFT)) + dx -= dtime * keyspeed; + if(input->isKeyDown(irr::KEY_RIGHT)) + dx += dtime * keyspeed;*/ + + camera_yaw -= dx*0.2; + camera_pitch += dy*0.2; + if(camera_pitch < -89.5) camera_pitch = -89.5; + if(camera_pitch > 89.5) camera_pitch = 89.5; + } + input->setMousePos(displaycenter.X, displaycenter.Y); + } + else{ + // Mac OSX gets upset if this is set every frame + if(device->getCursorControl()->isVisible() == false) + device->getCursorControl()->setVisible(true); + + //std::cout<<"window inactive"<setPosition(camera_position); + // *100.0 helps in large map coordinates + camera->setTarget(camera_position + camera_direction * 100.0); + + if(FIELD_OF_VIEW_TEST){ + client.updateCamera(v3f(0,0,0), v3f(0,0,1)); + } + else{ + //TimeTaker timer("client.updateCamera"); + client.updateCamera(camera_position, camera_direction); + } + + //timer2.stop(); + //TimeTaker //timer3("//timer3"); + + /* + Calculate what block is the crosshair pointing to + */ + + //u32 t1 = device->getTimer()->getRealTime(); + + //f32 d = 4; // max. distance + f32 d = 4; // max. distance + core::line3d shootline(camera_position, + camera_position + camera_direction * BS * (d+1)); + + MapBlockObject *selected_object = client.getSelectedObject + (d*BS, camera_position, shootline); + + ClientActiveObject *selected_active_object + = client.getSelectedActiveObject + (d*BS, camera_position, shootline); + + if(selected_object != NULL) + { + //dstream<<"Client returned selected_object != NULL"< box_on_map + = selected_object->getSelectionBoxOnMap(); + + hilightboxes.push_back(box_on_map); + + infotext = narrow_to_wide(selected_object->infoText()); + + if(input->getLeftClicked()) + { + std::cout<getBlock()->getPos(), + selected_object->getId(), g_selected_item); + } + else if(input->getRightClicked()) + { + std::cout<getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN) + { + dstream<<"Sign object right-clicked"<getBlock()->getPos(), + selected_object->getId(), + &client); + + SignObject *sign_object = (SignObject*)selected_object; + + std::wstring wtext = + narrow_to_wide(sign_object->getText()); + + (new GUITextInputMenu(guienv, guiroot, -1, + &g_menumgr, dest, + wtext))->drop(); + } + } + /* + Otherwise pass the event to the server as-is + */ + else + { + client.clickObject(1, selected_object->getBlock()->getPos(), + selected_object->getId(), g_selected_item); + } + } + } + else if(selected_active_object != NULL) + { + //dstream<<"Client returned selected_active_object != NULL"< *selection_box + = selected_active_object->getSelectionBox(); + // Box should exist because object was returned in the + // first place + assert(selection_box); + + v3f pos = selected_active_object->getPosition(); + + core::aabbox3d box_on_map( + selection_box->MinEdge + pos, + selection_box->MaxEdge + pos + ); + + hilightboxes.push_back(box_on_map); + + //infotext = narrow_to_wide("A ClientActiveObject"); + infotext = narrow_to_wide(selected_active_object->infoText()); + + if(input->getLeftClicked()) + { + std::cout<getId(), g_selected_item); + } + else if(input->getRightClicked()) + { + std::cout<getId(), g_selected_item); + } + } + else // selected_object == NULL + { + + /* + Find out which node we are pointing at + */ + + bool nodefound = false; + v3s16 nodepos; + v3s16 neighbourpos; + core::aabbox3d nodehilightbox; + + getPointedNode(&client, player_position, + camera_direction, camera_position, + nodefound, shootline, + nodepos, neighbourpos, + nodehilightbox, d); + + static float nodig_delay_counter = 0.0; + + if(nodefound) + { + static v3s16 nodepos_old(-32768,-32768,-32768); + + static float dig_time = 0.0; + static u16 dig_index = 0; + + /* + Visualize selection + */ + + hilightboxes.push_back(nodehilightbox); + + /* + Check information text of node + */ + + NodeMetadata *meta = client.getNodeMetadata(nodepos); + if(meta) + { + infotext = narrow_to_wide(meta->infoText()); + } + + //MapNode node = client.getNode(nodepos); + + /* + Handle digging + */ + + if(input->getLeftReleased()) + { + client.clearTempMod(nodepos); + dig_time = 0.0; + } + + if(nodig_delay_counter > 0.0) + { + nodig_delay_counter -= dtime; + } + else + { + if(nodepos != nodepos_old) + { + std::cout<getLeftClicked() || + (input->getLeftState() && nodepos != nodepos_old)) + { + dstream<getLeftClicked()) + { + client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0)); + } + if(input->getLeftState()) + { + MapNode n = client.getNode(nodepos); + + // Get tool name. Default is "" = bare hands + std::string toolname = ""; + InventoryList *mlist = local_inventory.getList("main"); + if(mlist != NULL) + { + InventoryItem *item = mlist->getItem(g_selected_item); + if(item && (std::string)item->getName() == "ToolItem") + { + ToolItem *titem = (ToolItem*)item; + toolname = titem->getToolName(); + } + } + + // Get digging properties for material and tool + content_t material = n.getContent(); + DiggingProperties prop = + getDiggingProperties(material, toolname); + + float dig_time_complete = 0.0; + + if(prop.diggable == false) + { + /*dstream<<"Material "<<(int)material + <<" not diggable with \"" + <= 0.001) + { + dig_index = (u16)((float)CRACK_ANIMATION_LENGTH + * dig_time/dig_time_complete); + } + // This is for torches + else + { + dig_index = CRACK_ANIMATION_LENGTH; + } + + if(dig_index < CRACK_ANIMATION_LENGTH) + { + //TimeTaker timer("client.setTempMod"); + //dstream<<"dig_index="< 0.5) + { + nodig_delay_counter = 0.5; + } + // We want a slight delay to very little + // time consuming nodes + float mindelay = 0.15; + if(nodig_delay_counter < mindelay) + { + nodig_delay_counter = mindelay; + } + } + + dig_time += dtime; + } + } + + if(input->getRightClicked()) + { + std::cout<getInventoryDrawSpecString() != "" && !random_input) + { + dstream< draw_spec; + v2s16 invsize = + GUIInventoryMenu::makeDrawSpecArrayFromString( + draw_spec, + meta->getInventoryDrawSpecString(), + current_name); + + GUIInventoryMenu *menu = + new GUIInventoryMenu(guienv, guiroot, -1, + &g_menumgr, invsize, + client.getInventoryContext(), + &client); + menu->setDrawSpec(draw_spec); + menu->drop(); + } + else if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input) + { + dstream<<"Sign node right-clicked"<getText()); + + (new GUITextInputMenu(guienv, guiroot, -1, + &g_menumgr, dest, + wtext))->drop(); + } + else + { + client.groundAction(1, nodepos, neighbourpos, g_selected_item); + } + } + + nodepos_old = nodepos; + } + else{ + } + + } // selected_object == NULL + + input->resetLeftClicked(); + input->resetRightClicked(); + + if(input->getLeftReleased()) + { + std::cout<getRightReleased()) + { + //std::cout<resetLeftReleased(); + input->resetRightReleased(); + + /* + Calculate stuff for drawing + */ + + camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y); + + u32 daynight_ratio = client.getDayNightRatio(); + u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000); + video::SColor bgcolor = video::SColor( + 255, + bgcolor_bright.getRed() * l / 255, + bgcolor_bright.getGreen() * l / 255, + bgcolor_bright.getBlue() * l / 255); + /*skycolor.getRed() * l / 255, + skycolor.getGreen() * l / 255, + skycolor.getBlue() * l / 255);*/ + + float brightness = (float)l/255.0; + + /* + Update skybox + */ + if(fabs(brightness - old_brightness) > 0.01) + update_skybox(driver, smgr, skybox, brightness); + + /* + Update coulds + */ + if(clouds) + { + clouds->step(dtime); + clouds->update(v2f(player_position.X, player_position.Z), + 0.05+brightness*0.95); + } + + /* + Update farmesh + */ + if(farmesh) + { + farmesh_range = draw_control.wanted_range * 10; + if(draw_control.range_all && farmesh_range < 500) + farmesh_range = 500; + if(farmesh_range > 1000) + farmesh_range = 1000; + + farmesh->step(dtime); + farmesh->update(v2f(player_position.X, player_position.Z), + 0.05+brightness*0.95, farmesh_range); + } + + // Store brightness value + old_brightness = brightness; + + /* + Fog + */ + + if(g_settings.getBool("enable_fog") == true) + { + f32 range; + if(farmesh) + { + range = BS*farmesh_range; + } + else + { + range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5; + if(draw_control.range_all) + range = 100000*BS; + if(range < 50*BS) + range = range * 0.5 + 25*BS; + } + + driver->setFog( + bgcolor, + video::EFT_FOG_LINEAR, + range*0.4, + range*1.0, + 0.01, + false, // pixel fog + false // range fog + ); + } + else + { + driver->setFog( + bgcolor, + video::EFT_FOG_LINEAR, + 100000*BS, + 110000*BS, + 0.01, + false, // pixel fog + false // range fog + ); + } + + + /* + Update gui stuff (0ms) + */ + + //TimeTaker guiupdatetimer("Gui updating"); + + { + static float drawtime_avg = 0; + drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05; + static float beginscenetime_avg = 0; + beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05; + static float scenetime_avg = 0; + scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05; + static float endscenetime_avg = 0; + endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05; + + char temptext[300]; + snprintf(temptext, 300, "Minetest-c55 %s (" + "R: range_all=%i" + ")" + " drawtime=%.0f, beginscenetime=%.0f" + ", scenetime=%.0f, endscenetime=%.0f", + VERSION_STRING, + draw_control.range_all, + drawtime_avg, + beginscenetime_avg, + scenetime_avg, + endscenetime_avg + ); + + guitext->setText(narrow_to_wide(temptext).c_str()); + } + + { + char temptext[300]; + snprintf(temptext, 300, + "(% .1f, % .1f, % .1f)" + " (% .3f < btime_jitter < % .3f" + ", dtime_jitter = % .1f %%" + ", v_range = %.1f)", + player_position.X/BS, + player_position.Y/BS, + player_position.Z/BS, + busytime_jitter1_min_sample, + busytime_jitter1_max_sample, + dtime_jitter1_max_fraction * 100.0, + draw_control.wanted_range + ); + + guitext2->setText(narrow_to_wide(temptext).c_str()); + } + + { + guitext_info->setText(infotext.c_str()); + } + + /* + Get chat messages from client + */ + { + // Get new messages + std::wstring message; + while(client.getChatMessage(message)) + { + chat_lines.push_back(ChatLine(message)); + /*if(chat_lines.size() > 6) + { + core::list::Iterator + i = chat_lines.begin(); + chat_lines.erase(i); + }*/ + } + // Append them to form the whole static text and throw + // it to the gui element + std::wstring whole; + // This will correspond to the line number counted from + // top to bottom, from size-1 to 0 + s16 line_number = chat_lines.size(); + // Count of messages to be removed from the top + u16 to_be_removed_count = 0; + for(core::list::Iterator + i = chat_lines.begin(); + i != chat_lines.end(); i++) + { + // After this, line number is valid for this loop + line_number--; + // Increment age + (*i).age += dtime; + /* + This results in a maximum age of 60*6 to the + lowermost line and a maximum of 6 lines + */ + float allowed_age = (6-line_number) * 60.0; + + if((*i).age > allowed_age) + { + to_be_removed_count++; + continue; + } + whole += (*i).text + L'\n'; + } + for(u16 i=0; i::Iterator + it = chat_lines.begin(); + chat_lines.erase(it); + } + guitext_chat->setText(whole.c_str()); + + // Update gui element size and position + + /*core::rect rect( + 10, + screensize.Y - guitext_chat_pad_bottom + - text_height*chat_lines.size(), + screensize.X - 10, + screensize.Y - guitext_chat_pad_bottom + );*/ + core::rect rect( + 10, + 50, + screensize.X - 10, + 50 + guitext_chat->getTextHeight() + ); + + guitext_chat->setRelativePosition(rect); + + if(chat_lines.size() == 0) + guitext_chat->setVisible(false); + else + guitext_chat->setVisible(true); + } + + /* + Inventory + */ + + static u16 old_selected_item = 65535; + if(client.getLocalInventoryUpdated() + || g_selected_item != old_selected_item) + { + client.selectPlayerItem(g_selected_item); + old_selected_item = g_selected_item; + //std::cout<<"Updating local inventory"<beginScene(true, true, bgcolor); + //driver->beginScene(false, true, bgcolor); + beginscenetime = timer.stop(true); + } + + //timer3.stop(); + + //std::cout<drawAll()"<drawAll(); + scenetime = timer.stop(true); + } + + { + //TimeTaker timer9("auxiliary drawings"); + // 0ms + + //timer9.stop(); + //TimeTaker //timer10("//timer10"); + + video::SMaterial m; + //m.Thickness = 10; + m.Thickness = 3; + m.Lighting = false; + driver->setMaterial(m); + + driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); + + for(core::list< core::aabbox3d >::Iterator i=hilightboxes.begin(); + i != hilightboxes.end(); i++) + { + /*std::cout<<"hilightbox min=" + <<"("<MinEdge.X<<","<MinEdge.Y<<","<MinEdge.Z<<")" + <<" max=" + <<"("<MaxEdge.X<<","<MaxEdge.Y<<","<MaxEdge.Z<<")" + <draw3DBox(*i, video::SColor(255,0,0,0)); + } + + /* + Frametime log + */ + if(g_settings.getBool("frametime_graph") == true) + { + s32 x = 10; + for(core::list::Iterator + i = frametime_log.begin(); + i != frametime_log.end(); + i++) + { + driver->draw2DLine(v2s32(x,50), + v2s32(x,50+(*i)*1000), + video::SColor(255,255,255,255)); + x++; + } + } + + /* + Draw crosshair + */ + driver->draw2DLine(displaycenter - core::vector2d(10,0), + displaycenter + core::vector2d(10,0), + video::SColor(255,255,255,255)); + driver->draw2DLine(displaycenter - core::vector2d(0,10), + displaycenter + core::vector2d(0,10), + video::SColor(255,255,255,255)); + + } // timer + + //timer10.stop(); + //TimeTaker //timer11("//timer11"); + + /* + Draw gui + */ + // 0-1ms + guienv->drawAll(); + + /* + Environment post fx + */ + { + client.getEnv()->drawPostFx(driver, camera_position); + } + + /* + Draw hotbar + */ + { + draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y), + hotbar_imagesize, hotbar_itemcount, &local_inventory, + client.getHP()); + } + + /* + Damage flash + */ + if(damage_flash_timer > 0.0) + { + damage_flash_timer -= dtime; + + video::SColor color(128,255,0,0); + driver->draw2DRectangle(color, + core::rect(0,0,screensize.X,screensize.Y), + NULL); + } + + /* + End scene + */ + { + TimeTaker timer("endScene"); + endSceneX(driver); + endscenetime = timer.stop(true); + } + + drawtime = drawtimer.stop(true); + + /* + End of drawing + */ + + static s16 lastFPS = 0; + //u16 fps = driver->getFPS(); + u16 fps = (1.0/dtime_avg1); + + if (lastFPS != fps) + { + core::stringw str = L"Minetest ["; + str += driver->getName(); + str += "] FPS="; + str += fps; + + device->setWindowCaption(str.c_str()); + lastFPS = fps; + } + } + + /* + Drop stuff + */ + if(clouds) + clouds->drop(); + + /* + Draw a "shutting down" screen, which will be shown while the map + generator and other stuff quits + */ + { + /*gui::IGUIStaticText *gui_shuttingdowntext = */ + draw_load_screen(L"Shutting down stuff...", driver, font); + /*driver->beginScene(true, true, video::SColor(255,0,0,0)); + guienv->drawAll(); + driver->endScene(); + gui_shuttingdowntext->remove();*/ + } +} + + diff --git a/src/game.h b/src/game.h new file mode 100644 index 0000000..a9db6c3 --- /dev/null +++ b/src/game.h @@ -0,0 +1,141 @@ +/* +Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GAME_HEADER +#define GAME_HEADER + +#include "common_irrlicht.h" +#include + +#include "keycode.h" + +class KeyList : protected core::list +{ + typedef core::list super; + typedef super::Iterator Iterator; + typedef super::ConstIterator ConstIterator; + + virtual ConstIterator find(const KeyPress &key) const + { + ConstIterator f(begin()); + ConstIterator e(end()); + while (f!=e) { + if (*f == key) + return f; + ++f; + } + return e; + } + + virtual Iterator find(const KeyPress &key) + { + Iterator f(begin()); + Iterator e(end()); + while (f!=e) { + if (*f == key) + return f; + ++f; + } + return e; + } + +public: + void clear() { super::clear(); } + + void set(const KeyPress &key) + { + if (find(key) == end()) + push_back(key); + } + + void unset(const KeyPress &key) + { + Iterator p(find(key)); + if (p != end()) + erase(p); + } + + void toggle(const KeyPress &key) + { + Iterator p(this->find(key)); + if (p != end()) + erase(p); + else + push_back(key); + } + + bool operator[](const KeyPress &key) const + { + return find(key) != end(); + } +}; + +class InputHandler +{ +public: + InputHandler() + { + } + virtual ~InputHandler() + { + } + + virtual bool isKeyDown(const KeyPress &keyCode) = 0; + virtual bool wasKeyDown(const KeyPress &keyCode) = 0; + + virtual v2s32 getMousePos() = 0; + virtual void setMousePos(s32 x, s32 y) = 0; + + virtual bool getLeftState() = 0; + virtual bool getRightState() = 0; + + virtual bool getLeftClicked() = 0; + virtual bool getRightClicked() = 0; + virtual void resetLeftClicked() = 0; + virtual void resetRightClicked() = 0; + + virtual bool getLeftReleased() = 0; + virtual bool getRightReleased() = 0; + virtual void resetLeftReleased() = 0; + virtual void resetRightReleased() = 0; + + virtual s32 getMouseWheel() = 0; + + virtual void step(float dtime) {}; + + virtual void clear() {}; +}; + +void the_game( + bool &kill, + bool random_input, + InputHandler *input, + IrrlichtDevice *device, + gui::IGUIFont* font, + std::string map_dir, + std::string playername, + std::string password, + std::string address, + u16 port, + std::wstring &error_message, + std::string configpath +); + +#endif + diff --git a/src/gettext.h b/src/gettext.h new file mode 100644 index 0000000..0e6ee0f --- /dev/null +++ b/src/gettext.h @@ -0,0 +1,49 @@ +#ifndef GETTEXT_HEADER +#include "config.h" // for USE_GETTEXT +#include + +#if USE_GETTEXT +#include +#else +#define gettext(String) String +#endif + +#define _(String) gettext(String) +#define gettext_noop(String) String +#define N_(String) gettext_noop (String) + +inline void init_gettext(const char *path) { +#if USE_GETTEXT + // don't do this if MSVC compiler is used, it gives an assertion fail + #ifndef _MSC_VER + setlocale(LC_MESSAGES, ""); + #endif + bindtextdomain(PROJECT_NAME, path); + textdomain(PROJECT_NAME); +#endif +} + +inline wchar_t* chartowchar_t(const char *str) +{ + size_t l = strlen(str)+1; + wchar_t* nstr = new wchar_t[l]; + mbstowcs(nstr, str, l); + return nstr; +} + +inline wchar_t* wgettext(const char *str) +{ + return chartowchar_t(gettext(str)); +} + +inline void changeCtype(const char *l) +{ + char *ret = NULL; + ret = setlocale(LC_CTYPE, l); + if(ret == NULL) + std::cout<<"locale could not be set"< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GETTIME_HEADER +#define GETTIME_HEADER + +#include "common_irrlicht.h" + +/* + Get a millisecond counter value. + Precision depends on implementation. + Overflows at any value above 10000000. + + Implementation of this is done in: + Normal build: main.cpp + Server build: servermain.cpp +*/ +extern u32 getTimeMs(); + +/* + Timestamp stuff +*/ + +#include +#include + +inline std::string getTimestamp() +{ + time_t t = time(NULL); + // This is not really thread-safe but it won't break anything + // except its own output, so just go with it. + struct tm *tm = localtime(&t); + char cs[20]; + strftime(cs, 20, "%H:%M:%S", tm); + return cs; +} + + +#endif diff --git a/src/guiInventoryMenu.cpp b/src/guiInventoryMenu.cpp new file mode 100644 index 0000000..bf955a4 --- /dev/null +++ b/src/guiInventoryMenu.cpp @@ -0,0 +1,510 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + + +#include "guiInventoryMenu.h" +#include "constants.h" +#include "keycode.h" +#include "strfnd.h" + +void drawInventoryItem(video::IVideoDriver *driver, + gui::IGUIFont *font, + InventoryItem *item, core::rect rect, + const core::rect *clip) +{ + if(item == NULL) + return; + + video::ITexture *texture = NULL; + texture = item->getImage(); + + if(texture != NULL) + { + const video::SColor color(255,255,255,255); + const video::SColor colors[] = {color,color,color,color}; + driver->draw2DImage(texture, rect, + core::rect(core::position2d(0,0), + core::dimension2di(texture->getOriginalSize())), + clip, colors, true); + } + else + { + video::SColor bgcolor(255,50,50,128); + driver->draw2DRectangle(bgcolor, rect, clip); + } + + if(font != NULL) + { + std::string text = item->getText(); + if(font && text != "") + { + v2u32 dim = font->getDimension(narrow_to_wide(text).c_str()); + v2s32 sdim(dim.X,dim.Y); + + core::rect rect2( + /*rect.UpperLeftCorner, + core::dimension2d(rect.getWidth(), 15)*/ + rect.LowerRightCorner - sdim, + sdim + ); + + video::SColor bgcolor(128,0,0,0); + driver->draw2DRectangle(bgcolor, rect2, clip); + + font->draw(text.c_str(), rect2, + video::SColor(255,255,255,255), false, false, + clip); + } + } +} + +/* + GUIInventoryMenu +*/ + +GUIInventoryMenu::GUIInventoryMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + v2s16 menu_size, + InventoryContext *c, + InventoryManager *invmgr + ): + GUIModalMenu(env, parent, id, menumgr), + m_menu_size(menu_size), + m_c(c), + m_invmgr(invmgr) +{ + m_selected_item = NULL; +} + +GUIInventoryMenu::~GUIInventoryMenu() +{ + removeChildren(); + + if(m_selected_item) + delete m_selected_item; +} + +void GUIInventoryMenu::removeChildren() +{ + const core::list &children = getChildren(); + core::list children_copy; + for(core::list::ConstIterator + i = children.begin(); i != children.end(); i++) + { + children_copy.push_back(*i); + } + for(core::list::Iterator + i = children_copy.begin(); + i != children_copy.end(); i++) + { + (*i)->remove(); + } + /*{ + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + e->remove(); + }*/ +} + +void GUIInventoryMenu::regenerateGui(v2u32 screensize) +{ + // Remove children + removeChildren(); + + /*padding = v2s32(24,24); + spacing = v2s32(60,56); + imgsize = v2s32(48,48);*/ + + padding = v2s32(screensize.Y/40, screensize.Y/40); + spacing = v2s32(screensize.Y/12, screensize.Y/13); + imgsize = v2s32(screensize.Y/15, screensize.Y/15); + + s32 helptext_h = 15; + + v2s32 size( + padding.X*2+spacing.X*(m_menu_size.X-1)+imgsize.X, + padding.Y*2+spacing.Y*(m_menu_size.Y-1)+imgsize.Y + helptext_h + ); + + core::rect rect( + screensize.X/2 - size.X/2, + screensize.Y/2 - size.Y/2, + screensize.X/2 + size.X/2, + screensize.Y/2 + size.Y/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 basepos = getBasePos(); + + m_draw_spec.clear(); + for(u16 i=0; i rect(0, 0, size.X-padding.X*2, helptext_h); + rect = rect + v2s32(size.X/2 - rect.getWidth()/2, + size.Y-rect.getHeight()-15); + const wchar_t *text = + L"Left click: Move all items, Right click: Move single item"; + Environment->addStaticText(text, rect, false, true, this, 256); + } +} + +GUIInventoryMenu::ItemSpec GUIInventoryMenu::getItemAtPos(v2s32 p) const +{ + core::rect imgrect(0,0,imgsize.X,imgsize.Y); + + for(u32 i=0; i rect = imgrect + s.pos + p0; + if(rect.isPointInside(p)) + { + return ItemSpec(s.inventoryname, s.listname, i); + } + } + } + + return ItemSpec("", "", -1); +} + +void GUIInventoryMenu::drawList(const ListDrawSpec &s) +{ + video::IVideoDriver* driver = Environment->getVideoDriver(); + + // Get font + gui::IGUIFont *font = NULL; + gui::IGUISkin* skin = Environment->getSkin(); + if (skin) + font = skin->getFont(); + + Inventory *inv = m_invmgr->getInventory(m_c, s.inventoryname); + assert(inv); + InventoryList *ilist = inv->getList(s.listname); + + core::rect imgrect(0,0,imgsize.X,imgsize.Y); + + for(s32 i=0; i rect = imgrect + s.pos + p; + InventoryItem *item = NULL; + if(ilist) + item = ilist->getItem(i); + + if(m_selected_item != NULL && m_selected_item->listname == s.listname + && m_selected_item->i == i) + { + /*s32 border = imgsize.X/12; + driver->draw2DRectangle(video::SColor(255,192,192,192), + core::rect(rect.UpperLeftCorner - v2s32(1,1)*border, + rect.LowerRightCorner + v2s32(1,1)*border), + NULL); + driver->draw2DRectangle(video::SColor(255,0,0,0), + core::rect(rect.UpperLeftCorner - v2s32(1,1)*((border+1)/2), + rect.LowerRightCorner + v2s32(1,1)*((border+1)/2)), + NULL);*/ + s32 border = 2; + driver->draw2DRectangle(video::SColor(255,255,0,0), + core::rect(rect.UpperLeftCorner - v2s32(1,1)*border, + rect.LowerRightCorner + v2s32(1,1)*border), + &AbsoluteClippingRect); + } + + video::SColor bgcolor(255,128,128,128); + driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect); + + if(item) + { + drawInventoryItem(driver, font, item, + rect, &AbsoluteClippingRect); + } + + } +} + +void GUIInventoryMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); + + /* + Draw items + */ + + for(u32 i=0; i= 0) + { + v2s32 p(event.MouseInput.X, event.MouseInput.Y); + //dstream<<"Mouse down at p=("<getInventory(m_c, + m_selected_item->inventoryname); + Inventory *inv_to = m_invmgr->getInventory(m_c, + s.inventoryname); + assert(inv_from); + assert(inv_to); + InventoryList *list_from = + inv_from->getList(m_selected_item->listname); + InventoryList *list_to = + inv_to->getList(s.listname); + if(list_from == NULL) + dstream<<"from list doesn't exist"<getItem(m_selected_item->i) != NULL) + { + dstream<<"Handing IACTION_MOVE to manager"<count = amount; + a->from_inv = m_selected_item->inventoryname; + a->from_list = m_selected_item->listname; + a->from_i = m_selected_item->i; + a->to_inv = s.inventoryname; + a->to_list = s.listname; + a->to_i = s.i; + //ispec.actions->push_back(a); + m_invmgr->inventoryAction(a); + + if(list_from->getItem(m_selected_item->i)->getCount()==1) + source_empties = true; + } + // Remove selection if target was left-clicked or source + // slot was emptied + if(amount == 0 || source_empties) + { + delete m_selected_item; + m_selected_item = NULL; + } + } + else + { + /* + Select if non-NULL + */ + Inventory *inv = m_invmgr->getInventory(m_c, + s.inventoryname); + assert(inv); + InventoryList *list = inv->getList(s.listname); + if(list->getItem(s.i) != NULL) + { + m_selected_item = new ItemSpec(s); + } + } + } + else + { + if(m_selected_item) + { + delete m_selected_item; + m_selected_item = NULL; + } + } + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUIInventoryMenu: Not allowing focus change." + <getID()) + { + case 256: // continue + setVisible(false); + break; + case 257: // exit + dev->closeDevice(); + break; + }*/ + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + +/* + Here is an example traditional set-up sequence for a DrawSpec list: + + std::string furnace_inv_id = "nodemetadata:0,1,2"; + core::array draw_spec; + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", furnace_inv_id, "fuel", + v2s32(2, 3), v2s32(1, 1))); + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", furnace_inv_id, "src", + v2s32(2, 1), v2s32(1, 1))); + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", furnace_inv_id, "dst", + v2s32(5, 1), v2s32(2, 2))); + draw_spec.push_back(GUIInventoryMenu::DrawSpec( + "list", "current_player", "main", + v2s32(0, 5), v2s32(8, 4))); + setDrawSpec(draw_spec); + + Here is the string for creating the same DrawSpec list (a single line, + spread to multiple lines here): + + GUIInventoryMenu::makeDrawSpecArrayFromString( + draw_spec, + "nodemetadata:0,1,2", + "invsize[8,9;]" + "list[current_name;fuel;2,3;1,1;]" + "list[current_name;src;2,1;1,1;]" + "list[current_name;dst;5,1;2,2;]" + "list[current_player;main;0,5;8,4;]"); + + Returns inventory menu size defined by invsize[]. +*/ +v2s16 GUIInventoryMenu::makeDrawSpecArrayFromString( + core::array &draw_spec, + const std::string &data, + const std::string ¤t_name) +{ + v2s16 invsize(8,9); + Strfnd f(data); + while(f.atend() == false) + { + std::string type = trim(f.next("[")); + //dstream<<"type="< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + + +#ifndef GUIINVENTORYMENU_HEADER +#define GUIINVENTORYMENU_HEADER + +#include "common_irrlicht.h" +#include "inventory.h" +#include "utility.h" +#include "modalMenu.h" + +void drawInventoryItem(video::IVideoDriver *driver, + gui::IGUIFont *font, + InventoryItem *item, core::rect rect, + const core::rect *clip); + +class GUIInventoryMenu : public GUIModalMenu +{ + struct ItemSpec + { + ItemSpec() + { + i = -1; + } + ItemSpec(const std::string &a_inventoryname, + const std::string &a_listname, + s32 a_i) + { + inventoryname = a_inventoryname; + listname = a_listname; + i = a_i; + } + bool isValid() const + { + return i != -1; + } + + std::string inventoryname; + std::string listname; + s32 i; + }; + + struct ListDrawSpec + { + ListDrawSpec() + { + } + ListDrawSpec(const std::string &a_inventoryname, + const std::string &a_listname, + v2s32 a_pos, v2s32 a_geom) + { + inventoryname = a_inventoryname; + listname = a_listname; + pos = a_pos; + geom = a_geom; + } + + std::string inventoryname; + std::string listname; + v2s32 pos; + v2s32 geom; + }; +public: + struct DrawSpec + { + DrawSpec() + { + } + DrawSpec(const std::string &a_type, + const std::string &a_name, + const std::string &a_subname, + v2s32 a_pos, + v2s32 a_geom) + { + type = a_type; + name = a_name; + subname = a_subname; + pos = a_pos; + geom = a_geom; + } + + std::string type; + std::string name; + std::string subname; + v2s32 pos; + v2s32 geom; + }; + + // See .cpp for format + static v2s16 makeDrawSpecArrayFromString( + core::array &draw_spec, + const std::string &data, + const std::string ¤t_name); + + GUIInventoryMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + v2s16 menu_size, + InventoryContext *c, + InventoryManager *invmgr + ); + ~GUIInventoryMenu(); + + void setDrawSpec(core::array &init_draw_spec) + { + m_init_draw_spec = init_draw_spec; + } + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + ItemSpec getItemAtPos(v2s32 p) const; + void drawList(const ListDrawSpec &s); + void drawMenu(); + + bool OnEvent(const SEvent& event); + +protected: + v2s32 getBasePos() const + { + return padding + AbsoluteRect.UpperLeftCorner; + } + + v2s16 m_menu_size; + + v2s32 padding; + v2s32 spacing; + v2s32 imgsize; + + InventoryContext *m_c; + InventoryManager *m_invmgr; + + core::array m_init_draw_spec; + core::array m_draw_spec; + + ItemSpec *m_selected_item; +}; + +#endif + diff --git a/src/guiKeyChangeMenu.cpp b/src/guiKeyChangeMenu.cpp new file mode 100644 index 0000000..d6de114 --- /dev/null +++ b/src/guiKeyChangeMenu.cpp @@ -0,0 +1,625 @@ +/* + Minetest-c55 + Copyright (C) 2010-11 celeron55, Perttu Ahola + Copyright (C) 2011 Ciaran Gultnieks + Copyright (C) 2011 teddydestodes + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "guiKeyChangeMenu.h" +#include "debug.h" +#include "serialization.h" +#include "main.h" +#include + +GUIKeyChangeMenu::GUIKeyChangeMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, IMenuManager *menumgr) : + GUIModalMenu(env, parent, id, menumgr) +{ + activeKey = -1; + init_keys(); +} + +GUIKeyChangeMenu::~GUIKeyChangeMenu() +{ + removeChildren(); +} + +void GUIKeyChangeMenu::removeChildren() +{ + const core::list &children = getChildren(); + core::list children_copy; + for (core::list::ConstIterator i = children.begin(); i + != children.end(); i++) + { + children_copy.push_back(*i); + } + for (core::list::Iterator i = children_copy.begin(); i + != children_copy.end(); i++) + { + (*i)->remove(); + } +} + +void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) +{ + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + + v2s32 size(620, 430); + + core::rect < s32 > rect(screensize.X / 2 - size.X / 2, + screensize.Y / 2 - size.Y / 2, screensize.X / 2 + size.X / 2, + screensize.Y / 2 + size.Y / 2); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 topleft(0, 0); + changeCtype(""); + { + core::rect < s32 > rect(0, 0, 125, 20); + rect += topleft + v2s32(25, 3); + //gui::IGUIStaticText *t = + Environment->addStaticText(wgettext("KEYBINDINGS"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + v2s32 offset(25, 40); + // buttons + + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Forward"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->forward = Environment->addButton(rect, this, + GUI_ID_KEY_FORWARD_BUTTON, + wgettext(key_forward.name())); + } + + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Backward"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->backward = Environment->addButton(rect, this, + GUI_ID_KEY_BACKWARD_BUTTON, + wgettext(key_backward.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Left"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->left = Environment->addButton(rect, this, GUI_ID_KEY_LEFT_BUTTON, + wgettext(key_left.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Right"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->right = Environment->addButton(rect, this, + GUI_ID_KEY_RIGHT_BUTTON, + wgettext(key_right.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Use"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->use = Environment->addButton(rect, this, GUI_ID_KEY_USE_BUTTON, + wgettext(key_use.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Sneak"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->sneak = Environment->addButton(rect, this, + GUI_ID_KEY_SNEAK_BUTTON, + wgettext(key_sneak.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Jump"), rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->jump = Environment->addButton(rect, this, GUI_ID_KEY_JUMP_BUTTON, + wgettext(key_jump.name())); + } + + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Inventory"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->inventory = Environment->addButton(rect, this, + GUI_ID_KEY_INVENTORY_BUTTON, + wgettext(key_inventory.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Chat"), rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->chat = Environment->addButton(rect, this, GUI_ID_KEY_CHAT_BUTTON, + wgettext(key_chat.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Command"), rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->cmd = Environment->addButton(rect, this, GUI_ID_KEY_CMD_BUTTON, + wgettext(key_cmd.name())); + } + + + //next col + offset = v2s32(250, 40); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Toggle fly"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->fly = Environment->addButton(rect, this, GUI_ID_KEY_FLY_BUTTON, + wgettext(key_fly.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Toggle fast"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->fast = Environment->addButton(rect, this, GUI_ID_KEY_FAST_BUTTON, + wgettext(key_fast.name())); + } + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Range select"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->range = Environment->addButton(rect, this, + GUI_ID_KEY_RANGE_BUTTON, + wgettext(key_range.name())); + } + + offset += v2s32(0, 25); + { + core::rect < s32 > rect(0, 0, 100, 20); + rect += topleft + v2s32(offset.X, offset.Y); + Environment->addStaticText(wgettext("Print stacks"), + rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(offset.X + 105, offset.Y - 5); + this->dump = Environment->addButton(rect, this, GUI_ID_KEY_DUMP_BUTTON, + wgettext(key_dump.name())); + } + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(size.X - 100 - 20, size.Y - 40); + Environment->addButton(rect, this, GUI_ID_BACK_BUTTON, + wgettext("Save")); + } + { + core::rect < s32 > rect(0, 0, 100, 30); + rect += topleft + v2s32(size.X - 100 - 20 - 100 - 20, size.Y - 40); + Environment->addButton(rect, this, GUI_ID_ABORT_BUTTON, + wgettext("Cancel")); + } + changeCtype("C"); +} + +void GUIKeyChangeMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140, 0, 0, 0); + + { + core::rect < s32 > rect(0, 0, 620, 620); + rect += AbsoluteRect.UpperLeftCorner; + driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect); + } + + gui::IGUIElement::draw(); +} + +bool GUIKeyChangeMenu::acceptInput() +{ + g_settings.set("keymap_forward", key_forward.sym()); + g_settings.set("keymap_backward", key_backward.sym()); + g_settings.set("keymap_left", key_left.sym()); + g_settings.set("keymap_right", key_right.sym()); + g_settings.set("keymap_jump", key_jump.sym()); + g_settings.set("keymap_sneak", key_sneak.sym()); + g_settings.set("keymap_inventory", key_inventory.sym()); + g_settings.set("keymap_chat", key_chat.sym()); + g_settings.set("keymap_cmd", key_cmd.sym()); + g_settings.set("keymap_rangeselect", key_range.sym()); + g_settings.set("keymap_freemove", key_fly.sym()); + g_settings.set("keymap_fastmove", key_fast.sym()); + g_settings.set("keymap_special1", key_use.sym()); + g_settings.set("keymap_print_debug_stacks", key_dump.sym()); + clearKeyCache(); + return true; +} +void GUIKeyChangeMenu::init_keys() +{ + key_forward = getKeySetting("keymap_forward"); + key_backward = getKeySetting("keymap_backward"); + key_left = getKeySetting("keymap_left"); + key_right = getKeySetting("keymap_right"); + key_jump = getKeySetting("keymap_jump"); + key_sneak = getKeySetting("keymap_sneak"); + key_inventory = getKeySetting("keymap_inventory"); + key_chat = getKeySetting("keymap_chat"); + key_cmd = getKeySetting("keymap_cmd"); + key_range = getKeySetting("keymap_rangeselect"); + key_fly = getKeySetting("keymap_freemove"); + key_fast = getKeySetting("keymap_fastmove"); + key_use = getKeySetting("keymap_special1"); + key_dump = getKeySetting("keymap_print_debug_stacks"); +} + +bool GUIKeyChangeMenu::resetMenu() +{ + if (activeKey >= 0) + { + switch (activeKey) + { + case GUI_ID_KEY_FORWARD_BUTTON: + this->forward->setText( + wgettext(key_forward.name())); + break; + case GUI_ID_KEY_BACKWARD_BUTTON: + this->backward->setText( + wgettext(key_backward.name())); + break; + case GUI_ID_KEY_LEFT_BUTTON: + this->left->setText(wgettext(key_left.name())); + break; + case GUI_ID_KEY_RIGHT_BUTTON: + this->right->setText(wgettext(key_right.name())); + break; + case GUI_ID_KEY_JUMP_BUTTON: + this->jump->setText(wgettext(key_jump.name())); + break; + case GUI_ID_KEY_SNEAK_BUTTON: + this->sneak->setText(wgettext(key_sneak.name())); + break; + case GUI_ID_KEY_INVENTORY_BUTTON: + this->inventory->setText( + wgettext(key_inventory.name())); + break; + case GUI_ID_KEY_CHAT_BUTTON: + this->chat->setText(wgettext(key_chat.name())); + break; + case GUI_ID_KEY_CMD_BUTTON: + this->cmd->setText(wgettext(key_cmd.name())); + break; + case GUI_ID_KEY_RANGE_BUTTON: + this->range->setText(wgettext(key_range.name())); + break; + case GUI_ID_KEY_FLY_BUTTON: + this->fly->setText(wgettext(key_fly.name())); + break; + case GUI_ID_KEY_FAST_BUTTON: + this->fast->setText(wgettext(key_fast.name())); + break; + case GUI_ID_KEY_USE_BUTTON: + this->use->setText(wgettext(key_use.name())); + break; + case GUI_ID_KEY_DUMP_BUTTON: + this->dump->setText(wgettext(key_dump.name())); + break; + } + activeKey = -1; + return false; + } + return true; +} +bool GUIKeyChangeMenu::OnEvent(const SEvent& event) +{ + if (event.EventType == EET_KEY_INPUT_EVENT && activeKey >= 0 + && event.KeyInput.PressedDown) + { + changeCtype(""); + KeyPress kp(event.KeyInput); + + if (activeKey == GUI_ID_KEY_FORWARD_BUTTON) + { + this->forward->setText(wgettext(kp.name())); + this->key_forward = kp; + } + else if (activeKey == GUI_ID_KEY_BACKWARD_BUTTON) + { + this->backward->setText(wgettext(kp.name())); + this->key_backward = kp; + } + else if (activeKey == GUI_ID_KEY_LEFT_BUTTON) + { + this->left->setText(wgettext(kp.name())); + this->key_left = kp; + } + else if (activeKey == GUI_ID_KEY_RIGHT_BUTTON) + { + this->right->setText(wgettext(kp.name())); + this->key_right = kp; + } + else if (activeKey == GUI_ID_KEY_JUMP_BUTTON) + { + this->jump->setText(wgettext(kp.name())); + this->key_jump = kp; + } + else if (activeKey == GUI_ID_KEY_SNEAK_BUTTON) + { + this->sneak->setText(wgettext(kp.name())); + this->key_sneak = kp; + } + else if (activeKey == GUI_ID_KEY_INVENTORY_BUTTON) + { + this->inventory->setText(wgettext(kp.name())); + this->key_inventory = kp; + } + else if (activeKey == GUI_ID_KEY_CHAT_BUTTON) + { + this->chat->setText(wgettext(kp.name())); + this->key_chat = kp; + } + else if (activeKey == GUI_ID_KEY_CMD_BUTTON) + { + this->cmd->setText(wgettext(kp.name())); + this->key_cmd = kp; + } + else if (activeKey == GUI_ID_KEY_RANGE_BUTTON) + { + this->range->setText(wgettext(kp.name())); + this->key_range = kp; + } + else if (activeKey == GUI_ID_KEY_FLY_BUTTON) + { + this->fly->setText(wgettext(kp.name())); + this->key_fly = kp; + } + else if (activeKey == GUI_ID_KEY_FAST_BUTTON) + { + this->fast->setText(wgettext(kp.name())); + this->key_fast = kp; + } + else if (activeKey == GUI_ID_KEY_USE_BUTTON) + { + this->use->setText(wgettext(kp.name())); + this->key_use = kp; + } + else if (activeKey == GUI_ID_KEY_DUMP_BUTTON) + { + this->dump->setText(wgettext(kp.name())); + this->key_dump = kp; + } + changeCtype("C"); + activeKey = -1; + return true; + } + if (event.EventType == EET_GUI_EVENT) + { + if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if (!canTakeFocus(event.GUIEvent.Element)) + { + dstream << "GUIMainMenu: Not allowing focus change." + << std::endl; + // Returning true disables focus change + return true; + } + } + if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) + { + if(event.GUIEvent.Caller->getID() != GUI_ID_BACK_BUTTON && + event.GUIEvent.Caller->getID() != GUI_ID_ABORT_BUTTON) + { + changeCtype(""); + } + + switch (event.GUIEvent.Caller->getID()) + { + case GUI_ID_BACK_BUTTON: //back + acceptInput(); + quitMenu(); + return true; + case GUI_ID_ABORT_BUTTON: //abort + quitMenu(); + return true; + case GUI_ID_KEY_FORWARD_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->forward->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_BACKWARD_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->backward->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_LEFT_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->left->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_RIGHT_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->right->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_USE_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->use->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_FLY_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->fly->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_FAST_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->fast->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_JUMP_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->jump->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_CHAT_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->chat->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_CMD_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->cmd->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_SNEAK_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->sneak->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_INVENTORY_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->inventory->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_DUMP_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->dump->setText(wgettext("press Key")); + break; + case GUI_ID_KEY_RANGE_BUTTON: + resetMenu(); + activeKey = event.GUIEvent.Caller->getID(); + this->range->setText(wgettext("press Key")); + break; + } + //Buttons + changeCtype("C"); + + } + } + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiKeyChangeMenu.h b/src/guiKeyChangeMenu.h new file mode 100644 index 0000000..2e8773a --- /dev/null +++ b/src/guiKeyChangeMenu.h @@ -0,0 +1,111 @@ +/* + Minetest-c55 + Copyright (C) 2010-11 celeron55, Perttu Ahola + Copyright (C) 2011 Ciaran Gultnieks + Copyright (C) 2011 teddydestodes + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifndef GUIKEYCHANGEMENU_HEADER +#define GUIKEYCHANGEMENU_HEADER + +#include "common_irrlicht.h" +#include "utility.h" +#include "modalMenu.h" +#include "client.h" +#include "gettext.h" +#include "keycode.h" +#include + +enum +{ + GUI_ID_BACK_BUTTON = 101, GUI_ID_ABORT_BUTTON, GUI_ID_SCROLL_BAR, + //buttons + GUI_ID_KEY_FORWARD_BUTTON, + GUI_ID_KEY_BACKWARD_BUTTON, + GUI_ID_KEY_LEFT_BUTTON, + GUI_ID_KEY_RIGHT_BUTTON, + GUI_ID_KEY_USE_BUTTON, + GUI_ID_KEY_FLY_BUTTON, + GUI_ID_KEY_FAST_BUTTON, + GUI_ID_KEY_JUMP_BUTTON, + GUI_ID_KEY_CHAT_BUTTON, + GUI_ID_KEY_CMD_BUTTON, + GUI_ID_KEY_SNEAK_BUTTON, + GUI_ID_KEY_INVENTORY_BUTTON, + GUI_ID_KEY_DUMP_BUTTON, + GUI_ID_KEY_RANGE_BUTTON +}; + +class GUIKeyChangeMenu: public GUIModalMenu +{ +public: + GUIKeyChangeMenu(gui::IGUIEnvironment* env, gui::IGUIElement* parent, + s32 id, IMenuManager *menumgr); + ~GUIKeyChangeMenu(); + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + void drawMenu(); + + bool acceptInput(); + + bool OnEvent(const SEvent& event); + +private: + + void init_keys(); + + bool resetMenu(); + + gui::IGUIButton *forward; + gui::IGUIButton *backward; + gui::IGUIButton *left; + gui::IGUIButton *right; + gui::IGUIButton *use; + gui::IGUIButton *sneak; + gui::IGUIButton *jump; + gui::IGUIButton *inventory; + gui::IGUIButton *fly; + gui::IGUIButton *fast; + gui::IGUIButton *range; + gui::IGUIButton *dump; + gui::IGUIButton *chat; + gui::IGUIButton *cmd; + + s32 activeKey; + KeyPress key_forward; + KeyPress key_backward; + KeyPress key_left; + KeyPress key_right; + KeyPress key_use; + KeyPress key_sneak; + KeyPress key_jump; + KeyPress key_inventory; + KeyPress key_fly; + KeyPress key_fast; + KeyPress key_range; + KeyPress key_chat; + KeyPress key_cmd; + KeyPress key_dump; +}; + +#endif + diff --git a/src/guiMainMenu.cpp b/src/guiMainMenu.cpp new file mode 100644 index 0000000..fde71e4 --- /dev/null +++ b/src/guiMainMenu.cpp @@ -0,0 +1,440 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiMainMenu.h" +#include "guiKeyChangeMenu.h" +#include "debug.h" +#include "serialization.h" +#include + + + +#include "gettext.h" + +GUIMainMenu::GUIMainMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + MainMenuData *data, + IGameCallback *gamecallback +): + GUIModalMenu(env, parent, id, menumgr), + m_data(data), + m_accepted(false), + m_gamecallback(gamecallback) +{ + assert(m_data); + this->env = env; + this->parent = parent; + this->id = id; + this->menumgr = menumgr; +} + +GUIMainMenu::~GUIMainMenu() +{ + removeChildren(); +} + +void GUIMainMenu::removeChildren() +{ + const core::list &children = getChildren(); + core::list children_copy; + for(core::list::ConstIterator + i = children.begin(); i != children.end(); i++) + { + children_copy.push_back(*i); + } + for(core::list::Iterator + i = children_copy.begin(); + i != children_copy.end(); i++) + { + (*i)->remove(); + } +} + +void GUIMainMenu::regenerateGui(v2u32 screensize) +{ + std::wstring text_name; + std::wstring text_address; + std::wstring text_port; + bool creative_mode; + bool enable_damage; + bool fancy_trees; + bool smooth_lighting; + + // Client options + { + gui::IGUIElement *e = getElementFromId(GUI_ID_NAME_INPUT); + if(e != NULL) + text_name = e->getText(); + else + text_name = m_data->name; + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_ADDRESS_INPUT); + if(e != NULL) + text_address = e->getText(); + else + text_address = m_data->address; + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_PORT_INPUT); + if(e != NULL) + text_port = e->getText(); + else + text_port = m_data->port; + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_FANCYTREE_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + fancy_trees = ((gui::IGUICheckBox*)e)->isChecked(); + else + fancy_trees = m_data->fancy_trees; + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_SMOOTH_LIGHTING_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + smooth_lighting = ((gui::IGUICheckBox*)e)->isChecked(); + else + smooth_lighting = m_data->smooth_lighting; + } + + // Server options + { + gui::IGUIElement *e = getElementFromId(GUI_ID_CREATIVE_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + creative_mode = ((gui::IGUICheckBox*)e)->isChecked(); + else + creative_mode = m_data->creative_mode; + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_DAMAGE_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + enable_damage = ((gui::IGUICheckBox*)e)->isChecked(); + else + enable_damage = m_data->enable_damage; + } + + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + + v2s32 size(620, 430); + + core::rect rect( + screensize.X/2 - size.X/2, + screensize.Y/2 - size.Y/2, + screensize.X/2 + size.X/2, + screensize.Y/2 + size.Y/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + //v2s32 size = rect.getSize(); + + /* + Add stuff + */ + + /* + Client section + */ + + v2s32 topleft_client(40, 0); + v2s32 size_client = size - v2s32(40, 0); + + changeCtype(""); + { + core::rect rect(0, 0, 20, 125); + rect += topleft_client + v2s32(-15, 60); + const wchar_t *text = L"C\nL\nI\nE\nN\nT"; + //gui::IGUIStaticText *t = + Environment->addStaticText(text, rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + // Nickname + password + { + core::rect rect(0, 0, 110, 20); + rect += topleft_client + v2s32(35, 50+6); + Environment->addStaticText(wgettext("Name/Password"), + rect, false, true, this, -1); + } + changeCtype("C"); + { + core::rect rect(0, 0, 230, 30); + rect += topleft_client + v2s32(160, 50); + gui::IGUIElement *e = + Environment->addEditBox(text_name.c_str(), rect, true, this, GUI_ID_NAME_INPUT); + if(text_name == L"") + Environment->setFocus(e); + } + { + core::rect rect(0, 0, 120, 30); + rect += topleft_client + v2s32(size_client.X-60-100, 50); + gui::IGUIEditBox *e = + Environment->addEditBox(L"", rect, true, this, 264); + e->setPasswordBox(true); + if(text_name != L"" && text_address != L"") + Environment->setFocus(e); + + } + changeCtype(""); + // Address + port + { + core::rect rect(0, 0, 110, 20); + rect += topleft_client + v2s32(35, 100+6); + Environment->addStaticText(wgettext("Address/Port"), + rect, false, true, this, -1); + } + changeCtype("C"); + { + core::rect rect(0, 0, 230, 30); + rect += topleft_client + v2s32(160, 100); + gui::IGUIElement *e = + Environment->addEditBox(text_address.c_str(), rect, true, this, GUI_ID_ADDRESS_INPUT); + if(text_name != L"" && text_address == L"") + Environment->setFocus(e); + } + { + core::rect rect(0, 0, 120, 30); + //rect += topleft_client + v2s32(160+250+20, 125); + rect += topleft_client + v2s32(size_client.X-60-100, 100); + Environment->addEditBox(text_port.c_str(), rect, true, this, GUI_ID_PORT_INPUT); + } + changeCtype(""); + { + core::rect rect(0, 0, 400, 20); + rect += topleft_client + v2s32(160, 100+35); + Environment->addStaticText(wgettext("Leave address blank to start a local server."), + rect, false, true, this, -1); + } + { + core::rect rect(0, 0, 250, 30); + rect += topleft_client + v2s32(35, 150); + Environment->addCheckBox(fancy_trees, rect, this, GUI_ID_FANCYTREE_CB, + wgettext("Fancy trees")); + } + { + core::rect rect(0, 0, 250, 30); + rect += topleft_client + v2s32(35, 150+30); + Environment->addCheckBox(smooth_lighting, rect, this, GUI_ID_SMOOTH_LIGHTING_CB, + wgettext("Smooth Lighting")); + } + // Start game button + { + core::rect rect(0, 0, 180, 30); + //rect += topleft_client + v2s32(size_client.X/2-180/2, 225-30/2); + rect += topleft_client + v2s32(size_client.X-180-40, 150+25); + Environment->addButton(rect, this, GUI_ID_JOIN_GAME_BUTTON, + wgettext("Start Game / Connect")); + } + + // Key change button + { + core::rect rect(0, 0, 100, 30); + //rect += topleft_client + v2s32(size_client.X/2-180/2, 225-30/2); + rect += topleft_client + v2s32(size_client.X-180-40-100-20, 150+25); + Environment->addButton(rect, this, GUI_ID_CHANGE_KEYS_BUTTON, + wgettext("Change keys")); + } + /* + Server section + */ + + v2s32 topleft_server(40, 250); + v2s32 size_server = size - v2s32(40, 0); + + { + core::rect rect(0, 0, 20, 125); + rect += topleft_server + v2s32(-15, 40); + const wchar_t *text = L"S\nE\nR\nV\nE\nR"; + //gui::IGUIStaticText *t = + Environment->addStaticText(text, rect, false, true, this, -1); + //t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); + } + + // Server parameters + { + core::rect rect(0, 0, 250, 30); + rect += topleft_server + v2s32(35, 30); + Environment->addCheckBox(creative_mode, rect, this, GUI_ID_CREATIVE_CB, + wgettext("Creative Mode")); + } + { + core::rect rect(0, 0, 250, 30); + rect += topleft_server + v2s32(35, 60); + Environment->addCheckBox(enable_damage, rect, this, GUI_ID_DAMAGE_CB, + wgettext("Enable Damage")); + } + // Map delete button + { + core::rect rect(0, 0, 130, 30); + //rect += topleft_server + v2s32(size_server.X-40-130, 100+25); + rect += topleft_server + v2s32(40, 100+25); + Environment->addButton(rect, this, GUI_ID_DELETE_MAP_BUTTON, + wgettext("Delete map")); + } + changeCtype("C"); +} + +void GUIMainMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + /*video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect);*/ + + video::SColor bgcolor(140,0,0,0); + + { + core::rect rect(0, 0, 620, 230); + rect += AbsoluteRect.UpperLeftCorner; + driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect); + } + + { + core::rect rect(0, 250, 620, 430); + rect += AbsoluteRect.UpperLeftCorner; + driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect); + } + + gui::IGUIElement::draw(); +} + +void GUIMainMenu::acceptInput() +{ + { + gui::IGUIElement *e = getElementFromId(GUI_ID_NAME_INPUT); + if(e != NULL) + m_data->name = e->getText(); + } + { + gui::IGUIElement *e = getElementFromId(264); + if(e != NULL) + m_data->password = e->getText(); + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_ADDRESS_INPUT); + if(e != NULL) + m_data->address = e->getText(); + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_PORT_INPUT); + if(e != NULL) + m_data->port = e->getText(); + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_CREATIVE_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + m_data->creative_mode = ((gui::IGUICheckBox*)e)->isChecked(); + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_DAMAGE_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + m_data->enable_damage = ((gui::IGUICheckBox*)e)->isChecked(); + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_SMOOTH_LIGHTING_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + m_data->smooth_lighting = ((gui::IGUICheckBox*)e)->isChecked(); + } + { + gui::IGUIElement *e = getElementFromId(GUI_ID_FANCYTREE_CB); + if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX) + m_data->fancy_trees = ((gui::IGUICheckBox*)e)->isChecked(); + } + + m_accepted = true; +} + +bool GUIMainMenu::OnEvent(const SEvent& event) +{ + if(event.EventType==EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.Key==KEY_ESCAPE && event.KeyInput.PressedDown) + { + m_gamecallback->exitToOS(); + quitMenu(); + return true; + } + if(event.KeyInput.Key==KEY_RETURN && event.KeyInput.PressedDown) + { + acceptInput(); + quitMenu(); + return true; + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUIMainMenu: Not allowing focus change." + <getID()) + { + case GUI_ID_JOIN_GAME_BUTTON: // Start game + acceptInput(); + quitMenu(); + return true; + case GUI_ID_CHANGE_KEYS_BUTTON: { + GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(env, parent, -1,menumgr); + kmenu->drop(); + return true; + } + case GUI_ID_DELETE_MAP_BUTTON: // Delete map + // Don't accept input data, just set deletion request + m_data->delete_map = true; + m_accepted = true; + quitMenu(); + return true; + } + } + if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER) + { + switch(event.GUIEvent.Caller->getID()) + { + case GUI_ID_ADDRESS_INPUT: case GUI_ID_PORT_INPUT: case GUI_ID_NAME_INPUT: case 264: + acceptInput(); + quitMenu(); + return true; + } + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiMainMenu.h b/src/guiMainMenu.h new file mode 100644 index 0000000..87561f7 --- /dev/null +++ b/src/guiMainMenu.h @@ -0,0 +1,113 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GUIMAINMENU_HEADER +#define GUIMAINMENU_HEADER + +#include "common_irrlicht.h" +#include "modalMenu.h" +#include "utility.h" +#include +// For IGameCallback +#include "guiPauseMenu.h" + +enum +{ + GUI_ID_QUIT_BUTTON = 101, + GUI_ID_NAME_INPUT, + GUI_ID_ADDRESS_INPUT, + GUI_ID_PORT_INPUT, + GUI_ID_FANCYTREE_CB, + GUI_ID_SMOOTH_LIGHTING_CB, + GUI_ID_DAMAGE_CB, + GUI_ID_CREATIVE_CB, + GUI_ID_JOIN_GAME_BUTTON, + GUI_ID_CHANGE_KEYS_BUTTON, + GUI_ID_DELETE_MAP_BUTTON +}; + +struct MainMenuData +{ + MainMenuData(): + // Client opts + fancy_trees(false), + smooth_lighting(false), + // Server opts + creative_mode(false), + enable_damage(false), + // Actions + delete_map(false) + {} + + // These are in the native format of the gui elements + + // Client options + std::wstring address; + std::wstring port; + std::wstring name; + std::wstring password; + bool fancy_trees; + bool smooth_lighting; + // Server options + bool creative_mode; + bool enable_damage; + // If map deletion is requested, this is set to true + bool delete_map; +}; + +class GUIMainMenu : public GUIModalMenu +{ +public: + GUIMainMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + MainMenuData *data, + IGameCallback *gamecallback); + ~GUIMainMenu(); + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + void drawMenu(); + + void acceptInput(); + + bool getStatus() + { + return m_accepted; + } + + bool OnEvent(const SEvent& event); + +private: + MainMenuData *m_data; + bool m_accepted; + IGameCallback *m_gamecallback; + + gui::IGUIEnvironment* env; + gui::IGUIElement* parent; + s32 id; + IMenuManager *menumgr; +}; + +#endif + diff --git a/src/guiMessageMenu.cpp b/src/guiMessageMenu.cpp new file mode 100644 index 0000000..14b3607 --- /dev/null +++ b/src/guiMessageMenu.cpp @@ -0,0 +1,157 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiMessageMenu.h" +#include "debug.h" +#include "serialization.h" +#include + +#include "gettext.h" + +GUIMessageMenu::GUIMessageMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + std::wstring message_text +): + GUIModalMenu(env, parent, id, menumgr), + m_message_text(message_text), + m_status(false) +{ +} + +GUIMessageMenu::~GUIMessageMenu() +{ + removeChildren(); +} + +void GUIMessageMenu::removeChildren() +{ + { + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(257); + if(e != NULL) + e->remove(); + } +} + +void GUIMessageMenu::regenerateGui(v2u32 screensize) +{ + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + core::rect rect( + screensize.X/2 - 580/2, + screensize.Y/2 - 300/2, + screensize.X/2 + 580/2, + screensize.Y/2 + 300/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 size = rect.getSize(); + + /* + Add stuff + */ + { + core::rect rect(0, 0, 400, 50); + rect = rect + v2s32(size.X/2-400/2, size.Y/2-50/2-25); + Environment->addStaticText(m_message_text.c_str(), rect, false, + true, this, 256); + } + changeCtype(""); + { + core::rect rect(0, 0, 140, 30); + rect = rect + v2s32(size.X/2-140/2, size.Y/2-30/2+25); + gui::IGUIElement *e = + Environment->addButton(rect, this, 257, + wgettext("Proceed")); + Environment->setFocus(e); + } + changeCtype("C"); +} + +void GUIMessageMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); + + gui::IGUIElement::draw(); +} + +bool GUIMessageMenu::OnEvent(const SEvent& event) +{ + if(event.EventType==EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.Key==KEY_ESCAPE && event.KeyInput.PressedDown) + { + m_status = true; + quitMenu(); + return true; + } + if(event.KeyInput.Key==KEY_RETURN && event.KeyInput.PressedDown) + { + m_status = true; + quitMenu(); + return true; + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUIMessageMenu: Not allowing focus change." + <getID()) + { + case 257: + m_status = true; + quitMenu(); + return true; + } + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiMessageMenu.h b/src/guiMessageMenu.h new file mode 100644 index 0000000..82c40ce --- /dev/null +++ b/src/guiMessageMenu.h @@ -0,0 +1,61 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GUIMESSAGEMENU_HEADER +#define GUIMESSAGEMENU_HEADER + +#include "common_irrlicht.h" +#include "modalMenu.h" +#include "utility.h" +#include + +class GUIMessageMenu : public GUIModalMenu +{ +public: + GUIMessageMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + std::wstring message_text); + ~GUIMessageMenu(); + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + void drawMenu(); + + bool OnEvent(const SEvent& event); + + /* + true = ok'd + */ + bool getStatus() + { + return m_status; + } + +private: + std::wstring m_message_text; + bool m_status; +}; + +#endif + diff --git a/src/guiPasswordChange.cpp b/src/guiPasswordChange.cpp new file mode 100644 index 0000000..273326f --- /dev/null +++ b/src/guiPasswordChange.cpp @@ -0,0 +1,261 @@ +/* +Part of Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola +Copyright (C) 2011 Ciaran Gultnieks + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#include "guiPasswordChange.h" +#include "debug.h" +#include "serialization.h" +#include + +#include "gettext.h" + +const int ID_oldPassword = 256; +const int ID_newPassword1 = 257; +const int ID_newPassword2 = 258; +const int ID_change = 259; +const int ID_message = 260; + +GUIPasswordChange::GUIPasswordChange(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + Client* client +): + GUIModalMenu(env, parent, id, menumgr), + m_client(client) +{ +} + +GUIPasswordChange::~GUIPasswordChange() +{ + removeChildren(); +} + +void GUIPasswordChange::removeChildren() +{ + { + gui::IGUIElement *e = getElementFromId(ID_oldPassword); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(ID_newPassword1); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(ID_newPassword2); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(ID_change); + if(e != NULL) + e->remove(); + } +} + +void GUIPasswordChange::regenerateGui(v2u32 screensize) +{ + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + core::rect rect( + screensize.X/2 - 580/2, + screensize.Y/2 - 300/2, + screensize.X/2 + 580/2, + screensize.Y/2 + 300/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 size = rect.getSize(); + v2s32 topleft_client(40, 0); + v2s32 size_client = size - v2s32(40, 0); + + /* + Add stuff + */ + s32 ypos = 50; + changeCtype(""); + { + core::rect rect(0, 0, 110, 20); + rect += topleft_client + v2s32(35, ypos+6); + Environment->addStaticText(wgettext("Old Password"), + rect, false, true, this, -1); + } + changeCtype("C"); + { + core::rect rect(0, 0, 230, 30); + rect += topleft_client + v2s32(160, ypos); + gui::IGUIEditBox *e = + Environment->addEditBox(L"", rect, true, this, ID_oldPassword); + Environment->setFocus(e); + e->setPasswordBox(true); + } + ypos += 50; + changeCtype(""); + { + core::rect rect(0, 0, 110, 20); + rect += topleft_client + v2s32(35, ypos+6); + Environment->addStaticText(wgettext("New Password"), + rect, false, true, this, -1); + } + changeCtype("C"); + { + core::rect rect(0, 0, 230, 30); + rect += topleft_client + v2s32(160, ypos); + gui::IGUIEditBox *e = + Environment->addEditBox(L"", rect, true, this, ID_newPassword1); + e->setPasswordBox(true); + } + ypos += 50; + changeCtype(""); + { + core::rect rect(0, 0, 110, 20); + rect += topleft_client + v2s32(35, ypos+6); + Environment->addStaticText(wgettext("Confirm Password"), + rect, false, true, this, -1); + } + changeCtype("C"); + { + core::rect rect(0, 0, 230, 30); + rect += topleft_client + v2s32(160, ypos); + gui::IGUIEditBox *e = + Environment->addEditBox(L"", rect, true, this, ID_newPassword2); + e->setPasswordBox(true); + } + + ypos += 50; + changeCtype(""); + { + core::rect rect(0, 0, 140, 30); + rect = rect + v2s32(size.X/2-140/2, ypos); + Environment->addButton(rect, this, ID_change, wgettext("Change")); + } + + ypos += 50; + { + core::rect rect(0, 0, 300, 20); + rect += topleft_client + v2s32(35, ypos); + IGUIElement *e = + Environment->addStaticText( + wgettext("Passwords do not match!"), + rect, false, true, this, ID_message); + e->setVisible(false); + } + changeCtype("C"); + +} + +void GUIPasswordChange::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); + + gui::IGUIElement::draw(); +} + +bool GUIPasswordChange::acceptInput() +{ + std::wstring oldpass; + std::wstring newpass; + gui::IGUIElement *e; + e = getElementFromId(ID_oldPassword); + if(e != NULL) + oldpass = e->getText(); + e = getElementFromId(ID_newPassword1); + if(e != NULL) + newpass = e->getText(); + e = getElementFromId(ID_newPassword2); + if(e != NULL && newpass != e->getText()) + { + e = getElementFromId(ID_message); + if(e != NULL) + e->setVisible(true); + return false; + } + m_client->sendChangePassword(oldpass, newpass); + return true; +} + +bool GUIPasswordChange::OnEvent(const SEvent& event) +{ + if(event.EventType==EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.Key==KEY_ESCAPE && event.KeyInput.PressedDown) + { + quitMenu(); + return true; + } + if(event.KeyInput.Key==KEY_RETURN && event.KeyInput.PressedDown) + { + if(acceptInput()) + quitMenu(); + return true; + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUIPasswordChange: Not allowing focus change." + <getID()) + { + case ID_change: + if(acceptInput()) + quitMenu(); + return true; + } + } + if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER) + { + switch(event.GUIEvent.Caller->getID()) + { + case ID_oldPassword: + case ID_newPassword1: + case ID_newPassword2: + if(acceptInput()) + quitMenu(); + return true; + } + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiPasswordChange.h b/src/guiPasswordChange.h new file mode 100644 index 0000000..1748baa --- /dev/null +++ b/src/guiPasswordChange.h @@ -0,0 +1,55 @@ +/* +Part of Minetest-c55 +Copyright (C) 2010-11 celeron55, Perttu Ahola +Copyright (C) 2011 Ciaran Gultnieks + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef GUIPASSWORDCHANGE_HEADER +#define GUIPASSWORDCHANGE_HEADER + +#include "common_irrlicht.h" +#include "modalMenu.h" +#include "utility.h" +#include "client.h" +#include + +class GUIPasswordChange : public GUIModalMenu +{ +public: + GUIPasswordChange(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + Client* client); + ~GUIPasswordChange(); + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + void drawMenu(); + + bool acceptInput(); + + bool OnEvent(const SEvent& event); + +private: + Client* m_client; + +}; + +#endif + diff --git a/src/guiPauseMenu.cpp b/src/guiPauseMenu.cpp new file mode 100644 index 0000000..eae887a --- /dev/null +++ b/src/guiPauseMenu.cpp @@ -0,0 +1,258 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiPauseMenu.h" +#include "debug.h" +#include "serialization.h" +#include "porting.h" +#include "config.h" +#include "main.h" + +#include "gettext.h" + +GUIPauseMenu::GUIPauseMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IGameCallback *gamecallback, + IMenuManager *menumgr): + GUIModalMenu(env, parent, id, menumgr) +{ + m_gamecallback = gamecallback; +} + +GUIPauseMenu::~GUIPauseMenu() +{ + removeChildren(); +} + +void GUIPauseMenu::removeChildren() +{ + { + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(257); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(258); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(259); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(260); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(261); + if(e != NULL) + e->remove(); + } +} + +void GUIPauseMenu::regenerateGui(v2u32 screensize) +{ + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + core::rect rect( + screensize.X/2 - 580/2, + screensize.Y/2 - 300/2, + screensize.X/2 + 580/2, + screensize.Y/2 + 300/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 size = rect.getSize(); + + /* + Add stuff + */ + const s32 btn_height = 30; + const s32 btn_gap = 20; + const s32 btn_num = 4; + s32 btn_y = size.Y/2-((btn_num*btn_height+(btn_num-1)*btn_gap))/2; + changeCtype(""); + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 256, + wgettext("Continue")); + } + btn_y += btn_height + btn_gap; + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 261, + wgettext("Change Password")); + } + btn_y += btn_height + btn_gap; + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 260, + wgettext("Disconnect")); + } + btn_y += btn_height + btn_gap; + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 257, + wgettext("Exit to OS")); + } + + { + core::rect rect(0, 0, 180, 240); + rect = rect + v2s32(size.X/2 + 90, size.Y/2-rect.getHeight()/2); + Environment->addStaticText(chartowchar_t(gettext( + "Default Controls:\n" + "- WASD: Walk\n" + "- Mouse left: dig/hit\n" + "- Mouse right: place/use\n" + "- Mouse wheel: select item\n" + "- 0...9: select item\n" + "- Shift: sneak\n" + "- R: Toggle viewing all loaded chunks\n" + "- I: Inventory menu\n" + "- ESC: This menu\n" + "- T: Chat\n" + )), rect, false, true, this, 258); + } + { + core::rect rect(0, 0, 180, 220); + rect = rect + v2s32(size.X/2 - 90 - rect.getWidth(), size.Y/2-rect.getHeight()/2); + + v2u32 max_texture_size; + { + video::IVideoDriver* driver = Environment->getVideoDriver(); + max_texture_size = driver->getMaxTextureSize(); + } + + /*wchar_t text[200]; + swprintf(text, 200, + L"Minetest-c55\n" + L"by Perttu Ahola\n" + L"celeron55@gmail.com\n\n" + SWPRINTF_CHARSTRING L"\n" + L"userdata path = " + SWPRINTF_CHARSTRING + , + BUILD_INFO, + porting::path_userdata.c_str() + );*/ + + std::ostringstream os; + os<<"Minetest\n"; + os<<"by Perttu Ahola and contributors\n"; + os<<"celeron55@gmail.com\n"; + os<addStaticText(narrow_to_wide(os.str()).c_str(), rect, false, true, this, 259); + } + changeCtype("C"); +} + +void GUIPauseMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); + + gui::IGUIElement::draw(); +} + +bool GUIPauseMenu::OnEvent(const SEvent& event) +{ + + if(event.EventType==EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.PressedDown) + { + if(event.KeyInput.Key==KEY_ESCAPE) + { + quitMenu(); + return true; + } + else if(event.KeyInput.Key==KEY_RETURN) + { + quitMenu(); + return true; + } + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUIPauseMenu: Not allowing focus change." + <getID()) + { + case 256: // continue + quitMenu(); + // ALWAYS return immediately after quitMenu() + return true; + case 261: + quitMenu(); + m_gamecallback->changePassword(); + return true; + case 260: // disconnect + m_gamecallback->disconnect(); + quitMenu(); + return true; + case 257: // exit + m_gamecallback->exitToOS(); + quitMenu(); + return true; + } + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiPauseMenu.cpp~ b/src/guiPauseMenu.cpp~ new file mode 100644 index 0000000..eae887a --- /dev/null +++ b/src/guiPauseMenu.cpp~ @@ -0,0 +1,258 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiPauseMenu.h" +#include "debug.h" +#include "serialization.h" +#include "porting.h" +#include "config.h" +#include "main.h" + +#include "gettext.h" + +GUIPauseMenu::GUIPauseMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IGameCallback *gamecallback, + IMenuManager *menumgr): + GUIModalMenu(env, parent, id, menumgr) +{ + m_gamecallback = gamecallback; +} + +GUIPauseMenu::~GUIPauseMenu() +{ + removeChildren(); +} + +void GUIPauseMenu::removeChildren() +{ + { + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(257); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(258); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(259); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(260); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(261); + if(e != NULL) + e->remove(); + } +} + +void GUIPauseMenu::regenerateGui(v2u32 screensize) +{ + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + core::rect rect( + screensize.X/2 - 580/2, + screensize.Y/2 - 300/2, + screensize.X/2 + 580/2, + screensize.Y/2 + 300/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 size = rect.getSize(); + + /* + Add stuff + */ + const s32 btn_height = 30; + const s32 btn_gap = 20; + const s32 btn_num = 4; + s32 btn_y = size.Y/2-((btn_num*btn_height+(btn_num-1)*btn_gap))/2; + changeCtype(""); + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 256, + wgettext("Continue")); + } + btn_y += btn_height + btn_gap; + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 261, + wgettext("Change Password")); + } + btn_y += btn_height + btn_gap; + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 260, + wgettext("Disconnect")); + } + btn_y += btn_height + btn_gap; + { + core::rect rect(0, 0, 140, btn_height); + rect = rect + v2s32(size.X/2-140/2, btn_y); + Environment->addButton(rect, this, 257, + wgettext("Exit to OS")); + } + + { + core::rect rect(0, 0, 180, 240); + rect = rect + v2s32(size.X/2 + 90, size.Y/2-rect.getHeight()/2); + Environment->addStaticText(chartowchar_t(gettext( + "Default Controls:\n" + "- WASD: Walk\n" + "- Mouse left: dig/hit\n" + "- Mouse right: place/use\n" + "- Mouse wheel: select item\n" + "- 0...9: select item\n" + "- Shift: sneak\n" + "- R: Toggle viewing all loaded chunks\n" + "- I: Inventory menu\n" + "- ESC: This menu\n" + "- T: Chat\n" + )), rect, false, true, this, 258); + } + { + core::rect rect(0, 0, 180, 220); + rect = rect + v2s32(size.X/2 - 90 - rect.getWidth(), size.Y/2-rect.getHeight()/2); + + v2u32 max_texture_size; + { + video::IVideoDriver* driver = Environment->getVideoDriver(); + max_texture_size = driver->getMaxTextureSize(); + } + + /*wchar_t text[200]; + swprintf(text, 200, + L"Minetest-c55\n" + L"by Perttu Ahola\n" + L"celeron55@gmail.com\n\n" + SWPRINTF_CHARSTRING L"\n" + L"userdata path = " + SWPRINTF_CHARSTRING + , + BUILD_INFO, + porting::path_userdata.c_str() + );*/ + + std::ostringstream os; + os<<"Minetest\n"; + os<<"by Perttu Ahola and contributors\n"; + os<<"celeron55@gmail.com\n"; + os<addStaticText(narrow_to_wide(os.str()).c_str(), rect, false, true, this, 259); + } + changeCtype("C"); +} + +void GUIPauseMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); + + gui::IGUIElement::draw(); +} + +bool GUIPauseMenu::OnEvent(const SEvent& event) +{ + + if(event.EventType==EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.PressedDown) + { + if(event.KeyInput.Key==KEY_ESCAPE) + { + quitMenu(); + return true; + } + else if(event.KeyInput.Key==KEY_RETURN) + { + quitMenu(); + return true; + } + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUIPauseMenu: Not allowing focus change." + <getID()) + { + case 256: // continue + quitMenu(); + // ALWAYS return immediately after quitMenu() + return true; + case 261: + quitMenu(); + m_gamecallback->changePassword(); + return true; + case 260: // disconnect + m_gamecallback->disconnect(); + quitMenu(); + return true; + case 257: // exit + m_gamecallback->exitToOS(); + quitMenu(); + return true; + } + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiPauseMenu.h b/src/guiPauseMenu.h new file mode 100644 index 0000000..64e3c71 --- /dev/null +++ b/src/guiPauseMenu.h @@ -0,0 +1,58 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GUIPAUSEMENU_HEADER +#define GUIPAUSEMENU_HEADER + +#include "common_irrlicht.h" +#include "modalMenu.h" + +class IGameCallback +{ +public: + virtual void exitToOS() = 0; + virtual void disconnect() = 0; + virtual void changePassword() = 0; +}; + +class GUIPauseMenu : public GUIModalMenu +{ +public: + GUIPauseMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IGameCallback *gamecallback, + IMenuManager *menumgr); + ~GUIPauseMenu(); + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + void drawMenu(); + + bool OnEvent(const SEvent& event); + +private: + IGameCallback *m_gamecallback; +}; + +#endif + diff --git a/src/guiTextInputMenu.cpp b/src/guiTextInputMenu.cpp new file mode 100644 index 0000000..208ced8 --- /dev/null +++ b/src/guiTextInputMenu.cpp @@ -0,0 +1,205 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "guiTextInputMenu.h" +#include "debug.h" +#include "serialization.h" +#include + +#include "gettext.h" + +GUITextInputMenu::GUITextInputMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + TextDest *dest, + std::wstring initial_text +): + GUIModalMenu(env, parent, id, menumgr), + m_dest(dest), + m_initial_text(initial_text) +{ +} + +GUITextInputMenu::~GUITextInputMenu() +{ + removeChildren(); + if(m_dest) + delete m_dest; +} + +void GUITextInputMenu::removeChildren() +{ + { + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + e->remove(); + } + { + gui::IGUIElement *e = getElementFromId(257); + if(e != NULL) + e->remove(); + } +} + +void GUITextInputMenu::regenerateGui(v2u32 screensize) +{ + std::wstring text; + + { + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + { + text = e->getText(); + } + else + { + text = m_initial_text; + m_initial_text = L""; + } + } + + /* + Remove stuff + */ + removeChildren(); + + /* + Calculate new sizes and positions + */ + core::rect rect( + screensize.X/2 - 580/2, + screensize.Y/2 - 300/2, + screensize.X/2 + 580/2, + screensize.Y/2 + 300/2 + ); + + DesiredRect = rect; + recalculateAbsolutePosition(false); + + v2s32 size = rect.getSize(); + + /* + Add stuff + */ + { + core::rect rect(0, 0, 300, 30); + rect = rect + v2s32(size.X/2-300/2, size.Y/2-30/2-25); + gui::IGUIElement *e = + Environment->addEditBox(text.c_str(), rect, true, this, 256); + Environment->setFocus(e); + + irr::SEvent evt; + evt.EventType = EET_KEY_INPUT_EVENT; + evt.KeyInput.Key = KEY_END; + evt.KeyInput.PressedDown = true; + e->OnEvent(evt); + } + changeCtype(""); + { + core::rect rect(0, 0, 140, 30); + rect = rect + v2s32(size.X/2-140/2, size.Y/2-30/2+25); + Environment->addButton(rect, this, 257, + wgettext("Proceed")); + } + changeCtype("C"); +} + +void GUITextInputMenu::drawMenu() +{ + gui::IGUISkin* skin = Environment->getSkin(); + if (!skin) + return; + video::IVideoDriver* driver = Environment->getVideoDriver(); + + video::SColor bgcolor(140,0,0,0); + driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); + + gui::IGUIElement::draw(); +} + +void GUITextInputMenu::acceptInput() +{ + if(m_dest) + { + gui::IGUIElement *e = getElementFromId(256); + if(e != NULL) + { + m_dest->gotText(e->getText()); + } + delete m_dest; + m_dest = NULL; + } +} + +bool GUITextInputMenu::OnEvent(const SEvent& event) +{ + if(event.EventType==EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.Key==KEY_ESCAPE && event.KeyInput.PressedDown) + { + quitMenu(); + return true; + } + if(event.KeyInput.Key==KEY_RETURN && event.KeyInput.PressedDown) + { + acceptInput(); + quitMenu(); + return true; + } + } + if(event.EventType==EET_GUI_EVENT) + { + if(event.GUIEvent.EventType==gui::EGET_ELEMENT_FOCUS_LOST + && isVisible()) + { + if(!canTakeFocus(event.GUIEvent.Element)) + { + dstream<<"GUITextInputMenu: Not allowing focus change." + <getID()) + { + case 257: + acceptInput(); + quitMenu(); + // quitMenu deallocates menu + return true; + } + } + if(event.GUIEvent.EventType==gui::EGET_EDITBOX_ENTER) + { + switch(event.GUIEvent.Caller->getID()) + { + case 256: + acceptInput(); + quitMenu(); + // quitMenu deallocates menu + return true; + } + } + } + + return Parent ? Parent->OnEvent(event) : false; +} + diff --git a/src/guiTextInputMenu.h b/src/guiTextInputMenu.h new file mode 100644 index 0000000..c679aa9 --- /dev/null +++ b/src/guiTextInputMenu.h @@ -0,0 +1,61 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef GUITEXTINPUTMENU_HEADER +#define GUITEXTINPUTMENU_HEADER + +#include "common_irrlicht.h" +#include "modalMenu.h" +#include "utility.h" +#include + +struct TextDest +{ + virtual void gotText(std::wstring text) = 0; +}; + +class GUITextInputMenu : public GUIModalMenu +{ +public: + GUITextInputMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr, + TextDest *dest, + std::wstring initial_text); + ~GUITextInputMenu(); + + void removeChildren(); + /* + Remove and re-add (or reposition) stuff + */ + void regenerateGui(v2u32 screensize); + + void drawMenu(); + + void acceptInput(); + + bool OnEvent(const SEvent& event); + +private: + TextDest *m_dest; + std::wstring m_initial_text; +}; + +#endif + diff --git a/src/inventory.cpp b/src/inventory.cpp new file mode 100644 index 0000000..f31e19f --- /dev/null +++ b/src/inventory.cpp @@ -0,0 +1,1036 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* +(c) 2010 Perttu Ahola +*/ + +#include "inventory.h" +#include "serialization.h" +#include "utility.h" +#include "debug.h" +#include +#include "main.h" +#include "serverobject.h" +#include "content_mapnode.h" +#include "content_inventory.h" +#include "content_sao.h" +#include "player.h" + +/* + InventoryItem +*/ + +InventoryItem::InventoryItem(u16 count) +{ + m_count = count; +} + +InventoryItem::~InventoryItem() +{ +} + +content_t content_translate_from_19_to_internal(content_t c_from) +{ + for(u32 i=0; i>material; + u16 count; + is>>count; + // Convert old materials + if(material <= 0xff) + { + material = content_translate_from_19_to_internal(material); + } + if(material > MAX_CONTENT) + throw SerializationError("Too large material number"); + return new MaterialItem(material, count); + } + else if(name == "MaterialItem2") + { + u16 material; + is>>material; + u16 count; + is>>count; + if(material > MAX_CONTENT) + throw SerializationError("Too large material number"); + return new MaterialItem(material, count); + } + else if(name == "MBOItem") + { + std::string inventorystring; + std::getline(is, inventorystring, '|'); + return new MapBlockObjectItem(inventorystring); + } + else if(name == "CraftItem") + { + std::string subname; + std::getline(is, subname, ' '); + u16 count; + is>>count; + return new CraftItem(subname, count); + } + else if(name == "ToolItem") + { + std::string toolname; + std::getline(is, toolname, ' '); + u16 wear; + is>>wear; + return new ToolItem(toolname, wear); + } + else + { + dstream<<"Unknown InventoryItem name=\""<getTextureRaw(name); +} +#endif + +ServerActiveObject* CraftItem::createSAO(ServerEnvironment *env, u16 id, v3f pos) +{ + // Special cases + ServerActiveObject *obj = item_craft_create_object(m_subname, env, id, pos); + if(obj) + return obj; + // Default + return InventoryItem::createSAO(env, id, pos); +} + +u16 CraftItem::getDropCount() const +{ + // Special cases + s16 dc = item_craft_get_drop_count(m_subname); + if(dc != -1) + return dc; + // Default + return InventoryItem::getDropCount(); +} + +bool CraftItem::isCookable() const +{ + return item_craft_is_cookable(m_subname); +} + +InventoryItem *CraftItem::createCookResult() const +{ + return item_craft_create_cook_result(m_subname); +} + +bool CraftItem::use(ServerEnvironment *env, Player *player) +{ + if(item_craft_is_eatable(m_subname)) + { + u16 result_count = getCount() - 1; // Eat one at a time + s16 hp_change = item_craft_eat_hp_change(m_subname); + if(player->hp + hp_change > 20) + player->hp = 20; + else + player->hp += hp_change; + + if(result_count < 1) + return true; + else + setCount(result_count); + } + return false; +} + +/* + MapBlockObjectItem DEPRECATED + TODO: Remove +*/ +#ifndef SERVER +video::ITexture * MapBlockObjectItem::getImage() +{ + if(m_inventorystring.substr(0,3) == "Rat") + return g_texturesource->getTextureRaw("rat.png"); + + if(m_inventorystring.substr(0,4) == "Sign") + return g_texturesource->getTextureRaw("sign.png"); + + return NULL; +} +#endif +std::string MapBlockObjectItem::getText() +{ + if(m_inventorystring.substr(0,3) == "Rat") + return ""; + + if(m_inventorystring.substr(0,4) == "Sign") + return ""; + + return "obj"; +} + +MapBlockObject * MapBlockObjectItem::createObject + (v3f pos, f32 player_yaw, f32 player_pitch) +{ + std::istringstream is(m_inventorystring); + std::string name; + std::getline(is, name, ' '); + + if(name == "None") + { + return NULL; + } + else if(name == "Sign") + { + std::string text; + std::getline(is, text, '|'); + SignObject *obj = new SignObject(NULL, -1, pos); + obj->setText(text); + obj->setYaw(-player_yaw); + return obj; + } + else if(name == "Rat") + { + RatObject *obj = new RatObject(NULL, -1, pos); + return obj; + } + else if(name == "ItemObj") + { + /* + Now we are an inventory item containing the serialization + string of an object that contains the serialization + string of an inventory item. Fuck this. + */ + //assert(0); + dstream<<__FUNCTION_NAME<<": WARNING: Ignoring ItemObj " + <<"because an item-object should never be inside " + <<"an object-item."<serialize(os); + } + else + { + os<<"Empty"; + } + os<<"\n"; + } + + os<<"EndInventoryList\n"; +} + +void InventoryList::deSerialize(std::istream &is) +{ + //is.imbue(std::locale("C")); + + clearItems(); + u32 item_i = 0; + + for(;;) + { + std::string line; + std::getline(is, line, '\n'); + + std::istringstream iss(line); + //iss.imbue(std::locale("C")); + + std::string name; + std::getline(iss, name, ' '); + + if(name == "EndInventoryList") + { + break; + } + // This is a temporary backwards compatibility fix + else if(name == "end") + { + break; + } + else if(name == "Item") + { + if(item_i > getSize() - 1) + throw SerializationError("too many items"); + InventoryItem *item = InventoryItem::deSerialize(iss); + m_items[item_i++] = item; + } + else if(name == "Empty") + { + if(item_i > getSize() - 1) + throw SerializationError("too many items"); + m_items[item_i++] = NULL; + } + else + { + throw SerializationError("Unknown inventory identifier"); + } + } +} + +InventoryList::InventoryList(const InventoryList &other) +{ + /* + Do this so that the items get cloned. Otherwise the pointers + in the array will just get copied. + */ + *this = other; +} + +InventoryList & InventoryList::operator = (const InventoryList &other) +{ + m_name = other.m_name; + m_size = other.m_size; + clearItems(); + for(u32 i=0; iclone(); + } + } + //setDirty(true); + + return *this; +} + +const std::string &InventoryList::getName() const +{ + return m_name; +} + +u32 InventoryList::getSize() +{ + return m_items.size(); +} + +u32 InventoryList::getUsedSlots() +{ + u32 num = 0; + for(u32 i=0; i m_items.size() - 1) + return NULL; + return m_items[i]; +} + +InventoryItem * InventoryList::getItem(u32 i) +{ + if(i > m_items.size() - 1) + return NULL; + return m_items[i]; +} + +InventoryItem * InventoryList::changeItem(u32 i, InventoryItem *newitem) +{ + assert(i < m_items.size()); + + InventoryItem *olditem = m_items[i]; + m_items[i] = newitem; + //setDirty(true); + return olditem; +} + +void InventoryList::deleteItem(u32 i) +{ + assert(i < m_items.size()); + InventoryItem *item = changeItem(i, NULL); + if(item) + delete item; +} + +InventoryItem * InventoryList::addItem(InventoryItem *newitem) +{ + if(newitem == NULL) + return NULL; + + /* + First try to find if it could be added to some existing items + */ + for(u32 i=0; iaddableTo(to_item) == false) + return newitem; + + // If the item fits fully in the slot, add counter and delete it + if(newitem->getCount() <= to_item->freeSpace()) + { + to_item->add(newitem->getCount()); + delete newitem; + return NULL; + } + // Else the item does not fit fully. Add all that fits and return + // the rest. + else + { + u16 freespace = to_item->freeSpace(); + to_item->add(freespace); + newitem->remove(freespace); + return newitem; + } +} + +bool InventoryList::itemFits(const u32 i, const InventoryItem *newitem) +{ + // If it is an empty position, it's an easy job. + const InventoryItem *to_item = getItem(i); + if(to_item == NULL) + { + return true; + } + + // If not addable, fail + if(newitem->addableTo(to_item) == false) + return false; + + // If the item fits fully in the slot, pass + if(newitem->getCount() <= to_item->freeSpace()) + { + return true; + } + + return false; +} + +bool InventoryList::roomForItem(const InventoryItem *item) +{ + for(u32 i=0; icreateCookResult(); + if(!cook) + return false; + bool room = roomForItem(cook); + delete cook; + return room; +} + +InventoryItem * InventoryList::takeItem(u32 i, u32 count) +{ + if(count == 0) + return NULL; + + //setDirty(true); + + InventoryItem *item = getItem(i); + // If it is an empty position, return NULL + if(item == NULL) + return NULL; + + if(count >= item->getCount()) + { + // Get the item by swapping NULL to its place + return changeItem(i, NULL); + } + else + { + InventoryItem *item2 = item->clone(); + item->remove(count); + item2->setCount(count); + return item2; + } + + return false; +} + +void InventoryList::decrementMaterials(u16 count) +{ + for(u32 i=0; iserialize(o); + o<<"\n"; + } + } +} + +/* + Inventory +*/ + +Inventory::~Inventory() +{ + clear(); +} + +void Inventory::clear() +{ + for(u32 i=0; igetName()<<" "<getSize()<<"\n"; + list->serialize(os); + } + + os<<"EndInventory\n"; +} + +void Inventory::deSerialize(std::istream &is) +{ + clear(); + + for(;;) + { + std::string line; + std::getline(is, line, '\n'); + + std::istringstream iss(line); + + std::string name; + std::getline(iss, name, ' '); + + if(name == "EndInventory") + { + break; + } + // This is a temporary backwards compatibility fix + else if(name == "end") + { + break; + } + else if(name == "List") + { + std::string listname; + u32 listsize; + + std::getline(iss, listname, ' '); + iss>>listsize; + + InventoryList *list = new InventoryList(listname, listsize); + list->deSerialize(is); + + m_lists.push_back(list); + } + else + { + throw SerializationError("Unknown inventory identifier"); + } + } +} + +InventoryList * Inventory::addList(const std::string &name, u32 size) +{ + s32 i = getListIndex(name); + if(i != -1) + { + if(m_lists[i]->getSize() != size) + { + delete m_lists[i]; + m_lists[i] = new InventoryList(name, size); + } + return m_lists[i]; + } + else + { + m_lists.push_back(new InventoryList(name, size)); + return m_lists.getLast(); + } +} + +InventoryList * Inventory::getList(const std::string &name) +{ + s32 i = getListIndex(name); + if(i == -1) + return NULL; + return m_lists[i]; +} + +const InventoryList * Inventory::getList(const std::string &name) const +{ + s32 i = getListIndex(name); + if(i == -1) + return NULL; + return m_lists[i]; +} + +const s32 Inventory::getListIndex(const std::string &name) const +{ + for(u32 i=0; igetName() == name) + return i; + } + return -1; +} + +/* + InventoryAction +*/ + +InventoryAction * InventoryAction::deSerialize(std::istream &is) +{ + std::string type; + std::getline(is, type, ' '); + + InventoryAction *a = NULL; + + if(type == "Move") + { + a = new IMoveAction(is); + } + + return a; +} + +void IMoveAction::apply(InventoryContext *c, InventoryManager *mgr) +{ +#if 1 + + /*dstream<<"from_inv="<getList(from_list); + InventoryList *list_to = inv_to->getList(to_list); + + /*dstream<<"list_from="<getItem(from_i)="<getItem(from_i) + <getItem(to_i)="<getItem(to_i) + <getItem(from_i) == NULL) + { + dstream<<__FUNCTION_NAME<<": Operation not allowed " + <<"(the source item doesn't exist)" + <changeItem(from_i, NULL); + else + item1 = list_from->takeItem(from_i, count); + + // Try to add the item to destination list + InventoryItem *olditem = item1; + item1 = list_to->addItem(to_i, item1); + + // If something is returned, the item was not fully added + if(item1 != NULL) + { + // If olditem is returned, nothing was added. + bool nothing_added = (item1 == olditem); + + // If something else is returned, part of the item was left unadded. + // Add the other part back to the source item + list_from->addItem(from_i, item1); + + // If olditem is returned, nothing was added. + // Swap the items + if(nothing_added) + { + // Take item from source list + item1 = list_from->changeItem(from_i, NULL); + // Adding was not possible, swap the items. + InventoryItem *item2 = list_to->changeItem(to_i, item1); + // Put item from destination list to the source list + list_from->changeItem(from_i, item2); + } + } + + mgr->inventoryModified(c, from_inv); + if(from_inv != to_inv) + mgr->inventoryModified(c, to_inv); +#endif +} + +/* + Craft checking system +*/ + +bool ItemSpec::checkItem(const InventoryItem *item) const +{ + if(type == ITEM_NONE) + { + // Has to be no item + if(item != NULL) + return false; + return true; + } + + // There should be an item + if(item == NULL) + return false; + + std::string itemname = item->getName(); + + if(type == ITEM_MATERIAL) + { + if(itemname != "MaterialItem") + return false; + MaterialItem *mitem = (MaterialItem*)item; + if(mitem->getMaterial() != num) + return false; + } + else if(type == ITEM_CRAFT) + { + if(itemname != "CraftItem") + return false; + CraftItem *mitem = (CraftItem*)item; + if(mitem->getSubName() != name) + return false; + } + else if(type == ITEM_TOOL) + { + // Not supported yet + assert(0); + } + else if(type == ITEM_MBO) + { + // Not supported yet + assert(0); + } + else + { + // Not supported yet + assert(0); + } + return true; +} + +bool checkItemCombination(InventoryItem const * const *items, const ItemSpec *specs) +{ + u16 items_min_x = 100; + u16 items_max_x = 100; + u16 items_min_y = 100; + u16 items_max_y = 100; + for(u16 y=0; y<3; y++) + for(u16 x=0; x<3; x++) + { + if(items[y*3 + x] == NULL) + continue; + if(items_min_x == 100 || x < items_min_x) + items_min_x = x; + if(items_min_y == 100 || y < items_min_y) + items_min_y = y; + if(items_max_x == 100 || x > items_max_x) + items_max_x = x; + if(items_max_y == 100 || y > items_max_y) + items_max_y = y; + } + // No items at all, just return false + if(items_min_x == 100) + return false; + + u16 items_w = items_max_x - items_min_x + 1; + u16 items_h = items_max_y - items_min_y + 1; + + u16 specs_min_x = 100; + u16 specs_max_x = 100; + u16 specs_min_y = 100; + u16 specs_max_y = 100; + for(u16 y=0; y<3; y++) + for(u16 x=0; x<3; x++) + { + if(specs[y*3 + x].type == ITEM_NONE) + continue; + if(specs_min_x == 100 || x < specs_min_x) + specs_min_x = x; + if(specs_min_y == 100 || y < specs_min_y) + specs_min_y = y; + if(specs_max_x == 100 || x > specs_max_x) + specs_max_x = x; + if(specs_max_y == 100 || y > specs_max_y) + specs_max_y = y; + } + // No specs at all, just return false + if(specs_min_x == 100) + return false; + + u16 specs_w = specs_max_x - specs_min_x + 1; + u16 specs_h = specs_max_y - specs_min_y + 1; + + // Different sizes + if(items_w != specs_w || items_h != specs_h) + return false; + + for(u16 y=0; y + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* +(c) 2010 Perttu Ahola +*/ + +#ifndef INVENTORY_HEADER +#define INVENTORY_HEADER + +#include +#include +#include +#include "common_irrlicht.h" +#include "debug.h" +#include "mapblockobject.h" +#include "main.h" // For g_materials +#include "mapnode.h" // For content_t + +#define QUANTITY_ITEM_MAX_COUNT 99 + +class ServerActiveObject; +class ServerEnvironment; +class Player; + +class InventoryItem +{ +public: + InventoryItem(u16 count); + virtual ~InventoryItem(); + + static InventoryItem* deSerialize(std::istream &is); + + virtual const char* getName() const = 0; + // Shall write the name and the parameters + virtual void serialize(std::ostream &os) const = 0; + // Shall make an exact clone of the item + virtual InventoryItem* clone() = 0; +#ifndef SERVER + // Shall return an image to show in the GUI (or NULL) + virtual video::ITexture * getImage() { return NULL; } +#endif + // Shall return a text to show in the GUI + virtual std::string getText() { return ""; } + // Returns the string used for inventory + virtual std::string getItemString(); + // Creates an object from the item, to be placed in the world. + virtual ServerActiveObject* createSAO(ServerEnvironment *env, u16 id, v3f pos); + // Gets amount of items that dropping one SAO will decrement + virtual u16 getDropCount() const { return getCount(); } + + /* + Quantity methods + */ + + // Shall return true if the item can be add()ed to the other + virtual bool addableTo(const InventoryItem *other) const + { + return false; + } + + u16 getCount() const + { + return m_count; + } + void setCount(u16 count) + { + m_count = count; + } + // This should return something else for stackable items + virtual u16 freeSpace() const + { + return 0; + } + void add(u16 count) + { + assert(m_count + count <= QUANTITY_ITEM_MAX_COUNT); + m_count += count; + } + void remove(u16 count) + { + assert(m_count >= count); + m_count -= count; + } + + /* + Other properties + */ + + // Whether it can be cooked + virtual bool isCookable() const {return false;} + // Time of cooking + virtual float getCookTime(){return 3.0;} + // Result of cooking (can randomize) + virtual InventoryItem *createCookResult() const {return NULL;} + + // Eat, press, activate, whatever. + // Called when item is right-clicked when lying on ground. + // If returns true, item shall be deleted. + virtual bool use(ServerEnvironment *env, + Player *player){return false;} + +protected: + u16 m_count; +}; + +class MaterialItem : public InventoryItem +{ +public: + MaterialItem(content_t content, u16 count): + InventoryItem(count) + { + m_content = content; + } + /* + Implementation interface + */ + virtual const char* getName() const + { + return "MaterialItem"; + } + virtual void serialize(std::ostream &os) const + { + //os.imbue(std::locale("C")); + os<<"MaterialItem2"; + os<<" "; + os<<(unsigned int)m_content; + os<<" "; + os<getName()) != "MaterialItem") + return false; + MaterialItem *m = (MaterialItem*)other; + if(m->getMaterial() != m_content) + return false; + return true; + } + u16 freeSpace() const + { + if(m_count > QUANTITY_ITEM_MAX_COUNT) + return 0; + return QUANTITY_ITEM_MAX_COUNT - m_count; + } + /* + Other properties + */ + bool isCookable() const; + InventoryItem *createCookResult() const; + /* + Special methods + */ + content_t getMaterial() + { + return m_content; + } +private: + content_t m_content; +}; + +//TODO: Remove +class MapBlockObjectItem : public InventoryItem +{ +public: + MapBlockObjectItem(std::string inventorystring): + InventoryItem(1) + { + m_inventorystring = inventorystring; + } + + /* + Implementation interface + */ + virtual const char* getName() const + { + return "MBOItem"; + } + virtual void serialize(std::ostream &os) const + { + std::string sane_string(m_inventorystring); + str_replace_char(sane_string, '|', '?'); + os<getName()) != "CraftItem") + return false; + CraftItem *m = (CraftItem*)other; + if(m->m_subname != m_subname) + return false; + return true; + } + u16 freeSpace() const + { + if(m_count > QUANTITY_ITEM_MAX_COUNT) + return 0; + return QUANTITY_ITEM_MAX_COUNT - m_count; + } + + /* + Other properties + */ + + bool isCookable() const; + InventoryItem *createCookResult() const; + + bool use(ServerEnvironment *env, Player *player); + + /* + Special methods + */ + std::string getSubName() + { + return m_subname; + } +private: + std::string m_subname; +}; + +class ToolItem : public InventoryItem +{ +public: + ToolItem(std::string toolname, u16 wear): + InventoryItem(1) + { + m_toolname = toolname; + m_wear = wear; + } + /* + Implementation interface + */ + virtual const char* getName() const + { + return "ToolItem"; + } + virtual void serialize(std::ostream &os) const + { + os<getTextureRaw(os.str()); + } +#endif + std::string getText() + { + return ""; + + /*std::ostringstream os; + u16 f = 4; + u16 d = 65535/f; + u16 i; + for(i=0; i<(65535-m_wear)/d; i++) + os<<'X'; + for(; i= 65535 - add) + { + m_wear = 65535; + return true; + } + else + { + m_wear += add; + return false; + } + } +private: + std::string m_toolname; + u16 m_wear; +}; + +class InventoryList +{ +public: + InventoryList(std::string name, u32 size); + ~InventoryList(); + void clearItems(); + void serialize(std::ostream &os) const; + void deSerialize(std::istream &is); + + InventoryList(const InventoryList &other); + InventoryList & operator = (const InventoryList &other); + + const std::string &getName() const; + u32 getSize(); + // Count used slots + u32 getUsedSlots(); + u32 getFreeSlots(); + + /*bool getDirty(){ return m_dirty; } + void setDirty(bool dirty=true){ m_dirty = dirty; }*/ + + // Get pointer to item + const InventoryItem * getItem(u32 i) const; + InventoryItem * getItem(u32 i); + // Returns old item (or NULL). Parameter can be NULL. + InventoryItem * changeItem(u32 i, InventoryItem *newitem); + // Delete item + void deleteItem(u32 i); + + // Adds an item to a suitable place. Returns leftover item. + // If all went into the list, returns NULL. + InventoryItem * addItem(InventoryItem *newitem); + + // If possible, adds item to given slot. + // If cannot be added at all, returns the item back. + // If can be added partly, decremented item is returned back. + // If can be added fully, NULL is returned. + InventoryItem * addItem(u32 i, InventoryItem *newitem); + + // Checks whether the item could be added to the given slot + bool itemFits(const u32 i, const InventoryItem *newitem); + + // Checks whether there is room for a given item + bool roomForItem(const InventoryItem *item); + + // Checks whether there is room for a given item aftr it has been cooked + bool roomForCookedItem(const InventoryItem *item); + + // Takes some items from a slot. + // If there are not enough, takes as many as it can. + // Returns NULL if couldn't take any. + InventoryItem * takeItem(u32 i, u32 count); + + // Decrements amount of every material item + void decrementMaterials(u16 count); + + void print(std::ostream &o); + +private: + core::array m_items; + u32 m_size; + std::string m_name; + //bool m_dirty; +}; + +class Inventory +{ +public: + ~Inventory(); + + void clear(); + + Inventory(); + Inventory(const Inventory &other); + Inventory & operator = (const Inventory &other); + + void serialize(std::ostream &os) const; + void deSerialize(std::istream &is); + + InventoryList * addList(const std::string &name, u32 size); + InventoryList * getList(const std::string &name); + const InventoryList * getList(const std::string &name) const; + bool deleteList(const std::string &name); + // A shorthand for adding items. + // Returns NULL if the item was fully added, leftover otherwise. + InventoryItem * addItem(const std::string &listname, InventoryItem *newitem) + { + InventoryList *list = getList(listname); + if(list == NULL) + return newitem; + return list->addItem(newitem); + } + +private: + // -1 if not found + const s32 getListIndex(const std::string &name) const; + + core::array m_lists; +}; + +class Player; + +struct InventoryContext +{ + Player *current_player; + + InventoryContext(): + current_player(NULL) + {} +}; + +struct InventoryAction; + +class InventoryManager +{ +public: + InventoryManager(){} + virtual ~InventoryManager(){} + + /* + Get a pointer to an inventory specified by id. + id can be: + - "current_player" + - "nodemeta:X,Y,Z" + */ + virtual Inventory* getInventory(InventoryContext *c, std::string id) + {return NULL;} + // Used on the server by InventoryAction::apply and other stuff + virtual void inventoryModified(InventoryContext *c, std::string id) + {} + // Used on the client + virtual void inventoryAction(InventoryAction *a) + {} +}; + +#define IACTION_MOVE 0 + +struct InventoryAction +{ + static InventoryAction * deSerialize(std::istream &is); + + virtual u16 getType() const = 0; + virtual void serialize(std::ostream &os) const = 0; + virtual void apply(InventoryContext *c, InventoryManager *mgr) = 0; +}; + +struct IMoveAction : public InventoryAction +{ + // count=0 means "everything" + u16 count; + std::string from_inv; + std::string from_list; + s16 from_i; + std::string to_inv; + std::string to_list; + s16 to_i; + + IMoveAction() + { + count = 0; + from_i = -1; + to_i = -1; + } + IMoveAction(std::istream &is) + { + std::string ts; + + std::getline(is, ts, ' '); + count = stoi(ts); + + std::getline(is, from_inv, ' '); + + std::getline(is, from_list, ' '); + + std::getline(is, ts, ' '); + from_i = stoi(ts); + + std::getline(is, to_inv, ' '); + + std::getline(is, to_list, ' '); + + std::getline(is, ts, ' '); + to_i = stoi(ts); + } + + u16 getType() const + { + return IACTION_MOVE; + } + + void serialize(std::ostream &os) const + { + os<<"Move "; + os< + #endif // _WIN32_WCE + #include + #include + // CriticalSection is way faster than the alternative + #define JMUTEX_CRITICALSECTION +#else // using pthread + #include +#endif // WIN32 + +#define ERR_JMUTEX_ALREADYINIT -1 +#define ERR_JMUTEX_NOTINIT -2 +#define ERR_JMUTEX_CANTCREATEMUTEX -3 + +class JMutex +{ +public: + JMutex(); + ~JMutex(); + int Init(); + int Lock(); + int Unlock(); + bool IsInitialized() { return initialized; } +private: +#if (defined(WIN32) || defined(_WIN32_WCE)) +#ifdef JMUTEX_CRITICALSECTION + CRITICAL_SECTION mutex; +#else // Use standard mutex + HANDLE mutex; +#endif // JMUTEX_CRITICALSECTION +#else // pthread mutex + pthread_mutex_t mutex; +#endif // WIN32 + bool initialized; +}; + +#endif // JMUTEX_H diff --git a/src/jthread/jmutexautolock.h b/src/jthread/jmutexautolock.h new file mode 100644 index 0000000..6020a5c --- /dev/null +++ b/src/jthread/jmutexautolock.h @@ -0,0 +1,43 @@ +/* + + This file is a part of the JThread package, which contains some object- + oriented thread wrappers for different thread implementations. + + Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +*/ + +#ifndef JMUTEXAUTOLOCK_H + +#define JMUTEXAUTOLOCK_H + +#include "jmutex.h" + +class JMutexAutoLock +{ +public: + JMutexAutoLock(JMutex &m) : mutex(m) { mutex.Lock(); } + ~JMutexAutoLock() { mutex.Unlock(); } +private: + JMutex &mutex; +}; + +#endif // JMUTEXAUTOLOCK_H diff --git a/src/jthread/jthread.h b/src/jthread/jthread.h new file mode 100644 index 0000000..9440a15 --- /dev/null +++ b/src/jthread/jthread.h @@ -0,0 +1,77 @@ +/* + + This file is a part of the JThread package, which contains some object- + oriented thread wrappers for different thread implementations. + + Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +*/ + +#ifndef JTHREAD_H + +#define JTHREAD_H + +#include "jmutex.h" + +#define ERR_JTHREAD_CANTINITMUTEX -1 +#define ERR_JTHREAD_CANTSTARTTHREAD -2 +#define ERR_JTHREAD_THREADFUNCNOTSET -3 +#define ERR_JTHREAD_NOTRUNNING -4 +#define ERR_JTHREAD_ALREADYRUNNING -5 + +class JThread +{ +public: + JThread(); + virtual ~JThread(); + int Start(); + int Kill(); + virtual void *Thread() = 0; + bool IsRunning(); + void *GetReturnValue(); +protected: + void ThreadStarted(); +private: + +#if (defined(WIN32) || defined(_WIN32_WCE)) +#ifdef _WIN32_WCE + DWORD threadid; + static DWORD WINAPI TheThread(void *param); +#else + static UINT __stdcall TheThread(void *param); + UINT threadid; +#endif // _WIN32_WCE + HANDLE threadhandle; +#else // pthread type threads + static void *TheThread(void *param); + + pthread_t threadid; +#endif // WIN32 + void *retval; + bool running; + + JMutex runningmutex; + JMutex continuemutex,continuemutex2; + bool mutexinit; +}; + +#endif // JTHREAD_H + diff --git a/src/jthread/pthread/jmutex.cpp b/src/jthread/pthread/jmutex.cpp new file mode 100644 index 0000000..6bc3ae5 --- /dev/null +++ b/src/jthread/pthread/jmutex.cpp @@ -0,0 +1,67 @@ +/* + + This file is a part of the JThread package, which contains some object- + oriented thread wrappers for different thread implementations. + + Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +*/ + +#include "jmutex.h" + +JMutex::JMutex() +{ + initialized = false; +} + +JMutex::~JMutex() +{ + if (initialized) + pthread_mutex_destroy(&mutex); +} + +int JMutex::Init() +{ + if (initialized) + return ERR_JMUTEX_ALREADYINIT; + + pthread_mutex_init(&mutex,NULL); + initialized = true; + return 0; +} + +int JMutex::Lock() +{ + if (!initialized) + return ERR_JMUTEX_NOTINIT; + + pthread_mutex_lock(&mutex); + return 0; +} + +int JMutex::Unlock() +{ + if (!initialized) + return ERR_JMUTEX_NOTINIT; + + pthread_mutex_unlock(&mutex); + return 0; +} diff --git a/src/jthread/pthread/jthread.cpp b/src/jthread/pthread/jthread.cpp new file mode 100644 index 0000000..978cac2 --- /dev/null +++ b/src/jthread/pthread/jthread.cpp @@ -0,0 +1,180 @@ +/* + + This file is a part of the JThread package, which contains some object- + oriented thread wrappers for different thread implementations. + + Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +*/ + +#include "jthread.h" +#include +#include +#include + +JThread::JThread() +{ + retval = NULL; + mutexinit = false; + running = false; +} + +JThread::~JThread() +{ + Kill(); +} + +int JThread::Start() +{ + int status; + + if (!mutexinit) + { + if (!runningmutex.IsInitialized()) + { + if (runningmutex.Init() < 0) + return ERR_JTHREAD_CANTINITMUTEX; + } + if (!continuemutex.IsInitialized()) + { + if (continuemutex.Init() < 0) + return ERR_JTHREAD_CANTINITMUTEX; + } + if (!continuemutex2.IsInitialized()) + { + if (continuemutex2.Init() < 0) + return ERR_JTHREAD_CANTINITMUTEX; + } + mutexinit = true; + } + + runningmutex.Lock(); + if (running) + { + runningmutex.Unlock(); + return ERR_JTHREAD_ALREADYRUNNING; + } + runningmutex.Unlock(); + + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + + continuemutex.Lock(); + status = pthread_create(&threadid,&attr,TheThread,this); + pthread_attr_destroy(&attr); + if (status != 0) + { + continuemutex.Unlock(); + return ERR_JTHREAD_CANTSTARTTHREAD; + } + + /* Wait until 'running' is set */ + + runningmutex.Lock(); + while (!running) + { + runningmutex.Unlock(); + + struct timespec req,rem; + + req.tv_sec = 0; + req.tv_nsec = 1000000; + nanosleep(&req,&rem); + + runningmutex.Lock(); + } + runningmutex.Unlock(); + + continuemutex.Unlock(); + + continuemutex2.Lock(); + continuemutex2.Unlock(); + return 0; +} + +int JThread::Kill() +{ + runningmutex.Lock(); + if (!running) + { + runningmutex.Unlock(); + return ERR_JTHREAD_NOTRUNNING; + } + pthread_cancel(threadid); + running = false; + runningmutex.Unlock(); + return 0; +} + +bool JThread::IsRunning() +{ + bool r; + + runningmutex.Lock(); + r = running; + runningmutex.Unlock(); + return r; +} + +void *JThread::GetReturnValue() +{ + void *val; + + runningmutex.Lock(); + if (running) + val = NULL; + else + val = retval; + runningmutex.Unlock(); + return val; +} + +void *JThread::TheThread(void *param) +{ + JThread *jthread; + void *ret; + + jthread = (JThread *)param; + + jthread->continuemutex2.Lock(); + jthread->runningmutex.Lock(); + jthread->running = true; + jthread->runningmutex.Unlock(); + + jthread->continuemutex.Lock(); + jthread->continuemutex.Unlock(); + + ret = jthread->Thread(); + + jthread->runningmutex.Lock(); + jthread->running = false; + jthread->retval = ret; + jthread->runningmutex.Unlock(); + + return NULL; +} + +void JThread::ThreadStarted() +{ + continuemutex2.Unlock(); +} + diff --git a/src/jthread/win32/jmutex.cpp b/src/jthread/win32/jmutex.cpp new file mode 100644 index 0000000..000461e --- /dev/null +++ b/src/jthread/win32/jmutex.cpp @@ -0,0 +1,83 @@ +/* + + This file is a part of the JThread package, which contains some object- + oriented thread wrappers for different thread implementations. + + Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +*/ + +#include "jmutex.h" + +JMutex::JMutex() +{ + initialized = false; +} + +JMutex::~JMutex() +{ + if (initialized) +#ifdef JMUTEX_CRITICALSECTION + DeleteCriticalSection(&mutex); +#else + CloseHandle(mutex); +#endif // JMUTEX_CRITICALSECTION +} + +int JMutex::Init() +{ + if (initialized) + return ERR_JMUTEX_ALREADYINIT; +#ifdef JMUTEX_CRITICALSECTION + InitializeCriticalSection(&mutex); +#else + mutex = CreateMutex(NULL,FALSE,NULL); + if (mutex == NULL) + return ERR_JMUTEX_CANTCREATEMUTEX; +#endif // JMUTEX_CRITICALSECTION + initialized = true; + return 0; +} + +int JMutex::Lock() +{ + if (!initialized) + return ERR_JMUTEX_NOTINIT; +#ifdef JMUTEX_CRITICALSECTION + EnterCriticalSection(&mutex); +#else + WaitForSingleObject(mutex,INFINITE); +#endif // JMUTEX_CRITICALSECTION + return 0; +} + +int JMutex::Unlock() +{ + if (!initialized) + return ERR_JMUTEX_NOTINIT; +#ifdef JMUTEX_CRITICALSECTION + LeaveCriticalSection(&mutex); +#else + ReleaseMutex(mutex); +#endif // JMUTEX_CRITICALSECTION + return 0; +} + diff --git a/src/jthread/win32/jthread.cpp b/src/jthread/win32/jthread.cpp new file mode 100644 index 0000000..54b110b --- /dev/null +++ b/src/jthread/win32/jthread.cpp @@ -0,0 +1,177 @@ +/* + + This file is a part of the JThread package, which contains some object- + oriented thread wrappers for different thread implementations. + + Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +*/ + +#include "jthread.h" + +#ifndef _WIN32_WCE + #include +#endif // _WIN32_WCE + +JThread::JThread() +{ + retval = NULL; + mutexinit = false; + running = false; +} + +JThread::~JThread() +{ + Kill(); +} + +int JThread::Start() +{ + if (!mutexinit) + { + if (!runningmutex.IsInitialized()) + { + if (runningmutex.Init() < 0) + return ERR_JTHREAD_CANTINITMUTEX; + } + if (!continuemutex.IsInitialized()) + { + if (continuemutex.Init() < 0) + return ERR_JTHREAD_CANTINITMUTEX; + } + if (!continuemutex2.IsInitialized()) + { + if (continuemutex2.Init() < 0) + return ERR_JTHREAD_CANTINITMUTEX; + } mutexinit = true; + } + + runningmutex.Lock(); + if (running) + { + runningmutex.Unlock(); + return ERR_JTHREAD_ALREADYRUNNING; + } + runningmutex.Unlock(); + + continuemutex.Lock(); +#ifndef _WIN32_WCE + threadhandle = (HANDLE)_beginthreadex(NULL,0,TheThread,this,0,&threadid); +#else + threadhandle = CreateThread(NULL,0,TheThread,this,0,&threadid); +#endif // _WIN32_WCE + if (threadhandle == NULL) + { + continuemutex.Unlock(); + return ERR_JTHREAD_CANTSTARTTHREAD; + } + + /* Wait until 'running' is set */ + + runningmutex.Lock(); + while (!running) + { + runningmutex.Unlock(); + Sleep(1); + runningmutex.Lock(); + } + runningmutex.Unlock(); + + continuemutex.Unlock(); + + continuemutex2.Lock(); + continuemutex2.Unlock(); + + return 0; +} + +int JThread::Kill() +{ + runningmutex.Lock(); + if (!running) + { + runningmutex.Unlock(); + return ERR_JTHREAD_NOTRUNNING; + } + TerminateThread(threadhandle,0); + CloseHandle(threadhandle); + running = false; + runningmutex.Unlock(); + return 0; +} + +bool JThread::IsRunning() +{ + bool r; + + runningmutex.Lock(); + r = running; + runningmutex.Unlock(); + return r; +} + +void *JThread::GetReturnValue() +{ + void *val; + + runningmutex.Lock(); + if (running) + val = NULL; + else + val = retval; + runningmutex.Unlock(); + return val; +} + +#ifndef _WIN32_WCE +UINT __stdcall JThread::TheThread(void *param) +#else +DWORD WINAPI JThread::TheThread(void *param) +#endif // _WIN32_WCE +{ + JThread *jthread; + void *ret; + + jthread = (JThread *)param; + + jthread->continuemutex2.Lock(); + jthread->runningmutex.Lock(); + jthread->running = true; + jthread->runningmutex.Unlock(); + + jthread->continuemutex.Lock(); + jthread->continuemutex.Unlock(); + + ret = jthread->Thread(); + + jthread->runningmutex.Lock(); + jthread->running = false; + jthread->retval = ret; + CloseHandle(jthread->threadhandle); + jthread->runningmutex.Unlock(); + return 0; +} + +void JThread::ThreadStarted() +{ + continuemutex2.Unlock(); +} + diff --git a/src/keycode.cpp b/src/keycode.cpp new file mode 100644 index 0000000..5ad5ab5 --- /dev/null +++ b/src/keycode.cpp @@ -0,0 +1,344 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "keycode.h" +#include "main.h" // For g_settings +#include "exceptions.h" + +class UnknownKeycode : public BaseException +{ +public: + UnknownKeycode(const char *s) : + BaseException(s) {}; +}; + +#define CHECKKEY(x){if(strcmp(name, #x)==0) return irr::x;} + +irr::EKEY_CODE keyname_to_keycode(const char *name) +{ + CHECKKEY(KEY_LBUTTON) + CHECKKEY(KEY_RBUTTON) + CHECKKEY(KEY_CANCEL) + CHECKKEY(KEY_MBUTTON) + CHECKKEY(KEY_XBUTTON1) + CHECKKEY(KEY_XBUTTON2) + CHECKKEY(KEY_BACK) + CHECKKEY(KEY_TAB) + CHECKKEY(KEY_CLEAR) + CHECKKEY(KEY_RETURN) + CHECKKEY(KEY_SHIFT) + CHECKKEY(KEY_CONTROL) + CHECKKEY(KEY_MENU) + CHECKKEY(KEY_PAUSE) + CHECKKEY(KEY_CAPITAL) + CHECKKEY(KEY_KANA) + CHECKKEY(KEY_HANGUEL) + CHECKKEY(KEY_HANGUL) + CHECKKEY(KEY_JUNJA) + CHECKKEY(KEY_FINAL) + CHECKKEY(KEY_HANJA) + CHECKKEY(KEY_KANJI) + CHECKKEY(KEY_ESCAPE) + CHECKKEY(KEY_CONVERT) + CHECKKEY(KEY_NONCONVERT) + CHECKKEY(KEY_ACCEPT) + CHECKKEY(KEY_MODECHANGE) + CHECKKEY(KEY_SPACE) + CHECKKEY(KEY_PRIOR) + CHECKKEY(KEY_NEXT) + CHECKKEY(KEY_END) + CHECKKEY(KEY_HOME) + CHECKKEY(KEY_LEFT) + CHECKKEY(KEY_UP) + CHECKKEY(KEY_RIGHT) + CHECKKEY(KEY_DOWN) + CHECKKEY(KEY_SELECT) + CHECKKEY(KEY_PRINT) + CHECKKEY(KEY_EXECUT) + CHECKKEY(KEY_SNAPSHOT) + CHECKKEY(KEY_INSERT) + CHECKKEY(KEY_DELETE) + CHECKKEY(KEY_HELP) + CHECKKEY(KEY_KEY_0) + CHECKKEY(KEY_KEY_1) + CHECKKEY(KEY_KEY_2) + CHECKKEY(KEY_KEY_3) + CHECKKEY(KEY_KEY_4) + CHECKKEY(KEY_KEY_5) + CHECKKEY(KEY_KEY_6) + CHECKKEY(KEY_KEY_7) + CHECKKEY(KEY_KEY_8) + CHECKKEY(KEY_KEY_9) + CHECKKEY(KEY_KEY_A) + CHECKKEY(KEY_KEY_B) + CHECKKEY(KEY_KEY_C) + CHECKKEY(KEY_KEY_D) + CHECKKEY(KEY_KEY_E) + CHECKKEY(KEY_KEY_F) + CHECKKEY(KEY_KEY_G) + CHECKKEY(KEY_KEY_H) + CHECKKEY(KEY_KEY_I) + CHECKKEY(KEY_KEY_J) + CHECKKEY(KEY_KEY_K) + CHECKKEY(KEY_KEY_L) + CHECKKEY(KEY_KEY_M) + CHECKKEY(KEY_KEY_N) + CHECKKEY(KEY_KEY_O) + CHECKKEY(KEY_KEY_P) + CHECKKEY(KEY_KEY_Q) + CHECKKEY(KEY_KEY_R) + CHECKKEY(KEY_KEY_S) + CHECKKEY(KEY_KEY_T) + CHECKKEY(KEY_KEY_U) + CHECKKEY(KEY_KEY_V) + CHECKKEY(KEY_KEY_W) + CHECKKEY(KEY_KEY_X) + CHECKKEY(KEY_KEY_Y) + CHECKKEY(KEY_KEY_Z) + CHECKKEY(KEY_LWIN) + CHECKKEY(KEY_RWIN) + CHECKKEY(KEY_APPS) + CHECKKEY(KEY_SLEEP) + CHECKKEY(KEY_NUMPAD0) + CHECKKEY(KEY_NUMPAD1) + CHECKKEY(KEY_NUMPAD2) + CHECKKEY(KEY_NUMPAD3) + CHECKKEY(KEY_NUMPAD4) + CHECKKEY(KEY_NUMPAD5) + CHECKKEY(KEY_NUMPAD6) + CHECKKEY(KEY_NUMPAD7) + CHECKKEY(KEY_NUMPAD8) + CHECKKEY(KEY_NUMPAD9) + CHECKKEY(KEY_MULTIPLY) + CHECKKEY(KEY_ADD) + CHECKKEY(KEY_SEPARATOR) + CHECKKEY(KEY_SUBTRACT) + CHECKKEY(KEY_DECIMAL) + CHECKKEY(KEY_DIVIDE) + CHECKKEY(KEY_F1) + CHECKKEY(KEY_F2) + CHECKKEY(KEY_F3) + CHECKKEY(KEY_F4) + CHECKKEY(KEY_F5) + CHECKKEY(KEY_F6) + CHECKKEY(KEY_F7) + CHECKKEY(KEY_F8) + CHECKKEY(KEY_F9) + CHECKKEY(KEY_F10) + CHECKKEY(KEY_F11) + CHECKKEY(KEY_F12) + CHECKKEY(KEY_F13) + CHECKKEY(KEY_F14) + CHECKKEY(KEY_F15) + CHECKKEY(KEY_F16) + CHECKKEY(KEY_F17) + CHECKKEY(KEY_F18) + CHECKKEY(KEY_F19) + CHECKKEY(KEY_F20) + CHECKKEY(KEY_F21) + CHECKKEY(KEY_F22) + CHECKKEY(KEY_F23) + CHECKKEY(KEY_F24) + CHECKKEY(KEY_NUMLOCK) + CHECKKEY(KEY_SCROLL) + CHECKKEY(KEY_LSHIFT) + CHECKKEY(KEY_RSHIFT) + CHECKKEY(KEY_LCONTROL) + CHECKKEY(KEY_RCONTROL) + CHECKKEY(KEY_LMENU) + CHECKKEY(KEY_RMENU) + CHECKKEY(KEY_PLUS) + CHECKKEY(KEY_COMMA) + CHECKKEY(KEY_MINUS) + CHECKKEY(KEY_PERIOD) + CHECKKEY(KEY_ATTN) + CHECKKEY(KEY_CRSEL) + CHECKKEY(KEY_EXSEL) + CHECKKEY(KEY_EREOF) + CHECKKEY(KEY_PLAY) + CHECKKEY(KEY_ZOOM) + CHECKKEY(KEY_PA1) + CHECKKEY(KEY_OEM_CLEAR) + + throw UnknownKeycode(name); +} + +static const char *KeyNames[] = +{ "-", "KEY_LBUTTON", "KEY_RBUTTON", "Cancel", "Middle Button", "X Button 1", + "X Button 2", "-", "Back", "Tab", "-", "-", "Clear", "Return", "-", + "-", "KEY_SHIFT", "Control", "Menu", "Pause", "Capital", "Kana", "-", + "Junja", "Final", "Kanji", "-", "Escape", "Convert", "Nonconvert", + "Accept", "Mode Change", "KEY_SPACE", "Priot", "Next", "KEY_END", + "KEY_HOME", "Left", "Up", "Right", "Down", "Select", "KEY_PRINT", + "Execute", "Snapshot", "Insert", "Delete", "Help", "KEY_KEY_0", + "KEY_KEY_1", "KEY_KEY_2", "KEY_KEY_3", "KEY_KEY_4", "KEY_KEY_5", + "KEY_KEY_6", "KEY_KEY_7", "KEY_KEY_8", "KEY_KEY_9", "-", "-", "-", "-", + "-", "-", "-", "KEY_KEY_A", "KEY_KEY_B", "KEY_KEY_C", "KEY_KEY_D", + "KEY_KEY_E", "KEY_KEY_F", "KEY_KEY_G", "KEY_KEY_H", "KEY_KEY_I", + "KEY_KEY_J", "KEY_KEY_K", "KEY_KEY_L", "KEY_KEY_M", "KEY_KEY_N", + "KEY_KEY_O", "KEY_KEY_P", "KEY_KEY_Q", "KEY_KEY_R", "KEY_KEY_S", + "KEY_KEY_T", "KEY_KEY_U", "KEY_KEY_V", "KEY_KEY_W", "KEY_KEY_X", + "KEY_KEY_Y", "KEY_KEY_Z", "Left Windows", "Right Windows", "Apps", "-", + "Sleep", "KEY_NUMPAD0", "KEY_NUMPAD1", "KEY_NUMPAD2", "KEY_NUMPAD3", + "KEY_NUMPAD4", "KEY_NUMPAD5", "KEY_NUMPAD6", "KEY_NUMPAD7", + "KEY_NUMPAD8", "KEY_NUMPAD9", "Numpad *", "Numpad +", "Numpad /", + "Numpad -", "Numpad .", "Numpad /", "KEY_F1", "KEY_F2", "KEY_F3", + "KEY_F4", "KEY_F5", "KEY_F6", "KEY_F7", "KEY_F8", "KEY_F9", "KEY_F10", + "KEY_F11", "KEY_F12", "KEY_F13", "KEY_F14", "KEY_F15", "KEY_F16", + "KEY_F17", "KEY_F18", "KEY_F19", "KEY_F20", "KEY_F21", "KEY_F22", + "KEY_F23", "KEY_F24", "-", "-", "-", "-", "-", "-", "-", "-", + "Num Lock", "Scroll Lock", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "KEY_LSHIFT", "KEY_RSHIFT", "Left Control", + "Right Control", "Left Menu", "Right Menu", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "Plus", "Comma", "Minus", "Period", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "Attn", "CrSel", "ExSel", + "Erase OEF", "Play", "Zoom", "PA1", "OEM Clear", "-" }; + +#define N_(text) text + +static const char *KeyNamesLang[] = + { "-", N_("Left Button"), N_("Right Button"), N_("Cancel"), N_("Middle Button"), N_("X Button 1"), + N_("X Button 2"), "-", N_("Back"), N_("Tab"), "-", "-", N_("Clear"), N_("Return"), "-", + "-", N_("Shift"), N_("Control"), N_("Menu"), N_("Pause"), N_("Capital"), N_("Kana"), "-", + N_("Junja"), N_("Final"), N_("Kanji"), "-", N_("Escape"), N_("Convert"), N_("Nonconvert"), + N_("Accept"), N_("Mode Change"), N_("Space"), N_("Prior"), N_("Next"), N_("End"), N_("Home"), + N_("Left"), N_("Up"), N_("Right"), N_("Down"), N_("Select"), N_("Print"), N_("Execute"), + N_("Snapshot"), N_("Insert"), N_("Delete"), N_("Help"), "0", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "-", "-", "-", "-", "-", "-", "-", "A", "B", "C", + "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", + "R", "S", "T", "U", "V", "W", "X", "Y", "Z", N_("Left Windows"), + N_("Right Windows"), N_("Apps"), "-", N_("Sleep"), N_("Numpad 0"), N_("Numpad 1"), + N_("Numpad 2"), N_("Numpad 3"), N_("Numpad 4"), N_("Numpad 5"), N_("Numpad 6"), N_("Numpad 7"), + N_("Numpad 8"), N_("Numpad 9"), N_("Numpad *"), N_("Numpad +"), N_("Numpad /"), N_("Numpad -"), + "Numpad .", "Numpad /", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", + "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", + "F19", "F20", "F21", "F22", "F23", "F24", "-", "-", "-", "-", "-", "-", + "-", "-", N_("Num Lock"), N_("Scroll Lock"), "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", N_("Left Shift"), N_("Right Shift"), + N_("Left Control"), N_("Right Control"), N_("Left Menu"), N_("Right Menu"), "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", N_("Plus"), N_("Comma"), N_("Minus"), N_("Period"), "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", + "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", N_("Attn"), N_("CrSel"), + N_("ExSel"), N_("Erase OEF"), N_("Play"), N_("Zoom"), N_("PA1"), N_("OEM Clear"), "-" }; + +#undef N_ + +KeyPress::KeyPress() : + Key(irr::KEY_KEY_CODES_COUNT), + Char(L'\0') +{} + +KeyPress::KeyPress(const char *name) +{ + if (strlen(name) > 4) { + try { + Key = keyname_to_keycode(name); + m_name = name; + if (strlen(name) > 8) + mbtowc(&Char, name + 8, 1); + else + Char = L'\0'; + return; + } catch (UnknownKeycode &e) {}; + } else { + // see if we can set it up as a KEY_KEY_something + m_name = "KEY_KEY_"; + m_name += name; + try { + Key = keyname_to_keycode(m_name.c_str()); + mbtowc(&Char, name, 1); + return; + } catch (UnknownKeycode &e) {}; + } + + // it's not a (known) key, just take the first char and use that + + Key = irr::KEY_KEY_CODES_COUNT; + + mbtowc(&Char, name, 1); + m_name = name[0]; +} + +KeyPress::KeyPress(const irr::SEvent::SKeyInput &in) +{ + Key = in.Key; + Char = in.Char; + if (valid_kcode(Key)) { + m_name = KeyNames[Key]; + } else { + size_t maxlen = wctomb(NULL, Char); + m_name.resize(maxlen+1, '\0'); + wctomb(&m_name[0], Char); + } +} + +const char *KeyPress::sym() const +{ + if (Key && Key < irr::KEY_KEY_CODES_COUNT) + return KeyNames[Key]; + else { + return m_name.c_str(); + } +} + +const char *KeyPress::name() const +{ + if (Key && Key < irr::KEY_KEY_CODES_COUNT) + return KeyNamesLang[Key]; + else { + return m_name.c_str(); + } +} + +const KeyPress EscapeKey("KEY_ESCAPE"); +const KeyPress NumberKey[] = { + KeyPress("KEY_KEY_0"), KeyPress("KEY_KEY_1"), KeyPress("KEY_KEY_2"), + KeyPress("KEY_KEY_3"), KeyPress("KEY_KEY_4"), KeyPress("KEY_KEY_5"), + KeyPress("KEY_KEY_6"), KeyPress("KEY_KEY_7"), KeyPress("KEY_KEY_8"), + KeyPress("KEY_KEY_9")}; + +/* + Key config +*/ + +// A simple cache for quicker lookup +core::map g_key_setting_cache; + +KeyPress getKeySetting(const char *settingname) +{ + core::map::Node *n; + n = g_key_setting_cache.find(settingname); + if(n) + return n->getValue(); + g_key_setting_cache.insert(settingname, + g_settings.get(settingname).c_str()); + return g_key_setting_cache.find(settingname)->getValue(); +} + +void clearKeyCache() +{ + g_key_setting_cache.clear(); +} diff --git a/src/keycode.h b/src/keycode.h new file mode 100644 index 0000000..28fb3f1 --- /dev/null +++ b/src/keycode.h @@ -0,0 +1,67 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef KEYCODE_HEADER +#define KEYCODE_HEADER + +#include "common_irrlicht.h" +#include + +/* A key press, consisting of either an Irrlicht keycode + or an actual char */ + +class KeyPress +{ +public: + KeyPress(); + KeyPress(const char *name); + + KeyPress(const irr::SEvent::SKeyInput &in); + + bool operator==(const KeyPress &o) const + { + return valid_kcode(Key) ? Key == o.Key : Char == o.Char; + } + + const char *sym() const; + const char *name() const; + + std::string debug() const; +protected: + static bool valid_kcode(irr::EKEY_CODE k) + { + return k > 0 && k < irr::KEY_KEY_CODES_COUNT; + } + + irr::EKEY_CODE Key; + wchar_t Char; + std::string m_name; +}; + +extern const KeyPress EscapeKey; +extern const KeyPress NumberKey[10]; + +// Key configuration getter +KeyPress getKeySetting(const char *settingname); + +// Clear fast lookup cache +void clearKeyCache(); + +#endif + diff --git a/src/light.cpp b/src/light.cpp new file mode 100644 index 0000000..f214d6e --- /dev/null +++ b/src/light.cpp @@ -0,0 +1,248 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "light.h" + +#if 1 +// This is good +// a_n+1 = a_n * 0.786 +// Length of LIGHT_MAX+1 means LIGHT_MAX is the last value. +// LIGHT_SUN is read as LIGHT_MAX from here. +u8 light_decode_table[LIGHT_MAX+1] = +{ +8, +11, +14, +18, +22, +29, +37, +47, +60, +76, +97, +123, +157, +200, +255, +}; +#else +// Use for debugging in dark +u8 light_decode_table[LIGHT_MAX+1] = +{ +58, +64, +72, +80, +88, +98, +109, +121, +135, +150, +167, +185, +206, +229, +255, +}; +#endif + +// This is reasonable with classic lighting with a light source +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +2, +3, +4, +6, +9, +13, +18, +25, +32, +35, +45, +57, +69, +79, +255 +};*/ + + +// As in minecraft, a_n+1 = a_n * 0.8 +// NOTE: This doesn't really work that well because this defines +// LIGHT_MAX as dimmer than LIGHT_SUN +// NOTE: Uh, this has had 34 left out; forget this. +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +8, +11, +14, +17, +21, +27, +42, +53, +66, +83, +104, +130, +163, +204, +255, +};*/ + +// This was a quick try of more light, manually quickly made +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +0, +7, +11, +15, +21, +29, +42, +53, +69, +85, +109, +135, +167, +205, +255, +};*/ + +// This was used for a long time, manually made +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +0, +6, +8, +11, +14, +19, +26, +34, +45, +61, +81, +108, +143, +191, +255, +};*/ + +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +0, +3, +6, +10, +18, +25, +35, +50, +75, +95, +120, +150, +185, +215, +255, +};*/ +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +0, +5, +12, +22, +35, +50, +65, +85, +100, +120, +140, +160, +185, +215, +255, +};*/ +// LIGHT_MAX is 14, 0-14 is 15 values +/*u8 light_decode_table[LIGHT_MAX+1] = +{ +0, +9, +12, +14, +16, +20, +26, +34, +45, +61, +81, +108, +143, +191, +255, +};*/ + +#if 0 +/* +#!/usr/bin/python + +from math import * +from sys import stdout + +# We want 0 at light=0 and 255 at light=LIGHT_MAX +LIGHT_MAX = 14 +#FACTOR = 0.69 +FACTOR = 0.75 + +L = [] +for i in range(1,LIGHT_MAX+1): + L.append(int(round(255.0 * FACTOR ** (i-1)))) +L.append(0) + +L.reverse() +for i in L: + stdout.write(str(i)+",\n") +*/ +u8 light_decode_table[LIGHT_MAX+1] = +{ +0, +6, +8, +11, +14, +19, +26, +34, +45, +61, +81, +108, +143, +191, +255, +}; +#endif + + diff --git a/src/light.h b/src/light.h new file mode 100644 index 0000000..c1af7fa --- /dev/null +++ b/src/light.h @@ -0,0 +1,90 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef LIGHT_HEADER +#define LIGHT_HEADER + +#include "common_irrlicht.h" +#include "debug.h" + +/* + Day/night cache: + Meshes are cached for different day-to-night transition values +*/ + +/*#define DAYNIGHT_CACHE_COUNT 3 +// First one is day, last one is night. +extern u32 daynight_cache_ratios[DAYNIGHT_CACHE_COUNT];*/ + +/* + Lower level lighting stuff +*/ + +// This directly sets the range of light. +// Actually this is not the real maximum, and this is not the +// brightest. The brightest is LIGHT_SUN. +#define LIGHT_MAX 14 +// Light is stored as 4 bits, thus 15 is the maximum. +// This brightness is reserved for sunlight +#define LIGHT_SUN 15 + +inline u8 diminish_light(u8 light) +{ + if(light == 0) + return 0; + if(light >= LIGHT_MAX) + return LIGHT_MAX - 1; + + return light - 1; +} + +inline u8 diminish_light(u8 light, u8 distance) +{ + if(distance >= light) + return 0; + return light - distance; +} + +inline u8 undiminish_light(u8 light) +{ + // We don't know if light should undiminish from this particular 0. + // Thus, keep it at 0. + if(light == 0) + return 0; + if(light == LIGHT_MAX) + return light; + + return light + 1; +} + +extern u8 light_decode_table[LIGHT_MAX+1]; + +inline u8 decode_light(u8 light) +{ + if(light == LIGHT_SUN) + return light_decode_table[LIGHT_MAX]; + + if(light > LIGHT_MAX) + light = LIGHT_MAX; + + return light_decode_table[light]; +} + +#endif + diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..b9a9573 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,1680 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* +=============================== NOTES ============================== +NOTE: Things starting with TODO are sometimes only suggestions. + +NOTE: iostream.imbue(std::locale("C")) is very slow +NOTE: Global locale is now set at initialization + +NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the + hardware buffer (it is not freed automatically) + +NOTE: A random to-do list saved here as documentation: +A list of "active blocks" in which stuff happens. (+=done) + + Add a never-resetted game timer to the server + + Add a timestamp value to blocks + + The simple rule: All blocks near some player are "active" + - Do stuff in real time in active blocks + + Handle objects + - Grow grass, delete leaves without a tree + - Spawn some mobs based on some rules + - Transform cobble to mossy cobble near water + - Run a custom script + - ...And all kinds of other dynamic stuff + + Keep track of when a block becomes active and becomes inactive + + When a block goes inactive: + + Store objects statically to block + + Store timer value as the timestamp + + When a block goes active: + + Create active objects out of static objects + - Simulate the results of what would have happened if it would have + been active for all the time + - Grow a lot of grass and so on + + Initially it is fine to send information about every active object + to every player. Eventually it should be modified to only send info + about the nearest ones. + + This was left to be done by the old system and it sends only the + nearest ones. + +Vim conversion regexpes for moving to extended content type storage: +%s/\(\.\|->\)d \([!=]=\)/\1getContent() \2/g +%s/content_features(\([^.]*\)\.d)/content_features(\1)/g +%s/\(\.\|->\)d = \([^;]*\);/\1setContent(\2);/g +%s/\(getNodeNoExNoEmerge([^)]*)\)\.d/\1.getContent()/g +%s/\(getNodeNoExNoEmerge(.*)\)\.d/\1.getContent()/g +%s/\.d;/.getContent();/g +%s/\(content_liquid\|content_flowing_liquid\|make_liquid_flowing\|content_pointable\)(\([^.]*\).d)/\1(\2.getContent())/g +Other things to note: +- node.d = node.param0 (only in raw serialization; use getContent() otherwise) +- node.param = node.param1 +- node.dir = node.param2 +- content_walkable(node.d) etc should be changed to + content_features(node).walkable etc +- Also check for lines that store the result of getContent to a 8-bit + variable and fix them (result of getContent() must be stored in + content_t, which is 16-bit) + +NOTE: Seeds in 1260:6c77e7dbfd29: +5721858502589302589: + Spawns you on a small sand island with a surface dungeon +2983455799928051958: + Enormous jungle + a surface dungeon at ~(250,0,0) + +Old, wild and random suggestions that probably won't be done: +------------------------------------------------------------- + +SUGG: If player is on ground, mainly fetch ground-level blocks + +SUGG: Expose Connection's seqnums and ACKs to server and client. + - This enables saving many packets and making a faster connection + - This also enables server to check if client has received the + most recent block sent, for example. +SUGG: Add a sane bandwidth throttling system to Connection + +SUGG: More fine-grained control of client's dumping of blocks from + memory + - ...What does this mean in the first place? + +SUGG: A map editing mode (similar to dedicated server mode) + +SUGG: Transfer more blocks in a single packet +SUGG: A blockdata combiner class, to which blocks are added and at + destruction it sends all the stuff in as few packets as possible. +SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize + it by sending more stuff in a single packet. + - Add a packet queue to RemoteClient, from which packets will be + combined with object data packets + - This is not exactly trivial: the object data packets are + sometimes very big by themselves + - This might not give much network performance gain though. + +SUGG: Precalculate lighting translation table at runtime (at startup) + - This is not doable because it is currently hand-made and not + based on some mathematical function. + - Note: This has been changing lately + +SUGG: A version number to blocks, which increments when the block is + modified (node add/remove, water update, lighting update) + - This can then be used to make sure the most recent version of + a block has been sent to client, for example + +SUGG: Make the amount of blocks sending to client and the total + amount of blocks dynamically limited. Transferring blocks is the + main network eater of this system, so it is the one that has + to be throttled so that RTTs stay low. + +SUGG: Meshes of blocks could be split into 6 meshes facing into + different directions and then only those drawn that need to be + +SUGG: Background music based on cellular automata? + http://www.earslap.com/projectslab/otomata + +SUGG: Simple light color information to air + +SUGG: Server-side objects could be moved based on nodes to enable very + lightweight operation and simple AI + - Not practical; client would still need to show smooth movement. + +SUGG: Make a system for pregenerating quick information for mapblocks, so + that the client can show them as cubes before they are actually sent + or even generated. + +SUGG: Erosion simulation at map generation time + - This might be plausible if larger areas of map were pregenerated + without lighting (which is slow) + - Simulate water flows, which would carve out dirt fast and + then turn stone into gravel and sand and relocate it. + - How about relocating minerals, too? Coal and gold in + downstream sand and gravel would be kind of cool + - This would need a better way of handling minerals, mainly + to have mineral content as a separate field. the first + parameter field is free for this. + - Simulate rock falling from cliffs when water has removed + enough solid rock from the bottom + +SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface + stuff as simple flags/values + - Light? + - A building? + And at some point make the server send this data to the client too, + instead of referring to the noise functions + - Ground height + - Surface ground type + - Trees? + +Gaming ideas: +------------- + +- Aim for something like controlling a single dwarf in Dwarf Fortress +- The player could go faster by a crafting a boat, or riding an animal +- Random NPC traders. what else? + +Game content: +------------- + +- When furnace is destroyed, move items to player's inventory +- Add lots of stuff +- Glass blocks +- Growing grass, decaying leaves + - This can be done in the active blocks I guess. + - Lots of stuff can be done in the active blocks. + - Uh, is there an active block list somewhere? I think not. Add it. +- Breaking weak structures + - This can probably be accomplished in the same way as grass +- Player health points + - When player dies, throw items on map (needs better item-on-map + implementation) +- Cobble to get mossy if near water +- More slots in furnace source list, so that multiple ingredients + are possible. +- Keys to chests? + +- The Treasure Guard; a big monster with a hammer + - The hammer does great damage, shakes the ground and removes a block + - You can drop on top of it, and have some time to attack there + before he shakes you off + +- Maybe the difficulty could come from monsters getting tougher in + far-away places, and the player starting to need something from + there when time goes by. + - The player would have some of that stuff at the beginning, and + would need new supplies of it when it runs out + +- A bomb +- A spread-items-on-map routine for the bomb, and for dying players + +- Fighting: + - Proper sword swing simulation + - Player should get damage from colliding to a wall at high speed + +Documentation: +-------------- + +Build system / running: +----------------------- + +Networking and serialization: +----------------------------- + +SUGG: Fix address to be ipv6 compatible + +User Interface: +--------------- + +Graphics: +--------- + +SUGG: Combine MapBlock's face caches to so big pieces that VBO + can be used + - That is >500 vertices + - This is not easy; all the MapBlocks close to the player would + still need to be drawn separately and combining the blocks + would have to happen in a background thread + +SUGG: Make fetching sector's blocks more efficient when rendering + sectors that have very large amounts of blocks (on client) + - Is this necessary at all? + +SUGG: Draw cubes in inventory directly with 3D drawing commands, so that + animating them is easier. + +SUGG: Option for enabling proper alpha channel for textures + +TODO: Flowing water animation + +TODO: A setting for enabling bilinear filtering for textures + +TODO: Better control of draw_control.wanted_max_blocks + +TODO: Further investigate the use of GPU lighting in addition to the + current one + +TODO: Artificial (night) light could be more yellow colored than sunlight. + - This is technically doable. + - Also the actual colors of the textures could be made less colorful + in the dark but it's a bit more difficult. + +SUGG: Somehow make the night less colorful + +TODO: Occlusion culling + - At the same time, move some of the renderMap() block choosing code + to the same place as where the new culling happens. + - Shoot some rays per frame and when ready, make a new list of + blocks for usage of renderMap and give it a new pointer to it. + +Configuration: +-------------- + +Client: +------- + +TODO: Untie client network operations from framerate + - Needs some input queues or something + - This won't give much performance boost because calculating block + meshes takes so long + +SUGG: Make morning and evening transition more smooth and maybe shorter + +TODO: Don't update all meshes always on single node changes, but + check which ones should be updated + - implement Map::updateNodeMeshes() and the usage of it + - It will give almost always a 4x boost in mesh update performance. + +- A weapon engine + +- Tool/weapon visualization + +FIXME: When disconnected to the menu, memory is not freed properly + +TODO: Investigate how much the mesh generator thread gets used when + transferring map data + +Server: +------- + +SUGG: Make an option to the server to disable building and digging near + the starting position + +FIXME: Server sometimes goes into some infinite PeerNotFoundException loop + +* Fix the problem with the server constantly saving one or a few + blocks? List the first saved block, maybe it explains. + - It is probably caused by oscillating water + - TODO: Investigate if this still happens (this is a very old one) +* Make a small history check to transformLiquids to detect and log + continuous oscillations, in such detail that they can be fixed. + +FIXME: The new optimized map sending doesn't sometimes send enough blocks + from big caves and such +FIXME: Block send distance configuration does not take effect for some reason + +Environment: +------------ + +TODO: Add proper hooks to when adding and removing active blocks + +TODO: Finish the ActiveBlockModifier stuff and use it for something + +Objects: +-------- + +TODO: Get rid of MapBlockObjects and use only ActiveObjects + - Skipping the MapBlockObject data is nasty - there is no "total + length" stored; have to make a SkipMBOs function which contains + enough of the current code to skip them properly. + +SUGG: MovingObject::move and Player::move are basically the same. + combine them. + - NOTE: This is a bit tricky because player has the sneaking ability + - NOTE: Player::move is more up-to-date. + - NOTE: There is a simple move implementation now in collision.{h,cpp} + - NOTE: MovingObject will be deleted (MapBlockObject) + +TODO: Add a long step function to objects that is called with the time + difference when block activates + +Map: +---- + +TODO: Mineral and ground material properties + - This way mineral ground toughness can be calculated with just + some formula, as well as tool strengths. Sounds too. + - There are TODOs in appropriate files: material.h, content_mapnode.h + +TODO: Flowing water to actually contain flow direction information + - There is a space for this - it just has to be implemented. + +TODO: Consider smoothening cave floors after generating them + +TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom + - delta also + +Misc. stuff: +------------ +TODO: Make sure server handles removing grass when a block is placed (etc) + - The client should not do it by itself + - NOTE: I think nobody does it currently... +TODO: Block cube placement around player's head +TODO: Protocol version field +TODO: Think about using same bits for material for fences and doors, for + example +TODO: Move mineral to param2, increment map serialization version, add + conversion + +SUGG: Restart irrlicht completely when coming back to main menu from game. + - This gets rid of everything that is stored in irrlicht's caches. + - This might be needed for texture pack selection in menu + +TODO: Merge bahamada's audio stuff (clean patch available) + +TODO: Move content_features to mapnode_content_features.{h,cpp} or so + +TODO: Fix item use() stuff; dropping a stack of cooked rats and eating + it gives 3 hearts and consumes all the rats. + +Making it more portable: +------------------------ + +Stuff to do before release: +--------------------------- + +Fixes to the current release: +----------------------------- + +Stuff to do after release: +--------------------------- + +Doing currently: +---------------- + +====================================================================== + +*/ + +#ifdef NDEBUG + #ifdef _WIN32 + #pragma message ("Disabling unit tests") + #else + #warning "Disabling unit tests" + #endif + // Disable unit tests + #define ENABLE_TESTS 0 +#else + // Enable unit tests + #define ENABLE_TESTS 1 +#endif + +#ifdef _MSC_VER + #pragma comment(lib, "Irrlicht.lib") + //#pragma comment(lib, "jthread.lib") + #pragma comment(lib, "zlibwapi.lib") + #pragma comment(lib, "Shell32.lib") + // This would get rid of the console window + //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup") +#endif + +#include +#include +#include +#include "main.h" +#include "common_irrlicht.h" +#include "debug.h" +#include "test.h" +#include "server.h" +#include "constants.h" +#include "porting.h" +#include "gettime.h" +#include "guiMessageMenu.h" +#include "filesys.h" +#include "config.h" +#include "guiMainMenu.h" +#include "mineral.h" +#include "materials.h" +#include "game.h" +#include "keycode.h" +#include "tile.h" + +#include "gettext.h" + +// This makes textures +ITextureSource *g_texturesource = NULL; + +/* + Settings. + These are loaded from the config file. +*/ + +Settings g_settings; +// This is located in defaultsettings.cpp +extern void set_default_settings(); + +// Global profiler +Profiler g_profiler; + +/* + Random stuff +*/ + +/* + GUI Stuff +*/ + +gui::IGUIEnvironment* guienv = NULL; +gui::IGUIStaticText *guiroot = NULL; + +MainMenuManager g_menumgr; + +bool noMenuActive() +{ + return (g_menumgr.menuCount() == 0); +} + +// Passed to menus to allow disconnecting and exiting + +MainGameCallback *g_gamecallback = NULL; + +/* + Debug streams +*/ + +// Connection +std::ostream *dout_con_ptr = &dummyout; +std::ostream *derr_con_ptr = &dstream_no_stderr; +//std::ostream *dout_con_ptr = &dstream_no_stderr; +//std::ostream *derr_con_ptr = &dstream_no_stderr; +//std::ostream *dout_con_ptr = &dstream; +//std::ostream *derr_con_ptr = &dstream; + +// Server +std::ostream *dout_server_ptr = &dstream; +std::ostream *derr_server_ptr = &dstream; + +// Client +std::ostream *dout_client_ptr = &dstream; +std::ostream *derr_client_ptr = &dstream; + +/* + gettime.h implementation +*/ + +// A small helper class +class TimeGetter +{ +public: + virtual u32 getTime() = 0; +}; + +// A precise irrlicht one +class IrrlichtTimeGetter: public TimeGetter +{ +public: + IrrlichtTimeGetter(IrrlichtDevice *device): + m_device(device) + {} + u32 getTime() + { + if(m_device == NULL) + return 0; + return m_device->getTimer()->getRealTime(); + } +private: + IrrlichtDevice *m_device; +}; +// Not so precise one which works without irrlicht +class SimpleTimeGetter: public TimeGetter +{ +public: + u32 getTime() + { + return porting::getTimeMs(); + } +}; + +// A pointer to a global instance of the time getter +// TODO: why? +TimeGetter *g_timegetter = NULL; + +u32 getTimeMs() +{ + if(g_timegetter == NULL) + return 0; + return g_timegetter->getTime(); +} + +/* + Event handler for Irrlicht + + NOTE: Everything possible should be moved out from here, + probably to InputHandler and the_game +*/ + +class MyEventReceiver : public IEventReceiver +{ +public: + // This is the one method that we have to implement + virtual bool OnEvent(const SEvent& event) + { + /* + React to nothing here if a menu is active + */ + if(noMenuActive() == false) + { + return false; + } + + // Remember whether each key is down or up + if(event.EventType == irr::EET_KEY_INPUT_EVENT) + { + if(event.KeyInput.PressedDown) { + keyIsDown.set(event.KeyInput); + keyWasDown.set(event.KeyInput); + } else { + keyIsDown.unset(event.KeyInput); + } + } + + if(event.EventType == irr::EET_MOUSE_INPUT_EVENT) + { + if(noMenuActive() == false) + { + left_active = false; + middle_active = false; + right_active = false; + } + else + { + //dstream<<"MyEventReceiver: mouse input"<IsKeyDown(keyCode); + } + virtual bool wasKeyDown(const KeyPress &keyCode) + { + return m_receiver->WasKeyDown(keyCode); + } + virtual v2s32 getMousePos() + { + return m_device->getCursorControl()->getPosition(); + } + virtual void setMousePos(s32 x, s32 y) + { + m_device->getCursorControl()->setPosition(x, y); + } + + virtual bool getLeftState() + { + return m_receiver->left_active; + } + virtual bool getRightState() + { + return m_receiver->right_active; + } + + virtual bool getLeftClicked() + { + return m_receiver->leftclicked; + } + virtual bool getRightClicked() + { + return m_receiver->rightclicked; + } + virtual void resetLeftClicked() + { + m_receiver->leftclicked = false; + } + virtual void resetRightClicked() + { + m_receiver->rightclicked = false; + } + + virtual bool getLeftReleased() + { + return m_receiver->leftreleased; + } + virtual bool getRightReleased() + { + return m_receiver->rightreleased; + } + virtual void resetLeftReleased() + { + m_receiver->leftreleased = false; + } + virtual void resetRightReleased() + { + m_receiver->rightreleased = false; + } + + virtual s32 getMouseWheel() + { + return m_receiver->getMouseWheel(); + } + + void clear() + { + m_receiver->clearInput(); + } +private: + IrrlichtDevice *m_device; + MyEventReceiver *m_receiver; +}; + +class RandomInputHandler : public InputHandler +{ +public: + RandomInputHandler() + { + leftdown = false; + rightdown = false; + leftclicked = false; + rightclicked = false; + leftreleased = false; + rightreleased = false; + keydown.clear(); + } + virtual bool isKeyDown(const KeyPress &keyCode) + { + return keydown[keyCode]; + } + virtual bool wasKeyDown(const KeyPress &keyCode) + { + return false; + } + virtual v2s32 getMousePos() + { + return mousepos; + } + virtual void setMousePos(s32 x, s32 y) + { + mousepos = v2s32(x,y); + } + + virtual bool getLeftState() + { + return leftdown; + } + virtual bool getRightState() + { + return rightdown; + } + + virtual bool getLeftClicked() + { + return leftclicked; + } + virtual bool getRightClicked() + { + return rightclicked; + } + virtual void resetLeftClicked() + { + leftclicked = false; + } + virtual void resetRightClicked() + { + rightclicked = false; + } + + virtual bool getLeftReleased() + { + return leftreleased; + } + virtual bool getRightReleased() + { + return rightreleased; + } + virtual void resetLeftReleased() + { + leftreleased = false; + } + virtual void resetRightReleased() + { + rightreleased = false; + } + + virtual s32 getMouseWheel() + { + return 0; + } + + virtual void step(float dtime) + { + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 40); + keydown.toggle(getKeySetting("keymap_jump")); + } + } + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 40); + keydown.toggle(getKeySetting("keymap_special1")); + } + } + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 40); + keydown.toggle(getKeySetting("keymap_forward")); + } + } + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 40); + keydown.toggle(getKeySetting("keymap_left")); + } + } + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 20); + mousespeed = v2s32(Rand(-20,20), Rand(-15,20)); + } + } + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 30); + leftdown = !leftdown; + if(leftdown) + leftclicked = true; + if(!leftdown) + leftreleased = true; + } + } + { + static float counter1 = 0; + counter1 -= dtime; + if(counter1 < 0.0) + { + counter1 = 0.1*Rand(1, 15); + rightdown = !rightdown; + if(rightdown) + rightclicked = true; + if(!rightdown) + rightreleased = true; + } + } + mousepos += mousespeed; + } + + s32 Rand(s32 min, s32 max) + { + return (myrand()%(max-min+1))+min; + } +private: + KeyList keydown; + v2s32 mousepos; + v2s32 mousespeed; + bool leftdown; + bool rightdown; + bool leftclicked; + bool rightclicked; + bool leftreleased; + bool rightreleased; +}; + +// These are defined global so that they're not optimized too much. +// Can't change them to volatile. +s16 temp16; +f32 tempf; +v3f tempv3f1; +v3f tempv3f2; +std::string tempstring; +std::string tempstring2; + +void SpeedTests() +{ + { + dstream<<"The following test should take around 20ms."< map1; + tempf = -324; + const s16 ii=300; + for(s16 y=0; y=0; y--){ + for(s16 x=0; x screensize = driver->getScreenSize(); + + video::ITexture *bgtexture = + driver->getTexture(getTexturePath("mud.png").c_str()); + if(bgtexture) + { + s32 texturesize = 128; + s32 tiled_y = screensize.Height / texturesize + 1; + s32 tiled_x = screensize.Width / texturesize + 1; + + for(s32 y=0; y rect(0,0,texturesize,texturesize); + rect += v2s32(x*texturesize, y*texturesize); + driver->draw2DImage(bgtexture, rect, + core::rect(core::position2d(0,0), + core::dimension2di(bgtexture->getSize())), + NULL, NULL, true); + } + } + + video::ITexture *logotexture = + driver->getTexture(getTexturePath("menulogo.png").c_str()); + if(logotexture) + { + v2s32 logosize(logotexture->getOriginalSize().Width, + logotexture->getOriginalSize().Height); + logosize *= 4; + + video::SColor bgcolor(255,50,50,50); + core::rect bgrect(0, screensize.Height-logosize.Y-20, + screensize.Width, screensize.Height); + driver->draw2DRectangle(bgcolor, bgrect, NULL); + + core::rect rect(0,0,logosize.X,logosize.Y); + rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y); + rect -= v2s32(logosize.X/2, 0); + driver->draw2DImage(logotexture, rect, + core::rect(core::position2d(0,0), + core::dimension2di(logotexture->getSize())), + NULL, NULL, true); + } +} + +int main(int argc, char *argv[]) +{ + /* + Initialization + */ + + // Set locale. This is for forcing '.' as the decimal point. + std::locale::global(std::locale("C")); + // This enables printing all characters in bitmap font + setlocale(LC_CTYPE, "en_US"); + + /* + Parse command line + */ + + // List all allowed options + core::map allowed_options; + allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG, + "Run server directly")); + allowed_options.insert("config", ValueSpec(VALUETYPE_STRING, + "Load configuration from specified file")); + allowed_options.insert("port", ValueSpec(VALUETYPE_STRING)); + allowed_options.insert("address", ValueSpec(VALUETYPE_STRING)); + allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING)); +#ifdef _WIN32 + allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG)); +#endif + allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG)); + + Settings cmd_args; + + bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options); + + if(ret == false || cmd_args.getFlag("help")) + { + dstream<<"Allowed options:"<::Iterator + i = allowed_options.getIterator(); + i.atEnd() == false; i++) + { + dstream<<" --"<getKey(); + if(i.getNode()->getValue().type == VALUETYPE_FLAG) + { + } + else + { + dstream<<" "; + } + dstream<getValue().help != NULL) + { + dstream<<" "<getValue().help + < filenames; + filenames.push_back(porting::path_userdata + "/minetest.conf"); +#ifdef RUN_IN_PLACE + filenames.push_back(porting::path_userdata + "/../minetest.conf"); +#endif + + for(u32 i=0; i(screenW, screenH), + 16, fullscreen, false, false, &receiver); + + if (device == 0) + return 1; // could not create selected driver. + + // Set the window caption + device->setWindowCaption(L"Minetest [Main Menu]"); + + // Create time getter + g_timegetter = new IrrlichtTimeGetter(device); + + // Create game callback for menus + g_gamecallback = new MainGameCallback(device); + + // Create texture source + g_texturesource = new TextureSource(device); + + /* + Speed tests (done after irrlicht is loaded to get timer) + */ + if(cmd_args.getFlag("speedtests")) + { + dstream<<"Running speed tests"<setResizable(true); + + bool random_input = g_settings.getBool("random_input") + || cmd_args.getFlag("random-input"); + InputHandler *input = NULL; + if(random_input) + input = new RandomInputHandler(); + else + input = new RealInputHandler(device, &receiver); + + /* + Continue initialization + */ + + //video::IVideoDriver* driver = device->getVideoDriver(); + + /* + This changes the minimum allowed number of vertices in a VBO. + Default is 500. + */ + //driver->setMinHardwareBufferVertexCount(50); + + scene::ISceneManager* smgr = device->getSceneManager(); + + guienv = device->getGUIEnvironment(); + gui::IGUISkin* skin = guienv->getSkin(); + gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str()); + if(font) + skin->setFont(font); + else + dstream<<"WARNING: Font file was not found." + " Using default font."<getFont(); + assert(font); + + u32 text_height = font->getDimension(L"Hello, world!").Height; + dstream<<"text_height="<setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0)); + skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255)); + //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0)); + //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0)); + skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0)); + skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0)); + + /* + Preload some textures and stuff + */ + + init_mapnode(); // Second call with g_texturesource set + init_mineral(); + + /* + GUI stuff + */ + + /* + If an error occurs, this is set to something and the + menu-game loop is restarted. It is then displayed before + the menu. + */ + std::wstring error_message = L""; + + // The password entered during the menu screen, + std::string password; + + /* + Menu-game loop + */ + while(device->run() && kill == false) + { + + // This is used for catching disconnects + try + { + + /* + Clear everything from the GUIEnvironment + */ + guienv->clear(); + + /* + We need some kind of a root node to be able to add + custom gui elements directly on the screen. + Otherwise they won't be automatically drawn. + */ + guiroot = guienv->addStaticText(L"", + core::rect(0, 0, 10000, 10000)); + + /* + Out-of-game menu loop. + + Loop quits when menu returns proper parameters. + */ + while(kill == false) + { + // Cursor can be non-visible when coming from the game + device->getCursorControl()->setVisible(true); + // Some stuff are left to scene manager when coming from the game + // (map at least?) + smgr->clear(); + // Reset or hide the debug gui texts + /*guitext->setText(L"Minetest-c55"); + guitext2->setVisible(false); + guitext_info->setVisible(false); + guitext_chat->setVisible(false);*/ + + // Initialize menu data + MainMenuData menudata; + menudata.address = narrow_to_wide(address); + menudata.name = narrow_to_wide(playername); + menudata.port = narrow_to_wide(itos(port)); + menudata.fancy_trees = g_settings.getBool("new_style_leaves"); + menudata.smooth_lighting = g_settings.getBool("smooth_lighting"); + menudata.creative_mode = g_settings.getBool("creative_mode"); + menudata.enable_damage = g_settings.getBool("enable_damage"); + + GUIMainMenu *menu = + new GUIMainMenu(guienv, guiroot, -1, + &g_menumgr, &menudata, g_gamecallback); + menu->allowFocusRemoval(true); + + if(error_message != L"") + { + dstream<<"WARNING: error_message = " + <drop(); + error_message = L""; + } + + video::IVideoDriver* driver = device->getVideoDriver(); + + dstream<<"Created main menu"<run() && kill == false) + { + if(menu->getStatus() == true) + break; + + //driver->beginScene(true, true, video::SColor(255,0,0,0)); + driver->beginScene(true, true, video::SColor(255,128,128,128)); + + drawMenuBackground(driver); + + guienv->drawAll(); + + driver->endScene(); + + // On some computers framerate doesn't seem to be + // automatically limited + sleep_ms(25); + } + + // Break out of menu-game loop to shut down cleanly + if(device->run() == false || kill == true) + break; + + dstream<<"Dropping main menu"<drop(); + + // Delete map if requested + if(menudata.delete_map) + { + bool r = fs::RecursiveDeleteContent(map_dir); + if(r == false) + error_message = L"Delete failed"; + continue; + } + + playername = wide_to_narrow(menudata.name); + + password = translatePassword(playername, menudata.password); + + //dstream<<"Main: password hash: '"<run() == false) + break; + + // Initialize mapnode again to enable changed graphics settings + init_mapnode(); + + /* + Run game + */ + the_game( + kill, + random_input, + input, + device, + font, + map_dir, + playername, + password, + address, + port, + error_message, + configpath + ); + + } //try + catch(con::PeerNotFoundException &e) + { + dstream<drop(); + + END_DEBUG_EXCEPTION_HANDLER + + debugstreams_deinit(); + + return 0; +} + +//END + diff --git a/src/main.h b/src/main.h new file mode 100644 index 0000000..b2dee14 --- /dev/null +++ b/src/main.h @@ -0,0 +1,154 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAIN_HEADER +#define MAIN_HEADER + +// Settings +#include "utility.h" +extern Settings g_settings; + +// This makes and maps textures +class ITextureSource; +extern ITextureSource *g_texturesource; + +// Global profiler +#include "profiler.h" +extern Profiler g_profiler; + +// Debug streams + +#include + +extern std::ostream *dout_con_ptr; +extern std::ostream *derr_con_ptr; +extern std::ostream *dout_client_ptr; +extern std::ostream *derr_client_ptr; +extern std::ostream *dout_server_ptr; +extern std::ostream *derr_server_ptr; + +#define dout_con (*dout_con_ptr) +#define derr_con (*derr_con_ptr) +#define dout_client (*dout_client_ptr) +#define derr_client (*derr_client_ptr) +#define dout_server (*dout_server_ptr) +#define derr_server (*derr_server_ptr) + +/* + All kinds of stuff that needs to be exposed from main.cpp +*/ + +#include "modalMenu.h" +#include "guiPauseMenu.h" //For IGameCallback + +extern gui::IGUIEnvironment* guienv; +extern gui::IGUIStaticText *guiroot; + +// Handler for the modal menus + +class MainMenuManager : public IMenuManager +{ +public: + virtual void createdMenu(GUIModalMenu *menu) + { + for(core::list::Iterator + i = m_stack.begin(); + i != m_stack.end(); i++) + { + assert(*i != menu); + } + + if(m_stack.size() != 0) + (*m_stack.getLast())->setVisible(false); + m_stack.push_back(menu); + } + + virtual void deletingMenu(GUIModalMenu *menu) + { + // Remove all entries if there are duplicates + bool removed_entry; + do{ + removed_entry = false; + for(core::list::Iterator + i = m_stack.begin(); + i != m_stack.end(); i++) + { + if(*i == menu) + { + m_stack.erase(i); + removed_entry = true; + break; + } + } + }while(removed_entry); + + /*core::list::Iterator i = m_stack.getLast(); + assert(*i == menu); + m_stack.erase(i);*/ + + if(m_stack.size() != 0) + (*m_stack.getLast())->setVisible(true); + } + + u32 menuCount() + { + return m_stack.size(); + } + + core::list m_stack; +}; + +extern MainMenuManager g_menumgr; + +extern bool noMenuActive(); + +class MainGameCallback : public IGameCallback +{ +public: + MainGameCallback(IrrlichtDevice *a_device): + disconnect_requested(false), + changepassword_requested(false), + device(a_device) + { + } + + virtual void exitToOS() + { + device->closeDevice(); + } + + virtual void disconnect() + { + disconnect_requested = true; + } + + virtual void changePassword() + { + changepassword_requested = true; + } + + bool disconnect_requested; + bool changepassword_requested; + IrrlichtDevice *device; +}; + +extern MainGameCallback *g_gamecallback; + +#endif + diff --git a/src/map.cpp b/src/map.cpp new file mode 100644 index 0000000..7de79c7 --- /dev/null +++ b/src/map.cpp @@ -0,0 +1,4407 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "map.h" +#include "mapsector.h" +#include "mapblock.h" +#include "main.h" +#include "client.h" +#include "filesys.h" +#include "utility.h" +#include "voxel.h" +#include "porting.h" +#include "mapgen.h" +#include "nodemetadata.h" + +/* + SQLite format specification: + - Initially only replaces sectors/ and sectors2/ + + If map.sqlite does not exist in the save dir + or the block was not found in the database + the map will try to load from sectors folder. + In either case, map.sqlite will be created + and all future saves will save there. + + Structure of map.sqlite: + Tables: + blocks + (PK) INT pos + BLOB data +*/ + +/* + Map +*/ + +Map::Map(std::ostream &dout): + m_dout(dout), + m_sector_cache(NULL) +{ + /*m_sector_mutex.Init(); + assert(m_sector_mutex.IsInitialized());*/ +} + +Map::~Map() +{ + /* + Free all MapSectors + */ + core::map::Iterator i = m_sectors.getIterator(); + for(; i.atEnd() == false; i++) + { + MapSector *sector = i.getNode()->getValue(); + delete sector; + } +} + +void Map::addEventReceiver(MapEventReceiver *event_receiver) +{ + m_event_receivers.insert(event_receiver, false); +} + +void Map::removeEventReceiver(MapEventReceiver *event_receiver) +{ + if(m_event_receivers.find(event_receiver) == NULL) + return; + m_event_receivers.remove(event_receiver); +} + +void Map::dispatchEvent(MapEditEvent *event) +{ + for(core::map::Iterator + i = m_event_receivers.getIterator(); + i.atEnd()==false; i++) + { + MapEventReceiver* event_receiver = i.getNode()->getKey(); + event_receiver->onMapEditEvent(event); + } +} + +MapSector * Map::getSectorNoGenerateNoExNoLock(v2s16 p) +{ + if(m_sector_cache != NULL && p == m_sector_cache_p){ + MapSector * sector = m_sector_cache; + return sector; + } + + core::map::Node *n = m_sectors.find(p); + + if(n == NULL) + return NULL; + + MapSector *sector = n->getValue(); + + // Cache the last result + m_sector_cache_p = p; + m_sector_cache = sector; + + return sector; +} + +MapSector * Map::getSectorNoGenerateNoEx(v2s16 p) +{ + return getSectorNoGenerateNoExNoLock(p); +} + +MapSector * Map::getSectorNoGenerate(v2s16 p) +{ + MapSector *sector = getSectorNoGenerateNoEx(p); + if(sector == NULL) + throw InvalidPositionException(); + + return sector; +} + +MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d) +{ + v2s16 p2d(p3d.X, p3d.Z); + MapSector * sector = getSectorNoGenerateNoEx(p2d); + if(sector == NULL) + return NULL; + MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y); + return block; +} + +MapBlock * Map::getBlockNoCreate(v3s16 p3d) +{ + MapBlock *block = getBlockNoCreateNoEx(p3d); + if(block == NULL) + throw InvalidPositionException(); + return block; +} + +bool Map::isNodeUnderground(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + try{ + MapBlock * block = getBlockNoCreate(blockpos); + return block->getIsUnderground(); + } + catch(InvalidPositionException &e) + { + return false; + } +} + +bool Map::isValidPosition(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + MapBlock *block = getBlockNoCreate(blockpos); + return (block != NULL); +} + +// Returns a CONTENT_IGNORE node if not found +MapNode Map::getNodeNoEx(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + return MapNode(CONTENT_IGNORE); + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + return block->getNodeNoCheck(relpos); +} + +// throws InvalidPositionException if not found +MapNode Map::getNode(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + throw InvalidPositionException(); + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + return block->getNodeNoCheck(relpos); +} + +// throws InvalidPositionException if not found +void Map::setNode(v3s16 p, MapNode & n) +{ + v3s16 blockpos = getNodeBlockPos(p); + MapBlock *block = getBlockNoCreate(blockpos); + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + block->setNodeNoCheck(relpos, n); +} + + +/* + Goes recursively through the neighbours of the node. + + Alters only transparent nodes. + + If the lighting of the neighbour is lower than the lighting of + the node was (before changing it to 0 at the step before), the + lighting of the neighbour is set to 0 and then the same stuff + repeats for the neighbour. + + The ending nodes of the routine are stored in light_sources. + This is useful when a light is removed. In such case, this + routine can be called for the light node and then again for + light_sources to re-light the area without the removed light. + + values of from_nodes are lighting values. +*/ +void Map::unspreadLight(enum LightBank bank, + core::map & from_nodes, + core::map & light_sources, + core::map & modified_blocks) +{ + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + if(from_nodes.size() == 0) + return; + + u32 blockchangecount = 0; + + core::map unlighted_nodes; + core::map::Iterator j; + j = from_nodes.getIterator(); + + /* + Initialize block cache + */ + v3s16 blockpos_last; + MapBlock *block = NULL; + // Cache this a bit, too + bool block_checked_in_modified = false; + + for(; j.atEnd() == false; j++) + { + v3s16 pos = j.getNode()->getKey(); + v3s16 blockpos = getNodeBlockPos(pos); + + // Only fetch a new block if the block position has changed + try{ + if(block == NULL || blockpos != blockpos_last){ + block = getBlockNoCreate(blockpos); + blockpos_last = blockpos; + + block_checked_in_modified = false; + blockchangecount++; + } + } + catch(InvalidPositionException &e) + { + continue; + } + + if(block->isDummy()) + continue; + + // Calculate relative position in block + v3s16 relpos = pos - blockpos_last * MAP_BLOCKSIZE; + + // Get node straight from the block + MapNode n = block->getNode(relpos); + + u8 oldlight = j.getNode()->getValue(); + + // Loop through 6 neighbors + for(u16 i=0; i<6; i++) + { + // Get the position of the neighbor node + v3s16 n2pos = pos + dirs[i]; + + // Get the block where the node is located + v3s16 blockpos = getNodeBlockPos(n2pos); + + try + { + // Only fetch a new block if the block position has changed + try{ + if(block == NULL || blockpos != blockpos_last){ + block = getBlockNoCreate(blockpos); + blockpos_last = blockpos; + + block_checked_in_modified = false; + blockchangecount++; + } + } + catch(InvalidPositionException &e) + { + continue; + } + + // Calculate relative position in block + v3s16 relpos = n2pos - blockpos * MAP_BLOCKSIZE; + // Get node straight from the block + MapNode n2 = block->getNode(relpos); + + bool changed = false; + + //TODO: Optimize output by optimizing light_sources? + + /* + If the neighbor is dimmer than what was specified + as oldlight (the light of the previous node) + */ + if(n2.getLight(bank) < oldlight) + { + /* + And the neighbor is transparent and it has some light + */ + if(n2.light_propagates() && n2.getLight(bank) != 0) + { + /* + Set light to 0 and add to queue + */ + + u8 current_light = n2.getLight(bank); + n2.setLight(bank, 0); + block->setNode(relpos, n2); + + unlighted_nodes.insert(n2pos, current_light); + changed = true; + + /* + Remove from light_sources if it is there + NOTE: This doesn't happen nearly at all + */ + /*if(light_sources.find(n2pos)) + { + std::cout<<"Removed from light_sources"< 0) + unspreadLight(bank, unlighted_nodes, light_sources, modified_blocks); +} + +/* + A single-node wrapper of the above +*/ +void Map::unLightNeighbors(enum LightBank bank, + v3s16 pos, u8 lightwas, + core::map & light_sources, + core::map & modified_blocks) +{ + core::map from_nodes; + from_nodes.insert(pos, lightwas); + + unspreadLight(bank, from_nodes, light_sources, modified_blocks); +} + +/* + Lights neighbors of from_nodes, collects all them and then + goes on recursively. +*/ +void Map::spreadLight(enum LightBank bank, + core::map & from_nodes, + core::map & modified_blocks) +{ + const v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + if(from_nodes.size() == 0) + return; + + u32 blockchangecount = 0; + + core::map lighted_nodes; + core::map::Iterator j; + j = from_nodes.getIterator(); + + /* + Initialize block cache + */ + v3s16 blockpos_last; + MapBlock *block = NULL; + // Cache this a bit, too + bool block_checked_in_modified = false; + + for(; j.atEnd() == false; j++) + //for(; j != from_nodes.end(); j++) + { + v3s16 pos = j.getNode()->getKey(); + //v3s16 pos = *j; + //dstream<<"pos=("<isDummy()) + continue; + + // Calculate relative position in block + v3s16 relpos = pos - blockpos_last * MAP_BLOCKSIZE; + + // Get node straight from the block + MapNode n = block->getNode(relpos); + + u8 oldlight = n.getLight(bank); + u8 newlight = diminish_light(oldlight); + + // Loop through 6 neighbors + for(u16 i=0; i<6; i++){ + // Get the position of the neighbor node + v3s16 n2pos = pos + dirs[i]; + + // Get the block where the node is located + v3s16 blockpos = getNodeBlockPos(n2pos); + + try + { + // Only fetch a new block if the block position has changed + try{ + if(block == NULL || blockpos != blockpos_last){ + block = getBlockNoCreate(blockpos); + blockpos_last = blockpos; + + block_checked_in_modified = false; + blockchangecount++; + } + } + catch(InvalidPositionException &e) + { + continue; + } + + // Calculate relative position in block + v3s16 relpos = n2pos - blockpos * MAP_BLOCKSIZE; + // Get node straight from the block + MapNode n2 = block->getNode(relpos); + + bool changed = false; + /* + If the neighbor is brighter than the current node, + add to list (it will light up this node on its turn) + */ + if(n2.getLight(bank) > undiminish_light(oldlight)) + { + lighted_nodes.insert(n2pos, true); + //lighted_nodes.push_back(n2pos); + changed = true; + } + /* + If the neighbor is dimmer than how much light this node + would spread on it, add to list + */ + if(n2.getLight(bank) < newlight) + { + if(n2.light_propagates()) + { + n2.setLight(bank, newlight); + block->setNode(relpos, n2); + lighted_nodes.insert(n2pos, true); + //lighted_nodes.push_back(n2pos); + changed = true; + } + } + + // Add to modified_blocks + if(changed == true && block_checked_in_modified == false) + { + // If the block is not found in modified_blocks, add. + if(modified_blocks.find(blockpos) == NULL) + { + modified_blocks.insert(blockpos, block); + } + block_checked_in_modified = true; + } + } + catch(InvalidPositionException &e) + { + continue; + } + } + } + + /*dstream<<"spreadLight(): Changed block " + < 0) + spreadLight(bank, lighted_nodes, modified_blocks); +} + +/* + A single-node source variation of the above. +*/ +void Map::lightNeighbors(enum LightBank bank, + v3s16 pos, + core::map & modified_blocks) +{ + core::map from_nodes; + from_nodes.insert(pos, true); + spreadLight(bank, from_nodes, modified_blocks); +} + +v3s16 Map::getBrightestNeighbour(enum LightBank bank, v3s16 p) +{ + v3s16 dirs[6] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + + u8 brightest_light = 0; + v3s16 brightest_pos(0,0,0); + bool found_something = false; + + // Loop through 6 neighbors + for(u16 i=0; i<6; i++){ + // Get the position of the neighbor node + v3s16 n2pos = p + dirs[i]; + MapNode n2; + try{ + n2 = getNode(n2pos); + } + catch(InvalidPositionException &e) + { + continue; + } + if(n2.getLight(bank) > brightest_light || found_something == false){ + brightest_light = n2.getLight(bank); + brightest_pos = n2pos; + found_something = true; + } + } + + if(found_something == false) + throw InvalidPositionException(); + + return brightest_pos; +} + +/* + Propagates sunlight down from a node. + Starting point gets sunlight. + + Returns the lowest y value of where the sunlight went. + + Mud is turned into grass in where the sunlight stops. +*/ +s16 Map::propagateSunlight(v3s16 start, + core::map & modified_blocks) +{ + s16 y = start.Y; + for(; ; y--) + { + v3s16 pos(start.X, y, start.Z); + + v3s16 blockpos = getNodeBlockPos(pos); + MapBlock *block; + try{ + block = getBlockNoCreate(blockpos); + } + catch(InvalidPositionException &e) + { + break; + } + + v3s16 relpos = pos - blockpos*MAP_BLOCKSIZE; + MapNode n = block->getNode(relpos); + + if(n.sunlight_propagates()) + { + n.setLight(LIGHTBANK_DAY, LIGHT_SUN); + block->setNode(relpos, n); + + modified_blocks.insert(blockpos, block); + } + else + { + /*// Turn mud into grass + if(n.getContent() == CONTENT_MUD) + { + n.setContent(CONTENT_GRASS); + block->setNode(relpos, n); + modified_blocks.insert(blockpos, block); + }*/ + + // Sunlight goes no further + break; + } + } + return y + 1; +} + +void Map::updateLighting(enum LightBank bank, + core::map & a_blocks, + core::map & modified_blocks) +{ + /*m_dout< blocks_to_update; + + core::map light_sources; + + core::map unlight_from; + + core::map::Iterator i; + i = a_blocks.getIterator(); + for(; i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + + for(;;) + { + // Don't bother with dummy blocks. + if(block->isDummy()) + break; + + v3s16 pos = block->getPos(); + modified_blocks.insert(pos, block); + + blocks_to_update.insert(pos, block); + + /* + Clear all light from block + */ + for(s16 z=0; zgetNode(v3s16(x,y,z)); + u8 oldlight = n.getLight(bank); + n.setLight(bank, 0); + block->setNode(v3s16(x,y,z), n); + + // Collect borders for unlighting + if(x==0 || x == MAP_BLOCKSIZE-1 + || y==0 || y == MAP_BLOCKSIZE-1 + || z==0 || z == MAP_BLOCKSIZE-1) + { + v3s16 p_map = p + v3s16( + MAP_BLOCKSIZE*pos.X, + MAP_BLOCKSIZE*pos.Y, + MAP_BLOCKSIZE*pos.Z); + unlight_from.insert(p_map, oldlight); + } + } + catch(InvalidPositionException &e) + { + /* + This would happen when dealing with a + dummy block. + */ + //assert(0); + dstream<<"updateLighting(): InvalidPositionException" + <propagateSunlight(light_sources); + + // If bottom is valid, we're done. + if(bottom_valid) + break; + } + else if(bank == LIGHTBANK_NIGHT) + { + // For night lighting, sunlight is not propagated + break; + } + else + { + // Invalid lighting bank + assert(0); + } + + /*dstream<<"Bottom for sunlight-propagated block (" + <::Iterator i; + i = blocks_to_update.getIterator(); + for(; i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + v3s16 p = block->getPos(); + block->setLightingExpired(false); + } + return; + } +#endif + +#if 0 + { + TimeTaker timer("unspreadLight"); + unspreadLight(bank, unlight_from, light_sources, modified_blocks); + } + + if(debug) + { + u32 diff = modified_blocks.size() - count_was; + count_was = modified_blocks.size(); + dstream<<"unspreadLight modified "<::Iterator i; + i = blocks_to_update.getIterator(); + for(; i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + v3s16 p = block->getPos(); + + // Add all surrounding blocks + vmanip.initialEmerge(p - v3s16(1,1,1), p + v3s16(1,1,1)); + + /* + Add all surrounding blocks that have up-to-date lighting + NOTE: This doesn't quite do the job (not everything + appropriate is lighted) + */ + /*for(s16 z=-1; z<=1; z++) + for(s16 y=-1; y<=1; y++) + for(s16 x=-1; x<=1; x++) + { + v3s16 p(x,y,z); + MapBlock *block = getBlockNoCreateNoEx(p); + if(block == NULL) + continue; + if(block->isDummy()) + continue; + if(block->getLightingExpired()) + continue; + vmanip.initialEmerge(p, p); + }*/ + + // Lighting of block will be updated completely + block->setLightingExpired(false); + } + + { + //TimeTaker timer("unSpreadLight"); + vmanip.unspreadLight(bank, unlight_from, light_sources); + } + { + //TimeTaker timer("spreadLight"); + vmanip.spreadLight(bank, light_sources); + } + { + //TimeTaker timer("blitBack"); + vmanip.blitBack(modified_blocks); + } + /*dstream<<"emerge_time="< & a_blocks, + core::map & modified_blocks) +{ + updateLighting(LIGHTBANK_DAY, a_blocks, modified_blocks); + updateLighting(LIGHTBANK_NIGHT, a_blocks, modified_blocks); + + /* + Update information about whether day and night light differ + */ + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } +} + +/* +*/ +void Map::addNodeAndUpdate(v3s16 p, MapNode n, + core::map &modified_blocks) +{ + /*PrintInfo(m_dout); + m_dout< light_sources; + + /* + If there is a node at top and it doesn't have sunlight, + there has not been any sunlight going down. + + Otherwise there probably is. + */ + try{ + MapNode topnode = getNode(toppos); + + if(topnode.getLight(LIGHTBANK_DAY) != LIGHT_SUN) + node_under_sunlight = false; + } + catch(InvalidPositionException &e) + { + } + +#if 0 + /* + If the new node is solid and there is grass below, change it to mud + */ + if(content_features(n).walkable == true) + { + try{ + MapNode bottomnode = getNode(bottompos); + + if(bottomnode.getContent() == CONTENT_GRASS + || bottomnode.getContent() == CONTENT_GRASS_FOOTSTEPS) + { + bottomnode.setContent(CONTENT_MUD); + setNode(bottompos, bottomnode); + } + } + catch(InvalidPositionException &e) + { + } + } +#endif + +#if 0 + /* + If the new node is mud and it is under sunlight, change it + to grass + */ + if(n.getContent() == CONTENT_MUD && node_under_sunlight) + { + n.setContent(CONTENT_GRASS); + } +#endif + + /* + Remove all light that has come out of this node + */ + + enum LightBank banks[] = + { + LIGHTBANK_DAY, + LIGHTBANK_NIGHT + }; + for(s32 i=0; i<2; i++) + { + enum LightBank bank = banks[i]; + + u8 lightwas = getNode(p).getLight(bank); + + // Add the block of the added node to modified_blocks + v3s16 blockpos = getNodeBlockPos(p); + MapBlock * block = getBlockNoCreate(blockpos); + assert(block != NULL); + modified_blocks.insert(blockpos, block); + + assert(isValidPosition(p)); + + // Unlight neighbours of node. + // This means setting light of all consequent dimmer nodes + // to 0. + // This also collects the nodes at the border which will spread + // light again into this. + unLightNeighbors(bank, p, lightwas, light_sources, modified_blocks); + + n.setLight(bank, 0); + } + + /* + If node lets sunlight through and is under sunlight, it has + sunlight too. + */ + if(node_under_sunlight && content_features(n).sunlight_propagates) + { + n.setLight(LIGHTBANK_DAY, LIGHT_SUN); + } + + /* + Set the node on the map + */ + + setNode(p, n); + + /* + Add intial metadata + */ + + NodeMetadata *meta_proto = content_features(n).initial_metadata; + if(meta_proto) + { + NodeMetadata *meta = meta_proto->clone(); + setNodeMetadata(p, meta); + } + + /* + If node is under sunlight and doesn't let sunlight through, + take all sunlighted nodes under it and clear light from them + and from where the light has been spread. + TODO: This could be optimized by mass-unlighting instead + of looping + */ + if(node_under_sunlight && !content_features(n).sunlight_propagates) + { + s16 y = p.Y - 1; + for(;; y--){ + //m_dout<::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } + + /* + Add neighboring liquid nodes and the node itself if it is + liquid (=water node was added) to transform queue. + */ + v3s16 dirs[7] = { + v3s16(0,0,0), // self + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<7; i++) + { + try + { + + v3s16 p2 = p + dirs[i]; + + MapNode n2 = getNode(p2); + if(content_liquid(n2.getContent()) || n2.getContent() == CONTENT_AIR) + { + m_transforming_liquid.push_back(p2); + } + + }catch(InvalidPositionException &e) + { + } + } +} + +/* +*/ +void Map::removeNodeAndUpdate(v3s16 p, + core::map &modified_blocks) +{ + /*PrintInfo(m_dout); + m_dout< light_sources; + + enum LightBank banks[] = + { + LIGHTBANK_DAY, + LIGHTBANK_NIGHT + }; + for(s32 i=0; i<2; i++) + { + enum LightBank bank = banks[i]; + + /* + Unlight neighbors (in case the node is a light source) + */ + unLightNeighbors(bank, p, + getNode(p).getLight(bank), + light_sources, modified_blocks); + } + + /* + Remove node metadata + */ + + removeNodeMetadata(p); + + /* + Remove the node. + This also clears the lighting. + */ + + MapNode n; + n.setContent(replace_material); + setNode(p, n); + + for(s32 i=0; i<2; i++) + { + enum LightBank bank = banks[i]; + + /* + Recalculate lighting + */ + spreadLight(bank, light_sources, modified_blocks); + } + + // Add the block of the removed node to modified_blocks + v3s16 blockpos = getNodeBlockPos(p); + MapBlock * block = getBlockNoCreate(blockpos); + assert(block != NULL); + modified_blocks.insert(blockpos, block); + + /* + If the removed node was under sunlight, propagate the + sunlight down from it and then light all neighbors + of the propagated blocks. + */ + if(node_under_sunlight) + { + s16 ybottom = propagateSunlight(p, modified_blocks); + /*m_dout< ybottom="<= ybottom; y--) + { + v3s16 p2(p.X, y, p.Z); + /*m_dout<::Iterator + i = modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + block->updateDayNightDiff(); + } + + /* + Add neighboring liquid nodes and this node to transform queue. + (it's vital for the node itself to get updated last.) + */ + v3s16 dirs[7] = { + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + v3s16(0,0,0), // self + }; + for(u16 i=0; i<7; i++) + { + try + { + + v3s16 p2 = p + dirs[i]; + + MapNode n2 = getNode(p2); + if(content_liquid(n2.getContent()) || n2.getContent() == CONTENT_AIR) + { + m_transforming_liquid.push_back(p2); + } + + }catch(InvalidPositionException &e) + { + } + } +} + +bool Map::addNodeWithEvent(v3s16 p, MapNode n) +{ + MapEditEvent event; + event.type = MEET_ADDNODE; + event.p = p; + event.n = n; + + bool succeeded = true; + try{ + core::map modified_blocks; + addNodeAndUpdate(p, n, modified_blocks); + + // Copy modified_blocks to event + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + event.modified_blocks.insert(i.getNode()->getKey(), false); + } + } + catch(InvalidPositionException &e){ + succeeded = false; + } + + dispatchEvent(&event); + + return succeeded; +} + +bool Map::removeNodeWithEvent(v3s16 p) +{ + MapEditEvent event; + event.type = MEET_REMOVENODE; + event.p = p; + + bool succeeded = true; + try{ + core::map modified_blocks; + removeNodeAndUpdate(p, modified_blocks); + + // Copy modified_blocks to event + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + event.modified_blocks.insert(i.getNode()->getKey(), false); + } + } + catch(InvalidPositionException &e){ + succeeded = false; + } + + dispatchEvent(&event); + + return succeeded; +} + +bool Map::dayNightDiffed(v3s16 blockpos) +{ + try{ + v3s16 p = blockpos + v3s16(0,0,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + // Leading edges + try{ + v3s16 p = blockpos + v3s16(-1,0,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,-1,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,0,-1); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + // Trailing edges + try{ + v3s16 p = blockpos + v3s16(1,0,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,1,0); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,0,1); + MapBlock *b = getBlockNoCreate(p); + if(b->dayNightDiffed()) + return true; + } + catch(InvalidPositionException &e){} + + return false; +} + +/* + Updates usage timers +*/ +void Map::timerUpdate(float dtime, float unload_timeout, + core::list *unloaded_blocks) +{ + bool save_before_unloading = (mapType() == MAPTYPE_SERVER); + + core::list sector_deletion_queue; + u32 deleted_blocks_count = 0; + u32 saved_blocks_count = 0; + + core::map::Iterator si; + + beginSave(); + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + + bool all_blocks_deleted = true; + + core::list blocks; + sector->getBlocks(blocks); + + for(core::list::Iterator i = blocks.begin(); + i != blocks.end(); i++) + { + MapBlock *block = (*i); + + block->incrementUsageTimer(dtime); + + if(block->getUsageTimer() > unload_timeout) + { + v3s16 p = block->getPos(); + + // Save if modified + if(block->getModified() != MOD_STATE_CLEAN + && save_before_unloading) + { + saveBlock(block); + saved_blocks_count++; + } + + // Delete from memory + sector->deleteBlock(block); + + if(unloaded_blocks) + unloaded_blocks->push_back(p); + + deleted_blocks_count++; + } + else + { + all_blocks_deleted = false; + } + } + + if(all_blocks_deleted) + { + sector_deletion_queue.push_back(si.getNode()->getKey()); + } + } + endSave(); + + // Finally delete the empty sectors + deleteSectors(sector_deletion_queue); + + if(deleted_blocks_count != 0) + { + PrintInfo(dstream); // ServerMap/ClientMap: + dstream<<"Unloaded "< &list) +{ + core::list::Iterator j; + for(j=list.begin(); j!=list.end(); j++) + { + MapSector *sector = m_sectors[*j]; + // If sector is in sector cache, remove it from there + if(m_sector_cache == sector) + m_sector_cache = NULL; + // Remove from map and delete + m_sectors.remove(*j); + delete sector; + } +} + +#if 0 +void Map::unloadUnusedData(float timeout, + core::list *deleted_blocks) +{ + core::list sector_deletion_queue; + u32 deleted_blocks_count = 0; + u32 saved_blocks_count = 0; + + core::map::Iterator si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + + bool all_blocks_deleted = true; + + core::list blocks; + sector->getBlocks(blocks); + for(core::list::Iterator i = blocks.begin(); + i != blocks.end(); i++) + { + MapBlock *block = (*i); + + if(block->getUsageTimer() > timeout) + { + // Save if modified + if(block->getModified() != MOD_STATE_CLEAN) + { + saveBlock(block); + saved_blocks_count++; + } + // Delete from memory + sector->deleteBlock(block); + deleted_blocks_count++; + } + else + { + all_blocks_deleted = false; + } + } + + if(all_blocks_deleted) + { + sector_deletion_queue.push_back(si.getNode()->getKey()); + } + } + + deleteSectors(sector_deletion_queue); + + dstream<<"Map: Unloaded "< & modified_blocks) +{ + DSTACK(__FUNCTION_NAME); + //TimeTaker timer("transformLiquids()"); + + u32 loopcount = 0; + u32 initial_size = m_transforming_liquid.size(); + + /*if(initial_size != 0) + dstream<<"transformLiquids(): initial_size="< must_reflow; + + // List of MapBlocks that will require a lighting update (due to lava) + core::map lighting_modified_blocks; + + while(m_transforming_liquid.size() != 0) + { + // This should be done here so that it is done when continue is used + if(loopcount >= initial_size * 3) + break; + loopcount++; + + /* + Get a queued transforming liquid node + */ + v3s16 p0 = m_transforming_liquid.pop_front(); + + MapNode n0 = getNodeNoEx(p0); + + /* + Collect information about current node + */ + s8 liquid_level = -1; + u8 liquid_kind = CONTENT_IGNORE; + LiquidType liquid_type = content_features(n0.getContent()).liquid_type; + switch (liquid_type) { + case LIQUID_SOURCE: + liquid_level = LIQUID_LEVEL_SOURCE; + liquid_kind = content_features(n0.getContent()).liquid_alternative_flowing; + break; + case LIQUID_FLOWING: + liquid_level = (n0.param2 & LIQUID_LEVEL_MASK); + liquid_kind = n0.getContent(); + break; + case LIQUID_NONE: + // if this is an air node, it *could* be transformed into a liquid. otherwise, + // continue with the next node. + if (n0.getContent() != CONTENT_AIR) + continue; + liquid_kind = CONTENT_AIR; + break; + } + + /* + Collect information about the environment + */ + const v3s16 *dirs = g_6dirs; + NodeNeighbor sources[6]; // surrounding sources + int num_sources = 0; + NodeNeighbor flows[6]; // surrounding flowing liquid nodes + int num_flows = 0; + NodeNeighbor airs[6]; // surrounding air + int num_airs = 0; + NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid + int num_neutrals = 0; + bool flowing_down = false; + for (u16 i = 0; i < 6; i++) { + NeighborType nt = NEIGHBOR_SAME_LEVEL; + switch (i) { + case 1: + nt = NEIGHBOR_UPPER; + break; + case 4: + nt = NEIGHBOR_LOWER; + break; + } + v3s16 npos = p0 + dirs[i]; + NodeNeighbor nb = {getNodeNoEx(npos), nt, npos}; + switch (content_features(nb.n.getContent()).liquid_type) { + case LIQUID_NONE: + if (nb.n.getContent() == CONTENT_AIR) { + airs[num_airs++] = nb; + // if the current node is a water source the neighbor + // should be enqueded for transformation regardless of whether the + // current node changes or not. + if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE) + m_transforming_liquid.push_back(npos); + // if the current node happens to be a flowing node, it will start to flow down here. + if (nb.t == NEIGHBOR_LOWER) { + flowing_down = true; + } + } else { + neutrals[num_neutrals++] = nb; + } + break; + case LIQUID_SOURCE: + // if this node is not (yet) of a liquid type, choose the first liquid type we encounter + if (liquid_kind == CONTENT_AIR) + liquid_kind = content_features(nb.n.getContent()).liquid_alternative_flowing; + if (content_features(nb.n.getContent()).liquid_alternative_flowing !=liquid_kind) { + neutrals[num_neutrals++] = nb; + } else { + sources[num_sources++] = nb; + } + break; + case LIQUID_FLOWING: + // if this node is not (yet) of a liquid type, choose the first liquid type we encounter + if (liquid_kind == CONTENT_AIR) + liquid_kind = content_features(nb.n.getContent()).liquid_alternative_flowing; + if (content_features(nb.n.getContent()).liquid_alternative_flowing != liquid_kind) { + neutrals[num_neutrals++] = nb; + } else { + flows[num_flows++] = nb; + if (nb.t == NEIGHBOR_LOWER) + flowing_down = true; + } + break; + } + } + + /* + decide on the type (and possibly level) of the current node + */ + content_t new_node_content; + s8 new_node_level = -1; + s8 max_node_level = -1; + if (num_sources >= 2 || liquid_type == LIQUID_SOURCE) { + // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid) + // or the flowing alternative of the first of the surrounding sources (if it's air), so + // it's perfectly safe to use liquid_kind here to determine the new node content. + new_node_content = content_features(liquid_kind).liquid_alternative_source; + } else if (num_sources == 1 && sources[0].t != NEIGHBOR_LOWER) { + // liquid_kind is set properly, see above + new_node_content = liquid_kind; + max_node_level = new_node_level = LIQUID_LEVEL_MAX; + } else { + // no surrounding sources, so get the maximum level that can flow into this node + for (u16 i = 0; i < num_flows; i++) { + u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK); + switch (flows[i].t) { + case NEIGHBOR_UPPER: + if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) { + max_node_level = LIQUID_LEVEL_MAX; + if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX) + max_node_level = nb_liquid_level + WATER_DROP_BOOST; + } else if (nb_liquid_level > max_node_level) + max_node_level = nb_liquid_level; + break; + case NEIGHBOR_LOWER: + break; + case NEIGHBOR_SAME_LEVEL: + if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK && + nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level) { + max_node_level = nb_liquid_level - 1; + } + break; + } + } + + u8 viscosity = content_features(liquid_kind).liquid_viscosity; + if (viscosity > 1 && max_node_level != liquid_level) { + // amount to gain, limited by viscosity + // must be at least 1 in absolute value + s8 level_inc = max_node_level - liquid_level; + if (level_inc < -viscosity || level_inc > viscosity) + new_node_level = liquid_level + level_inc/viscosity; + else if (level_inc < 0) + new_node_level = liquid_level - 1; + else if (level_inc > 0) + new_node_level = liquid_level + 1; + if (new_node_level != max_node_level) + must_reflow.push_back(p0); + } else + new_node_level = max_node_level; + + if (new_node_level >= 0) + new_node_content = liquid_kind; + else + new_node_content = CONTENT_AIR; + + } + + /* + check if anything has changed. if not, just continue with the next node. + */ + if (new_node_content == n0.getContent() && (content_features(n0.getContent()).liquid_type != LIQUID_FLOWING || + ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level && + ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK) + == flowing_down))) + continue; + + + /* + update the current node + */ + bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK)); + if (content_features(new_node_content).liquid_type == LIQUID_FLOWING) { + // set level to last 3 bits, flowing down bit to 4th bit + n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK); + } else { + // set the liquid level and flow bit to 0 + n0.param2 = ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK); + } + n0.setContent(new_node_content); + setNode(p0, n0); + v3s16 blockpos = getNodeBlockPos(p0); + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block != NULL) { + modified_blocks.insert(blockpos, block); + // If node emits light, MapBlock requires lighting update + if(content_features(n0).light_source != 0) + lighting_modified_blocks[block->getPos()] = block; + } + + /* + enqueue neighbors for update if neccessary + */ + switch (content_features(n0.getContent()).liquid_type) { + case LIQUID_SOURCE: + case LIQUID_FLOWING: + // make sure source flows into all neighboring nodes + for (u16 i = 0; i < num_flows; i++) + if (flows[i].t != NEIGHBOR_UPPER) + m_transforming_liquid.push_back(flows[i].p); + for (u16 i = 0; i < num_airs; i++) + if (airs[i].t != NEIGHBOR_UPPER) + m_transforming_liquid.push_back(airs[i].p); + break; + case LIQUID_NONE: + // this flow has turned to air; neighboring flows might need to do the same + for (u16 i = 0; i < num_flows; i++) + m_transforming_liquid.push_back(flows[i].p); + break; + } + } + //dstream<<"Map::transformLiquids(): loopcount="< 0) + m_transforming_liquid.push_back(must_reflow.pop_front()); + updateLighting(lighting_modified_blocks, modified_blocks); +} + +NodeMetadata* Map::getNodeMetadata(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + { + dstream<<"WARNING: Map::setNodeMetadata(): Block not found" + <m_node_metadata.get(p_rel); + return meta; +} + +void Map::setNodeMetadata(v3s16 p, NodeMetadata *meta) +{ + v3s16 blockpos = getNodeBlockPos(p); + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + { + dstream<<"WARNING: Map::setNodeMetadata(): Block not found" + <m_node_metadata.set(p_rel, meta); +} + +void Map::removeNodeMetadata(v3s16 p) +{ + v3s16 blockpos = getNodeBlockPos(p); + v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE; + MapBlock *block = getBlockNoCreateNoEx(blockpos); + if(block == NULL) + { + dstream<<"WARNING: Map::removeNodeMetadata(): Block not found" + <m_node_metadata.remove(p_rel); +} + +void Map::nodeMetadataStep(float dtime, + core::map &changed_blocks) +{ + /* + NOTE: + Currently there is no way to ensure that all the necessary + blocks are loaded when this is run. (They might get unloaded) + NOTE: ^- Actually, that might not be so. In a quick test it + reloaded a block with a furnace when I walked back to it from + a distance. + */ + core::map::Iterator si; + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + core::list< MapBlock * > sectorblocks; + sector->getBlocks(sectorblocks); + core::list< MapBlock * >::Iterator i; + for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++) + { + MapBlock *block = *i; + bool changed = block->m_node_metadata.step(dtime); + if(changed) + changed_blocks[block->getPos()] = block; + } + } +} + +/* + ServerMap +*/ + +ServerMap::ServerMap(std::string savedir): + Map(dout_server), + m_seed(0), + m_map_metadata_changed(true), + m_database(NULL), + m_database_read(NULL), + m_database_write(NULL) +{ + dstream<<__FUNCTION_NAME<::Iterator i = m_chunks.getIterator(); + for(; i.atEnd() == false; i++) + { + MapChunk *chunk = i.getNode()->getValue(); + delete chunk; + } +#endif +} + +void ServerMap::initBlockMake(mapgen::BlockMakeData *data, v3s16 blockpos) +{ + bool enable_mapgen_debug_info = g_settings.getBool("enable_mapgen_debug_info"); + if(enable_mapgen_debug_info) + dstream<<"initBlockMake(): ("<no_op = true; + return; + } + + data->no_op = false; + data->seed = m_seed; + data->blockpos = blockpos; + + /* + Create the whole area of this and the neighboring blocks + */ + { + //TimeTaker timer("initBlockMake() create area"); + + for(s16 x=-1; x<=1; x++) + for(s16 z=-1; z<=1; z++) + { + v2s16 sectorpos(blockpos.X+x, blockpos.Z+z); + // Sector metadata is loaded from disk if not already loaded. + ServerMapSector *sector = createSector(sectorpos); + assert(sector); + + for(s16 y=-1; y<=1; y++) + { + v3s16 p(blockpos.X+x, blockpos.Y+y, blockpos.Z+z); + //MapBlock *block = createBlock(p); + // 1) get from memory, 2) load from disk + MapBlock *block = emergeBlock(p, false); + // 3) create a blank one + if(block == NULL) + { + block = createBlock(p); + + /* + Block gets sunlight if this is true. + + Refer to the map generator heuristics. + */ + bool ug = mapgen::block_is_underground(data->seed, p); + block->setIsUnderground(ug); + } + + // Lighting will not be valid after make_chunk is called + block->setLightingExpired(true); + // Lighting will be calculated + //block->setLightingExpired(false); + } + } + } + + /* + Now we have a big empty area. + + Make a ManualMapVoxelManipulator that contains this and the + neighboring blocks + */ + + // The area that contains this block and it's neighbors + v3s16 bigarea_blocks_min = blockpos - v3s16(1,1,1); + v3s16 bigarea_blocks_max = blockpos + v3s16(1,1,1); + + data->vmanip = new ManualMapVoxelManipulator(this); + //data->vmanip->setMap(this); + + // Add the area + { + //TimeTaker timer("initBlockMake() initialEmerge"); + data->vmanip->initialEmerge(bigarea_blocks_min, bigarea_blocks_max); + } + + // Data is ready now. +} + +MapBlock* ServerMap::finishBlockMake(mapgen::BlockMakeData *data, + core::map &changed_blocks) +{ + v3s16 blockpos = data->blockpos; + /*dstream<<"finishBlockMake(): ("<no_op) + { + //dstream<<"finishBlockMake(): no-op"<vmanip.print(dstream);*/ + + /* + Blit generated stuff to map + NOTE: blitBackAll adds nearly everything to changed_blocks + */ + { + // 70ms @cs=8 + //TimeTaker timer("finishBlockMake() blitBackAll"); + data->vmanip->blitBackAll(&changed_blocks); + } + + if(enable_mapgen_debug_info) + dstream<<"finishBlockMake: changed_blocks.size()=" + <transforming_liquid.size() > 0) + { + v3s16 p = data->transforming_liquid.pop_front(); + m_transforming_liquid.push_back(p); + } + + /* + Get central block + */ + MapBlock *block = getBlockNoCreateNoEx(data->blockpos); + assert(block); + + /* + Set is_underground flag for lighting with sunlight. + + Refer to map generator heuristics. + + NOTE: This is done in initChunkMake + */ + //block->setIsUnderground(mapgen::block_is_underground(data->seed, blockpos)); + + + /* + Add sunlight to central block. + This makes in-dark-spawning monsters to not flood the whole thing. + Do not spread the light, though. + */ + /*core::map light_sources; + bool black_air_left = false; + block->propagateSunlight(light_sources, true, &black_air_left);*/ + + /* + NOTE: Lighting and object adding shouldn't really be here, but + lighting is a bit tricky to move properly to makeBlock. + TODO: Do this the right way anyway, that is, move it to makeBlock. + - There needs to be some way for makeBlock to report back if + the lighting update is going further down because of the + new block blocking light + */ + + /* + Update lighting + NOTE: This takes ~60ms, TODO: Investigate why + */ + { + TimeTaker t("finishBlockMake lighting update"); + + core::map lighting_update_blocks; +#if 1 + // Center block + lighting_update_blocks.insert(block->getPos(), block); + + /*{ + s16 x = 0; + s16 z = 0; + v3s16 p = block->getPos()+v3s16(x,1,z); + lighting_update_blocks[p] = getBlockNoCreateNoEx(p); + }*/ +#endif +#if 0 + // All modified blocks + // NOTE: Should this be done? If this is not done, then the lighting + // of the others will be updated in a different place, one by one, i + // think... or they might not? Well, at least they are left marked as + // "lighting expired"; it seems that is not handled at all anywhere, + // so enabling this will slow it down A LOT because otherwise it + // would not do this at all. This causes the black trees. + for(core::map::Iterator + i = changed_blocks.getIterator(); + i.atEnd() == false; i++) + { + lighting_update_blocks.insert(i.getNode()->getKey(), + i.getNode()->getValue()); + } + /*// Also force-add all the upmost blocks for proper sunlight + for(s16 x=-1; x<=1; x++) + for(s16 z=-1; z<=1; z++) + { + v3s16 p = block->getPos()+v3s16(x,1,z); + lighting_update_blocks[p] = getBlockNoCreateNoEx(p); + }*/ +#endif + updateLighting(lighting_update_blocks, changed_blocks); + + /* + Set lighting to non-expired state in all of them. + This is cheating, but it is not fast enough if all of them + would actually be updated. + */ + for(s16 x=-1; x<=1; x++) + for(s16 y=-1; y<=1; y++) + for(s16 z=-1; z<=1; z++) + { + v3s16 p = block->getPos()+v3s16(x,y,z); + getBlockNoCreateNoEx(p)->setLightingExpired(false); + } + + if(enable_mapgen_debug_info == false) + t.stop(true); // Hide output + } + + /* + Add random objects to block + */ + mapgen::add_random_objects(block); + + /* + Go through changed blocks + */ + for(core::map::Iterator i = changed_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + assert(block); + /* + Update day/night difference cache of the MapBlocks + */ + block->updateDayNightDiff(); + /* + Set block as modified + */ + block->raiseModified(MOD_STATE_WRITE_NEEDED); + } + + /* + Set central block as generated + */ + block->setGenerated(true); + + /* + Save changed parts of map + NOTE: Will be saved later. + */ + //save(true); + + /*dstream<<"finishBlockMake() done for ("<getPos()+v3s16(x,y,z); + MapBlock *block = getBlockNoCreateNoEx(p); + char spos[20]; + snprintf(spos, 20, "(%2d,%2d,%2d)", x, y, z); + dstream<<"Generated "< MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p2d.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p2d.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + throw InvalidPositionException("createSector(): pos. over limit"); + + /* + Generate blank sector + */ + + sector = new ServerMapSector(this, p2d); + + // Sector position on map in nodes + v2s16 nodepos2d = p2d * MAP_BLOCKSIZE; + + /* + Insert to container + */ + m_sectors.insert(p2d, sector); + + return sector; +} + +/* + This is a quick-hand function for calling makeBlock(). +*/ +MapBlock * ServerMap::generateBlock( + v3s16 p, + core::map &modified_blocks +) +{ + DSTACKF("%s: p=(%d,%d,%d)", __FUNCTION_NAME, p.X, p.Y, p.Z); + + /*dstream<<"generateBlock(): " + <<"("<getNode(p); + if(n.getContent() == CONTENT_IGNORE) + { + dstream<<"CONTENT_IGNORE at " + <<"("<setNode(v3s16(x0,y0,z0), n); + } + } + } +#endif + + if(enable_mapgen_debug_info == false) + timer.stop(true); // Hide output + + return block; +} + +MapBlock * ServerMap::createBlock(v3s16 p) +{ + DSTACKF("%s: p=(%d,%d,%d)", + __FUNCTION_NAME, p.X, p.Y, p.Z); + + /* + Do not create over-limit + */ + if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + throw InvalidPositionException("createBlock(): pos. over limit"); + + v2s16 p2d(p.X, p.Z); + s16 block_y = p.Y; + /* + This will create or load a sector if not found in memory. + If block exists on disk, it will be loaded. + + NOTE: On old save formats, this will be slow, as it generates + lighting on blocks for them. + */ + ServerMapSector *sector; + try{ + sector = (ServerMapSector*)createSector(p2d); + assert(sector->getId() == MAPSECTOR_SERVER); + } + catch(InvalidPositionException &e) + { + dstream<<"createBlock: createSector() failed"<getBlockNoCreateNoEx(block_y); + if(block) + { + if(block->isDummy()) + block->unDummify(); + return block; + } + // Create blank + block = sector->createBlankBlock(block_y); + return block; +} + +MapBlock * ServerMap::emergeBlock(v3s16 p, bool allow_generate) +{ + DSTACKF("%s: p=(%d,%d,%d), allow_generate=%d", + __FUNCTION_NAME, + p.X, p.Y, p.Z, allow_generate); + + { + MapBlock *block = getBlockNoCreateNoEx(p); + if(block && block->isDummy() == false) + return block; + } + + { + MapBlock *block = loadBlock(p); + if(block) + return block; + } + + if(allow_generate) + { + core::map modified_blocks; + MapBlock *block = generateBlock(p, modified_blocks); + if(block) + { + MapEditEvent event; + event.type = MEET_OTHER; + event.p = p; + + // Copy modified_blocks to event + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + event.modified_blocks.insert(i.getNode()->getKey(), false); + } + + // Queue event + dispatchEvent(&event); + + return block; + } + } + + return NULL; +} + +#if 0 + /* + Do not generate over-limit + */ + if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + throw InvalidPositionException("emergeBlock(): pos. over limit"); + + v2s16 p2d(p.X, p.Z); + s16 block_y = p.Y; + /* + This will create or load a sector if not found in memory. + If block exists on disk, it will be loaded. + */ + ServerMapSector *sector; + try{ + sector = createSector(p2d); + //sector = emergeSector(p2d, changed_blocks); + } + catch(InvalidPositionException &e) + { + dstream<<"emergeBlock: createSector() failed: " + <getBlockNoCreateNoEx(block_y); + + // If not found, try loading from disk + if(block == NULL) + { + block = loadBlock(p); + } + + // Handle result + if(block == NULL) + { + does_not_exist = true; + } + else if(block->isDummy() == true) + { + does_not_exist = true; + } + else if(block->getLightingExpired()) + { + lighting_expired = true; + } + else + { + // Valid block + //dstream<<"emergeBlock(): Returning already valid block"<insertBlock(block); + } + // Done. + return block; + } + + //dstream<<"Not found on disk, generating."< making one"< light_sources; + bool black_air_left = false; + bool bottom_invalid = + block->propagateSunlight(light_sources, true, + &black_air_left); + + // If sunlight didn't reach everywhere and part of block is + // above ground, lighting has to be properly updated + //if(black_air_left && some_part_underground) + if(black_air_left) + { + lighting_invalidated_blocks[block->getPos()] = block; + } + + if(bottom_invalid) + { + lighting_invalidated_blocks[block->getPos()] = block; + } + } +#endif + + return block; +} +#endif + +s16 ServerMap::findGroundLevel(v2s16 p2d) +{ +#if 0 + /* + Uh, just do something random... + */ + // Find existing map from top to down + s16 max=63; + s16 min=-64; + v3s16 p(p2d.X, max, p2d.Y); + for(; p.Y>min; p.Y--) + { + MapNode n = getNodeNoEx(p); + if(n.getContent() != CONTENT_IGNORE) + break; + } + if(p.Y == min) + goto plan_b; + // If this node is not air, go to plan b + if(getNodeNoEx(p).getContent() != CONTENT_AIR) + goto plan_b; + // Search existing walkable and return it + for(; p.Y>min; p.Y--) + { + MapNode n = getNodeNoEx(p); + if(content_walkable(n.d) && n.getContent() != CONTENT_IGNORE) + return p.Y; + } + + // Move to plan b +plan_b: +#endif + + /* + Determine from map generator noise functions + */ + + s16 level = mapgen::find_ground_level_from_noise(m_seed, p2d, 1); + return level; + + //double level = base_rock_level_2d(m_seed, p2d) + AVERAGE_MUD_AMOUNT; + //return (s16)level; +} + +void ServerMap::createDatabase() { + int e; + assert(m_database); + e = sqlite3_exec(m_database, + "CREATE TABLE IF NOT EXISTS `blocks` (" + "`pos` INT NOT NULL PRIMARY KEY," + "`data` BLOB" + ");" + , NULL, NULL, NULL); + if(e == SQLITE_ABORT) + throw FileNotGoodException("Could not create database structure"); + else + dstream<<"Server: Database structure was created"; +} + +void ServerMap::verifyDatabase() { + if(m_database) + return; + + { + std::string dbp = m_savedir + "/map.sqlite"; + bool needs_create = false; + int d; + + /* + Open the database connection + */ + + createDirs(m_savedir); + + if(!fs::PathExists(dbp)) + needs_create = true; + + d = sqlite3_open_v2(dbp.c_str(), &m_database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); + if(d != SQLITE_OK) { + dstream<<"WARNING: Database failed to open: "<::Iterator i = m_sectors.getIterator(); + for(; i.atEnd() == false; i++) + { + ServerMapSector *sector = (ServerMapSector*)i.getNode()->getValue(); + assert(sector->getId() == MAPSECTOR_SERVER); + + if(sector->differs_from_disk || only_changed == false) + { + saveSectorMeta(sector); + sector_meta_count++; + } + core::list blocks; + sector->getBlocks(blocks); + core::list::Iterator j; + + //sqlite3_exec(m_database, "BEGIN;", NULL, NULL, NULL); + for(j=blocks.begin(); j!=blocks.end(); j++) + { + MapBlock *block = *j; + + block_count_all++; + + if(block->getModified() >= MOD_STATE_WRITE_NEEDED + || only_changed == false) + { + saveBlock(block); + block_count++; + + /*dstream<<"ServerMap: Written block (" + <getPos().X<<"," + <getPos().Y<<"," + <getPos().Z<<")" + <serialize(o, version); + + sector->differs_from_disk = false; +} + +MapSector* ServerMap::loadSectorMeta(std::string sectordir, bool save_after_load) +{ + DSTACK(__FUNCTION_NAME); + // Get destination + v2s16 p2d = getSectorPos(sectordir); + + ServerMapSector *sector = NULL; + + std::string fullpath = sectordir + "/meta"; + std::ifstream is(fullpath.c_str(), std::ios_base::binary); + if(is.good() == false) + { + // If the directory exists anyway, it probably is in some old + // format. Just go ahead and create the sector. + if(fs::PathExists(sectordir)) + { + /*dstream<<"ServerMap::loadSectorMeta(): Sector metafile " + <differs_from_disk = false; + + return sector; +} + +bool ServerMap::loadSectorMeta(v2s16 p2d) +{ + DSTACK(__FUNCTION_NAME); + + MapSector *sector = NULL; + + // The directory layout we're going to load from. + // 1 - original sectors/xxxxzzzz/ + // 2 - new sectors2/xxx/zzz/ + // If we load from anything but the latest structure, we will + // immediately save to the new one, and remove the old. + int loadlayout = 1; + std::string sectordir1 = getSectorDir(p2d, 1); + std::string sectordir; + if(fs::PathExists(sectordir1)) + { + sectordir = sectordir1; + } + else + { + loadlayout = 2; + sectordir = getSectorDir(p2d, 2); + } + + try{ + sector = loadSectorMeta(sectordir, loadlayout != 2); + } + catch(InvalidFilenameException &e) + { + return false; + } + catch(FileNotGoodException &e) + { + return false; + } + catch(std::exception &e) + { + return false; + } + + return true; +} + +#if 0 +bool ServerMap::loadSectorFull(v2s16 p2d) +{ + DSTACK(__FUNCTION_NAME); + + MapSector *sector = NULL; + + // The directory layout we're going to load from. + // 1 - original sectors/xxxxzzzz/ + // 2 - new sectors2/xxx/zzz/ + // If we load from anything but the latest structure, we will + // immediately save to the new one, and remove the old. + int loadlayout = 1; + std::string sectordir1 = getSectorDir(p2d, 1); + std::string sectordir; + if(fs::PathExists(sectordir1)) + { + sectordir = sectordir1; + } + else + { + loadlayout = 2; + sectordir = getSectorDir(p2d, 2); + } + + try{ + sector = loadSectorMeta(sectordir, loadlayout != 2); + } + catch(InvalidFilenameException &e) + { + return false; + } + catch(FileNotGoodException &e) + { + return false; + } + catch(std::exception &e) + { + return false; + } + + /* + Load blocks + */ + std::vector list2 = fs::GetDirListing + (sectordir); + std::vector::iterator i2; + for(i2=list2.begin(); i2!=list2.end(); i2++) + { + // We want files + if(i2->dir) + continue; + try{ + loadBlock(sectordir, i2->name, sector, loadlayout != 2); + } + catch(InvalidFilenameException &e) + { + // This catches unknown crap in directory + } + } + + if(loadlayout != 2) + { + dstream<<"Sector converted to new layout - deleting "<< + sectordir1<isDummy()) + { + /*v3s16 p = block->getPos(); + dstream<<"ServerMap::saveBlock(): WARNING: Not writing dummy block " + <<"("<getPos(); + + +#if 0 + v2s16 p2d(p3d.X, p3d.Z); + std::string sectordir = getSectorDir(p2d); + + createDirs(sectordir); + + std::string fullpath = sectordir+"/"+getBlockFilename(p3d); + std::ofstream o(fullpath.c_str(), std::ios_base::binary); + if(o.good() == false) + throw FileNotGoodException("Cannot open block data"); +#endif + /* + [0] u8 serialization version + [1] data + */ + + verifyDatabase(); + + std::ostringstream o(std::ios_base::binary); + + o.write((char*)&version, 1); + + // Write basic data + block->serialize(o, version); + + // Write extra data stored on disk + block->serializeDiskExtra(o, version); + + // Write block to database + + std::string tmp = o.str(); + const char *bytes = tmp.c_str(); + + if(sqlite3_bind_int64(m_database_write, 1, getBlockAsInteger(p3d)) != SQLITE_OK) + dstream<<"WARNING: Block position failed to bind: "<resetModified(); +} + +void ServerMap::loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load) +{ + DSTACK(__FUNCTION_NAME); + + std::string fullpath = sectordir+"/"+blockfile; + try{ + + std::ifstream is(fullpath.c_str(), std::ios_base::binary); + if(is.good() == false) + throw FileNotGoodException("Cannot open block file"); + + v3s16 p3d = getBlockPos(sectordir, blockfile); + v2s16 p2d(p3d.X, p3d.Z); + + assert(sector->getPos() == p2d); + + u8 version = SER_FMT_VER_INVALID; + is.read((char*)&version, 1); + + if(is.fail()) + throw SerializationError("ServerMap::loadBlock(): Failed" + " to read MapBlock version"); + + /*u32 block_size = MapBlock::serializedLength(version); + SharedBuffer data(block_size); + is.read((char*)*data, block_size);*/ + + // This will always return a sector because we're the server + //MapSector *sector = emergeSector(p2d); + + MapBlock *block = NULL; + bool created_new = false; + block = sector->getBlockNoCreateNoEx(p3d.Y); + if(block == NULL) + { + block = sector->createBlankBlockNoInsert(p3d.Y); + created_new = true; + } + + // Read basic data + block->deSerialize(is, version); + + // Read extra data stored on disk + block->deSerializeDiskExtra(is, version); + + // If it's a new block, insert it to the map + if(created_new) + sector->insertBlock(block); + + /* + Save blocks loaded in old format in new format + */ + + if(version < SER_FMT_VER_HIGHEST || save_after_load) + { + saveBlock(block); + + // Should be in database now, so delete the old file + fs::RecursiveDelete(fullpath); + } + + // We just loaded it from the disk, so it's up-to-date. + block->resetModified(); + + } + catch(SerializationError &e) + { + dstream<<"WARNING: Invalid block data on disk " + <<"fullpath="< data(block_size); + is.read((char*)*data, block_size);*/ + + // This will always return a sector because we're the server + //MapSector *sector = emergeSector(p2d); + + MapBlock *block = NULL; + bool created_new = false; + block = sector->getBlockNoCreateNoEx(p3d.Y); + if(block == NULL) + { + block = sector->createBlankBlockNoInsert(p3d.Y); + created_new = true; + } + + // Read basic data + block->deSerialize(is, version); + + // Read extra data stored on disk + block->deSerializeDiskExtra(is, version); + + // If it's a new block, insert it to the map + if(created_new) + sector->insertBlock(block); + + /* + Save blocks loaded in old format in new format + */ + + if(version < SER_FMT_VER_HIGHEST || save_after_load) + { + saveBlock(block); + } + + // We just loaded it from, so it's up-to-date. + block->resetModified(); + + } + catch(SerializationError &e) + { + dstream<<"WARNING: Invalid block data in database " + <<" (SerializationError). " + <<"what()="<(-BS*1000000,-BS*1000000,-BS*1000000, + BS*1000000,BS*1000000,BS*1000000); +} + +ClientMap::~ClientMap() +{ + /*JMutexAutoLock lock(mesh_mutex); + + if(mesh != NULL) + { + mesh->drop(); + mesh = NULL; + }*/ +} + +MapSector * ClientMap::emergeSector(v2s16 p2d) +{ + DSTACK(__FUNCTION_NAME); + // Check that it doesn't exist already + try{ + return getSectorNoGenerate(p2d); + } + catch(InvalidPositionException &e) + { + } + + // Create a sector + ClientMapSector *sector = new ClientMapSector(this, p2d); + + { + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + m_sectors.insert(p2d, sector); + } + + return sector; +} + +#if 0 +void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is) +{ + DSTACK(__FUNCTION_NAME); + ClientMapSector *sector = NULL; + + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + + core::map::Node *n = m_sectors.find(p2d); + + if(n != NULL) + { + sector = (ClientMapSector*)n->getValue(); + assert(sector->getId() == MAPSECTOR_CLIENT); + } + else + { + sector = new ClientMapSector(this, p2d); + { + //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out + m_sectors.insert(p2d, sector); + } + } + + sector->deSerialize(is); +} +#endif + +void ClientMap::OnRegisterSceneNode() +{ + if(IsVisible) + { + SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID); + SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT); + } + + ISceneNode::OnRegisterSceneNode(); +} + +void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) +{ + //m_dout<getDayNightRatio(); + + m_camera_mutex.Lock(); + v3f camera_position = m_camera_position; + v3f camera_direction = m_camera_direction; + m_camera_mutex.Unlock(); + + /* + Get all blocks and draw all visible ones + */ + + v3s16 cam_pos_nodes( + camera_position.X / BS, + camera_position.Y / BS, + camera_position.Z / BS); + + v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1); + + v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d; + v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d; + + // Take a fair amount as we will be dropping more out later + v3s16 p_blocks_min( + p_nodes_min.X / MAP_BLOCKSIZE - 2, + p_nodes_min.Y / MAP_BLOCKSIZE - 2, + p_nodes_min.Z / MAP_BLOCKSIZE - 2); + v3s16 p_blocks_max( + p_nodes_max.X / MAP_BLOCKSIZE + 1, + p_nodes_max.Y / MAP_BLOCKSIZE + 1, + p_nodes_max.Z / MAP_BLOCKSIZE + 1); + + u32 vertex_count = 0; + + // For limiting number of mesh updates per frame + u32 mesh_update_count = 0; + + u32 blocks_would_have_drawn = 0; + u32 blocks_drawn = 0; + + int timecheck_counter = 0; + core::map::Iterator si; + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + { + timecheck_counter++; + if(timecheck_counter > 50) + { + timecheck_counter = 0; + int time2 = time(0); + if(time2 > time1 + 4) + { + dstream<<"ClientMap::renderMap(): " + "Rendering takes ages, returning." + <getValue(); + v2s16 sp = sector->getPos(); + + if(m_control.range_all == false) + { + if(sp.X < p_blocks_min.X + || sp.X > p_blocks_max.X + || sp.Y < p_blocks_min.Z + || sp.Y > p_blocks_max.Z) + continue; + } + + core::list< MapBlock * > sectorblocks; + sector->getBlocks(sectorblocks); + + /* + Draw blocks + */ + + u32 sector_blocks_drawn = 0; + + core::list< MapBlock * >::Iterator i; + for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++) + { + MapBlock *block = *i; + + /* + Compare block position to camera position, skip + if not seen on display + */ + + float range = 100000 * BS; + if(m_control.range_all == false) + range = m_control.wanted_range * BS; + + float d = 0.0; + if(isBlockInSight(block->getPos(), camera_position, + camera_direction, range, &d) == false) + { + continue; + } + + // Okay, this block will be drawn. Reset usage timer. + block->resetUsageTimer(); + + // This is ugly (spherical distance limit?) + /*if(m_control.range_all == false && + d - 0.5*BS*MAP_BLOCKSIZE > range) + continue;*/ + +#if 1 + /* + Update expired mesh (used for day/night change) + + It doesn't work exactly like it should now with the + tasked mesh update but whatever. + */ + + bool mesh_expired = false; + + { + JMutexAutoLock lock(block->mesh_mutex); + + mesh_expired = block->getMeshExpired(); + + // Mesh has not been expired and there is no mesh: + // block has no content + if(block->mesh == NULL && mesh_expired == false) + continue; + } + + f32 faraway = BS*50; + //f32 faraway = m_control.wanted_range * BS; + + /* + This has to be done with the mesh_mutex unlocked + */ + // Pretty random but this should work somewhat nicely + if(mesh_expired && ( + (mesh_update_count < 3 + && (d < faraway || mesh_update_count < 2) + ) + || + (m_control.range_all && mesh_update_count < 20) + ) + ) + /*if(mesh_expired && mesh_update_count < 6 + && (d < faraway || mesh_update_count < 3))*/ + { + mesh_update_count++; + + // Mesh has been expired: generate new mesh + //block->updateMesh(daynight_ratio); + m_client->addUpdateMeshTask(block->getPos()); + + mesh_expired = false; + } + +#endif + /* + Draw the faces of the block + */ + { + JMutexAutoLock lock(block->mesh_mutex); + + scene::SMesh *mesh = block->mesh; + + if(mesh == NULL) + continue; + + blocks_would_have_drawn++; + if(blocks_drawn >= m_control.wanted_max_blocks + && m_control.range_all == false + && d > m_control.wanted_min_range * BS) + continue; + + blocks_drawn++; + sector_blocks_drawn++; + + u32 c = mesh->getMeshBufferCount(); + + for(u32 i=0; igetMeshBuffer(i); + const video::SMaterial& material = buf->getMaterial(); + video::IMaterialRenderer* rnd = + driver->getMaterialRenderer(material.MaterialType); + bool transparent = (rnd && rnd->isTransparent()); + // Render transparent on transparent pass and likewise. + if(transparent == is_transparent_pass) + { + /* + This *shouldn't* hurt too much because Irrlicht + doesn't change opengl textures if the old + material is set again. + */ + driver->setMaterial(buf->getMaterial()); + driver->drawMeshBuffer(buf); + vertex_count += buf->getVertexCount(); + } + } + } + } // foreach sectorblocks + + if(sector_blocks_drawn != 0) + { + m_last_drawn_sectors[sp] = true; + } + } + + m_control.blocks_drawn = blocks_drawn; + m_control.blocks_would_have_drawn = blocks_would_have_drawn; + + /*dstream<<"renderMap(): is_transparent_pass="< *affected_blocks) +{ + bool changed = false; + /* + Add it to all blocks touching it + */ + v3s16 dirs[7] = { + v3s16(0,0,0), // this + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + // Relative position of requested node + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + if(blockref->setTempMod(relpos, mod)) + { + changed = true; + } + } + if(changed && affected_blocks!=NULL) + { + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + affected_blocks->insert(blockpos, blockref); + } + } + return changed; +} + +bool ClientMap::clearTempMod(v3s16 p, + core::map *affected_blocks) +{ + bool changed = false; + v3s16 dirs[7] = { + v3s16(0,0,0), // this + v3s16(0,0,1), // back + v3s16(0,1,0), // top + v3s16(1,0,0), // right + v3s16(0,0,-1), // front + v3s16(0,-1,0), // bottom + v3s16(-1,0,0), // left + }; + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + // Relative position of requested node + v3s16 relpos = p - blockpos*MAP_BLOCKSIZE; + if(blockref->clearTempMod(relpos)) + { + changed = true; + } + } + if(changed && affected_blocks!=NULL) + { + for(u16 i=0; i<7; i++) + { + v3s16 p2 = p + dirs[i]; + // Block position of neighbor (or requested) node + v3s16 blockpos = getNodeBlockPos(p2); + MapBlock * blockref = getBlockNoCreateNoEx(blockpos); + if(blockref == NULL) + continue; + affected_blocks->insert(blockpos, blockref); + } + } + return changed; +} + +void ClientMap::expireMeshes(bool only_daynight_diffed) +{ + TimeTaker timer("expireMeshes()"); + + core::map::Iterator si; + si = m_sectors.getIterator(); + for(; si.atEnd() == false; si++) + { + MapSector *sector = si.getNode()->getValue(); + + core::list< MapBlock * > sectorblocks; + sector->getBlocks(sectorblocks); + + core::list< MapBlock * >::Iterator i; + for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++) + { + MapBlock *block = *i; + + if(only_daynight_diffed && dayNightDiffed(block->getPos()) == false) + { + continue; + } + + { + JMutexAutoLock lock(block->mesh_mutex); + if(block->mesh != NULL) + { + /*block->mesh->drop(); + block->mesh = NULL;*/ + block->setMeshExpired(true); + } + } + } + } +} + +void ClientMap::updateMeshes(v3s16 blockpos, u32 daynight_ratio) +{ + assert(mapType() == MAPTYPE_CLIENT); + + try{ + v3s16 p = blockpos + v3s16(0,0,0); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} + // Leading edge + try{ + v3s16 p = blockpos + v3s16(-1,0,0); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,-1,0); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} + try{ + v3s16 p = blockpos + v3s16(0,0,-1); + MapBlock *b = getBlockNoCreate(p); + b->updateMesh(daynight_ratio); + //b->setMeshExpired(true); + } + catch(InvalidPositionException &e){} +} + +#if 0 +/* + Update mesh of block in which the node is, and if the node is at the + leading edge, update the appropriate leading blocks too. +*/ +void ClientMap::updateNodeMeshes(v3s16 nodepos, u32 daynight_ratio) +{ + v3s16 dirs[4] = { + v3s16(0,0,0), + v3s16(-1,0,0), + v3s16(0,-1,0), + v3s16(0,0,-1), + }; + v3s16 blockposes[4]; + for(u32 i=0; i<4; i++) + { + v3s16 np = nodepos + dirs[i]; + blockposes[i] = getNodeBlockPos(np); + // Don't update mesh of block if it has been done already + bool already_updated = false; + for(u32 j=0; jupdateMesh(daynight_ratio); + } +} +#endif + +void ClientMap::PrintInfo(std::ostream &out) +{ + out<<"ClientMap: "; +} + +#endif // !SERVER + +/* + MapVoxelManipulator +*/ + +MapVoxelManipulator::MapVoxelManipulator(Map *map) +{ + m_map = map; +} + +MapVoxelManipulator::~MapVoxelManipulator() +{ + /*dstream<<"MapVoxelManipulator: blocks: "<::Node *n; + n = m_loaded_blocks.find(p); + if(n != NULL) + continue; + + bool block_data_inexistent = false; + try + { + TimeTaker timer1("emerge load", &emerge_load_time); + + /*dstream<<"Loading block (caller_id="<getBlockNoCreate(p); + if(block->isDummy()) + block_data_inexistent = true; + else + block->copyTo(*this); + } + catch(InvalidPositionException &e) + { + block_data_inexistent = true; + } + + if(block_data_inexistent) + { + VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + // Fill with VOXELFLAG_INEXISTENT + for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) + for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) + { + s32 i = m_area.index(a.MinEdge.X,y,z); + memset(&m_flags[i], VOXELFLAG_INEXISTENT, MAP_BLOCKSIZE); + } + } + + m_loaded_blocks.insert(p, !block_data_inexistent); + } + + //dstream<<"emerge done"< & modified_blocks) +{ + if(m_area.getExtent() == v3s16(0,0,0)) + return; + + //TimeTaker timer1("blitBack"); + + /*dstream<<"blitBack(): m_loaded_blocks.size()=" + <getBlockNoCreate(blockpos); + blockpos_last = blockpos; + block_checked_in_modified = false; + } + + // Calculate relative position in block + v3s16 relpos = p - blockpos * MAP_BLOCKSIZE; + + // Don't continue if nothing has changed here + if(block->getNode(relpos) == n) + continue; + + //m_map->setNode(m_area.MinEdge + p, n); + block->setNode(relpos, n); + + /* + Make sure block is in modified_blocks + */ + if(block_checked_in_modified == false) + { + modified_blocks[blockpos] = block; + block_checked_in_modified = true; + } + } + catch(InvalidPositionException &e) + { + } + } +} + +ManualMapVoxelManipulator::ManualMapVoxelManipulator(Map *map): + MapVoxelManipulator(map), + m_create_area(false) +{ +} + +ManualMapVoxelManipulator::~ManualMapVoxelManipulator() +{ +} + +void ManualMapVoxelManipulator::emerge(VoxelArea a, s32 caller_id) +{ + // Just create the area so that it can be pointed to + VoxelManipulator::emerge(a, caller_id); +} + +void ManualMapVoxelManipulator::initialEmerge( + v3s16 blockpos_min, v3s16 blockpos_max) +{ + TimeTaker timer1("initialEmerge", &emerge_time); + + // Units of these are MapBlocks + v3s16 p_min = blockpos_min; + v3s16 p_max = blockpos_max; + + VoxelArea block_area_nodes + (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + + u32 size_MB = block_area_nodes.getVolume()*4/1000000; + if(size_MB >= 1) + { + dstream<<"initialEmerge: area: "; + block_area_nodes.print(dstream); + dstream<<" ("<::Node *n; + n = m_loaded_blocks.find(p); + if(n != NULL) + continue; + + bool block_data_inexistent = false; + try + { + TimeTaker timer1("emerge load", &emerge_load_time); + + MapBlock *block = m_map->getBlockNoCreate(p); + if(block->isDummy()) + block_data_inexistent = true; + else + block->copyTo(*this); + } + catch(InvalidPositionException &e) + { + block_data_inexistent = true; + } + + if(block_data_inexistent) + { + /* + Mark area inexistent + */ + VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1)); + // Fill with VOXELFLAG_INEXISTENT + for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++) + for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++) + { + s32 i = m_area.index(a.MinEdge.X,y,z); + memset(&m_flags[i], VOXELFLAG_INEXISTENT, MAP_BLOCKSIZE); + } + } + + m_loaded_blocks.insert(p, !block_data_inexistent); + } +} + +void ManualMapVoxelManipulator::blitBackAll( + core::map * modified_blocks) +{ + if(m_area.getExtent() == v3s16(0,0,0)) + return; + + /* + Copy data of all blocks + */ + for(core::map::Iterator + i = m_loaded_blocks.getIterator(); + i.atEnd() == false; i++) + { + v3s16 p = i.getNode()->getKey(); + bool existed = i.getNode()->getValue(); + if(existed == false) + { + // The Great Bug was found using this + /*dstream<<"ManualMapVoxelManipulator::blitBackAll: " + <<"Inexistent ("<getBlockNoCreateNoEx(p); + if(block == NULL) + { + dstream<<"WARNING: "<<__FUNCTION_NAME + <<": got NULL block " + <<"("<copyFrom(*this); + + if(modified_blocks) + modified_blocks->insert(p, block); + } +} + +//END diff --git a/src/map.h b/src/map.h new file mode 100644 index 0000000..e0b67eb --- /dev/null +++ b/src/map.h @@ -0,0 +1,657 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAP_HEADER +#define MAP_HEADER + +#include +#include +#include +#include +#include + +#include "common_irrlicht.h" +#include "mapnode.h" +#include "mapblock_nodemod.h" +#include "constants.h" +#include "voxel.h" + +extern "C" { + #include "sqlite3.h" +} + +class MapSector; +class ServerMapSector; +class ClientMapSector; +class MapBlock; +class NodeMetadata; + +namespace mapgen{ + struct BlockMakeData; +}; + +/* + MapEditEvent +*/ + +#define MAPTYPE_BASE 0 +#define MAPTYPE_SERVER 1 +#define MAPTYPE_CLIENT 2 + +enum MapEditEventType{ + // Node added (changed from air or something else to something) + MEET_ADDNODE, + // Node removed (changed to air) + MEET_REMOVENODE, + // Node metadata of block changed (not knowing which node exactly) + // p stores block coordinate + MEET_BLOCK_NODE_METADATA_CHANGED, + // Anything else (modified_blocks are set unsent) + MEET_OTHER +}; + +struct MapEditEvent +{ + MapEditEventType type; + v3s16 p; + MapNode n; + core::map modified_blocks; + u16 already_known_by_peer; + + MapEditEvent(): + type(MEET_OTHER), + already_known_by_peer(0) + { + } + + MapEditEvent * clone() + { + MapEditEvent *event = new MapEditEvent(); + event->type = type; + event->p = p; + event->n = n; + for(core::map::Iterator + i = modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + bool v = i.getNode()->getValue(); + event->modified_blocks.insert(p, v); + } + return event; + } +}; + +class MapEventReceiver +{ +public: + // event shall be deleted by caller after the call. + virtual void onMapEditEvent(MapEditEvent *event) = 0; +}; + +class Map /*: public NodeContainer*/ +{ +public: + + Map(std::ostream &dout); + virtual ~Map(); + + /*virtual u16 nodeContainerId() const + { + return NODECONTAINER_ID_MAP; + }*/ + + virtual s32 mapType() const + { + return MAPTYPE_BASE; + } + + /* + Drop (client) or delete (server) the map. + */ + virtual void drop() + { + delete this; + } + + void addEventReceiver(MapEventReceiver *event_receiver); + void removeEventReceiver(MapEventReceiver *event_receiver); + // event shall be deleted by caller after the call. + void dispatchEvent(MapEditEvent *event); + + // On failure returns NULL + MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d); + // Same as the above (there exists no lock anymore) + MapSector * getSectorNoGenerateNoEx(v2s16 p2d); + // On failure throws InvalidPositionException + MapSector * getSectorNoGenerate(v2s16 p2d); + // Gets an existing sector or creates an empty one + //MapSector * getSectorCreate(v2s16 p2d); + + /* + This is overloaded by ClientMap and ServerMap to allow + their differing fetch methods. + */ + virtual MapSector * emergeSector(v2s16 p){ return NULL; } + virtual MapSector * emergeSector(v2s16 p, + core::map &changed_blocks){ return NULL; } + + // Returns InvalidPositionException if not found + MapBlock * getBlockNoCreate(v3s16 p); + // Returns NULL if not found + MapBlock * getBlockNoCreateNoEx(v3s16 p); + + // Returns InvalidPositionException if not found + bool isNodeUnderground(v3s16 p); + + bool isValidPosition(v3s16 p); + + // throws InvalidPositionException if not found + MapNode getNode(v3s16 p); + + // throws InvalidPositionException if not found + void setNode(v3s16 p, MapNode & n); + + // Returns a CONTENT_IGNORE node if not found + MapNode getNodeNoEx(v3s16 p); + + void unspreadLight(enum LightBank bank, + core::map & from_nodes, + core::map & light_sources, + core::map & modified_blocks); + + void unLightNeighbors(enum LightBank bank, + v3s16 pos, u8 lightwas, + core::map & light_sources, + core::map & modified_blocks); + + void spreadLight(enum LightBank bank, + core::map & from_nodes, + core::map & modified_blocks); + + void lightNeighbors(enum LightBank bank, + v3s16 pos, + core::map & modified_blocks); + + v3s16 getBrightestNeighbour(enum LightBank bank, v3s16 p); + + s16 propagateSunlight(v3s16 start, + core::map & modified_blocks); + + void updateLighting(enum LightBank bank, + core::map & a_blocks, + core::map & modified_blocks); + + void updateLighting(core::map & a_blocks, + core::map & modified_blocks); + + /* + These handle lighting but not faces. + */ + void addNodeAndUpdate(v3s16 p, MapNode n, + core::map &modified_blocks); + void removeNodeAndUpdate(v3s16 p, + core::map &modified_blocks); + + /* + Wrappers for the latter ones. + These emit events. + Return true if succeeded, false if not. + */ + bool addNodeWithEvent(v3s16 p, MapNode n); + bool removeNodeWithEvent(v3s16 p); + + /* + Takes the blocks at the edges into account + */ + bool dayNightDiffed(v3s16 blockpos); + + //core::aabbox3d getDisplayedBlockArea(); + + //bool updateChangedVisibleArea(); + + // Call these before and after saving of many blocks + virtual void beginSave() {return;}; + virtual void endSave() {return;}; + + virtual void save(bool only_changed){assert(0);}; + + // Server implements this. + // Client leaves it as no-op. + virtual void saveBlock(MapBlock *block){}; + + /* + Updates usage timers and unloads unused blocks and sectors. + Saves modified blocks before unloading on MAPTYPE_SERVER. + */ + void timerUpdate(float dtime, float unload_timeout, + core::list *unloaded_blocks=NULL); + + // Deletes sectors and their blocks from memory + // Takes cache into account + // If deleted sector is in sector cache, clears cache + void deleteSectors(core::list &list); + +#if 0 + /* + Unload unused data + = flush changed to disk and delete from memory, if usage timer of + block is more than timeout + */ + void unloadUnusedData(float timeout, + core::list *deleted_blocks=NULL); +#endif + + // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: " + virtual void PrintInfo(std::ostream &out); + + void transformLiquids(core::map & modified_blocks); + + /* + Node metadata + These are basically coordinate wrappers to MapBlock + */ + + NodeMetadata* getNodeMetadata(v3s16 p); + void setNodeMetadata(v3s16 p, NodeMetadata *meta); + void removeNodeMetadata(v3s16 p); + void nodeMetadataStep(float dtime, + core::map &changed_blocks); + + /* + Misc. + */ + core::map *getSectorsPtr(){return &m_sectors;} + + /* + Variables + */ + +protected: + + std::ostream &m_dout; + + core::map m_event_receivers; + + core::map m_sectors; + + // Be sure to set this to NULL when the cached sector is deleted + MapSector *m_sector_cache; + v2s16 m_sector_cache_p; + + // Queued transforming water nodes + UniqueQueue m_transforming_liquid; +}; + +/* + ServerMap + + This is the only map class that is able to generate map. +*/ + +class ServerMap : public Map +{ +public: + /* + savedir: directory to which map data should be saved + */ + ServerMap(std::string savedir); + ~ServerMap(); + + s32 mapType() const + { + return MAPTYPE_SERVER; + } + + /* + Get a sector from somewhere. + - Check memory + - Check disk (doesn't load blocks) + - Create blank one + */ + ServerMapSector * createSector(v2s16 p); + + /* + Blocks are generated by using these and makeBlock(). + */ + void initBlockMake(mapgen::BlockMakeData *data, v3s16 blockpos); + MapBlock* finishBlockMake(mapgen::BlockMakeData *data, + core::map &changed_blocks); + + // A non-threaded wrapper to the above + MapBlock * generateBlock( + v3s16 p, + core::map &modified_blocks + ); + + /* + Get a block from somewhere. + - Memory + - Create blank + */ + MapBlock * createBlock(v3s16 p); + + /* + Forcefully get a block from somewhere. + - Memory + - Load from disk + - Generate + */ + MapBlock * emergeBlock(v3s16 p, bool allow_generate=true); + + // Helper for placing objects on ground level + s16 findGroundLevel(v2s16 p2d); + + /* + Misc. helper functions for fiddling with directory and file + names when saving + */ + void createDirs(std::string path); + // returns something like "map/sectors/xxxxxxxx" + std::string getSectorDir(v2s16 pos, int layout = 2); + // dirname: final directory name + v2s16 getSectorPos(std::string dirname); + v3s16 getBlockPos(std::string sectordir, std::string blockfile); + static std::string getBlockFilename(v3s16 p); + + /* + Database functions + */ + // Create the database structure + void createDatabase(); + // Verify we can read/write to the database + void verifyDatabase(); + // Get an integer suitable for a block + static sqlite3_int64 getBlockAsInteger(const v3s16 pos); + + // Returns true if the database file does not exist + bool loadFromFolders(); + + // Call these before and after saving of blocks + void beginSave(); + void endSave(); + + void save(bool only_changed); + //void loadAll(); + + // Saves map seed and possibly other stuff + void saveMapMeta(); + void loadMapMeta(); + + /*void saveChunkMeta(); + void loadChunkMeta();*/ + + // The sector mutex should be locked when calling most of these + + // This only saves sector-specific data such as the heightmap + // (no MapBlocks) + // DEPRECATED? Sectors have no metadata anymore. + void saveSectorMeta(ServerMapSector *sector); + MapSector* loadSectorMeta(std::string dirname, bool save_after_load); + bool loadSectorMeta(v2s16 p2d); + + // Full load of a sector including all blocks. + // returns true on success, false on failure. + bool loadSectorFull(v2s16 p2d); + // If sector is not found in memory, try to load it from disk. + // Returns true if sector now resides in memory + //bool deFlushSector(v2s16 p2d); + + void saveBlock(MapBlock *block); + // This will generate a sector with getSector if not found. + void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false); + MapBlock* loadBlock(v3s16 p); + // Database version + void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false); + + // For debug printing + virtual void PrintInfo(std::ostream &out); + + bool isSavingEnabled(){ return m_map_saving_enabled; } + + u64 getSeed(){ return m_seed; } + +private: + // Seed used for all kinds of randomness + u64 m_seed; + + std::string m_savedir; + bool m_map_saving_enabled; + +#if 0 + // Chunk size in MapSectors + // If 0, chunks are disabled. + s16 m_chunksize; + // Chunks + core::map m_chunks; +#endif + + /* + Metadata is re-written on disk only if this is true. + This is reset to false when written on disk. + */ + bool m_map_metadata_changed; + + /* + SQLite database and statements + */ + sqlite3 *m_database; + sqlite3_stmt *m_database_read; + sqlite3_stmt *m_database_write; +}; + +/* + ClientMap stuff +*/ + +#ifndef SERVER + +struct MapDrawControl +{ + MapDrawControl(): + range_all(false), + wanted_range(50), + wanted_max_blocks(0), + wanted_min_range(0), + blocks_drawn(0), + blocks_would_have_drawn(0) + { + } + // Overrides limits by drawing everything + bool range_all; + // Wanted drawing range + float wanted_range; + // Maximum number of blocks to draw + u32 wanted_max_blocks; + // Blocks in this range are drawn regardless of number of blocks drawn + float wanted_min_range; + // Number of blocks rendered is written here by the renderer + u32 blocks_drawn; + // Number of blocks that would have been drawn in wanted_range + u32 blocks_would_have_drawn; +}; + +class Client; + +/* + ClientMap + + This is the only map class that is able to render itself on screen. +*/ + +class ClientMap : public Map, public scene::ISceneNode +{ +public: + ClientMap( + Client *client, + MapDrawControl &control, + scene::ISceneNode* parent, + scene::ISceneManager* mgr, + s32 id + ); + + ~ClientMap(); + + s32 mapType() const + { + return MAPTYPE_CLIENT; + } + + void drop() + { + ISceneNode::drop(); + } + + void updateCamera(v3f pos, v3f dir) + { + JMutexAutoLock lock(m_camera_mutex); + m_camera_position = pos; + m_camera_direction = dir; + } + + /* + Forcefully get a sector from somewhere + */ + MapSector * emergeSector(v2s16 p); + + //void deSerializeSector(v2s16 p2d, std::istream &is); + + /* + ISceneNode methods + */ + + virtual void OnRegisterSceneNode(); + + virtual void render() + { + video::IVideoDriver* driver = SceneManager->getVideoDriver(); + driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); + renderMap(driver, SceneManager->getSceneNodeRenderPass()); + } + + virtual const core::aabbox3d& getBoundingBox() const + { + return m_box; + } + + void renderMap(video::IVideoDriver* driver, s32 pass); + + /* + Methods for setting temporary modifications to nodes for + drawing. + + Returns true if something changed. + + All blocks whose mesh could have been changed are inserted + to affected_blocks. + */ + bool setTempMod(v3s16 p, NodeMod mod, + core::map *affected_blocks=NULL); + bool clearTempMod(v3s16 p, + core::map *affected_blocks=NULL); + // Efficient implementation needs a cache of TempMods + //void clearTempMods(); + + void expireMeshes(bool only_daynight_diffed); + + /* + Update the faces of the given block and blocks on the + leading edge. + */ + void updateMeshes(v3s16 blockpos, u32 daynight_ratio); + + // Update meshes that touch the node + //void updateNodeMeshes(v3s16 nodepos, u32 daynight_ratio); + + // For debug printing + virtual void PrintInfo(std::ostream &out); + + // Check if sector was drawn on last render() + bool sectorWasDrawn(v2s16 p) + { + return (m_last_drawn_sectors.find(p) != NULL); + } + +private: + Client *m_client; + + core::aabbox3d m_box; + + // This is the master heightmap mesh + //scene::SMesh *mesh; + //JMutex mesh_mutex; + + MapDrawControl &m_control; + + v3f m_camera_position; + v3f m_camera_direction; + JMutex m_camera_mutex; + + core::map m_last_drawn_sectors; +}; + +#endif + +class MapVoxelManipulator : public VoxelManipulator +{ +public: + MapVoxelManipulator(Map *map); + virtual ~MapVoxelManipulator(); + + virtual void clear() + { + VoxelManipulator::clear(); + m_loaded_blocks.clear(); + } + + virtual void emerge(VoxelArea a, s32 caller_id=-1); + + void blitBack(core::map & modified_blocks); + +protected: + Map *m_map; + /* + key = blockpos + value = block existed when loaded + */ + core::map m_loaded_blocks; +}; + +class ManualMapVoxelManipulator : public MapVoxelManipulator +{ +public: + ManualMapVoxelManipulator(Map *map); + virtual ~ManualMapVoxelManipulator(); + + void setMap(Map *map) + {m_map = map;} + + virtual void emerge(VoxelArea a, s32 caller_id=-1); + + void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max); + + // This is much faster with big chunks of generated data + void blitBackAll(core::map * modified_blocks); + +protected: + bool m_create_area; +}; + +#endif + diff --git a/src/mapblock.cpp b/src/mapblock.cpp new file mode 100644 index 0000000..44ca75f --- /dev/null +++ b/src/mapblock.cpp @@ -0,0 +1,996 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "mapblock.h" +#include "map.h" +// For g_settings +#include "main.h" +#include "light.h" +#include + +/* + MapBlock +*/ + +MapBlock::MapBlock(Map *parent, v3s16 pos, bool dummy): + m_parent(parent), + m_pos(pos), + m_modified(MOD_STATE_WRITE_NEEDED), + is_underground(false), + m_lighting_expired(true), + m_day_night_differs(false), + m_generated(false), + m_objects(this), + m_timestamp(BLOCK_TIMESTAMP_UNDEFINED), + m_usage_timer(0) +{ + data = NULL; + if(dummy == false) + reallocate(); + + //m_spawn_timer = -10000; + +#ifndef SERVER + m_mesh_expired = false; + mesh_mutex.Init(); + mesh = NULL; + m_temp_mods_mutex.Init(); +#endif +} + +MapBlock::~MapBlock() +{ +#ifndef SERVER + { + JMutexAutoLock lock(mesh_mutex); + + if(mesh) + { + mesh->drop(); + mesh = NULL; + } + } +#endif + + if(data) + delete[] data; +} + +bool MapBlock::isValidPositionParent(v3s16 p) +{ + if(isValidPosition(p)) + { + return true; + } + else{ + return m_parent->isValidPosition(getPosRelative() + p); + } +} + +MapNode MapBlock::getNodeParent(v3s16 p) +{ + if(isValidPosition(p) == false) + { + return m_parent->getNode(getPosRelative() + p); + } + else + { + if(data == NULL) + throw InvalidPositionException(); + return data[p.Z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + p.Y*MAP_BLOCKSIZE + p.X]; + } +} + +void MapBlock::setNodeParent(v3s16 p, MapNode & n) +{ + if(isValidPosition(p) == false) + { + m_parent->setNode(getPosRelative() + p, n); + } + else + { + if(data == NULL) + throw InvalidPositionException(); + data[p.Z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + p.Y*MAP_BLOCKSIZE + p.X] = n; + } +} + +MapNode MapBlock::getNodeParentNoEx(v3s16 p) +{ + if(isValidPosition(p) == false) + { + try{ + return m_parent->getNode(getPosRelative() + p); + } + catch(InvalidPositionException &e) + { + return MapNode(CONTENT_IGNORE); + } + } + else + { + if(data == NULL) + { + return MapNode(CONTENT_IGNORE); + } + return data[p.Z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + p.Y*MAP_BLOCKSIZE + p.X]; + } +} + +#ifndef SERVER + +#if 1 +void MapBlock::updateMesh(u32 daynight_ratio) +{ +#if 0 + /* + DEBUG: If mesh has been generated, don't generate it again + */ + { + JMutexAutoLock meshlock(mesh_mutex); + if(mesh != NULL) + return; + } +#endif + + MeshMakeData data; + data.fill(daynight_ratio, this); + + scene::SMesh *mesh_new = makeMapBlockMesh(&data); + + /* + Replace the mesh + */ + + replaceMesh(mesh_new); + +} +#endif + +void MapBlock::replaceMesh(scene::SMesh *mesh_new) +{ + mesh_mutex.Lock(); + + //scene::SMesh *mesh_old = mesh[daynight_i]; + //mesh[daynight_i] = mesh_new; + + scene::SMesh *mesh_old = mesh; + mesh = mesh_new; + setMeshExpired(false); + + if(mesh_old != NULL) + { + // Remove hardware buffers of meshbuffers of mesh + // NOTE: No way, this runs in a different thread and everything + /*u32 c = mesh_old->getMeshBufferCount(); + for(u32 i=0; igetMeshBuffer(i); + }*/ + + /*dstream<<"mesh_old->getReferenceCount()=" + <getReferenceCount()<getMeshBufferCount(); + for(u32 i=0; igetMeshBuffer(i); + dstream<<"buf->getReferenceCount()=" + <getReferenceCount()<drop(); + + //delete mesh_old; + } + + mesh_mutex.Unlock(); +} + +#endif // !SERVER + +/* + Propagates sunlight down through the block. + Doesn't modify nodes that are not affected by sunlight. + + Returns false if sunlight at bottom block is invalid. + Returns true if sunlight at bottom block is valid. + Returns true if bottom block doesn't exist. + + If there is a block above, continues from it. + If there is no block above, assumes there is sunlight, unless + is_underground is set or highest node is water. + + All sunlighted nodes are added to light_sources. + + if remove_light==true, sets non-sunlighted nodes black. + + if black_air_left!=NULL, it is set to true if non-sunlighted + air is left in block. +*/ +bool MapBlock::propagateSunlight(core::map & light_sources, + bool remove_light, bool *black_air_left) +{ + // Whether the sunlight at the top of the bottom block is valid + bool block_below_is_valid = true; + + v3s16 pos_relative = getPosRelative(); + + for(s16 x=0; x=0; y--) + { + MapNode n = getNodeRef(p2d.X, y, p2d.Y); + if(content_features(n).walkable) + { + if(y == MAP_BLOCKSIZE-1) + return -2; + else + return y; + } + } + return -1; + } + catch(InvalidPositionException &e) + { + return -3; + } +} + +/* + Serialization +*/ + +void MapBlock::serialize(std::ostream &os, u8 version) +{ + if(!ser_ver_supported(version)) + throw VersionMismatchException("ERROR: MapBlock format not supported"); + + if(data == NULL) + { + throw SerializationError("ERROR: Not writing dummy block."); + } + + // These have no compression + if(version <= 3 || version == 5 || version == 6) + { + u32 nodecount = MAP_BLOCKSIZE*MAP_BLOCKSIZE*MAP_BLOCKSIZE; + + u32 buflen = 1 + nodecount * MapNode::serializedLength(version); + SharedBuffer dest(buflen); + + dest[0] = is_underground; + for(u32 i=0; i materialdata(nodecount); + for(u32 i=0; i lightdata(nodecount); + for(u32 i=0; i= 10) + { + // Get and compress param2 + SharedBuffer param2data(nodecount); + for(u32 i=0; i= 18) + { + if(m_generated == false) + flags |= 0x08; + } + os.write((char*)&flags, 1); + + u32 nodecount = MAP_BLOCKSIZE*MAP_BLOCKSIZE*MAP_BLOCKSIZE; + + /* + Get data + */ + + // Serialize nodes + SharedBuffer databuf_nodelist(nodecount*3); + for(u32 i=0; i databuf(nodecount*3); + for(u32 i=0; i= 14) + { + if(version <= 15) + { + try{ + std::ostringstream oss(std::ios_base::binary); + m_node_metadata.serialize(oss); + os< d(len); + is.read((char*)*d, len); + if(is.gcount() != len) + throw SerializationError + ("MapBlock::deSerialize: no enough input data"); + data[i].deSerialize(*d, version); + } + } + else if(version <= 10) + { + u32 nodecount = MAP_BLOCKSIZE*MAP_BLOCKSIZE*MAP_BLOCKSIZE; + + u8 t8; + is.read((char*)&t8, 1); + is_underground = t8; + + { + // Uncompress and set material data + std::ostringstream os(std::ios_base::binary); + decompress(is, os, version); + std::string s = os.str(); + if(s.size() != nodecount) + throw SerializationError + ("MapBlock::deSerialize: invalid format"); + for(u32 i=0; i= 10) + { + // Uncompress and set param2 data + std::ostringstream os(std::ios_base::binary); + decompress(is, os, version); + std::string s = os.str(); + if(s.size() != nodecount) + throw SerializationError + ("MapBlock::deSerialize: invalid format"); + for(u32 i=0; i= 18) + m_generated = (flags & 0x08) ? false : true; + + // Uncompress data + std::ostringstream os(std::ios_base::binary); + decompress(is, os, version); + std::string s = os.str(); + if(s.size() != nodecount*3) + throw SerializationError + ("MapBlock::deSerialize: decompress resulted in size" + " other than nodecount*3"); + + // deserialize nodes from buffer + for(u32 i=0; i= 14) + { + // Ignore errors + try{ + if(version <= 15) + { + std::string data = deSerializeString(is); + std::istringstream iss(data, std::ios_base::binary); + m_node_metadata.deSerialize(iss); + } + else + { + //std::string data = deSerializeLongString(is); + std::ostringstream oss(std::ios_base::binary); + decompressZlib(is, oss); + std::istringstream iss(oss.str(), std::ios_base::binary); + m_node_metadata.deSerialize(iss); + } + } + catch(SerializationError &e) + { + dstream<<"WARNING: MapBlock::deSerialize(): Ignoring an error" + <<" while deserializing node metadata"<= 9) + { + //serializeObjects(os, version); // DEPRECATED + // count=0 + writeU16(os, 0); + } + + // Versions up from 15 have static objects. + if(version >= 15) + { + m_static_objects.serialize(os); + } + + // Timestamp + if(version >= 17) + { + writeU32(os, getTimestamp()); + } +} + +void MapBlock::deSerializeDiskExtra(std::istream &is, u8 version) +{ + /* + Versions up from 9 have block objects. + */ + if(version >= 9) + { + updateObjects(is, version, NULL, 0); + } + + /* + Versions up from 15 have static objects. + */ + if(version >= 15) + { + m_static_objects.deSerialize(is); + } + + // Timestamp + if(version >= 17) + { + setTimestamp(readU32(is)); + } + else + { + setTimestamp(BLOCK_TIMESTAMP_UNDEFINED); + } +} + +/* + Get a quick string to describe what a block actually contains +*/ +std::string analyze_block(MapBlock *block) +{ + if(block == NULL) + { + return "NULL"; + } + + std::ostringstream desc; + + v3s16 p = block->getPos(); + char spos[20]; + snprintf(spos, 20, "(%2d,%2d,%2d), ", p.X, p.Y, p.Z); + desc<getModified()) + { + case MOD_STATE_CLEAN: + desc<<"CLEAN, "; + break; + case MOD_STATE_WRITE_AT_UNLOAD: + desc<<"WRITE_AT_UNLOAD, "; + break; + case MOD_STATE_WRITE_NEEDED: + desc<<"WRITE_NEEDED, "; + break; + default: + desc<<"unknown getModified()="+itos(block->getModified())+", "; + } + + if(block->isGenerated()) + desc<<"is_gen [X], "; + else + desc<<"is_gen [ ], "; + + if(block->getIsUnderground()) + desc<<"is_ug [X], "; + else + desc<<"is_ug [ ], "; + +#ifndef SERVER + if(block->getMeshExpired()) + desc<<"mesh_exp [X], "; + else + desc<<"mesh_exp [ ], "; +#endif + + if(block->getLightingExpired()) + desc<<"lighting_exp [X], "; + else + desc<<"lighting_exp [ ], "; + + if(block->isDummy()) + { + desc<<"Dummy, "; + } + else + { + // We'll just define the numbers here, don't want to include + // content_mapnode.h + const content_t content_water = 2; + const content_t content_watersource = 9; + const content_t content_tree = 0x801; + const content_t content_leaves = 0x802; + const content_t content_jungletree = 0x815; + + bool full_ignore = true; + bool some_ignore = false; + bool full_air = true; + bool some_air = false; + bool trees = false; + bool water = false; + for(s16 z0=0; z0getNode(p); + content_t c = n.getContent(); + if(c == CONTENT_IGNORE) + some_ignore = true; + else + full_ignore = false; + if(c == CONTENT_AIR) + some_air = true; + else + full_air = false; + if(c == content_tree || c == content_jungletree + || c == content_leaves) + trees = true; + if(c == content_water + || c == content_watersource) + water = true; + } + + desc<<"content {"; + + std::ostringstream ss; + + if(full_ignore) + ss<<"IGNORE (full), "; + else if(some_ignore) + ss<<"IGNORE, "; + + if(full_air) + ss<<"AIR (full), "; + else if(some_air) + ss<<"AIR, "; + + if(trees) + ss<<"trees, "; + if(water) + ss<<"water, "; + + if(ss.str().size()>=2) + desc< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAPBLOCK_HEADER +#define MAPBLOCK_HEADER + +#include +#include +#include +#include "debug.h" +#include "common_irrlicht.h" +#include "mapnode.h" +#include "exceptions.h" +#include "serialization.h" +#include "constants.h" +#include "mapblockobject.h" +#include "voxel.h" +#include "nodemetadata.h" +#include "staticobject.h" +#include "mapblock_nodemod.h" +#ifndef SERVER + #include "mapblock_mesh.h" +#endif + +class Map; + +#define BLOCK_TIMESTAMP_UNDEFINED 0xffffffff + +/*// Named by looking towards z+ +enum{ + FACE_BACK=0, + FACE_TOP, + FACE_RIGHT, + FACE_FRONT, + FACE_BOTTOM, + FACE_LEFT +};*/ + +enum ModifiedState +{ + // Has not been modified. + MOD_STATE_CLEAN = 0, + MOD_RESERVED1 = 1, + // Has been modified, and will be saved when being unloaded. + MOD_STATE_WRITE_AT_UNLOAD = 2, + MOD_RESERVED3 = 3, + // Has been modified, and will be saved as soon as possible. + MOD_STATE_WRITE_NEEDED = 4, + MOD_RESERVED5 = 5, +}; + +// NOTE: If this is enabled, set MapBlock to be initialized with +// CONTENT_IGNORE. +/*enum BlockGenerationStatus +{ + // Completely non-generated (filled with CONTENT_IGNORE). + BLOCKGEN_UNTOUCHED=0, + // Trees or similar might have been blitted from other blocks to here. + // Otherwise, the block contains CONTENT_IGNORE + BLOCKGEN_FROM_NEIGHBORS=2, + // Has been generated, but some neighbors might put some stuff in here + // when they are generated. + // Does not contain any CONTENT_IGNORE + BLOCKGEN_SELF_GENERATED=4, + // The block and all its neighbors have been generated + BLOCKGEN_FULLY_GENERATED=6 +};*/ + +#if 0 +enum +{ + NODECONTAINER_ID_MAPBLOCK, + NODECONTAINER_ID_MAPSECTOR, + NODECONTAINER_ID_MAP, + NODECONTAINER_ID_MAPBLOCKCACHE, + NODECONTAINER_ID_VOXELMANIPULATOR, +}; + +class NodeContainer +{ +public: + virtual bool isValidPosition(v3s16 p) = 0; + virtual MapNode getNode(v3s16 p) = 0; + virtual void setNode(v3s16 p, MapNode & n) = 0; + virtual u16 nodeContainerId() const = 0; + + MapNode getNodeNoEx(v3s16 p) + { + try{ + return getNode(p); + } + catch(InvalidPositionException &e){ + return MapNode(CONTENT_IGNORE); + } + } +}; +#endif + +/* + MapBlock itself +*/ + +class MapBlock /*: public NodeContainer*/ +{ +public: + MapBlock(Map *parent, v3s16 pos, bool dummy=false); + ~MapBlock(); + + /*virtual u16 nodeContainerId() const + { + return NODECONTAINER_ID_MAPBLOCK; + }*/ + + Map * getParent() + { + return m_parent; + } + + void reallocate() + { + if(data != NULL) + delete[] data; + u32 l = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE; + data = new MapNode[l]; + for(u32 i=0; i getBox() + { + return core::aabbox3d(getPosRelative(), + getPosRelative() + + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE) + - v3s16(1,1,1)); + } + + /* + Regular MapNode get-setters + */ + + bool isValidPosition(v3s16 p) + { + if(data == NULL) + return false; + return (p.X >= 0 && p.X < MAP_BLOCKSIZE + && p.Y >= 0 && p.Y < MAP_BLOCKSIZE + && p.Z >= 0 && p.Z < MAP_BLOCKSIZE); + } + + MapNode getNode(s16 x, s16 y, s16 z) + { + if(data == NULL) + throw InvalidPositionException(); + if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException(); + if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException(); + if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException(); + return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x]; + } + + MapNode getNode(v3s16 p) + { + return getNode(p.X, p.Y, p.Z); + } + + MapNode getNodeNoEx(v3s16 p) + { + try{ + return getNode(p.X, p.Y, p.Z); + }catch(InvalidPositionException &e){ + return MapNode(CONTENT_IGNORE); + } + } + + void setNode(s16 x, s16 y, s16 z, MapNode & n) + { + if(data == NULL) + throw InvalidPositionException(); + if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException(); + if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException(); + if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException(); + data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x] = n; + raiseModified(MOD_STATE_WRITE_NEEDED); + } + + void setNode(v3s16 p, MapNode & n) + { + setNode(p.X, p.Y, p.Z, n); + } + + /* + Non-checking variants of the above + */ + + MapNode getNodeNoCheck(s16 x, s16 y, s16 z) + { + if(data == NULL) + throw InvalidPositionException(); + return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x]; + } + + MapNode getNodeNoCheck(v3s16 p) + { + return getNodeNoCheck(p.X, p.Y, p.Z); + } + + void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n) + { + if(data == NULL) + throw InvalidPositionException(); + data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x] = n; + raiseModified(MOD_STATE_WRITE_NEEDED); + } + + void setNodeNoCheck(v3s16 p, MapNode & n) + { + setNodeNoCheck(p.X, p.Y, p.Z, n); + } + + /* + These functions consult the parent container if the position + is not valid on this MapBlock. + */ + bool isValidPositionParent(v3s16 p); + MapNode getNodeParent(v3s16 p); + void setNodeParent(v3s16 p, MapNode & n); + MapNode getNodeParentNoEx(v3s16 p); + + void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node) + { + for(u16 z=0; z & light_sources, + bool remove_light=false, bool *black_air_left=NULL); + + // Copies data to VoxelManipulator to getPosRelative() + void copyTo(VoxelManipulator &dst); + // Copies data from VoxelManipulator getPosRelative() + void copyFrom(VoxelManipulator &dst); + + /* + MapBlockObject stuff + DEPRECATED + */ + + /*void serializeObjects(std::ostream &os, u8 version) + { + m_objects.serialize(os, version); + }*/ + // If smgr!=NULL, new objects are added to the scene + void updateObjects(std::istream &is, u8 version, + scene::ISceneManager *smgr, u32 daynight_ratio) + { + m_objects.update(is, version, smgr, daynight_ratio); + + raiseModified(MOD_STATE_WRITE_NEEDED); + } + void clearObjects() + { + m_objects.clear(); + + raiseModified(MOD_STATE_WRITE_NEEDED); + } + void addObject(MapBlockObject *object) + throw(ContainerFullException, AlreadyExistsException) + { + m_objects.add(object); + + raiseModified(MOD_STATE_WRITE_NEEDED); + } + void removeObject(s16 id) + { + m_objects.remove(id); + + raiseModified(MOD_STATE_WRITE_NEEDED); + } + MapBlockObject * getObject(s16 id) + { + return m_objects.get(id); + } + JMutexAutoLock * getObjectLock() + { + return m_objects.getLock(); + } + + /* + Moves objects, deletes objects and spawns new objects + */ + void stepObjects(float dtime, bool server, u32 daynight_ratio); + + // origin is relative to block + void getObjects(v3f origin, f32 max_d, + core::array &dest) + { + m_objects.getObjects(origin, max_d, dest); + } + + s32 getObjectCount() + { + return m_objects.getCount(); + } + +#ifndef SERVER // Only on client + /* + Methods for setting temporary modifications to nodes for + drawing + + returns true if the mod was different last time + */ + bool setTempMod(v3s16 p, const NodeMod &mod) + { + /*dstream<<"setTempMod called on block" + <<" ("<getPos(); + + v3s16 blockpos_nodes = m_blockpos*MAP_BLOCKSIZE; + + /* + There is no harm not copying the TempMods of the neighbors + because they are already copied to this block + */ + m_temp_mods.clear(); + block->copyTempMods(m_temp_mods); + + /* + Copy data + */ + + // Allocate this block + neighbors + m_vmanip.clear(); + m_vmanip.addArea(VoxelArea(blockpos_nodes-v3s16(1,1,1)*MAP_BLOCKSIZE, + blockpos_nodes+v3s16(1,1,1)*MAP_BLOCKSIZE*2-v3s16(1,1,1))); + + { + //TimeTaker timer("copy central block data"); + // 0ms + + // Copy our data + block->copyTo(m_vmanip); + } + { + //TimeTaker timer("copy neighbor block data"); + // 0ms + + /* + Copy neighbors. This is lightning fast. + Copying only the borders would be *very* slow. + */ + + // Get map + Map *map = block->getParent(); + + for(u16 i=0; i<6; i++) + { + const v3s16 &dir = g_6dirs[i]; + v3s16 bp = m_blockpos + dir; + MapBlock *b = map->getBlockNoCreateNoEx(bp); + if(b) + b->copyTo(m_vmanip); + } + } +} + +/* + vertex_dirs: v3s16[4] +*/ +void getNodeVertexDirs(v3s16 dir, v3s16 *vertex_dirs) +{ + /* + If looked from outside the node towards the face, the corners are: + 0: bottom-right + 1: bottom-left + 2: top-left + 3: top-right + */ + if(dir == v3s16(0,0,1)) + { + // If looking towards z+, this is the face that is behind + // the center point, facing towards z+. + vertex_dirs[0] = v3s16(-1,-1, 1); + vertex_dirs[1] = v3s16( 1,-1, 1); + vertex_dirs[2] = v3s16( 1, 1, 1); + vertex_dirs[3] = v3s16(-1, 1, 1); + } + else if(dir == v3s16(0,0,-1)) + { + // faces towards Z- + vertex_dirs[0] = v3s16( 1,-1,-1); + vertex_dirs[1] = v3s16(-1,-1,-1); + vertex_dirs[2] = v3s16(-1, 1,-1); + vertex_dirs[3] = v3s16( 1, 1,-1); + } + else if(dir == v3s16(1,0,0)) + { + // faces towards X+ + vertex_dirs[0] = v3s16( 1,-1, 1); + vertex_dirs[1] = v3s16( 1,-1,-1); + vertex_dirs[2] = v3s16( 1, 1,-1); + vertex_dirs[3] = v3s16( 1, 1, 1); + } + else if(dir == v3s16(-1,0,0)) + { + // faces towards X- + vertex_dirs[0] = v3s16(-1,-1,-1); + vertex_dirs[1] = v3s16(-1,-1, 1); + vertex_dirs[2] = v3s16(-1, 1, 1); + vertex_dirs[3] = v3s16(-1, 1,-1); + } + else if(dir == v3s16(0,1,0)) + { + // faces towards Y+ (assume Z- as "down" in texture) + vertex_dirs[0] = v3s16( 1, 1,-1); + vertex_dirs[1] = v3s16(-1, 1,-1); + vertex_dirs[2] = v3s16(-1, 1, 1); + vertex_dirs[3] = v3s16( 1, 1, 1); + } + else if(dir == v3s16(0,-1,0)) + { + // faces towards Y- (assume Z+ as "down" in texture) + vertex_dirs[0] = v3s16( 1,-1, 1); + vertex_dirs[1] = v3s16(-1,-1, 1); + vertex_dirs[2] = v3s16(-1,-1,-1); + vertex_dirs[3] = v3s16( 1,-1,-1); + } +} + +video::SColor MapBlock_LightColor(u8 alpha, u8 light) +{ +#if 0 + return video::SColor(alpha,light,light,light); +#endif + //return video::SColor(alpha,light,light,MYMAX(0, (s16)light-25)+25); + /*return video::SColor(alpha,light,light,MYMAX(0, + pow((float)light/255.0, 0.8)*255.0));*/ +#if 1 + // Emphase blue a bit in darker places + float lim = 80; + float power = 0.8; + if(light > lim) + return video::SColor(alpha,light,light,light); + else + return video::SColor(alpha,light,light,MYMAX(0, + pow((float)light/lim, power)*lim)); +#endif +} + +struct FastFace +{ + TileSpec tile; + video::S3DVertex vertices[4]; // Precalculated vertices +}; + +void makeFastFace(TileSpec tile, u8 li0, u8 li1, u8 li2, u8 li3, v3f p, + v3s16 dir, v3f scale, v3f posRelative_f, + core::array &dest) +{ + FastFace face; + + // Position is at the center of the cube. + v3f pos = p * BS; + posRelative_f *= BS; + + v3f vertex_pos[4]; + v3s16 vertex_dirs[4]; + getNodeVertexDirs(dir, vertex_dirs); + for(u16 i=0; i<4; i++) + { + vertex_pos[i] = v3f( + BS/2*vertex_dirs[i].X, + BS/2*vertex_dirs[i].Y, + BS/2*vertex_dirs[i].Z + ); + } + + for(u16 i=0; i<4; i++) + { + vertex_pos[i].X *= scale.X; + vertex_pos[i].Y *= scale.Y; + vertex_pos[i].Z *= scale.Z; + vertex_pos[i] += pos + posRelative_f; + } + + f32 abs_scale = 1.; + if (scale.X < 0.999 || scale.X > 1.001) abs_scale = scale.X; + else if(scale.Y < 0.999 || scale.Y > 1.001) abs_scale = scale.Y; + else if(scale.Z < 0.999 || scale.Z > 1.001) abs_scale = scale.Z; + + v3f zerovector = v3f(0,0,0); + + u8 alpha = tile.alpha; + /*u8 alpha = 255; + if(tile.id == TILE_WATER) + alpha = WATER_ALPHA;*/ + + float x0 = tile.texture.pos.X; + float y0 = tile.texture.pos.Y; + float w = tile.texture.size.X; + float h = tile.texture.size.Y; + + /*video::SColor c = MapBlock_LightColor(alpha, li); + + face.vertices[0] = video::S3DVertex(vertex_pos[0], v3f(0,1,0), c, + core::vector2d(x0+w*abs_scale, y0+h)); + face.vertices[1] = video::S3DVertex(vertex_pos[1], v3f(0,1,0), c, + core::vector2d(x0, y0+h)); + face.vertices[2] = video::S3DVertex(vertex_pos[2], v3f(0,1,0), c, + core::vector2d(x0, y0)); + face.vertices[3] = video::S3DVertex(vertex_pos[3], v3f(0,1,0), c, + core::vector2d(x0+w*abs_scale, y0));*/ + + face.vertices[0] = video::S3DVertex(vertex_pos[0], v3f(0,1,0), + MapBlock_LightColor(alpha, li0), + core::vector2d(x0+w*abs_scale, y0+h)); + face.vertices[1] = video::S3DVertex(vertex_pos[1], v3f(0,1,0), + MapBlock_LightColor(alpha, li1), + core::vector2d(x0, y0+h)); + face.vertices[2] = video::S3DVertex(vertex_pos[2], v3f(0,1,0), + MapBlock_LightColor(alpha, li2), + core::vector2d(x0, y0)); + face.vertices[3] = video::S3DVertex(vertex_pos[3], v3f(0,1,0), + MapBlock_LightColor(alpha, li3), + core::vector2d(x0+w*abs_scale, y0)); + + face.tile = tile; + //DEBUG + //f->tile = TILE_STONE; + + dest.push_back(face); +} + +/* + Gets node tile from any place relative to block. + Returns TILE_NODE if doesn't exist or should not be drawn. +*/ +TileSpec getNodeTile(MapNode mn, v3s16 p, v3s16 face_dir, + NodeModMap &temp_mods) +{ + TileSpec spec; + spec = mn.getTile(face_dir); + + /* + Check temporary modifications on this node + */ + /*core::map::Node *n; + n = m_temp_mods.find(p); + // If modified + if(n != NULL) + { + struct NodeMod mod = n->getValue();*/ + NodeMod mod; + if(temp_mods.get(p, &mod)) + { + if(mod.type == NODEMOD_CHANGECONTENT) + { + MapNode mn2(mod.param); + spec = mn2.getTile(face_dir); + } + if(mod.type == NODEMOD_CRACK) + { + /* + Get texture id, translate it to name, append stuff to + name, get texture id + */ + + // Get original texture name + u32 orig_id = spec.texture.id; + std::string orig_name = g_texturesource->getTextureName(orig_id); + + // Create new texture name + std::ostringstream os; + os<getTextureId(os.str()); + + /*dstream<<"MapBlock::getNodeTile(): Switching from " + <getTexture(new_id); + } + } + + return spec; +} + +content_t getNodeContent(v3s16 p, MapNode mn, NodeModMap &temp_mods) +{ + /* + Check temporary modifications on this node + */ + /*core::map::Node *n; + n = m_temp_mods.find(p); + // If modified + if(n != NULL) + { + struct NodeMod mod = n->getValue();*/ + NodeMod mod; + if(temp_mods.get(p, &mod)) + { + if(mod.type == NODEMOD_CHANGECONTENT) + { + // Overrides content + return mod.param; + } + if(mod.type == NODEMOD_CRACK) + { + /* + Content doesn't change. + + face_contents works just like it should, because + there should not be faces between differently cracked + nodes. + + If a semi-transparent node is cracked in front an + another one, it really doesn't matter whether there + is a cracked face drawn in between or not. + */ + } + } + + return mn.getContent(); +} + +v3s16 dirs8[8] = { + v3s16(0,0,0), + v3s16(0,0,1), + v3s16(0,1,0), + v3s16(0,1,1), + v3s16(1,0,0), + v3s16(1,1,0), + v3s16(1,0,1), + v3s16(1,1,1), +}; + +// Calculate lighting at the XYZ- corner of p +u8 getSmoothLight(v3s16 p, VoxelManipulator &vmanip, u32 daynight_ratio) +{ + u16 ambient_occlusion = 0; + u16 light = 0; + u16 light_count = 0; + for(u32 i=0; i<8; i++) + { + MapNode n = vmanip.getNodeNoEx(p - dirs8[i]); + if(content_features(n).param_type == CPT_LIGHT + // Fast-style leaves look better this way + && content_features(n).solidness != 2) + { + light += decode_light(n.getLightBlend(daynight_ratio)); + light_count++; + } + else + { + if(n.getContent() != CONTENT_IGNORE) + ambient_occlusion++; + } + } + + if(light_count == 0) + return 255; + + light /= light_count; + + if(ambient_occlusion > 4) + { + ambient_occlusion -= 4; + light = (float)light / ((float)ambient_occlusion * 0.5 + 1.0); + } + + return light; +} + +// Calculate lighting at the given corner of p +u8 getSmoothLight(v3s16 p, v3s16 corner, + VoxelManipulator &vmanip, u32 daynight_ratio) +{ + if(corner.X == 1) p.X += 1; + else assert(corner.X == -1); + if(corner.Y == 1) p.Y += 1; + else assert(corner.Y == -1); + if(corner.Z == 1) p.Z += 1; + else assert(corner.Z == -1); + + return getSmoothLight(p, vmanip, daynight_ratio); +} + +void getTileInfo( + // Input: + v3s16 blockpos_nodes, + v3s16 p, + v3s16 face_dir, + u32 daynight_ratio, + VoxelManipulator &vmanip, + NodeModMap &temp_mods, + bool smooth_lighting, + // Output: + bool &makes_face, + v3s16 &p_corrected, + v3s16 &face_dir_corrected, + u8 *lights, + TileSpec &tile + ) +{ + MapNode n0 = vmanip.getNodeNoEx(blockpos_nodes + p); + MapNode n1 = vmanip.getNodeNoEx(blockpos_nodes + p + face_dir); + TileSpec tile0 = getNodeTile(n0, p, face_dir, temp_mods); + TileSpec tile1 = getNodeTile(n1, p + face_dir, -face_dir, temp_mods); + + // This is hackish + content_t content0 = getNodeContent(p, n0, temp_mods); + content_t content1 = getNodeContent(p + face_dir, n1, temp_mods); + u8 mf = face_contents(content0, content1); + + if(mf == 0) + { + makes_face = false; + return; + } + + makes_face = true; + + if(mf == 1) + { + tile = tile0; + p_corrected = p; + face_dir_corrected = face_dir; + } + else + { + tile = tile1; + p_corrected = p + face_dir; + face_dir_corrected = -face_dir; + } + + if(smooth_lighting == false) + { + lights[0] = lights[1] = lights[2] = lights[3] = + decode_light(getFaceLight(daynight_ratio, n0, n1, face_dir)); + } + else + { + v3s16 vertex_dirs[4]; + getNodeVertexDirs(face_dir_corrected, vertex_dirs); + for(u16 i=0; i<4; i++) + { + lights[i] = getSmoothLight(blockpos_nodes + p_corrected, + vertex_dirs[i], vmanip, daynight_ratio); + } + } + + return; +} + +/* + startpos: + translate_dir: unit vector with only one of x, y or z + face_dir: unit vector with only one of x, y or z +*/ +void updateFastFaceRow( + u32 daynight_ratio, + v3f posRelative_f, + v3s16 startpos, + u16 length, + v3s16 translate_dir, + v3f translate_dir_f, + v3s16 face_dir, + v3f face_dir_f, + core::array &dest, + NodeModMap &temp_mods, + VoxelManipulator &vmanip, + v3s16 blockpos_nodes, + bool smooth_lighting) +{ + v3s16 p = startpos; + + u16 continuous_tiles_count = 0; + + bool makes_face; + v3s16 p_corrected; + v3s16 face_dir_corrected; + u8 lights[4]; + TileSpec tile; + getTileInfo(blockpos_nodes, p, face_dir, daynight_ratio, + vmanip, temp_mods, smooth_lighting, + makes_face, p_corrected, face_dir_corrected, lights, tile); + + for(u16 j=0; j fastfaces_new; + + v3s16 blockpos_nodes = data->m_blockpos*MAP_BLOCKSIZE; + + // floating point conversion + v3f posRelative_f(blockpos_nodes.X, blockpos_nodes.Y, blockpos_nodes.Z); + + /* + Some settings + */ + //bool new_style_water = g_settings.getBool("new_style_water"); + //bool new_style_leaves = g_settings.getBool("new_style_leaves"); + bool smooth_lighting = g_settings.getBool("smooth_lighting"); + + /* + We are including the faces of the trailing edges of the block. + This means that when something changes, the caller must + also update the meshes of the blocks at the leading edges. + + NOTE: This is the slowest part of this method. + */ + + { + // 4-23ms for MAP_BLOCKSIZE=16 + //TimeTaker timer2("updateMesh() collect"); + + /* + Go through every y,z and get top(y+) faces in rows of x+ + */ + for(s16 y=0; ym_daynight_ratio, posRelative_f, + v3s16(0,y,z), MAP_BLOCKSIZE, + v3s16(1,0,0), //dir + v3f (1,0,0), + v3s16(0,1,0), //face dir + v3f (0,1,0), + fastfaces_new, + data->m_temp_mods, + data->m_vmanip, + blockpos_nodes, + smooth_lighting); + } + } + /* + Go through every x,y and get right(x+) faces in rows of z+ + */ + for(s16 x=0; xm_daynight_ratio, posRelative_f, + v3s16(x,y,0), MAP_BLOCKSIZE, + v3s16(0,0,1), + v3f (0,0,1), + v3s16(1,0,0), + v3f (1,0,0), + fastfaces_new, + data->m_temp_mods, + data->m_vmanip, + blockpos_nodes, + smooth_lighting); + } + } + /* + Go through every y,z and get back(z+) faces in rows of x+ + */ + for(s16 z=0; zm_daynight_ratio, posRelative_f, + v3s16(0,y,z), MAP_BLOCKSIZE, + v3s16(1,0,0), + v3f (1,0,0), + v3s16(0,0,1), + v3f (0,0,1), + fastfaces_new, + data->m_temp_mods, + data->m_vmanip, + blockpos_nodes, + smooth_lighting); + } + } + } + + // End of slow part + + /* + Convert FastFaces to SMesh + */ + + MeshCollector collector; + + if(fastfaces_new.size() > 0) + { + // avg 0ms (100ms spikes when loading textures the first time) + //TimeTaker timer2("updateMesh() mesh building"); + + video::SMaterial material; + material.setFlag(video::EMF_LIGHTING, false); + material.setFlag(video::EMF_BILINEAR_FILTER, false); + material.setFlag(video::EMF_FOG_ENABLE, true); + //material.setFlag(video::EMF_ANTI_ALIASING, video::EAAM_OFF); + //material.setFlag(video::EMF_ANTI_ALIASING, video::EAAM_SIMPLE); + + for(u32 i=0; irecalculateBoundingBox(); + + /* + Delete new mesh if it is empty + */ + + if(mesh_new->getMeshBufferCount() == 0) + { + mesh_new->drop(); + mesh_new = NULL; + } + + if(mesh_new) + { +#if 0 + // Usually 1-700 faces and 1-7 materials + std::cout<<"Updated MapBlock has "<getMeshBufferCount() + <<" materials (meshbuffers)"<setHardwareMappingHint(scene::EHM_STATIC); + + /* + NOTE: If that is enabled, some kind of a queue to the main + thread should be made which would call irrlicht to delete + the hardware buffer and then delete the mesh + */ + } + + return mesh_new; + + //std::cout<<"added "< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAPBLOCK_MESH_HEADER +#define MAPBLOCK_MESH_HEADER + +#include "common_irrlicht.h" +#include "mapblock_nodemod.h" +#include "voxel.h" + +/* + Mesh making stuff +*/ + +/* + This is used because CMeshBuffer::append() is very slow +*/ +struct PreMeshBuffer +{ + video::SMaterial material; + core::array indices; + core::array vertices; +}; + +class MeshCollector +{ +public: + void append( + video::SMaterial material, + const video::S3DVertex* const vertices, + u32 numVertices, + const u16* const indices, + u32 numIndices + ) + { + PreMeshBuffer *p = NULL; + for(u32 i=0; ivertices.size(); + for(u32 i=0; i 65535) + { + dstream<<"FIXME: Meshbuffer ran out of indices"<indices.push_back(j); + } + for(u32 i=0; ivertices.push_back(vertices[i]); + } + } + + void fillMesh(scene::SMesh *mesh) + { + /*dstream<<"Filling mesh with "< + scene::SMeshBuffer *buf = new scene::SMeshBuffer(); + // Set material + buf->Material = p.material; + //((scene::SMeshBuffer*)buf)->Material = p.material; + // Use VBO + //buf->setHardwareMappingHint(scene::EHM_STATIC); + // Add to mesh + mesh->addMeshBuffer(buf); + // Mesh grabbed it + buf->drop(); + + buf->append(p.vertices.pointer(), p.vertices.size(), + p.indices.pointer(), p.indices.size()); + } + } + +private: + core::array m_prebuffers; +}; + +// Helper functions +video::SColor MapBlock_LightColor(u8 alpha, u8 light); + +class MapBlock; + +struct MeshMakeData +{ + u32 m_daynight_ratio; + NodeModMap m_temp_mods; + VoxelManipulator m_vmanip; + v3s16 m_blockpos; + + /* + Copy central data directly from block, and other data from + parent of block. + */ + void fill(u32 daynight_ratio, MapBlock *block); +}; + +// This is the highest-level function in here +scene::SMesh* makeMapBlockMesh(MeshMakeData *data); + +#endif + diff --git a/src/mapblock_nodemod.h b/src/mapblock_nodemod.h new file mode 100644 index 0000000..4952df1 --- /dev/null +++ b/src/mapblock_nodemod.h @@ -0,0 +1,114 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAPBLOCK_NODEMOD_HEADER +#define MAPBLOCK_NODEMOD_HEADER + +enum NodeModType +{ + NODEMOD_NONE, + NODEMOD_CHANGECONTENT, //param is content id + NODEMOD_CRACK // param is crack progression +}; + +struct NodeMod +{ + NodeMod(enum NodeModType a_type=NODEMOD_NONE, u16 a_param=0) + { + type = a_type; + param = a_param; + } + bool operator==(const NodeMod &other) + { + return (type == other.type && param == other.param); + } + enum NodeModType type; + u16 param; +}; + +class NodeModMap +{ +public: + /* + returns true if the mod was different last time + */ + bool set(v3s16 p, const NodeMod &mod) + { + // See if old is different, cancel if it is not different. + core::map::Node *n = m_mods.find(p); + if(n) + { + NodeMod old = n->getValue(); + if(old == mod) + return false; + + n->setValue(mod); + } + else + { + m_mods.insert(p, mod); + } + + return true; + } + // Returns true if there was one + bool get(v3s16 p, NodeMod *mod) + { + core::map::Node *n; + n = m_mods.find(p); + if(n == NULL) + return false; + if(mod) + *mod = n->getValue(); + return true; + } + bool clear(v3s16 p) + { + if(m_mods.find(p)) + { + m_mods.remove(p); + return true; + } + return false; + } + bool clear() + { + if(m_mods.size() == 0) + return false; + m_mods.clear(); + return true; + } + void copy(NodeModMap &dest) + { + dest.m_mods.clear(); + + for(core::map::Iterator + i = m_mods.getIterator(); + i.atEnd() == false; i++) + { + dest.m_mods.insert(i.getNode()->getKey(), i.getNode()->getValue()); + } + } + +private: + core::map m_mods; +}; + +#endif + diff --git a/src/mapblockobject.cpp b/src/mapblockobject.cpp new file mode 100644 index 0000000..071a14b --- /dev/null +++ b/src/mapblockobject.cpp @@ -0,0 +1,939 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// This file contains the DEPRECATED MapBlockObject system + +#include "mapblockobject.h" +#include "mapblock.h" +// For object wrapping +#include "map.h" +#include "inventory.h" +#include "utility.h" +#include "mapblock.h" + +/* + MapBlockObject +*/ + +// This is here because it uses the MapBlock +v3f MapBlockObject::getAbsolutePos() +{ + if(m_block == NULL) + return m_pos; + + // getPosRelative gets nodepos relative to map origin + v3f blockpos = intToFloat(m_block->getPosRelative(), BS); + return blockpos + m_pos; +} + +void MapBlockObject::setBlockChanged() +{ + if(m_block) + m_block->setChangedFlag(); +} + +/* + MovingObject +*/ + +v3f MovingObject::getAbsoluteShowPos() +{ + if(m_block == NULL) + return m_pos; + + // getPosRelative gets nodepos relative to map origin + v3f blockpos = intToFloat(m_block->getPosRelative(), BS); + return blockpos + m_showpos; +} + +void MovingObject::move(float dtime, v3f acceleration) +{ + DSTACKF("%s: typeid=%i, pos=(%f,%f,%f), speed=(%f,%f,%f)" + ", dtime=%f, acc=(%f,%f,%f)", + __FUNCTION_NAME, + getTypeId(), + m_pos.X, m_pos.Y, m_pos.Z, + m_speed.X, m_speed.Y, m_speed.Z, + dtime, + acceleration.X, acceleration.Y, acceleration.Z + ); + + v3s16 oldpos_i = floatToInt(m_pos, BS); + + if(m_block->isValidPosition(oldpos_i) == false) + { + // Should have wrapped, cancelling further movement. + return; + } + + // No collisions if there is no collision box + if(m_collision_box == NULL) + { + m_speed += dtime * acceleration; + m_pos += m_speed * dtime; + return; + } + + // Set insane speed to zero + // Otherwise there will be divides by zero and other silly stuff + if(m_speed.getLength() > 1000.0*BS) + m_speed = v3f(0,0,0); + + // Limit speed to a reasonable value + float speed_limit = 20.0*BS; + if(m_speed.getLength() > speed_limit) + m_speed = m_speed * (speed_limit / m_speed.getLength()); + + v3f position = m_pos; + v3f oldpos = position; + + /*std::cout<<"oldpos_i=("< 0.001) + dtime_max_increment = 0.05*BS / speedlength; + else + dtime_max_increment = 0.5; + + m_touching_ground = false; + + u32 loopcount = 0; + do + { + loopcount++; + + f32 dtime_part; + if(dtime > dtime_max_increment) + dtime_part = dtime_max_increment; + else + dtime_part = dtime; + dtime -= dtime_part; + + // Begin of dtime limited code + + m_speed += acceleration * dtime_part; + position += m_speed * dtime_part; + + /* + Collision detection + */ + + v3s16 pos_i = floatToInt(position, BS); + + // The loop length is limited to the object moving a distance + f32 d = (float)BS * 0.15; + + core::aabbox3d objectbox( + m_collision_box->MinEdge + position, + m_collision_box->MaxEdge + position + ); + + core::aabbox3d objectbox_old( + m_collision_box->MinEdge + oldpos, + m_collision_box->MaxEdge + oldpos + ); + + //TODO: Get these ranges from somewhere + for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++) + for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++) + for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++) + { + try{ + MapNode n = m_block->getNodeParent(v3s16(x,y,z)); + if(content_features(n).walkable == false) + continue; + } + catch(InvalidPositionException &e) + { + // Doing nothing here will block the object from + // walking over map borders + } + + core::aabbox3d nodebox = getNodeBox(v3s16(x,y,z), BS); + + // See if the object is touching ground + if( + fabs(nodebox.MaxEdge.Y-objectbox.MinEdge.Y) < d + && nodebox.MaxEdge.X-d > objectbox.MinEdge.X + && nodebox.MinEdge.X+d < objectbox.MaxEdge.X + && nodebox.MaxEdge.Z-d > objectbox.MinEdge.Z + && nodebox.MinEdge.Z+d < objectbox.MaxEdge.Z + ){ + m_touching_ground = true; + } + + if(objectbox.intersectsWithBox(nodebox)) + { + + v3f dirs[3] = { + v3f(0,0,1), // back + v3f(0,1,0), // top + v3f(1,0,0), // right + }; + for(u16 i=0; i<3; i++) + { + f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]); + f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]); + f32 playermax = objectbox.MaxEdge.dotProduct(dirs[i]); + f32 playermin = objectbox.MinEdge.dotProduct(dirs[i]); + f32 playermax_old = objectbox_old.MaxEdge.dotProduct(dirs[i]); + f32 playermin_old = objectbox_old.MinEdge.dotProduct(dirs[i]); + + bool main_edge_collides = + ((nodemax > playermin && nodemax <= playermin_old + d + && m_speed.dotProduct(dirs[i]) < 0) + || + (nodemin < playermax && nodemin >= playermax_old - d + && m_speed.dotProduct(dirs[i]) > 0)); + + bool other_edges_collide = true; + for(u16 j=0; j<3; j++) + { + if(j == i) + continue; + f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]); + f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]); + f32 playermax = objectbox.MaxEdge.dotProduct(dirs[j]); + f32 playermin = objectbox.MinEdge.dotProduct(dirs[j]); + if(!(nodemax - d > playermin && nodemin + d < playermax)) + { + other_edges_collide = false; + break; + } + } + + if(main_edge_collides && other_edges_collide) + { + m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i]; + position -= position.dotProduct(dirs[i]) * dirs[i]; + position += oldpos.dotProduct(dirs[i]) * dirs[i]; + } + + } + + } // if(objectbox.intersectsWithBox(nodebox)) + } // for y + + } // End of dtime limited loop + while(dtime > 0.001); + + m_pos = position; +} + +void MovingObject::simpleMove(float dtime) +{ + m_pos_animation_time_counter += dtime; + m_pos_animation_counter += dtime; + v3f movevector = m_pos - m_oldpos; + f32 moveratio; + if(m_pos_animation_time < 0.001) + moveratio = 1.0; + else + moveratio = m_pos_animation_counter / m_pos_animation_time; + if(moveratio > 1.5) + moveratio = 1.5; + m_showpos = m_oldpos + movevector * moveratio; +} + +#ifndef SERVER +/* + RatObject +*/ +void RatObject::addToScene(scene::ISceneManager *smgr) +{ + if(m_node != NULL) + return; + + video::IVideoDriver* driver = smgr->getVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("rat.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + updateNodePos(); +} +#endif + +/* + ItemObject +*/ +#ifndef SERVER +void ItemObject::addToScene(scene::ISceneManager *smgr) +{ + if(m_node != NULL) + return; + + //video::IVideoDriver* driver = smgr->getVideoDriver(); + + // Get image of item for showing + video::ITexture *texture = getItemImage(); + + /* + Create a mesh + */ + + scene::SMesh *mesh = new scene::SMesh(); + { + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + /*video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, 0,1), + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, 1,1), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, 1,0), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, 0,0),*/ + video::S3DVertex(BS/3,-BS/2,0, 0,0,0, c, 0,1), + video::S3DVertex(-BS/3,-BS/2,0, 0,0,0, c, 1,1), + video::S3DVertex(-BS/3,-BS/2+BS*2/3,0, 0,0,0, c, 1,0), + video::S3DVertex(BS/3,-BS/2+BS*2/3,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture(0, texture); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + m_node = smgr->addMeshSceneNode(mesh, NULL); + // Set it to use the materials of the meshbuffers directly. + // This is needed for changing the texture in the future + ((scene::IMeshSceneNode*)m_node)->setReadOnlyMaterials(true); + mesh->drop(); + + updateSceneNode(); +} + +video::ITexture * ItemObject::getItemImage() +{ + /* + Create an inventory item to see what is its image + */ + video::ITexture *texture = NULL; + InventoryItem *item = createInventoryItem(); + if(item) + texture = item->getImage(); + if(item) + delete item; + return texture; +} + +#endif + +InventoryItem * ItemObject::createInventoryItem() +{ + try{ + std::istringstream is(m_itemstring, std::ios_base::binary); + InventoryItem *item = InventoryItem::deSerialize(is); + dstream<<__FUNCTION_NAME<<": m_itemstring=\"" + < item="<getVideoDriver(); + + // Attach a simple mesh to the player for showing an image + scene::SMesh *mesh = new scene::SMesh(); + { // Front + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + { // Back + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1), + video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1), + video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0), + video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player_back.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + updateNodePos(); +} +#endif + +/* + MapBlockObjectList +*/ + +MapBlockObjectList::MapBlockObjectList(MapBlock *block): + m_block(block) +{ + m_mutex.Init(); +} + +MapBlockObjectList::~MapBlockObjectList() +{ + clear(); +} + +/* + The serialization format: + [0] u16 number of entries + [2] entries (id, typeId, parameters) +*/ + +void MapBlockObjectList::serialize(std::ostream &os, u8 version) +{ + JMutexAutoLock lock(m_mutex); + + u8 buf[2]; + writeU16(buf, m_objects.size()); + os.write((char*)buf, 2); + + for(core::map::Iterator + i = m_objects.getIterator(); + i.atEnd() == false; i++) + { + i.getNode()->getValue()->serialize(os, version); + } +} + +void MapBlockObjectList::update(std::istream &is, u8 version, + scene::ISceneManager *smgr, u32 daynight_ratio) +{ + JMutexAutoLock lock(m_mutex); + + /* + Collect all existing ids to a set. + + As things are updated, they are removed from this. + + All remaining ones are deleted. + */ + core::map ids_to_delete; + for(core::map::Iterator + i = m_objects.getIterator(); + i.atEnd() == false; i++) + { + ids_to_delete.insert(i.getNode()->getKey(), true); + } + + u8 buf[6]; + + is.read((char*)buf, 2); + u16 count = readU16(buf); + + for(u16 i=0; i::Node *n; + n = m_objects.find(id); + // If no entry is found for id + if(n == NULL) + { + // Insert dummy pointer node + m_objects.insert(id, NULL); + // Get node + n = m_objects.find(id); + // A new object will be created at this node + create_new = true; + } + // If type_id differs + else if(n->getValue()->getTypeId() != type_id) + { + // Delete old object + delete n->getValue(); + // A new object will be created at this node + create_new = true; + } + + MapBlockObject *obj = NULL; + + if(create_new) + { + /*dstream<<"MapBlockObjectList adding new object" + " id="<addToScene(smgr, daynight_ratio); + obj->addToScene(smgr); + + n->setValue(obj); + } + else + { + obj = n->getValue(); + obj->updatePos(pos); + /*if(daynight_ratio != m_last_update_daynight_ratio) + { + obj->removeFromScene(); + obj->addToScene(smgr, daynight_ratio); + }*/ + } + + // Now there is an object in obj. + // Update it. + + obj->update(is, version); + + /* + Update light on client + */ + if(smgr != NULL) + { + u8 light = LIGHT_MAX; + try{ + v3s16 relpos_i = floatToInt(obj->m_pos, BS); + MapNode n = m_block->getNodeParent(relpos_i); + light = n.getLightBlend(daynight_ratio); + } + catch(InvalidPositionException &e) {} + obj->updateLight(light); + } + + // Remove from deletion list + if(ids_to_delete.find(id) != NULL) + ids_to_delete.remove(id); + } + + // Delete all objects whose ids_to_delete remain in ids_to_delete + for(core::map::Iterator + i = ids_to_delete.getIterator(); + i.atEnd() == false; i++) + { + s16 id = i.getNode()->getKey(); + + /*dstream<<"MapBlockObjectList deleting object" + " id="<removeFromScene(); + delete obj; + m_objects.remove(id); + } + + m_last_update_daynight_ratio = daynight_ratio; +} + +s16 MapBlockObjectList::getFreeId() throw(ContainerFullException) +{ + s16 id = 0; + for(;;) + { + if(m_objects.find(id) == NULL) + return id; + if(id == 32767) + throw ContainerFullException + ("MapBlockObjectList doesn't fit more objects"); + id++; + } +} + +void MapBlockObjectList::add(MapBlockObject *object) + throw(ContainerFullException, AlreadyExistsException) +{ + if(object == NULL) + { + dstream<<"MapBlockObjectList::add(): NULL object"<m_id == -1) + { + object->m_id = getFreeId(); + } + + if(m_objects.find(object->m_id) != NULL) + { + dstream<<"MapBlockObjectList::add(): " + "object with same id already exists"<m_block = m_block; + + /*v3f p = object->m_pos; + dstream<<"MapBlockObjectList::add(): " + <<"m_block->getPos()=(" + <getPos().X<<"," + <getPos().Y<<"," + <getPos().Z<<")" + <<" inserting object with id="<m_id + <<" pos=" + <<"("<m_id, object); +} + +void MapBlockObjectList::clear() +{ + JMutexAutoLock lock(m_mutex); + + for(core::map::Iterator + i = m_objects.getIterator(); + i.atEnd() == false; i++) + { + MapBlockObject *obj = i.getNode()->getValue(); + //FIXME: This really shouldn't be NULL at any time, + // but this condition was added because it was. + if(obj != NULL) + { + obj->removeFromScene(); + delete obj; + } + } + + m_objects.clear(); +} + +void MapBlockObjectList::remove(s16 id) +{ + JMutexAutoLock lock(m_mutex); + + core::map::Node *n; + n = m_objects.find(id); + if(n == NULL) + return; + + n->getValue()->removeFromScene(); + delete n->getValue(); + m_objects.remove(id); +} + +MapBlockObject * MapBlockObjectList::get(s16 id) +{ + core::map::Node *n; + n = m_objects.find(id); + if(n == NULL) + return NULL; + else + return n->getValue(); +} + +void MapBlockObjectList::step(float dtime, bool server, u32 daynight_ratio) +{ + DSTACK(__FUNCTION_NAME); + + JMutexAutoLock lock(m_mutex); + + core::map ids_to_delete; + + { + DSTACKF("%s: stepping objects", __FUNCTION_NAME); + + for(core::map::Iterator + i = m_objects.getIterator(); + i.atEnd() == false; i++) + { + MapBlockObject *obj = i.getNode()->getValue(); + + DSTACKF("%s: stepping object type %i", __FUNCTION_NAME, + obj->getTypeId()); + + if(server) + { + // Update light + u8 light = LIGHT_MAX; + try{ + v3s16 relpos_i = floatToInt(obj->m_pos, BS); + MapNode n = m_block->getNodeParent(relpos_i); + light = n.getLightBlend(daynight_ratio); + } + catch(InvalidPositionException &e) {} + obj->updateLight(light); + + bool to_delete = obj->serverStep(dtime, daynight_ratio); + + if(to_delete) + ids_to_delete.insert(obj->m_id, true); + } + else + { + obj->clientStep(dtime); + } + } + } + + { + DSTACKF("%s: deleting objects", __FUNCTION_NAME); + + // Delete objects in delete queue + for(core::map::Iterator + i = ids_to_delete.getIterator(); + i.atEnd() == false; i++) + { + s16 id = i.getNode()->getKey(); + + MapBlockObject *obj = m_objects[id]; + obj->removeFromScene(); + delete obj; + m_objects.remove(id); + } + } + + /* + Wrap objects on server + */ + + if(server == false) + return; + + { + DSTACKF("%s: object wrap loop", __FUNCTION_NAME); + + for(core::map::Iterator + i = m_objects.getIterator(); + i.atEnd() == false; i++) + { + MapBlockObject *obj = i.getNode()->getValue(); + + v3s16 pos_i = floatToInt(obj->m_pos, BS); + + if(m_block->isValidPosition(pos_i)) + { + // No wrap + continue; + } + + bool impossible = wrapObject(obj); + + if(impossible) + { + // No wrap + continue; + } + + // Restart find + i = m_objects.getIterator(); + } + } +} + +bool MapBlockObjectList::wrapObject(MapBlockObject *object) +{ + DSTACK(__FUNCTION_NAME); + + // No lock here; this is called so that the lock is already locked. + //JMutexAutoLock lock(m_mutex); + + assert(object->m_block == m_block); + assert(m_objects.find(object->m_id) != NULL); + assert(m_objects[object->m_id] == object); + + Map *map = m_block->getParent(); + + // Calculate blockpos on map + v3s16 oldblock_pos_i_on_map = m_block->getPosRelative(); + v3f pos_f_on_oldblock = object->m_pos; + v3s16 pos_i_on_oldblock = floatToInt(pos_f_on_oldblock, BS); + v3s16 pos_i_on_map = pos_i_on_oldblock + oldblock_pos_i_on_map; + v3s16 pos_blocks_on_map = getNodeBlockPos(pos_i_on_map); + + // Get new block + MapBlock *newblock; + try{ + newblock = map->getBlockNoCreate(pos_blocks_on_map); + } + catch(InvalidPositionException &e) + { + // Couldn't find block -> not wrapping + /*dstream<<"WARNING: Wrapping object not possible: " + <<"could not find new block" + <<"("<getPosRelative(); + v3f newblock_pos_f_on_map = intToFloat(newblock_pos_i_on_map, BS); + v3f pos_f_on_newblock = pos_f_on_oldblock + - newblock_pos_f_on_map + oldblock_pos_f_on_map; + + // Remove object from this block + m_objects.remove(object->m_id); + + // Add object to new block + object->m_pos = pos_f_on_newblock; + object->m_id = -1; + object->m_block = NULL; + newblock->addObject(object); + + //dstream<<"NOTE: Wrapped object"< &dest) +{ + for(core::map::Iterator + i = m_objects.getIterator(); + i.atEnd() == false; i++) + { + MapBlockObject *obj = i.getNode()->getValue(); + + f32 d = (obj->getRelativeShowPos() - origin).getLength(); + + if(d > max_d) + continue; + + DistanceSortedObject dso(obj, d); + + dest.push_back(dso); + } +} + +//END diff --git a/src/mapblockobject.h b/src/mapblockobject.h new file mode 100644 index 0000000..8044947 --- /dev/null +++ b/src/mapblockobject.h @@ -0,0 +1,1116 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +// This file contains the DEPRECATED MapBlockObject system + +#ifndef MAPBLOCKOBJECT_HEADER +#define MAPBLOCKOBJECT_HEADER + +#include "common_irrlicht.h" +#include +#include +#include "serialization.h" +#include "mapnode.h" +#include "constants.h" +#include "debug.h" + +#define MAPBLOCKOBJECT_TYPE_PLAYER 0 +#define MAPBLOCKOBJECT_TYPE_SIGN 2 +#define MAPBLOCKOBJECT_TYPE_RAT 3 +#define MAPBLOCKOBJECT_TYPE_ITEM 4 +// Used for handling selecting special stuff +//#define MAPBLOCKOBJECT_TYPE_PSEUDO 1000 + +class MapBlock; + +class MapBlockObject +{ +public: + MapBlockObject(MapBlock *block, s16 id, v3f pos): + m_collision_box(NULL), + m_selection_box(NULL), + m_block(block), + m_id(id), + m_pos(pos) + { + } + virtual ~MapBlockObject() + { + } + + s16 getId() + { + return m_id; + } + MapBlock* getBlock() + { + return m_block; + } + + // Writes id, pos and typeId + void serializeBase(std::ostream &os, u8 version) + { + u8 buf[6]; + + // id + writeS16(buf, m_id); + os.write((char*)buf, 2); + + // position + // stored as x1000/BS v3s16 + v3s16 pos_i(m_pos.X*1000/BS, m_pos.Y*1000/BS, m_pos.Z*1000/BS); + writeV3S16(buf, pos_i); + os.write((char*)buf, 6); + + // typeId + writeU16(buf, getTypeId()); + os.write((char*)buf, 2); + } + + // Position where the object is drawn relative to block + virtual v3f getRelativeShowPos() + { + return m_pos; + } + // Get floating point position on map + v3f getAbsolutePos(); + + void setBlockChanged(); + + // Shootline is relative to block + bool isSelected(core::line3d shootline) + { + if(m_selection_box == NULL) + return false; + + core::aabbox3d offsetted_box( + m_selection_box->MinEdge + m_pos, + m_selection_box->MaxEdge + m_pos + ); + + return offsetted_box.intersectsWithLine(shootline); + } + + core::aabbox3d getSelectionBoxOnMap() + { + v3f absolute_pos = getAbsolutePos(); + + core::aabbox3d box( + m_selection_box->MinEdge + absolute_pos, + m_selection_box->MaxEdge + absolute_pos + ); + + return box; + } + + /* + Implementation interface + */ + + virtual u16 getTypeId() const = 0; + // Shall call serializeBase and then write the parameters + virtual void serialize(std::ostream &os, u8 version) = 0; + // Shall read parameters from stream + virtual void update(std::istream &is, u8 version) = 0; + + virtual std::string getInventoryString() { return "None"; } + + // Reimplementation shall call this. + virtual void updatePos(v3f pos) + { + m_pos = pos; + } + + // Shall move the object around, modify it and possibly delete it. + // Typical dtimes are 0.2 and 10000. + // A return value of true requests deletion of the object by the caller. + // NOTE: Only server calls this. + virtual bool serverStep(float dtime, u32 daynight_ratio) + { return false; }; + +#ifdef SERVER + void clientStep(float dtime) {}; + void addToScene(void *smgr) {}; + void removeFromScene() {}; + void updateLight(u8 light_at_pos) {}; +#else + // This should do slight animations only or so + virtual void clientStep(float dtime) {}; + + // NOTE: These functions should do nothing if the asked state is + // same as the current state + // Shall add and remove relevant scene nodes for rendering the + // object in the game world + virtual void addToScene(scene::ISceneManager *smgr) = 0; + // Shall remove stuff from the scene + // Should return silently if there is nothing to remove + // NOTE: This has to be called before calling destructor + virtual void removeFromScene() = 0; + + // 0 <= light_at_pos <= LIGHT_SUN + virtual void updateLight(u8 light_at_pos) {}; +#endif + + virtual std::string infoText() { return ""; } + + // Shall be left NULL if doesn't collide + // Position is relative to m_pos in block + core::aabbox3d * m_collision_box; + + // Shall be left NULL if can't be selected + core::aabbox3d * m_selection_box; + +protected: + MapBlock *m_block; + // This differentiates the instance of the object + // Not same as typeId. + s16 m_id; + // Position of the object inside the block + // Units is node coordinates * BS + v3f m_pos; + + friend class MapBlockObjectList; +}; + +#if 0 +/* + Used for handling selections of special stuff +*/ +class PseudoMBObject : public MapBlockObject +{ +public: + // The constructor of every MapBlockObject should be like this + PseudoMBObject(MapBlock *block, s16 id, v3f pos): + MapBlockObject(block, id, pos) + { + } + virtual ~PseudoMBObject() + { + if(m_selection_box) + delete m_selection_box; + } + + /* + Implementation interface + */ + virtual u16 getTypeId() const + { + return MAPBLOCKOBJECT_TYPE_PSEUDO; + } + virtual void serialize(std::ostream &os, u8 version) + { + assert(0); + } + virtual void update(std::istream &is, u8 version) + { + assert(0); + } + virtual bool serverStep(float dtime, u32 daynight_ratio) + { + assert(0); + } + + /* + Special methods + */ + + void setSelectionBox(core::aabbox3d box) + { + m_selection_box = new core::aabbox3d(box); + } + +protected: +}; +#endif + +class MovingObject : public MapBlockObject +{ +public: + // The constructor of every MapBlockObject should be like this + MovingObject(MapBlock *block, s16 id, v3f pos): + MapBlockObject(block, id, pos), + m_speed(0,0,0), + m_oldpos(pos), + m_pos_animation_time(0), + m_showpos(pos) + { + m_touching_ground = false; + } + virtual ~MovingObject() + { + } + + /* + Implementation interface + */ + + virtual u16 getTypeId() const = 0; + + virtual void serialize(std::ostream &os, u8 version) + { + serializeBase(os, version); + + u8 buf[6]; + + // Write speed + // stored as x100/BS v3s16 + v3s16 speed_i(m_speed.X*100/BS, m_speed.Y*100/BS, m_speed.Z*100/BS); + writeV3S16(buf, speed_i); + os.write((char*)buf, 6); + } + virtual void update(std::istream &is, u8 version) + { + u8 buf[6]; + + // Read speed + // stored as x100/BS v3s16 + is.read((char*)buf, 6); + v3s16 speed_i = readV3S16(buf); + v3f speed((f32)speed_i.X/100*BS, + (f32)speed_i.Y/100*BS, + (f32)speed_i.Z/100*BS); + + m_speed = speed; + } + + // Reimplementation shall call this. + virtual void updatePos(v3f pos) + { + m_oldpos = m_showpos; + m_pos = pos; + + if(m_pos_animation_time < 0.001 || m_pos_animation_time > 1.0) + m_pos_animation_time = m_pos_animation_time_counter; + else + m_pos_animation_time = m_pos_animation_time * 0.9 + + m_pos_animation_time_counter * 0.1; + m_pos_animation_time_counter = 0; + m_pos_animation_counter = 0; + } + + // Position where the object is drawn relative to block + virtual v3f getRelativeShowPos() + { + return m_showpos; + } + // Returns m_showpos relative to whole map + v3f getAbsoluteShowPos(); + + virtual bool serverStep(float dtime, u32 daynight_ratio) + { return false; }; + virtual void clientStep(float dtime) + {}; + + /*virtual void addToScene(scene::ISceneManager *smgr) = 0; + virtual void removeFromScene() = 0;*/ + + /* + Special methods + */ + + // Move with collision detection, server side + void move(float dtime, v3f acceleration); + + // Move from old position to new position, client side + void simpleMove(float dtime); + +protected: + v3f m_speed; + bool m_touching_ground; + // Client-side moving + v3f m_oldpos; + f32 m_pos_animation_counter; + f32 m_pos_animation_time; + f32 m_pos_animation_time_counter; + v3f m_showpos; +}; + +class SignObject : public MapBlockObject +{ +public: + // The constructor of every MapBlockObject should be like this + SignObject(MapBlock *block, s16 id, v3f pos): + MapBlockObject(block, id, pos), + m_node(NULL) + { + m_selection_box = new core::aabbox3d + (-BS*0.4,-BS*0.5,-BS*0.4, BS*0.4,BS*0.5,BS*0.4); + } + virtual ~SignObject() + { + delete m_selection_box; + } + + /* + Implementation interface + */ + virtual u16 getTypeId() const + { + return MAPBLOCKOBJECT_TYPE_SIGN; + } + virtual void serialize(std::ostream &os, u8 version) + { + serializeBase(os, version); + u8 buf[2]; + + // Write yaw * 10 + writeS16(buf, m_yaw * 10); + os.write((char*)buf, 2); + + // Write text length + writeU16(buf, m_text.size()); + os.write((char*)buf, 2); + + // Write text + os.write(m_text.c_str(), m_text.size()); + } + virtual void update(std::istream &is, u8 version) + { + u8 buf[2]; + + // Read yaw * 10 + is.read((char*)buf, 2); + s16 yaw_i = readS16(buf); + m_yaw = (f32)yaw_i / 10; + + // Read text length + is.read((char*)buf, 2); + u16 size = readU16(buf); + + // Read text + m_text.clear(); + for(u16 i=0; igetVideoDriver(); + + scene::SMesh *mesh = new scene::SMesh(); + { // Front + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, 0,1), + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, 1,1), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, 1,0), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("sign.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + { // Back + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,-BS/2,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,-BS/2,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS/2,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS/2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture + (0, driver->getTexture(getTexturePath("sign_back.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + m_node = smgr->addMeshSceneNode(mesh, NULL); + mesh->drop(); + + updateSceneNode(); + } + virtual void removeFromScene() + { + if(m_node != NULL) + { + m_node->remove(); + m_node = NULL; + } + } + virtual void updateLight(u8 light_at_pos) + { + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(getAbsolutePos()); + m_node->setRotation(v3f(0, m_yaw, 0)); + } +#endif + } + + void setText(std::string text) + { + if(text.size() > SIGN_TEXT_MAX_LENGTH) + text = text.substr(0, SIGN_TEXT_MAX_LENGTH); + m_text = text; + + setBlockChanged(); + } + + std::string getText() + { + return m_text; + } + + void setYaw(f32 yaw) + { + m_yaw = yaw; + + setBlockChanged(); + } + +protected: + scene::IMeshSceneNode *m_node; + std::string m_text; + f32 m_yaw; +}; + +class RatObject : public MovingObject +{ +public: + RatObject(MapBlock *block, s16 id, v3f pos): + MovingObject(block, id, pos), + m_node(NULL) + { + m_collision_box = new core::aabbox3d + (-BS*0.3,-BS*.25,-BS*0.3, BS*0.3,BS*0.25,BS*0.3); + m_selection_box = new core::aabbox3d + (-BS*0.3,-BS*.25,-BS*0.3, BS*0.3,BS*0.25,BS*0.3); + + m_yaw = 0; + m_counter1 = 0; + m_counter2 = 0; + m_age = 0; + } + virtual ~RatObject() + { + delete m_collision_box; + delete m_selection_box; + } + + /* + Implementation interface + */ + virtual u16 getTypeId() const + { + return MAPBLOCKOBJECT_TYPE_RAT; + } + virtual void serialize(std::ostream &os, u8 version) + { + MovingObject::serialize(os, version); + u8 buf[2]; + + // Write yaw * 10 + writeS16(buf, m_yaw * 10); + os.write((char*)buf, 2); + + } + virtual void update(std::istream &is, u8 version) + { + MovingObject::update(is, version); + u8 buf[2]; + + // Read yaw * 10 + is.read((char*)buf, 2); + s16 yaw_i = readS16(buf); + m_yaw = (f32)yaw_i / 10; + + updateNodePos(); + } + + virtual bool serverStep(float dtime, u32 daynight_ratio) + { + m_age += dtime; + if(m_age > 60) + // Die + return true; + + v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI)); + + f32 speed = 2*BS; + + m_speed.X = speed * dir.X; + m_speed.Z = speed * dir.Z; + + if(m_touching_ground && (m_oldpos - m_pos).getLength() < dtime*speed/2) + { + m_counter1 -= dtime; + if(m_counter1 < 0.0) + { + m_counter1 += 1.0; + m_speed.Y = 5.0*BS; + } + } + + { + m_counter2 -= dtime; + if(m_counter2 < 0.0) + { + m_counter2 += (float)(myrand()%100)/100*3.0; + m_yaw += ((float)(myrand()%200)-100)/100*180; + m_yaw = wrapDegrees(m_yaw); + } + } + + m_oldpos = m_pos; + + //m_yaw += dtime*90; + + move(dtime, v3f(0, -9.81*BS, 0)); + + //updateNodePos(); + + return false; + } +#ifndef SERVER + virtual void clientStep(float dtime) + { + //m_pos += m_speed * dtime; + MovingObject::simpleMove(dtime); + + updateNodePos(); + } + + virtual void addToScene(scene::ISceneManager *smgr); + + virtual void removeFromScene() + { + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; + } + + virtual void updateLight(u8 light_at_pos) + { + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(getAbsoluteShowPos()); + m_node->setRotation(v3f(0, -m_yaw+180, 0)); + } + +protected: + scene::IMeshSceneNode *m_node; + float m_yaw; + + float m_counter1; + float m_counter2; + float m_age; +}; + +/* + An object on the map that represents an inventory item +*/ + +class InventoryItem; + +class ItemObject : public MapBlockObject +{ +public: + // The constructor of every MapBlockObject should be like this + ItemObject(MapBlock *block, s16 id, v3f pos): + MapBlockObject(block, id, pos), + m_node(NULL) + { + /*m_selection_box = new core::aabbox3d + (-BS*0.4,-BS*0.5,-BS*0.4, BS*0.4,BS*0.5,BS*0.4);*/ + m_selection_box = new core::aabbox3d + (-BS/3,-BS/2,-BS/3, BS/3,-BS/2+BS*2/3,BS/3); + m_yaw = 0.0; + } + virtual ~ItemObject() + { + delete m_selection_box; + } + + /* + Implementation interface + */ + virtual u16 getTypeId() const + { + return MAPBLOCKOBJECT_TYPE_ITEM; + } + virtual void serialize(std::ostream &os, u8 version) + { + serializeBase(os, version); + u8 buf[2]; + + // Write text length + writeU16(buf, m_itemstring.size()); + os.write((char*)buf, 2); + + // Write text + os.write(m_itemstring.c_str(), m_itemstring.size()); + } + virtual void update(std::istream &is, u8 version) + { + u8 buf[2]; + + // Read text length + is.read((char*)buf, 2); + u16 size = readU16(buf); + + // Read text + std::string old_itemstring = m_itemstring; + m_itemstring.clear(); + for(u16 i=0; igetMesh(); + if(mesh->getMeshBufferCount() >= 1) + { + scene::IMeshBuffer *buf = mesh->getMeshBuffer(0); + //dstream<<"Setting texture "<getMaterial().setTexture(0, texture); + } + } + + updateSceneNode(); +#endif + } + + virtual bool serverStep(float dtime, u32 daynight_ratio) + { + return false; + } + +#ifndef SERVER + virtual void clientStep(float dtime) + { + m_yaw += dtime * 60; + if(m_yaw >= 360.) + m_yaw -= 360.; + + updateSceneNode(); + } + + virtual void addToScene(scene::ISceneManager *smgr); + + virtual void removeFromScene() + { + if(m_node != NULL) + { + m_node->remove(); + m_node = NULL; + } + } + virtual void updateLight(u8 light_at_pos) + { + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(getAbsolutePos()); + m_node->setRotation(v3f(0, m_yaw, 0)); + } + } +#endif + + void setItemString(std::string inventorystring) + { + m_itemstring = inventorystring; + setBlockChanged(); + } + + std::string getItemString() + { + return m_itemstring; + } + +protected: + scene::IMeshSceneNode *m_node; + std::string m_itemstring; + f32 m_yaw; +}; + +/* + NOTE: Not used. +*/ +class PlayerObject : public MovingObject +{ +public: + PlayerObject(MapBlock *block, s16 id, v3f pos): + MovingObject(block, id, pos), + m_node(NULL), + m_yaw(0) + { + m_collision_box = new core::aabbox3d + (-BS*0.3,-BS*.25,-BS*0.3, BS*0.3,BS*0.25,BS*0.3); + /*m_selection_box = new core::aabbox3d + (-BS*0.3,-BS*.25,-BS*0.3, BS*0.3,BS*0.25,BS*0.3);*/ + } + virtual ~PlayerObject() + { + if(m_collision_box) + delete m_collision_box; + if(m_selection_box) + delete m_selection_box; + } + + /* + Implementation interface + */ + virtual u16 getTypeId() const + { + return MAPBLOCKOBJECT_TYPE_PLAYER; + } + virtual void serialize(std::ostream &os, u8 version) + { + // Object data is generated from actual player + } + virtual void update(std::istream &is, u8 version) + { + MovingObject::update(is, version); + u8 buf[2]; + + // Read yaw * 10 + is.read((char*)buf, 2); + s16 yaw_i = readS16(buf); + m_yaw = (f32)yaw_i / 10; + + updateNodePos(); + } + + virtual bool serverStep(float dtime, u32 daynight_ratio) + { + // Player is handled elsewhere. + // Die. + //return true; + // Actually, fail very loudly: + assert(0); + } + +#ifndef SERVER + virtual void clientStep(float dtime) + { + MovingObject::simpleMove(dtime); + + updateNodePos(); + } + + virtual void addToScene(scene::ISceneManager *smgr); + + virtual void removeFromScene() + { + if(m_node == NULL) + return; + + m_node->remove(); + m_node = NULL; + } + + virtual void updateLight(u8 light_at_pos) + { + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; isetPosition(getAbsoluteShowPos()); + m_node->setRotation(v3f(0, -m_yaw+180, 0)); + } + +protected: + scene::IMeshSceneNode *m_node; + float m_yaw; + + v3f m_oldpos; +}; + +struct DistanceSortedObject +{ + DistanceSortedObject(MapBlockObject *a_obj, f32 a_d) + { + obj = a_obj; + d = a_d; + } + + MapBlockObject *obj; + f32 d; + + bool operator < (DistanceSortedObject &other) + { + return d < other.d; + } +}; + +class MapBlockObjectList +{ +public: + MapBlockObjectList(MapBlock *block); + ~MapBlockObjectList(); + + // Writes the count, id, the type id and the parameters of all objects + void serialize(std::ostream &os, u8 version); + + // Reads ids, type_ids and parameters. + // Creates, updates and deletes objects. + // If smgr!=NULL, new objects are added to the scene + void update(std::istream &is, u8 version, scene::ISceneManager *smgr, + u32 daynight_ratio); + + // Finds a new unique id + s16 getFreeId() throw(ContainerFullException); + /* + Adds an object. + Set id to -1 to have this set it to a suitable one. + The block pointer member is set to this block. + */ + void add(MapBlockObject *object) + throw(ContainerFullException, AlreadyExistsException); + + // Deletes and removes all objects + void clear(); + + /* + Removes an object. + Ignores inexistent objects + */ + void remove(s16 id); + /* + References an object. + The object will not be valid after step() or of course if + it is removed. + Grabbing the lock is recommended while processing. + */ + MapBlockObject * get(s16 id); + + // You'll want to grab this in a SharedPtr + JMutexAutoLock * getLock() + { + return new JMutexAutoLock(m_mutex); + } + + // Steps all objects and if server==true, removes those that + // want to be removed + void step(float dtime, bool server, u32 daynight_ratio); + + // Wraps an object that wants to move onto this block from an another + // Returns true if wrapping was impossible + bool wrapObject(MapBlockObject *object); + + // origin is relative to block + void getObjects(v3f origin, f32 max_d, + core::array &dest); + + // Number of objects + s32 getCount() + { + return m_objects.size(); + } + +private: + JMutex m_mutex; + // Key is id + core::map m_objects; + MapBlock *m_block; + + u32 m_last_update_daynight_ratio; +}; + + +#endif + diff --git a/src/mapchunk.h b/src/mapchunk.h new file mode 100644 index 0000000..98df7ce --- /dev/null +++ b/src/mapchunk.h @@ -0,0 +1,77 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAPCHUNK_HEADER +#define MAPCHUNK_HEADER + +/* + TODO: Remove +*/ + +#if 0 +/* + MapChunk contains map-generation-time metadata for an area of + some MapSectors. (something like 16x16) +*/ + +// These should fit in 8 bits, as they are saved as such. +enum{ + GENERATED_FULLY = 0, + GENERATED_PARTLY = 10, + GENERATED_NOT = 20 +}; + +class MapChunk +{ +public: + MapChunk(): + m_generation_level(GENERATED_NOT), + m_modified(true) + { + } + + /* + Generation level. Possible values: + GENERATED_FULLY = 0 = fully generated + GENERATED_PARTLY = partly generated + GENERATED_NOT = not generated + */ + u16 getGenLevel(){ return m_generation_level; } + void setGenLevel(u16 lev){ m_generation_level = lev; } + + void serialize(std::ostream &os, u8 version) + { + os.write((char*)&m_generation_level, 1); + } + void deSerialize(std::istream &is, u8 version) + { + is.read((char*)&m_generation_level, 1); + } + + bool isModified(){ return m_modified; } + void setModified(bool modified){ m_modified = modified; } + +private: + u8 m_generation_level; + bool m_modified; +}; +#endif + +#endif + diff --git a/src/mapgen.cpp b/src/mapgen.cpp new file mode 100644 index 0000000..a07f4ca --- /dev/null +++ b/src/mapgen.cpp @@ -0,0 +1,2294 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "mapgen.h" +#include "voxel.h" +#include "content_mapnode.h" +#include "noise.h" +#include "mapblock.h" +#include "map.h" +#include "mineral.h" +//#include "serverobject.h" +#include "content_sao.h" + +namespace mapgen +{ + +/* + Some helper functions for the map generator +*/ + +#if 0 +static s16 find_ground_level(VoxelManipulator &vmanip, v2s16 p2d) +{ + v3s16 em = vmanip.m_area.getExtent(); + s16 y_nodes_max = vmanip.m_area.MaxEdge.Y; + s16 y_nodes_min = vmanip.m_area.MinEdge.Y; + u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y)); + s16 y; + for(y=y_nodes_max; y>=y_nodes_min; y--) + { + MapNode &n = vmanip.m_data[i]; + if(content_walkable(n.d)) + break; + + vmanip.m_area.add_y(em, i, -1); + } + if(y >= y_nodes_min) + return y; + else + return y_nodes_min; +} + +static s16 find_ground_level_clever(VoxelManipulator &vmanip, v2s16 p2d) +{ + v3s16 em = vmanip.m_area.getExtent(); + s16 y_nodes_max = vmanip.m_area.MaxEdge.Y; + s16 y_nodes_min = vmanip.m_area.MinEdge.Y; + u32 i = vmanip.m_area.index(v3s16(p2d.X, y_nodes_max, p2d.Y)); + s16 y; + for(y=y_nodes_max; y>=y_nodes_min; y--) + { + MapNode &n = vmanip.m_data[i]; + if(content_walkable(n.d) + && n.getContent() != CONTENT_TREE + && n.getContent() != CONTENT_LEAVES) + break; + + vmanip.m_area.add_y(em, i, -1); + } + if(y >= y_nodes_min) + return y; + else + return y_nodes_min; +} +#endif + +static void make_tree(VoxelManipulator &vmanip, v3s16 p0, bool is_apple_tree) +{ + MapNode treenode(CONTENT_TREE); + MapNode leavesnode(CONTENT_LEAVES); + MapNode applenode(CONTENT_APPLE); + + s16 trunk_h = myrand_range(4, 5); + v3s16 p1 = p0; + for(s16 ii=0; ii leaves_d(new u8[leaves_a.getVolume()]); + Buffer leaves_d(leaves_a.getVolume()); + for(s32 i=0; i leaves_d(new u8[leaves_a.getVolume()]); + Buffer leaves_d(leaves_a.getVolume()); + for(s32 i=0; i stone_d(stone_a.getVolume()); + for(s32 i=0; i 0.0) + { + u32 vi = stone_a.index(v3s16(x,y,z)); + stone_d[vi] = 1; + } + } + + /*// Add stone randomly + for(u32 iii=0; iii<7; iii++) + { + s16 d = 1; + + v3s16 p( + myrand_range(stone_a.MinEdge.X, stone_a.MaxEdge.X-d), + myrand_range(stone_a.MinEdge.Y, stone_a.MaxEdge.Y-d), + myrand_range(stone_a.MinEdge.Z, stone_a.MaxEdge.Z-d) + ); + + for(s16 z=0; z<=d; z++) + for(s16 y=0; y<=d; y++) + for(s16 x=0; x<=d; x++) + { + stone_d[stone_a.index(p+v3s16(x,y,z))] = 1; + } + }*/ + + // Blit stone to vmanip + for(s16 z=stone_a.MinEdge.Z; z<=stone_a.MaxEdge.Z; z++) + for(s16 y=stone_a.MinEdge.Y; y<=stone_a.MaxEdge.Y; y++) + for(s16 x=stone_a.MinEdge.X; x<=stone_a.MaxEdge.X; x++) + { + v3s16 p(x,y,z); + p += p0; + if(vmanip.m_area.contains(p) == false) + continue; + u32 vi = vmanip.m_area.index(p); + if(vmanip.m_data[vi].getContent() != CONTENT_AIR + && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) + continue; + u32 i = stone_a.index(x,y,z); + if(stone_d[i] == 1) + vmanip.m_data[vi] = stonenode; + } +} +#endif + +#if 0 +static void make_largestone(VoxelManipulator &vmanip, v3s16 p0) +{ + MapNode stonenode(CONTENT_STONE); + + s16 size = myrand_range(8, 16); + + VoxelArea stone_a(v3s16(-size/2,0,-size/2), v3s16(size/2,size,size/2)); + Buffer stone_d(stone_a.getVolume()); + for(s32 i=0; i 1.0) + { + u32 vi = stone_a.index(v3s16(x,y,z)); + stone_d[vi] = 1; + } + } + + /*// Add stone randomly + for(u32 iii=0; iii<7; iii++) + { + s16 d = 1; + + v3s16 p( + myrand_range(stone_a.MinEdge.X, stone_a.MaxEdge.X-d), + myrand_range(stone_a.MinEdge.Y, stone_a.MaxEdge.Y-d), + myrand_range(stone_a.MinEdge.Z, stone_a.MaxEdge.Z-d) + ); + + for(s16 z=0; z<=d; z++) + for(s16 y=0; y<=d; y++) + for(s16 x=0; x<=d; x++) + { + stone_d[stone_a.index(p+v3s16(x,y,z))] = 1; + } + }*/ + + // Blit stone to vmanip + for(s16 z=stone_a.MinEdge.Z; z<=stone_a.MaxEdge.Z; z++) + for(s16 y=stone_a.MinEdge.Y; y<=stone_a.MaxEdge.Y; y++) + for(s16 x=stone_a.MinEdge.X; x<=stone_a.MaxEdge.X; x++) + { + v3s16 p(x,y,z); + p += p0; + if(vmanip.m_area.contains(p) == false) + continue; + u32 vi = vmanip.m_area.index(p); + /*if(vmanip.m_data[vi].getContent() != CONTENT_AIR + && vmanip.m_data[vi].getContent() != CONTENT_IGNORE) + continue;*/ + u32 i = stone_a.index(x,y,z); + if(stone_d[i] == 1) + vmanip.m_data[vi] = stonenode; + } +} +#endif + +/* + Dungeon making routines +*/ + +#define VMANIP_FLAG_DUNGEON_INSIDE VOXELFLAG_CHECKED1 +#define VMANIP_FLAG_DUNGEON_PRESERVE VOXELFLAG_CHECKED2 +#define VMANIP_FLAG_DUNGEON_UNTOUCHABLE (\ + VMANIP_FLAG_DUNGEON_INSIDE|VMANIP_FLAG_DUNGEON_PRESERVE) + +static void make_room1(VoxelManipulator &vmanip, v3s16 roomsize, v3s16 roomplace) +{ + // Make +-X walls + for(s16 z=0; z= 3) + make_stairs = random.next()%2 ? 1 : -1; + for(u32 i=0; i= partlength) + { + partcount = 0; + + dir = random_turn(random, dir); + + partlength = random.range(1,length); + + make_stairs = 0; + if(random.next()%2 == 0 && partlength >= 3) + make_stairs = random.next()%2 ? 1 : -1; + } + } + result_place = p0; + result_dir = dir; +} + +class RoomWalker +{ +public: + + RoomWalker(VoxelManipulator &vmanip_, v3s16 pos, PseudoRandom &random): + vmanip(vmanip_), + m_pos(pos), + m_random(random) + { + randomizeDir(); + } + + void randomizeDir() + { + m_dir = rand_ortho_dir(m_random); + } + + void setPos(v3s16 pos) + { + m_pos = pos; + } + + void setDir(v3s16 dir) + { + m_dir = dir; + } + + bool findPlaceForDoor(v3s16 &result_place, v3s16 &result_dir) + { + for(u32 i=0; i<100; i++) + { + v3s16 p = m_pos + m_dir; + v3s16 p1 = p + v3s16(0,1,0); + if(vmanip.m_area.contains(p) == false + || vmanip.m_area.contains(p1) == false + || i % 4 == 0) + { + randomizeDir(); + continue; + } + if(vmanip.getNodeNoExNoEmerge(p).getContent() + == CONTENT_COBBLE + && vmanip.getNodeNoExNoEmerge(p1).getContent() + == CONTENT_COBBLE) + { + // Found wall, this is a good place! + result_place = p; + result_dir = m_dir; + // Randomize next direction + randomizeDir(); + return true; + } + /* + Determine where to move next + */ + // Jump one up if the actual space is there + if(vmanip.getNodeNoExNoEmerge(p+v3s16(0,0,0)).getContent() + == CONTENT_COBBLE + && vmanip.getNodeNoExNoEmerge(p+v3s16(0,1,0)).getContent() + == CONTENT_AIR + && vmanip.getNodeNoExNoEmerge(p+v3s16(0,2,0)).getContent() + == CONTENT_AIR) + p += v3s16(0,1,0); + // Jump one down if the actual space is there + if(vmanip.getNodeNoExNoEmerge(p+v3s16(0,1,0)).getContent() + == CONTENT_COBBLE + && vmanip.getNodeNoExNoEmerge(p+v3s16(0,0,0)).getContent() + == CONTENT_AIR + && vmanip.getNodeNoExNoEmerge(p+v3s16(0,-1,0)).getContent() + == CONTENT_AIR) + p += v3s16(0,-1,0); + // Check if walking is now possible + if(vmanip.getNodeNoExNoEmerge(p).getContent() + != CONTENT_AIR + || vmanip.getNodeNoExNoEmerge(p+v3s16(0,1,0)).getContent() + != CONTENT_AIR) + { + // Cannot continue walking here + randomizeDir(); + continue; + } + // Move there + m_pos = p; + } + return false; + } + + bool findPlaceForRoomDoor(v3s16 roomsize, v3s16 &result_doorplace, + v3s16 &result_doordir, v3s16 &result_roomplace) + { + for(s16 trycount=0; trycount<30; trycount++) + { + v3s16 doorplace; + v3s16 doordir; + bool r = findPlaceForDoor(doorplace, doordir); + if(r == false) + continue; + v3s16 roomplace; + // X east, Z north, Y up +#if 1 + if(doordir == v3s16(1,0,0)) // X+ + roomplace = doorplace + + v3s16(0,-1,m_random.range(-roomsize.Z+2,-2)); + if(doordir == v3s16(-1,0,0)) // X- + roomplace = doorplace + + v3s16(-roomsize.X+1,-1,m_random.range(-roomsize.Z+2,-2)); + if(doordir == v3s16(0,0,1)) // Z+ + roomplace = doorplace + + v3s16(m_random.range(-roomsize.X+2,-2),-1,0); + if(doordir == v3s16(0,0,-1)) // Z- + roomplace = doorplace + + v3s16(m_random.range(-roomsize.X+2,-2),-1,-roomsize.Z+1); +#endif +#if 0 + if(doordir == v3s16(1,0,0)) // X+ + roomplace = doorplace + v3s16(0,-1,-roomsize.Z/2); + if(doordir == v3s16(-1,0,0)) // X- + roomplace = doorplace + v3s16(-roomsize.X+1,-1,-roomsize.Z/2); + if(doordir == v3s16(0,0,1)) // Z+ + roomplace = doorplace + v3s16(-roomsize.X/2,-1,0); + if(doordir == v3s16(0,0,-1)) // Z- + roomplace = doorplace + v3s16(-roomsize.X/2,-1,-roomsize.Z+1); +#endif + + // Check fit + bool fits = true; + for(s16 z=1; z CAVE_NOISE_THRESHOLD; +} + +/* + Ground density noise shall be interpreted by using this. + + TODO: No perlin noises here, they should be outsourced + and buffered + NOTE: The speed of these actually isn't terrible +*/ +bool val_is_ground(double ground_noise1_val, v3s16 p, u64 seed) +{ + //return ((double)p.Y < ground_noise1_val); + + double f = 0.55 + noise2d_perlin( + 0.5+(float)p.X/250, 0.5+(float)p.Z/250, + seed+920381, 3, 0.45); + if(f < 0.01) + f = 0.01; + else if(f >= 1.0) + f *= 1.6; + double h = WATER_LEVEL + 10 * noise2d_perlin( + 0.5+(float)p.X/250, 0.5+(float)p.Z/250, + seed+84174, 4, 0.5); + /*double f = 1; + double h = 0;*/ + return ((double)p.Y - h < ground_noise1_val * f); +} + +/* + Queries whether a position is ground or not. +*/ +bool is_ground(u64 seed, v3s16 p) +{ + double val1 = noise3d_param(get_ground_noise1_params(seed), p.X,p.Y,p.Z); + return val_is_ground(val1, p, seed); +} + +// Amount of trees per area in nodes +double tree_amount_2d(u64 seed, v2s16 p) +{ + /*double noise = noise2d_perlin( + 0.5+(float)p.X/250, 0.5+(float)p.Y/250, + seed+2, 5, 0.66);*/ + double noise = noise2d_perlin( + 0.5+(float)p.X/125, 0.5+(float)p.Y/125, + seed+2, 4, 0.66); + double zeroval = -0.39; + if(noise < zeroval) + return 0; + else + return 0.04 * (noise-zeroval) / (1.0-zeroval); +} + +double surface_humidity_2d(u64 seed, v2s16 p) +{ + double noise = noise2d_perlin( + 0.5+(float)p.X/500, 0.5+(float)p.Y/500, + seed+72384, 4, 0.66); + noise = (noise + 1.0)/2.0; + if(noise < 0.0) + noise = 0.0; + if(noise > 1.0) + noise = 1.0; + return noise; +} + +#if 0 +double randomstone_amount_2d(u64 seed, v2s16 p) +{ + double noise = noise2d_perlin( + 0.5+(float)p.X/250, 0.5+(float)p.Y/250, + seed+3829434, 5, 0.66); + double zeroval = 0.1; + if(noise < zeroval) + return 0; + else + return 0.01 * (noise-zeroval) / (1.0-zeroval); +} +#endif + +double largestone_amount_2d(u64 seed, v2s16 p) +{ + double noise = noise2d_perlin( + 0.5+(float)p.X/250, 0.5+(float)p.Y/250, + seed+14143242, 5, 0.66); + double zeroval = 0.3; + if(noise < zeroval) + return 0; + else + return 0.005 * (noise-zeroval) / (1.0-zeroval); +} + +/* + Incrementally find ground level from 3d noise +*/ +s16 find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision) +{ + // Start a bit fuzzy to make averaging lower precision values + // more useful + s16 level = myrand_range(-precision/2, precision/2); + s16 dec[] = {31000, 100, 20, 4, 1, 0}; + s16 i; + for(i = 1; dec[i] != 0 && precision <= dec[i]; i++) + { + // First find non-ground by going upwards + // Don't stop in caves. + { + s16 max = level+dec[i-1]*2; + v3s16 p(p2d.X, level, p2d.Y); + for(; p.Y < max; p.Y += dec[i]) + { + if(!is_ground(seed, p)) + { + level = p.Y; + break; + } + } + } + // Then find ground by going downwards from there. + // Go in caves, too, when precision is 1. + { + s16 min = level-dec[i-1]*2; + v3s16 p(p2d.X, level, p2d.Y); + for(; p.Y>min; p.Y-=dec[i]) + { + bool ground = is_ground(seed, p); + /*if(dec[i] == 1 && is_cave(seed, p)) + ground = false;*/ + if(ground) + { + level = p.Y; + break; + } + } + } + } + + // This is more like the actual ground level + level += dec[i-1]/2; + + return level; +} + +double get_sector_average_ground_level(u64 seed, v2s16 sectorpos, double p=4); + +double get_sector_average_ground_level(u64 seed, v2s16 sectorpos, double p) +{ + v2s16 node_min = sectorpos*MAP_BLOCKSIZE; + v2s16 node_max = (sectorpos+v2s16(1,1))*MAP_BLOCKSIZE-v2s16(1,1); + double a = 0; + a += find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y), p); + a += find_ground_level_from_noise(seed, + v2s16(node_min.X, node_max.Y), p); + a += find_ground_level_from_noise(seed, + v2s16(node_max.X, node_max.Y), p); + a += find_ground_level_from_noise(seed, + v2s16(node_max.X, node_min.Y), p); + a += find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_min.Y+MAP_BLOCKSIZE/2), p); + a /= 5; + return a; +} + +double get_sector_maximum_ground_level(u64 seed, v2s16 sectorpos, double p=4); + +double get_sector_maximum_ground_level(u64 seed, v2s16 sectorpos, double p) +{ + v2s16 node_min = sectorpos*MAP_BLOCKSIZE; + v2s16 node_max = (sectorpos+v2s16(1,1))*MAP_BLOCKSIZE-v2s16(1,1); + double a = -31000; + // Corners + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y), p)); + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_max.Y), p)); + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_max.X, node_max.Y), p)); + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y), p)); + // Center + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_min.Y+MAP_BLOCKSIZE/2), p)); + // Side middle points + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_min.Y), p)); + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_max.Y), p)); + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y+MAP_BLOCKSIZE/2), p)); + a = MYMAX(a, find_ground_level_from_noise(seed, + v2s16(node_max.X, node_min.Y+MAP_BLOCKSIZE/2), p)); + return a; +} + +double get_sector_minimum_ground_level(u64 seed, v2s16 sectorpos, double p=4); + +double get_sector_minimum_ground_level(u64 seed, v2s16 sectorpos, double p) +{ + v2s16 node_min = sectorpos*MAP_BLOCKSIZE; + v2s16 node_max = (sectorpos+v2s16(1,1))*MAP_BLOCKSIZE-v2s16(1,1); + double a = 31000; + // Corners + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y), p)); + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_max.Y), p)); + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_max.X, node_max.Y), p)); + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y), p)); + // Center + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_min.Y+MAP_BLOCKSIZE/2), p)); + // Side middle points + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_min.Y), p)); + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X+MAP_BLOCKSIZE/2, node_max.Y), p)); + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_min.X, node_min.Y+MAP_BLOCKSIZE/2), p)); + a = MYMIN(a, find_ground_level_from_noise(seed, + v2s16(node_max.X, node_min.Y+MAP_BLOCKSIZE/2), p)); + return a; +} + +bool block_is_underground(u64 seed, v3s16 blockpos) +{ + s16 minimum_groundlevel = (s16)get_sector_minimum_ground_level( + seed, v2s16(blockpos.X, blockpos.Z)); + + if(blockpos.Y*MAP_BLOCKSIZE + MAP_BLOCKSIZE <= minimum_groundlevel) + return true; + else + return false; +} + +#if 0 +#define AVERAGE_MUD_AMOUNT 4 + +double base_rock_level_2d(u64 seed, v2s16 p) +{ + // The base ground level + double base = (double)WATER_LEVEL - (double)AVERAGE_MUD_AMOUNT + + 20. * noise2d_perlin( + 0.5+(float)p.X/500., 0.5+(float)p.Y/500., + (seed>>32)+654879876, 6, 0.6); + + /*// A bit hillier one + double base2 = WATER_LEVEL - 4.0 + 40. * noise2d_perlin( + 0.5+(float)p.X/250., 0.5+(float)p.Y/250., + (seed>>27)+90340, 6, 0.69); + if(base2 > base) + base = base2;*/ +#if 1 + // Higher ground level + double higher = (double)WATER_LEVEL + 25. + 35. * noise2d_perlin( + 0.5+(float)p.X/250., 0.5+(float)p.Y/250., + seed+85039, 5, 0.69); + //higher = 30; // For debugging + + // Limit higher to at least base + if(higher < base) + higher = base; + + // Steepness factor of cliffs + double b = 1.0 + 1.0 * noise2d_perlin( + 0.5+(float)p.X/250., 0.5+(float)p.Y/250., + seed-932, 7, 0.7); + b = rangelim(b, 0.0, 1000.0); + b = pow(b, 5); + b *= 7; + b = rangelim(b, 3.0, 1000.0); + //dstream<<"b="<blockpos; + + /*dstream<<"makeBlock(): ("<vmanip); + v3s16 blockpos_min = blockpos - v3s16(1,1,1); + v3s16 blockpos_max = blockpos + v3s16(1,1,1); + // Area of center block + v3s16 node_min = blockpos*MAP_BLOCKSIZE; + v3s16 node_max = (blockpos+v3s16(1,1,1))*MAP_BLOCKSIZE-v3s16(1,1,1); + // Full allocated area + v3s16 full_node_min = (blockpos-1)*MAP_BLOCKSIZE; + v3s16 full_node_max = (blockpos+2)*MAP_BLOCKSIZE-v3s16(1,1,1); + // Area of a block + double block_area_nodes = MAP_BLOCKSIZE*MAP_BLOCKSIZE; + + v2s16 p2d_center(node_min.X+MAP_BLOCKSIZE/2, node_min.Z+MAP_BLOCKSIZE/2); + + /* + Get average ground level from noise + */ + + s16 approx_groundlevel = (s16)get_sector_average_ground_level( + data->seed, v2s16(blockpos.X, blockpos.Z)); + //dstream<<"approx_groundlevel="<seed, v2s16(blockpos.X, blockpos.Z)); + // Minimum amount of ground above the top of the central block + s16 minimum_ground_depth = minimum_groundlevel - node_max.Y; + + s16 maximum_groundlevel = (s16)get_sector_maximum_ground_level( + data->seed, v2s16(blockpos.X, blockpos.Z), 1); + // Maximum amount of ground above the bottom of the central block + s16 maximum_ground_depth = maximum_groundlevel - node_min.Y; + + #if 0 + /* + Special case for high air or water: Just fill with air and water. + */ + if(maximum_ground_depth < -20) + { + for(s16 x=node_min.X; x<=node_max.X; x++) + for(s16 z=node_min.Z; z<=node_max.Z; z++) + { + // Node position + v2s16 p2d(x,z); + { + // Use fast index incrementing + v3s16 em = vmanip.m_area.getExtent(); + u32 i = vmanip.m_area.index(v3s16(p2d.X, node_min.Y, p2d.Y)); + for(s16 y=node_min.Y; y<=node_max.Y; y++) + { + // Only modify places that have no content + if(vmanip.m_data[i].getContent() == CONTENT_IGNORE) + { + if(y <= WATER_LEVEL) + vmanip.m_data[i] = MapNode(CONTENT_WATERSOURCE); + else + vmanip.m_data[i] = MapNode(CONTENT_AIR); + } + + data->vmanip->m_area.add_y(em, i, 1); + } + } + } + + // We're done + return; + } + #endif + + /* + If block is deep underground, this is set to true and ground + density noise is not generated, for speed optimization. + */ + bool all_is_ground_except_caves = (minimum_ground_depth > 40); + + /* + Create a block-specific seed + */ + u32 blockseed = (u32)(data->seed%0x100000000ULL) + full_node_min.Z*38134234 + + full_node_min.Y*42123 + full_node_min.X*23; + + /* + Make some 3D noise + */ + + //NoiseBuffer noisebuf1; + //NoiseBuffer noisebuf2; + NoiseBuffer noisebuf_cave; + NoiseBuffer noisebuf_ground; + NoiseBuffer noisebuf_ground_crumbleness; + NoiseBuffer noisebuf_ground_wetness; + { + v3f minpos_f(node_min.X, node_min.Y, node_min.Z); + v3f maxpos_f(node_max.X, node_max.Y, node_max.Z); + + //TimeTaker timer("noisebuf.create"); + + /* + Cave noise + */ +#if 1 + noisebuf_cave.create(get_cave_noise1_params(data->seed), + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y, maxpos_f.Z, + 2, 2, 2); + noisebuf_cave.multiply(get_cave_noise2_params(data->seed)); +#endif + + /* + Ground noise + */ + + // Sample length + v3f sl = v3f(4.0, 4.0, 4.0); + + /* + Density noise + */ + if(all_is_ground_except_caves == false) + //noisebuf_ground.create(data->seed+983240, 6, 0.60, false, + noisebuf_ground.create(get_ground_noise1_params(data->seed), + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y, maxpos_f.Z, + sl.X, sl.Y, sl.Z); + + /* + Ground property noise + */ + sl = v3f(2.5, 2.5, 2.5); + noisebuf_ground_crumbleness.create( + get_ground_crumbleness_params(data->seed), + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y+5, maxpos_f.Z, + sl.X, sl.Y, sl.Z); + noisebuf_ground_wetness.create( + get_ground_wetness_params(data->seed), + minpos_f.X, minpos_f.Y, minpos_f.Z, + maxpos_f.X, maxpos_f.Y+5, maxpos_f.Z, + sl.X, sl.Y, sl.Z); + } + + /* + Make base ground level + */ + + for(s16 x=node_min.X; x<=node_max.X; x++) + for(s16 z=node_min.Z; z<=node_max.Z; z++) + { + // Node position + v2s16 p2d(x,z); + { + // Use fast index incrementing + v3s16 em = vmanip.m_area.getExtent(); + u32 i = vmanip.m_area.index(v3s16(p2d.X, node_min.Y, p2d.Y)); + for(s16 y=node_min.Y; y<=node_max.Y; y++) + { + // Only modify places that have no content + if(vmanip.m_data[i].getContent() == CONTENT_IGNORE) + { + // First priority: make air and water. + // This avoids caves inside water. + if(all_is_ground_except_caves == false + && val_is_ground(noisebuf_ground.get(x,y,z), + v3s16(x,y,z), data->seed) == false) + { + if(y <= WATER_LEVEL) + vmanip.m_data[i] = MapNode(CONTENT_WATERSOURCE); + else + vmanip.m_data[i] = MapNode(CONTENT_AIR); + } + else if(noisebuf_cave.get(x,y,z) > CAVE_NOISE_THRESHOLD) + vmanip.m_data[i] = MapNode(CONTENT_AIR); + else + vmanip.m_data[i] = MapNode(CONTENT_STONE); + } + + data->vmanip->m_area.add_y(em, i, 1); + } + } + } + + /* + Add minerals + */ + + { + PseudoRandom mineralrandom(blockseed); + + /* + Add meseblocks + */ + for(s16 i=0; i 0.0) + new_content = MapNode(CONTENT_STONE, MINERAL_IRON); + /*if(noisebuf_ground_wetness.get(x,y,z) > 0.0) + vmanip.m_data[i] = MapNode(CONTENT_MUD); + else + vmanip.m_data[i] = MapNode(CONTENT_SAND);*/ + } + /*else if(noisebuf_ground_crumbleness.get(x,y,z) > 0.1) + { + }*/ + + if(new_content.getContent() != CONTENT_IGNORE) + { + for(u16 i=0; i<27; i++) + { + v3s16 p = v3s16(x,y,z) + g_27dirs[i]; + u32 vi = vmanip.m_area.index(p); + if(vmanip.m_data[vi].getContent() == base_content) + { + if(mineralrandom.next()%sparseness == 0) + vmanip.m_data[vi] = new_content; + } + } + } + } + } + /* + Add coal + */ + //for(s16 i=0; i < MYMAX(0, 50 - abs(node_min.Y+8 - (-30))); i++) + //for(s16 i=0; i<50; i++) + u16 coal_amount = 30; + u16 coal_rareness = 60 / coal_amount; + if(coal_rareness == 0) + coal_rareness = 1; + if(mineralrandom.next()%coal_rareness == 0) + { + u16 a = mineralrandom.next() % 16; + u16 amount = coal_amount * a*a*a / 1000; + for(s16 i=0; i=node_min.Y; y--) + { + if(vmanip.m_data[i].getContent() == CONTENT_STONE) + { + if(noisebuf_ground_crumbleness.get(x,y,z) > 1.3) + { + if(noisebuf_ground_wetness.get(x,y,z) > 0.0) + vmanip.m_data[i] = MapNode(CONTENT_MUD); + else + vmanip.m_data[i] = MapNode(CONTENT_SAND); + } + else if(noisebuf_ground_crumbleness.get(x,y,z) > 0.7) + { + if(noisebuf_ground_wetness.get(x,y,z) < -0.6) + vmanip.m_data[i] = MapNode(CONTENT_GRAVEL); + } + else if(noisebuf_ground_crumbleness.get(x,y,z) < + -3.0 + MYMIN(0.1 * sqrt((float)MYMAX(0, -y)), 1.5)) + { + vmanip.m_data[i] = MapNode(CONTENT_LAVASOURCE); + for(s16 x1=-1; x1<=1; x1++) + for(s16 y1=-1; y1<=1; y1++) + for(s16 z1=-1; z1<=1; z1++) + data->transforming_liquid.push_back( + v3s16(p2d.X+x1, y+y1, p2d.Y+z1)); + } + } + + data->vmanip->m_area.add_y(em, i, -1); + } + } + } + + /* + Add dungeons + */ + + //if(node_min.Y < approx_groundlevel) + //if(myrand() % 3 == 0) + //if(myrand() % 3 == 0 && node_min.Y < approx_groundlevel) + //if(myrand() % 100 == 0 && node_min.Y < approx_groundlevel) + //float dungeon_rarity = g_settings.getFloat("dungeon_rarity"); + float dungeon_rarity = 0.02; + if(((noise3d(blockpos.X,blockpos.Y,blockpos.Z,data->seed)+1.0)/2.0) + < dungeon_rarity + && node_min.Y < approx_groundlevel) + { + // Dungeon generator doesn't modify places which have this set + data->vmanip->clearFlag(VMANIP_FLAG_DUNGEON_INSIDE + | VMANIP_FLAG_DUNGEON_PRESERVE); + + // Set all air and water to be untouchable to make dungeons open + // to caves and open air + for(s16 x=full_node_min.X; x<=full_node_max.X; x++) + for(s16 z=full_node_min.Z; z<=full_node_max.Z; z++) + { + // Node position + v2s16 p2d(x,z); + { + // Use fast index incrementing + v3s16 em = vmanip.m_area.getExtent(); + u32 i = vmanip.m_area.index(v3s16(p2d.X, full_node_max.Y, p2d.Y)); + for(s16 y=full_node_max.Y; y>=full_node_min.Y; y--) + { + if(vmanip.m_data[i].getContent() == CONTENT_AIR) + vmanip.m_flags[i] |= VMANIP_FLAG_DUNGEON_PRESERVE; + else if(vmanip.m_data[i].getContent() == CONTENT_WATERSOURCE) + vmanip.m_flags[i] |= VMANIP_FLAG_DUNGEON_PRESERVE; + data->vmanip->m_area.add_y(em, i, -1); + } + } + } + + PseudoRandom random(blockseed+2); + + // Add it + make_dungeon1(vmanip, random); + + // Convert some cobble to mossy cobble + for(s16 x=full_node_min.X; x<=full_node_max.X; x++) + for(s16 z=full_node_min.Z; z<=full_node_max.Z; z++) + { + // Node position + v2s16 p2d(x,z); + { + // Use fast index incrementing + v3s16 em = vmanip.m_area.getExtent(); + u32 i = vmanip.m_area.index(v3s16(p2d.X, full_node_max.Y, p2d.Y)); + for(s16 y=full_node_max.Y; y>=full_node_min.Y; y--) + { + // (noisebuf not used because it doesn't contain the + // full area) + double wetness = noise3d_param( + get_ground_wetness_params(data->seed), x,y,z); + double d = noise3d_perlin((float)x/2.5, + (float)y/2.5,(float)z/2.5, + blockseed, 2, 1.4); + if(vmanip.m_data[i].getContent() == CONTENT_COBBLE) + { + if(d < wetness/3.0) + { + vmanip.m_data[i].setContent(CONTENT_MOSSYCOBBLE); + } + } + /*else if(vmanip.m_flags[i] & VMANIP_FLAG_DUNGEON_INSIDE) + { + if(wetness > 1.2) + vmanip.m_data[i].setContent(CONTENT_MUD); + }*/ + data->vmanip->m_area.add_y(em, i, -1); + } + } + } + } + + /* + Add NC + */ + { + PseudoRandom ncrandom(blockseed+9324342); + if(ncrandom.range(0, 1000) == 0 && blockpos.Y <= -3) + { + make_nc(vmanip, ncrandom); + } + } + + /* + Add top and bottom side of water to transforming_liquid queue + */ + + for(s16 x=node_min.X; x<=node_max.X; x++) + for(s16 z=node_min.Z; z<=node_max.Z; z++) + { + // Node position + v2s16 p2d(x,z); + { + bool water_found = false; + // Use fast index incrementing + v3s16 em = vmanip.m_area.getExtent(); + u32 i = vmanip.m_area.index(v3s16(p2d.X, node_max.Y, p2d.Y)); + for(s16 y=node_max.Y; y>=node_min.Y; y--) + { + if(water_found == false) + { + if(vmanip.m_data[i].getContent() == CONTENT_WATERSOURCE) + { + v3s16 p = v3s16(p2d.X, y, p2d.Y); + data->transforming_liquid.push_back(p); + water_found = true; + } + } + else + { + // This can be done because water_found can only + // turn to true and end up here after going through + // a single block. + if(vmanip.m_data[i+1].getContent() != CONTENT_WATERSOURCE) + { + v3s16 p = v3s16(p2d.X, y+1, p2d.Y); + data->transforming_liquid.push_back(p); + water_found = false; + } + } + + data->vmanip->m_area.add_y(em, i, -1); + } + } + } + + /* + If close to ground level + */ + + //if(abs(approx_ground_depth) < 30) + if(minimum_ground_depth < 5 && maximum_ground_depth > -5) + { + /* + Add grass and mud + */ + + for(s16 x=node_min.X; x<=node_max.X; x++) + for(s16 z=node_min.Z; z<=node_max.Z; z++) + { + // Node position + v2s16 p2d(x,z); + { + bool possibly_have_sand = get_have_sand(data->seed, p2d); + bool have_sand = false; + u32 current_depth = 0; + bool air_detected = false; + bool water_detected = false; + bool have_clay = false; + + // Use fast index incrementing + s16 start_y = node_max.Y+2; + v3s16 em = vmanip.m_area.getExtent(); + u32 i = vmanip.m_area.index(v3s16(p2d.X, start_y, p2d.Y)); + for(s16 y=start_y; y>=node_min.Y-3; y--) + { + if(vmanip.m_data[i].getContent() == CONTENT_WATERSOURCE) + water_detected = true; + if(vmanip.m_data[i].getContent() == CONTENT_AIR) + air_detected = true; + + if((vmanip.m_data[i].getContent() == CONTENT_STONE + || vmanip.m_data[i].getContent() == CONTENT_GRASS + || vmanip.m_data[i].getContent() == CONTENT_MUD + || vmanip.m_data[i].getContent() == CONTENT_SAND + || vmanip.m_data[i].getContent() == CONTENT_GRAVEL + ) && (air_detected || water_detected)) + { + if(current_depth == 0 && y <= WATER_LEVEL+2 + && possibly_have_sand) + have_sand = true; + + if(current_depth < 4) + { + if(have_sand) + { + // Determine whether to have clay in the sand here + double claynoise = noise2d_perlin( + 0.5+(float)p2d.X/500, 0.5+(float)p2d.Y/500, + data->seed+4321, 6, 0.95) + 0.5; + + have_clay = (y <= WATER_LEVEL) && (y >= WATER_LEVEL-2) && ( + ((claynoise > 0) && (claynoise < 0.04) && (current_depth == 0)) || + ((claynoise > 0) && (claynoise < 0.12) && (current_depth == 1)) + ); + if (have_clay) + vmanip.m_data[i] = MapNode(CONTENT_CLAY); + else + vmanip.m_data[i] = MapNode(CONTENT_SAND); + } + #if 1 + else if(current_depth==0 && !water_detected + && y >= WATER_LEVEL && air_detected) + vmanip.m_data[i] = MapNode(CONTENT_GRASS); + #endif + else + vmanip.m_data[i] = MapNode(CONTENT_MUD); + } + else + { + if(vmanip.m_data[i].getContent() == CONTENT_MUD + || vmanip.m_data[i].getContent() == CONTENT_GRASS) + vmanip.m_data[i] = MapNode(CONTENT_STONE); + } + + current_depth++; + + if(current_depth >= 8) + break; + } + else if(current_depth != 0) + break; + + data->vmanip->m_area.add_y(em, i, -1); + } + } + } + + /* + Calculate some stuff + */ + + float surface_humidity = surface_humidity_2d(data->seed, p2d_center); + bool is_jungle = surface_humidity > 0.75; + // Amount of trees + u32 tree_count = block_area_nodes * tree_amount_2d(data->seed, p2d_center); + if(is_jungle) + tree_count *= 5; + + /* + Add trees + */ + PseudoRandom treerandom(blockseed); + // Put trees in random places on part of division + for(u32 i=0; ivmanip, v2s16(x,z)); + s16 y = find_ground_level_from_noise(data->seed, v2s16(x,z), 4); + // Don't make a tree under water level + if(y < WATER_LEVEL) + continue; + // Make sure tree fits (only trees whose starting point is + // at this block are added) + if(y < node_min.Y || y > node_max.Y) + continue; + /* + Find exact ground level + */ + v3s16 p(x,y+6,z); + bool found = false; + for(; p.Y >= y-6; p.Y--) + { + u32 i = data->vmanip->m_area.index(p); + MapNode *n = &data->vmanip->m_data[i]; + if(n->getContent() != CONTENT_AIR && n->getContent() != CONTENT_WATERSOURCE && n->getContent() != CONTENT_IGNORE) + { + found = true; + break; + } + } + // If not found, handle next one + if(found == false) + continue; + + { + u32 i = data->vmanip->m_area.index(p); + MapNode *n = &data->vmanip->m_data[i]; + + if(n->getContent() != CONTENT_MUD && n->getContent() != CONTENT_GRASS && n->getContent() != CONTENT_SAND) + continue; + + // Papyrus grows only on mud and in water + if(n->getContent() == CONTENT_MUD && y <= WATER_LEVEL) + { + p.Y++; + make_papyrus(vmanip, p); + } + // Trees grow only on mud and grass, on land + else if((n->getContent() == CONTENT_MUD || n->getContent() == CONTENT_GRASS) && y > WATER_LEVEL + 2) + { + p.Y++; + //if(surface_humidity_2d(data->seed, v2s16(x, y)) < 0.5) + if(is_jungle == false) + { + bool is_apple_tree; + if(myrand_range(0,4) != 0) + is_apple_tree = false; + else + is_apple_tree = noise2d_perlin( + 0.5+(float)p.X/100, 0.5+(float)p.Z/100, + data->seed+342902, 3, 0.45) > 0.2; + make_tree(vmanip, p, is_apple_tree); + } + else + make_jungletree(vmanip, p); + } + // Cactii grow only on sand, on land + else if(n->getContent() == CONTENT_SAND && y > WATER_LEVEL + 2) + { + p.Y++; + make_cactus(vmanip, p); + } + } + } + + /* + Add jungle grass + */ + if(is_jungle) + { + PseudoRandom grassrandom(blockseed); + for(u32 i=0; iseed, v2s16(x,z), 4); + if(y < WATER_LEVEL) + continue; + if(y < node_min.Y || y > node_max.Y) + continue; + /* + Find exact ground level + */ + v3s16 p(x,y+6,z); + bool found = false; + for(; p.Y >= y-6; p.Y--) + { + u32 i = data->vmanip->m_area.index(p); + MapNode *n = &data->vmanip->m_data[i]; + if(content_features(*n).is_ground_content + || n->getContent() == CONTENT_JUNGLETREE) + { + found = true; + break; + } + } + // If not found, handle next one + if(found == false) + continue; + p.Y++; + if(vmanip.m_area.contains(p) == false) + continue; + if(vmanip.m_data[vmanip.m_area.index(p)].getContent() != CONTENT_AIR) + continue; + /*p.Y--; + if(vmanip.m_area.contains(p)) + vmanip.m_data[vmanip.m_area.index(p)] = CONTENT_MUD; + p.Y++;*/ + if(vmanip.m_area.contains(p)) + vmanip.m_data[vmanip.m_area.index(p)] = CONTENT_JUNGLEGRASS; + } + } + +#if 0 + /* + Add some kind of random stones + */ + + u32 random_stone_count = block_area_nodes * + randomstone_amount_2d(data->seed, p2d_center); + // Put in random places on part of division + for(u32 i=0; iseed, v2s16(x,z), 1); + // Don't add under water level + /*if(y < WATER_LEVEL) + continue;*/ + // Don't add if doesn't belong to this block + if(y < node_min.Y || y > node_max.Y) + continue; + v3s16 p(x,y,z); + // Filter placement + /*{ + u32 i = data->vmanip->m_area.index(v3s16(p)); + MapNode *n = &data->vmanip->m_data[i]; + if(n->getContent() != CONTENT_MUD && n->getContent() != CONTENT_GRASS) + continue; + }*/ + // Will be placed one higher + p.Y++; + // Add it + make_randomstone(data->vmanip, p); + } +#endif + +#if 0 + /* + Add larger stones + */ + + u32 large_stone_count = block_area_nodes * + largestone_amount_2d(data->seed, p2d_center); + //u32 large_stone_count = 1; + // Put in random places on part of division + for(u32 i=0; iseed, v2s16(x,z), 1); + // Don't add under water level + /*if(y < WATER_LEVEL) + continue;*/ + // Don't add if doesn't belong to this block + if(y < node_min.Y || y > node_max.Y) + continue; + v3s16 p(x,y,z); + // Filter placement + /*{ + u32 i = data->vmanip->m_area.index(v3s16(p)); + MapNode *n = &data->vmanip->m_data[i]; + if(n->getContent() != CONTENT_MUD && n->getContent() != CONTENT_GRASS) + continue; + }*/ + // Will be placed one lower + p.Y--; + // Add it + make_largestone(data->vmanip, p); + } +#endif + } + +} + +BlockMakeData::BlockMakeData(): + no_op(false), + vmanip(NULL), + seed(0) +{} + +BlockMakeData::~BlockMakeData() +{ + delete vmanip; +} + +}; // namespace mapgen + + diff --git a/src/mapgen.h b/src/mapgen.h new file mode 100644 index 0000000..57d0ee8 --- /dev/null +++ b/src/mapgen.h @@ -0,0 +1,66 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAPGEN_HEADER +#define MAPGEN_HEADER + +#include "common_irrlicht.h" +#include "utility.h" // UniqueQueue + +struct BlockMakeData; +class MapBlock; +class ManualMapVoxelManipulator; + +namespace mapgen +{ + // Finds precise ground level at any position + s16 find_ground_level_from_noise(u64 seed, v2s16 p2d, s16 precision); + + // Find out if block is completely underground + bool block_is_underground(u64 seed, v3s16 blockpos); + + // Main map generation routine + void make_block(BlockMakeData *data); + + // Add objects according to block content + void add_random_objects(MapBlock *block); + + /* + These are used by FarMesh + */ + bool get_have_sand(u64 seed, v2s16 p2d); + double tree_amount_2d(u64 seed, v2s16 p); + + + struct BlockMakeData + { + bool no_op; + ManualMapVoxelManipulator *vmanip; + u64 seed; + v3s16 blockpos; + UniqueQueue transforming_liquid; + + BlockMakeData(); + ~BlockMakeData(); + }; + +}; // namespace mapgen + +#endif + diff --git a/src/mapnode.cpp b/src/mapnode.cpp new file mode 100644 index 0000000..956abe5 --- /dev/null +++ b/src/mapnode.cpp @@ -0,0 +1,401 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "common_irrlicht.h" +#include "mapnode.h" +#include "tile.h" +#include "porting.h" +#include +#include "mineral.h" +// For g_settings +#include "main.h" +#include "content_mapnode.h" +#include "nodemetadata.h" + +ContentFeatures::~ContentFeatures() +{ + delete initial_metadata; + delete special_material; + delete special_atlas; +} + +void ContentFeatures::setTexture(u16 i, std::string name, u8 alpha) +{ + if(g_texturesource) + { + tiles[i].texture = g_texturesource->getTexture(name); + } + + if(alpha != 255) + { + tiles[i].alpha = alpha; + tiles[i].material_type = MATERIAL_ALPHA_VERTEX; + } + + if(inventory_texture == NULL) + setInventoryTexture(name); +} + +void ContentFeatures::setInventoryTexture(std::string imgname) +{ + if(g_texturesource == NULL) + return; + + imgname += "^[forcesingle"; + + inventory_texture = g_texturesource->getTextureRaw(imgname); +} + +void ContentFeatures::setInventoryTextureCube(std::string top, + std::string left, std::string right) +{ + if(g_texturesource == NULL) + return; + + str_replace_char(top, '^', '&'); + str_replace_char(left, '^', '&'); + str_replace_char(right, '^', '&'); + + std::string imgname_full; + imgname_full += "[inventorycube{"; + imgname_full += top; + imgname_full += "{"; + imgname_full += left; + imgname_full += "{"; + imgname_full += right; + inventory_texture = g_texturesource->getTextureRaw(imgname_full); +} + +struct ContentFeatures g_content_features[MAX_CONTENT+1]; + +ContentFeatures & content_features(content_t i) +{ + return g_content_features[i]; +} +ContentFeatures & content_features(MapNode &n) +{ + return content_features(n.getContent()); +} + +/* + See mapnode.h for description. +*/ +void init_mapnode() +{ + if(g_texturesource == NULL) + { + dstream<<"INFO: Initial run of init_mapnode with " + "g_texturesource=NULL. If this segfaults, " + "there is a bug with something not checking for " + "the NULL value."<reset(); + + for(u16 j=0; j<6; j++) + f->tiles[j].material_type = initial_material_type; + } + + /* + Initially set every block to be shown as an unknown block. + Don't touch CONTENT_IGNORE or CONTENT_AIR. + */ + for(u16 i=0; isetAllTextures("unknown_block.png"); + f->dug_item = std::string("MaterialItem2 ")+itos(i)+" 1"; + } + + /* + Initialize mapnode content + */ + content_mapnode_init(); + +} + +v3s16 facedir_rotate(u8 facedir, v3s16 dir) +{ + /* + Face 2 (normally Z-) direction: + facedir=0: Z- + facedir=1: X- + facedir=2: Z+ + facedir=3: X+ + */ + v3s16 newdir; + if(facedir==0) // Same + newdir = v3s16(dir.X, dir.Y, dir.Z); + else if(facedir == 1) // Face is taken from rotXZccv(-90) + newdir = v3s16(-dir.Z, dir.Y, dir.X); + else if(facedir == 2) // Face is taken from rotXZccv(180) + newdir = v3s16(-dir.X, dir.Y, -dir.Z); + else if(facedir == 3) // Face is taken from rotXZccv(90) + newdir = v3s16(dir.Z, dir.Y, -dir.X); + else + newdir = dir; + return newdir; +} + +TileSpec MapNode::getTile(v3s16 dir) +{ + if(content_features(*this).param_type == CPT_FACEDIR_SIMPLE) + dir = facedir_rotate(param1, dir); + + TileSpec spec; + + s32 dir_i = -1; + + if(dir == v3s16(0,0,0)) + dir_i = -1; + else if(dir == v3s16(0,1,0)) + dir_i = 0; + else if(dir == v3s16(0,-1,0)) + dir_i = 1; + else if(dir == v3s16(1,0,0)) + dir_i = 2; + else if(dir == v3s16(-1,0,0)) + dir_i = 3; + else if(dir == v3s16(0,0,1)) + dir_i = 4; + else if(dir == v3s16(0,0,-1)) + dir_i = 5; + + if(dir_i == -1) + // Non-directional + spec = content_features(*this).tiles[0]; + else + spec = content_features(*this).tiles[dir_i]; + + /* + If it contains some mineral, change texture id + */ + if(content_features(*this).param_type == CPT_MINERAL && g_texturesource) + { + u8 mineral = getMineral(); + std::string mineral_texture_name = mineral_block_texture(mineral); + if(mineral_texture_name != "") + { + u32 orig_id = spec.texture.id; + std::string texture_name = g_texturesource->getTextureName(orig_id); + //texture_name += "^blit:"; + texture_name += "^"; + texture_name += mineral_texture_name; + u32 new_id = g_texturesource->getTextureId(texture_name); + spec.texture = g_texturesource->getTexture(new_id); + } + } + + return spec; +} + +u8 MapNode::getMineral() +{ + if(content_features(*this).param_type == CPT_MINERAL) + { + return param1 & 0x0f; + } + + return MINERAL_NONE; +} + +u32 MapNode::serializedLength(u8 version) +{ + if(!ser_ver_supported(version)) + throw VersionMismatchException("ERROR: MapNode format not supported"); + + if(version == 0) + return 1; + else if(version <= 9) + return 2; + else + return 3; +} +void MapNode::serialize(u8 *dest, u8 version) +{ + if(!ser_ver_supported(version)) + throw VersionMismatchException("ERROR: MapNode format not supported"); + + // Translate to wanted version + MapNode n_foreign = mapnode_translate_from_internal(*this, version); + + u8 actual_param0 = n_foreign.param0; + + // Convert special values from new version to old + if(version <= 18) + { + // In these versions, CONTENT_IGNORE and CONTENT_AIR + // are 255 and 254 + if(actual_param0 == CONTENT_IGNORE) + actual_param0 = 255; + else if(actual_param0 == CONTENT_AIR) + actual_param0 = 254; + } + + if(version == 0) + { + dest[0] = actual_param0; + } + else if(version <= 9) + { + dest[0] = actual_param0; + dest[1] = n_foreign.param1; + } + else + { + dest[0] = actual_param0; + dest[1] = n_foreign.param1; + dest[2] = n_foreign.param2; + } +} +void MapNode::deSerialize(u8 *source, u8 version) +{ + if(!ser_ver_supported(version)) + throw VersionMismatchException("ERROR: MapNode format not supported"); + + if(version == 0) + { + param0 = source[0]; + } + else if(version == 1) + { + param0 = source[0]; + // This version doesn't support saved lighting + if(light_propagates() || light_source() > 0) + param1 = 0; + else + param1 = source[1]; + } + else if(version <= 9) + { + param0 = source[0]; + param1 = source[1]; + } + else + { + param0 = source[0]; + param1 = source[1]; + param2 = source[2]; + } + + // Convert special values from old version to new + if(version <= 18) + { + // In these versions, CONTENT_IGNORE and CONTENT_AIR + // are 255 and 254 + if(param0 == 255) + param0 = CONTENT_IGNORE; + else if(param0 == 254) + param0 = CONTENT_AIR; + } + // version 19 is fucked up with sometimes the old values and sometimes not + if(version == 19) + { + if(param0 == 255) + param0 = CONTENT_IGNORE; + else if(param0 == 254) + param0 = CONTENT_AIR; + } + + // Translate to our known version + *this = mapnode_translate_to_internal(*this, version); +} + +/* + Gets lighting value at face of node + + Parameters must consist of air and !air. + Order doesn't matter. + + If either of the nodes doesn't exist, light is 0. + + parameters: + daynight_ratio: 0...1000 + n: getNodeParent(p) + n2: getNodeParent(p + face_dir) + face_dir: axis oriented unit vector from p to p2 + + returns encoded light value. +*/ +u8 getFaceLight(u32 daynight_ratio, MapNode n, MapNode n2, + v3s16 face_dir) +{ + try{ + u8 light; + u8 l1 = n.getLightBlend(daynight_ratio); + u8 l2 = n2.getLightBlend(daynight_ratio); + if(l1 > l2) + light = l1; + else + light = l2; + + // Make some nice difference to different sides + + // This makes light come from a corner + /*if(face_dir.X == 1 || face_dir.Z == 1 || face_dir.Y == -1) + light = diminish_light(diminish_light(light)); + else if(face_dir.X == -1 || face_dir.Z == -1) + light = diminish_light(light);*/ + + // All neighboring faces have different shade (like in minecraft) + if(face_dir.X == 1 || face_dir.X == -1 || face_dir.Y == -1) + light = diminish_light(diminish_light(light)); + else if(face_dir.Z == 1 || face_dir.Z == -1) + light = diminish_light(light); + + return light; + } + catch(InvalidPositionException &e) + { + return 0; + } +} + + diff --git a/src/mapnode.h b/src/mapnode.h new file mode 100644 index 0000000..3ad67aa --- /dev/null +++ b/src/mapnode.h @@ -0,0 +1,672 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MAPNODE_HEADER +#define MAPNODE_HEADER + +#include +#include "common_irrlicht.h" +#include "light.h" +#include "utility.h" +#include "exceptions.h" +#include "serialization.h" +#include "tile.h" +#include "materials.h" + +/* + Naming scheme: + - Material = irrlicht's Material class + - Content = (content_t) content of a node + - Tile = TileSpec at some side of a node of some content type + + Content ranges: + 0x000...0x07f: param2 is fully usable + 0x800...0xfff: param2 lower 4 bytes are free +*/ +typedef u16 content_t; +#define MAX_CONTENT 0xfff + +/* + Initializes all kind of stuff in here. + Many things depend on this. + + This accesses g_texturesource; if it is non-NULL, textures are set. + + Client first calls this with g_texturesource=NULL to run some + unit tests and stuff, then it runs this again with g_texturesource + defined to get the textures. + + Server only calls this once with g_texturesource=NULL. +*/ +void init_mapnode(); + +/* + Ignored node. + + Anything that stores MapNodes doesn't have to preserve parameters + associated with this material. + + Doesn't create faces with anything and is considered being + out-of-map in the game map. +*/ +//#define CONTENT_IGNORE 255 +#define CONTENT_IGNORE 127 +#define CONTENT_IGNORE_DEFAULT_PARAM 0 + +/* + The common material through which the player can walk and which + is transparent to light +*/ +//#define CONTENT_AIR 254 +#define CONTENT_AIR 126 + +/* + Content feature list +*/ + +enum ContentParamType +{ + CPT_NONE, + CPT_LIGHT, + CPT_MINERAL, + // Direction for chests and furnaces and such + CPT_FACEDIR_SIMPLE +}; + +enum LiquidType +{ + LIQUID_NONE, + LIQUID_FLOWING, + LIQUID_SOURCE +}; + +struct MapNode; +class NodeMetadata; + +struct ContentFeatures +{ + // Type of MapNode::param1 + ContentParamType param_type; + + /* + 0: up + 1: down + 2: right + 3: left + 4: back + 5: front + */ + TileSpec tiles[6]; + + video::ITexture *inventory_texture; + + // True for all ground-like things like stone and mud, false for eg. trees + bool is_ground_content; + bool light_propagates; + bool sunlight_propagates; + u8 solidness; // Used when choosing which face is drawn + u8 visual_solidness; // When solidness=0, this tells how it looks like + // This is used for collision detection. + // Also for general solidness queries. + bool walkable; + // Player can point to these + bool pointable; + // Player can dig these + bool diggable; + // Player can climb these + bool climbable; + // Player can build on these + bool buildable_to; + // Whether the node has no liquid, source liquid or flowing liquid + enum LiquidType liquid_type; + // If true, param2 is set to direction when placed. Used for torches. + // NOTE: the direction format is quite inefficient and should be changed + bool wall_mounted; + // If true, node is equivalent to air. Torches are, air is. Water is not. + // Is used for example to check whether a mud block can have grass on. + bool air_equivalent; + + // Inventory item string as which the node appears in inventory when dug. + // Mineral overrides this. + std::string dug_item; + + // Initial metadata is cloned from this + NodeMetadata *initial_metadata; + + // If the content is liquid, this is the flowing version of the liquid. + // If content is liquid, this is the same content. + content_t liquid_alternative_flowing; + // If the content is liquid, this is the source version of the liquid. + content_t liquid_alternative_source; + // Viscosity for fluid flow, ranging from 1 to 7, with + // 1 giving almost instantaneous propagation and 7 being + // the slowest possible + u8 liquid_viscosity; + // Used currently for flowing liquids + u8 vertex_alpha; + // Special irrlicht material, used sometimes + video::SMaterial *special_material; + AtlasPointer *special_atlas; + + // Amount of light the node emits + u8 light_source; + + // Digging properties for different tools + DiggingPropertiesList digging_properties; + + u32 damage_per_second; + + // NOTE: Move relevant properties to here from elsewhere + + void reset() + { + param_type = CPT_NONE; + inventory_texture = NULL; + is_ground_content = false; + light_propagates = false; + sunlight_propagates = false; + solidness = 2; + visual_solidness = 0; + walkable = true; + pointable = true; + diggable = true; + climbable = false; + buildable_to = false; + liquid_type = LIQUID_NONE; + wall_mounted = false; + air_equivalent = false; + dug_item = ""; + initial_metadata = NULL; + liquid_alternative_flowing = CONTENT_IGNORE; + liquid_alternative_source = CONTENT_IGNORE; + liquid_viscosity = 0; + vertex_alpha = 255; + special_material = NULL; + special_atlas = NULL; + light_source = 0; + digging_properties.clear(); + damage_per_second = 0; + } + + ContentFeatures() + { + reset(); + } + + ~ContentFeatures(); + + /* + Quickhands for simple materials + */ + + void setTexture(u16 i, std::string name, u8 alpha=255); + + void setAllTextures(std::string name, u8 alpha=255) + { + for(u16 i=0; i<6; i++) + { + setTexture(i, name, alpha); + } + // Force inventory texture too + setInventoryTexture(name); + } + + void setTile(u16 i, const TileSpec &tile) + { + tiles[i] = tile; + } + void setAllTiles(const TileSpec &tile) + { + for(u16 i=0; i<6; i++) + { + setTile(i, tile); + } + } + + void setInventoryTexture(std::string imgname); + + void setInventoryTextureCube(std::string top, + std::string left, std::string right); +}; + +/* + Call this to access the ContentFeature list +*/ +ContentFeatures & content_features(content_t i); +ContentFeatures & content_features(MapNode &n); + +/* + Here is a bunch of DEPRECATED functions. +*/ + +/* + If true, the material allows light propagation and brightness is stored + in param. + NOTE: Don't use, use "content_features(m).whatever" instead +*/ +inline bool light_propagates_content(content_t m) +{ + return content_features(m).light_propagates; +} +/* + If true, the material allows lossless sunlight propagation. + NOTE: It doesn't seem to go through torches regardlessly of this + NOTE: Don't use, use "content_features(m).whatever" instead +*/ +inline bool sunlight_propagates_content(content_t m) +{ + return content_features(m).sunlight_propagates; +} +/* + On a node-node surface, the material of the node with higher solidness + is used for drawing. + 0: Invisible + 1: Transparent + 2: Opaque + NOTE: Don't use, use "content_features(m).whatever" instead +*/ +inline u8 content_solidness(content_t m) +{ + return content_features(m).solidness; +} +// Objects collide with walkable contents +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_walkable(content_t m) +{ + return content_features(m).walkable; +} +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_liquid(content_t m) +{ + return content_features(m).liquid_type != LIQUID_NONE; +} +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_flowing_liquid(content_t m) +{ + return content_features(m).liquid_type == LIQUID_FLOWING; +} +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_liquid_source(content_t m) +{ + return content_features(m).liquid_type == LIQUID_SOURCE; +} +// CONTENT_WATER || CONTENT_WATERSOURCE -> CONTENT_WATER +// CONTENT_LAVA || CONTENT_LAVASOURCE -> CONTENT_LAVA +// NOTE: Don't use, use "content_features(m).whatever" instead +inline content_t make_liquid_flowing(content_t m) +{ + u8 c = content_features(m).liquid_alternative_flowing; + assert(c != CONTENT_IGNORE); + return c; +} +// Pointable contents can be pointed to in the map +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_pointable(content_t m) +{ + return content_features(m).pointable; +} +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_diggable(content_t m) +{ + return content_features(m).diggable; +} +// NOTE: Don't use, use "content_features(m).whatever" instead +inline bool content_buildable_to(content_t m) +{ + return content_features(m).buildable_to; +} + +/* + Nodes make a face if contents differ and solidness differs. + Return value: + 0: No face + 1: Face uses m1's content + 2: Face uses m2's content +*/ +inline u8 face_contents(content_t m1, content_t m2) +{ + if(m1 == CONTENT_IGNORE || m2 == CONTENT_IGNORE) + return 0; + + bool contents_differ = (m1 != m2); + + // Contents don't differ for different forms of same liquid + if(content_liquid(m1) && content_liquid(m2) + && make_liquid_flowing(m1) == make_liquid_flowing(m2)) + contents_differ = false; + + bool solidness_differs = (content_solidness(m1) != content_solidness(m2)); + bool makes_face = contents_differ && solidness_differs; + + if(makes_face == false) + return 0; + + if(content_solidness(m1) > content_solidness(m2)) + return 1; + else + return 2; +} + +/* + Packs directions like (1,0,0), (1,-1,0) +*/ +inline u8 packDir(v3s16 dir) +{ + u8 b = 0; + + if(dir.X > 0) + b |= (1<<0); + else if(dir.X < 0) + b |= (1<<1); + + if(dir.Y > 0) + b |= (1<<2); + else if(dir.Y < 0) + b |= (1<<3); + + if(dir.Z > 0) + b |= (1<<4); + else if(dir.Z < 0) + b |= (1<<5); + + return b; +} +inline v3s16 unpackDir(u8 b) +{ + v3s16 d(0,0,0); + + if(b & (1<<0)) + d.X = 1; + else if(b & (1<<1)) + d.X = -1; + + if(b & (1<<2)) + d.Y = 1; + else if(b & (1<<3)) + d.Y = -1; + + if(b & (1<<4)) + d.Z = 1; + else if(b & (1<<5)) + d.Z = -1; + + return d; +} + +/* + facedir: CPT_FACEDIR_SIMPLE param1 value + dir: The face for which stuff is wanted + return value: The face from which the stuff is actually found + + NOTE: Currently this uses 2 bits for Z-,X-,Z+,X+, should there be Y+ + and Y- too? +*/ +v3s16 facedir_rotate(u8 facedir, v3s16 dir); + +enum LightBank +{ + LIGHTBANK_DAY, + LIGHTBANK_NIGHT +}; + +/* + Masks for MapNode.param2 of flowing liquids + */ +#define LIQUID_LEVEL_MASK 0x07 +#define LIQUID_FLOW_DOWN_MASK 0x08 + +/* maximum amount of liquid in a block */ +#define LIQUID_LEVEL_MAX LIQUID_LEVEL_MASK +#define LIQUID_LEVEL_SOURCE (LIQUID_LEVEL_MAX+1) + +/* + This is the stuff what the whole world consists of. +*/ + + +struct MapNode +{ + /* + Main content + 0x00-0x7f: Short content type + 0x80-0xff: Long content type (param2>>4 makes up low bytes) + */ + union + { + u8 param0; + //u8 d; + }; + + /* + Misc parameter. Initialized to 0. + - For light_propagates() blocks, this is light intensity, + stored logarithmically from 0 to LIGHT_MAX. + Sunlight is LIGHT_SUN, which is LIGHT_MAX+1. + - Contains 2 values, day- and night lighting. Each takes 4 bits. + - Mineral content (should be removed from here) + - Uhh... well, most blocks have light or nothing in here. + */ + union + { + u8 param1; + //s8 param; + }; + + /* + The second parameter. Initialized to 0. + E.g. direction for torches and flowing water. + If param0 >= 0x80, bits 0xf0 of this is extended content type data + */ + union + { + u8 param2; + //u8 dir; + }; + + MapNode(const MapNode & n) + { + *this = n; + } + + MapNode(content_t content=CONTENT_AIR, u8 a_param1=0, u8 a_param2=0) + { + //param0 = a_param0; + param1 = a_param1; + param2 = a_param2; + // Set after other params because this needs to override part of param2 + setContent(content); + } + + bool operator==(const MapNode &other) + { + return (param0 == other.param0 + && param1 == other.param1 + && param2 == other.param2); + } + + // To be used everywhere + content_t getContent() + { + if(param0 < 0x80) + return param0; + else + return (param0<<4) + (param2>>4); + } + void setContent(content_t c) + { + if(c < 0x80) + { + if(param0 >= 0x80) + param2 &= ~(0xf0); + param0 = c; + } + else + { + param0 = c>>4; + param2 &= ~(0xf0); + param2 |= (c&0x0f)<<4; + } + } + + /* + These four are DEPRECATED I guess. -c55 + */ + bool light_propagates() + { + return light_propagates_content(getContent()); + } + bool sunlight_propagates() + { + return sunlight_propagates_content(getContent()); + } + u8 solidness() + { + return content_solidness(getContent()); + } + u8 light_source() + { + return content_features(*this).light_source; + } + + u8 getLightBanksWithSource() + { + // Select the brightest of [light source, propagated light] + u8 lightday = 0; + u8 lightnight = 0; + if(content_features(*this).param_type == CPT_LIGHT) + { + lightday = param1 & 0x0f; + lightnight = (param1>>4)&0x0f; + } + if(light_source() > lightday) + lightday = light_source(); + if(light_source() > lightnight) + lightnight = light_source(); + return (lightday&0x0f) | ((lightnight<<4)&0xf0); + } + + u8 getLight(enum LightBank bank) + { + // Select the brightest of [light source, propagated light] + u8 light = 0; + if(content_features(*this).param_type == CPT_LIGHT) + { + if(bank == LIGHTBANK_DAY) + light = param1 & 0x0f; + else if(bank == LIGHTBANK_NIGHT) + light = (param1>>4)&0x0f; + else + assert(0); + } + if(light_source() > light) + light = light_source(); + return light; + } + + // 0 <= daylight_factor <= 1000 + // 0 <= return value <= LIGHT_SUN + u8 getLightBlend(u32 daylight_factor) + { + u8 l = ((daylight_factor * getLight(LIGHTBANK_DAY) + + (1000-daylight_factor) * getLight(LIGHTBANK_NIGHT)) + )/1000; + u8 max = LIGHT_MAX; + if(getLight(LIGHTBANK_DAY) == LIGHT_SUN) + max = LIGHT_SUN; + if(l > max) + l = max; + return l; + } + /*// 0 <= daylight_factor <= 1000 + // 0 <= return value <= 255 + u8 getLightBlend(u32 daylight_factor) + { + u8 daylight = decode_light(getLight(LIGHTBANK_DAY)); + u8 nightlight = decode_light(getLight(LIGHTBANK_NIGHT)); + u8 mix = ((daylight_factor * daylight + + (1000-daylight_factor) * nightlight) + )/1000; + return mix; + }*/ + + void setLight(enum LightBank bank, u8 a_light) + { + // If node doesn't contain light data, ignore this + if(content_features(*this).param_type != CPT_LIGHT) + return; + if(bank == LIGHTBANK_DAY) + { + param1 &= 0xf0; + param1 |= a_light & 0x0f; + } + else if(bank == LIGHTBANK_NIGHT) + { + param1 &= 0x0f; + param1 |= (a_light & 0x0f)<<4; + } + else + assert(0); + } + + // In mapnode.cpp + /* + Get tile of a face of the node. + dir: direction of face + Returns: TileSpec. Can contain miscellaneous texture coordinates, + which must be obeyed so that the texture atlas can be used. + */ + TileSpec getTile(v3s16 dir); + + /* + Gets mineral content of node, if there is any. + MINERAL_NONE if doesn't contain or isn't able to contain mineral. + */ + u8 getMineral(); + + /* + Serialization functions + */ + + static u32 serializedLength(u8 version); + void serialize(u8 *dest, u8 version); + void deSerialize(u8 *source, u8 version); + +}; + +/* + Gets lighting value at face of node + + Parameters must consist of air and !air. + Order doesn't matter. + + If either of the nodes doesn't exist, light is 0. + + parameters: + daynight_ratio: 0...1000 + n: getNodeParent(p) + n2: getNodeParent(p + face_dir) + face_dir: axis oriented unit vector from p to p2 + + returns encoded light value. +*/ +u8 getFaceLight(u32 daynight_ratio, MapNode n, MapNode n2, + v3s16 face_dir); + +#endif + diff --git a/src/mapsector.cpp b/src/mapsector.cpp new file mode 100644 index 0000000..4a526c4 --- /dev/null +++ b/src/mapsector.cpp @@ -0,0 +1,261 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "mapsector.h" +#include "jmutexautolock.h" +#include "client.h" +#include "exceptions.h" +#include "mapblock.h" + +MapSector::MapSector(Map *parent, v2s16 pos): + differs_from_disk(false), + m_parent(parent), + m_pos(pos), + m_block_cache(NULL) +{ +} + +MapSector::~MapSector() +{ + deleteBlocks(); +} + +void MapSector::deleteBlocks() +{ + // Clear cache + m_block_cache = NULL; + + // Delete all + core::map::Iterator i = m_blocks.getIterator(); + for(; i.atEnd() == false; i++) + { + delete i.getNode()->getValue(); + } + + // Clear container + m_blocks.clear(); +} + +MapBlock * MapSector::getBlockBuffered(s16 y) +{ + MapBlock *block; + + if(m_block_cache != NULL && y == m_block_cache_y){ + return m_block_cache; + } + + // If block doesn't exist, return NULL + core::map::Node *n = m_blocks.find(y); + if(n == NULL) + { + block = NULL; + } + // If block exists, return it + else{ + block = n->getValue(); + } + + // Cache the last result + m_block_cache_y = y; + m_block_cache = block; + + return block; +} + +MapBlock * MapSector::getBlockNoCreateNoEx(s16 y) +{ + return getBlockBuffered(y); +} + +MapBlock * MapSector::createBlankBlockNoInsert(s16 y) +{ + assert(getBlockBuffered(y) == NULL); + + v3s16 blockpos_map(m_pos.X, y, m_pos.Y); + + MapBlock *block = new MapBlock(m_parent, blockpos_map); + + return block; +} + +MapBlock * MapSector::createBlankBlock(s16 y) +{ + MapBlock *block = createBlankBlockNoInsert(y); + + m_blocks.insert(y, block); + + return block; +} + +void MapSector::insertBlock(MapBlock *block) +{ + s16 block_y = block->getPos().Y; + + MapBlock *block2 = getBlockBuffered(block_y); + if(block2 != NULL){ + throw AlreadyExistsException("Block already exists"); + } + + v2s16 p2d(block->getPos().X, block->getPos().Z); + assert(p2d == m_pos); + + // Insert into container + m_blocks.insert(block_y, block); +} + +void MapSector::deleteBlock(MapBlock *block) +{ + s16 block_y = block->getPos().Y; + + // Clear from cache + m_block_cache = NULL; + + // Remove from container + m_blocks.remove(block_y); + + // Delete + delete block; +} + +void MapSector::getBlocks(core::list &dest) +{ + core::list ref_list; + + core::map::Iterator bi; + + bi = m_blocks.getIterator(); + for(; bi.atEnd() == false; bi++) + { + MapBlock *b = bi.getNode()->getValue(); + dest.push_back(b); + } +} + +/* + ServerMapSector +*/ + +ServerMapSector::ServerMapSector(Map *parent, v2s16 pos): + MapSector(parent, pos) +{ +} + +ServerMapSector::~ServerMapSector() +{ +} + +void ServerMapSector::serialize(std::ostream &os, u8 version) +{ + if(!ser_ver_supported(version)) + throw VersionMismatchException("ERROR: MapSector format not supported"); + + /* + [0] u8 serialization version + + heightmap data + */ + + // Server has both of these, no need to support not having them. + //assert(m_objects != NULL); + + // Write version + os.write((char*)&version, 1); + + /* + Add stuff here, if needed + */ + +} + +ServerMapSector* ServerMapSector::deSerialize( + std::istream &is, + Map *parent, + v2s16 p2d, + core::map & sectors + ) +{ + /* + [0] u8 serialization version + + heightmap data + */ + + /* + Read stuff + */ + + // Read version + u8 version = SER_FMT_VER_INVALID; + is.read((char*)&version, 1); + + if(!ser_ver_supported(version)) + throw VersionMismatchException("ERROR: MapSector format not supported"); + + /* + Add necessary reading stuff here + */ + + /* + Get or create sector + */ + + ServerMapSector *sector = NULL; + + core::map::Node *n = sectors.find(p2d); + + if(n != NULL) + { + dstream<<"WARNING: deSerializing existent sectors not supported " + "at the moment, because code hasn't been tested." + <getValue(); + assert(sector->getId() == MAPSECTOR_SERVER); + return (ServerMapSector*)sector; + } + else + { + sector = new ServerMapSector(parent, p2d); + sectors.insert(p2d, sector); + } + + /* + Set stuff in sector + */ + + // Nothing here + + return sector; +} + +#ifndef SERVER +/* + ClientMapSector +*/ + +ClientMapSector::ClientMapSector(Map *parent, v2s16 pos): + MapSector(parent, pos) +{ +} + +ClientMapSector::~ClientMapSector() +{ +} + +#endif // !SERVER + +//END diff --git a/src/mapsector.h b/src/mapsector.h new file mode 100644 index 0000000..44f45d8 --- /dev/null +++ b/src/mapsector.h @@ -0,0 +1,137 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* +(c) 2010 Perttu Ahola +*/ + +#ifndef MAPSECTOR_HEADER +#define MAPSECTOR_HEADER + +#include +#include "common_irrlicht.h" +#include "exceptions.h" +#include + +class MapBlock; +class Map; + +/* + This is an Y-wise stack of MapBlocks. +*/ + +#define MAPSECTOR_SERVER 0 +#define MAPSECTOR_CLIENT 1 + +class MapSector +{ +public: + + MapSector(Map *parent, v2s16 pos); + virtual ~MapSector(); + + virtual u32 getId() const = 0; + + void deleteBlocks(); + + v2s16 getPos() + { + return m_pos; + } + + MapBlock * getBlockNoCreateNoEx(s16 y); + MapBlock * createBlankBlockNoInsert(s16 y); + MapBlock * createBlankBlock(s16 y); + + void insertBlock(MapBlock *block); + + void deleteBlock(MapBlock *block); + + void getBlocks(core::list &dest); + + // Always false at the moment, because sector contains no metadata. + bool differs_from_disk; + +protected: + + // The pile of MapBlocks + core::map m_blocks; + + Map *m_parent; + // Position on parent (in MapBlock widths) + v2s16 m_pos; + + // Last-used block is cached here for quicker access. + // Be sure to set this to NULL when the cached block is deleted + MapBlock *m_block_cache; + s16 m_block_cache_y; + + /* + Private methods + */ + MapBlock *getBlockBuffered(s16 y); + +}; + +class ServerMapSector : public MapSector +{ +public: + ServerMapSector(Map *parent, v2s16 pos); + ~ServerMapSector(); + + u32 getId() const + { + return MAPSECTOR_SERVER; + } + + /* + These functions handle metadata. + They do not handle blocks. + */ + + void serialize(std::ostream &os, u8 version); + + static ServerMapSector* deSerialize( + std::istream &is, + Map *parent, + v2s16 p2d, + core::map & sectors + ); + +private: +}; + +#ifndef SERVER +class ClientMapSector : public MapSector +{ +public: + ClientMapSector(Map *parent, v2s16 pos); + ~ClientMapSector(); + + u32 getId() const + { + return MAPSECTOR_CLIENT; + } + +private: +}; +#endif + +#endif + diff --git a/src/materials.cpp b/src/materials.cpp new file mode 100644 index 0000000..24f3007 --- /dev/null +++ b/src/materials.cpp @@ -0,0 +1,20 @@ +#include "materials.h" +#include "mapnode.h" + +// NOTE: DEPRECATED + +DiggingPropertiesList * getDiggingPropertiesList(u16 content) +{ + return &content_features(content).digging_properties; +} + +DiggingProperties getDiggingProperties(u16 content, const std::string &tool) +{ + DiggingPropertiesList *mprop = getDiggingPropertiesList(content); + if(mprop == NULL) + // Not diggable + return DiggingProperties(); + + return mprop->get(tool); +} + diff --git a/src/materials.h b/src/materials.h new file mode 100644 index 0000000..1439df1 --- /dev/null +++ b/src/materials.h @@ -0,0 +1,103 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MATERIALS_HEADER +#define MATERIALS_HEADER + +/* + Material properties +*/ + +#include "common_irrlicht.h" +#include + +struct DiggingProperties +{ + DiggingProperties(): + diggable(false), + time(0.0), + wear(0) + { + } + DiggingProperties(bool a_diggable, float a_time, u16 a_wear): + diggable(a_diggable), + time(a_time), + wear(a_wear) + { + } + bool diggable; + // Digging time in seconds + float time; + // Caused wear + u16 wear; +}; + +/* + This is a bad way of determining mining characteristics. + TODO: Get rid of this and set up some attributes like toughness, + fluffyness, and a funciton to calculate time and durability loss + (and sound? and whatever else) from them +*/ +class DiggingPropertiesList +{ +public: + DiggingPropertiesList() + { + } + + void set(const std::string toolname, + const DiggingProperties &prop) + { + m_digging_properties[toolname] = prop; + } + + DiggingProperties get(const std::string toolname) + { + core::map::Node *n; + n = m_digging_properties.find(toolname); + if(n == NULL) + { + // Not diggable by this tool, try to get defaults + n = m_digging_properties.find(""); + if(n == NULL) + { + // Not diggable at all + return DiggingProperties(); + } + } + // Return found properties + return n->getValue(); + } + + void clear() + { + m_digging_properties.clear(); + } + +private: + // toolname="": default properties (digging by hand) + // Key is toolname + core::map m_digging_properties; +}; + +// For getting the default properties, set tool="" +DiggingProperties getDiggingProperties(u16 material, const std::string &tool); + +#endif + diff --git a/src/mineral.cpp b/src/mineral.cpp new file mode 100644 index 0000000..038251f --- /dev/null +++ b/src/mineral.cpp @@ -0,0 +1,51 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "mineral.h" + + +const char *mineral_filenames[MINERAL_COUNT] = +{ + NULL, + "mineral_coal.png", + "mineral_iron.png" +}; + +std::string mineral_textures[MINERAL_COUNT]; + +void init_mineral() +{ + for(u32 i=0; i= MINERAL_COUNT) + return ""; + + return mineral_textures[mineral]; +} + + + diff --git a/src/mineral.h b/src/mineral.h new file mode 100644 index 0000000..61776e6 --- /dev/null +++ b/src/mineral.h @@ -0,0 +1,54 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MINERAL_HEADER +#define MINERAL_HEADER + +#include "inventory.h" + +/* + Minerals + + Value is stored in the lowest 5 bits of a MapNode's CPT_MINERAL + type param. +*/ + +// Caches textures +void init_mineral(); + +#define MINERAL_NONE 0 +#define MINERAL_COAL 1 +#define MINERAL_IRON 2 + +#define MINERAL_COUNT 3 + +std::string mineral_block_texture(u8 mineral); + +inline CraftItem * getDiggedMineralItem(u8 mineral) +{ + if(mineral == MINERAL_COAL) + return new CraftItem("lump_of_coal", 1); + else if(mineral == MINERAL_IRON) + return new CraftItem("lump_of_iron", 1); + + return NULL; +} + +#endif + diff --git a/src/modalMenu.h b/src/modalMenu.h new file mode 100644 index 0000000..1f6d4d8 --- /dev/null +++ b/src/modalMenu.h @@ -0,0 +1,138 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef MODALMENU_HEADER +#define MODALMENU_HEADER + +#include "common_irrlicht.h" + +class GUIModalMenu; + +class IMenuManager +{ +public: + // A GUIModalMenu calls these when this class is passed as a parameter + virtual void createdMenu(GUIModalMenu *menu) = 0; + virtual void deletingMenu(GUIModalMenu *menu) = 0; +}; + +/* + Remember to drop() the menu after creating, so that it can + remove itself when it wants to. +*/ + +class GUIModalMenu : public gui::IGUIElement +{ +public: + GUIModalMenu(gui::IGUIEnvironment* env, + gui::IGUIElement* parent, s32 id, + IMenuManager *menumgr): + IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, + core::rect(0,0,100,100)) + { + //m_force_regenerate_gui = false; + + m_menumgr = menumgr; + m_allow_focus_removal = false; + m_screensize_old = v2u32(0,0); + + setVisible(true); + Environment->setFocus(this); + m_menumgr->createdMenu(this); + } + virtual ~GUIModalMenu() + { + m_menumgr->deletingMenu(this); + } + + void allowFocusRemoval(bool allow) + { + m_allow_focus_removal = allow; + } + + bool canTakeFocus(gui::IGUIElement *e) + { + return (e && (e == this || isMyChild(e))) || m_allow_focus_removal; + } + + void draw() + { + if(!IsVisible) + return; + + video::IVideoDriver* driver = Environment->getVideoDriver(); + v2u32 screensize = driver->getScreenSize(); + if(screensize != m_screensize_old /*|| m_force_regenerate_gui*/) + { + m_screensize_old = screensize; + regenerateGui(screensize); + //m_force_regenerate_gui = false; + } + + drawMenu(); + } + + /* + This should be called when the menu wants to quit. + + WARNING: THIS DEALLOCATES THE MENU FROM MEMORY. Return + immediately if you call this from the menu itself. + */ + void quitMenu() + { + allowFocusRemoval(true); + // This removes Environment's grab on us + Environment->removeFocus(this); + this->remove(); + } + + void removeChildren() + { + const core::list &children = getChildren(); + core::list children_copy; + for(core::list::ConstIterator + i = children.begin(); i != children.end(); i++) + { + children_copy.push_back(*i); + } + for(core::list::Iterator + i = children_copy.begin(); + i != children_copy.end(); i++) + { + (*i)->remove(); + } + } + + virtual void regenerateGui(v2u32 screensize) = 0; + virtual void drawMenu() = 0; + virtual bool OnEvent(const SEvent& event) { return false; }; + +protected: + //bool m_force_regenerate_gui; +private: + IMenuManager *m_menumgr; + // This might be necessary to expose to the implementation if it + // wants to launch other menus + bool m_allow_focus_removal; + v2u32 m_screensize_old; +}; + + +#endif + diff --git a/src/nodemetadata.cpp b/src/nodemetadata.cpp new file mode 100644 index 0000000..3edf6d3 --- /dev/null +++ b/src/nodemetadata.cpp @@ -0,0 +1,230 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "nodemetadata.h" +#include "utility.h" +#include "mapnode.h" +#include "exceptions.h" +#include "inventory.h" +#include +#include "content_mapnode.h" + +/* + NodeMetadata +*/ + +core::map NodeMetadata::m_types; + +NodeMetadata::NodeMetadata() +{ +} + +NodeMetadata::~NodeMetadata() +{ +} + +NodeMetadata* NodeMetadata::deSerialize(std::istream &is) +{ + // Read id + u8 buf[2]; + is.read((char*)buf, 2); + s16 id = readS16(buf); + + // Read data + std::string data = deSerializeString(is); + + // Find factory function + core::map::Node *n; + n = m_types.find(id); + if(n == NULL) + { + // If factory is not found, just return. + dstream<<"WARNING: NodeMetadata: No factory for typeId=" + <getValue(); + NodeMetadata *meta = (*f)(iss); + return meta; + } + catch(SerializationError &e) + { + dstream<<"WARNING: NodeMetadata: ignoring SerializationError"<::Node *n; + n = m_types.find(id); + if(n) + return; + m_types.insert(id, f); +} + +/* + NodeMetadataList +*/ + +void NodeMetadataList::serialize(std::ostream &os) +{ + u8 buf[6]; + + u16 version = 1; + writeU16(buf, version); + os.write((char*)buf, 2); + + u16 count = m_data.size(); + writeU16(buf, count); + os.write((char*)buf, 2); + + for(core::map::Iterator + i = m_data.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + NodeMetadata *data = i.getNode()->getValue(); + + u16 p16 = p.Z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + p.Y*MAP_BLOCKSIZE + p.X; + writeU16(buf, p16); + os.write((char*)buf, 2); + + data->serialize(os); + } + +} +void NodeMetadataList::deSerialize(std::istream &is) +{ + m_data.clear(); + + u8 buf[6]; + + is.read((char*)buf, 2); + u16 version = readU16(buf); + + if(version > 1) + { + dstream<<__FUNCTION_NAME<<": version "<::Iterator + i = m_data.getIterator(); + i.atEnd()==false; i++) + { + delete i.getNode()->getValue(); + } +} + +NodeMetadata* NodeMetadataList::get(v3s16 p) +{ + core::map::Node *n; + n = m_data.find(p); + if(n == NULL) + return NULL; + return n->getValue(); +} + +void NodeMetadataList::remove(v3s16 p) +{ + NodeMetadata *olddata = get(p); + if(olddata) + { + delete olddata; + m_data.remove(p); + } +} + +void NodeMetadataList::set(v3s16 p, NodeMetadata *d) +{ + remove(p); + m_data.insert(p, d); +} + +bool NodeMetadataList::step(float dtime) +{ + bool something_changed = false; + for(core::map::Iterator + i = m_data.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + NodeMetadata *meta = i.getNode()->getValue(); + bool changed = meta->step(dtime); + if(changed) + something_changed = true; + } + return something_changed; +} + diff --git a/src/nodemetadata.h b/src/nodemetadata.h new file mode 100644 index 0000000..de682f9 --- /dev/null +++ b/src/nodemetadata.h @@ -0,0 +1,102 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef NODEMETADATA_HEADER +#define NODEMETADATA_HEADER + +#include "common_irrlicht.h" +#include +#include + +/* + Used for storing: + + Oven: + - Item that is being burned + - Burning time + - Item stack that is being heated + - Result item stack + + Sign: + - Text +*/ + +class Inventory; + +class NodeMetadata +{ +public: + typedef NodeMetadata* (*Factory)(std::istream&); + + NodeMetadata(); + virtual ~NodeMetadata(); + + static NodeMetadata* deSerialize(std::istream &is); + void serialize(std::ostream &os); + + // This usually is the CONTENT_ value + virtual u16 typeId() const = 0; + virtual NodeMetadata* clone() = 0; + virtual void serializeBody(std::ostream &os) = 0; + virtual std::string infoText() {return "";} + virtual Inventory* getInventory() {return NULL;} + // This is called always after the inventory is modified, before + // the changes are copied elsewhere + virtual void inventoryModified(){} + // A step in time. Returns true if metadata changed. + virtual bool step(float dtime) {return false;} + virtual bool nodeRemovalDisabled(){return false;} + // Used to make custom inventory menus. + // See format in guiInventoryMenu.cpp. + virtual std::string getInventoryDrawSpecString(){return "";} + +protected: + static void registerType(u16 id, Factory f); +private: + static core::map m_types; +}; + +/* + List of metadata of all the nodes of a block +*/ + +class NodeMetadataList +{ +public: + ~NodeMetadataList(); + + void serialize(std::ostream &os); + void deSerialize(std::istream &is); + + // Get pointer to data + NodeMetadata* get(v3s16 p); + // Deletes data + void remove(v3s16 p); + // Deletes old data and sets a new one + void set(v3s16 p, NodeMetadata *d); + + // A step in time. Returns true if something changed. + bool step(float dtime); + +private: + core::map m_data; +}; + +#endif + diff --git a/src/noise.cpp b/src/noise.cpp new file mode 100644 index 0000000..9c2141c --- /dev/null +++ b/src/noise.cpp @@ -0,0 +1,425 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include +#include "noise.h" +#include +#include "debug.h" + +#define NOISE_MAGIC_X 1619 +#define NOISE_MAGIC_Y 31337 +#define NOISE_MAGIC_Z 52591 +#define NOISE_MAGIC_SEED 1013 + +double cos_lookup[16] = { + 1.0,0.9238,0.7071,0.3826,0,-0.3826,-0.7071,-0.9238, + 1.0,-0.9238,-0.7071,-0.3826,0,0.3826,0.7071,0.9238 +}; + +double dotProduct(double vx, double vy, double wx, double wy){ + return vx*wx+vy*wy; +} + +double easeCurve(double t){ + return 6*pow(t,5)-15*pow(t,4)+10*pow(t,3); +} + +double linearInterpolation(double x0, double x1, double t){ + return x0+(x1-x0)*t; +} + +double biLinearInterpolation(double x0y0, double x1y0, double x0y1, double x1y1, double x, double y){ + double tx = easeCurve(x); + double ty = easeCurve(y); + /*double tx = x; + double ty = y;*/ + double u = linearInterpolation(x0y0,x1y0,tx); + double v = linearInterpolation(x0y1,x1y1,tx); + return linearInterpolation(u,v,ty); +} + +double triLinearInterpolation( + double v000, double v100, double v010, double v110, + double v001, double v101, double v011, double v111, + double x, double y, double z) +{ + /*double tx = easeCurve(x); + double ty = easeCurve(y); + double tz = easeCurve(z);*/ + double tx = x; + double ty = y; + double tz = z; + return( + v000*(1-tx)*(1-ty)*(1-tz) + + v100*tx*(1-ty)*(1-tz) + + v010*(1-tx)*ty*(1-tz) + + v110*tx*ty*(1-tz) + + v001*(1-tx)*(1-ty)*tz + + v101*tx*(1-ty)*tz + + v011*(1-tx)*ty*tz + + v111*tx*ty*tz + ); +} + +double noise2d(int x, int y, int seed) +{ + int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + + NOISE_MAGIC_SEED * seed) & 0x7fffffff; + n = (n>>13)^n; + n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff; + return 1.0 - (double)n/1073741824; +} + +double noise3d(int x, int y, int z, int seed) +{ + int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z + + NOISE_MAGIC_SEED * seed) & 0x7fffffff; + n = (n>>13)^n; + n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff; + return 1.0 - (double)n/1073741824; +} + +#if 0 +double noise2d_gradient(double x, double y, int seed) +{ + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + // Calculate random cosine lookup table indices for the integer corners. + // They are looked up as unit vector gradients from the lookup table. + int n00 = (int)((noise2d(x0, y0, seed)+1)*8); + int n10 = (int)((noise2d(x0+1, y0, seed)+1)*8); + int n01 = (int)((noise2d(x0, y0+1, seed)+1)*8); + int n11 = (int)((noise2d(x0+1, y0+1, seed)+1)*8); + // Make a dot product for the gradients and the positions, to get the values + double s = dotProduct(cos_lookup[n00], cos_lookup[(n00+12)%16], xl, yl); + double u = dotProduct(-cos_lookup[n10], cos_lookup[(n10+12)%16], 1.-xl, yl); + double v = dotProduct(cos_lookup[n01], -cos_lookup[(n01+12)%16], xl, 1.-yl); + double w = dotProduct(-cos_lookup[n11], -cos_lookup[(n11+12)%16], 1.-xl, 1.-yl); + // Interpolate between the values + return biLinearInterpolation(s,u,v,w,xl,yl); +} +#endif + +#if 1 +double noise2d_gradient(double x, double y, int seed) +{ + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + // Get values for corners of cube + double v00 = noise2d(x0, y0, seed); + double v10 = noise2d(x0+1, y0, seed); + double v01 = noise2d(x0, y0+1, seed); + double v11 = noise2d(x0+1, y0+1, seed); + // Interpolate + return biLinearInterpolation(v00,v10,v01,v11,xl,yl); +} +#endif + +double noise3d_gradient(double x, double y, double z, int seed) +{ + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + int z0 = (z > 0.0 ? (int)z : (int)z - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + double zl = z - (double)z0; + // Get values for corners of cube + double v000 = noise3d(x0, y0, z0, seed); + double v100 = noise3d(x0+1, y0, z0, seed); + double v010 = noise3d(x0, y0+1, z0, seed); + double v110 = noise3d(x0+1, y0+1, z0, seed); + double v001 = noise3d(x0, y0, z0+1, seed); + double v101 = noise3d(x0+1, y0, z0+1, seed); + double v011 = noise3d(x0, y0+1, z0+1, seed); + double v111 = noise3d(x0+1, y0+1, z0+1, seed); + // Interpolate + return triLinearInterpolation(v000,v100,v010,v110,v001,v101,v011,v111,xl,yl,zl); +} + +double noise2d_perlin(double x, double y, int seed, + int octaves, double persistence) +{ + double a = 0; + double f = 1.0; + double g = 1.0; + for(int i=0; i0, 0->1, 1->0 +double contour(double v) +{ + v = fabs(v); + if(v >= 1.0) + return 0.0; + return (1.0-v); +} + +double noise3d_param(const NoiseParams ¶m, double x, double y, double z) +{ + double s = param.pos_scale; + x /= s; + y /= s; + z /= s; + + if(param.type == NOISE_CONSTANT_ONE) + { + return 1.0; + } + else if(param.type == NOISE_PERLIN) + { + return param.noise_scale*noise3d_perlin(x,y,z, param.seed, + param.octaves, + param.persistence); + } + else if(param.type == NOISE_PERLIN_ABS) + { + return param.noise_scale*noise3d_perlin_abs(x,y,z, param.seed, + param.octaves, + param.persistence); + } + else if(param.type == NOISE_PERLIN_CONTOUR) + { + return contour(param.noise_scale*noise3d_perlin(x,y,z, + param.seed, param.octaves, + param.persistence)); + } + else if(param.type == NOISE_PERLIN_CONTOUR_FLIP_YZ) + { + return contour(param.noise_scale*noise3d_perlin(x,z,y, + param.seed, param.octaves, + param.persistence)); + } + else assert(0); +} + +/* + NoiseBuffer +*/ + +NoiseBuffer::NoiseBuffer(): + m_data(NULL) +{ +} + +NoiseBuffer::~NoiseBuffer() +{ + clear(); +} + +void NoiseBuffer::clear() +{ + if(m_data) + delete[] m_data; + m_data = NULL; + m_size_x = 0; + m_size_y = 0; + m_size_z = 0; +} + +void NoiseBuffer::create(const NoiseParams ¶m, + double first_x, double first_y, double first_z, + double last_x, double last_y, double last_z, + double samplelength_x, double samplelength_y, double samplelength_z) +{ + clear(); + + m_start_x = first_x - samplelength_x; + m_start_y = first_y - samplelength_y; + m_start_z = first_z - samplelength_z; + m_samplelength_x = samplelength_x; + m_samplelength_y = samplelength_y; + m_samplelength_z = samplelength_z; + + m_size_x = (last_x - m_start_x)/samplelength_x + 2; + m_size_y = (last_y - m_start_y)/samplelength_y + 2; + m_size_z = (last_z - m_start_z)/samplelength_z + 2; + + m_data = new double[m_size_x*m_size_y*m_size_z]; + + for(int x=0; x= 0); + assert(i < m_size_x*m_size_y*m_size_z); + m_data[i] = d; +} + +void NoiseBuffer::intMultiply(int x, int y, int z, double d) +{ + int i = m_size_x*m_size_y*z + m_size_x*y + x; + assert(i >= 0); + assert(i < m_size_x*m_size_y*m_size_z); + m_data[i] = m_data[i] * d; +} + +double NoiseBuffer::intGet(int x, int y, int z) +{ + int i = m_size_x*m_size_y*z + m_size_x*y + x; + assert(i >= 0); + assert(i < m_size_x*m_size_y*m_size_z); + return m_data[i]; +} + +double NoiseBuffer::get(double x, double y, double z) +{ + x -= m_start_x; + y -= m_start_y; + z -= m_start_z; + x /= m_samplelength_x; + y /= m_samplelength_y; + z /= m_samplelength_z; + // Calculate the integer coordinates + int x0 = (x > 0.0 ? (int)x : (int)x - 1); + int y0 = (y > 0.0 ? (int)y : (int)y - 1); + int z0 = (z > 0.0 ? (int)z : (int)z - 1); + // Calculate the remaining part of the coordinates + double xl = x - (double)x0; + double yl = y - (double)y0; + double zl = z - (double)z0; + // Get values for corners of cube + double v000 = intGet(x0, y0, z0); + double v100 = intGet(x0+1, y0, z0); + double v010 = intGet(x0, y0+1, z0); + double v110 = intGet(x0+1, y0+1, z0); + double v001 = intGet(x0, y0, z0+1); + double v101 = intGet(x0+1, y0, z0+1); + double v011 = intGet(x0, y0+1, z0+1); + double v111 = intGet(x0+1, y0+1, z0+1); + // Interpolate + return triLinearInterpolation(v000,v100,v010,v110,v001,v101,v011,v111,xl,yl,zl); +} + +/*bool NoiseBuffer::contains(double x, double y, double z) +{ + x -= m_start_x; + y -= m_start_y; + z -= m_start_z; + x /= m_samplelength_x; + y /= m_samplelength_y; + z /= m_samplelength_z; + if(x <= 0.0 || x >= m_size_x) +}*/ + diff --git a/src/noise.h b/src/noise.h new file mode 100644 index 0000000..ed75f31 --- /dev/null +++ b/src/noise.h @@ -0,0 +1,149 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef NOISE_HEADER +#define NOISE_HEADER + +#include "debug.h" + +class PseudoRandom +{ +public: + PseudoRandom(): m_next(0) + { + } + PseudoRandom(int seed): m_next(seed) + { + } + void seed(int seed) + { + m_next = seed; + } + // Returns 0...32767 + int next() + { + m_next = m_next * 1103515245 + 12345; + return((unsigned)(m_next/65536) % 32768); + } + int range(int min, int max) + { + if(max-min > 32768/10) + { + //dstream<<"WARNING: PseudoRandom::range: max > 32767"< max) + { + assert(0); + return max; + } + return (next()%(max-min+1))+min; + } +private: + int m_next; +}; + +double easeCurve(double t); + +// Return value: -1 ... 1 +double noise2d(int x, int y, int seed); +double noise3d(int x, int y, int z, int seed); + +double noise2d_gradient(double x, double y, int seed); +double noise3d_gradient(double x, double y, double z, int seed); + +double noise2d_perlin(double x, double y, int seed, + int octaves, double persistence); + +double noise2d_perlin_abs(double x, double y, int seed, + int octaves, double persistence); + +double noise3d_perlin(double x, double y, double z, int seed, + int octaves, double persistence); + +double noise3d_perlin_abs(double x, double y, double z, int seed, + int octaves, double persistence); + +enum NoiseType +{ + NOISE_CONSTANT_ONE, + NOISE_PERLIN, + NOISE_PERLIN_ABS, + NOISE_PERLIN_CONTOUR, + NOISE_PERLIN_CONTOUR_FLIP_YZ, +}; + +struct NoiseParams +{ + NoiseType type; + int seed; + int octaves; + double persistence; + double pos_scale; + double noise_scale; // Useful for contour noises + + NoiseParams(NoiseType type_=NOISE_PERLIN, int seed_=0, + int octaves_=3, double persistence_=0.5, + double pos_scale_=100.0, double noise_scale_=1.0): + type(type_), + seed(seed_), + octaves(octaves_), + persistence(persistence_), + pos_scale(pos_scale_), + noise_scale(noise_scale_) + { + } +}; + +double noise3d_param(const NoiseParams ¶m, double x, double y, double z); + +class NoiseBuffer +{ +public: + NoiseBuffer(); + ~NoiseBuffer(); + + void clear(); + void create(const NoiseParams ¶m, + double first_x, double first_y, double first_z, + double last_x, double last_y, double last_z, + double samplelength_x, double samplelength_y, double samplelength_z); + void multiply(const NoiseParams ¶m); + // Deprecated + void create(int seed, int octaves, double persistence, + bool abs, + double first_x, double first_y, double first_z, + double last_x, double last_y, double last_z, + double samplelength_x, double samplelength_y, double samplelength_z); + + void intSet(int x, int y, int z, double d); + void intMultiply(int x, int y, int z, double d); + double intGet(int x, int y, int z); + double get(double x, double y, double z); + //bool contains(double x, double y, double z); + +private: + double *m_data; + double m_start_x, m_start_y, m_start_z; + double m_samplelength_x, m_samplelength_y, m_samplelength_z; + int m_size_x, m_size_y, m_size_z; +}; + +#endif + diff --git a/src/player.cpp b/src/player.cpp new file mode 100644 index 0000000..7cfdfeb --- /dev/null +++ b/src/player.cpp @@ -0,0 +1,882 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "player.h" +#include "map.h" +#include "connection.h" +#include "constants.h" +#include "utility.h" + + +Player::Player(): + touching_ground(false), + in_water(false), + in_water_stable(false), + swimming_up(false), + inventory_backup(NULL), + craftresult_is_preview(true), + hp(20), + peer_id(PEER_ID_INEXISTENT), + m_selected_item(0), + m_pitch(0), + m_yaw(0), + m_speed(0,0,0), + m_position(0,0,0) +{ + updateName(""); + resetInventory(); +} + +Player::~Player() +{ + delete inventory_backup; +} + +void Player::wieldItem(u16 item) +{ + m_selected_item = item; +} + +void Player::resetInventory() +{ + inventory.clear(); + inventory.addList("main", PLAYER_INVENTORY_SIZE); + inventory.addList("craft", 9); + inventory.addList("craftresult", 1); +} + +// Y direction is ignored +void Player::accelerate(v3f target_speed, f32 max_increase) +{ + v3f d_wanted = target_speed - m_speed; + d_wanted.Y = 0; + f32 dl_wanted = d_wanted.getLength(); + f32 dl = dl_wanted; + if(dl > max_increase) + dl = max_increase; + + v3f d = d_wanted.normalize() * dl; + + m_speed.X += d.X; + m_speed.Z += d.Z; + //m_speed += d; + +#if 0 // old code + if(m_speed.X < target_speed.X - max_increase) + m_speed.X += max_increase; + else if(m_speed.X > target_speed.X + max_increase) + m_speed.X -= max_increase; + else if(m_speed.X < target_speed.X) + m_speed.X = target_speed.X; + else if(m_speed.X > target_speed.X) + m_speed.X = target_speed.X; + + if(m_speed.Z < target_speed.Z - max_increase) + m_speed.Z += max_increase; + else if(m_speed.Z > target_speed.Z + max_increase) + m_speed.Z -= max_increase; + else if(m_speed.Z < target_speed.Z) + m_speed.Z = target_speed.Z; + else if(m_speed.Z > target_speed.Z) + m_speed.Z = target_speed.Z; +#endif +} + +void Player::serialize(std::ostream &os) +{ + // Utilize a Settings object for storing values + Settings args; + args.setS32("version", 1); + args.set("name", m_name); + //args.set("password", m_password); + args.setFloat("pitch", m_pitch); + args.setFloat("yaw", m_yaw); + args.setV3F("position", m_position); + args.setBool("craftresult_is_preview", craftresult_is_preview); + args.setS32("hp", hp); + + args.writeLines(os); + + os<<"PlayerArgsEnd\n"; + + // If actual inventory is backed up due to creative mode, save it + // instead of the dummy creative mode inventory + if(inventory_backup) + inventory_backup->serialize(os); + else + inventory.serialize(os); +} + +void Player::deSerialize(std::istream &is) +{ + Settings args; + + for(;;) + { + if(is.eof()) + throw SerializationError + ("Player::deSerialize(): PlayerArgsEnd not found"); + std::string line; + std::getline(is, line); + std::string trimmedline = trim(line); + if(trimmedline == "PlayerArgsEnd") + break; + args.parseConfigLine(line); + } + + //args.getS32("version"); + std::string name = args.get("name"); + updateName(name.c_str()); + /*std::string password = ""; + if(args.exists("password")) + password = args.get("password"); + updatePassword(password.c_str());*/ + m_pitch = args.getFloat("pitch"); + m_yaw = args.getFloat("yaw"); + m_position = args.getV3F("position"); + try{ + craftresult_is_preview = args.getBool("craftresult_is_preview"); + }catch(SettingNotFoundException &e){ + craftresult_is_preview = true; + } + try{ + hp = args.getS32("hp"); + }catch(SettingNotFoundException &e){ + hp = 20; + } + /*try{ + std::string sprivs = args.get("privs"); + if(sprivs == "all") + { + privs = PRIV_ALL; + } + else + { + std::istringstream ss(sprivs); + ss>>privs; + } + }catch(SettingNotFoundException &e){ + privs = PRIV_DEFAULT; + }*/ + + inventory.deSerialize(is); +} + +/* + RemotePlayer +*/ + +#ifndef SERVER + +RemotePlayer::RemotePlayer( + scene::ISceneNode* parent, + IrrlichtDevice *device, + s32 id): + scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id), + m_text(NULL) +{ + m_box = core::aabbox3d(-BS/2,0,-BS/2,BS/2,BS*2,BS/2); + + if(parent != NULL && device != NULL) + { + // ISceneNode stores a member called SceneManager + scene::ISceneManager* mgr = SceneManager; + video::IVideoDriver* driver = mgr->getVideoDriver(); + gui::IGUIEnvironment* gui = device->getGUIEnvironment(); + + // Add a text node for showing the name + wchar_t wname[1] = {0}; + m_text = mgr->addTextSceneNode(gui->getBuiltInFont(), + wname, video::SColor(255,255,255,255), this); + m_text->setPosition(v3f(0, (f32)BS*2.1, 0)); + + // Attach a simple mesh to the player for showing an image + scene::SMesh *mesh = new scene::SMesh(); + { // Front + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1), + video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1), + video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0), + video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + { // Back + scene::IMeshBuffer *buf = new scene::SMeshBuffer(); + video::SColor c(255,255,255,255); + video::S3DVertex vertices[4] = + { + video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1), + video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1), + video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0), + video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0), + }; + u16 indices[] = {0,1,2,2,3,0}; + buf->append(vertices, 4, indices, 6); + // Set material + buf->getMaterial().setFlag(video::EMF_LIGHTING, false); + //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false); + buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player_back.png").c_str())); + buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false); + buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true); + buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; + // Add to mesh + mesh->addMeshBuffer(buf); + buf->drop(); + } + m_node = mgr->addMeshSceneNode(mesh, this); + mesh->drop(); + m_node->setPosition(v3f(0,0,0)); + } +} + +RemotePlayer::~RemotePlayer() +{ + if(SceneManager != NULL) + ISceneNode::remove(); +} + +void RemotePlayer::updateName(const char *name) +{ + Player::updateName(name); + if(m_text != NULL) + { + wchar_t wname[PLAYERNAME_SIZE]; + mbstowcs(wname, m_name, strlen(m_name)+1); + m_text->setText(wname); + } +} + +void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d) +{ + m_pos_animation_time_counter += dtime; + m_pos_animation_counter += dtime; + v3f movevector = m_position - m_oldpos; + f32 moveratio; + if(m_pos_animation_time < 0.001) + moveratio = 1.0; + else + moveratio = m_pos_animation_counter / m_pos_animation_time; + if(moveratio > 1.5) + moveratio = 1.5; + m_showpos = m_oldpos + movevector * moveratio; + + ISceneNode::setPosition(m_showpos); +} + +#endif + +#ifndef SERVER +/* + LocalPlayer +*/ + +LocalPlayer::LocalPlayer(): + m_sneak_node(32767,32767,32767), + m_sneak_node_exists(false) +{ + // Initialize hp to 0, so that no hearts will be shown if server + // doesn't support health points + hp = 0; +} + +LocalPlayer::~LocalPlayer() +{ +} + +void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d, + core::list *collision_info) +{ + v3f position = getPosition(); + v3f oldpos = position; + v3s16 oldpos_i = floatToInt(oldpos, BS); + + v3f old_speed = m_speed; + + /*std::cout<<"oldpos_i=("< pos_max_d); + + float player_radius = BS*0.35; + float player_height = BS*1.7; + + // Maximum distance over border for sneaking + f32 sneak_max = BS*0.4; + + /* + If sneaking, player has larger collision radius to keep from + falling + */ + /*if(control.sneak) + player_radius = sneak_max + d*1.1;*/ + + /* + If sneaking, keep in range from the last walked node and don't + fall off from it + */ + if(control.sneak && m_sneak_node_exists) + { + f32 maxd = 0.5*BS + sneak_max; + v3f lwn_f = intToFloat(m_sneak_node, BS); + position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd); + position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd); + + f32 min_y = lwn_f.Y + 0.5*BS; + if(position.Y < min_y) + { + position.Y = min_y; + + //v3f old_speed = m_speed; + + if(m_speed.Y < 0) + m_speed.Y = 0; + + /*if(collision_info) + { + // Report fall collision + if(old_speed.Y < m_speed.Y - 0.1) + { + CollisionInfo info; + info.t = COLLISION_FALL; + info.speed = m_speed.Y - old_speed.Y; + collision_info->push_back(info); + } + }*/ + } + } + + /* + Calculate player collision box (new and old) + */ + core::aabbox3d playerbox( + position.X - player_radius, + position.Y - 0.0, + position.Z - player_radius, + position.X + player_radius, + position.Y + player_height, + position.Z + player_radius + ); + core::aabbox3d playerbox_old( + oldpos.X - player_radius, + oldpos.Y - 0.0, + oldpos.Z - player_radius, + oldpos.X + player_radius, + oldpos.Y + player_height, + oldpos.Z + player_radius + ); + + /* + If the player's feet touch the topside of any node, this is + set to true. + + Player is allowed to jump when this is true. + */ + touching_ground = false; + + /*std::cout<<"Checking collisions for (" + < (" + < nodebox = getNodeBox(v3s16(x,y,z), BS); + + /* + See if the player is touching ground. + + Player touches ground if player's minimum Y is near node's + maximum Y and player's X-Z-area overlaps with the node's + X-Z-area. + + Use 0.15*BS so that it is easier to get on a node. + */ + if( + //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d + fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS + && nodebox.MaxEdge.X-d > playerbox.MinEdge.X + && nodebox.MinEdge.X+d < playerbox.MaxEdge.X + && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z + && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z + ){ + touching_ground = true; + } + + // If player doesn't intersect with node, ignore node. + if(playerbox.intersectsWithBox(nodebox) == false) + continue; + + /* + Go through every axis + */ + v3f dirs[3] = { + v3f(0,0,1), // back-front + v3f(0,1,0), // top-bottom + v3f(1,0,0), // right-left + }; + for(u16 i=0; i<3; i++) + { + /* + Calculate values along the axis + */ + f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]); + f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]); + f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]); + f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]); + f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]); + f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]); + + /* + Check collision for the axis. + Collision happens when player is going through a surface. + */ + /*f32 neg_d = d; + f32 pos_d = d; + // Make it easier to get on top of a node + if(i == 1) + neg_d = 0.15*BS; + bool negative_axis_collides = + (nodemax > playermin && nodemax <= playermin_old + neg_d + && m_speed.dotProduct(dirs[i]) < 0); + bool positive_axis_collides = + (nodemin < playermax && nodemin >= playermax_old - pos_d + && m_speed.dotProduct(dirs[i]) > 0);*/ + bool negative_axis_collides = + (nodemax > playermin && nodemax <= playermin_old + d + && m_speed.dotProduct(dirs[i]) < 0); + bool positive_axis_collides = + (nodemin < playermax && nodemin >= playermax_old - d + && m_speed.dotProduct(dirs[i]) > 0); + bool main_axis_collides = + negative_axis_collides || positive_axis_collides; + + /* + Check overlap of player and node in other axes + */ + bool other_axes_overlap = true; + for(u16 j=0; j<3; j++) + { + if(j == i) + continue; + f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]); + f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]); + f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]); + f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]); + if(!(nodemax - d > playermin && nodemin + d < playermax)) + { + other_axes_overlap = false; + break; + } + } + + /* + If this is a collision, revert the position in the main + direction. + */ + if(other_axes_overlap && main_axis_collides) + { + //v3f old_speed = m_speed; + + m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i]; + position -= position.dotProduct(dirs[i]) * dirs[i]; + position += oldpos.dotProduct(dirs[i]) * dirs[i]; + + /*if(collision_info) + { + // Report fall collision + if(old_speed.Y < m_speed.Y - 0.1) + { + CollisionInfo info; + info.t = COLLISION_FALL; + info.speed = m_speed.Y - old_speed.Y; + collision_info->push_back(info); + } + }*/ + } + + } + } // xyz + + /* + Check the nodes under the player to see from which node the + player is sneaking from, if any. + */ + { + v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS); + v2f player_p2df(position.X, position.Z); + f32 min_distance_f = 100000.0*BS; + // If already seeking from some node, compare to it. + /*if(m_sneak_node_exists) + { + v3f sneaknode_pf = intToFloat(m_sneak_node, BS); + v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z); + f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df); + f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y); + // Ignore if player is not on the same level (likely dropped) + if(d_vert_f < 0.15*BS) + min_distance_f = d_horiz_f; + }*/ + v3s16 new_sneak_node = m_sneak_node; + for(s16 x=-1; x<=1; x++) + for(s16 z=-1; z<=1; z++) + { + v3s16 p = pos_i_bottom + v3s16(x,0,z); + v3f pf = intToFloat(p, BS); + v2f node_p2df(pf.X, pf.Z); + f32 distance_f = player_p2df.getDistanceFrom(node_p2df); + f32 max_axis_distance_f = MYMAX( + fabs(player_p2df.X-node_p2df.X), + fabs(player_p2df.Y-node_p2df.Y)); + + if(distance_f > min_distance_f || + max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS) + continue; + + try{ + // The node to be sneaked on has to be walkable + if(content_walkable(map.getNode(p).getContent()) == false) + continue; + // And the node above it has to be nonwalkable + if(content_walkable(map.getNode(p+v3s16(0,1,0)).getContent()) == true) + continue; + } + catch(InvalidPositionException &e) + { + continue; + } + + min_distance_f = distance_f; + new_sneak_node = p; + } + + bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9); + + if(control.sneak && m_sneak_node_exists) + { + if(sneak_node_found) + m_sneak_node = new_sneak_node; + } + else + { + m_sneak_node = new_sneak_node; + m_sneak_node_exists = sneak_node_found; + } + + /* + If sneaking, the player's collision box can be in air, so + this has to be set explicitly + */ + if(sneak_node_found && control.sneak) + touching_ground = true; + } + + /* + Set new position + */ + setPosition(position); + + /* + Report collisions + */ + if(collision_info) + { + // Report fall collision + if(old_speed.Y < m_speed.Y - 0.1) + { + CollisionInfo info; + info.t = COLLISION_FALL; + info.speed = m_speed.Y - old_speed.Y; + collision_info->push_back(info); + } + } +} + +void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d) +{ + move(dtime, map, pos_max_d, NULL); +} + +void LocalPlayer::applyControl(float dtime) +{ + // Clear stuff + swimming_up = false; + + // Random constants + f32 walk_acceleration = 4.0 * BS; + f32 walkspeed_max = 4.0 * BS; + + setPitch(control.pitch); + setYaw(control.yaw); + + v3f move_direction = v3f(0,0,1); + move_direction.rotateXZBy(getYaw()); + + v3f speed = v3f(0,0,0); + + bool free_move = g_settings.getBool("free_move"); + bool fast_move = g_settings.getBool("fast_move"); + bool continuous_forward = g_settings.getBool("continuous_forward"); + + if(free_move || is_climbing) + { + v3f speed = getSpeed(); + speed.Y = 0; + setSpeed(speed); + } + + // Whether superspeed mode is used or not + bool superspeed = false; + + // If free movement and fast movement, always move fast + if(free_move && fast_move) + superspeed = true; + + // Auxiliary button 1 (E) + if(control.aux1) + { + if(free_move) + { + // In free movement mode, aux1 descends + v3f speed = getSpeed(); + if(fast_move) + speed.Y = -20*BS; + else + speed.Y = -walkspeed_max; + setSpeed(speed); + } + else if(is_climbing) + { + v3f speed = getSpeed(); + speed.Y = -3*BS; + setSpeed(speed); + } + else + { + // If not free movement but fast is allowed, aux1 is + // "Turbo button" + if(fast_move) + superspeed = true; + } + } + + if(continuous_forward) + speed += move_direction; + + if(control.up) + { + if(continuous_forward) + superspeed = true; + else + speed += move_direction; + } + if(control.down) + { + speed -= move_direction; + } + if(control.left) + { + speed += move_direction.crossProduct(v3f(0,1,0)); + } + if(control.right) + { + speed += move_direction.crossProduct(v3f(0,-1,0)); + } + if(control.jump) + { + if(free_move) + { + v3f speed = getSpeed(); + if(fast_move) + speed.Y = 20*BS; + else + speed.Y = walkspeed_max; + setSpeed(speed); + } + else if(touching_ground) + { + v3f speed = getSpeed(); + /* + NOTE: The d value in move() affects jump height by + raising the height at which the jump speed is kept + at its starting value + */ + speed.Y = 6.5*BS; + setSpeed(speed); + } + // Use the oscillating value for getting out of water + // (so that the player doesn't fly on the surface) + else if(in_water) + { + v3f speed = getSpeed(); + speed.Y = 1.5*BS; + setSpeed(speed); + swimming_up = true; + } + else if(is_climbing) + { + v3f speed = getSpeed(); + speed.Y = 3*BS; + setSpeed(speed); + } + } + + // The speed of the player (Y is ignored) + if(superspeed) + speed = speed.normalize() * walkspeed_max * 5.0; + else if(control.sneak) + speed = speed.normalize() * walkspeed_max / 3.0; + else + speed = speed.normalize() * walkspeed_max; + + f32 inc = walk_acceleration * BS * dtime; + + // Faster acceleration if fast and free movement + if(free_move && fast_move) + inc = walk_acceleration * BS * dtime * 10; + + // Accelerate to target speed with maximum increment + accelerate(speed, inc); +} +#endif + diff --git a/src/player.h b/src/player.h new file mode 100644 index 0000000..13cffa2 --- /dev/null +++ b/src/player.h @@ -0,0 +1,377 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef PLAYER_HEADER +#define PLAYER_HEADER + +#include "common_irrlicht.h" +#include "inventory.h" +#include "collision.h" + +#define PLAYERNAME_SIZE 20 + +#define PLAYERNAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" + + +class Map; + +class Player +{ +public: + + + Player(); + virtual ~Player(); + + void resetInventory(); + + //void move(f32 dtime, Map &map); + virtual void move(f32 dtime, Map &map, f32 pos_max_d) = 0; + + v3f getSpeed() + { + return m_speed; + } + + void setSpeed(v3f speed) + { + m_speed = speed; + } + + // Y direction is ignored + void accelerate(v3f target_speed, f32 max_increase); + + v3f getPosition() + { + return m_position; + } + + v3s16 getLightPosition() const + { + return floatToInt(m_position + v3f(0,BS+BS/2,0), BS); + } + + v3f getEyePosition() + { + // This is at the height of the eyes of the current figure + // return m_position + v3f(0, BS+BS/2, 0); + // This is more like in minecraft + return m_position + v3f(0,BS+(5*BS)/8,0); + } + + virtual void setPosition(const v3f &position) + { + m_position = position; + } + + void setPitch(f32 pitch) + { + m_pitch = pitch; + } + + virtual void setYaw(f32 yaw) + { + m_yaw = yaw; + } + + f32 getPitch() + { + return m_pitch; + } + + f32 getYaw() + { + return m_yaw; + } + + virtual void updateName(const char *name) + { + snprintf(m_name, PLAYERNAME_SIZE, "%s", name); + } + + virtual void wieldItem(u16 item); + virtual const InventoryItem *getWieldItem() const + { + const InventoryList *list = inventory.getList("main"); + if (list) + return list->getItem(m_selected_item); + return NULL; + } + + const char * getName() + { + return m_name; + } + + virtual bool isLocal() const = 0; + + virtual void updateLight(u8 light_at_pos) {}; + + // NOTE: Use peer_id == 0 for disconnected + /*virtual bool isClientConnected() { return false; } + virtual void setClientConnected(bool) {}*/ + + /* + serialize() writes a bunch of text that can contain + any characters except a '\0', and such an ending that + deSerialize stops reading exactly at the right point. + */ + void serialize(std::ostream &os); + void deSerialize(std::istream &is); + + bool touching_ground; + // This oscillates so that the player jumps a bit above the surface + bool in_water; + // This is more stable and defines the maximum speed of the player + bool in_water_stable; + bool is_climbing; + bool swimming_up; + bool is_frozen; + + Inventory inventory; + // Actual inventory is backed up here when creative mode is used + Inventory *inventory_backup; + + bool craftresult_is_preview; + + u16 hp; + + u16 peer_id; + +protected: + char m_name[PLAYERNAME_SIZE]; + u16 m_selected_item; + f32 m_pitch; + f32 m_yaw; + v3f m_speed; + v3f m_position; + +public: + +}; + +/* + Player on the server +*/ + +class ServerRemotePlayer : public Player +{ +public: + ServerRemotePlayer() + { + } + virtual ~ServerRemotePlayer() + { + } + + virtual bool isLocal() const + { + return false; + } + + virtual void move(f32 dtime, Map &map, f32 pos_max_d) + { + } + +private: +}; + +#ifndef SERVER + +/* + All the other players on the client are these +*/ + +class RemotePlayer : public Player, public scene::ISceneNode +{ +public: + RemotePlayer( + scene::ISceneNode* parent=NULL, + IrrlichtDevice *device=NULL, + s32 id=0); + + virtual ~RemotePlayer(); + + /* + ISceneNode methods + */ + + virtual void OnRegisterSceneNode() + { + if (IsVisible) + SceneManager->registerNodeForRendering(this); + + ISceneNode::OnRegisterSceneNode(); + } + + virtual void render() + { + // Do nothing + } + + virtual const core::aabbox3d& getBoundingBox() const + { + return m_box; + } + + void setPosition(const v3f &position) + { + m_oldpos = m_showpos; + + if(m_pos_animation_time < 0.001 || m_pos_animation_time > 1.0) + m_pos_animation_time = m_pos_animation_time_counter; + else + m_pos_animation_time = m_pos_animation_time * 0.9 + + m_pos_animation_time_counter * 0.1; + m_pos_animation_time_counter = 0; + m_pos_animation_counter = 0; + + Player::setPosition(position); + //ISceneNode::setPosition(position); + } + + virtual void setYaw(f32 yaw) + { + Player::setYaw(yaw); + ISceneNode::setRotation(v3f(0, -yaw, 0)); + } + + bool isLocal() const + { + return false; + } + + void updateName(const char *name); + + virtual void updateLight(u8 light_at_pos) + { + if(m_node == NULL) + return; + + u8 li = decode_light(light_at_pos); + video::SColor color(255,li,li,li); + + scene::IMesh *mesh = m_node->getMesh(); + + u16 mc = mesh->getMeshBufferCount(); + for(u16 j=0; jgetMeshBuffer(j); + video::S3DVertex *vertices = (video::S3DVertex*)buf->getVertices(); + u16 vc = buf->getVertexCount(); + for(u16 i=0; i m_box; + + v3f m_oldpos; + f32 m_pos_animation_counter; + f32 m_pos_animation_time; + f32 m_pos_animation_time_counter; + v3f m_showpos; +}; + +#endif // !SERVER + +#ifndef SERVER +struct PlayerControl +{ + PlayerControl() + { + up = false; + down = false; + left = false; + right = false; + jump = false; + aux1 = false; + sneak = false; + pitch = 0; + yaw = 0; + } + PlayerControl( + bool a_up, + bool a_down, + bool a_left, + bool a_right, + bool a_jump, + bool a_aux1, + bool a_sneak, + float a_pitch, + float a_yaw + ) + { + up = a_up; + down = a_down; + left = a_left; + right = a_right; + jump = a_jump; + aux1 = a_aux1; + sneak = a_sneak; + pitch = a_pitch; + yaw = a_yaw; + } + bool up; + bool down; + bool left; + bool right; + bool jump; + bool aux1; + bool sneak; + float pitch; + float yaw; +}; + +class LocalPlayer : public Player +{ +public: + LocalPlayer(); + virtual ~LocalPlayer(); + + bool isLocal() const + { + return true; + } + + void move(f32 dtime, Map &map, f32 pos_max_d, + core::list *collision_info); + void move(f32 dtime, Map &map, f32 pos_max_d); + + void applyControl(float dtime); + + PlayerControl control; + +private: + // This is used for determining the sneaking range + v3s16 m_sneak_node; + // Whether the player is allowed to sneak + bool m_sneak_node_exists; +}; +#endif // !SERVER + +#endif + diff --git a/src/porting.cpp b/src/porting.cpp new file mode 100644 index 0000000..39b2c57 --- /dev/null +++ b/src/porting.cpp @@ -0,0 +1,262 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* + Random portability stuff + + See comments in porting.h +*/ + +#include "porting.h" +#include "config.h" +#include "debug.h" +#include "filesys.h" + +#ifdef __APPLE__ + #include "CoreFoundation/CoreFoundation.h" +#endif + +namespace porting +{ + +/* + Signal handler (grabs Ctrl-C on POSIX systems) +*/ + +bool g_killed = false; + +bool * signal_handler_killstatus(void) +{ + return &g_killed; +} + +#if !defined(_WIN32) // POSIX + #include + +void sigint_handler(int sig) +{ + if(g_killed == false) + { + dstream<=0; i--) + { + if(path[i] == delim) + break; + } + path[i] = 0; +} + +void initializePaths() +{ +#ifdef RUN_IN_PLACE + /* + Use relative paths if RUN_IN_PLACE + */ + + dstream<<"Using relative paths (RUN_IN_PLACE)"< + + const DWORD buflen = 1000; + char buf[buflen]; + DWORD len; + + // Find path of executable and set path_data relative to it + len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); + assert(len < buflen); + pathRemoveFile(buf, '\\'); + + // Use "./bin/../data" + path_data = std::string(buf) + "/../data"; + + // Use "./bin/../" + path_userdata = std::string(buf) + "/../"; + + /* + Linux + */ + #elif defined(linux) + #include + + char buf[BUFSIZ]; + memset(buf, 0, BUFSIZ); + // Get path to executable + assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1); + + pathRemoveFile(buf, '/'); + + // Use "./bin/../data" + path_data = std::string(buf) + "/../data"; + + // Use "./bin/../" + path_userdata = std::string(buf) + "/../"; + + /* + OS X + */ + #elif defined(__APPLE__) || defined(__FreeBSD__) + + //TODO: Get path of executable. This assumes working directory is bin/ + dstream<<"WARNING: Relative path not properly supported on OS X and FreeBSD" + < + + const DWORD buflen = 1000; + char buf[buflen]; + DWORD len; + + // Find path of executable and set path_data relative to it + len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen); + assert(len < buflen); + pathRemoveFile(buf, '\\'); + + // Use "./bin/../data" + path_data = std::string(buf) + "/../data"; + //path_data = std::string(buf) + "/../share/" + PROJECT_NAME; + + // Use "C:\Documents and Settings\user\Application Data\" + len = GetEnvironmentVariable("APPDATA", buf, buflen); + assert(len < buflen); + path_userdata = std::string(buf) + "/" + PROJECT_NAME; + + /* + Linux + */ + #elif defined(linux) + #include + + char buf[BUFSIZ]; + memset(buf, 0, BUFSIZ); + // Get path to executable + assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1); + + pathRemoveFile(buf, '/'); + + path_data = std::string(buf) + "/../share/" + PROJECT_NAME; + //path_data = std::string(INSTALL_PREFIX) + "/share/" + PROJECT_NAME; + if (!fs::PathExists(path_data)) { + dstream<<"WARNING: data path " << path_data << " not found!"; + path_data = std::string(buf) + "/../data"; + dstream<<" Trying " << path_data << std::endl; + } + + path_userdata = std::string(getenv("HOME")) + "/." + PROJECT_NAME; + + /* + OS X + */ + #elif defined(__APPLE__) + #include + + // Code based on + // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c + CFBundleRef main_bundle = CFBundleGetMainBundle(); + CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle); + char path[PATH_MAX]; + if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) + { + dstream<<"Bundle resource path: "< + #define sleep_ms(x) Sleep(x) +#else + #include + #define sleep_ms(x) usleep(x*1000) +#endif + +namespace porting +{ + +/* + Signal handler (grabs Ctrl-C on POSIX systems) +*/ + +void signal_handler_init(void); +// Returns a pointer to a bool. +// When the bool is true, program should quit. +bool * signal_handler_killstatus(void); + +/* + Path of static data directory. +*/ +extern std::string path_data; + +/* + Directory for storing user data. Examples: + Windows: "C:\Documents and Settings\user\Application Data\" + Linux: "~/." + Mac: "~/Library/Application Support/" +*/ +extern std::string path_userdata; + +/* + Get full path of stuff in data directory. + Example: "stone.png" -> "../data/stone.png" +*/ +inline std::string getDataPath(const char *subpath) +{ + return path_data + "/" + subpath; +} + +/* + Initialize path_data and path_userdata. +*/ +void initializePaths(); + +/* + Resolution is 10-20ms. + Remember to check for overflows. + Overflow can occur at any value higher than 10000000. +*/ +#ifdef _WIN32 // Windows + #include + inline u32 getTimeMs() + { + return GetTickCount(); + } +#else // Posix + #include + inline u32 getTimeMs() + { + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * 1000 + tv.tv_usec / 1000; + } + /*#include + inline u32 getTimeMs() + { + struct timeb tb; + ftime(&tb); + return tb.time * 1000 + tb.millitm; + }*/ +#endif + +} // namespace porting + +#endif // PORTING_HEADER + diff --git a/src/profiler.h b/src/profiler.h new file mode 100644 index 0000000..a30e34a --- /dev/null +++ b/src/profiler.h @@ -0,0 +1,131 @@ +/* +Minetest-c55 +Copyright (C) 2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef PROFILER_HEADER +#define PROFILER_HEADER + +#include "common_irrlicht.h" +#include +#include "utility.h" +#include +#include + +/* + Time profiler +*/ + +class Profiler +{ +public: + Profiler() + { + m_mutex.Init(); + } + + void add(const std::string &name, u32 duration) + { + JMutexAutoLock lock(m_mutex); + core::map::Node *n = m_data.find(name); + if(n == NULL) + { + m_data[name] = duration; + } + else + { + n->setValue(n->getValue()+duration); + } + } + + void clear() + { + JMutexAutoLock lock(m_mutex); + for(core::map::Iterator + i = m_data.getIterator(); + i.atEnd() == false; i++) + { + i.getNode()->setValue(0); + } + } + + void print(std::ostream &o) + { + JMutexAutoLock lock(m_mutex); + for(core::map::Iterator + i = m_data.getIterator(); + i.atEnd() == false; i++) + { + std::string name = i.getNode()->getKey(); + o<getValue(); + o< m_data; +}; + +class ScopeProfiler +{ +public: + ScopeProfiler(Profiler *profiler, const std::string &name): + m_profiler(profiler), + m_name(name), + m_timer(NULL) + { + if(m_profiler) + m_timer = new TimeTaker(m_name.c_str()); + } + // name is copied + ScopeProfiler(Profiler *profiler, const char *name): + m_profiler(profiler), + m_name(name), + m_timer(NULL) + { + if(m_profiler) + m_timer = new TimeTaker(m_name.c_str()); + } + ~ScopeProfiler() + { + if(m_timer) + { + u32 duration = m_timer->stop(true); + if(m_profiler) + m_profiler->add(m_name, duration); + delete m_timer; + } + } +private: + Profiler *m_profiler; + std::string m_name; + TimeTaker *m_timer; +}; + +#endif + diff --git a/src/serialization.cpp b/src/serialization.cpp new file mode 100644 index 0000000..f150d45 --- /dev/null +++ b/src/serialization.cpp @@ -0,0 +1,277 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "serialization.h" +#include "utility.h" +#ifdef _WIN32 + #define ZLIB_WINAPI +#endif +#include "zlib.h" + +/* report a zlib or i/o error */ +void zerr(int ret) +{ + dstream<<"zerr: "; + switch (ret) { + case Z_ERRNO: + if (ferror(stdin)) + dstream<<"error reading stdin"< databuf((u8*)data.c_str(), data.size()); + compressZlib(databuf, os); +} + +void decompressZlib(std::istream &is, std::ostream &os) +{ + z_stream z; + const s32 bufsize = 16384; + char input_buffer[bufsize]; + char output_buffer[bufsize]; + int status = 0; + int ret; + int bytes_read = 0; + int input_buffer_len = 0; + + z.zalloc = Z_NULL; + z.zfree = Z_NULL; + z.opaque = Z_NULL; + + ret = inflateInit(&z); + if(ret != Z_OK) + throw SerializationError("dcompressZlib: inflateInit failed"); + + z.avail_in = 0; + + //dstream<<"initial fail="< data, std::ostream &os, u8 version) +{ + if(version >= 11) + { + compressZlib(data, os); + return; + } + + if(data.getSize() == 0) + return; + + // Write length (u32) + + u8 tmp[4]; + writeU32(tmp, data.getSize()); + os.write((char*)tmp, 4); + + // We will be writing 8-bit pairs of more_count and byte + u8 more_count = 0; + u8 current_byte = data[0]; + for(u32 i=1; i= 11) + { + decompressZlib(is, os); + return; + } + + // Read length (u32) + + u8 tmp[4]; + is.read((char*)tmp, 4); + u32 len = readU32(tmp); + + // We will be reading 8-bit pairs of more_count and byte + u32 count = 0; + for(;;) + { + u8 more_count=0; + u8 byte=0; + + is.read((char*)&more_count, 1); + + is.read((char*)&byte, 1); + + if(is.eof()) + throw SerializationError("decompress: stream ended halfway"); + + for(s32 i=0; i<(u16)more_count+1; i++) + os.write((char*)&byte, 1); + + count += (u16)more_count+1; + + if(count == len) + break; + } +} + + diff --git a/src/serialization.h b/src/serialization.h new file mode 100644 index 0000000..d93e618 --- /dev/null +++ b/src/serialization.h @@ -0,0 +1,83 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef SERIALIZATION_HEADER +#define SERIALIZATION_HEADER + +#include "common_irrlicht.h" +#include "exceptions.h" +#include +#include "utility.h" + +/* + Map format serialization version + -------------------------------- + + For map data (blocks, nodes, sectors). + + NOTE: The goal is to increment this so that saved maps will be + loadable by any version. Other compatibility is not + maintained. + + 0: original networked test with 1-byte nodes + 1: update with 2-byte nodes + 2: lighting is transmitted in param + 3: optional fetching of far blocks + 4: block compression + 5: sector objects NOTE: block compression was left accidentally out + 6: failed attempt at switching block compression on again + 7: block compression switched on again + 8: server-initiated block transfers and all kinds of stuff + 9: block objects + 10: water pressure + 11: zlib'd blocks, block flags + 12: UnlimitedHeightmap now uses interpolated areas + 13: Mapgen v2 + 14: NodeMetadata + 15: StaticObjects + 16: larger maximum size of node metadata, and compression + 17: MapBlocks contain timestamp + 18: new generator (not really necessary, but it's there) + 19: new content type handling + 20: many existing content types translated to extended ones +*/ +// This represents an uninitialized or invalid format +#define SER_FMT_VER_INVALID 255 +// Highest supported serialization version +#define SER_FMT_VER_HIGHEST 20 +// Lowest supported serialization version +#define SER_FMT_VER_LOWEST 0 + +#define ser_ver_supported(v) (v >= SER_FMT_VER_LOWEST && v <= SER_FMT_VER_HIGHEST) + +/* + Misc. serialization functions +*/ + +void compressZlib(SharedBuffer data, std::ostream &os); +void compressZlib(const std::string &data, std::ostream &os); +void decompressZlib(std::istream &is, std::ostream &os); + +// These choose between zlib and a self-made one according to version +void compress(SharedBuffer data, std::ostream &os, u8 version); +//void compress(const std::string &data, std::ostream &os, u8 version); +void decompress(std::istream &is, std::ostream &os, u8 version); + +#endif + diff --git a/src/server.cpp b/src/server.cpp new file mode 100644 index 0000000..a044170 --- /dev/null +++ b/src/server.cpp @@ -0,0 +1,4530 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "server.h" +#include "utility.h" +#include +#include "clientserver.h" +#include "map.h" +#include "jmutexautolock.h" +#include "main.h" +#include "constants.h" +#include "voxel.h" +#include "materials.h" +#include "mineral.h" +#include "config.h" +#include "servercommand.h" +#include "filesys.h" +#include "content_mapnode.h" +#include "content_craft.h" +#include "content_nodemeta.h" +#include "mapblock.h" +#include "serverobject.h" + +#define BLOCK_EMERGE_FLAG_FROMDISK (1<<0) + +class MapEditEventIgnorer +{ +public: + MapEditEventIgnorer(bool *flag): + m_flag(flag) + { + if(*m_flag == false) + *m_flag = true; + else + m_flag = NULL; + } + + ~MapEditEventIgnorer() + { + if(m_flag) + { + assert(*m_flag); + *m_flag = false; + } + } + +private: + bool *m_flag; +}; + +void * ServerThread::Thread() +{ + ThreadStarted(); + + DSTACK(__FUNCTION_NAME); + + BEGIN_DEBUG_EXCEPTION_HANDLER + + while(getRun()) + { + try{ + //TimeTaker timer("AsyncRunStep() + Receive()"); + + { + //TimeTaker timer("AsyncRunStep()"); + m_server->AsyncRunStep(); + } + + //dout_server<<"Running m_server->Receive()"<Receive(); + } + catch(con::NoIncomingDataException &e) + { + } + catch(con::PeerNotFoundException &e) + { + dout_server<<"Server: PeerNotFoundException"<m_emerge_queue.pop(); + if(qptr == NULL) + break; + + SharedPtr q(qptr); + + v3s16 &p = q->pos; + v2s16 p2d(p.X,p.Z); + + /* + Do not generate over-limit + */ + if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + continue; + + //derr_server<<"EmergeThread::Thread(): running"<::Iterator i; + for(i=q->peer_ids.getIterator(); i.atEnd()==false; i++) + { + //u16 peer_id = i.getNode()->getKey(); + + // Check flags + u8 flags = i.getNode()->getValue(); + if((flags & BLOCK_EMERGE_FLAG_FROMDISK) == false) + only_from_disk = false; + + } + } + + if(enable_mapgen_debug_info) + dstream<<"EmergeThread: p=" + <<"("<isGenerated() == false) + { + if(enable_mapgen_debug_info) + dstream<<"EmergeThread: generating"<m_ignore_map_edit_events); + + // Activate objects and stuff + m_server->m_env.activateBlock(block, 3600); + } + } + else + { + /*if(block->getLightingExpired()){ + lighting_invalidated_blocks[block->getPos()] = block; + }*/ + } + + // TODO: Some additional checking and lighting updating, + // see emergeBlock + } + + {//envlock + JMutexAutoLock envlock(m_server->m_env_mutex); + + if(got_block) + { + /* + Collect a list of blocks that have been modified in + addition to the fetched one. + */ + +#if 0 + if(lighting_invalidated_blocks.size() > 0) + { + /*dstream<<"lighting "<::Iterator i = changed_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + modified_blocks.insert(block->getPos(), block); + } +#endif + } + // If we got no block, there should be no invalidated blocks + else + { + //assert(lighting_invalidated_blocks.size() == 0); + } + + }//envlock + + /* + Set sent status of modified blocks on clients + */ + + // NOTE: Server's clients are also behind the connection mutex + JMutexAutoLock lock(m_server->m_con_mutex); + + /* + Add the originally fetched block to the modified list + */ + if(got_block) + { + modified_blocks.insert(p, block); + } + + /* + Set the modified blocks unsent for all the clients + */ + + for(core::map::Iterator + i = m_server->m_clients.getIterator(); + i.atEnd() == false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + + if(modified_blocks.size() > 0) + { + // Remove block from sent history + client->SetBlocksNotSent(modified_blocks); + } + } + + } + + END_DEBUG_EXCEPTION_HANDLER + + return NULL; +} + +void RemoteClient::GetNextBlocks(Server *server, float dtime, + core::array &dest) +{ + DSTACK(__FUNCTION_NAME); + + /*u32 timer_result; + TimeTaker timer("RemoteClient::GetNextBlocks", &timer_result);*/ + + // Increment timers + m_nothing_to_send_pause_timer -= dtime; + + if(m_nothing_to_send_pause_timer >= 0) + { + // Keep this reset + m_nearest_unsent_reset_timer = 0; + return; + } + + // Won't send anything if already sending + if(m_blocks_sending.size() >= g_settings.getU16 + ("max_simultaneous_block_sends_per_client")) + { + //dstream<<"Not sending any blocks, Queue full."<m_env.getPlayer(peer_id); + + assert(player != NULL); + + v3f playerpos = player->getPosition(); + v3f playerspeed = player->getSpeed(); + v3f playerspeeddir(0,0,0); + if(playerspeed.getLength() > 1.0*BS) + playerspeeddir = playerspeed / playerspeed.getLength(); + // Predict to next block + v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS; + + v3s16 center_nodepos = floatToInt(playerpos_predicted, BS); + + v3s16 center = getNodeBlockPos(center_nodepos); + + // Camera position and direction + v3f camera_pos = player->getEyePosition(); + v3f camera_dir = v3f(0,0,1); + camera_dir.rotateYZBy(player->getPitch()); + camera_dir.rotateXZBy(player->getYaw()); + + /*dstream<<"camera_dir=("<getPlayerName(peer_id)< d_start+1) + d_max = d_start+1; + /*if(d_max_gen > d_start+2) + d_max_gen = d_start+2;*/ + + //dstream<<"Starting from "< list; + getFacePositions(list, d); + + core::list::Iterator li; + for(li=list.begin(); li!=list.end(); li++) + { + v3s16 p = *li + center; + + /* + Send throttling + - Don't allow too many simultaneous transfers + - EXCEPT when the blocks are very close + + Also, don't send blocks that are already flying. + */ + + // Start with the usual maximum + u16 max_simul_dynamic = max_simul_sends_usually; + + // If block is very close, allow full maximum + if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D) + max_simul_dynamic = max_simul_sends_setting; + + // Don't select too many blocks for sending + if(num_blocks_selected >= max_simul_dynamic) + { + queue_is_full = true; + goto queue_full_break; + } + + // Don't send blocks that are currently being transferred + if(m_blocks_sending.find(p) != NULL) + continue; + + /* + Do not go over-limit + */ + if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE + || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE) + continue; + + // If this is true, inexistent block will be made from scratch + bool generate = d <= d_max_gen; + + { + /*// Limit the generating area vertically to 2/3 + if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3) + generate = false;*/ + + // Limit the send area vertically to 2/3 + if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3) + continue; + } + +#if 1 + /* + If block is far away, don't generate it unless it is + near ground level. + */ + if(d >= 4) + { + #if 1 + // Block center y in nodes + f32 y = (f32)(p.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE/2); + // Don't generate if it's very high or very low + if(y < -64 || y > 64) + generate = false; + #endif + #if 0 + v2s16 p2d_nodes_center( + MAP_BLOCKSIZE*p.X, + MAP_BLOCKSIZE*p.Z); + + // Get ground height in nodes + s16 gh = server->m_env.getServerMap().findGroundLevel( + p2d_nodes_center); + + // If differs a lot, don't generate + if(fabs(gh - y) > MAP_BLOCKSIZE*2) + generate = false; + // Actually, don't even send it + //continue; + #endif + } +#endif + + //dstream<<"d="<m_env.getMap().getBlockNoCreateNoEx(p); + + bool surely_not_found_on_disk = false; + bool block_is_invalid = false; + if(block != NULL) + { + // Reset usage timer, this block will be of use in the future. + block->resetUsageTimer(); + + // Block is dummy if data doesn't exist. + // It means it has been not found from disk and not generated + if(block->isDummy()) + { + surely_not_found_on_disk = true; + } + + // Block is valid if lighting is up-to-date and data exists + if(block->isValid() == false) + { + block_is_invalid = true; + } + + /*if(block->isFullyGenerated() == false) + { + block_is_invalid = true; + }*/ + +#if 0 + v2s16 p2d(p.X, p.Z); + ServerMap *map = (ServerMap*)(&server->m_env.getMap()); + v2s16 chunkpos = map->sector_to_chunk(p2d); + if(map->chunkNonVolatile(chunkpos) == false) + block_is_invalid = true; +#endif + if(block->isGenerated() == false) + block_is_invalid = true; +#if 1 + /* + If block is not close, don't send it unless it is near + ground level. + + Block is near ground level if night-time mesh + differs from day-time mesh. + */ + if(d > 3) + { + if(block->dayNightDiffed() == false) + continue; + } +#endif + } + + /* + If block has been marked to not exist on disk (dummy) + and generating new ones is not wanted, skip block. + */ + if(generate == false && surely_not_found_on_disk == true) + { + // get next one. + continue; + } + + /* + Record the lowest d from which a block has been + found being not sent and possibly to exist + */ + if(no_blocks_found_for_sending) + { + if(generate == true) + new_nearest_unsent_d = d; + } + + no_blocks_found_for_sending = false; + + /* + Add inexistent block to emerge queue. + */ + if(block == NULL || surely_not_found_on_disk || block_is_invalid) + { + //TODO: Get value from somewhere + // Allow only one block in emerge queue + //if(server->m_emerge_queue.peerItemCount(peer_id) < 1) + // Allow two blocks in queue per client + if(server->m_emerge_queue.peerItemCount(peer_id) < 2) + { + //dstream<<"Adding block to emerge queue"<m_emerge_queue.addBlock(peer_id, p, flags); + server->m_emergethread.trigger(); + } + + // get next one. + continue; + } + + /* + Add block to send queue + */ + + PrioritySortedBlockTransfer q((float)d, p, peer_id); + + dest.push_back(q); + + num_blocks_selected += 1; + sending_something = true; + } + } +queue_full_break: + + //dstream<<"Stopped at "<= + g_settings.getS16("max_block_send_distance")) + { + // Pause time in seconds + m_nothing_to_send_pause_timer = 1.0; + /*dstream<<"nothing to send to " + <getPlayerName(peer_id) + <<" (d="< &stepped_blocks + ) +{ + DSTACK(__FUNCTION_NAME); + + // Can't send anything without knowing version + if(serialization_version == SER_FMT_VER_INVALID) + { + dstream<<"RemoteClient::SendObjectData(): Not sending, no version." + < players = server->m_env.getPlayers(true); + + // Write player count + u16 playercount = players.size(); + writeU16(buf, playercount); + os.write((char*)buf, 2); + + core::list::Iterator i; + for(i = players.begin(); + i != players.end(); i++) + { + Player *player = *i; + + v3f pf = player->getPosition(); + v3f sf = player->getSpeed(); + + v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100); + v3s32 speed_i (sf.X*100, sf.Y*100, sf.Z*100); + s32 pitch_i (player->getPitch() * 100); + s32 yaw_i (player->getYaw() * 100); + + writeU16(buf, player->peer_id); + os.write((char*)buf, 2); + writeV3S32(buf, position_i); + os.write((char*)buf, 12); + writeV3S32(buf, speed_i); + os.write((char*)buf, 12); + writeS32(buf, pitch_i); + os.write((char*)buf, 4); + writeS32(buf, yaw_i); + os.write((char*)buf, 4); + } + + /* + Get and write object data + */ + + /* + Get nearby blocks. + + For making players to be able to build to their nearby + environment (building is not possible on blocks that are not + in memory): + - Set blocks changed + - Add blocks to emerge queue if they are not found + + SUGGESTION: These could be ignored from the backside of the player + */ + + Player *player = server->m_env.getPlayer(peer_id); + + assert(player); + + v3f playerpos = player->getPosition(); + v3f playerspeed = player->getSpeed(); + + v3s16 center_nodepos = floatToInt(playerpos, BS); + v3s16 center = getNodeBlockPos(center_nodepos); + + s16 d_max = g_settings.getS16("active_object_range"); + + // Number of blocks whose objects were written to bos + u16 blockcount = 0; + + std::ostringstream bos(std::ios_base::binary); + + for(s16 d = 0; d <= d_max; d++) + { + core::list list; + getFacePositions(list, d); + + core::list::Iterator li; + for(li=list.begin(); li!=list.end(); li++) + { + v3s16 p = *li + center; + + /* + Ignore blocks that haven't been sent to the client + */ + { + if(m_blocks_sent.find(p) == NULL) + continue; + } + + // Try stepping block and add it to a send queue + try + { + + // Get block + MapBlock *block = server->m_env.getMap().getBlockNoCreate(p); + + /* + Step block if not in stepped_blocks and add to stepped_blocks. + */ + if(stepped_blocks.find(p) == NULL) + { + block->stepObjects(dtime, true, server->m_env.getDayNightRatio()); + stepped_blocks.insert(p, true); + block->setChangedFlag(); + } + + // Skip block if there are no objects + if(block->getObjectCount() == 0) + continue; + + /* + Write objects + */ + + // Write blockpos + writeV3S16(buf, p); + bos.write((char*)buf, 6); + + // Write objects + //block->serializeObjects(bos, serialization_version); // DEPRECATED + // count=0 + writeU16(bos, 0); + + blockcount++; + + /* + Stop collecting objects if data is already too big + */ + // Sum of player and object data sizes + s32 sum = (s32)os.tellp() + 2 + (s32)bos.tellp(); + // break out if data too big + if(sum > MAX_OBJECTDATA_SIZE) + { + goto skip_subsequent; + } + + } //try + catch(InvalidPositionException &e) + { + // Not in memory + // Add it to the emerge queue and trigger the thread. + // Fetch the block only if it is on disk. + + // Grab and increment counter + /*SharedPtr lock + (m_num_blocks_in_emerge_queue.getLock()); + m_num_blocks_in_emerge_queue.m_value++;*/ + + // Add to queue as an anonymous fetch from disk + u8 flags = BLOCK_EMERGE_FLAG_FROMDISK; + server->m_emerge_queue.addBlock(0, p, flags); + server->m_emergethread.trigger(); + } + } + } + +skip_subsequent: + + // Write block count + writeU16(buf, blockcount); + os.write((char*)buf, 2); + + // Write block objects + os< data((u8*)s.c_str(), s.size()); + // Send as unreliable + server->m_con.Send(peer_id, 0, data, false); +} + +void RemoteClient::GotBlock(v3s16 p) +{ + if(m_blocks_sending.find(p) != NULL) + m_blocks_sending.remove(p); + else + { + /*dstream<<"RemoteClient::GotBlock(): Didn't find in" + " m_blocks_sending"< &blocks) +{ + m_nearest_unsent_d = 0; + + for(core::map::Iterator + i = blocks.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + + if(m_blocks_sending.find(p) != NULL) + m_blocks_sending.remove(p); + if(m_blocks_sent.find(p) != NULL) + m_blocks_sent.remove(p); + } +} + +/* + PlayerInfo +*/ + +PlayerInfo::PlayerInfo() +{ + name[0] = 0; + avg_rtt = 0; +} + +void PlayerInfo::PrintLine(std::ostream *s) +{ + (*s)<::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + // Get client and check that it is valid + RemoteClient *client = i.getNode()->getValue(); + assert(client->peer_id == i.getNode()->getKey()); + if(client->serialization_version == SER_FMT_VER_INVALID) + continue; + + try{ + SendChatMessage(client->peer_id, line); + } + catch(con::PeerNotFoundException &e) + {} + } + } + + /* + Save players + */ + dstream<<"Server: Saving players"<::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + /*// Delete player + // NOTE: These are removed by env destructor + { + u16 peer_id = i.getNode()->getKey(); + JMutexAutoLock envlock(m_env_mutex); + m_env.removePlayer(peer_id); + }*/ + + // Delete client + delete i.getNode()->getValue(); + } + } +} + +void Server::start(unsigned short port) +{ + DSTACK(__FUNCTION_NAME); + // Stop thread if already running + m_thread.stop(); + + // Initialize connection + m_con.setTimeoutMs(30); + m_con.Serve(port); + + // Start thread + m_thread.setRun(true); + m_thread.Start(); + + dout_server<<"Server: Started on port "< 2.0) + dtime = 2.0; + { + JMutexAutoLock lock(m_step_dtime_mutex); + m_step_dtime += dtime; + } +} + +void Server::AsyncRunStep() +{ + DSTACK(__FUNCTION_NAME); + + float dtime; + { + JMutexAutoLock lock1(m_step_dtime_mutex); + dtime = m_step_dtime; + } + + { + ScopeProfiler sp(&g_profiler, "Server: selecting and sending " + "blocks to clients"); + // Send blocks to clients + SendBlocks(dtime); + } + + if(dtime < 0.001) + return; + + //dstream<<"Server steps "<::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + //Player *player = m_env.getPlayer(client->peer_id); + + SharedBuffer data = makePacket_TOCLIENT_TIME_OF_DAY( + m_env.getTimeOfDay()); + // Send as reliable + m_con.Send(client->peer_id, 0, data, true); + } + } + } + + { + JMutexAutoLock lock(m_env_mutex); + // Step environment + ScopeProfiler sp(&g_profiler, "Server: environment step"); + m_env.step(dtime); + } + + const float map_timer_and_unload_dtime = 5.15; + if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) + { + JMutexAutoLock lock(m_env_mutex); + // Run Map's timers and unload unused data + ScopeProfiler sp(&g_profiler, "Server: map timer and unload"); + m_env.getMap().timerUpdate(map_timer_and_unload_dtime, + g_settings.getFloat("server_unload_unused_data_timeout")); + } + + /* + Do background stuff + */ + + /* + Transform liquids + */ + m_liquid_transform_timer += dtime; + if(m_liquid_transform_timer >= 1.00) + { + m_liquid_transform_timer -= 1.00; + + JMutexAutoLock lock(m_env_mutex); + + ScopeProfiler sp(&g_profiler, "Server: liquid transform"); + + core::map modified_blocks; + m_env.getMap().transformLiquids(modified_blocks); +#if 0 + /* + Update lighting + */ + core::map lighting_modified_blocks; + ServerMap &map = ((ServerMap&)m_env.getMap()); + map.updateLighting(modified_blocks, lighting_modified_blocks); + + // Add blocks modified by lighting to modified_blocks + for(core::map::Iterator + i = lighting_modified_blocks.getIterator(); + i.atEnd() == false; i++) + { + MapBlock *block = i.getNode()->getValue(); + modified_blocks.insert(block->getPos(), block); + } +#endif + /* + Set the modified blocks unsent for all the clients + */ + + JMutexAutoLock lock2(m_con_mutex); + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + + if(modified_blocks.size() > 0) + { + // Remove block from sent history + client->SetBlocksNotSent(modified_blocks); + } + } + } + + // Periodically print some info + { + float &counter = m_print_info_timer; + counter += dtime; + if(counter >= 30.0) + { + counter = 0.0; + + JMutexAutoLock lock2(m_con_mutex); + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + //u16 peer_id = i.getNode()->getKey(); + RemoteClient *client = i.getNode()->getValue(); + Player *player = m_env.getPlayer(client->peer_id); + if(player==NULL) + continue; + std::cout<getName()<<"\t"; + client->PrintInfo(std::cout); + } + } + } + + //if(g_settings.getBool("enable_experimental")) + { + + /* + Check added and deleted active objects + */ + { + //dstream<<"Server: Checking added and deleted active objects"<::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + Player *player = m_env.getPlayer(client->peer_id); + if(player==NULL) + { + // This can happen if the client timeouts somehow + /*dstream<<"WARNING: "<<__FUNCTION_NAME<<": Client " + <peer_id + <<" has no associated player"<getPosition(), BS); + + core::map removed_objects; + core::map added_objects; + m_env.getRemovedActiveObjects(pos, radius, + client->m_known_objects, removed_objects); + m_env.getAddedActiveObjects(pos, radius, + client->m_known_objects, added_objects); + + // Ignore if nothing happened + if(removed_objects.size() == 0 && added_objects.size() == 0) + { + //dstream<<"INFO: active objects: none changed"<::Iterator + i = removed_objects.getIterator(); + i.atEnd()==false; i++) + { + // Get object + u16 id = i.getNode()->getKey(); + ServerActiveObject* obj = m_env.getActiveObject(id); + + // Add to data buffer for sending + writeU16((u8*)buf, i.getNode()->getKey()); + data_buffer.append(buf, 2); + + // Remove from known objects + client->m_known_objects.remove(i.getNode()->getKey()); + + if(obj && obj->m_known_by_count > 0) + obj->m_known_by_count--; + } + + // Handle added objects + writeU16((u8*)buf, added_objects.size()); + data_buffer.append(buf, 2); + for(core::map::Iterator + i = added_objects.getIterator(); + i.atEnd()==false; i++) + { + // Get object + u16 id = i.getNode()->getKey(); + ServerActiveObject* obj = m_env.getActiveObject(id); + + // Get object type + u8 type = ACTIVEOBJECT_TYPE_INVALID; + if(obj == NULL) + dstream<<"WARNING: "<<__FUNCTION_NAME + <<": NULL object"<getType(); + + // Add to data buffer for sending + writeU16((u8*)buf, id); + data_buffer.append(buf, 2); + writeU8((u8*)buf, type); + data_buffer.append(buf, 1); + + if(obj) + data_buffer.append(serializeLongString( + obj->getClientInitializationData())); + else + data_buffer.append(serializeLongString("")); + + // Add to known objects + client->m_known_objects.insert(i.getNode()->getKey(), false); + + if(obj) + obj->m_known_by_count++; + } + + // Send packet + SharedBuffer reply(2 + data_buffer.size()); + writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD); + memcpy((char*)&reply[2], data_buffer.c_str(), + data_buffer.size()); + // Send as reliable + m_con.Send(client->peer_id, 0, reply, true); + + dstream<<"INFO: Server: Sent object remove/add: " + < all_known_objects; + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + // Go through all known objects of client + for(core::map::Iterator + i = client->m_known_objects.getIterator(); + i.atEnd()==false; i++) + { + u16 id = i.getNode()->getKey(); + all_known_objects[id] = true; + } + } + + m_env.setKnownActiveObjects(whatever); +#endif + + } + + /* + Send object messages + */ + { + JMutexAutoLock envlock(m_env_mutex); + JMutexAutoLock conlock(m_con_mutex); + + ScopeProfiler sp(&g_profiler, "Server: sending object messages"); + + // Key = object id + // Value = data sent by object + core::map* > buffered_messages; + + // Get active object messages from environment + for(;;) + { + ActiveObjectMessage aom = m_env.getActiveObjectMessage(); + if(aom.id == 0) + break; + + core::list* message_list = NULL; + core::map* >::Node *n; + n = buffered_messages.find(aom.id); + if(n == NULL) + { + message_list = new core::list; + buffered_messages.insert(aom.id, message_list); + } + else + { + message_list = n->getValue(); + } + message_list->push_back(aom); + } + + // Route data to every client + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd()==false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + std::string reliable_data; + std::string unreliable_data; + // Go through all objects in message buffer + for(core::map* >::Iterator + j = buffered_messages.getIterator(); + j.atEnd()==false; j++) + { + // If object is not known by client, skip it + u16 id = j.getNode()->getKey(); + if(client->m_known_objects.find(id) == NULL) + continue; + // Get message list of object + core::list* list = j.getNode()->getValue(); + // Go through every message + for(core::list::Iterator + k = list->begin(); k != list->end(); k++) + { + // Compose the full new data with header + ActiveObjectMessage aom = *k; + std::string new_data; + // Add object id + char buf[2]; + writeU16((u8*)&buf[0], aom.id); + new_data.append(buf, 2); + // Add data + new_data += serializeString(aom.datastring); + // Add data to buffer + if(aom.reliable) + reliable_data += new_data; + else + unreliable_data += new_data; + } + } + /* + reliable_data and unreliable_data are now ready. + Send them. + */ + if(reliable_data.size() > 0) + { + SharedBuffer reply(2 + reliable_data.size()); + writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES); + memcpy((char*)&reply[2], reliable_data.c_str(), + reliable_data.size()); + // Send as reliable + m_con.Send(client->peer_id, 0, reply, true); + } + if(unreliable_data.size() > 0) + { + SharedBuffer reply(2 + unreliable_data.size()); + writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES); + memcpy((char*)&reply[2], unreliable_data.c_str(), + unreliable_data.size()); + // Send as unreliable + m_con.Send(client->peer_id, 0, reply, false); + } + + /*if(reliable_data.size() > 0 || unreliable_data.size() > 0) + { + dstream<<"INFO: Server: Size of object message data: " + <<"reliable: "<* >::Iterator + i = buffered_messages.getIterator(); + i.atEnd()==false; i++) + { + delete i.getNode()->getValue(); + } + } + + } // enable_experimental + + /* + Send queued-for-sending map edit events. + */ + { + // Don't send too many at a time + //u32 count = 0; + + // Single change sending is disabled if queue size is not small + bool disable_single_change_sending = false; + if(m_unsent_map_edit_queue.size() >= 4) + disable_single_change_sending = true; + + bool got_any_events = false; + + // We'll log the amount of each + Profiler prof; + + while(m_unsent_map_edit_queue.size() != 0) + { + got_any_events = true; + + MapEditEvent* event = m_unsent_map_edit_queue.pop_front(); + + // Players far away from the change are stored here. + // Instead of sending the changes, MapBlocks are set not sent + // for them. + core::list far_players; + + if(event->type == MEET_ADDNODE) + { + //dstream<<"Server: MEET_ADDNODE"<p, event->n, event->already_known_by_peer, + &far_players, 5); + else + sendAddNode(event->p, event->n, event->already_known_by_peer, + &far_players, 30); + } + else if(event->type == MEET_REMOVENODE) + { + //dstream<<"Server: MEET_REMOVENODE"<p, event->already_known_by_peer, + &far_players, 5); + else + sendRemoveNode(event->p, event->already_known_by_peer, + &far_players, 30); + } + else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED) + { + dstream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<p); + } + else if(event->type == MEET_OTHER) + { + dstream<<"Server: MEET_OTHER"<::Iterator + i = event->modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + setBlockNotSent(p); + } + } + else + { + prof.add("unknown", 1); + dstream<<"WARNING: Server: Unknown MapEditEvent " + <<((u32)event->type)< 0) + { + // Convert list format to that wanted by SetBlocksNotSent + core::map modified_blocks2; + for(core::map::Iterator + i = event->modified_blocks.getIterator(); + i.atEnd()==false; i++) + { + v3s16 p = i.getNode()->getKey(); + modified_blocks2.insert(p, + m_env.getMap().getBlockNoCreateNoEx(p)); + } + // Set blocks not sent + for(core::list::Iterator + i = far_players.begin(); + i != far_players.end(); i++) + { + u16 peer_id = *i; + RemoteClient *client = getClient(peer_id); + if(client==NULL) + continue; + client->SetBlocksNotSent(modified_blocks2); + } + } + + delete event; + + /*// Don't send too many at a time + count++; + if(count >= 1 && m_unsent_map_edit_queue.size() < 100) + break;*/ + } + + if(got_any_events) + { + dstream<<"Server: MapEditEvents:"<= g_settings.getFloat("objectdata_interval")) + { + JMutexAutoLock lock1(m_env_mutex); + JMutexAutoLock lock2(m_con_mutex); + + ScopeProfiler sp(&g_profiler, "Server: sending mbo positions"); + + SendObjectData(counter); + + counter = 0.0; + } + } + + /* + Trigger emergethread (it somehow gets to a non-triggered but + bysy state sometimes) + */ + { + float &counter = m_emergethread_trigger_timer; + counter += dtime; + if(counter >= 2.0) + { + counter = 0.0; + + m_emergethread.trigger(); + } + } + + // Save map, players and auth stuff + { + float &counter = m_savemap_timer; + counter += dtime; + if(counter >= g_settings.getFloat("server_map_save_interval")) + { + counter = 0.0; + + ScopeProfiler sp(&g_profiler, "Server: saving stuff"); + + // Auth stuff + if(m_authmanager.isModified()) + m_authmanager.save(); + + //Bann stuff + if(m_banmanager.isModified()) + m_banmanager.save(); + + // Map + JMutexAutoLock lock(m_env_mutex); + + /*// Unload unused data (delete from memory) + m_env.getMap().unloadUnusedData( + g_settings.getFloat("server_unload_unused_sectors_timeout")); + */ + /*u32 deleted_count = m_env.getMap().unloadUnusedData( + g_settings.getFloat("server_unload_unused_sectors_timeout")); + */ + + // Save only changed parts + m_env.getMap().save(true); + + /*if(deleted_count > 0) + { + dout_server<<"Server: Unloaded "< data(data_maxsize); + u16 peer_id; + u32 datasize; + try{ + { + JMutexAutoLock conlock(m_con_mutex); + datasize = m_con.Receive(peer_id, *data, data_maxsize); + } + + // This has to be called so that the client list gets synced + // with the peer list of the connection + handlePeerChanges(); + + ProcessData(*data, datasize, peer_id); + } + catch(con::InvalidIncomingDataException &e) + { + derr_server<<"Server::Receive(): " + "InvalidIncomingDataException: what()=" + <address.serializeString())){ + SendAccessDenied(m_con, peer_id, + L"Your ip is banned. Banned name was " + +narrow_to_wide(m_banmanager.getBanName( + peer->address.serializeString()))); + m_con.deletePeer(peer_id, false); + return; + } + + u8 peer_ser_ver = getClient(peer->id)->serialization_version; + + try + { + + if(datasize < 2) + return; + + ToServerCommand command = (ToServerCommand)readU16(&data[0]); + + if(command == TOSERVER_INIT) + { + // [0] u16 TOSERVER_INIT + // [2] u8 SER_FMT_VER_HIGHEST + // [3] u8[20] player_name + // [23] u8[28] password <--- can be sent without this, from old versions + + if(datasize < 2+1+PLAYERNAME_SIZE) + return; + + derr_server<id<serialization_version = deployed; + getClient(peer->id)->pending_serialization_version = deployed; + + if(deployed == SER_FMT_VER_INVALID) + { + derr_server<= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2) + { + net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]); + } + + getClient(peer->id)->net_proto_version = net_proto_version; + + if(net_proto_version == 0) + { + SendAccessDenied(m_con, peer_id, + L"Your client is too old. Please upgrade."); + return; + } + + /* Uhh... this should actually be a warning but let's do it like this */ + if(net_proto_version < 2) + { + SendAccessDenied(m_con, peer_id, + L"Your client is too old. Please upgrade."); + return; + } + + /* + Set up player + */ + + // Get player name + char playername[PLAYERNAME_SIZE]; + for(u32 i=0; iserialize(test_os); + dstream<<"Player serialization test: \""<deSerialize(test_is); + }*/ + + // If failed, cancel + if(player == NULL) + { + derr_server<peer_id != 0) + { + derr_server<peer_id = peer_id; + */ + + // Check if player doesn't exist + if(player == NULL) + throw con::InvalidIncomingDataException + ("Server::ProcessData(): INIT: Player doesn't exist"); + + /*// update name if it was supplied + if(datasize >= 20+3) + { + data[20+3-1] = 0; + player->updateName((const char*)&data[3]); + }*/ + + /* + Answer with a TOCLIENT_INIT + */ + { + SharedBuffer reply(2+1+6+8); + writeU16(&reply[0], TOCLIENT_INIT); + writeU8(&reply[2], deployed); + writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS)); + writeU64(&reply[2+1+6], m_env.getServerMap().getSeed()); + + // Send as reliable + m_con.Send(peer_id, 0, reply, true); + } + + /* + Send complete position information + */ + SendMovePlayer(player); + + return; + } + + if(command == TOSERVER_INIT2) + { + derr_server<id<id)->serialization_version + = getClient(peer->id)->pending_serialization_version; + + /* + Send some initialization data + */ + + // Send player info to all players + SendPlayerInfos(); + + // Send inventory to player + UpdateCrafting(peer->id); + SendInventory(peer->id); + + // Send player items to all players + SendPlayerItems(); + + // Send HP + { + Player *player = m_env.getPlayer(peer_id); + SendPlayerHP(player); + } + + // Send time of day + { + SharedBuffer data = makePacket_TOCLIENT_TIME_OF_DAY( + m_env.getTimeOfDay()); + m_con.Send(peer->id, 0, data, true); + } + + // Send information about server to player in chat + SendChatMessage(peer_id, getStatusString()); + + // Send information about joining in chat + { + std::wstring name = L"unknown"; + Player *player = m_env.getPlayer(peer_id); + if(player != NULL) + name = narrow_to_wide(player->getName()); + + std::wstring message; + message += L"*** "; + message += name; + message += L" joined game"; + BroadcastChatMessage(message); + } + + // Warnings about protocol version can be issued here + /*if(getClient(peer->id)->net_proto_version == 0) + { + SendChatMessage(peer_id, L"# Server: NOTE: YOUR CLIENT IS OLD AND DOES NOT WORK PROPERLY WITH THIS SERVER"); + }*/ + + return; + } + + if(peer_ser_ver == SER_FMT_VER_INVALID) + { + derr_server<GotBlock(p); + } + } + else if(command == TOSERVER_DELETEDBLOCKS) + { + if(datasize < 2+1) + return; + + /* + [0] u16 command + [2] u8 count + [3] v3s16 pos_0 + [3+6] v3s16 pos_1 + ... + */ + + u16 count = data[2]; + for(u16 i=0; iSetBlockNotSent(p); + } + } + else if(command == TOSERVER_CLICK_OBJECT) + { + if(datasize < 13) + return; + + if((getPlayerPrivs(player) & PRIV_BUILD) == 0) + return; + + /* + [0] u16 command + [2] u8 button (0=left, 1=right) + [3] v3s16 block + [9] s16 id + [11] u16 item + */ + u8 button = readU8(&data[2]); + v3s16 p; + p.X = readS16(&data[3]); + p.Y = readS16(&data[5]); + p.Z = readS16(&data[7]); + s16 id = readS16(&data[9]); + //u16 item_i = readU16(&data[11]); + + MapBlock *block = NULL; + try + { + block = m_env.getMap().getBlockNoCreate(p); + } + catch(InvalidPositionException &e) + { + derr_server<<"CLICK_OBJECT block not found"<getObject(id); + + if(obj == NULL) + { + derr_server<<"CLICK_OBJECT object not found"<inventory.getList("main"); + if(g_settings.getBool("creative_mode") == false && ilist != NULL) + { + + // Skip if inventory has no free space + if(ilist->getUsedSlots() == ilist->getSize()) + { + dout_server<<"Player inventory has no free space"<getTypeId() == MAPBLOCKOBJECT_TYPE_ITEM) + { + item = ((ItemObject*)obj)->createInventoryItem(); + } + // Else create an item of the object + else + { + item = new MapBlockObjectItem + (obj->getInventoryString()); + } + + // Add to inventory and send inventory + ilist->addItem(item); + UpdateCrafting(player->peer_id); + SendInventory(player->peer_id); + } + + // Remove from block + block->removeObject(id); + } + } + else if(command == TOSERVER_CLICK_ACTIVEOBJECT) + { + if(datasize < 7) + return; + + if((getPlayerPrivs(player) & PRIV_BUILD) == 0) + return; + + /* + length: 7 + [0] u16 command + [2] u8 button (0=left, 1=right) + [3] u16 id + [5] u16 item + */ + u8 button = readU8(&data[2]); + u16 id = readS16(&data[3]); + u16 item_i = readU16(&data[11]); + + ServerActiveObject *obj = m_env.getActiveObject(id); + + if(obj == NULL) + { + derr_server<<"Server: CLICK_ACTIVEOBJECT: object not found" + <m_removed) + return; + + //TODO: Check that object is reasonably close + + // Left click, pick object up (usually) + if(button == 0) + { + /* + Try creating inventory item + */ + InventoryItem *item = obj->createPickedUpItem(); + + if(item) + { + InventoryList *ilist = player->inventory.getList("main"); + if(ilist != NULL) + { + if(g_settings.getBool("creative_mode") == false) + { + // Skip if inventory has no free space + if(ilist->roomForItem(item) == false) + { + dout_server<<"Player inventory has no free space"<addItem(item); + UpdateCrafting(player->peer_id); + SendInventory(player->peer_id); + } + + // Remove object from environment + obj->m_removed = true; + } + } + else + { + /* + Item cannot be picked up. Punch it instead. + */ + + ToolItem *titem = NULL; + std::string toolname = ""; + + InventoryList *mlist = player->inventory.getList("main"); + if(mlist != NULL) + { + InventoryItem *item = mlist->getItem(item_i); + if(item && (std::string)item->getName() == "ToolItem") + { + titem = (ToolItem*)item; + toolname = titem->getToolName(); + } + } + + v3f playerpos = player->getPosition(); + v3f objpos = obj->getBasePosition(); + v3f dir = (objpos - playerpos).normalize(); + + u16 wear = obj->punch(toolname, dir); + + if(titem) + { + bool weared_out = titem->addWear(wear); + if(weared_out) + mlist->deleteItem(item_i); + SendInventory(player->peer_id); + } + } + } + // Right click, do something with object + if(button == 1) + { + // Track hp changes super-crappily + u16 oldhp = player->hp; + + // Do stuff + obj->rightClick(player); + + // Send back stuff + if(player->hp != oldhp) + { + SendPlayerHP(player); + } + } + } + else if(command == TOSERVER_GROUND_ACTION) + { + if(datasize < 17) + return; + /* + length: 17 + [0] u16 command + [2] u8 action + [3] v3s16 nodepos_undersurface + [9] v3s16 nodepos_abovesurface + [15] u16 item + actions: + 0: start digging + 1: place block + 2: stop digging (all parameters ignored) + 3: digging completed + */ + u8 action = readU8(&data[2]); + v3s16 p_under; + p_under.X = readS16(&data[3]); + p_under.Y = readS16(&data[5]); + p_under.Z = readS16(&data[7]); + v3s16 p_over; + p_over.X = readS16(&data[9]); + p_over.Y = readS16(&data[11]); + p_over.Z = readS16(&data[13]); + u16 item_i = readU16(&data[15]); + + //TODO: Check that target is reasonably close + + /* + 0: start digging + */ + if(action == 0) + { + /* + NOTE: This can be used in the future to check if + somebody is cheating, by checking the timing. + */ + } // action == 0 + + /* + 2: stop digging + */ + else if(action == 2) + { +#if 0 + RemoteClient *client = getClient(peer->id); + JMutexAutoLock digmutex(client->m_dig_mutex); + client->m_dig_tool_item = -1; +#endif + } + + /* + 3: Digging completed + */ + else if(action == 3) + { + // Mandatory parameter; actually used for nothing + core::map modified_blocks; + + content_t material = CONTENT_IGNORE; + u8 mineral = MINERAL_NONE; + + bool cannot_remove_node = false; + + try + { + MapNode n = m_env.getMap().getNode(p_under); + // Get mineral + mineral = n.getMineral(); + // Get material at position + material = n.getContent(); + // If not yet cancelled + if(cannot_remove_node == false) + { + // If it's not diggable, do nothing + if(content_diggable(material) == false) + { + derr_server<<"Server: Not finishing digging: " + <<"Node not diggable" + <nodeRemovalDisabled() == true) + { + derr_server<<"Server: Not finishing digging: " + <<"Node metadata disables removal" + <getName()<<" cannot remove node" + <<" because privileges are "<SetBlockNotSent(blockpos); + + return; + } + + /* + Send the removal to all close-by players. + - If other player is close, send REMOVENODE + - Otherwise set blocks not sent + */ + core::list far_players; + sendRemoveNode(p_under, peer_id, &far_players, 30); + + /* + Update and send inventory + */ + + if(g_settings.getBool("creative_mode") == false) + { + /* + Wear out tool + */ + InventoryList *mlist = player->inventory.getList("main"); + if(mlist != NULL) + { + InventoryItem *item = mlist->getItem(item_i); + if(item && (std::string)item->getName() == "ToolItem") + { + ToolItem *titem = (ToolItem*)item; + std::string toolname = titem->getToolName(); + + // Get digging properties for material and tool + DiggingProperties prop = + getDiggingProperties(material, toolname); + + if(prop.diggable == false) + { + derr_server<<"Server: WARNING: Player digged" + <<" with impossible material + tool" + <<" combination"<addWear(prop.wear); + + if(weared_out) + { + mlist->deleteItem(item_i); + } + } + } + + /* + Add dug item to inventory + */ + + InventoryItem *item = NULL; + + if(mineral != MINERAL_NONE) + item = getDiggedMineralItem(mineral); + + // If not mineral + if(item == NULL) + { + std::string &dug_s = content_features(material).dug_item; + if(dug_s != "") + { + std::istringstream is(dug_s, std::ios::binary); + item = InventoryItem::deSerialize(is); + } + } + + if(item != NULL) + { + // Add a item to inventory + player->inventory.addItem("main", item); + + // Send inventory + UpdateCrafting(player->peer_id); + SendInventory(player->peer_id); + } + } + + /* + Remove the node + (this takes some time so it is done after the quick stuff) + */ + { + MapEditEventIgnorer ign(&m_ignore_map_edit_events); + + m_env.getMap().removeNodeAndUpdate(p_under, modified_blocks); + } + /* + Set blocks not sent to far players + */ + for(core::list::Iterator + i = far_players.begin(); + i != far_players.end(); i++) + { + u16 peer_id = *i; + RemoteClient *client = getClient(peer_id); + if(client==NULL) + continue; + client->SetBlocksNotSent(modified_blocks); + } + } + + /* + 1: place block + */ + else if(action == 1) + { + + InventoryList *ilist = player->inventory.getList("main"); + if(ilist == NULL) + return; + + // Get item + InventoryItem *item = ilist->getItem(item_i); + + // If there is no item, it is not possible to add it anywhere + if(item == NULL) + return; + + /* + Handle material items + */ + if(std::string("MaterialItem") == item->getName()) + { + try{ + // Don't add a node if this is not a free space + MapNode n2 = m_env.getMap().getNode(p_over); + bool no_enough_privs = + ((getPlayerPrivs(player) & PRIV_BUILD)==0); + if(no_enough_privs) + dstream<<"Player "<getName()<<" cannot add node" + <<" because privileges are "<SetBlockNotSent(blockpos); + return; + } + } + catch(InvalidPositionException &e) + { + derr_server<<"Server: Ignoring ADDNODE: Node not found" + <<" Adding block to emerge queue." + <id)->m_time_from_building = 0.0; + + // Create node data + MaterialItem *mitem = (MaterialItem*)item; + MapNode n; + n.setContent(mitem->getMaterial()); + + // Calculate direction for wall mounted stuff + if(content_features(n).wall_mounted) + n.param2 = packDir(p_under - p_over); + + // Calculate the direction for furnaces and chests and stuff + if(content_features(n).param_type == CPT_FACEDIR_SIMPLE) + { + v3f playerpos = player->getPosition(); + v3f blockpos = intToFloat(p_over, BS) - playerpos; + blockpos = blockpos.normalize(); + n.param1 = 0; + if (fabs(blockpos.X) > fabs(blockpos.Z)) { + if (blockpos.X < 0) + n.param1 = 3; + else + n.param1 = 1; + } else { + if (blockpos.Z < 0) + n.param1 = 2; + else + n.param1 = 0; + } + } + + /* + Send to all close-by players + */ + core::list far_players; + sendAddNode(p_over, n, 0, &far_players, 30); + + /* + Handle inventory + */ + InventoryList *ilist = player->inventory.getList("main"); + if(g_settings.getBool("creative_mode") == false && ilist) + { + // Remove from inventory and send inventory + if(mitem->getCount() == 1) + ilist->deleteItem(item_i); + else + mitem->remove(1); + // Send inventory + UpdateCrafting(peer_id); + SendInventory(peer_id); + } + + /* + Add node. + + This takes some time so it is done after the quick stuff + */ + core::map modified_blocks; + { + MapEditEventIgnorer ign(&m_ignore_map_edit_events); + + m_env.getMap().addNodeAndUpdate(p_over, n, modified_blocks); + } + /* + Set blocks not sent to far players + */ + for(core::list::Iterator + i = far_players.begin(); + i != far_players.end(); i++) + { + u16 peer_id = *i; + RemoteClient *client = getClient(peer_id); + if(client==NULL) + continue; + client->SetBlocksNotSent(modified_blocks); + } + + /* + Calculate special events + */ + + /*if(n.d == CONTENT_MESE) + { + u32 count = 0; + for(s16 z=-1; z<=1; z++) + for(s16 y=-1; y<=1; y++) + for(s16 x=-1; x<=1; x++) + { + + } + }*/ + } + /* + Place other item (not a block) + */ + else + { + v3s16 blockpos = getNodeBlockPos(p_over); + + /* + Check that the block is loaded so that the item + can properly be added to the static list too + */ + MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos); + if(block==NULL) + { + derr_server<<"Error while placing object: " + "block not found"<createSAO(&m_env, 0, pos); + + if(obj == NULL) + { + derr_server<<"WARNING: item resulted in NULL object, " + <<"not placing onto map" + <getDropCount(); + + // Delete item if all gone + if(item->getCount() <= dropcount) + { + if(item->getCount() < dropcount) + dstream<<"WARNING: Server: dropped more items" + <<" than the slot contains"<inventory.getList("main"); + if(ilist) + // Remove from inventory and send inventory + ilist->deleteItem(item_i); + } + // Else decrement it + else + item->remove(dropcount); + + // Send inventory + UpdateCrafting(peer_id); + SendInventory(peer_id); + } + } + } + + } // action == 1 + + /* + Catch invalid actions + */ + else + { + derr_server<<"WARNING: Server: Invalid action " + <getObject(id); + if(obj == NULL) + { + derr_server<<"Error while setting sign text: " + "object not found"<getTypeId() != MAPBLOCKOBJECT_TYPE_SIGN) + { + derr_server<<"Error while setting sign text: " + "object is not a sign"<setText(text); + + obj->getBlock()->setChangedFlag(); + } + else if(command == TOSERVER_SIGNNODETEXT) + { + if((getPlayerPrivs(player) & PRIV_BUILD) == 0) + return; + /* + u16 command + v3s16 p + u16 textlen + textdata + */ + std::string datastring((char*)&data[2], datasize-2); + std::istringstream is(datastring, std::ios_base::binary); + u8 buf[6]; + // Read stuff + is.read((char*)buf, 6); + v3s16 p = readV3S16(buf); + is.read((char*)buf, 2); + u16 textlen = readU16(buf); + std::string text; + for(u16 i=0; itypeId() != CONTENT_SIGN_WALL) + return; + SignNodeMetadata *signmeta = (SignNodeMetadata*)meta; + signmeta->setText(text); + + v3s16 blockpos = getNodeBlockPos(p); + MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos); + if(block) + { + block->setChangedFlag(); + } + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd()==false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + client->SetBlockNotSent(blockpos); + } + } + else if(command == TOSERVER_INVENTORY_ACTION) + { + /*// Ignore inventory changes if in creative mode + if(g_settings.getBool("creative_mode") == true) + { + dstream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode" + <to_inv == "current_player" && + ma->from_inv == "current_player") + { + InventoryList *rlist = player->inventory.getList("craftresult"); + assert(rlist); + InventoryList *clist = player->inventory.getList("craft"); + assert(clist); + InventoryList *mlist = player->inventory.getList("main"); + assert(mlist); + /* + Craftresult is no longer preview if something + is moved into it + */ + if(ma->to_list == "craftresult" + && ma->from_list != "craftresult") + { + // If it currently is a preview, remove + // its contents + if(player->craftresult_is_preview) + { + rlist->deleteItem(0); + } + player->craftresult_is_preview = false; + } + /* + Crafting takes place if this condition is true. + */ + if(player->craftresult_is_preview && + ma->from_list == "craftresult") + { + player->craftresult_is_preview = false; + clist->decrementMaterials(1); + } + /* + If the craftresult is placed on itself, move it to + main inventory instead of doing the action + */ + if(ma->to_list == "craftresult" + && ma->from_list == "craftresult") + { + disable_action = true; + + InventoryItem *item1 = rlist->changeItem(0, NULL); + mlist->addItem(item1); + } + } + // Disallow moving items if not allowed to build + else if((getPlayerPrivs(player) & PRIV_BUILD) == 0) + return; + } + + if(disable_action == false) + { + // Feed action to player inventory + a->apply(&c, this); + // Eat the action + delete a; + } + else + { + // Send inventory + UpdateCrafting(player->peer_id); + SendInventory(player->peer_id); + } + } + else + { + dstream<<"TOSERVER_INVENTORY_ACTION: " + <<"InventoryAction::deSerialize() returned NULL" + <getName()); + + // Line to send to players + std::wstring line; + // Whether to send to the player that sent the line + bool send_to_sender = false; + // Whether to send to other players + bool send_to_others = false; + + // Local player gets all privileges regardless of + // what's set on their account. + u64 privs = getPlayerPrivs(player); + + // Parse commands + if(message[0] == L'/') + { + size_t strip_size = 1; + if (message[1] == L'#') // support old-style commans + ++strip_size; + message = message.substr(strip_size); + + WStrfnd f1(message); + f1.next(L" "); // Skip over /#whatever + std::wstring paramstring = f1.next(L""); + + ServerCommandContext *ctx = new ServerCommandContext( + str_split(message, L' '), + paramstring, + this, + &m_env, + player, + privs); + + std::wstring reply(processServerCommand(ctx)); + send_to_sender = ctx->flags & SEND_TO_SENDER; + send_to_others = ctx->flags & SEND_TO_OTHERS; + + if (ctx->flags & SEND_NO_PREFIX) + line += reply; + else + line += L"Server: " + reply; + + delete ctx; + + } + else + { + if(privs & PRIV_SHOUT) + { + line += L"<"; + line += name; + line += L"> "; + line += message; + send_to_others = true; + } + else + { + line += L"Server: You are not allowed to shout"; + send_to_sender = true; + } + } + + if(line != L"") + { + dstream<<"CHAT: "<::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + // Get client and check that it is valid + RemoteClient *client = i.getNode()->getValue(); + assert(client->peer_id == i.getNode()->getKey()); + if(client->serialization_version == SER_FMT_VER_INVALID) + continue; + + // Filter recipient + bool sender_selected = (peer_id == client->peer_id); + if(sender_selected == true && send_to_sender == false) + continue; + if(sender_selected == false && send_to_others == false) + continue; + + SendChatMessage(client->peer_id, line); + } + } + } + else if(command == TOSERVER_DAMAGE) + { + if(g_settings.getBool("enable_damage")) + { + std::string datastring((char*)&data[2], datasize-2); + std::istringstream is(datastring, std::ios_base::binary); + u8 damage = readU8(is); + if(player->hp > damage) + { + player->hp -= damage; + } + else + { + player->hp = 0; + + dstream<<"TODO: Server: TOSERVER_HP_DECREMENT: Player dies" + <setPosition(pos); + player->hp = 20; + SendMovePlayer(player); + SendPlayerHP(player); + + //TODO: Throw items around + } + } + + SendPlayerHP(player); + } + else if(command == TOSERVER_PASSWORD) + { + /* + [0] u16 TOSERVER_PASSWORD + [2] u8[28] old password + [30] u8[28] new password + */ + + if(datasize != 2+PASSWORD_SIZE*2) + return; + /*char password[PASSWORD_SIZE]; + for(u32 i=0; igetName(); + + if(m_authmanager.exists(playername) == false) + { + dstream<<"Server: playername not found in authmanager"<wieldItem(item); + SendWieldedItem(player); + } + else + { + derr_server<<"WARNING: Server::ProcessData(): Ignoring " + "unknown command "<clone(); + m_unsent_map_edit_queue.push_back(e); +} + +Inventory* Server::getInventory(InventoryContext *c, std::string id) +{ + if(id == "current_player") + { + assert(c->current_player); + return &(c->current_player->inventory); + } + + Strfnd fn(id); + std::string id0 = fn.next(":"); + + if(id0 == "nodemeta") + { + v3s16 p; + p.X = stoi(fn.next(",")); + p.Y = stoi(fn.next(",")); + p.Z = stoi(fn.next(",")); + NodeMetadata *meta = m_env.getMap().getNodeMetadata(p); + if(meta) + return meta->getInventory(); + dstream<<"nodemeta at ("<current_player); + // Send inventory + UpdateCrafting(c->current_player->peer_id); + SendInventory(c->current_player->peer_id); + return; + } + + Strfnd fn(id); + std::string id0 = fn.next(":"); + + if(id0 == "nodemeta") + { + v3s16 p; + p.X = stoi(fn.next(",")); + p.Y = stoi(fn.next(",")); + p.Z = stoi(fn.next(",")); + v3s16 blockpos = getNodeBlockPos(p); + + NodeMetadata *meta = m_env.getMap().getNodeMetadata(p); + if(meta) + meta->inventoryModified(); + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd()==false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + client->SetBlockNotSent(blockpos); + } + + return; + } + + dstream<<__FUNCTION_NAME<<": unknown id "< Server::getPlayerInfo() +{ + DSTACK(__FUNCTION_NAME); + JMutexAutoLock envlock(m_env_mutex); + JMutexAutoLock conlock(m_con_mutex); + + core::list list; + + core::list players = m_env.getPlayers(); + + core::list::Iterator i; + for(i = players.begin(); + i != players.end(); i++) + { + PlayerInfo info; + + Player *player = *i; + + try{ + con::Peer *peer = m_con.GetPeer(player->peer_id); + // Copy info from peer to info struct + info.id = peer->id; + info.address = peer->address; + info.avg_rtt = peer->avg_rtt; + } + catch(con::PeerNotFoundException &e) + { + // Set dummy peer info + info.id = 0; + info.address = Address(0,0,0,0,0); + info.avg_rtt = 0.0; + } + + snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName()); + info.position = player->getPosition(); + + list.push_back(info); + } + + return list; +} + + +void Server::peerAdded(con::Peer *peer) +{ + DSTACK(__FUNCTION_NAME); + dout_server<<"Server::peerAdded(): peer->id=" + <id<id; + c.timeout = false; + m_peer_change_queue.push_back(c); +} + +void Server::deletingPeer(con::Peer *peer, bool timeout) +{ + DSTACK(__FUNCTION_NAME); + dout_server<<"Server::deletingPeer(): peer->id=" + <id<<", timeout="<id; + c.timeout = timeout; + m_peer_change_queue.push_back(c); +} + +/* + Static send methods +*/ + +void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp) +{ + DSTACK(__FUNCTION_NAME); + std::ostringstream os(std::ios_base::binary); + + writeU16(os, TOCLIENT_HP); + writeU8(os, hp); + + // Make data buffer + std::string s = os.str(); + SharedBuffer data((u8*)s.c_str(), s.size()); + // Send as reliable + con.Send(peer_id, 0, data, true); +} + +void Server::SendAccessDenied(con::Connection &con, u16 peer_id, + const std::wstring &reason) +{ + DSTACK(__FUNCTION_NAME); + std::ostringstream os(std::ios_base::binary); + + writeU16(os, TOCLIENT_ACCESS_DENIED); + os< data((u8*)s.c_str(), s.size()); + // Send as reliable + con.Send(peer_id, 0, data, true); +} + +/* + Non-static send methods +*/ + +void Server::SendObjectData(float dtime) +{ + DSTACK(__FUNCTION_NAME); + + core::map stepped_blocks; + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + u16 peer_id = i.getNode()->getKey(); + RemoteClient *client = i.getNode()->getValue(); + assert(client->peer_id == peer_id); + + if(client->serialization_version == SER_FMT_VER_INVALID) + continue; + + client->SendObjectData(this, dtime, stepped_blocks); + } +} + +void Server::SendPlayerInfos() +{ + DSTACK(__FUNCTION_NAME); + + //JMutexAutoLock envlock(m_env_mutex); + + // Get connected players + core::list players = m_env.getPlayers(true); + + u32 player_count = players.getSize(); + u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count; + + SharedBuffer data(datasize); + writeU16(&data[0], TOCLIENT_PLAYERINFO); + + u32 start = 2; + core::list::Iterator i; + for(i = players.begin(); + i != players.end(); i++) + { + Player *player = *i; + + /*dstream<<"Server sending player info for player with " + "peer_id="<peer_id<peer_id); + memset((char*)&data[start+2], 0, PLAYERNAME_SIZE); + snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName()); + start += 2+PLAYERNAME_SIZE; + } + + //JMutexAutoLock conlock(m_con_mutex); + + // Send as reliable + m_con.SendToAll(0, data, true); +} + +void Server::SendInventory(u16 peer_id) +{ + DSTACK(__FUNCTION_NAME); + + Player* player = m_env.getPlayer(peer_id); + assert(player); + + /* + Serialize it + */ + + std::ostringstream os; + //os.imbue(std::locale("C")); + + player->inventory.serialize(os); + + std::string s = os.str(); + + SharedBuffer data(s.size()+2); + writeU16(&data[0], TOCLIENT_INVENTORY); + memcpy(&data[2], s.c_str(), s.size()); + + // Send as reliable + m_con.Send(peer_id, 0, data, true); +} + +std::string getWieldedItemString(const Player *player) +{ + const InventoryItem *item = player->getWieldItem(); + if (item == NULL) + return std::string(""); + std::ostringstream os(std::ios_base::binary); + item->serialize(os); + return os.str(); +} + +void Server::SendWieldedItem(const Player* player) +{ + DSTACK(__FUNCTION_NAME); + + assert(player); + + std::ostringstream os(std::ios_base::binary); + + writeU16(os, TOCLIENT_PLAYERITEM); + writeU16(os, 1); + writeU16(os, player->peer_id); + os< data((u8*)s.c_str(), s.size()); + + m_con.SendToAll(0, data, true); +} + +void Server::SendPlayerItems() +{ + DSTACK(__FUNCTION_NAME); + + std::ostringstream os(std::ios_base::binary); + core::list players = m_env.getPlayers(true); + + writeU16(os, TOCLIENT_PLAYERITEM); + writeU16(os, players.size()); + core::list::Iterator i; + for(i = players.begin(); i != players.end(); ++i) + { + Player *p = *i; + writeU16(os, p->peer_id); + os< data((u8*)s.c_str(), s.size()); + + m_con.SendToAll(0, data, true); +} + +void Server::SendChatMessage(u16 peer_id, const std::wstring &message) +{ + DSTACK(__FUNCTION_NAME); + + std::ostringstream os(std::ios_base::binary); + u8 buf[12]; + + // Write command + writeU16(buf, TOCLIENT_CHAT_MESSAGE); + os.write((char*)buf, 2); + + // Write length + writeU16(buf, message.size()); + os.write((char*)buf, 2); + + // Write string + for(u32 i=0; i data((u8*)s.c_str(), s.size()); + // Send as reliable + m_con.Send(peer_id, 0, data, true); +} + +void Server::BroadcastChatMessage(const std::wstring &message) +{ + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + // Get client and check that it is valid + RemoteClient *client = i.getNode()->getValue(); + assert(client->peer_id == i.getNode()->getKey()); + if(client->serialization_version == SER_FMT_VER_INVALID) + continue; + + SendChatMessage(client->peer_id, message); + } +} + +void Server::SendPlayerHP(Player *player) +{ + SendHP(m_con, player->peer_id, player->hp); +} + +void Server::SendMovePlayer(Player *player) +{ + DSTACK(__FUNCTION_NAME); + std::ostringstream os(std::ios_base::binary); + + writeU16(os, TOCLIENT_MOVE_PLAYER); + writeV3F1000(os, player->getPosition()); + writeF1000(os, player->getPitch()); + writeF1000(os, player->getYaw()); + + { + v3f pos = player->getPosition(); + f32 pitch = player->getPitch(); + f32 yaw = player->getYaw(); + dstream<<"Server sending TOCLIENT_MOVE_PLAYER" + <<" pos=("<serialize(os, ver); + std::string s = os.str(); + SharedBuffer blockdata((u8*)s.c_str(), s.size()); + + u32 replysize = 8 + blockdata.getSize(); + SharedBuffer reply(replysize); + writeU16(&reply[0], TOCLIENT_BLOCKDATA); + writeS16(&reply[2], p.X); + writeS16(&reply[4], p.Y); + writeS16(&reply[6], p.Z); + memcpy(&reply[8], *blockdata, blockdata.getSize()); + + /*dstream<<"Server: Sending block ("< queue; + + s32 total_sending = 0; + + { + ScopeProfiler sp(&g_profiler, "Server: selecting blocks for sending"); + + for(core::map::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + RemoteClient *client = i.getNode()->getValue(); + assert(client->peer_id == i.getNode()->getKey()); + + total_sending += client->SendingCount(); + + if(client->serialization_version == SER_FMT_VER_INVALID) + continue; + + client->GetNextBlocks(this, dtime, queue); + } + } + + // Sort. + // Lowest priority number comes first. + // Lowest is most important. + queue.sort(); + + for(u32 i=0; i= g_settings.getS32 + ("max_simultaneous_block_sends_server_total")) + break; + + PrioritySortedBlockTransfer q = queue[i]; + + MapBlock *block = NULL; + try + { + block = m_env.getMap().getBlockNoCreate(q.pos); + } + catch(InvalidPositionException &e) + { + continue; + } + + RemoteClient *client = getClient(q.peer_id); + + SendBlockNoLock(q.peer_id, block, client->serialization_version); + + client->SentBlock(q.pos); + + total_sending++; + } +} + +/* + Something random +*/ + +void Server::UpdateCrafting(u16 peer_id) +{ + DSTACK(__FUNCTION_NAME); + + Player* player = m_env.getPlayer(peer_id); + assert(player); + + /* + Calculate crafting stuff + */ + if(g_settings.getBool("creative_mode") == false) + { + InventoryList *clist = player->inventory.getList("craft"); + InventoryList *rlist = player->inventory.getList("craftresult"); + + if(rlist->getUsedSlots() == 0) + player->craftresult_is_preview = true; + + if(rlist && player->craftresult_is_preview) + { + rlist->clearItems(); + } + if(clist && rlist && player->craftresult_is_preview) + { + InventoryItem *items[9]; + for(u16 i=0; i<9; i++) + { + items[i] = clist->getItem(i); + } + + // Get result of crafting grid + InventoryItem *result = craft_get_result(items); + if(result) + rlist->addItem(result); + } + + } // if creative_mode == false +} + +RemoteClient* Server::getClient(u16 peer_id) +{ + DSTACK(__FUNCTION_NAME); + //JMutexAutoLock lock(m_con_mutex); + core::map::Node *n; + n = m_clients.find(peer_id); + // A client should exist for all peers + assert(n != NULL); + return n->getValue(); +} + +std::wstring Server::getStatusString() +{ + std::wostringstream os(std::ios_base::binary); + os<::Iterator + i = m_clients.getIterator(); + i.atEnd() == false; i++) + { + // Get client and check that it is valid + RemoteClient *client = i.getNode()->getValue(); + assert(client->peer_id == i.getNode()->getKey()); + if(client->serialization_version == SER_FMT_VER_INVALID) + continue; + // Get player + Player *player = m_env.getPlayer(client->peer_id); + // Get name of player + std::wstring name = L"unknown"; + if(player != NULL) + name = narrow_to_wide(player->getName()); + // Add name to information string + os<isSavingEnabled() == false) + os< Underwater"< WATER_LEVEL + 4) + { + //dstream<<"-> Underwater"<peer_id != 0) + { + dstream<<"emergePlayer(): Player already connected"<peer_id = peer_id; + + // Reset inventory to creative if in creative mode + if(g_settings.getBool("creative_mode")) + { + // Warning: double code below + // Backup actual inventory + player->inventory_backup = new Inventory(); + *(player->inventory_backup) = player->inventory; + // Set creative inventory + craft_set_creative_inventory(player); + } + + return player; + } + + /* + If player with the wanted peer_id already exists, cancel. + */ + if(m_env.getPlayer(peer_id) != NULL) + { + dstream<<"emergePlayer(): Player with wrong name but same" + " peer_id already exists"<peer_id = c.peer_id; + //player->peer_id = PEER_ID_INEXISTENT; + player->peer_id = peer_id; + player->updateName(name); + m_authmanager.add(name); + m_authmanager.setPassword(name, password); + m_authmanager.setPrivs(name, + stringToPrivs(g_settings.get("default_privs"))); + + /* + Set player position + */ + + dstream<<"Server: Finding spawn place for player \"" + <getName()<<"\""<setPosition(pos); + + /* + Add player to environment + */ + + m_env.addPlayer(player); + + /* + Add stuff to inventory + */ + + if(g_settings.getBool("creative_mode")) + { + // Warning: double code above + // Backup actual inventory + player->inventory_backup = new Inventory(); + *(player->inventory_backup) = player->inventory; + // Set creative inventory + craft_set_creative_inventory(player); + } + else if(g_settings.getBool("give_initial_stuff")) + { + craft_give_initial_stuff(player); + } + + return player; + + } // create new player +} + +void Server::handlePeerChange(PeerChange &c) +{ + JMutexAutoLock envlock(m_env_mutex); + JMutexAutoLock conlock(m_con_mutex); + + if(c.type == PEER_ADDED) + { + /* + Add + */ + + // Error check + core::map::Node *n; + n = m_clients.find(c.peer_id); + // The client shouldn't already exist + assert(n == NULL); + + // Create client + RemoteClient *client = new RemoteClient(); + client->peer_id = c.peer_id; + m_clients.insert(client->peer_id, client); + + } // PEER_ADDED + else if(c.type == PEER_REMOVED) + { + /* + Delete + */ + + // Error check + core::map::Node *n; + n = m_clients.find(c.peer_id); + // The client should exist + assert(n != NULL); + + /* + Mark objects to be not known by the client + */ + RemoteClient *client = n->getValue(); + // Handle objects + for(core::map::Iterator + i = client->m_known_objects.getIterator(); + i.atEnd()==false; i++) + { + // Get object + u16 id = i.getNode()->getKey(); + ServerActiveObject* obj = m_env.getActiveObject(id); + + if(obj && obj->m_known_by_count > 0) + obj->m_known_by_count--; + } + + // Collect information about leaving in chat + std::wstring message; + { + std::wstring name = L"unknown"; + Player *player = m_env.getPlayer(c.peer_id); + if(player != NULL) + name = narrow_to_wide(player->getName()); + + message += L"*** "; + message += name; + message += L" left game"; + if(c.timeout) + message += L" (timed out)"; + } + + /*// Delete player + { + m_env.removePlayer(c.peer_id); + }*/ + + // Set player client disconnected + { + Player *player = m_env.getPlayer(c.peer_id); + if(player != NULL) + player->peer_id = 0; + } + + // Delete client + delete m_clients[c.peer_id]; + m_clients.remove(c.peer_id); + + // Send player info to all remaining clients + SendPlayerInfos(); + + // Send leave chat message to all remaining clients + BroadcastChatMessage(message); + + } // PEER_REMOVED + else + { + assert(0); + } +} + +void Server::handlePeerChanges() +{ + while(m_peer_change_queue.size() > 0) + { + PeerChange c = m_peer_change_queue.pop_front(); + + dout_server<<"Server: Handling peer change: " + <<"id="< list = server.getPlayerInfo(); + core::list::Iterator i; + static u32 sum_old = 0; + u32 sum = PIChecksum(list); + if(sum != sum_old) + { + dstream<PrintLine(&dstream); + } + } + sum_old = sum; + } + } +} + + diff --git a/src/server.h b/src/server.h new file mode 100644 index 0000000..7065efa --- /dev/null +++ b/src/server.h @@ -0,0 +1,696 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef SERVER_HEADER +#define SERVER_HEADER + +#include "connection.h" +#include "environment.h" +#include "common_irrlicht.h" +#include +#include "utility.h" +#include "porting.h" +#include "map.h" +#include "inventory.h" +#include "auth.h" +#include "ban.h" + +/* + Some random functions +*/ +v3f findSpawnPos(ServerMap &map); + +/* + A structure containing the data needed for queueing the fetching + of blocks. +*/ +struct QueuedBlockEmerge +{ + v3s16 pos; + // key = peer_id, value = flags + core::map peer_ids; +}; + +/* + This is a thread-safe class. +*/ +class BlockEmergeQueue +{ +public: + BlockEmergeQueue() + { + m_mutex.Init(); + } + + ~BlockEmergeQueue() + { + JMutexAutoLock lock(m_mutex); + + core::list::Iterator i; + for(i=m_queue.begin(); i!=m_queue.end(); i++) + { + QueuedBlockEmerge *q = *i; + delete q; + } + } + + /* + peer_id=0 adds with nobody to send to + */ + void addBlock(u16 peer_id, v3s16 pos, u8 flags) + { + DSTACK(__FUNCTION_NAME); + + JMutexAutoLock lock(m_mutex); + + if(peer_id != 0) + { + /* + Find if block is already in queue. + If it is, update the peer to it and quit. + */ + core::list::Iterator i; + for(i=m_queue.begin(); i!=m_queue.end(); i++) + { + QueuedBlockEmerge *q = *i; + if(q->pos == pos) + { + q->peer_ids[peer_id] = flags; + return; + } + } + } + + /* + Add the block + */ + QueuedBlockEmerge *q = new QueuedBlockEmerge; + q->pos = pos; + if(peer_id != 0) + q->peer_ids[peer_id] = flags; + m_queue.push_back(q); + } + + // Returned pointer must be deleted + // Returns NULL if queue is empty + QueuedBlockEmerge * pop() + { + JMutexAutoLock lock(m_mutex); + + core::list::Iterator i = m_queue.begin(); + if(i == m_queue.end()) + return NULL; + QueuedBlockEmerge *q = *i; + m_queue.erase(i); + return q; + } + + u32 size() + { + JMutexAutoLock lock(m_mutex); + return m_queue.size(); + } + + u32 peerItemCount(u16 peer_id) + { + JMutexAutoLock lock(m_mutex); + + u32 count = 0; + + core::list::Iterator i; + for(i=m_queue.begin(); i!=m_queue.end(); i++) + { + QueuedBlockEmerge *q = *i; + if(q->peer_ids.find(peer_id) != NULL) + count++; + } + + return count; + } + +private: + core::list m_queue; + JMutex m_mutex; +}; + +class Server; + +class ServerThread : public SimpleThread +{ + Server *m_server; + +public: + + ServerThread(Server *server): + SimpleThread(), + m_server(server) + { + } + + void * Thread(); +}; + +class EmergeThread : public SimpleThread +{ + Server *m_server; + +public: + + EmergeThread(Server *server): + SimpleThread(), + m_server(server) + { + } + + void * Thread(); + + void trigger() + { + setRun(true); + if(IsRunning() == false) + { + Start(); + } + } +}; + +struct PlayerInfo +{ + u16 id; + char name[PLAYERNAME_SIZE]; + v3f position; + Address address; + float avg_rtt; + + PlayerInfo(); + void PrintLine(std::ostream *s); +}; + +u32 PIChecksum(core::list &l); + +/* + Used for queueing and sorting block transfers in containers + + Lower priority number means higher priority. +*/ +struct PrioritySortedBlockTransfer +{ + PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id) + { + priority = a_priority; + pos = a_pos; + peer_id = a_peer_id; + } + bool operator < (PrioritySortedBlockTransfer &other) + { + return priority < other.priority; + } + float priority; + v3s16 pos; + u16 peer_id; +}; + +class RemoteClient +{ +public: + // peer_id=0 means this client has no associated peer + // NOTE: If client is made allowed to exist while peer doesn't, + // this has to be set to 0 when there is no peer. + // Also, the client must be moved to some other container. + u16 peer_id; + // The serialization version to use with the client + u8 serialization_version; + // + u16 net_proto_version; + // Version is stored in here after INIT before INIT2 + u8 pending_serialization_version; + + RemoteClient(): + m_time_from_building(9999), + m_excess_gotblocks(0) + { + peer_id = 0; + serialization_version = SER_FMT_VER_INVALID; + net_proto_version = 0; + pending_serialization_version = SER_FMT_VER_INVALID; + m_nearest_unsent_d = 0; + m_nearest_unsent_reset_timer = 0.0; + m_nothing_to_send_counter = 0; + m_nothing_to_send_pause_timer = 0; + } + ~RemoteClient() + { + } + + /* + Finds block that should be sent next to the client. + Environment should be locked when this is called. + dtime is used for resetting send radius at slow interval + */ + void GetNextBlocks(Server *server, float dtime, + core::array &dest); + + /* + Connection and environment should be locked when this is called. + steps() objects of blocks not found in active_blocks, then + adds those blocks to active_blocks + */ + void SendObjectData( + Server *server, + float dtime, + core::map &stepped_blocks + ); + + void GotBlock(v3s16 p); + + void SentBlock(v3s16 p); + + void SetBlockNotSent(v3s16 p); + void SetBlocksNotSent(core::map &blocks); + + s32 SendingCount() + { + return m_blocks_sending.size(); + } + + // Increments timeouts and removes timed-out blocks from list + // NOTE: This doesn't fix the server-not-sending-block bug + // because it is related to emerging, not sending. + //void RunSendingTimeouts(float dtime, float timeout); + + void PrintInfo(std::ostream &o) + { + o<<"RemoteClient "< *far_players=NULL, float far_d_nodes=100); + void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0, + core::list *far_players=NULL, float far_d_nodes=100); + void setBlockNotSent(v3s16 p); + + // Environment and Connection must be locked when called + void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver); + + // Sends blocks to clients (locks env and con on its own) + void SendBlocks(float dtime); + + /* + Something random + */ + + void UpdateCrafting(u16 peer_id); + + // When called, connection mutex should be locked + RemoteClient* getClient(u16 peer_id); + + // When called, environment mutex should be locked + std::string getPlayerName(u16 peer_id) + { + Player *player = m_env.getPlayer(peer_id); + if(player == NULL) + return "[id="+itos(peer_id); + return player->getName(); + } + + /* + Get a player from memory or creates one. + If player is already connected, return NULL + The password is not checked here - it is only used to + set the password if a new player is created. + + Call with env and con locked. + */ + Player *emergePlayer(const char *name, const char *password, u16 peer_id); + + // Locks environment and connection by its own + struct PeerChange; + void handlePeerChange(PeerChange &c); + void handlePeerChanges(); + + u64 getPlayerPrivs(Player *player); + + /* + Variables + */ + + // Some timers + float m_liquid_transform_timer; + float m_print_info_timer; + float m_objectdata_timer; + float m_emergethread_trigger_timer; + float m_savemap_timer; + IntervalLimiter m_map_timer_and_unload_interval; + + // NOTE: If connection and environment are both to be locked, + // environment shall be locked first. + + // Environment + ServerEnvironment m_env; + JMutex m_env_mutex; + + // Connection + con::Connection m_con; + JMutex m_con_mutex; + // Connected clients (behind the con mutex) + core::map m_clients; + + // User authentication + AuthManager m_authmanager; + + // Bann checking + BanManager m_banmanager; + + /* + Threads + */ + + // A buffer for time steps + // step() increments and AsyncRunStep() run by m_thread reads it. + float m_step_dtime; + JMutex m_step_dtime_mutex; + + // The server mainly operates in this thread + ServerThread m_thread; + // This thread fetches and generates map + EmergeThread m_emergethread; + // Queue of block coordinates to be processed by the emerge thread + BlockEmergeQueue m_emerge_queue; + + /* + Time related stuff + */ + + // 0-23999 + //MutexedVariable m_time_of_day; + // Used to buffer dtime for adding to m_time_of_day + float m_time_counter; + // Timer for sending time of day over network + float m_time_of_day_send_timer; + // Uptime of server in seconds + MutexedVariable m_uptime; + + /* + Peer change queue. + Queues stuff from peerAdded() and deletingPeer() to + handlePeerChanges() + */ + enum PeerChangeType + { + PEER_ADDED, + PEER_REMOVED + }; + struct PeerChange + { + PeerChangeType type; + u16 peer_id; + bool timeout; + }; + Queue m_peer_change_queue; + + /* + Random stuff + */ + + // Map directory + std::string m_mapsavedir; + + // Configuration path ("" = no configuration file) + std::string m_configpath; + + bool m_shutdown_requested; + + /* + Map edit event queue. Automatically receives all map edits. + The constructor of this class registers us to receive them through + onMapEditEvent + + NOTE: Should these be moved to actually be members of + ServerEnvironment? + */ + + /* + Queue of map edits from the environment for sending to the clients + This is behind m_env_mutex + */ + Queue m_unsent_map_edit_queue; + /* + Set to true when the server itself is modifying the map and does + all sending of information by itself. + This is behind m_env_mutex + */ + bool m_ignore_map_edit_events; + /* + If set to !=0, the incoming MapEditEvents are modified to have + this peed id as the disabled recipient + This is behind m_env_mutex + */ + u16 m_ignore_map_edit_events_peer_id; + + Profiler *m_profiler; + + friend class EmergeThread; + friend class RemoteClient; +}; + +/* + Runs a simple dedicated server loop. + + Shuts down when run is set to false. +*/ +void dedicated_server_loop(Server &server, bool &run); + +#endif + diff --git a/src/servercommand.cpp b/src/servercommand.cpp new file mode 100644 index 0000000..89ba077 --- /dev/null +++ b/src/servercommand.cpp @@ -0,0 +1,305 @@ +/* +Part of Minetest-c55 +Copyright (C) 2010-11 celeron55, Perttu Ahola +Copyright (C) 2011 Ciaran Gultnieks + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#include "servercommand.h" +#include "utility.h" + +void cmd_status(std::wostringstream &os, + ServerCommandContext *ctx) +{ + os<server->getStatusString(); +} + +void cmd_me(std::wostringstream &os, + ServerCommandContext *ctx) +{ + std::wstring name = narrow_to_wide(ctx->player->getName()); + os << L"* " << name << L" " << ctx->paramstring; + ctx->flags |= SEND_TO_OTHERS | SEND_NO_PREFIX; +} + +void cmd_privs(std::wostringstream &os, + ServerCommandContext *ctx) +{ + if(ctx->parms.size() == 1) + { + // Show our own real privs, without any adjustments + // made for admin status + os<server->getPlayerAuthPrivs(ctx->player->getName()))); + return; + } + + if((ctx->privs & PRIV_PRIVS) == 0) + { + os<env->getPlayer(wide_to_narrow(ctx->parms[1]).c_str()); + if(tp == NULL) + { + os<server->getPlayerAuthPrivs(tp->getName()))); +} + +void cmd_grantrevoke(std::wostringstream &os, + ServerCommandContext *ctx) +{ + if(ctx->parms.size() != 3) + { + os<privs & PRIV_PRIVS) == 0) + { + os<parms[2])); + if(newprivs == PRIV_INVALID) + { + os<env->getPlayer(wide_to_narrow(ctx->parms[1]).c_str()); + if(tp == NULL) + { + os<parms[1]); + u64 privs = ctx->server->getPlayerAuthPrivs(playername); + + if(ctx->parms[0] == L"grant") + privs |= newprivs; + else + privs &= ~newprivs; + + ctx->server->setPlayerAuthPrivs(playername, privs); + + os<parms.size() != 2) + { + os<privs & PRIV_SETTIME) ==0) + { + os<parms[1])); + ctx->server->setTimeOfDay(time); + os<privs & PRIV_SERVER) ==0) + { + os<server->requestShutdown(); + + os<flags |= SEND_TO_OTHERS; +} + +void cmd_setting(std::wostringstream &os, + ServerCommandContext *ctx) +{ + if((ctx->privs & PRIV_SERVER) ==0) + { + os<parms[1] + L" = " + ctx->params[2]);*/ + + std::string confline = wide_to_narrow(ctx->paramstring); + + g_settings.parseConfigLine(confline); + + ctx->server->saveConfig(); + + os<< L"-!- Setting changed and configuration saved."; +} + +void cmd_teleport(std::wostringstream &os, + ServerCommandContext *ctx) +{ + if((ctx->privs & PRIV_TELEPORT) ==0) + { + os<parms.size() != 2) + { + os< coords = str_split(ctx->parms[1], L','); + if(coords.size() != 3) + { + os<player->setPosition(dest); + ctx->server->SendMovePlayer(ctx->player); + + os<< L"-!- Teleported."; +} + +void cmd_banunban(std::wostringstream &os, ServerCommandContext *ctx) +{ + if((ctx->privs & PRIV_BAN) == 0) + { + os<parms.size() < 2) + { + std::string desc = ctx->server->getBanDescription(""); + os<parms[0] == L"ban") + { + Player *player = ctx->env->getPlayer(wide_to_narrow(ctx->parms[1]).c_str()); + + if(player == NULL) + { + os<server->getPeerNoEx(player->peer_id); + if(peer == NULL) + { + dstream<<__FUNCTION_NAME<<": peer was not found"<address.serializeString(); + ctx->server->setIpBanned(ip_string, player->getName()); + os<getName()); + } + else + { + std::string ip_or_name = wide_to_narrow(ctx->parms[1]); + std::string desc = ctx->server->getBanDescription(ip_or_name); + ctx->server->unsetIpBanned(ip_or_name); + os<flags = SEND_TO_SENDER; // Default, unless we change it. + + u64 privs = ctx->privs; + + if(ctx->parms.size() == 0 || ctx->parms[0] == L"help") + { + os<parms[0] == L"status") + { + cmd_status(os, ctx); + } + else if(ctx->parms[0] == L"privs") + { + cmd_privs(os, ctx); + } + else if(ctx->parms[0] == L"grant" || ctx->parms[0] == L"revoke") + { + cmd_grantrevoke(os, ctx); + } + else if(ctx->parms[0] == L"time") + { + cmd_time(os, ctx); + } + else if(ctx->parms[0] == L"shutdown") + { + cmd_shutdown(os, ctx); + } + else if(ctx->parms[0] == L"setting") + { + cmd_setting(os, ctx); + } + else if(ctx->parms[0] == L"teleport") + { + cmd_teleport(os, ctx); + } + else if(ctx->parms[0] == L"ban" || ctx->parms[0] == L"unban") + { + cmd_banunban(os, ctx); + } + else if(ctx->parms[0] == L"me") + { + cmd_me(os, ctx); + } + else + { + os<parms[0]; + } + return os.str(); +} + + diff --git a/src/servercommand.h b/src/servercommand.h new file mode 100644 index 0000000..648a573 --- /dev/null +++ b/src/servercommand.h @@ -0,0 +1,66 @@ +/* +Part of Minetest-c55 +Copyright (C) 2010-11 celeron55, Perttu Ahola +Copyright (C) 2011 Ciaran Gultnieks + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#ifndef SERVERCOMMAND_HEADER +#define SERVERCOMMAND_HEADER + +#include +#include +#include "common_irrlicht.h" +#include "player.h" +#include "server.h" + +#define SEND_TO_SENDER (1<<0) +#define SEND_TO_OTHERS (1<<1) +#define SEND_NO_PREFIX (1<<2) + +struct ServerCommandContext +{ + std::vector parms; + std::wstring paramstring; + Server* server; + ServerEnvironment *env; + Player* player; + // Effective privs for the player, which may be different to their + // stored ones - e.g. if they are named in the config as an admin. + u64 privs; + u32 flags; + + ServerCommandContext( + std::vector parms, + std::wstring paramstring, + Server* server, + ServerEnvironment *env, + Player* player, + u64 privs) + : parms(parms), paramstring(paramstring), + server(server), env(env), player(player), privs(privs) + { + } + +}; + +// Process a command sent from a client. The environment and connection +// should be locked when this is called. +// Returns a response message, to be dealt with according to the flags set +// in the context. +std::wstring processServerCommand(ServerCommandContext *ctx); + +#endif + + diff --git a/src/servermain.cpp b/src/servermain.cpp new file mode 100644 index 0000000..dc41720 --- /dev/null +++ b/src/servermain.cpp @@ -0,0 +1,345 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +/* +=============================== NOTES ============================== + + +*/ + +#ifndef SERVER + #ifdef _WIN32 + #pragma error ("For a server build, SERVER must be defined globally") + #else + #error "For a server build, SERVER must be defined globally" + #endif +#endif + +#ifdef NDEBUG + #ifdef _WIN32 + #pragma message ("Disabling unit tests") + #else + #warning "Disabling unit tests" + #endif + // Disable unit tests + #define ENABLE_TESTS 0 +#else + // Enable unit tests + #define ENABLE_TESTS 1 +#endif + +#ifdef _MSC_VER +#pragma comment(lib, "jthread.lib") +#pragma comment(lib, "zlibwapi.lib") +#endif + +#include +#include +#include +#include +#include +#include "common_irrlicht.h" +#include "debug.h" +#include "map.h" +#include "player.h" +#include "main.h" +#include "test.h" +#include "environment.h" +#include "server.h" +#include "serialization.h" +#include "constants.h" +#include "strfnd.h" +#include "porting.h" +#include "materials.h" +#include "config.h" +#include "mineral.h" +#include "filesys.h" + +/* + Settings. + These are loaded from the config file. +*/ + +Settings g_settings; + +extern void set_default_settings(); + +// Global profiler +Profiler g_profiler; + +// A dummy thing +ITextureSource *g_texturesource = NULL; + +/* + Debug streams +*/ + +// Connection +std::ostream *dout_con_ptr = &dummyout; +std::ostream *derr_con_ptr = &dstream_no_stderr; + +// Server +std::ostream *dout_server_ptr = &dstream; +std::ostream *derr_server_ptr = &dstream; + +// Client +std::ostream *dout_client_ptr = &dstream; +std::ostream *derr_client_ptr = &dstream; + +/* + gettime.h implementation +*/ + +u32 getTimeMs() +{ + /* + Use imprecise system calls directly (from porting.h) + */ + return porting::getTimeMs(); +} + +int main(int argc, char *argv[]) +{ + /* + Initialization + */ + + // Set locale. This is for forcing '.' as the decimal point. + std::locale::global(std::locale("C")); + // This enables printing all characters in bitmap font + setlocale(LC_CTYPE, "en_US"); + + /* + Low-level initialization + */ + + bool disable_stderr = false; +#ifdef _WIN32 + disable_stderr = true; +#endif + + porting::signal_handler_init(); + bool &kill = *porting::signal_handler_killstatus(); + + // Initialize porting::path_data and porting::path_userdata + porting::initializePaths(); + + // Create user data directory + fs::CreateDir(porting::path_userdata); + + // Initialize debug streams +#ifdef RUN_IN_PLACE + std::string debugfile = DEBUGFILE; +#else + std::string debugfile = porting::path_userdata+"/"+DEBUGFILE; +#endif + debugstreams_init(disable_stderr, debugfile.c_str()); + // Initialize debug stacks + debug_stacks_init(); + + DSTACK(__FUNCTION_NAME); + + // Init material properties table + //initializeMaterialProperties(); + + // Debug handler + BEGIN_DEBUG_EXCEPTION_HANDLER + + // Print startup message + dstream< allowed_options; + allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("config", ValueSpec(VALUETYPE_STRING, + "Load configuration from specified file")); + allowed_options.insert("port", ValueSpec(VALUETYPE_STRING)); + allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG)); + allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING)); + + Settings cmd_args; + + bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options); + + if(ret == false || cmd_args.getFlag("help")) + { + dstream<<"Allowed options:"<::Iterator + i = allowed_options.getIterator(); + i.atEnd() == false; i++) + { + dstream<<" --"<getKey(); + if(i.getNode()->getValue().type == VALUETYPE_FLAG) + { + } + else + { + dstream<<" "; + } + dstream<getValue().help != NULL) + { + dstream<<" "<getValue().help + < filenames; + filenames.push_back(porting::path_userdata + "/minetest.conf"); +#ifdef RUN_IN_PLACE + filenames.push_back(porting::path_userdata + "/../minetest.conf"); +#endif + + for(u32 i=0; i__| \\___ >____ > |__| "< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "serverobject.h" +#include +#include "inventory.h" + +ServerActiveObject::ServerActiveObject(ServerEnvironment *env, u16 id, v3f pos): + ActiveObject(id), + m_known_by_count(0), + m_removed(false), + m_pending_deactivation(false), + m_static_exists(false), + m_static_block(1337,1337,1337), + m_env(env), + m_base_position(pos) +{ +} + +ServerActiveObject::~ServerActiveObject() +{ +} + +ServerActiveObject* ServerActiveObject::create(u8 type, + ServerEnvironment *env, u16 id, v3f pos, + const std::string &data) +{ + // Find factory function + core::map::Node *n; + n = m_types.find(type); + if(n == NULL) + { + // If factory is not found, just return. + dstream<<"WARNING: ServerActiveObject: No factory for type=" + <getValue(); + ServerActiveObject *object = (*f)(env, id, pos, data); + return object; +} + +void ServerActiveObject::registerType(u16 type, Factory f) +{ + core::map::Node *n; + n = m_types.find(type); + if(n) + return; + m_types.insert(type, f); +} + + + diff --git a/src/serverobject.h b/src/serverobject.h new file mode 100644 index 0000000..01f199a --- /dev/null +++ b/src/serverobject.h @@ -0,0 +1,173 @@ +/* +Minetest-c55 +Copyright (C) 2010-2011 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef SERVEROBJECT_HEADER +#define SERVEROBJECT_HEADER + +#include "common_irrlicht.h" +#include "activeobject.h" +#include "utility.h" + +/* + +Some planning +------------- + +* Server environment adds an active object, which gets the id 1 +* The active object list is scanned for each client once in a while, + and it finds out what objects have been added that are not known + by the client yet. This scan is initiated by the Server class and + the result ends up directly to the server. +* A network packet is created with the info and sent to the client. +* Environment converts objects to static data and static data to + objects, based on how close players are to them. + +*/ + +class ServerEnvironment; +class InventoryItem; +class Player; + +class ServerActiveObject : public ActiveObject +{ +public: + /* + NOTE: m_env can be NULL, but step() isn't called if it is. + Prototypes are used that way. + */ + ServerActiveObject(ServerEnvironment *env, u16 id, v3f pos); + virtual ~ServerActiveObject(); + + // Create a certain type of ServerActiveObject + static ServerActiveObject* create(u8 type, + ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + + /* + Some simple getters/setters + */ + v3f getBasePosition() + {return m_base_position;} + void setBasePosition(v3f pos) + {m_base_position = pos;} + ServerEnvironment* getEnv() + {return m_env;} + + /* + Step object in time. + Messages added to messages are sent to client over network. + + send_recommended: + True at around 5-10 times a second, same for all objects. + This is used to let objects send most of the data at the + same time so that the data can be combined in a single + packet. + */ + virtual void step(float dtime, bool send_recommended){} + + /* + The return value of this is passed to the client-side object + when it is created + */ + virtual std::string getClientInitializationData(){return "";} + + /* + The return value of this is passed to the server-side object + when it is created (converted from static to active - actually + the data is the static form) + */ + virtual std::string getStaticData(){return "";} + + /* + Item that the player gets when this object is picked up. + If NULL, object cannot be picked up. + */ + virtual InventoryItem* createPickedUpItem(){return NULL;} + + /* + If the object doesn't return an item, this will be called. + Return value is tool wear. + */ + virtual u16 punch(const std::string &toolname, v3f dir) + {return 0;} + + /* + */ + virtual void rightClick(Player *player){} + + /* + Number of players which know about this object. Object won't be + deleted until this is 0 to keep the id preserved for the right + object. + */ + u16 m_known_by_count; + + /* + - Whether this object is to be removed when nobody knows about + it anymore. + - Removal is delayed to preserve the id for the time during which + it could be confused to some other object by some client. + - This is set to true by the step() method when the object wants + to be deleted. + - This can be set to true by anything else too. + */ + bool m_removed; + + /* + This is set to true when a block should be removed from the active + object list but couldn't be removed because the id has to be + reserved for some client. + + The environment checks this periodically. If this is true and also + m_known_by_count is true, + */ + bool m_pending_deactivation; + + /* + Whether the object's static data has been stored to a block + */ + bool m_static_exists; + /* + The block from which the object was loaded from, and in which + a copy of the static data resides. + */ + v3s16 m_static_block; + + /* + Queue of messages to be sent to the client + */ + Queue m_messages_out; + +protected: + // Used for creating objects based on type + typedef ServerActiveObject* (*Factory) + (ServerEnvironment *env, u16 id, v3f pos, + const std::string &data); + static void registerType(u16 type, Factory f); + + ServerEnvironment *m_env; + v3f m_base_position; + +private: + // Used for creating objects based on type + static core::map m_types; +}; + +#endif + diff --git a/src/sha1.cpp b/src/sha1.cpp new file mode 100644 index 0000000..98180ad --- /dev/null +++ b/src/sha1.cpp @@ -0,0 +1,207 @@ +/* sha1.cpp + +Copyright (c) 2005 Michael D. Leonhard + +http://tamale.net/ + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +#include +#include +#include +#include + +#include "sha1.h" + +// print out memory in hexadecimal +void SHA1::hexPrinter( unsigned char* c, int l ) +{ + assert( c ); + assert( l > 0 ); + while( l > 0 ) + { + printf( " %02x", *c ); + l--; + c++; + } +} + +// circular left bit rotation. MSB wraps around to LSB +Uint32 SHA1::lrot( Uint32 x, int bits ) +{ + return (x<>(32 - bits)); +}; + +// Save a 32-bit unsigned integer to memory, in big-endian order +void SHA1::storeBigEndianUint32( unsigned char* byte, Uint32 num ) +{ + assert( byte ); + byte[0] = (unsigned char)(num>>24); + byte[1] = (unsigned char)(num>>16); + byte[2] = (unsigned char)(num>>8); + byte[3] = (unsigned char)num; +} + + +// Constructor ******************************************************* +SHA1::SHA1() +{ + // make sure that the data type is the right size + assert( sizeof( Uint32 ) * 5 == 20 ); + + // initialize + H0 = 0x67452301; + H1 = 0xefcdab89; + H2 = 0x98badcfe; + H3 = 0x10325476; + H4 = 0xc3d2e1f0; + unprocessedBytes = 0; + size = 0; +} + +// Destructor ******************************************************** +SHA1::~SHA1() +{ + // erase data + H0 = H1 = H2 = H3 = H4 = 0; + for( int c = 0; c < 64; c++ ) bytes[c] = 0; + unprocessedBytes = size = 0; +} + +// process *********************************************************** +void SHA1::process() +{ + assert( unprocessedBytes == 64 ); + //printf( "process: " ); hexPrinter( bytes, 64 ); printf( "\n" ); + int t; + Uint32 a, b, c, d, e, K, f, W[80]; + // starting values + a = H0; + b = H1; + c = H2; + d = H3; + e = H4; + // copy and expand the message block + for( t = 0; t < 16; t++ ) W[t] = (bytes[t*4] << 24) + +(bytes[t*4 + 1] << 16) + +(bytes[t*4 + 2] << 8) + + bytes[t*4 + 3]; + for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 ); + + /* main loop */ + Uint32 temp; + for( t = 0; t < 80; t++ ) + { + if( t < 20 ) { + K = 0x5a827999; + f = (b & c) | ((b ^ 0xFFFFFFFF) & d);//TODO: try using ~ + } else if( t < 40 ) { + K = 0x6ed9eba1; + f = b ^ c ^ d; + } else if( t < 60 ) { + K = 0x8f1bbcdc; + f = (b & c) | (b & d) | (c & d); + } else { + K = 0xca62c1d6; + f = b ^ c ^ d; + } + temp = lrot(a,5) + f + e + W[t] + K; + e = d; + d = c; + c = lrot(b,30); + b = a; + a = temp; + //printf( "t=%d %08x %08x %08x %08x %08x\n",t,a,b,c,d,e ); + } + /* add variables */ + H0 += a; + H1 += b; + H2 += c; + H3 += d; + H4 += e; + //printf( "Current: %08x %08x %08x %08x %08x\n",H0,H1,H2,H3,H4 ); + /* all bytes have been processed */ + unprocessedBytes = 0; +} + +// addBytes ********************************************************** +void SHA1::addBytes( const char* data, int num ) +{ + assert( data ); + assert( num > 0 ); + // add these bytes to the running total + size += num; + // repeat until all data is processed + while( num > 0 ) + { + // number of bytes required to complete block + int needed = 64 - unprocessedBytes; + assert( needed > 0 ); + // number of bytes to copy (use smaller of two) + int toCopy = (num < needed) ? num : needed; + // Copy the bytes + memcpy( bytes + unprocessedBytes, data, toCopy ); + // Bytes have been copied + num -= toCopy; + data += toCopy; + unprocessedBytes += toCopy; + + // there is a full block + if( unprocessedBytes == 64 ) process(); + } +} + +// digest ************************************************************ +unsigned char* SHA1::getDigest() +{ + // save the message size + Uint32 totalBitsL = size << 3; + Uint32 totalBitsH = size >> 29; + // add 0x80 to the message + addBytes( "\x80", 1 ); + + unsigned char footer[64] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + // block has no room for 8-byte filesize, so finish it + if( unprocessedBytes > 56 ) + addBytes( (char*)footer, 64 - unprocessedBytes); + assert( unprocessedBytes <= 56 ); + // how many zeros do we need + int neededZeros = 56 - unprocessedBytes; + // store file size (in bits) in big-endian format + storeBigEndianUint32( footer + neededZeros , totalBitsH ); + storeBigEndianUint32( footer + neededZeros + 4, totalBitsL ); + // finish the final block + addBytes( (char*)footer, neededZeros + 8 ); + // allocate memory for the digest bytes + unsigned char* digest = (unsigned char*)malloc( 20 ); + // copy the digest bytes + storeBigEndianUint32( digest, H0 ); + storeBigEndianUint32( digest + 4, H1 ); + storeBigEndianUint32( digest + 8, H2 ); + storeBigEndianUint32( digest + 12, H3 ); + storeBigEndianUint32( digest + 16, H4 ); + // return the digest + return digest; +} diff --git a/src/sha1.h b/src/sha1.h new file mode 100644 index 0000000..c049473 --- /dev/null +++ b/src/sha1.h @@ -0,0 +1,51 @@ +/* sha1.h + +Copyright (c) 2005 Michael D. Leonhard + +http://tamale.net/ + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +#ifndef SHA1_HEADER +typedef unsigned int Uint32; + +class SHA1 +{ + private: + // fields + Uint32 H0, H1, H2, H3, H4; + unsigned char bytes[64]; + int unprocessedBytes; + Uint32 size; + void process(); + public: + SHA1(); + ~SHA1(); + void addBytes( const char* data, int num ); + unsigned char* getDigest(); + // utility methods + static Uint32 lrot( Uint32 x, int bits ); + static void storeBigEndianUint32( unsigned char* byte, Uint32 num ); + static void hexPrinter( unsigned char* c, int l ); +}; + +#define SHA1_HEADER +#endif diff --git a/src/socket.cpp b/src/socket.cpp new file mode 100644 index 0000000..ac4871f --- /dev/null +++ b/src/socket.cpp @@ -0,0 +1,361 @@ +/* +Minetest-c55 +Copyright (C) 2010 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "socket.h" +#include "debug.h" +#include +#include +#include +#include +#include "utility.h" + +// Debug printing options +// Set to 1 for debug output +#define DP 0 +// This is prepended to everything printed here +#define DPS "" + +bool g_sockets_initialized = false; + +void sockets_init() +{ +#ifdef _WIN32 + WSADATA WsaData; + if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR) + throw SocketException("WSAStartup failed"); +#else +#endif + g_sockets_initialized = true; +} + +void sockets_cleanup() +{ +#ifdef _WIN32 + WSACleanup(); +#endif +} + +Address::Address() +{ + m_address = 0; + m_port = 0; +} + +Address::Address(unsigned int address, unsigned short port) +{ + m_address = address; + m_port = port; +} + +Address::Address(unsigned int a, unsigned int b, + unsigned int c, unsigned int d, + unsigned short port) +{ + m_address = (a<<24) | (b<<16) | ( c<<8) | d; + m_port = port; +} + +bool Address::operator==(Address &address) +{ + return (m_address == address.m_address + && m_port == address.m_port); +} + +bool Address::operator!=(Address &address) +{ + return !(*this == address); +} + +void Address::Resolve(const char *name) +{ + struct addrinfo *resolved; + int e = getaddrinfo(name, NULL, NULL, &resolved); + if(e != 0) + throw ResolveError(""); + /* + FIXME: This is an ugly hack; change the whole class + to store the address as sockaddr + */ + struct sockaddr_in *t = (struct sockaddr_in*)resolved->ai_addr; + m_address = ntohl(t->sin_addr.s_addr); + freeaddrinfo(resolved); +} + +std::string Address::serializeString() +{ + unsigned int a, b, c, d; + a = (m_address & 0xFF000000)>>24; + b = (m_address & 0x00FF0000)>>16; + c = (m_address & 0x0000FF00)>>8; + d = (m_address & 0x000000FF); + return itos(a)+"."+itos(b)+"."+itos(c)+"."+itos(d); +} + +unsigned int Address::getAddress() const +{ + return m_address; +} + +unsigned short Address::getPort() const +{ + return m_port; +} + +void Address::setAddress(unsigned int address) +{ + m_address = address; +} + +void Address::setAddress(unsigned int a, unsigned int b, + unsigned int c, unsigned int d) +{ + m_address = (a<<24) | (b<<16) | ( c<<8) | d; +} + +void Address::setPort(unsigned short port) +{ + m_port = port; +} + +void Address::print(std::ostream *s) const +{ + (*s)<<((m_address>>24)&0xff)<<"." + <<((m_address>>16)&0xff)<<"." + <<((m_address>>8)&0xff)<<"." + <<((m_address>>0)&0xff)<<":" + < "; + destination.print(); + dstream<<", size="<20) + dstream<<"..."; + if(dumping_packet) + dstream<<" (DUMPED BY INTERNET_SIMULATOR)"; + dstream<20) + dstream<<"..."; + dstream< + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef SOCKET_HEADER +#define SOCKET_HEADER + +#ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN + // Without this some of the network functions are not found on mingw + #ifndef _WIN32_WINNT + #define _WIN32_WINNT 0x0501 + #endif + #include + #include + #include + #ifdef _MSC_VER + #pragma comment(lib, "ws2_32.lib") + #endif +typedef SOCKET socket_t; +typedef int socklen_t; +#else + #include + #include + #include + #include + #include + #include +typedef int socket_t; +#endif + +#include +#include "exceptions.h" +#include "constants.h" + +class SocketException : public BaseException +{ +public: + SocketException(const char *s): + BaseException(s) + { + } +}; + +class ResolveError : public BaseException +{ +public: + ResolveError(const char *s): + BaseException(s) + { + } +}; + +class SendFailedException : public BaseException +{ +public: + SendFailedException(const char *s): + BaseException(s) + { + } +}; + +void sockets_init(); +void sockets_cleanup(); + +class Address +{ +public: + Address(); + Address(unsigned int address, unsigned short port); + Address(unsigned int a, unsigned int b, + unsigned int c, unsigned int d, + unsigned short port); + bool operator==(Address &address); + bool operator!=(Address &address); + void Resolve(const char *name); + unsigned int getAddress() const; + unsigned short getPort() const; + void setAddress(unsigned int address); + void setAddress(unsigned int a, unsigned int b, + unsigned int c, unsigned int d); + void setPort(unsigned short port); + void print(std::ostream *s) const; + void print() const; + std::string serializeString(); +private: + unsigned int m_address; + unsigned short m_port; +}; + +class UDPSocket +{ +public: + UDPSocket(); + ~UDPSocket(); + void Bind(unsigned short port); + //void Close(); + //bool IsOpen(); + void Send(const Address & destination, const void * data, int size); + // Returns -1 if there is no data + int Receive(Address & sender, void * data, int size); + int GetHandle(); // For debugging purposes only + void setTimeoutMs(int timeout_ms); + // Returns true if there is data, false if timeout occurred + bool WaitData(int timeout_ms); +private: + int m_handle; + int m_timeout_ms; +}; + +#endif + diff --git a/src/sqlite/CMakeLists.txt b/src/sqlite/CMakeLists.txt new file mode 100644 index 0000000..2536255 --- /dev/null +++ b/src/sqlite/CMakeLists.txt @@ -0,0 +1,16 @@ +if( UNIX ) + set(sqlite3_SRCS sqlite3.c) + set(sqlite3_platform_LIBS "") +else( UNIX ) + set(sqlite3_SRCS sqlite3.c) + set(sqlite3_platform_LIBS "") +endif( UNIX ) + +add_library(sqlite3 ${sqlite3_SRCS}) + +target_link_libraries( + sqlite3 + ${sqlite3_platform_LIBS} +) + + diff --git a/src/sqlite/sqlite3.c b/src/sqlite/sqlite3.c new file mode 100644 index 0000000..2c426c2 --- /dev/null +++ b/src/sqlite/sqlite3.c @@ -0,0 +1,128416 @@ +/****************************************************************************** +** This file is an amalgamation of many separate C source files from SQLite +** version 3.7.7.1. By combining all the individual C code files into this +** single large file, the entire code can be compiled as a single translation +** unit. This allows many compilers to do optimizations that would not be +** possible if the files were compiled separately. Performance improvements +** of 5% or more are commonly seen when SQLite is compiled as a single +** translation unit. +** +** This file is all you need to compile SQLite. To use SQLite in other +** programs, you need this file and the "sqlite3.h" header file that defines +** the programming interface to the SQLite library. (If you do not have +** the "sqlite3.h" header file at hand, you will find a copy embedded within +** the text of this file. Search for "Begin file sqlite3.h" to find the start +** of the embedded sqlite3.h header file.) Additional code files may be needed +** if you want a wrapper to interface SQLite with your choice of programming +** language. The code for the "sqlite3" command-line shell is also in a +** separate file. This file contains only code for the core SQLite library. +*/ +#define SQLITE_CORE 1 +#define SQLITE_AMALGAMATION 1 +#ifndef SQLITE_PRIVATE +# define SQLITE_PRIVATE static +#endif +#ifndef SQLITE_API +# define SQLITE_API +#endif +/************** Begin file sqliteInt.h ***************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Internal interface definitions for SQLite. +** +*/ +#ifndef _SQLITEINT_H_ +#define _SQLITEINT_H_ + +/* +** These #defines should enable >2GB file support on POSIX if the +** underlying operating system supports it. If the OS lacks +** large file support, or if the OS is windows, these should be no-ops. +** +** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any +** system #includes. Hence, this block of code must be the very first +** code in all source files. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: Red Hat 7.2) but you want your code to work +** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in Red Hat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +/* +** Include the configuration header output by 'configure' if we're using the +** autoconf-based build +*/ +#ifdef _HAVE_SQLITE_CONFIG_H +#include "config.h" +#endif + +/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ +/************** Begin file sqliteLimit.h *************************************/ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file defines various limits of what SQLite can process. +*/ + +/* +** The maximum length of a TEXT or BLOB in bytes. This also +** limits the size of a row in a table or index. +** +** The hard limit is the ability of a 32-bit signed integer +** to count the size: 2^31-1 or 2147483647. +*/ +#ifndef SQLITE_MAX_LENGTH +# define SQLITE_MAX_LENGTH 1000000000 +#endif + +/* +** This is the maximum number of +** +** * Columns in a table +** * Columns in an index +** * Columns in a view +** * Terms in the SET clause of an UPDATE statement +** * Terms in the result set of a SELECT statement +** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. +** * Terms in the VALUES clause of an INSERT statement +** +** The hard upper limit here is 32676. Most database people will +** tell you that in a well-normalized database, you usually should +** not have more than a dozen or so columns in any table. And if +** that is the case, there is no point in having more than a few +** dozen values in any of the other situations described above. +*/ +#ifndef SQLITE_MAX_COLUMN +# define SQLITE_MAX_COLUMN 2000 +#endif + +/* +** The maximum length of a single SQL statement in bytes. +** +** It used to be the case that setting this value to zero would +** turn the limit off. That is no longer true. It is not possible +** to turn this limit off. +*/ +#ifndef SQLITE_MAX_SQL_LENGTH +# define SQLITE_MAX_SQL_LENGTH 1000000000 +#endif + +/* +** The maximum depth of an expression tree. This is limited to +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might +** want to place more severe limits on the complexity of an +** expression. +** +** A value of 0 used to mean that the limit was not enforced. +** But that is no longer true. The limit is now strictly enforced +** at all times. +*/ +#ifndef SQLITE_MAX_EXPR_DEPTH +# define SQLITE_MAX_EXPR_DEPTH 1000 +#endif + +/* +** The maximum number of terms in a compound SELECT statement. +** The code generator for compound SELECT statements does one +** level of recursion for each term. A stack overflow can result +** if the number of terms is too large. In practice, most SQL +** never has more than 3 or 4 terms. Use a value of 0 to disable +** any limit on the number of terms in a compount SELECT. +*/ +#ifndef SQLITE_MAX_COMPOUND_SELECT +# define SQLITE_MAX_COMPOUND_SELECT 500 +#endif + +/* +** The maximum number of opcodes in a VDBE program. +** Not currently enforced. +*/ +#ifndef SQLITE_MAX_VDBE_OP +# define SQLITE_MAX_VDBE_OP 25000 +#endif + +/* +** The maximum number of arguments to an SQL function. +*/ +#ifndef SQLITE_MAX_FUNCTION_ARG +# define SQLITE_MAX_FUNCTION_ARG 127 +#endif + +/* +** The maximum number of in-memory pages to use for the main database +** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE +*/ +#ifndef SQLITE_DEFAULT_CACHE_SIZE +# define SQLITE_DEFAULT_CACHE_SIZE 2000 +#endif +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 +#endif + +/* +** The default number of frames to accumulate in the log file before +** checkpointing the database in WAL mode. +*/ +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 +#endif + +/* +** The maximum number of attached databases. This must be between 0 +** and 62. The upper bound on 62 is because a 64-bit integer bitmap +** is used internally to track attached databases. +*/ +#ifndef SQLITE_MAX_ATTACHED +# define SQLITE_MAX_ATTACHED 10 +#endif + + +/* +** The maximum value of a ?nnn wildcard that the parser will accept. +*/ +#ifndef SQLITE_MAX_VARIABLE_NUMBER +# define SQLITE_MAX_VARIABLE_NUMBER 999 +#endif + +/* Maximum page size. The upper bound on this value is 65536. This a limit +** imposed by the use of 16-bit offsets within each page. +** +** Earlier versions of SQLite allowed the user to change this value at +** compile time. This is no longer permitted, on the grounds that it creates +** a library that is technically incompatible with an SQLite library +** compiled with a different limit. If a process operating on a database +** with a page-size of 65536 bytes crashes, then an instance of SQLite +** compiled with the default page-size limit will not be able to rollback +** the aborted transaction. This could lead to database corruption. +*/ +#ifdef SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_PAGE_SIZE +#endif +#define SQLITE_MAX_PAGE_SIZE 65536 + + +/* +** The default size of a database page. +*/ +#ifndef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE 1024 +#endif +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + +/* +** Ordinarily, if no value is explicitly provided, SQLite creates databases +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain +** device characteristics (sector-size and atomic write() support), +** SQLite may choose a larger value. This constant is the maximum value +** SQLite will choose on its own. +*/ +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 +#endif +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + + +/* +** Maximum number of pages in one database file. +** +** This is really just the default value for the max_page_count pragma. +** This value can be lowered (or raised) at run-time using that the +** max_page_count macro. +*/ +#ifndef SQLITE_MAX_PAGE_COUNT +# define SQLITE_MAX_PAGE_COUNT 1073741823 +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Maximum depth of recursion for triggers. +** +** A value of 1 means that a trigger program will not be able to itself +** fire any triggers. A value of 0 means that no trigger programs at all +** may be executed. +*/ +#ifndef SQLITE_MAX_TRIGGER_DEPTH +# define SQLITE_MAX_TRIGGER_DEPTH 1000 +#endif + +/************** End of sqliteLimit.h *****************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/* Disable nuisance warnings on Borland compilers */ +#if defined(__BORLANDC__) +#pragma warn -rch /* unreachable code */ +#pragma warn -ccc /* Condition is always true or false */ +#pragma warn -aus /* Assigned value is never used */ +#pragma warn -csu /* Comparing signed and unsigned */ +#pragma warn -spa /* Suspicious pointer arithmetic */ +#endif + +/* Needed for various definitions... */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE +#endif + +/* +** Include standard header files as necessary +*/ +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif + +/* +** The number of samples of an index that SQLite takes in order to +** construct a histogram of the table content when running ANALYZE +** and with SQLITE_ENABLE_STAT2 +*/ +#define SQLITE_INDEX_SAMPLES 10 + +/* +** The following macros are used to cast pointers to integers and +** integers to pointers. The way you do this varies from one compiler +** to the next, so we have developed the following set of #if statements +** to generate appropriate macros for a wide range of compilers. +** +** The correct "ANSI" way to do this is to use the intptr_t type. +** Unfortunately, that typedef is not available on all compilers, or +** if it is available, it requires an #include of specific headers +** that vary from one machine to the next. +** +** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on +** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). +** So we have to define the macros in different ways depending on the +** compiler. +*/ +#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ +# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) +#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ +# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) +# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) +#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ +# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) +#else /* Generates a warning - but it always works */ +# define SQLITE_INT_TO_PTR(X) ((void*)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(X)) +#endif + +/* +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. +** 0 means mutexes are permanently disable and the library is never +** threadsafe. 1 means the library is serialized which is the highest +** level of threadsafety. 2 means the libary is multithreaded - multiple +** threads can use SQLite as long as no two threads try to use the same +** database connection at the same time. +** +** Older versions of SQLite used an optional THREADSAFE macro. +** We support that for legacy. +*/ +#if !defined(SQLITE_THREADSAFE) +#if defined(THREADSAFE) +# define SQLITE_THREADSAFE THREADSAFE +#else +# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ +#endif +#endif + +/* +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. +** It determines whether or not the features related to +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can +** be overridden at runtime using the sqlite3_config() API. +*/ +#if !defined(SQLITE_DEFAULT_MEMSTATUS) +# define SQLITE_DEFAULT_MEMSTATUS 1 +#endif + +/* +** Exactly one of the following macros must be defined in order to +** specify which memory allocation subsystem to use. +** +** SQLITE_SYSTEM_MALLOC // Use normal system malloc() +** SQLITE_MEMDEBUG // Debugging version of system malloc() +** +** (Historical note: There used to be several other options, but we've +** pared it down to just these two.) +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ +#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1 +# error "At most one of the following compile-time configuration options\ + is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG" +#endif +#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0 +# define SQLITE_SYSTEM_MALLOC 1 +#endif + +/* +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the +** sizes of memory allocations below this value where possible. +*/ +#if !defined(SQLITE_MALLOC_SOFT_LIMIT) +# define SQLITE_MALLOC_SOFT_LIMIT 1024 +#endif + +/* +** We need to define _XOPEN_SOURCE as follows in order to enable +** recursive mutexes on most Unix systems. But Mac OS X is different. +** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, +** so it is omitted there. See ticket #2673. +** +** Later we learn that _XOPEN_SOURCE is poorly or incorrectly +** implemented on some systems. So we avoid defining it at all +** if it is already defined or if it is unneeded because we are +** not doing a threadsafe build. Ticket #2681. +** +** See also ticket #2741. +*/ +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE +# define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ +#endif + +/* +** The TCL headers are only needed when compiling the TCL bindings. +*/ +#if defined(SQLITE_TCL) || defined(TCLSH) +# include +#endif + +/* +** Many people are failing to set -DNDEBUG=1 when compiling SQLite. +** Setting NDEBUG makes the code smaller and run faster. So the following +** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1 +** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out +** feature. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +/* +** The testcase() macro is used to aid in coverage testing. When +** doing coverage testing, the condition inside the argument to +** testcase() must be evaluated both true and false in order to +** get full branch coverage. The testcase() macro is inserted +** to help ensure adequate test coverage in places where simple +** condition/decision coverage is inadequate. For example, testcase() +** can be used to make sure boundary values are tested. For +** bitmask tests, testcase() can be used to make sure each bit +** is significant and used at least once. On switch statements +** where multiple cases go to the same block of code, testcase() +** can insure that all cases are evaluated. +** +*/ +#ifdef SQLITE_COVERAGE_TEST +SQLITE_PRIVATE void sqlite3Coverage(int); +# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +#else +# define testcase(X) +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +/* +** Sometimes we need a small amount of code such as a variable initialization +** to setup for a later assert() statement. We do not want this code to +** appear when assert() is disabled. The following macro is therefore +** used to contain that setup code. The "VVA" acronym stands for +** "Verification, Validation, and Accreditation". In other words, the +** code within VVA_ONLY() will only run during verification processes. +*/ +#ifndef NDEBUG +# define VVA_ONLY(X) X +#else +# define VVA_ONLY(X) +#endif + +/* +** The ALWAYS and NEVER macros surround boolean expressions which +** are intended to always be true or false, respectively. Such +** expressions could be omitted from the code completely. But they +** are included in a few cases in order to enhance the resilience +** of SQLite to unexpected behavior - to make the code "self-healing" +** or "ductile" rather than being "brittle" and crashing at the first +** hint of unplanned behavior. +** +** In other words, ALWAYS and NEVER are added for defensive code. +** +** When doing coverage testing ALWAYS and NEVER are hard-coded to +** be true and false so that the unreachable code then specify will +** not be counted as untested code. +*/ +#if defined(SQLITE_COVERAGE_TEST) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif + +/* +** Return true (non-zero) if the input is a integer that is too large +** to fit in 32-bits. This macro is used inside of various testcase() +** macros to verify that we have tested SQLite for large-file support. +*/ +#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) + +/* +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. GCC is able to +** use these hints to generate better code, sometimes. +*/ +#if defined(__GNUC__) && 0 +# define likely(X) __builtin_expect((X),1) +# define unlikely(X) __builtin_expect((X),0) +#else +# define likely(X) !!(X) +# define unlikely(X) !!(X) +#endif + +/************** Include sqlite3.h in the middle of sqliteInt.h ***************/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve the right to make minor changes +** if experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +#ifndef SQLITE_API +# define SQLITE_API +#endif + + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.7.7.1" +#define SQLITE_VERSION_NUMBER 3007007 +#define SQLITE_SOURCE_ID "2011-06-28 17:39:05 af0d91adf497f5f36ec3813f04235a6e195a605f" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** is its destructor. There are many other interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() routine is the destructor for the [sqlite3] object. +** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is +** successfully destroyed and all associated resources are deallocated. +** +** Applications must [sqlite3_finalize | finalize] all [prepared statements] +** and [sqlite3_blob_close | close] all [BLOB handles] associated with +** the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close() is called on a [database connection] that still has +** outstanding [prepared statements] or [BLOB handles], then it returns +** SQLITE_BUSY. +** +** ^If [sqlite3_close()] is invoked while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() with a NULL pointer argument is a +** harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicates success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes], +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* Reserved: 0x00F00000 */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +** +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specialized VFSes +** that do require it. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 + + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 10 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_MASTER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc and xFree methods must work like the +** malloc() and free() functions from the standard C library. +** The xRealloc method must work like realloc() from the standard C library +** with the exception that if the second argument to xRealloc is zero, +** xRealloc must be a no-op - it must not perform any allocation or +** deallocation. ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** And so in cases where xRoundup always returns a positive number, +** xRealloc can perform exactly as the standard library realloc() and +** still be in compliance with this specification. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
+**
^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
+**
^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scratch allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
+** +** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+**
^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implementation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
+** +** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
+**
^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2^12. Reasonable values +** for the minimum allocation size are 2^5 through 2^8.
+** +** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+**
^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
+** +** [[SQLITE_CONFIG_PCACHE]]
SQLITE_CONFIG_PCACHE
+**
^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
+** +** [[SQLITE_CONFIG_GETPCACHE]]
SQLITE_CONFIG_GETPCACHE
+**
^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods] object. SQLite copies of the current +** page cache implementation into that object.)^
+** +** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+**
^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI +**
This option takes a single argument of type int. If non-zero, then +** URI handling is globally enabled. If the parameter is zero, then URI handling +** is globally disabled. If URI handling is globally enabled, all filenames +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined. +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ +#define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_DBCONFIG_LOOKASIDE
+**
^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to a memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
+** +**
SQLITE_DBCONFIG_ENABLE_FKEY
+**
^This option is used to enable or disable the enforcement of +** [foreign key constraints]. There should be two additional arguments. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
+** +**
SQLITE_DBCONFIG_ENABLE_TRIGGER
+**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back.
+** +**
+*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^As of SQLite version 3.7.7, this routines +** records the last insert rowid of both ordinary tables and [virtual tables]. +** ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger or within a [virtual table] +** method, then this routine will return the [rowid] of the inserted +** row as long as the trigger or virtual table method is running. +** But once the trigger or virtual table method ends, the value returned +** by this routine reverts to what it was before the trigger or virtual +** table method began.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
+**  char *zText = "It's a happy day!";
+** 
+** +** One can use this text in an SQL statement as follows: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
+**  INSERT INTO table1 VALUES('It''s a happy day!')
+** 
+** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
+**  INSERT INTO table1 VALUES('It's a happy day!');
+** 
+** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** The Windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] +** from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

URI Filenames

+** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the fourth argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** As of SQLite version 3.7.7, URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^On windows, the first component of an absolute path +** is a drive specification (e.g. "C:"). +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite interprets the following three query parameters: +** +**
    +**
  • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
  • mode: ^(The mode parameter may be set to either "ro", "rw" or +** "rwc". Attempting to set it to any other value is an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_prepare_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is +** used, it is an error to specify a value for the mode parameter that is +** less restrictive than that specified by the flags passed as the third +** parameter. +** +**
  • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behaviour requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +**
+** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

URI filename examples

+** +** +**
URI filenames Results +**
file:data.db +** Open the file "data.db" in the current directory. +**
file:/home/fred/data.db
+** file:///home/fred/data.db
+** file://localhost/home/fred/data.db
+** Open the database file "/home/fred/data.db". +**
file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
file:/home/fred/data.db?vfs=unix-nolock +** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". +**
file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +**
+** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** This is a utility routine, useful to VFS implementations, that checks +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of the query parameter. +** +** The zFilename argument is the filename pointer passed into the xOpen() +** method of a VFS implementation. The zParam argument is the name of the +** query parameter we seek. This routine returns the value of the zParam +** parameter if it exists. If the parameter does not exist, this routine +** returns a NULL pointer. +** +** If the zFilename argument to this function is not a pointer that SQLite +** passed into the xOpen VFS method, then the behavior of this routine +** is undefined and probably undesirable. +*/ +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); + + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
    +**
  1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
  2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
)^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled. +** the +**
  6. +**
+*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter is negative, the length of the string is +** the number of bytes up to the first zero terminator. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is NULL pointer +**
NULL BLOB Result is NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER Convert from float to integer +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB Same as FLOAT->TEXT +**
TEXT INTEGER Use atoi() +**
TEXT FLOAT Use atof() +**
TEXT BLOB No change +**
BLOB INTEGER Convert to TEXT then use atoi() +**
BLOB FLOAT Convert to TEXT then use atof() +**
BLOB TEXT Add a zero terminator if needed +**
+**
)^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is +** less than or equal to zero or if a memory allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** The following two functions may be used by scalar SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** metadata associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If no metadata has been ever +** been set for the Nth argument of the function, or if the corresponding +** function parameter has changed since the meta-data was set, +** then sqlite3_get_auxdata() returns a NULL pointer. +** +** ^The sqlite3_set_auxdata() interface saves the metadata +** pointed to by its 3rd parameter as the metadata for the N-th +** argument of the application-defined function. Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** ^If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the metadata when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. +** +** SQLite is free to call the destructor and drop metadata on any +** parameter of any function at any time. ^The only guarantee is that +** the destructor will be called before the metadata is dropped. +** +** ^(In practice, metadata is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and [parameters].)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_toobig() interface causes SQLite to throw an error +** indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_nomem() interface causes SQLite to throw an error +** indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +SQLITE_API void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +*/ +SQLITE_API char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** KEYWORDS: {shared cache} +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The soft heap limit is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** SQLite extension library contained in the file zFile. +** +** ^The entry point is zProc. +** ^zProc may be 0, in which case the name of the entry point +** defaults to "sqlite3_extension_init". +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. See ticket #1863. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked SQLite extension +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()]. +*/ +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_OS2 +**
  • SQLITE_MUTEX_PTHREAD +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
)^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on OS/2, Unix, and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_LRU2 +**
)^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provided versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_PGHDRSZ 17 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 18 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 19 +#define SQLITE_TESTCTRL_LAST 19 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
+**
This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
)^ +** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
)^ +** +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
+**
This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
+**
This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_MAX 6 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+** +**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will not be a power of two. ^szPage +** will the page size of the database file that is to be cached plus an +** increment (here called "R") of less than 250. SQLite will use the +** extra R bytes on each page to store metadata about the underlying +** database page on disk. The value of R depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^(R is constant for a particular build of SQLite. Except, there are two +** distinct values of R when SQLite is compiled with the proprietary +** ZIPVFS extension.)^ ^The second argument to +** xCreate(), bPurgeable, is true if the cache being created will +** be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** the page, or a NULL pointer. +** A "page", in this context, means a buffer of szPage bytes aligned at an +** 8-byte boundary. The page to be fetched is determined by the key. ^The +** minimum key value is 1. After it has been retrieved using xFetch, the page +** is considered to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behaviour when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods +** functions. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_strnicmp()] API allows applications and extensions to +** compare the contents of two buffers containing UTF-8 strings in a +** case-independent fashion, using the same definition of case independence +** that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the error log +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +** +** See also: [sqlite3_wal_checkpoint_v2()] +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** +** Run a checkpoint operation on WAL database zDb attached to database +** handle db. The specific operation is determined by the value of the +** eMode parameter: +** +**
+**
SQLITE_CHECKPOINT_PASSIVE
+** Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish. Sync the db file if all frames in the log +** are checkpointed. This mode is the same as calling +** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. +** +**
SQLITE_CHECKPOINT_FULL
+** This mode blocks (calls the busy-handler callback) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. It then checkpoints all frames in the log file and syncs the +** database file. This call blocks database writers while it is running, +** but not database readers. +** +**
SQLITE_CHECKPOINT_RESTART
+** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after +** checkpointing the log file it blocks (calls the busy-handler callback) +** until all readers are reading from the database file only. This ensures +** that the next client to write to the database file restarts the log file +** from the beginning. This call blocks database writers while it is running, +** but not database readers. +**
+** +** If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to +** the total number of checkpointed frames (including any that were already +** checkpointed when this function is called). *pnLog and *pnCkpt may be +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. +** If no values are available because of an error, they are both set to -1 +** before returning to communicate this to the caller. +** +** All calls obtain an exclusive "checkpoint" lock on the database file. If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive +** "writer" lock on the database file. If the writer lock cannot be obtained +** immediately, and a busy-handler is configured, it is invoked and the writer +** lock retried until either the busy-handler returns 0 or the lock is +** successfully obtained. The busy-handler is also invoked while waiting for +** database readers as described above. If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. SQLITE_BUSY is returned in this case. +** +** If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned to the caller. If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code returned to the caller immediately. If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint operation parameters +** +** These constants can be used as the 3rd parameter to +** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] +** documentation for additional information about the meaning and use of +** each of these values. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 +#define SQLITE_CHECKPOINT_FULL 1 +#define SQLITE_CHECKPOINT_RESTART 2 + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** At present, there is only one option that may be configured using +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options +** may be added in the future. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
+**
SQLITE_VTAB_CONSTRAINT_SUPPORT +**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
+*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Conflict resolution modes +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + + + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#if 0 +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, + int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes), + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#if 0 +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include hash.h in the middle of sqliteInt.h ******************/ +/************** Begin file hash.h ********************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implemenation +** used in SQLite. +*/ +#ifndef _SQLITE_HASH_H_ +#define _SQLITE_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Hash Hash; +typedef struct HashElem HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, some of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +** +** All elements of the hash table are on a single doubly-linked list. +** Hash.first points to the head of this list. +** +** There are Hash.htsize buckets. Each bucket points to a spot in +** the global doubly-linked list. The contents of the bucket are the +** element pointed to plus the next _ht.count-1 elements in the list. +** +** Hash.htsize and Hash.ht may be zero. In that case lookup is done +** by a linear search of the global list. For small tables, the +** Hash.ht table is never allocated because if there are few elements +** in the table, it is faster to do a linear search than to manage +** the hash table. +*/ +struct Hash { + unsigned int htsize; /* Number of buckets in the hash table */ + unsigned int count; /* Number of entries in this table */ + HashElem *first; /* The first element of the array */ + struct _ht { /* the hash table */ + int count; /* Number of entries with this hash */ + HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct HashElem { + HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + const char *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +SQLITE_PRIVATE void sqlite3HashInit(Hash*); +SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); +SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); +SQLITE_PRIVATE void sqlite3HashClear(Hash*); + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Hash h; +** HashElem *p; +** ... +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ +** SomeStructure *pData = sqliteHashData(p); +** // do something with pData +** } +*/ +#define sqliteHashFirst(H) ((H)->first) +#define sqliteHashNext(E) ((E)->next) +#define sqliteHashData(E) ((E)->data) +/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ +/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ + +/* +** Number of entries in a hash table +*/ +/* #define sqliteHashCount(H) ((H)->count) // NOT USED */ + +#endif /* _SQLITE_HASH_H_ */ + +/************** End of hash.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include parse.h in the middle of sqliteInt.h *****************/ +/************** Begin file parse.h *******************************************/ +#define TK_SEMI 1 +#define TK_EXPLAIN 2 +#define TK_QUERY 3 +#define TK_PLAN 4 +#define TK_BEGIN 5 +#define TK_TRANSACTION 6 +#define TK_DEFERRED 7 +#define TK_IMMEDIATE 8 +#define TK_EXCLUSIVE 9 +#define TK_COMMIT 10 +#define TK_END 11 +#define TK_ROLLBACK 12 +#define TK_SAVEPOINT 13 +#define TK_RELEASE 14 +#define TK_TO 15 +#define TK_TABLE 16 +#define TK_CREATE 17 +#define TK_IF 18 +#define TK_NOT 19 +#define TK_EXISTS 20 +#define TK_TEMP 21 +#define TK_LP 22 +#define TK_RP 23 +#define TK_AS 24 +#define TK_COMMA 25 +#define TK_ID 26 +#define TK_INDEXED 27 +#define TK_ABORT 28 +#define TK_ACTION 29 +#define TK_AFTER 30 +#define TK_ANALYZE 31 +#define TK_ASC 32 +#define TK_ATTACH 33 +#define TK_BEFORE 34 +#define TK_BY 35 +#define TK_CASCADE 36 +#define TK_CAST 37 +#define TK_COLUMNKW 38 +#define TK_CONFLICT 39 +#define TK_DATABASE 40 +#define TK_DESC 41 +#define TK_DETACH 42 +#define TK_EACH 43 +#define TK_FAIL 44 +#define TK_FOR 45 +#define TK_IGNORE 46 +#define TK_INITIALLY 47 +#define TK_INSTEAD 48 +#define TK_LIKE_KW 49 +#define TK_MATCH 50 +#define TK_NO 51 +#define TK_KEY 52 +#define TK_OF 53 +#define TK_OFFSET 54 +#define TK_PRAGMA 55 +#define TK_RAISE 56 +#define TK_REPLACE 57 +#define TK_RESTRICT 58 +#define TK_ROW 59 +#define TK_TRIGGER 60 +#define TK_VACUUM 61 +#define TK_VIEW 62 +#define TK_VIRTUAL 63 +#define TK_REINDEX 64 +#define TK_RENAME 65 +#define TK_CTIME_KW 66 +#define TK_ANY 67 +#define TK_OR 68 +#define TK_AND 69 +#define TK_IS 70 +#define TK_BETWEEN 71 +#define TK_IN 72 +#define TK_ISNULL 73 +#define TK_NOTNULL 74 +#define TK_NE 75 +#define TK_EQ 76 +#define TK_GT 77 +#define TK_LE 78 +#define TK_LT 79 +#define TK_GE 80 +#define TK_ESCAPE 81 +#define TK_BITAND 82 +#define TK_BITOR 83 +#define TK_LSHIFT 84 +#define TK_RSHIFT 85 +#define TK_PLUS 86 +#define TK_MINUS 87 +#define TK_STAR 88 +#define TK_SLASH 89 +#define TK_REM 90 +#define TK_CONCAT 91 +#define TK_COLLATE 92 +#define TK_BITNOT 93 +#define TK_STRING 94 +#define TK_JOIN_KW 95 +#define TK_CONSTRAINT 96 +#define TK_DEFAULT 97 +#define TK_NULL 98 +#define TK_PRIMARY 99 +#define TK_UNIQUE 100 +#define TK_CHECK 101 +#define TK_REFERENCES 102 +#define TK_AUTOINCR 103 +#define TK_ON 104 +#define TK_INSERT 105 +#define TK_DELETE 106 +#define TK_UPDATE 107 +#define TK_SET 108 +#define TK_DEFERRABLE 109 +#define TK_FOREIGN 110 +#define TK_DROP 111 +#define TK_UNION 112 +#define TK_ALL 113 +#define TK_EXCEPT 114 +#define TK_INTERSECT 115 +#define TK_SELECT 116 +#define TK_DISTINCT 117 +#define TK_DOT 118 +#define TK_FROM 119 +#define TK_JOIN 120 +#define TK_USING 121 +#define TK_ORDER 122 +#define TK_GROUP 123 +#define TK_HAVING 124 +#define TK_LIMIT 125 +#define TK_WHERE 126 +#define TK_INTO 127 +#define TK_VALUES 128 +#define TK_INTEGER 129 +#define TK_FLOAT 130 +#define TK_BLOB 131 +#define TK_REGISTER 132 +#define TK_VARIABLE 133 +#define TK_CASE 134 +#define TK_WHEN 135 +#define TK_THEN 136 +#define TK_ELSE 137 +#define TK_INDEX 138 +#define TK_ALTER 139 +#define TK_ADD 140 +#define TK_TO_TEXT 141 +#define TK_TO_BLOB 142 +#define TK_TO_NUMERIC 143 +#define TK_TO_INT 144 +#define TK_TO_REAL 145 +#define TK_ISNOT 146 +#define TK_END_OF_FILE 147 +#define TK_ILLEGAL 148 +#define TK_SPACE 149 +#define TK_UNCLOSED_STRING 150 +#define TK_FUNCTION 151 +#define TK_COLUMN 152 +#define TK_AGG_FUNCTION 153 +#define TK_AGG_COLUMN 154 +#define TK_CONST_FUNC 155 +#define TK_UMINUS 156 +#define TK_UPLUS 157 + +/************** End of parse.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +#include +#include +#include +#include +#include + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite_int64 +# define float sqlite_int64 +# define LONGDOUBLE_TYPE sqlite_int64 +# ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +# endif +# define SQLITE_OMIT_DATETIME_FUNCS 1 +# define SQLITE_OMIT_TRACE 1 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +# undef SQLITE_HAVE_ISNAN +#endif +#ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (1e99) +#endif + +/* +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 +** afterward. Having this macro allows us to cause the C compiler +** to omit code used by TEMP tables without messy #ifndef statements. +*/ +#ifdef SQLITE_OMIT_TEMPDB +#define OMIT_TEMPDB 1 +#else +#define OMIT_TEMPDB 0 +#endif + +/* +** The "file format" number is an integer that is incremented whenever +** the VDBE-level file format changes. The following macros define the +** the default file format for new databases and the maximum file format +** that the library can read. +*/ +#define SQLITE_MAX_FILE_FORMAT 4 +#ifndef SQLITE_DEFAULT_FILE_FORMAT +# define SQLITE_DEFAULT_FILE_FORMAT 1 +#endif + +/* +** Determine whether triggers are recursive by default. This can be +** changed at run-time using a pragma. +*/ +#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS +# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 +#endif + +/* +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** on the command-line +*/ +#ifndef SQLITE_TEMP_STORE +# define SQLITE_TEMP_STORE 1 +#endif + +/* +** GCC does not define the offsetof() macro so we'll have to do it +** ourselves. +*/ +#ifndef offsetof +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +#endif + +/* +** Check to see if this machine uses EBCDIC. (Yes, believe it or +** not, there are still machines out there that use EBCDIC.) +*/ +#if 'A' == '\301' +# define SQLITE_EBCDIC 1 +#else +# define SQLITE_ASCII 1 +#endif + +/* +** Integers of known sizes. These typedefs might change for architectures +** where the sizes very. Preprocessor macros are available so that the +** types can be conveniently redefined at compile-type. Like this: +** +** cc '-DUINTPTR_TYPE=long long int' ... +*/ +#ifndef UINT32_TYPE +# ifdef HAVE_UINT32_T +# define UINT32_TYPE uint32_t +# else +# define UINT32_TYPE unsigned int +# endif +#endif +#ifndef UINT16_TYPE +# ifdef HAVE_UINT16_T +# define UINT16_TYPE uint16_t +# else +# define UINT16_TYPE unsigned short int +# endif +#endif +#ifndef INT16_TYPE +# ifdef HAVE_INT16_T +# define INT16_TYPE int16_t +# else +# define INT16_TYPE short int +# endif +#endif +#ifndef UINT8_TYPE +# ifdef HAVE_UINT8_T +# define UINT8_TYPE uint8_t +# else +# define UINT8_TYPE unsigned char +# endif +#endif +#ifndef INT8_TYPE +# ifdef HAVE_INT8_T +# define INT8_TYPE int8_t +# else +# define INT8_TYPE signed char +# endif +#endif +#ifndef LONGDOUBLE_TYPE +# define LONGDOUBLE_TYPE long double +#endif +typedef sqlite_int64 i64; /* 8-byte signed integer */ +typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ +typedef INT16_TYPE i16; /* 2-byte signed integer */ +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ +typedef INT8_TYPE i8; /* 1-byte signed integer */ + +/* +** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value +** that can be stored in a u32 without loss of data. The value +** is 0x00000000ffffffff. But because of quirks of some compilers, we +** have to specify the value in the less intuitive manner shown: +*/ +#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) + +/* +** Macros to determine whether the machine is big or little endian, +** evaluated at runtime. +*/ +#ifdef SQLITE_AMALGAMATION +SQLITE_PRIVATE const int sqlite3one = 1; +#else +SQLITE_PRIVATE const int sqlite3one; +#endif +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ + || defined(__x86_64) || defined(__x86_64__) +# define SQLITE_BIGENDIAN 0 +# define SQLITE_LITTLEENDIAN 1 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else +# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) +#endif + +/* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + +/* +** Round up a number to the next larger multiple of 8. This is used +** to force 8-byte alignment on 64-bit architectures. +*/ +#define ROUND8(x) (((x)+7)&~7) + +/* +** Round down to the nearest multiple of 8 +*/ +#define ROUNDDOWN8(x) ((x)&~7) + +/* +** Assert that the pointer X is aligned to an 8-byte boundary. This +** macro is used only within assert() to verify that the code gets +** all alignment restrictions correct. +** +** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the +** underlying malloc() implemention might return us 4-byte aligned +** pointers. In that case, only verify 4-byte alignment. +*/ +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) +#else +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) +#endif + + +/* +** An instance of the following structure is used to store the busy-handler +** callback for a given sqlite handle. +** +** The sqlite.busyHandler member of the sqlite struct contains the busy +** callback for the database handle. Each pager opened via the sqlite +** handle is passed a pointer to sqlite.busyHandler. The busy-handler +** callback is currently invoked only from within pager.c. +*/ +typedef struct BusyHandler BusyHandler; +struct BusyHandler { + int (*xFunc)(void *,int); /* The busy callback */ + void *pArg; /* First arg to busy callback */ + int nBusy; /* Incremented with each busy call */ +}; + +/* +** Name of the master database table. The master database table +** is a special table that holds the names and attributes of all +** user tables and indices. +*/ +#define MASTER_NAME "sqlite_master" +#define TEMP_MASTER_NAME "sqlite_temp_master" + +/* +** The root-page of the master database table. +*/ +#define MASTER_ROOT 1 + +/* +** The name of the schema table. +*/ +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + +/* +** A convenience macro that returns the number of elements in +** an array. +*/ +#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) + +/* +** The following value as a destructor means to use sqlite3DbFree(). +** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT. +*/ +#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree) + +/* +** When SQLITE_OMIT_WSD is defined, it means that the target platform does +** not support Writable Static Data (WSD) such as global and static variables. +** All variables must either be on the stack or dynamically allocated from +** the heap. When WSD is unsupported, the variable declarations scattered +** throughout the SQLite code must become constants instead. The SQLITE_WSD +** macro is used for this purpose. And instead of referencing the variable +** directly, we use its constant as a key to lookup the run-time allocated +** buffer that holds real variable. The constant is also the initializer +** for the run-time allocated buffer. +** +** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL +** macros become no-ops and have zero performance impact. +*/ +#ifdef SQLITE_OMIT_WSD + #define SQLITE_WSD const + #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) + #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) +SQLITE_API int sqlite3_wsd_init(int N, int J); +SQLITE_API void *sqlite3_wsd_find(void *K, int L); +#else + #define SQLITE_WSD + #define GLOBAL(t,v) v + #define sqlite3GlobalConfig sqlite3Config +#endif + +/* +** The following macros are used to suppress compiler warnings and to +** make it clear to human readers when a function parameter is deliberately +** left unused within the body of a function. This usually happens when +** a function is called via a function pointer. For example the +** implementation of an SQL aggregate step callback may not use the +** parameter indicating the number of arguments passed to the aggregate, +** if it knows that this is enforced elsewhere. +** +** When a function parameter is not used at all within the body of a function, +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. +** However, these macros may also be used to suppress warnings related to +** parameters that may or may not be used depending on compilation options. +** For example those parameters only used in assert() statements. In these +** cases the parameters are named as per the usual conventions. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) + +/* +** Forward references to structures +*/ +typedef struct AggInfo AggInfo; +typedef struct AuthContext AuthContext; +typedef struct AutoincInfo AutoincInfo; +typedef struct Bitvec Bitvec; +typedef struct CollSeq CollSeq; +typedef struct Column Column; +typedef struct Db Db; +typedef struct Schema Schema; +typedef struct Expr Expr; +typedef struct ExprList ExprList; +typedef struct ExprSpan ExprSpan; +typedef struct FKey FKey; +typedef struct FuncDestructor FuncDestructor; +typedef struct FuncDef FuncDef; +typedef struct FuncDefHash FuncDefHash; +typedef struct IdList IdList; +typedef struct Index Index; +typedef struct IndexSample IndexSample; +typedef struct KeyClass KeyClass; +typedef struct KeyInfo KeyInfo; +typedef struct Lookaside Lookaside; +typedef struct LookasideSlot LookasideSlot; +typedef struct Module Module; +typedef struct NameContext NameContext; +typedef struct Parse Parse; +typedef struct RowSet RowSet; +typedef struct Savepoint Savepoint; +typedef struct Select Select; +typedef struct SrcList SrcList; +typedef struct StrAccum StrAccum; +typedef struct Table Table; +typedef struct TableLock TableLock; +typedef struct Token Token; +typedef struct Trigger Trigger; +typedef struct TriggerPrg TriggerPrg; +typedef struct TriggerStep TriggerStep; +typedef struct UnpackedRecord UnpackedRecord; +typedef struct VTable VTable; +typedef struct VtabCtx VtabCtx; +typedef struct Walker Walker; +typedef struct WherePlan WherePlan; +typedef struct WhereInfo WhereInfo; +typedef struct WhereLevel WhereLevel; + +/* +** Defer sourcing vdbe.h and btree.h until after the "u8" and +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque +** pointer types (i.e. FuncDef) defined above. +*/ +/************** Include btree.h in the middle of sqliteInt.h *****************/ +/************** Begin file btree.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite B-Tree file +** subsystem. See comments in the source code for a detailed description +** of what each interface routine does. +*/ +#ifndef _BTREE_H_ +#define _BTREE_H_ + +/* TODO: This definition is just included so other modules compile. It +** needs to be revisited. +*/ +#define SQLITE_N_BTREE_META 10 + +/* +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise +** it must be turned on for each database using "PRAGMA auto_vacuum = 1". +*/ +#ifndef SQLITE_DEFAULT_AUTOVACUUM + #define SQLITE_DEFAULT_AUTOVACUUM 0 +#endif + +#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ +#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ +#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ + +/* +** Forward declarations of structure +*/ +typedef struct Btree Btree; +typedef struct BtCursor BtCursor; +typedef struct BtShared BtShared; + + +SQLITE_PRIVATE int sqlite3BtreeOpen( + sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ + const char *zFilename, /* Name of database file to open */ + sqlite3 *db, /* Associated database connection */ + Btree **ppBtree, /* Return open Btree* here */ + int flags, /* Flags */ + int vfsFlags /* Flags passed through to VFS open */ +); + +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the +** following values. +** +** NOTE: These values must match the corresponding PAGER_ values in +** pager.h. +*/ +#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ +#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */ +#define BTREE_MEMORY 4 /* This is an in-memory DB */ +#define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */ +#define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */ + +SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int); +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*); +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); + +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); + +SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); + +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR +** of the flags shown below. +** +** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. +** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data +** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With +** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored +** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL +** indices.) +*/ +#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ +#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ + +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); + +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); + +/* +** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta +** should be one of the following values. The integer values are assigned +** to constants so that the offset of the corresponding field in an +** SQLite database header may be found using the following formula: +** +** offset = 36 + (idx * 4) +** +** For example, the free-page-count field is located at byte offset 36 of +** the database file header. The incr-vacuum-flag field is located at +** byte offset 64 (== 36+4*7). +*/ +#define BTREE_FREE_PAGE_COUNT 0 +#define BTREE_SCHEMA_VERSION 1 +#define BTREE_FILE_FORMAT 2 +#define BTREE_DEFAULT_CACHE_SIZE 3 +#define BTREE_LARGEST_ROOT_PAGE 4 +#define BTREE_TEXT_ENCODING 5 +#define BTREE_USER_VERSION 6 +#define BTREE_INCR_VACUUM 7 + +SQLITE_PRIVATE int sqlite3BtreeCursor( + Btree*, /* BTree containing table to open */ + int iTable, /* Index of root page */ + int wrFlag, /* 1 for writing. 0 for read-only */ + struct KeyInfo*, /* First argument to compare function */ + BtCursor *pCursor /* Space to write cursor structure */ +); +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); + +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( + BtCursor*, + UnpackedRecord *pUnKey, + i64 intKey, + int bias, + int *pRes +); +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, + const void *pData, int nData, + int nZero, int bias, int seekResult); +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); +SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); + +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); +SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); + +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); + +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); + +#ifndef NDEBUG +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); +#endif + +#ifndef SQLITE_OMIT_BTREECOUNT +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); +SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); +#endif + +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); +#endif + +/* +** If we are not using shared cache, then there is no need to +** use mutexes to access the BtShared structures. So make the +** Enter and Leave procedures no-ops. +*/ +#ifndef SQLITE_OMIT_SHARED_CACHE +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); +#else +# define sqlite3BtreeEnter(X) +# define sqlite3BtreeEnterAll(X) +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE +SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); +SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); +#ifndef NDEBUG + /* These routines are used inside assert() statements only. */ +SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); +SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); +SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); +#endif +#else + +# define sqlite3BtreeSharable(X) 0 +# define sqlite3BtreeLeave(X) +# define sqlite3BtreeEnterCursor(X) +# define sqlite3BtreeLeaveCursor(X) +# define sqlite3BtreeLeaveAll(X) + +# define sqlite3BtreeHoldsMutex(X) 1 +# define sqlite3BtreeHoldsAllMutexes(X) 1 +# define sqlite3SchemaMutexHeld(X,Y,Z) 1 +#endif + + +#endif /* _BTREE_H_ */ + +/************** End of btree.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include vdbe.h in the middle of sqliteInt.h ******************/ +/************** Begin file vdbe.h ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Header file for the Virtual DataBase Engine (VDBE) +** +** This header defines the interface to the virtual database engine +** or VDBE. The VDBE implements an abstract machine that runs a +** simple program to access and modify the underlying database. +*/ +#ifndef _SQLITE_VDBE_H_ +#define _SQLITE_VDBE_H_ + +/* +** A single VDBE is an opaque structure named "Vdbe". Only routines +** in the source file sqliteVdbe.c are allowed to see the insides +** of this structure. +*/ +typedef struct Vdbe Vdbe; + +/* +** The names of the following types declared in vdbeInt.h are required +** for the VdbeOp definition. +*/ +typedef struct VdbeFunc VdbeFunc; +typedef struct Mem Mem; +typedef struct SubProgram SubProgram; + +/* +** A single instruction of the virtual machine has an opcode +** and as many as three operands. The instruction is recorded +** as an instance of the following structure: +*/ +struct VdbeOp { + u8 opcode; /* What operation to perform */ + signed char p4type; /* One of the P4_xxx constants for p4 */ + u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */ + u8 p5; /* Fifth parameter is an unsigned character */ + int p1; /* First operand */ + int p2; /* Second parameter (often the jump destination) */ + int p3; /* The third parameter */ + union { /* fourth parameter */ + int i; /* Integer value if p4type==P4_INT32 */ + void *p; /* Generic pointer */ + char *z; /* Pointer to data for string (char array) types */ + i64 *pI64; /* Used when p4type is P4_INT64 */ + double *pReal; /* Used when p4type is P4_REAL */ + FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ + VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ + CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ + Mem *pMem; /* Used when p4type is P4_MEM */ + VTable *pVtab; /* Used when p4type is P4_VTAB */ + KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ + int *ai; /* Used when p4type is P4_INTARRAY */ + SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ + } p4; +#ifdef SQLITE_DEBUG + char *zComment; /* Comment to improve readability */ +#endif +#ifdef VDBE_PROFILE + int cnt; /* Number of times this instruction was executed */ + u64 cycles; /* Total time spent executing this instruction */ +#endif +}; +typedef struct VdbeOp VdbeOp; + + +/* +** A sub-routine used to implement a trigger program. +*/ +struct SubProgram { + VdbeOp *aOp; /* Array of opcodes for sub-program */ + int nOp; /* Elements in aOp[] */ + int nMem; /* Number of memory cells required */ + int nCsr; /* Number of cursors required */ + void *token; /* id that may be used to recursive triggers */ + SubProgram *pNext; /* Next sub-program already visited */ +}; + +/* +** A smaller version of VdbeOp used for the VdbeAddOpList() function because +** it takes up less space. +*/ +struct VdbeOpList { + u8 opcode; /* What operation to perform */ + signed char p1; /* First operand */ + signed char p2; /* Second parameter (often the jump destination) */ + signed char p3; /* Third parameter */ +}; +typedef struct VdbeOpList VdbeOpList; + +/* +** Allowed values of VdbeOp.p4type +*/ +#define P4_NOTUSED 0 /* The P4 parameter is not used */ +#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ +#define P4_STATIC (-2) /* Pointer to a static string */ +#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ +#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ +#define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */ +#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ +#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ +#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ +#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ +#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ +#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ +#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ + +/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure +** is made. That copy is freed when the Vdbe is finalized. But if the +** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still +** gets freed when the Vdbe is finalized so it still should be obtained +** from a single sqliteMalloc(). But no copy is made and the calling +** function should *not* try to free the KeyInfo. +*/ +#define P4_KEYINFO_HANDOFF (-16) +#define P4_KEYINFO_STATIC (-17) + +/* +** The Vdbe.aColName array contains 5n Mem structures, where n is the +** number of columns of data returned by the statement. +*/ +#define COLNAME_NAME 0 +#define COLNAME_DECLTYPE 1 +#define COLNAME_DATABASE 2 +#define COLNAME_TABLE 3 +#define COLNAME_COLUMN 4 +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ +#else +# ifdef SQLITE_OMIT_DECLTYPE +# define COLNAME_N 1 /* Store only the name */ +# else +# define COLNAME_N 2 /* Store the name and decltype */ +# endif +#endif + +/* +** The following macro converts a relative address in the p2 field +** of a VdbeOp structure into a negative number so that +** sqlite3VdbeAddOpList() knows that the address is relative. Calling +** the macro again restores the address. +*/ +#define ADDR(X) (-1-(X)) + +/* +** The makefile scans the vdbe.c source file and creates the "opcodes.h" +** header file that defines a number for each opcode used by the VDBE. +*/ +/************** Include opcodes.h in the middle of vdbe.h ********************/ +/************** Begin file opcodes.h *****************************************/ +/* Automatically generated. Do not edit */ +/* See the mkopcodeh.awk script for details */ +#define OP_Goto 1 +#define OP_Gosub 2 +#define OP_Return 3 +#define OP_Yield 4 +#define OP_HaltIfNull 5 +#define OP_Halt 6 +#define OP_Integer 7 +#define OP_Int64 8 +#define OP_Real 130 /* same as TK_FLOAT */ +#define OP_String8 94 /* same as TK_STRING */ +#define OP_String 9 +#define OP_Null 10 +#define OP_Blob 11 +#define OP_Variable 12 +#define OP_Move 13 +#define OP_Copy 14 +#define OP_SCopy 15 +#define OP_ResultRow 16 +#define OP_Concat 91 /* same as TK_CONCAT */ +#define OP_Add 86 /* same as TK_PLUS */ +#define OP_Subtract 87 /* same as TK_MINUS */ +#define OP_Multiply 88 /* same as TK_STAR */ +#define OP_Divide 89 /* same as TK_SLASH */ +#define OP_Remainder 90 /* same as TK_REM */ +#define OP_CollSeq 17 +#define OP_Function 18 +#define OP_BitAnd 82 /* same as TK_BITAND */ +#define OP_BitOr 83 /* same as TK_BITOR */ +#define OP_ShiftLeft 84 /* same as TK_LSHIFT */ +#define OP_ShiftRight 85 /* same as TK_RSHIFT */ +#define OP_AddImm 20 +#define OP_MustBeInt 21 +#define OP_RealAffinity 22 +#define OP_ToText 141 /* same as TK_TO_TEXT */ +#define OP_ToBlob 142 /* same as TK_TO_BLOB */ +#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ +#define OP_ToInt 144 /* same as TK_TO_INT */ +#define OP_ToReal 145 /* same as TK_TO_REAL */ +#define OP_Eq 76 /* same as TK_EQ */ +#define OP_Ne 75 /* same as TK_NE */ +#define OP_Lt 79 /* same as TK_LT */ +#define OP_Le 78 /* same as TK_LE */ +#define OP_Gt 77 /* same as TK_GT */ +#define OP_Ge 80 /* same as TK_GE */ +#define OP_Permutation 23 +#define OP_Compare 24 +#define OP_Jump 25 +#define OP_And 69 /* same as TK_AND */ +#define OP_Or 68 /* same as TK_OR */ +#define OP_Not 19 /* same as TK_NOT */ +#define OP_BitNot 93 /* same as TK_BITNOT */ +#define OP_If 26 +#define OP_IfNot 27 +#define OP_IsNull 73 /* same as TK_ISNULL */ +#define OP_NotNull 74 /* same as TK_NOTNULL */ +#define OP_Column 28 +#define OP_Affinity 29 +#define OP_MakeRecord 30 +#define OP_Count 31 +#define OP_Savepoint 32 +#define OP_AutoCommit 33 +#define OP_Transaction 34 +#define OP_ReadCookie 35 +#define OP_SetCookie 36 +#define OP_VerifyCookie 37 +#define OP_OpenRead 38 +#define OP_OpenWrite 39 +#define OP_OpenAutoindex 40 +#define OP_OpenEphemeral 41 +#define OP_OpenPseudo 42 +#define OP_Close 43 +#define OP_SeekLt 44 +#define OP_SeekLe 45 +#define OP_SeekGe 46 +#define OP_SeekGt 47 +#define OP_Seek 48 +#define OP_NotFound 49 +#define OP_Found 50 +#define OP_IsUnique 51 +#define OP_NotExists 52 +#define OP_Sequence 53 +#define OP_NewRowid 54 +#define OP_Insert 55 +#define OP_InsertInt 56 +#define OP_Delete 57 +#define OP_ResetCount 58 +#define OP_RowKey 59 +#define OP_RowData 60 +#define OP_Rowid 61 +#define OP_NullRow 62 +#define OP_Last 63 +#define OP_Sort 64 +#define OP_Rewind 65 +#define OP_Prev 66 +#define OP_Next 67 +#define OP_IdxInsert 70 +#define OP_IdxDelete 71 +#define OP_IdxRowid 72 +#define OP_IdxLT 81 +#define OP_IdxGE 92 +#define OP_Destroy 95 +#define OP_Clear 96 +#define OP_CreateIndex 97 +#define OP_CreateTable 98 +#define OP_ParseSchema 99 +#define OP_LoadAnalysis 100 +#define OP_DropTable 101 +#define OP_DropIndex 102 +#define OP_DropTrigger 103 +#define OP_IntegrityCk 104 +#define OP_RowSetAdd 105 +#define OP_RowSetRead 106 +#define OP_RowSetTest 107 +#define OP_Program 108 +#define OP_Param 109 +#define OP_FkCounter 110 +#define OP_FkIfZero 111 +#define OP_MemMax 112 +#define OP_IfPos 113 +#define OP_IfNeg 114 +#define OP_IfZero 115 +#define OP_AggStep 116 +#define OP_AggFinal 117 +#define OP_Checkpoint 118 +#define OP_JournalMode 119 +#define OP_Vacuum 120 +#define OP_IncrVacuum 121 +#define OP_Expire 122 +#define OP_TableLock 123 +#define OP_VBegin 124 +#define OP_VCreate 125 +#define OP_VDestroy 126 +#define OP_VOpen 127 +#define OP_VFilter 128 +#define OP_VColumn 129 +#define OP_VNext 131 +#define OP_VRename 132 +#define OP_VUpdate 133 +#define OP_Pagecount 134 +#define OP_MaxPgcnt 135 +#define OP_Trace 136 +#define OP_Noop 137 +#define OP_Explain 138 + +/* The following opcode values are never used */ +#define OP_NotUsed_139 139 +#define OP_NotUsed_140 140 + + +/* Properties such as "out2" or "jump" that are specified in +** comments following the "case" for each opcode in the vdbe.c +** are encoded into bitvectors as follows: +*/ +#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ +#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ +#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ +#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ +#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ +#define OPFLG_OUT2 0x0020 /* out2: P2 is an output */ +#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */ +#define OPFLG_INITIALIZER {\ +/* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\ +/* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\ +/* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\ +/* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\ +/* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\ +/* 40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\ +/* 48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\ +/* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\ +/* 64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\ +/* 72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ +/* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\ +/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\ +/* 96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\ +/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\ +/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\ +/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\ +/* 144 */ 0x04, 0x04,} + +/************** End of opcodes.h *********************************************/ +/************** Continuing where we left off in vdbe.h ***********************/ + +/* +** Prototypes for the VDBE interface. See comments on the implementation +** for a description of what each of these routines does. +*/ +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); +SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); +SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); +#endif +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8); +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); +#ifndef SQLITE_OMIT_TRACE +SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); +#endif + +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int); +SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*); +SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); + +#ifndef SQLITE_OMIT_TRIGGER +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); +#endif + + +#ifndef NDEBUG +SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); +# define VdbeComment(X) sqlite3VdbeComment X +SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); +# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +#else +# define VdbeComment(X) +# define VdbeNoopComment(X) +#endif + +#endif + +/************** End of vdbe.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pager.h in the middle of sqliteInt.h *****************/ +/************** Begin file pager.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. The page cache subsystem reads and writes a file a page +** at a time and provides a journal for rollback. +*/ + +#ifndef _PAGER_H_ +#define _PAGER_H_ + +/* +** Default maximum size for persistent journal files. A negative +** value means no limit. This value may be overridden using the +** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". +*/ +#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 +#endif + +/* +** The type used to represent a page number. The first page in a file +** is called page 1. 0 is used to represent "not a page". +*/ +typedef u32 Pgno; + +/* +** Each open file is managed by a separate instance of the "Pager" structure. +*/ +typedef struct Pager Pager; + +/* +** Handle type for pages. +*/ +typedef struct PgHdr DbPage; + +/* +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is +** reserved for working around a windows/posix incompatibility). It is +** used in the journal to signify that the remainder of the journal file +** is devoted to storing a master journal name - there are no more pages to +** roll back. See comments for function writeMasterJournal() in pager.c +** for details. +*/ +#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) + +/* +** Allowed values for the flags parameter to sqlite3PagerOpen(). +** +** NOTE: These values must match the corresponding BTREE_ values in btree.h. +*/ +#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ +#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */ +#define PAGER_MEMORY 0x0004 /* In-memory database */ + +/* +** Valid values for the second argument to sqlite3PagerLockingMode(). +*/ +#define PAGER_LOCKINGMODE_QUERY -1 +#define PAGER_LOCKINGMODE_NORMAL 0 +#define PAGER_LOCKINGMODE_EXCLUSIVE 1 + +/* +** Numeric constants that encode the journalmode. +*/ +#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ +#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ +#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ +#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ +#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ +#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ +#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ + +/* +** The remainder of this file contains the declarations of the functions +** that make up the Pager sub-system API. See source code comments for +** a detailed description of each routine. +*/ + +/* Open and close a Pager connection. */ +SQLITE_PRIVATE int sqlite3PagerOpen( + sqlite3_vfs*, + Pager **ppPager, + const char*, + int, + int, + int, + void(*)(DbPage*) +); +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); + +/* Functions used to configure a Pager object. */ +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int); +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); + +/* Functions used to obtain and release page references. */ +SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); +SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); + +/* Operations on page references. */ +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); +SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); + +/* Functions used to manage pager transactions and savepoints. */ +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); +SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); +SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); + +SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); +SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); +SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); + +/* Functions used to query pager state and configuration. */ +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*); +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*); +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); +SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); + +/* Functions used to truncate the database file. */ +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); + +#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) +SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); +#endif + +/* Functions to support testing and debugging. */ +#if !defined(NDEBUG) || defined(SQLITE_TEST) +SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); +SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); +#endif +#ifdef SQLITE_TEST +SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); +SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); + void disable_simulated_io_errors(void); + void enable_simulated_io_errors(void); +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +#endif /* _PAGER_H_ */ + +/************** End of pager.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pcache.h in the middle of sqliteInt.h ****************/ +/************** Begin file pcache.h ******************************************/ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. +*/ + +#ifndef _PCACHE_H_ + +typedef struct PgHdr PgHdr; +typedef struct PCache PCache; + +/* +** Every page in the cache is controlled by an instance of the following +** structure. +*/ +struct PgHdr { + void *pData; /* Content of this page */ + void *pExtra; /* Extra content */ + PgHdr *pDirty; /* Transient list of dirty pages */ + Pgno pgno; /* Page number for this page */ + Pager *pPager; /* The pager this page is part of */ +#ifdef SQLITE_CHECK_PAGES + u32 pageHash; /* Hash of page content */ +#endif + u16 flags; /* PGHDR flags defined below */ + + /********************************************************************** + ** Elements above are public. All that follows is private to pcache.c + ** and should not be accessed by other modules. + */ + i16 nRef; /* Number of users of this page */ + PCache *pCache; /* Cache that owns this page */ + + PgHdr *pDirtyNext; /* Next element in list of dirty pages */ + PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ +}; + +/* Bit values for PgHdr.flags */ +#define PGHDR_DIRTY 0x002 /* Page has changed */ +#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before + ** writing this page to the database */ +#define PGHDR_NEED_READ 0x008 /* Content is unread */ +#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ +#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ + +/* Initialize and shutdown the page cache subsystem */ +SQLITE_PRIVATE int sqlite3PcacheInitialize(void); +SQLITE_PRIVATE void sqlite3PcacheShutdown(void); + +/* Page cache buffer management: +** These routines implement SQLITE_CONFIG_PAGECACHE. +*/ +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); + +/* Create a new pager cache. +** Under memory stress, invoke xStress to try to make pages clean. +** Only clean and unpinned pages can be reclaimed. +*/ +SQLITE_PRIVATE void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *pToInit /* Preallocated space for the PCache */ +); + +/* Modify the page-size after the cache has been created. */ +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int); + +/* Return the size in bytes of a PCache object. Used to preallocate +** storage space. +*/ +SQLITE_PRIVATE int sqlite3PcacheSize(void); + +/* One release per successful fetch. Page is pinned until released. +** Reference counted. +*/ +SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); + +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ + +/* Change a page number. Used by incr-vacuum. */ +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); + +/* Remove all pages with pgno>x. Reset the cache if x==0 */ +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); + +/* Get a list of all dirty pages in the cache, sorted by page number */ +SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); + +/* Reset and close the cache object */ +SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); + +/* Clear flags from pages of the page cache */ +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); + +/* Discard the contents of the cache */ +SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); + +/* Return the total number of outstanding page references */ +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); + +/* Increment the reference count of an existing page */ +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); + +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); + +/* Return the total number of pages stored in the cache */ +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* Iterate through all dirty pages currently stored in the cache. This +** interface is only available if SQLITE_CHECK_PAGES is defined when the +** library is built. +*/ +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); +#endif + +/* Set and get the suggested cache-size for the specified pager-cache. +** +** If no global maximum is configured, then the system attempts to limit +** the total number of pages cached by purgeable pager-caches to the sum +** of the suggested cache-sizes. +*/ +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); +#endif + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* Try to return memory used by the pcache module to the main memory heap */ +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); +#endif + +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); + +#endif /* _PCACHE_H_ */ + +/************** End of pcache.h **********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/************** Include os.h in the middle of sqliteInt.h ********************/ +/************** Begin file os.h **********************************************/ +/* +** 2001 September 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file (together with is companion C source-code file +** "os.c") attempt to abstract the underlying operating system so that +** the SQLite library will work on both POSIX and windows systems. +** +** This header file is #include-ed by sqliteInt.h and thus ends up +** being included by every source file. +*/ +#ifndef _SQLITE_OS_H_ +#define _SQLITE_OS_H_ + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# undef SQLITE_OS_OS2 +# define SQLITE_OS_OS2 0 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# define SQLITE_OS_OS2 0 +# elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__) +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 0 +# define SQLITE_OS_OS2 1 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# define SQLITE_OS_OS2 0 +# endif +# else +# define SQLITE_OS_UNIX 0 +# define SQLITE_OS_OS2 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +/* +** Determine if we are dealing with WindowsCE - which has a much +** reduced API. +*/ +#if defined(_WIN32_WCE) +# define SQLITE_OS_WINCE 1 +#else +# define SQLITE_OS_WINCE 0 +#endif + + +/* +** Define the maximum size of a temporary filename +*/ +#if SQLITE_OS_WIN +# include +# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50) +#elif SQLITE_OS_OS2 +# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY) +# include /* has to be included before os2.h for linking to work */ +# endif +# define INCL_DOSDATETIME +# define INCL_DOSFILEMGR +# define INCL_DOSERRORS +# define INCL_DOSMISC +# define INCL_DOSPROCESS +# define INCL_DOSMODULEMGR +# define INCL_DOSSEMAPHORES +# include +# include +# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP) +#else +# define SQLITE_TEMPNAME_SIZE 200 +#endif + +/* If the SET_FULLSYNC macro is not defined above, then make it +** a no-op +*/ +#ifndef SET_FULLSYNC +# define SET_FULLSYNC(x,y) +#endif + +/* +** The default size of a disk sector +*/ +#ifndef SQLITE_DEFAULT_SECTOR_SIZE +# define SQLITE_DEFAULT_SECTOR_SIZE 512 +#endif + +/* +** Temporary files are named starting with this prefix followed by 16 random +** alphanumeric characters, and no file extension. They are stored in the +** OS's standard temporary file directory, and are deleted prior to exit. +** If sqlite is being embedded in another program, you may wish to change the +** prefix to reflect your program's name, so that if your program exits +** prematurely, old temporary files can be easily identified. This can be done +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. +** +** 2006-10-31: The default prefix used to be "sqlite_". But then +** Mcafee started using SQLite in their anti-virus product and it +** started putting files with the "sqlite" name in the c:/temp folder. +** This annoyed many windows users. Those users would then do a +** Google search for "sqlite", find the telephone numbers of the +** developers and call to wake them up at night and complain. +** For this reason, the default name prefix is changed to be "sqlite" +** spelled backwards. So the temp files are still identified, but +** anybody smart enough to figure out the code is also likely smart +** enough to know that calling the developer will not help get rid +** of the file. +*/ +#ifndef SQLITE_TEMP_FILE_PREFIX +# define SQLITE_TEMP_FILE_PREFIX "etilqs_" +#endif + +/* +** The following values may be passed as the second argument to +** sqlite3OsLock(). The various locks exhibit the following semantics: +** +** SHARED: Any number of processes may hold a SHARED lock simultaneously. +** RESERVED: A single process may hold a RESERVED lock on a file at +** any time. Other processes may hold and obtain new SHARED locks. +** PENDING: A single process may hold a PENDING lock on a file at +** any one time. Existing SHARED locks may persist, but no new +** SHARED locks may be obtained by other processes. +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. +** +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** process that requests an EXCLUSIVE lock may actually obtain a PENDING +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to +** sqlite3OsLock(). +*/ +#define NO_LOCK 0 +#define SHARED_LOCK 1 +#define RESERVED_LOCK 2 +#define PENDING_LOCK 3 +#define EXCLUSIVE_LOCK 4 + +/* +** File Locking Notes: (Mostly about windows but also some info for Unix) +** +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because +** those functions are not available. So we use only LockFile() and +** UnlockFile(). +** +** LockFile() prevents not just writing but also reading by other processes. +** A SHARED_LOCK is obtained by locking a single randomly-chosen +** byte out of a specific range of bytes. The lock byte is obtained at +** random so two separate readers can probably access the file at the +** same time, unless they are unlucky and choose the same lock byte. +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. +** There can only be one writer. A RESERVED_LOCK is obtained by locking +** a single byte of the file that is designated as the reserved lock byte. +** A PENDING_LOCK is obtained by locking a designated byte different from +** the RESERVED_LOCK byte. +** +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, +** which means we can use reader/writer locks. When reader/writer locks +** are used, the lock is placed on the same range of bytes that is used +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme +** will support two or more Win95 readers or two or more WinNT readers. +** But a single Win95 reader will lock out all WinNT readers and a single +** WinNT reader will lock out all other Win95 readers. +** +** The following #defines specify the range of bytes used for locking. +** SHARED_SIZE is the number of bytes available in the pool from which +** a random byte is selected for a shared lock. The pool of bytes for +** shared locks begins at SHARED_FIRST. +** +** The same locking strategy and +** byte ranges are used for Unix. This leaves open the possiblity of having +** clients on win95, winNT, and unix all talking to the same shared file +** and all locking correctly. To do so would require that samba (or whatever +** tool is being used for file sharing) implements locks correctly between +** windows and unix. I'm guessing that isn't likely to happen, but by +** using the same locking range we are at least open to the possibility. +** +** Locking in windows is manditory. For this reason, we cannot store +** actual data in the bytes used for locking. The pager never allocates +** the pages involved in locking therefore. SHARED_SIZE is selected so +** that all locks will fit on a single page even at the minimum page size. +** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE +** is set high so that we don't have to allocate an unused page except +** for very large databases. But one should test the page skipping logic +** by setting PENDING_BYTE low and running the entire regression suite. +** +** Changing the value of PENDING_BYTE results in a subtly incompatible +** file format. Depending on how it is changed, you might not notice +** the incompatibility right away, even running a full regression test. +** The default location of PENDING_BYTE is the first byte past the +** 1GB boundary. +** +*/ +#ifdef SQLITE_OMIT_WSD +# define PENDING_BYTE (0x40000000) +#else +# define PENDING_BYTE sqlite3PendingByte +#endif +#define RESERVED_BYTE (PENDING_BYTE+1) +#define SHARED_FIRST (PENDING_BYTE+2) +#define SHARED_SIZE 510 + +/* +** Wrapper around OS specific sqlite3_os_init() function. +*/ +SQLITE_PRIVATE int sqlite3OsInit(void); + +/* +** Functions for accessing sqlite3_file methods +*/ +SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*); +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); +#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); + +/* +** Functions for accessing sqlite3_vfs methods +*/ +SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); +SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); + +/* +** Convenience functions for opening and closing files using +** sqlite3_malloc() to obtain space for the file-handle structure. +*/ +SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); + +#endif /* _SQLITE_OS_H_ */ + +/************** End of os.h **************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include mutex.h in the middle of sqliteInt.h *****************/ +/************** Begin file mutex.h *******************************************/ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the common header for all mutex implementations. +** The sqliteInt.h header #includes this file so that it is available +** to all source files. We break it out in an effort to keep the code +** better organized. +** +** NOTE: source files should *not* #include this header file directly. +** Source files should #include the sqliteInt.h file and let that file +** include this one indirectly. +*/ + + +/* +** Figure out what version of the code to use. The choices are +** +** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The +** mutexes implemention cannot be overridden +** at start-time. +** +** SQLITE_MUTEX_NOOP For single-threaded applications. No +** mutual exclusion is provided. But this +** implementation can be overridden at +** start-time. +** +** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. +** +** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. +** +** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2. +*/ +#if !SQLITE_THREADSAFE +# define SQLITE_MUTEX_OMIT +#endif +#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) +# if SQLITE_OS_UNIX +# define SQLITE_MUTEX_PTHREADS +# elif SQLITE_OS_WIN +# define SQLITE_MUTEX_W32 +# elif SQLITE_OS_OS2 +# define SQLITE_MUTEX_OS2 +# else +# define SQLITE_MUTEX_NOOP +# endif +#endif + +#ifdef SQLITE_MUTEX_OMIT +/* +** If this is a no-op implementation, implement everything as macros. +*/ +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) +#define sqlite3MutexInit() SQLITE_OK +#define sqlite3MutexEnd() +#endif /* defined(SQLITE_MUTEX_OMIT) */ + +/************** End of mutex.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + + +/* +** Each database file to be accessed by the system is an instance +** of the following structure. There are normally two of these structures +** in the sqlite.aDb[] array. aDb[0] is the main database file and +** aDb[1] is the database file used to hold temporary tables. Additional +** databases may be attached. +*/ +struct Db { + char *zName; /* Name of this database */ + Btree *pBt; /* The B*Tree structure for this database file */ + u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ + u8 safety_level; /* How aggressive at syncing data to disk */ + Schema *pSchema; /* Pointer to database schema (possibly shared) */ +}; + +/* +** An instance of the following structure stores a database schema. +** +** Most Schema objects are associated with a Btree. The exception is +** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. +** In shared cache mode, a single Schema object can be shared by multiple +** Btrees that refer to the same underlying BtShared object. +** +** Schema objects are automatically deallocated when the last Btree that +** references them is destroyed. The TEMP Schema is manually freed by +** sqlite3_close(). +* +** A thread must be holding a mutex on the corresponding Btree in order +** to access Schema content. This implies that the thread must also be +** holding a mutex on the sqlite3 connection pointer that owns the Btree. +** For a TEMP Schema, only the connection mutex is required. +*/ +struct Schema { + int schema_cookie; /* Database schema version number for this file */ + int iGeneration; /* Generation counter. Incremented with each change */ + Hash tblHash; /* All tables indexed by name */ + Hash idxHash; /* All (named) indices indexed by name */ + Hash trigHash; /* All triggers indexed by name */ + Hash fkeyHash; /* All foreign keys by referenced table name */ + Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ + u8 file_format; /* Schema format version for this file */ + u8 enc; /* Text encoding used by this database */ + u16 flags; /* Flags associated with this schema */ + int cache_size; /* Number of pages to use in the cache */ +}; + +/* +** These macros can be used to test, set, or clear bits in the +** Db.pSchema->flags field. +*/ +#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) +#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) +#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) + +/* +** Allowed values for the DB.pSchema->flags field. +** +** The DB_SchemaLoaded flag is set after the database schema has been +** read into internal hash tables. +** +** DB_UnresetViews means that one or more views have column names that +** have been filled out. If the schema changes, these column names might +** changes and so the view will need to be reset. +*/ +#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ +#define DB_UnresetViews 0x0002 /* Some views have defined column names */ +#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ + +/* +** The number of different kinds of things that can be limited +** using the sqlite3_limit() interface. +*/ +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) + +/* +** Lookaside malloc is a set of fixed-size buffers that can be used +** to satisfy small transient memory allocation requests for objects +** associated with a particular database connection. The use of +** lookaside malloc provides a significant performance enhancement +** (approx 10%) by avoiding numerous malloc/free requests while parsing +** SQL statements. +** +** The Lookaside structure holds configuration information about the +** lookaside malloc subsystem. Each available memory allocation in +** the lookaside subsystem is stored on a linked list of LookasideSlot +** objects. +** +** Lookaside allocations are only allowed for objects that are associated +** with a particular database connection. Hence, schema information cannot +** be stored in lookaside because in shared cache mode the schema information +** is shared by multiple database connections. Therefore, while parsing +** schema information, the Lookaside.bEnabled flag is cleared so that +** lookaside allocations are not used to construct the schema objects. +*/ +struct Lookaside { + u16 sz; /* Size of each buffer in bytes */ + u8 bEnabled; /* False to disable new lookaside allocations */ + u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ + int nOut; /* Number of buffers currently checked out */ + int mxOut; /* Highwater mark for nOut */ + int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + LookasideSlot *pFree; /* List of available buffers */ + void *pStart; /* First byte of available memory space */ + void *pEnd; /* First byte past end of available space */ +}; +struct LookasideSlot { + LookasideSlot *pNext; /* Next buffer in the list of free buffers */ +}; + +/* +** A hash table for function definitions. +** +** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. +** Collisions are on the FuncDef.pHash chain. +*/ +struct FuncDefHash { + FuncDef *a[23]; /* Hash table for functions */ +}; + +/* +** Each database connection is an instance of the following structure. +** +** The sqlite.lastRowid records the last insert rowid generated by an +** insert statement. Inserts on views do not affect its value. Each +** trigger has its own context, so that lastRowid can be updated inside +** triggers as usual. The previous value will be restored once the trigger +** exits. Upon entering a before or instead of trigger, lastRowid is no +** longer (since after version 2.8.12) reset to -1. +** +** The sqlite.nChange does not count changes within triggers and keeps no +** context. It is reset at start of sqlite3_exec. +** The sqlite.lsChange represents the number of changes made by the last +** insert, update, or delete statement. It remains constant throughout the +** length of a statement and is then updated by OP_SetCounts. It keeps a +** context stack just like lastRowid so that the count of changes +** within a trigger is not seen outside the trigger. Changes to views do not +** affect the value of lsChange. +** The sqlite.csChange keeps track of the number of current changes (since +** the last statement) and is used to update sqlite_lsChange. +** +** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16 +** store the most recent error code and, if applicable, string. The +** internal function sqlite3Error() is used to set these variables +** consistently. +*/ +struct sqlite3 { + sqlite3_vfs *pVfs; /* OS Interface */ + int nDb; /* Number of backends currently in use */ + Db *aDb; /* All backends */ + int flags; /* Miscellaneous flags. See below */ + unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + int errCode; /* Most recent error code (SQLITE_*) */ + int errMask; /* & result codes with this before returning */ + u8 autoCommit; /* The auto-commit flag. */ + u8 temp_store; /* 1: file 2: memory 0: default */ + u8 mallocFailed; /* True if we have seen a malloc failure */ + u8 dfltLockMode; /* Default locking-mode for attached dbs */ + signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ + u8 suppressErr; /* Do not issue error messages if true */ + u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ + int nextPagesize; /* Pagesize after VACUUM if >0 */ + int nTable; /* Number of tables in the database */ + CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ + i64 lastRowid; /* ROWID of most recent insert (see above) */ + u32 magic; /* Magic number for detect library misuse */ + int nChange; /* Value returned by sqlite3_changes() */ + int nTotalChange; /* Value returned by sqlite3_total_changes() */ + sqlite3_mutex *mutex; /* Connection mutex */ + int aLimit[SQLITE_N_LIMIT]; /* Limits */ + struct sqlite3InitInfo { /* Information used during initialization */ + int iDb; /* When back is being initialized */ + int newTnum; /* Rootpage of table being initialized */ + u8 busy; /* TRUE if currently initializing */ + u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ + } init; + int nExtension; /* Number of loaded extensions */ + void **aExtension; /* Array of shared library handles */ + struct Vdbe *pVdbe; /* List of active virtual machines */ + int activeVdbeCnt; /* Number of VDBEs currently executing */ + int writeVdbeCnt; /* Number of active VDBEs that are writing */ + int vdbeExecCnt; /* Number of nested calls to VdbeExec() */ + void (*xTrace)(void*,const char*); /* Trace function */ + void *pTraceArg; /* Argument to the trace function */ + void (*xProfile)(void*,const char*,u64); /* Profiling function */ + void *pProfileArg; /* Argument to profile function */ + void *pCommitArg; /* Argument to xCommitCallback() */ + int (*xCommitCallback)(void*); /* Invoked at every commit. */ + void *pRollbackArg; /* Argument to xRollbackCallback() */ + void (*xRollbackCallback)(void*); /* Invoked at every commit. */ + void *pUpdateArg; + void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); +#ifndef SQLITE_OMIT_WAL + int (*xWalCallback)(void *, sqlite3 *, const char *, int); + void *pWalArg; +#endif + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); + void *pCollNeededArg; + sqlite3_value *pErr; /* Most recent error message */ + char *zErrMsg; /* Most recent error message (UTF-8 encoded) */ + char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */ + union { + volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ + double notUsed1; /* Spacer */ + } u1; + Lookaside lookaside; /* Lookaside malloc configuration */ +#ifndef SQLITE_OMIT_AUTHORIZATION + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + /* Access authorization function */ + void *pAuthArg; /* 1st argument to the access auth function */ +#endif +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + int (*xProgress)(void *); /* The progress callback */ + void *pProgressArg; /* Argument to the progress callback */ + int nProgressOps; /* Number of opcodes for progress callback */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + Hash aModule; /* populated by sqlite3_create_module() */ + VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ + VTable **aVTrans; /* Virtual tables with open transactions */ + int nVTrans; /* Allocated size of aVTrans */ + VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ +#endif + FuncDefHash aFunc; /* Hash table of connection functions */ + Hash aCollSeq; /* All collating sequences */ + BusyHandler busyHandler; /* Busy callback */ + int busyTimeout; /* Busy handler timeout, in msec */ + Db aDbStatic[2]; /* Static space for the 2 default backends */ + Savepoint *pSavepoint; /* List of active savepoints */ + int nSavepoint; /* Number of non-transaction savepoints */ + int nStatement; /* Number of nested statement-transactions */ + u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ + i64 nDeferredCons; /* Net deferred constraints this transaction. */ + int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + /* The following variables are all protected by the STATIC_MASTER + ** mutex, not by sqlite3.mutex. They are used by code in notify.c. + ** + ** When X.pUnlockConnection==Y, that means that X is waiting for Y to + ** unlock so that it can proceed. + ** + ** When X.pBlockingConnection==Y, that means that something that X tried + ** tried to do recently failed with an SQLITE_LOCKED error due to locks + ** held by Y. + */ + sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ + sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ + void *pUnlockArg; /* Argument to xUnlockNotify */ + void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ + sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ +#endif +}; + +/* +** A macro to discover the encoding of a database. +*/ +#define ENC(db) ((db)->aDb[0].pSchema->enc) + +/* +** Possible values for the sqlite3.flags. +*/ +#define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */ +#define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */ +#define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */ +#define SQLITE_ShortColNames 0x00000800 /* Show short columns names */ +#define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */ + /* DELETE, or UPDATE and return */ + /* the count using a callback. */ +#define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */ + /* result set is empty */ +#define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */ +#define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */ +#define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */ +#define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when + ** accessing read-only databases */ +#define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */ +#define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */ +#define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */ +#define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */ +#define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */ +#define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */ +#define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */ +#define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */ +#define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */ +#define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */ +#define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */ +#define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */ +#define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */ + +/* +** Bits of the sqlite3.flags field that are used by the +** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface. +** These must be the low-order bits of the flags field. +*/ +#define SQLITE_QueryFlattener 0x01 /* Disable query flattening */ +#define SQLITE_ColumnCache 0x02 /* Disable the column cache */ +#define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */ +#define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */ +#define SQLITE_IndexCover 0x10 /* Disable index covering table */ +#define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */ +#define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */ +#define SQLITE_IdxRealAsInt 0x80 /* Store REAL as INT in indices */ +#define SQLITE_OptMask 0xff /* Mask of all disablable opts */ + +/* +** Possible values for the sqlite.magic field. +** The numbers are obtained at random and have no special meaning, other +** than being distinct from one another. +*/ +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ +#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ + +/* +** Each SQL function is defined by an instance of the following +** structure. A pointer to this structure is stored in the sqlite.aFunc +** hash table. When multiple functions have the same name, the hash table +** points to a linked list of these structures. +*/ +struct FuncDef { + i16 nArg; /* Number of arguments. -1 means unlimited */ + u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ + u8 flags; /* Some combination of SQLITE_FUNC_* */ + void *pUserData; /* User data parameter */ + FuncDef *pNext; /* Next function with same name */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ + void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ + void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ + char *zName; /* SQL name of the function. */ + FuncDef *pHash; /* Next with a different name but the same hash */ + FuncDestructor *pDestructor; /* Reference counted destructor function */ +}; + +/* +** This structure encapsulates a user-function destructor callback (as +** configured using create_function_v2()) and a reference counter. When +** create_function_v2() is called to create a function with a destructor, +** a single object of this type is allocated. FuncDestructor.nRef is set to +** the number of FuncDef objects created (either 1 or 3, depending on whether +** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor +** member of each of the new FuncDef objects is set to point to the allocated +** FuncDestructor. +** +** Thereafter, when one of the FuncDef objects is deleted, the reference +** count on this object is decremented. When it reaches 0, the destructor +** is invoked and the FuncDestructor structure freed. +*/ +struct FuncDestructor { + int nRef; + void (*xDestroy)(void *); + void *pUserData; +}; + +/* +** Possible values for FuncDef.flags +*/ +#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ +#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ +#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ +#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ +#define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */ +#define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */ +#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */ + +/* +** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are +** used to create the initializers for the FuncDef structures. +** +** FUNCTION(zName, nArg, iArg, bNC, xFunc) +** Used to create a scalar function definition of a function zName +** implemented by C function xFunc that accepts nArg arguments. The +** value passed as iArg is cast to a (void*) and made available +** as the user-data (sqlite3_user_data()) for the function. If +** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. +** +** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) +** Used to create an aggregate function definition implemented by +** the C functions xStep and xFinal. The first four parameters +** are interpreted in the same way as the first 4 parameters to +** FUNCTION(). +** +** LIKEFUNC(zName, nArg, pArg, flags) +** Used to create a scalar function definition of a function zName +** that accepts nArg arguments and is implemented by a call to C +** function likeFunc. Argument pArg is cast to a (void *) and made +** available as the function user-data (sqlite3_user_data()). The +** FuncDef.flags variable is set to the value passed as the flags +** parameter. +*/ +#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + pArg, 0, xFunc, 0, 0, #zName, 0, 0} +#define LIKEFUNC(zName, nArg, arg, flags) \ + {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0} +#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ + {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ + SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0} + +/* +** All current savepoints are stored in a linked list starting at +** sqlite3.pSavepoint. The first element in the list is the most recently +** opened savepoint. Savepoints are added to the list by the vdbe +** OP_Savepoint instruction. +*/ +struct Savepoint { + char *zName; /* Savepoint name (nul-terminated) */ + i64 nDeferredCons; /* Number of deferred fk violations */ + Savepoint *pNext; /* Parent savepoint (if any) */ +}; + +/* +** The following are used as the second parameter to sqlite3Savepoint(), +** and as the P1 argument to the OP_Savepoint instruction. +*/ +#define SAVEPOINT_BEGIN 0 +#define SAVEPOINT_RELEASE 1 +#define SAVEPOINT_ROLLBACK 2 + + +/* +** Each SQLite module (virtual table definition) is defined by an +** instance of the following structure, stored in the sqlite3.aModule +** hash table. +*/ +struct Module { + const sqlite3_module *pModule; /* Callback pointers */ + const char *zName; /* Name passed to create_module() */ + void *pAux; /* pAux passed to create_module() */ + void (*xDestroy)(void *); /* Module destructor function */ +}; + +/* +** information about each column of an SQL table is held in an instance +** of this structure. +*/ +struct Column { + char *zName; /* Name of this column */ + Expr *pDflt; /* Default value of this column */ + char *zDflt; /* Original text of the default value */ + char *zType; /* Data type for this column */ + char *zColl; /* Collating sequence. If NULL, use the default */ + u8 notNull; /* True if there is a NOT NULL constraint */ + u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */ + char affinity; /* One of the SQLITE_AFF_... values */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + u8 isHidden; /* True if this column is 'hidden' */ +#endif +}; + +/* +** A "Collating Sequence" is defined by an instance of the following +** structure. Conceptually, a collating sequence consists of a name and +** a comparison routine that defines the order of that sequence. +** +** There may two separate implementations of the collation function, one +** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that +** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine +** native byte order. When a collation sequence is invoked, SQLite selects +** the version that will require the least expensive encoding +** translations, if any. +** +** The CollSeq.pUser member variable is an extra parameter that passed in +** as the first argument to the UTF-8 comparison function, xCmp. +** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function, +** xCmp16. +** +** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the +** collating sequence is undefined. Indices built on an undefined +** collating sequence may not be read or written. +*/ +struct CollSeq { + char *zName; /* Name of the collating sequence, UTF-8 encoded */ + u8 enc; /* Text encoding handled by xCmp() */ + u8 type; /* One of the SQLITE_COLL_... values below */ + void *pUser; /* First argument to xCmp() */ + int (*xCmp)(void*,int, const void*, int, const void*); + void (*xDel)(void*); /* Destructor for pUser */ +}; + +/* +** Allowed values of CollSeq.type: +*/ +#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */ +#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */ +#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */ +#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */ + +/* +** A sort order can be either ASC or DESC. +*/ +#define SQLITE_SO_ASC 0 /* Sort in ascending order */ +#define SQLITE_SO_DESC 1 /* Sort in ascending order */ + +/* +** Column affinity types. +** +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and +** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve +** the speed a little by numbering the values consecutively. +** +** But rather than start with 0 or 1, we begin with 'a'. That way, +** when multiple affinity types are concatenated into a string and +** used as the P4 operand, they will be more readable. +** +** Note also that the numeric types are grouped together so that testing +** for a numeric type is a single comparison. +*/ +#define SQLITE_AFF_TEXT 'a' +#define SQLITE_AFF_NONE 'b' +#define SQLITE_AFF_NUMERIC 'c' +#define SQLITE_AFF_INTEGER 'd' +#define SQLITE_AFF_REAL 'e' + +#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) + +/* +** The SQLITE_AFF_MASK values masks off the significant bits of an +** affinity value. +*/ +#define SQLITE_AFF_MASK 0x67 + +/* +** Additional bit values that can be ORed with an affinity without +** changing the affinity. +*/ +#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ +#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ +#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ + +/* +** An object of this type is created for each virtual table present in +** the database schema. +** +** If the database schema is shared, then there is one instance of this +** structure for each database connection (sqlite3*) that uses the shared +** schema. This is because each database connection requires its own unique +** instance of the sqlite3_vtab* handle used to access the virtual table +** implementation. sqlite3_vtab* handles can not be shared between +** database connections, even when the rest of the in-memory database +** schema is shared, as the implementation often stores the database +** connection handle passed to it via the xConnect() or xCreate() method +** during initialization internally. This database connection handle may +** then be used by the virtual table implementation to access real tables +** within the database. So that they appear as part of the callers +** transaction, these accesses need to be made via the same database +** connection as that used to execute SQL operations on the virtual table. +** +** All VTable objects that correspond to a single table in a shared +** database schema are initially stored in a linked-list pointed to by +** the Table.pVTable member variable of the corresponding Table object. +** When an sqlite3_prepare() operation is required to access the virtual +** table, it searches the list for the VTable that corresponds to the +** database connection doing the preparing so as to use the correct +** sqlite3_vtab* handle in the compiled query. +** +** When an in-memory Table object is deleted (for example when the +** schema is being reloaded for some reason), the VTable objects are not +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed +** immediately. Instead, they are moved from the Table.pVTable list to +** another linked list headed by the sqlite3.pDisconnect member of the +** corresponding sqlite3 structure. They are then deleted/xDisconnected +** next time a statement is prepared using said sqlite3*. This is done +** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. +** Refer to comments above function sqlite3VtabUnlockList() for an +** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect +** list without holding the corresponding sqlite3.mutex mutex. +** +** The memory for objects of this type is always allocated by +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as +** the first argument. +*/ +struct VTable { + sqlite3 *db; /* Database connection associated with this table */ + Module *pMod; /* Pointer to module implementation */ + sqlite3_vtab *pVtab; /* Pointer to vtab instance */ + int nRef; /* Number of pointers to this structure */ + u8 bConstraint; /* True if constraints are supported */ + int iSavepoint; /* Depth of the SAVEPOINT stack */ + VTable *pNext; /* Next in linked list (see above) */ +}; + +/* +** Each SQL table is represented in memory by an instance of the +** following structure. +** +** Table.zName is the name of the table. The case of the original +** CREATE TABLE statement is stored, but case is not significant for +** comparisons. +** +** Table.nCol is the number of columns in this table. Table.aCol is a +** pointer to an array of Column structures, one for each column. +** +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of +** the column that is that key. Otherwise Table.iPKey is negative. Note +** that the datatype of the PRIMARY KEY must be INTEGER for this field to +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid +** is generated for each row of the table. TF_HasPrimaryKey is set if +** the table has any PRIMARY KEY, INTEGER or otherwise. +** +** Table.tnum is the page number for the root BTree page of the table in the +** database file. If Table.iDb is the index of the database table backend +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that +** holds temporary tables and indices. If TF_Ephemeral is set +** then the table is stored in a file that is automatically deleted +** when the VDBE cursor to the table is closed. In this case Table.tnum +** refers VDBE cursor number that holds the table open, not to the root +** page number. Transient tables are used to hold the results of a +** sub-query that appears instead of a real table name in the FROM clause +** of a SELECT statement. +*/ +struct Table { + char *zName; /* Name of the table or view */ + int iPKey; /* If not negative, use aCol[iPKey] as the primary key */ + int nCol; /* Number of columns in this table */ + Column *aCol; /* Information about each column */ + Index *pIndex; /* List of SQL indexes on this table. */ + int tnum; /* Root BTree node for this table (see note above) */ + unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ + Select *pSelect; /* NULL for tables. Points to definition if a view. */ + u16 nRef; /* Number of pointers to this Table */ + u8 tabFlags; /* Mask of TF_* values */ + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ + FKey *pFKey; /* Linked list of all foreign keys in this table */ + char *zColAff; /* String defining the affinity of each column */ +#ifndef SQLITE_OMIT_CHECK + Expr *pCheck; /* The AND of all CHECK constraints */ +#endif +#ifndef SQLITE_OMIT_ALTERTABLE + int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + VTable *pVTable; /* List of VTable objects. */ + int nModuleArg; /* Number of arguments to the module */ + char **azModuleArg; /* Text of all module args. [0] is module name */ +#endif + Trigger *pTrigger; /* List of triggers stored in pSchema */ + Schema *pSchema; /* Schema that contains this table */ + Table *pNextZombie; /* Next on the Parse.pZombieTab list */ +}; + +/* +** Allowed values for Tabe.tabFlags. +*/ +#define TF_Readonly 0x01 /* Read-only system table */ +#define TF_Ephemeral 0x02 /* An ephemeral table */ +#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ +#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ +#define TF_Virtual 0x10 /* Is a virtual table */ +#define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */ + + + +/* +** Test to see whether or not a table is a virtual table. This is +** done as a macro so that it will be optimized out when virtual +** table support is omitted from the build. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE +# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +# define IsHiddenColumn(X) ((X)->isHidden) +#else +# define IsVirtual(X) 0 +# define IsHiddenColumn(X) 0 +#endif + +/* +** Each foreign key constraint is an instance of the following structure. +** +** A foreign key is associated with two tables. The "from" table is +** the table that contains the REFERENCES clause that creates the foreign +** key. The "to" table is the table that is named in the REFERENCES clause. +** Consider this example: +** +** CREATE TABLE ex1( +** a INTEGER PRIMARY KEY, +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) +** ); +** +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** +** Each REFERENCES clause generates an instance of the following structure +** which is attached to the from-table. The to-table need not exist when +** the from-table is created. The existence of the to-table is not checked. +*/ +struct FKey { + Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ + FKey *pNextFrom; /* Next foreign key in pFrom */ + char *zTo; /* Name of table that the key points to (aka: Parent) */ + FKey *pNextTo; /* Next foreign key on table named zTo */ + FKey *pPrevTo; /* Previous foreign key on table named zTo */ + int nCol; /* Number of columns in this key */ + /* EV: R-30323-21917 */ + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ + Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ + int iFrom; /* Index of column in pFrom */ + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ + } aCol[1]; /* One entry for each of nCol column s */ +}; + +/* +** SQLite supports many different ways to resolve a constraint +** error. ROLLBACK processing means that a constraint violation +** causes the operation in process to fail and for the current transaction +** to be rolled back. ABORT processing means the operation in process +** fails and any prior changes from that one operation are backed out, +** but the transaction is not rolled back. FAIL processing means that +** the operation in progress stops and returns an error code. But prior +** changes due to the same operation are not backed out and no rollback +** occurs. IGNORE means that the particular row that caused the constraint +** error is not inserted or updated. Processing continues and no error +** is returned. REPLACE means that preexisting database rows that caused +** a UNIQUE constraint violation are removed so that the new insert or +** update can proceed. Processing continues and no error is reported. +** +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the +** referenced table row is propagated into the row that holds the +** foreign key. +** +** The following symbolic values are used to record which type +** of action to take. +*/ +#define OE_None 0 /* There is no constraint to check */ +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ +#define OE_Abort 2 /* Back out changes but do no rollback transaction */ +#define OE_Fail 3 /* Stop the operation but leave all prior changes */ +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ + +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ +#define OE_SetNull 7 /* Set the foreign key value to NULL */ +#define OE_SetDflt 8 /* Set the foreign key value to its default */ +#define OE_Cascade 9 /* Cascade the changes */ + +#define OE_Default 99 /* Do whatever the default action is */ + + +/* +** An instance of the following structure is passed as the first +** argument to sqlite3VdbeKeyCompare and is used to control the +** comparison of the two index keys. +*/ +struct KeyInfo { + sqlite3 *db; /* The database connection */ + u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ + u16 nField; /* Number of entries in aColl[] */ + u8 *aSortOrder; /* Sort order for each column. May be NULL */ + CollSeq *aColl[1]; /* Collating sequence for each term of the key */ +}; + +/* +** An instance of the following structure holds information about a +** single index record that has already been parsed out into individual +** values. +** +** A record is an object that contains one or more fields of data. +** Records are used to store the content of a table row and to store +** the key of an index. A blob encoding of a record is created by +** the OP_MakeRecord opcode of the VDBE and is disassembled by the +** OP_Column opcode. +** +** This structure holds a record that has already been disassembled +** into its constituent fields. +*/ +struct UnpackedRecord { + KeyInfo *pKeyInfo; /* Collation and sort-order information */ + u16 nField; /* Number of entries in apMem[] */ + u16 flags; /* Boolean settings. UNPACKED_... below */ + i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ + Mem *aMem; /* Values */ +}; + +/* +** Allowed values of UnpackedRecord.flags +*/ +#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */ +#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */ +#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */ +#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */ +#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */ +#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */ + +/* +** Each SQL index is represented in memory by an +** instance of the following structure. +** +** The columns of the table that are to be indexed are described +** by the aiColumn[] field of this structure. For example, suppose +** we have the following table and index: +** +** CREATE TABLE Ex1(c1 int, c2 int, c3 text); +** CREATE INDEX Ex2 ON Ex1(c3,c1); +** +** In the Table structure describing Ex1, nCol==3 because there are +** three columns in the table. In the Index structure describing +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. +** The second column to be indexed (c1) has an index of 0 in +** Ex1.aCol[], hence Ex2.aiColumn[1]==0. +** +** The Index.onError field determines whether or not the indexed columns +** must be unique and what to do if they are not. When Index.onError=OE_None, +** it means this is not a unique index. Otherwise it is a unique index +** and the value of Index.onError indicate the which conflict resolution +** algorithm to employ whenever an attempt is made to insert a non-unique +** element. +*/ +struct Index { + char *zName; /* Name of this index */ + int nColumn; /* Number of columns in the table used by this index */ + int *aiColumn; /* Which columns are used by this index. 1st is 0 */ + unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */ + Table *pTable; /* The SQL table being indexed */ + int tnum; /* Page containing root of this index in database file */ + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */ + u8 bUnordered; /* Use this index for == or IN queries only */ + char *zColAff; /* String defining the affinity of each column */ + Index *pNext; /* The next index associated with the same table */ + Schema *pSchema; /* Schema containing this index */ + u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */ + char **azColl; /* Array of collation sequence names for index */ + IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */ +}; + +/* +** Each sample stored in the sqlite_stat2 table is represented in memory +** using a structure of this type. +*/ +struct IndexSample { + union { + char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */ + double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */ + } u; + u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ + u8 nByte; /* Size in byte of text or blob. */ +}; + +/* +** Each token coming out of the lexer is an instance of +** this structure. Tokens are also used as part of an expression. +** +** Note if Token.z==0 then Token.dyn and Token.n are undefined and +** may contain random values. Do not make any assumptions about Token.dyn +** and Token.n when Token.z==0. +*/ +struct Token { + const char *z; /* Text of the token. Not NULL-terminated! */ + unsigned int n; /* Number of characters in this token */ +}; + +/* +** An instance of this structure contains information needed to generate +** code for a SELECT that contains aggregate functions. +** +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a +** pointer to this structure. The Expr.iColumn field is the index in +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate +** code for that node. +** +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the +** original Select structure that describes the SELECT statement. These +** fields do not need to be freed when deallocating the AggInfo structure. +*/ +struct AggInfo { + u8 directMode; /* Direct rendering mode means take data directly + ** from source tables rather than from accumulators */ + u8 useSortingIdx; /* In direct mode, reference the sorting index rather + ** than the source table */ + int sortingIdx; /* Cursor number of the sorting index */ + ExprList *pGroupBy; /* The group by clause */ + int nSortingColumn; /* Number of columns in the sorting index */ + struct AggInfo_col { /* For each column used in source tables */ + Table *pTab; /* Source table */ + int iTable; /* Cursor number of the source table */ + int iColumn; /* Column number within the source table */ + int iSorterColumn; /* Column number in the sorting index */ + int iMem; /* Memory location that acts as accumulator */ + Expr *pExpr; /* The original expression */ + } *aCol; + int nColumn; /* Number of used entries in aCol[] */ + int nColumnAlloc; /* Number of slots allocated for aCol[] */ + int nAccumulator; /* Number of columns that show through to the output. + ** Additional columns are used only as parameters to + ** aggregate functions */ + struct AggInfo_func { /* For each aggregate function */ + Expr *pExpr; /* Expression encoding the function */ + FuncDef *pFunc; /* The aggregate function implementation */ + int iMem; /* Memory location that acts as accumulator */ + int iDistinct; /* Ephemeral table used to enforce DISTINCT */ + } *aFunc; + int nFunc; /* Number of entries in aFunc[] */ + int nFuncAlloc; /* Number of slots allocated for aFunc[] */ +}; + +/* +** The datatype ynVar is a signed integer, either 16-bit or 32-bit. +** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater +** than 32767 we have to make it 32-bit. 16-bit is preferred because +** it uses less memory in the Expr object, which is a big memory user +** in systems with lots of prepared statements. And few applications +** need more than about 10 or 20 variables. But some extreme users want +** to have prepared statements with over 32767 variables, and for them +** the option is available (at compile-time). +*/ +#if SQLITE_MAX_VARIABLE_NUMBER<=32767 +typedef i16 ynVar; +#else +typedef int ynVar; +#endif + +/* +** Each node of an expression in the parse tree is an instance +** of this structure. +** +** Expr.op is the opcode. The integer parser token codes are reused +** as opcodes here. For example, the parser defines TK_GE to be an integer +** code representing the ">=" operator. This same integer code is reused +** to represent the greater-than-or-equal-to operator in the expression +** tree. +** +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, +** or TK_STRING), then Expr.token contains the text of the SQL literal. If +** the expression is a variable (TK_VARIABLE), then Expr.token contains the +** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), +** then Expr.token contains the name of the function. +** +** Expr.pRight and Expr.pLeft are the left and right subexpressions of a +** binary operator. Either or both may be NULL. +** +** Expr.x.pList is a list of arguments if the expression is an SQL function, +** a CASE expression or an IN expression of the form " IN (, ...)". +** Expr.x.pSelect is used if the expression is a sub-select or an expression of +** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is +** valid. +** +** An expression of the form ID or ID.ID refers to a column in a table. +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is +** the integer cursor number of a VDBE cursor pointing to that table and +** Expr.iColumn is the column number for the specific column. If the +** expression is used as a result in an aggregate SELECT, then the +** value is also stored in the Expr.iAgg column in the aggregate so that +** it can be accessed after all aggregates are computed. +** +** If the expression is an unbound variable marker (a question mark +** character '?' in the original SQL) then the Expr.iTable holds the index +** number for that variable. +** +** If the expression is a subquery then Expr.iColumn holds an integer +** register number containing the result of the subquery. If the +** subquery gives a constant result, then iTable is -1. If the subquery +** gives a different answer at different times during statement processing +** then iTable is the address of a subroutine that computes the subquery. +** +** If the Expr is of type OP_Column, and the table it is selecting from +** is a disk table or the "old.*" pseudo-table, then pTab points to the +** corresponding table definition. +** +** ALLOCATION NOTES: +** +** Expr objects can use a lot of memory space in database schema. To +** help reduce memory requirements, sometimes an Expr object will be +** truncated. And to reduce the number of memory allocations, sometimes +** two or more Expr objects will be stored in a single memory allocation, +** together with Expr.zToken strings. +** +** If the EP_Reduced and EP_TokenOnly flags are set when +** an Expr object is truncated. When EP_Reduced is set, then all +** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees +** are contained within the same memory allocation. Note, however, that +** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately +** allocated, regardless of whether or not EP_Reduced is set. +*/ +struct Expr { + u8 op; /* Operation performed by this node */ + char affinity; /* The affinity of the column or 0 if not a column */ + u16 flags; /* Various flags. EP_* See below */ + union { + char *zToken; /* Token value. Zero terminated and dequoted */ + int iValue; /* Non-negative integer value if EP_IntValue */ + } u; + + /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + + Expr *pLeft; /* Left subnode */ + Expr *pRight; /* Right subnode */ + union { + ExprList *pList; /* Function arguments or in " IN ( IN (