├── vendor └── gflags │ ├── test │ ├── flagfile.1 │ ├── flagfile.3 │ ├── flagfile.2 │ ├── gflags_unittest_flagfile │ ├── config │ │ ├── CMakeLists.txt │ │ └── main.cc │ ├── gflags_declare_flags.cc │ ├── gflags_strip_flags_test.cmake │ ├── gflags_declare_test.cc │ ├── nc │ │ ├── CMakeLists.txt │ │ └── gflags_nc.cc │ ├── gflags_build.py.in │ ├── gflags_strip_flags_test.cc │ └── CMakeLists.txt │ ├── AUTHORS.txt │ ├── .gitattributes │ ├── cmake │ ├── README_runtime.txt │ ├── package.pc.in │ ├── version.cmake.in │ ├── execute_test.cmake │ ├── package.cmake.in │ ├── config.cmake.in │ └── utils.cmake │ ├── WORKSPACE │ ├── .gitignore │ ├── BUILD │ ├── .travis.yml │ ├── appveyor.yml │ ├── COPYING.txt │ ├── src │ ├── windows_port.cc │ ├── config.h.in │ ├── gflags_ns.h.in │ ├── gflags_completions.sh │ ├── windows_port.h │ ├── gflags_declare.h.in │ ├── gflags_completions.h.in │ ├── util.h │ └── mutex.h │ ├── bazel │ └── gflags.bzl │ ├── INSTALL.md │ ├── ChangeLog.txt │ └── README.md ├── pywrapper ├── compile.sh ├── compile_with_trace.sh ├── compile_with_cuda.sh ├── test.py └── setup.py ├── maps ├── test.png ├── huge_map.png ├── quad.map.png ├── small.map.png ├── synthetic2.png ├── synthetic3.png ├── gigantic_map.png ├── synthetic.map.png ├── basement_fixed.png ├── synthetic2.map.png ├── single_pixel.map.png ├── basement_hallways_10cm.png ├── basement_hallways_5cm.png └── basement_fixed_rectangle.png ├── media ├── comparison.png └── spheretrace.jpg ├── docs └── RangeLibcUsageandInformation.pdf ├── .gitignore ├── license.txt ├── generate_serialized.sh ├── includes ├── CudaRangeLib.h ├── lru_cache.h ├── RangeUtils.h └── kernels.cu ├── make_plots.py ├── CMakeLists.txt ├── visualize.py └── README.md /vendor/gflags/test/flagfile.1: -------------------------------------------------------------------------------- 1 | --version -------------------------------------------------------------------------------- /pywrapper/compile.sh: -------------------------------------------------------------------------------- 1 | sudo python setup.py install 2 | -------------------------------------------------------------------------------- /vendor/gflags/test/flagfile.3: -------------------------------------------------------------------------------- 1 | --flagfile=flagfile.2 -------------------------------------------------------------------------------- /vendor/gflags/test/flagfile.2: -------------------------------------------------------------------------------- 1 | --foo=bar 2 | --nounused_bool -------------------------------------------------------------------------------- /vendor/gflags/AUTHORS.txt: -------------------------------------------------------------------------------- 1 | google-gflags@googlegroups.com 2 | 3 | -------------------------------------------------------------------------------- /pywrapper/compile_with_trace.sh: -------------------------------------------------------------------------------- 1 | sudo TRACE=ON python setup.py install 2 | -------------------------------------------------------------------------------- /pywrapper/compile_with_cuda.sh: -------------------------------------------------------------------------------- 1 | sudo WITH_CUDA=ON python setup.py install 2 | -------------------------------------------------------------------------------- /maps/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/test.png -------------------------------------------------------------------------------- /vendor/gflags/test/gflags_unittest_flagfile: -------------------------------------------------------------------------------- 1 | --test_flag=1 2 | --test_flag=2 3 | -------------------------------------------------------------------------------- /maps/huge_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/huge_map.png -------------------------------------------------------------------------------- /maps/quad.map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/quad.map.png -------------------------------------------------------------------------------- /maps/small.map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/small.map.png -------------------------------------------------------------------------------- /maps/synthetic2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/synthetic2.png -------------------------------------------------------------------------------- /maps/synthetic3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/synthetic3.png -------------------------------------------------------------------------------- /maps/gigantic_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/gigantic_map.png -------------------------------------------------------------------------------- /maps/synthetic.map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/synthetic.map.png -------------------------------------------------------------------------------- /media/comparison.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/media/comparison.png -------------------------------------------------------------------------------- /media/spheretrace.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/media/spheretrace.jpg -------------------------------------------------------------------------------- /maps/basement_fixed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/basement_fixed.png -------------------------------------------------------------------------------- /maps/synthetic2.map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/synthetic2.map.png -------------------------------------------------------------------------------- /maps/single_pixel.map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/single_pixel.map.png -------------------------------------------------------------------------------- /maps/basement_hallways_10cm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/basement_hallways_10cm.png -------------------------------------------------------------------------------- /maps/basement_hallways_5cm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/basement_hallways_5cm.png -------------------------------------------------------------------------------- /maps/basement_fixed_rectangle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/maps/basement_fixed_rectangle.png -------------------------------------------------------------------------------- /docs/RangeLibcUsageandInformation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kctess5/range_libc/HEAD/docs/RangeLibcUsageandInformation.pdf -------------------------------------------------------------------------------- /vendor/gflags/.gitattributes: -------------------------------------------------------------------------------- 1 | # treat all files in this repository as text files 2 | # and normalize them to LF line endings when committed 3 | * text 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | paper/ 2 | build/ 3 | tmp/ 4 | pywrapper/*.so 5 | pywrapper/*.cpp 6 | pywrapper/test.png 7 | .DS_Store 8 | paper/data/basement 9 | paper/data/synthetic 10 | ._.* 11 | paper/bak 12 | pywrapper/watch.sh 13 | -------------------------------------------------------------------------------- /vendor/gflags/cmake/README_runtime.txt: -------------------------------------------------------------------------------- 1 | This package contains runtime libraries only which are required 2 | by applications that use these libraries for the commandline flags 3 | processing. If you want to develop such application, download 4 | and install the development package instead. 5 | -------------------------------------------------------------------------------- /vendor/gflags/WORKSPACE: -------------------------------------------------------------------------------- 1 | # Copyright 2006 Google Inc. All Rights Reserved. 2 | # Use of this source code is governed by a BSD-style 3 | # license that can be found in the COPYING.txt file. 4 | 5 | # Bazel (http://bazel.io/) WORKSPACE file for gflags. 6 | workspace(name="com_github_gflags_gflags") 7 | -------------------------------------------------------------------------------- /vendor/gflags/test/config/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | ## gflags package configuration tests 2 | 3 | cmake_minimum_required (VERSION 2.8.12 FATAL_ERROR) 4 | 5 | project (gflags_${TEST_NAME}) 6 | 7 | find_package (gflags REQUIRED) 8 | 9 | add_executable (foo main.cc) 10 | target_link_libraries (foo gflags) 11 | -------------------------------------------------------------------------------- /vendor/gflags/test/gflags_declare_flags.cc: -------------------------------------------------------------------------------- 1 | #define GFLAGS_DLL_DECLARE_FLAG 2 | 3 | #include 4 | #include 5 | 6 | DECLARE_string(message); // in gflags_delcare_test.cc 7 | 8 | void print_message(); 9 | void print_message() 10 | { 11 | std::cout << FLAGS_message << std::endl; 12 | } 13 | -------------------------------------------------------------------------------- /vendor/gflags/test/gflags_strip_flags_test.cmake: -------------------------------------------------------------------------------- 1 | if (NOT BINARY) 2 | message (FATAL_ERROR "BINARY file to check not specified!") 3 | endif () 4 | file (STRINGS "${BINARY}" strings REGEX "This text should be stripped out") 5 | if (strings) 6 | message (FATAL_ERROR "Text not stripped from binary like it should be: ${BINARY}") 7 | endif () 8 | -------------------------------------------------------------------------------- /vendor/gflags/test/gflags_declare_test.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | DEFINE_string(message, "", "The message to print"); 4 | void print_message(); // in gflags_declare_flags.cc 5 | 6 | int main(int argc, char **argv) 7 | { 8 | gflags::SetUsageMessage("Test compilation and use of gflags_declare.h"); 9 | gflags::ParseCommandLineFlags(&argc, &argv, true); 10 | print_message(); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /vendor/gflags/.gitignore: -------------------------------------------------------------------------------- 1 | /xcode/ 2 | /build/ 3 | /builds/ 4 | /build-*/ 5 | .DS_Store 6 | CMakeCache.txt 7 | DartConfiguration.tcl 8 | Makefile 9 | CMakeFiles/ 10 | /Testing/ 11 | /include/gflags/config.h 12 | /include/gflags/gflags_completions.h 13 | /include/gflags/gflags_declare.h 14 | /include/gflags/gflags.h 15 | /lib/ 16 | /test/gflags_unittest_main.cc 17 | /test/gflags_unittest-main.cc 18 | /packages/ 19 | CMakeLists.txt.user 20 | -------------------------------------------------------------------------------- /vendor/gflags/cmake/package.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@CMAKE_INSTALL_PREFIX@ 2 | exec_prefix=${prefix} 3 | bindir=${prefix}/@RUNTIME_INSTALL_DIR@ 4 | libdir=${prefix}/@LIBRARY_INSTALL_DIR@ 5 | includedir=${prefix}/@INCLUDE_INSTALL_DIR@ 6 | 7 | Name: @PACKAGE_NAME@ 8 | Version: @PACKAGE_VERSION@ 9 | Description: @PACKAGE_DESCRIPTION@ 10 | URL: @PACKAGE_URL@ 11 | Requires: 12 | Libs: -L${libdir} -lgflags 13 | Libs.private: -lpthread 14 | Cflags: -I${includedir} 15 | -------------------------------------------------------------------------------- /vendor/gflags/BUILD: -------------------------------------------------------------------------------- 1 | # Bazel (http://bazel.io/) BUILD file for gflags. 2 | # 3 | # See INSTALL.md for instructions for adding gflags to a Bazel workspace. 4 | 5 | licenses(["notice"]) 6 | 7 | exports_files(["src/gflags_complections.sh", "COPYING.txt"]) 8 | 9 | load(":bazel/gflags.bzl", "gflags_sources", "gflags_library") 10 | (hdrs, srcs) = gflags_sources(namespace=["gflags", "google"]) 11 | gflags_library(hdrs=hdrs, srcs=srcs, threads=0) 12 | gflags_library(hdrs=hdrs, srcs=srcs, threads=1) 13 | -------------------------------------------------------------------------------- /vendor/gflags/.travis.yml: -------------------------------------------------------------------------------- 1 | # Ubuntu 14.04 Trusty support, to get newer cmake and compilers. 2 | sudo: required 3 | dist: trusty 4 | 5 | language: cpp 6 | 7 | os: 8 | - linux 9 | - osx 10 | 11 | compiler: 12 | - clang 13 | - gcc 14 | 15 | env: 16 | - CONFIG=Release 17 | - CONFIG=Debug 18 | 19 | script: 20 | - mkdir out && cd out && cmake -D CMAKE_BUILD_TYPE=$CONFIG -D GFLAGS_BUILD_SHARED_LIBS=ON -D GFLAGS_BUILD_STATIC_LIBS=ON -D GFLAGS_BUILD_TESTING=ON .. && cmake --build . --config $CONFIG && ctest 21 | -------------------------------------------------------------------------------- /vendor/gflags/test/nc/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | ## gflags negative compilation tests 2 | 3 | cmake_minimum_required (VERSION 2.8.12 FATAL_ERROR) 4 | 5 | if (NOT TEST_NAME) 6 | message (FATAL_ERROR "Missing TEST_NAME CMake flag") 7 | endif () 8 | string (TOUPPER ${TEST_NAME} TEST_NAME_UPPER) 9 | 10 | project (gflags_${TEST_NAME}) 11 | 12 | find_package (gflags REQUIRED) 13 | include_directories ("${CMAKE_CURRENT_SOURCE_DIR}/..") 14 | add_definitions (-DTEST_${TEST_NAME_UPPER}) 15 | add_executable (gflags_${TEST_NAME} gflags_nc.cc) 16 | target_link_libraries(gflags_${TEST_NAME} gflags) 17 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | Copyright 2017 Corey H. Walsh (corey.walsh11@gmail.com) 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /vendor/gflags/test/config/main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | DEFINE_string(message, "Hello World!", "The message to print"); 5 | 6 | static bool ValidateMessage(const char* flagname, const std::string &message) 7 | { 8 | return !message.empty(); 9 | } 10 | DEFINE_validator(message, ValidateMessage); 11 | 12 | int main(int argc, char **argv) 13 | { 14 | gflags::SetUsageMessage("Test CMake configuration of gflags library (gflags-config.cmake)"); 15 | gflags::SetVersionString("0.1"); 16 | gflags::ParseCommandLineFlags(&argc, &argv, true); 17 | std::cout << FLAGS_message << std::endl; 18 | gflags::ShutDownCommandLineFlags(); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /vendor/gflags/cmake/version.cmake.in: -------------------------------------------------------------------------------- 1 | ## gflags CMake configuration version file 2 | 3 | # ----------------------------------------------------------------------------- 4 | # library version 5 | set (PACKAGE_VERSION "@PACKAGE_VERSION@") 6 | 7 | # ----------------------------------------------------------------------------- 8 | # check compatibility 9 | 10 | # Perform compatibility check here using the input CMake variables. 11 | # See example in http://www.cmake.org/Wiki/CMake_2.6_Notes. 12 | 13 | set (PACKAGE_VERSION_COMPATIBLE TRUE) 14 | set (PACKAGE_VERSION_UNSUITABLE FALSE) 15 | 16 | if ("${PACKAGE_FIND_VERSION_MAJOR}" EQUAL "@PACKAGE_VERSION_MAJOR@" AND 17 | "${PACKAGE_FIND_VERSION_MINOR}" EQUAL "@PACKAGE_VERSION_MINOR@") 18 | set (PACKAGE_VERSION_EXACT TRUE) 19 | else () 20 | set (PACKAGE_VERSION_EXACT FALSE) 21 | endif () 22 | -------------------------------------------------------------------------------- /generate_serialized.sh: -------------------------------------------------------------------------------- 1 | # ./bin/range_lib --method="pcddt" --map_path=../maps/synthetic.map.png --cddt_save_path=../tmp/synthetic/pcddt.json 2 | # ./bin/range_lib --method="cddt" --map_path=../maps/synthetic.map.png --cddt_save_path=../tmp/synthetic/cddt.json 3 | # ./bin/range_lib --method="pcddt" --map_path=../maps/basement_hallways_5cm.png --cddt_save_path=../tmp/basement/pcddt.json 4 | # ./bin/range_lib --method="cddt" --map_path=../maps/basement_hallways_5cm.png --cddt_save_path=../tmp/basement/cddt.json 5 | 6 | 7 | ./bin/range_lib --method="cddt" --map_path=../maps/basement_hallways_5cm.png --log_path=../tmp/basement/trial1/ 8 | ./bin/range_lib --method="cddt" --map_path=../maps/basement_hallways_5cm.png --log_path=../tmp/basement/trial2/ 9 | ./bin/range_lib --method="cddt" --map_path=../maps/basement_hallways_5cm.png --log_path=../tmp/basement/trial3/ 10 | ./bin/range_lib --method="cddt" --map_path=../maps/basement_hallways_5cm.png --log_path=../tmp/basement/trial4/ 11 | ./bin/range_lib --method="cddt" --map_path=../maps/basement_hallways_5cm.png --log_path=../tmp/basement/trial5/ -------------------------------------------------------------------------------- /vendor/gflags/appveyor.yml: -------------------------------------------------------------------------------- 1 | # Configuration for continuous integration service at appveyor.com 2 | 3 | shallow_clone: true 4 | 5 | # Operating system (build VM template) 6 | os: Visual Studio 2015 7 | 8 | # scripts that are called at very beginning, before repo cloning 9 | init: 10 | 11 | # clone directory 12 | clone_folder: c:\projects\gflags 13 | 14 | matrix: 15 | fast_finish: true 16 | 17 | platform: 18 | - Win32 19 | 20 | configuration: 21 | - Debug 22 | - Release 23 | 24 | install: 25 | # show all available env vars 26 | - set 27 | - echo cmake on AppVeyor, %configuration%-%platform% 28 | - cmake -version 29 | - call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" 30 | 31 | build_script: 32 | - cd c:\projects\gflags 33 | - mkdir out && cd out 34 | - cmake -G "Visual Studio 14 2015" 35 | -D CMAKE_BUILD_TYPE=%configuration% 36 | -D GFLAGS_BUILD_TESTING=ON 37 | -D GFLAGS_BUILD_SHARED_LIBS=ON 38 | -D GFLAGS_BUILD_STATIC_LIBS=ON 39 | .. 40 | - cmake --build . --config %configuration% 41 | 42 | test_script: 43 | - ctest -C %configuration% 44 | -------------------------------------------------------------------------------- /vendor/gflags/COPYING.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2006, Google Inc. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above 11 | copyright notice, this list of conditions and the following disclaimer 12 | in the documentation and/or other materials provided with the 13 | distribution. 14 | * Neither the name of Google Inc. nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /vendor/gflags/test/gflags_build.py.in: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | import subprocess 6 | import shutil 7 | 8 | CMAKE = '@CMAKE_COMMAND@' 9 | CMAKE_BUILD_TYPE = '@CMAKE_BUILD_TYPE@' 10 | TMPDIR = '@TMPDIR@' 11 | SRCDIR = '@SRCDIR@' 12 | GFLAGS_DIR = '@gflags_BINARY_DIR@' 13 | 14 | if __name__ == "__main__": 15 | if len(sys.argv) != 4: 16 | sys.stderr.write(' '.join(['usage:', sys.argv[0], ' \n'])) 17 | sys.exit(1) 18 | test_name = sys.argv[1] 19 | srcdir = sys.argv[2] 20 | expect_fail = (sys.argv[3].lower() in ['true', 'yes', 'on', '1']) 21 | bindir = os.path.join(TMPDIR, test_name) 22 | if TMPDIR == '': 23 | sys.stderr.write('Temporary directory not set!\n') 24 | sys.exit(1) 25 | # create build directory 26 | if os.path.isdir(bindir): shutil.rmtree(bindir) 27 | os.makedirs(bindir) 28 | # configure the build tree 29 | if subprocess.call([CMAKE, '-DCMAKE_BUILD_TYPE:STRING='+CMAKE_BUILD_TYPE, 30 | '-Dgflags_DIR:PATH='+GFLAGS_DIR, 31 | '-DTEST_NAME:STRING='+test_name, srcdir], cwd=bindir) != 0: 32 | sys.stderr.write('Failed to configure the build tree!\n') 33 | sys.exit(1) 34 | # build the test project 35 | exit_code = subprocess.call([CMAKE, '--build', bindir, '--config', CMAKE_BUILD_TYPE], cwd=bindir) 36 | if expect_fail == True: 37 | if exit_code == 0: 38 | sys.stderr.write('Build expected to fail, but it succeeded!\n') 39 | sys.exit(1) 40 | else: 41 | sys.stderr.write('Build failed as expected\n') 42 | exit_code = 0 43 | sys.exit(exit_code) 44 | -------------------------------------------------------------------------------- /includes/CudaRangeLib.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifndef ROS_WORLD_TO_GRID_CONVERSION 4 | #define ROS_WORLD_TO_GRID_CONVERSION 1 5 | #endif 6 | 7 | #ifndef M_PI 8 | #define M_PI 3.141592653589793238462643383279502 9 | #endif 10 | 11 | class RayMarchingCUDA 12 | { 13 | public: 14 | RayMarchingCUDA(std::vector > grid, int w, int h, float mr); 15 | ~RayMarchingCUDA(); 16 | void calc_range_many(float *ins, float *outs, int num_casts); 17 | void numpy_calc_range(float *ins, float *outs, int num_casts); 18 | void numpy_calc_range_angles(float * ins, float * angles, float * outs, int num_particles, int num_angles); 19 | void calc_range_repeat_angles_eval_sensor_model(float * ins, float * angles, float * obs, double * weights, int num_particles, int num_angles); 20 | 21 | void set_sensor_table(double *sensor_table, int table_width); 22 | 23 | #if ROS_WORLD_TO_GRID_CONVERSION == 1 24 | void set_conversion_params(float w_scale, float w_angle, float w_origin_x, 25 | float w_origin_y, float w_sin_angle, float w_cos_angle) { 26 | inv_world_scale = 1.0 / w_scale; 27 | world_scale = w_scale; 28 | world_angle = w_angle; 29 | world_origin_x = w_origin_x; 30 | world_origin_y = w_origin_y; 31 | world_sin_angle = w_sin_angle; 32 | world_cos_angle = w_cos_angle; 33 | rotation_const = -1.0 * w_angle - 3.0*M_PI / 2.0; 34 | constants_set = true; 35 | } 36 | #endif 37 | 38 | private: 39 | float *d_ins; 40 | float *d_outs; 41 | float *d_distMap; 42 | double *d_sensorTable; 43 | double *d_weights; 44 | int width; 45 | int height; 46 | int table_width; 47 | float max_range; 48 | 49 | bool allocated_weights = false; 50 | 51 | #if ROS_WORLD_TO_GRID_CONVERSION == 1 52 | float inv_world_scale; 53 | float world_scale; 54 | float world_angle; 55 | float world_origin_x; 56 | float world_origin_y; 57 | float world_sin_angle; 58 | float world_cos_angle; 59 | float rotation_const; 60 | bool constants_set = false; 61 | #endif 62 | }; -------------------------------------------------------------------------------- /vendor/gflags/cmake/execute_test.cmake: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------------------------------------- 2 | # sanitize string stored in variable for use in regular expression. 3 | macro (sanitize_for_regex STRVAR) 4 | string (REGEX REPLACE "([.+*?^$()])" "\\\\\\1" ${STRVAR} "${${STRVAR}}") 5 | endmacro () 6 | 7 | # ---------------------------------------------------------------------------- 8 | # script arguments 9 | if (NOT COMMAND) 10 | message (FATAL_ERROR "Test command not specified!") 11 | endif () 12 | if (NOT DEFINED EXPECTED_RC) 13 | set (EXPECTED_RC 0) 14 | endif () 15 | if (EXPECTED_OUTPUT) 16 | sanitize_for_regex(EXPECTED_OUTPUT) 17 | endif () 18 | if (UNEXPECTED_OUTPUT) 19 | sanitize_for_regex(UNEXPECTED_OUTPUT) 20 | endif () 21 | 22 | # ---------------------------------------------------------------------------- 23 | # set a few environment variables (useful for --tryfromenv) 24 | set (ENV{FLAGS_undefok} "foo,bar") 25 | set (ENV{FLAGS_weirdo} "") 26 | set (ENV{FLAGS_version} "true") 27 | set (ENV{FLAGS_help} "false") 28 | 29 | # ---------------------------------------------------------------------------- 30 | # execute test command 31 | execute_process( 32 | COMMAND ${COMMAND} 33 | RESULT_VARIABLE RC 34 | OUTPUT_VARIABLE OUTPUT 35 | ERROR_VARIABLE OUTPUT 36 | ) 37 | 38 | if (OUTPUT) 39 | message ("${OUTPUT}") 40 | endif () 41 | 42 | # ---------------------------------------------------------------------------- 43 | # check test result 44 | if (NOT RC EQUAL EXPECTED_RC) 45 | string (REPLACE ";" " " COMMAND "${COMMAND}") 46 | message (FATAL_ERROR "Command:\n\t${COMMAND}\nExit status is ${RC}, expected ${EXPECTED_RC}") 47 | endif () 48 | if (EXPECTED_OUTPUT AND NOT OUTPUT MATCHES "${EXPECTED_OUTPUT}") 49 | message (FATAL_ERROR "Test output does not match expected output: ${EXPECTED_OUTPUT}") 50 | endif () 51 | if (UNEXPECTED_OUTPUT AND OUTPUT MATCHES "${UNEXPECTED_OUTPUT}") 52 | message (FATAL_ERROR "Test output matches unexpected output: ${UNEXPECTED_OUTPUT}") 53 | endif () -------------------------------------------------------------------------------- /vendor/gflags/cmake/package.cmake.in: -------------------------------------------------------------------------------- 1 | # Per-generator CPack configuration file. See CPACK_PROJECT_CONFIG_FILE documented at 2 | # http://www.cmake.org/cmake/help/v2.8.12/cpack.html#variable:CPACK_PROJECT_CONFIG_FILE 3 | # 4 | # All common CPACK_* variables are set in CMakeLists.txt already. This file only 5 | # overrides some of these to provide package generator specific settings. 6 | 7 | # whether package contains all development files or only runtime files 8 | set (DEVEL @INSTALL_HEADERS@) 9 | 10 | # ------------------------------------------------------------------------------ 11 | # Mac OS X package 12 | if (CPACK_GENERATOR MATCHES "PackageMaker|DragNDrop") 13 | 14 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}") 15 | if (DEVEL) 16 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-devel") 17 | endif () 18 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CPACK_PACKAGE_VERSION}") 19 | 20 | # ------------------------------------------------------------------------------ 21 | # Debian package 22 | elseif (CPACK_GENERATOR MATCHES "DEB") 23 | 24 | set (CPACK_PACKAGE_FILE_NAME "lib${CPACK_PACKAGE_NAME}") 25 | if (DEVEL) 26 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-dev") 27 | else () 28 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}0") 29 | endif () 30 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}_${CPACK_PACKAGE_VERSION}-1_${CPACK_PACKAGE_ARCHITECTURE}") 31 | 32 | set (CPACK_DEBIAN_PACKAGE_DEPENDS) 33 | set (CPACK_DEBIAN_PACKAGE_SECTION "devel") 34 | set (CPACK_DEBIAN_PACKAGE_PRIORITY "optional") 35 | set (CPACK_DEBIAN_PACKAGE_HOMEPAGE "${CPACK_RPM_PACKAGE_URL}") 36 | set (CPACK_DEBIAN_PACKAGE_MAINTAINER "${CPACK_PACKAGE_VENDOR}") 37 | set (CPACK_DEBIAN_PACKAGE_ARCHITECTURE "${CPACK_PACKAGE_ARCHITECTURE}") 38 | 39 | # ------------------------------------------------------------------------------ 40 | # RPM package 41 | elseif (CPACK_GENERATOR MATCHES "RPM") 42 | 43 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}") 44 | if (DEVEL) 45 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-devel") 46 | endif () 47 | set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CPACK_PACKAGE_VERSION}-1.${CPACK_PACKAGE_ARCHITECTURE}") 48 | 49 | endif () 50 | -------------------------------------------------------------------------------- /make_plots.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import numpy as np 3 | from scipy.ndimage.morphology import distance_transform_edt 4 | import matplotlib.pyplot as plt 5 | from matplotlib import cm 6 | from mpl_toolkits.axes_grid1 import make_axes_locatable 7 | 8 | def reject_outliers(data, m = 12.): 9 | d = np.abs(data - np.median(data)) 10 | mdev = np.median(d) 11 | s = d/mdev if mdev else 0. 12 | return data[s 39 | 40 | #include 41 | 42 | using GFLAGS_NAMESPACE::SetUsageMessage; 43 | using GFLAGS_NAMESPACE::ParseCommandLineFlags; 44 | 45 | 46 | DEFINE_bool(test, true, "This text should be stripped out"); 47 | 48 | int main(int argc, char** argv) { 49 | SetUsageMessage("Usage message"); 50 | ParseCommandLineFlags(&argc, &argv, false); 51 | 52 | // Unfortunately, for us, libtool can replace executables with a shell 53 | // script that does some work before calling the 'real' executable 54 | // under a different name. We need the 'real' executable name to run 55 | // 'strings' on it, so we construct this binary to print the real 56 | // name (argv[0]) on stdout when run. 57 | puts(argv[0]); 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /vendor/gflags/test/nc/gflags_nc.cc: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2009, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | // --- 31 | // 32 | // A negative comiple test for gflags. 33 | 34 | #include 35 | 36 | #if defined(TEST_NC_SWAPPED_ARGS) 37 | 38 | DEFINE_bool(some_bool_flag, 39 | "the default value should go here, not the description", 40 | false); 41 | 42 | 43 | #elif defined(TEST_NC_INT_INSTEAD_OF_BOOL) 44 | 45 | DEFINE_bool(some_bool_flag_2, 46 | 0, 47 | "should have been an int32 flag but mistakenly used bool instead"); 48 | 49 | #elif defined(TEST_NC_BOOL_IN_QUOTES) 50 | 51 | 52 | DEFINE_bool(some_bool_flag_3, 53 | "false", 54 | "false in in quotes, which is wrong"); 55 | 56 | #elif defined(TEST_NC_SANITY) 57 | 58 | DEFINE_bool(some_bool_flag_4, 59 | true, 60 | "this is the correct usage of DEFINE_bool"); 61 | 62 | #elif defined(TEST_NC_DEFINE_STRING_WITH_0) 63 | 64 | DEFINE_string(some_string_flag, 65 | 0, 66 | "Trying to construct a string by passing 0 would cause a crash."); 67 | 68 | #endif 69 | 70 | int main(int, char **) 71 | { 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /vendor/gflags/src/windows_port.cc: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2009, Google Inc. 2 | * All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are 6 | * met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above 11 | * copyright notice, this list of conditions and the following disclaimer 12 | * in the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Google Inc. nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * --- 31 | * Author: Craig Silverstein 32 | */ 33 | 34 | #ifndef _WIN32 35 | # error You should only be including windows/port.cc in a windows environment! 36 | #endif 37 | 38 | #include // for strlen(), memset(), memcmp() 39 | #include 40 | #include // for va_list, va_start, va_end 41 | #include 42 | 43 | #include "windows_port.h" 44 | 45 | // These call the windows _vsnprintf, but always NUL-terminate. 46 | #if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */ 47 | #if !(defined(_MSC_VER) && _MSC_VER >= 1900) /* msvc 2015 already defines */ 48 | 49 | #ifdef _MSC_VER 50 | # pragma warning(push) 51 | # pragma warning(disable: 4996) // ignore _vsnprintf security warning 52 | #endif 53 | int safe_vsnprintf(char *str, size_t size, const char *format, va_list ap) { 54 | if (size == 0) // not even room for a \0? 55 | return -1; // not what C99 says to do, but what windows does 56 | str[size-1] = '\0'; 57 | return _vsnprintf(str, size-1, format, ap); 58 | } 59 | #ifdef _MSC_VER 60 | # pragma warning(pop) 61 | #endif 62 | 63 | int snprintf(char *str, size_t size, const char *format, ...) { 64 | int r; 65 | va_list ap; 66 | va_start(ap, format); 67 | r = vsnprintf(str, size, format, ap); 68 | va_end(ap); 69 | return r; 70 | } 71 | 72 | #endif /* if !(defined(_MSC_VER) && _MSC_VER >= 1900) */ 73 | #endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */ 74 | -------------------------------------------------------------------------------- /vendor/gflags/bazel/gflags.bzl: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------ 2 | # Add native rules to configure source files 3 | def gflags_sources(namespace=["google", "gflags"]): 4 | native.genrule( 5 | name = "config_h", 6 | srcs = ["src/config.h.in"], 7 | outs = ["config.h"], 8 | cmd = "awk '{ gsub(/^#cmakedefine/, \"//cmakedefine\"); print; }' $(<) > $(@)" 9 | ) 10 | native.genrule( 11 | name = "gflags_declare_h", 12 | srcs = ["src/gflags_declare.h.in"], 13 | outs = ["include/gflags/gflags_declare.h"], 14 | cmd = ("awk '{ " + 15 | "gsub(/@GFLAGS_NAMESPACE@/, \"" + namespace[0] + "\"); " + 16 | "gsub(/@(HAVE_STDINT_H|HAVE_SYS_TYPES_H|HAVE_INTTYPES_H|GFLAGS_INTTYPES_FORMAT_C99)@/, \"1\"); " + 17 | "gsub(/@([A-Z0-9_]+)@/, \"0\"); " + 18 | "print; }' $(<) > $(@)") 19 | ) 20 | gflags_ns_h_files = [] 21 | for ns in namespace[1:]: 22 | gflags_ns_h_file = "gflags_{}.h".format(ns) 23 | native.genrule( 24 | name = gflags_ns_h_file.replace('.', '_'), 25 | srcs = ["src/gflags_ns.h.in"], 26 | outs = ["include/gflags/" + gflags_ns_h_file], 27 | cmd = ("awk '{ " + 28 | "gsub(/@ns@/, \"" + ns + "\"); " + 29 | "gsub(/@NS@/, \"" + ns.upper() + "\"); " + 30 | "print; }' $(<) > $(@)") 31 | ) 32 | gflags_ns_h_files.append(gflags_ns_h_file) 33 | native.genrule( 34 | name = "gflags_h", 35 | srcs = ["src/gflags.h.in"], 36 | outs = ["include/gflags/gflags.h"], 37 | cmd = ("awk '{ " + 38 | "gsub(/@GFLAGS_ATTRIBUTE_UNUSED@/, \"\"); " + 39 | "gsub(/@INCLUDE_GFLAGS_NS_H@/, \"" + '\n'.join(["#include \\\"gflags/{}\\\"".format(hdr) for hdr in gflags_ns_h_files]) + "\"); " + 40 | "print; }' $(<) > $(@)") 41 | ) 42 | native.genrule( 43 | name = "gflags_completions_h", 44 | srcs = ["src/gflags_completions.h.in"], 45 | outs = ["include/gflags/gflags_completions.h"], 46 | cmd = "awk '{ gsub(/@GFLAGS_NAMESPACE@/, \"" + namespace[0] + "\"); print; }' $(<) > $(@)" 47 | ) 48 | hdrs = [":gflags_h", ":gflags_declare_h", ":gflags_completions_h"] 49 | hdrs.extend([':' + hdr.replace('.', '_') for hdr in gflags_ns_h_files]) 50 | srcs = [ 51 | ":config_h", 52 | "src/gflags.cc", 53 | "src/gflags_completions.cc", 54 | "src/gflags_reporting.cc", 55 | "src/mutex.h", 56 | "src/util.h" 57 | ] 58 | return [hdrs, srcs] 59 | 60 | # ------------------------------------------------------------------------------ 61 | # Add native rule to build gflags library 62 | def gflags_library(hdrs=[], srcs=[], threads=1): 63 | name = "gflags" 64 | copts = [ 65 | "-DHAVE_STDINT_H", 66 | "-DHAVE_SYS_TYPES_H", 67 | "-DHAVE_INTTYPES_H", 68 | "-DHAVE_SYS_STAT_H", 69 | "-DHAVE_UNISTD_H", 70 | "-DHAVE_FNMATCH_H", 71 | "-DHAVE_STRTOLL", 72 | "-DHAVE_STRTOQ", 73 | "-DHAVE_PTHREAD", 74 | "-DHAVE_RWLOCK", 75 | "-DGFLAGS_INTTYPES_FORMAT_C99", 76 | "-DGFLAGS_IS_A_DLL=0", 77 | ] 78 | linkopts = [] 79 | if threads: 80 | linkopts.append("-lpthread") 81 | else: 82 | name += "_nothreads" 83 | copts.append("-DNO_THREADS") 84 | native.cc_library( 85 | name = name, 86 | hdrs = hdrs, 87 | srcs = srcs, 88 | includes = ["include/"], 89 | copts = copts, 90 | linkopts = linkopts, 91 | visibility = ["//visibility:public"] 92 | ) 93 | -------------------------------------------------------------------------------- /includes/lru_cache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: lrucache.hpp 3 | * Author: Alexander Ponomarev 4 | * 5 | * Created on June 20, 2013, 5:09 PM 6 | 7 | Copyright (c) 2014, lamerman 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions are met: 12 | 13 | * Redistributions of source code must retain the above copyright notice, this 14 | list of conditions and the following disclaimer. 15 | 16 | * Redistributions in binary form must reproduce the above copyright notice, 17 | this list of conditions and the following disclaimer in the documentation 18 | and/or other materials provided with the distribution. 19 | 20 | * Neither the name of lamerman nor the names of its 21 | contributors may be used to endorse or promote products derived from 22 | this software without specific prior written permission. 23 | 24 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 25 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 28 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 30 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 31 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 32 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 33 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | 35 | */ 36 | 37 | #ifndef _LRU_CACHE_H_INCLUDED_ 38 | #define _LRU_CACHE_H_INCLUDED_ 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | 45 | namespace cache { 46 | 47 | template 48 | class lru_cache { 49 | public: 50 | typedef typename std::pair key_value_pair_t; 51 | typedef typename std::list::iterator list_iterator_t; 52 | 53 | lru_cache() : lru_cache(0,0) {} 54 | lru_cache(size_t max_size, value_t dv) : 55 | _max_size(max_size), default_val(dv) { 56 | } 57 | 58 | void put(const key_t& key, const value_t& value) { 59 | auto it = _cache_items_map.find(key); 60 | _cache_items_list.push_front(key_value_pair_t(key, value)); 61 | if (it != _cache_items_map.end()) { 62 | _cache_items_list.erase(it->second); 63 | _cache_items_map.erase(it); 64 | } 65 | _cache_items_map[key] = _cache_items_list.begin(); 66 | 67 | if (_cache_items_map.size() > _max_size) { 68 | auto last = _cache_items_list.end(); 69 | last--; 70 | _cache_items_map.erase(last->first); 71 | _cache_items_list.pop_back(); 72 | } 73 | } 74 | 75 | const value_t& get(const key_t& key) { 76 | auto it = _cache_items_map.find(key); 77 | if (it == _cache_items_map.end()) { 78 | return default_val; 79 | // throw std::range_error("There is no such key in cache"); 80 | } else { 81 | _cache_items_list.splice(_cache_items_list.begin(), _cache_items_list, it->second); 82 | return it->second->second; 83 | } 84 | } 85 | 86 | bool exists(const key_t& key) const { 87 | return _cache_items_map.find(key) != _cache_items_map.end(); 88 | } 89 | 90 | size_t size() const { 91 | return _cache_items_map.size(); 92 | } 93 | 94 | private: 95 | std::list _cache_items_list; 96 | std::unordered_map _cache_items_map; 97 | size_t _max_size; 98 | value_t default_val; 99 | }; 100 | 101 | } // namespace lru 102 | 103 | #endif /* _LRU_CACHE_H_INCLUDED_ */ -------------------------------------------------------------------------------- /vendor/gflags/src/config.h.in: -------------------------------------------------------------------------------- 1 | /* Generated from config.h.in during build configuration using CMake. */ 2 | 3 | // Note: This header file is only used internally. It is not part of public interface! 4 | 5 | #ifndef GFLAGS_CONFIG_H_ 6 | #define GFLAGS_CONFIG_H_ 7 | 8 | 9 | // --------------------------------------------------------------------------- 10 | // System checks 11 | 12 | // Define if you build this library for a MS Windows OS. 13 | #cmakedefine OS_WINDOWS 14 | 15 | // Define if you have the header file. 16 | #cmakedefine HAVE_STDINT_H 17 | 18 | // Define if you have the header file. 19 | #cmakedefine HAVE_SYS_TYPES_H 20 | 21 | // Define if you have the header file. 22 | #cmakedefine HAVE_INTTYPES_H 23 | 24 | // Define if you have the header file. 25 | #cmakedefine HAVE_SYS_STAT_H 26 | 27 | // Define if you have the header file. 28 | #cmakedefine HAVE_UNISTD_H 29 | 30 | // Define if you have the header file. 31 | #cmakedefine HAVE_FNMATCH_H 32 | 33 | // Define if you have the header file (Windows 2000/XP). 34 | #cmakedefine HAVE_SHLWAPI_H 35 | 36 | // Define if you have the strtoll function. 37 | #cmakedefine HAVE_STRTOLL 38 | 39 | // Define if you have the strtoq function. 40 | #cmakedefine HAVE_STRTOQ 41 | 42 | // Define if you have the header file. 43 | #cmakedefine HAVE_PTHREAD 44 | 45 | // Define if your pthread library defines the type pthread_rwlock_t 46 | #cmakedefine HAVE_RWLOCK 47 | 48 | // gcc requires this to get PRId64, etc. 49 | #if defined(HAVE_INTTYPES_H) && !defined(__STDC_FORMAT_MACROS) 50 | # define __STDC_FORMAT_MACROS 1 51 | #endif 52 | 53 | // --------------------------------------------------------------------------- 54 | // Package information 55 | 56 | // Name of package. 57 | #define PACKAGE @PROJECT_NAME@ 58 | 59 | // Define to the full name of this package. 60 | #define PACKAGE_NAME @PACKAGE_NAME@ 61 | 62 | // Define to the full name and version of this package. 63 | #define PACKAGE_STRING @PACKAGE_STRING@ 64 | 65 | // Define to the one symbol short name of this package. 66 | #define PACKAGE_TARNAME @PACKAGE_TARNAME@ 67 | 68 | // Define to the version of this package. 69 | #define PACKAGE_VERSION @PACKAGE_VERSION@ 70 | 71 | // Version number of package. 72 | #define VERSION PACKAGE_VERSION 73 | 74 | // Define to the address where bug reports for this package should be sent. 75 | #define PACKAGE_BUGREPORT @PACKAGE_BUGREPORT@ 76 | 77 | // --------------------------------------------------------------------------- 78 | // Path separator 79 | #ifndef PATH_SEPARATOR 80 | # ifdef OS_WINDOWS 81 | # define PATH_SEPARATOR '\\' 82 | # else 83 | # define PATH_SEPARATOR '/' 84 | # endif 85 | #endif 86 | 87 | // --------------------------------------------------------------------------- 88 | // Windows 89 | 90 | // Always export symbols when compiling a shared library as this file is only 91 | // included by internal modules when building the gflags library itself. 92 | // The gflags_declare.h header file will set it to import these symbols otherwise. 93 | #ifndef GFLAGS_DLL_DECL 94 | # if GFLAGS_IS_A_DLL && defined(_MSC_VER) 95 | # define GFLAGS_DLL_DECL __declspec(dllexport) 96 | # else 97 | # define GFLAGS_DLL_DECL 98 | # endif 99 | #endif 100 | // Flags defined by the gflags library itself must be exported 101 | #ifndef GFLAGS_DLL_DEFINE_FLAG 102 | # define GFLAGS_DLL_DEFINE_FLAG GFLAGS_DLL_DECL 103 | #endif 104 | 105 | #ifdef OS_WINDOWS 106 | // The unittests import the symbols of the shared gflags library 107 | # if GFLAGS_IS_A_DLL && defined(_MSC_VER) 108 | # define GFLAGS_DLL_DECL_FOR_UNITTESTS __declspec(dllimport) 109 | # endif 110 | # include "windows_port.h" 111 | #endif 112 | 113 | 114 | #endif // GFLAGS_CONFIG_H_ 115 | -------------------------------------------------------------------------------- /vendor/gflags/INSTALL.md: -------------------------------------------------------------------------------- 1 | Installing a binary distribution package 2 | ======================================== 3 | 4 | No official binary distribution packages are provided by the gflags developers. 5 | There may, however, be binary packages available for your OS. Please consult 6 | also the package repositories of your Linux distribution. 7 | 8 | For example on Debian/Ubuntu Linux, gflags can be installed using the 9 | following command: 10 | 11 | sudo apt-get install libgflags-dev 12 | 13 | 14 | Compiling the source code with CMake 15 | ========================= 16 | 17 | The build system of gflags is since version 2.1 based on [CMake](http://cmake.org). 18 | The common steps to build, test, and install software are therefore: 19 | 20 | 1. Extract source files. 21 | 2. Create build directory and change to it. 22 | 3. Run CMake to configure the build tree. 23 | 4. Build the software using selected build tool. 24 | 5. Test the built software. 25 | 6. Install the built files. 26 | 27 | On Unix-like systems with GNU Make as build tool, these build steps can be 28 | summarized by the following sequence of commands executed in a shell, 29 | where ```$package``` and ```$version``` are shell variables which represent 30 | the name of this package and the obtained version of the software. 31 | 32 | $ tar xzf gflags-$version-source.tar.gz 33 | $ cd gflags-$version 34 | $ mkdir build && cd build 35 | $ ccmake .. 36 | 37 | - Press 'c' to configure the build system and 'e' to ignore warnings. 38 | - Set CMAKE_INSTALL_PREFIX and other CMake variables and options. 39 | - Continue pressing 'c' until the option 'g' is available. 40 | - Then press 'g' to generate the configuration files for GNU Make. 41 | 42 | $ make 43 | $ make test (optional) 44 | $ make install (optional) 45 | 46 | In the following, only gflags-specific CMake settings available to 47 | configure the build and installation are documented. Note that most of these 48 | variables are for advanced users and binary package maintainers only. 49 | They usually do not have to be modified. 50 | 51 | 52 | CMake Option | Description 53 | --------------------------- | ------------------------------------------------------- 54 | CMAKE_INSTALL_PREFIX | Installation directory, e.g., "/usr/local" on Unix and "C:\Program Files\gflags" on Windows. 55 | BUILD_SHARED_LIBS | Request build of dynamic link libraries. 56 | BUILD_STATIC_LIBS | Request build of static link libraries. Implied if BUILD_SHARED_LIBS is OFF. 57 | BUILD_PACKAGING | Enable binary package generation using CPack. 58 | BUILD_TESTING | Build tests for execution by CTest. 59 | BUILD_NC_TESTS | Request inclusion of negative compilation tests (requires Python). 60 | BUILD_CONFIG_TESTS | Request inclusion of package configuration tests (requires Python). 61 | BUILD_gflags_LIBS | Request build of multi-threaded gflags libraries (if threading library found). 62 | BUILD_gflags_nothreads_LIBS | Request build of single-threaded gflags libraries. 63 | GFLAGS_NAMESPACE | Name of the C++ namespace to be used by the gflags library. Note that the public source header files are installed in a subdirectory named after this namespace. To maintain backwards compatibility with the Google Commandline Flags, set this variable to "google". The default is "gflags". 64 | GFLAGS_INTTYPES_FORMAT | String identifying format of built-in integer types. 65 | GFLAGS_INCLUDE_DIR | Name of headers installation directory relative to CMAKE_INSTALL_PREFIX. 66 | LIBRARY_INSTALL_DIR | Name of library installation directory relative to CMAKE_INSTALL_PREFIX. 67 | INSTALL_HEADERS | Request installation of public header files. 68 | 69 | Using gflags with [Bazel](http://bazel.io) 70 | ========================= 71 | 72 | To use gflags in a Bazel project, map it in as an external dependency by editing 73 | your WORKSPACE file: 74 | 75 | git_repository( 76 | name = "com_github_gflags_gflags", 77 | commit = "", 78 | remote = "https://github.com/gflags/gflags.git", 79 | ) 80 | 81 | bind( 82 | name = "gflags", 83 | actual = "@com_github_gflags_gflags//:gflags", 84 | ) 85 | 86 | You can then add `//external:gflags` to the `deps` section of a `cc_binary` or 87 | `cc_library` rule, and `#include ` to include it in your source 88 | code. 89 | -------------------------------------------------------------------------------- /vendor/gflags/src/gflags_ns.h.in: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014, Andreas Schuh 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | // ----------------------------------------------------------------------------- 31 | // Imports the gflags library symbols into an alternative/deprecated namespace. 32 | 33 | #ifndef GFLAGS_GFLAGS_H_ 34 | # error The internal header gflags_@ns@.h may only be included by gflags.h 35 | #endif 36 | 37 | #ifndef GFLAGS_NS_@NS@_H_ 38 | #define GFLAGS_NS_@NS@_H_ 39 | 40 | 41 | namespace @ns@ { 42 | 43 | 44 | using GFLAGS_NAMESPACE::int32; 45 | using GFLAGS_NAMESPACE::uint32; 46 | using GFLAGS_NAMESPACE::int64; 47 | using GFLAGS_NAMESPACE::uint64; 48 | 49 | using GFLAGS_NAMESPACE::RegisterFlagValidator; 50 | using GFLAGS_NAMESPACE::CommandLineFlagInfo; 51 | using GFLAGS_NAMESPACE::GetAllFlags; 52 | using GFLAGS_NAMESPACE::ShowUsageWithFlags; 53 | using GFLAGS_NAMESPACE::ShowUsageWithFlagsRestrict; 54 | using GFLAGS_NAMESPACE::DescribeOneFlag; 55 | using GFLAGS_NAMESPACE::SetArgv; 56 | using GFLAGS_NAMESPACE::GetArgvs; 57 | using GFLAGS_NAMESPACE::GetArgv; 58 | using GFLAGS_NAMESPACE::GetArgv0; 59 | using GFLAGS_NAMESPACE::GetArgvSum; 60 | using GFLAGS_NAMESPACE::ProgramInvocationName; 61 | using GFLAGS_NAMESPACE::ProgramInvocationShortName; 62 | using GFLAGS_NAMESPACE::ProgramUsage; 63 | using GFLAGS_NAMESPACE::VersionString; 64 | using GFLAGS_NAMESPACE::GetCommandLineOption; 65 | using GFLAGS_NAMESPACE::GetCommandLineFlagInfo; 66 | using GFLAGS_NAMESPACE::GetCommandLineFlagInfoOrDie; 67 | using GFLAGS_NAMESPACE::FlagSettingMode; 68 | using GFLAGS_NAMESPACE::SET_FLAGS_VALUE; 69 | using GFLAGS_NAMESPACE::SET_FLAG_IF_DEFAULT; 70 | using GFLAGS_NAMESPACE::SET_FLAGS_DEFAULT; 71 | using GFLAGS_NAMESPACE::SetCommandLineOption; 72 | using GFLAGS_NAMESPACE::SetCommandLineOptionWithMode; 73 | using GFLAGS_NAMESPACE::FlagSaver; 74 | using GFLAGS_NAMESPACE::CommandlineFlagsIntoString; 75 | using GFLAGS_NAMESPACE::ReadFlagsFromString; 76 | using GFLAGS_NAMESPACE::AppendFlagsIntoFile; 77 | using GFLAGS_NAMESPACE::ReadFromFlagsFile; 78 | using GFLAGS_NAMESPACE::BoolFromEnv; 79 | using GFLAGS_NAMESPACE::Int32FromEnv; 80 | using GFLAGS_NAMESPACE::Uint32FromEnv; 81 | using GFLAGS_NAMESPACE::Int64FromEnv; 82 | using GFLAGS_NAMESPACE::Uint64FromEnv; 83 | using GFLAGS_NAMESPACE::DoubleFromEnv; 84 | using GFLAGS_NAMESPACE::StringFromEnv; 85 | using GFLAGS_NAMESPACE::SetUsageMessage; 86 | using GFLAGS_NAMESPACE::SetVersionString; 87 | using GFLAGS_NAMESPACE::ParseCommandLineNonHelpFlags; 88 | using GFLAGS_NAMESPACE::HandleCommandLineHelpFlags; 89 | using GFLAGS_NAMESPACE::AllowCommandLineReparsing; 90 | using GFLAGS_NAMESPACE::ReparseCommandLineNonHelpFlags; 91 | using GFLAGS_NAMESPACE::ShutDownCommandLineFlags; 92 | using GFLAGS_NAMESPACE::FlagRegisterer; 93 | 94 | #ifndef SWIG 95 | using GFLAGS_NAMESPACE::ParseCommandLineFlags; 96 | #endif 97 | 98 | 99 | } // namespace @ns@ 100 | 101 | 102 | #endif // GFLAGS_NS_@NS@_H_ 103 | -------------------------------------------------------------------------------- /pywrapper/test.py: -------------------------------------------------------------------------------- 1 | import range_libc 2 | import numpy as np 3 | import itertools, time 4 | # import matplotlib.mlab as mlab 5 | # import matplotlib.pyplot as plt 6 | 7 | #################################################################################################### 8 | # 9 | # WARNING 10 | # 11 | # 12 | # This file uses range_libc in it's native coordinate space. 13 | # Use this method at your own peril since the coordinate 14 | # conversions are nontrivial from ROS's coordinate space. 15 | # Ignore this warning if you intend to use range_libc's 16 | # left handed coordinate space 17 | # 18 | # 19 | #################################################################################################### 20 | 21 | # print range_libc.USE_CACHED_TRIG 22 | # print range_libc.USE_CACHED_TRIG 23 | # print range_libc.USE_ALTERNATE_MOD 24 | # print range_libc.USE_CACHED_CONSTANTS 25 | # print range_libc.USE_FAST_ROUND 26 | # print range_libc.NO_INLINE 27 | # print range_libc.USE_LRU_CACHE 28 | # print range_libc.LRU_CACHE_SIZE 29 | 30 | # testMap = range_libc.PyOMap("../maps/basement_hallways_5cm.png",1) 31 | testMap = range_libc.PyOMap("../maps/synthetic.map.png",1) 32 | # testMap = range_libc.PyOMap("/home/racecar/racecar-ws/src/TA_examples/lab5/maps/basement.png",1) 33 | 34 | if testMap.error(): 35 | exit() 36 | # testMap.save("./test.png") 37 | 38 | num_vals = 100000 39 | 40 | # vals = np.zeros((3,num_vals), dtype=np.float32) 41 | # vals[0,:] = testMap.width()/2.0 42 | # vals[1,:] = testMap.height()/2.0 43 | # vals[2,:] = np.linspace(0,2.0*np.pi, num=num_vals) 44 | 45 | # def make_scan(x,y,theta,n_ranges): 46 | # MAX_SCAN_ANGLE = (0.75 * np.pi) 47 | # bl = range_libc.PyBresenhamsLine(testMap, 300) 48 | # # bl = range_libc.PyRayMarching(testMap, 500) 49 | # queries = np.zeros((n_ranges,3),dtype=np.float32) 50 | # ranges = np.zeros(n_ranges,dtype=np.float32) 51 | # queries[:,0] = x 52 | # queries[:,1] = y 53 | # queries[:,2] = theta + np.linspace(-MAX_SCAN_ANGLE, MAX_SCAN_ANGLE, n_ranges) 54 | # bl.calc_range_many(queries,ranges) 55 | # bl.saveTrace("./test.png") 56 | 57 | # make_scan(510,520,np.pi/2.0,61) 58 | 59 | print "Init: bl" 60 | bl = range_libc.PyBresenhamsLine(testMap, 500) 61 | print "Init: rm" 62 | rm = range_libc.PyRayMarching(testMap, 500) 63 | print "Init: cddt" 64 | cddt = range_libc.PyCDDTCast(testMap, 500, 108) 65 | cddt.prune() 66 | print "Init: glt" 67 | glt = range_libc.PyGiantLUTCast(testMap, 500, 108) 68 | # this is for testing the amount of raw functional call overhead, does not compute ranges 69 | # null = range_libc.PyNull(testMap, 500, 108) 70 | 71 | for x in xrange(10): 72 | vals = np.random.random((3,num_vals)).astype(np.float32) 73 | vals[0,:] *= (testMap.width() - 2.0) 74 | vals[1,:] *= (testMap.height() - 2.0) 75 | vals[0,:] += 1.0 76 | vals[1,:] += 1.0 77 | vals[2,:] *= np.pi * 2.0 78 | ranges = np.zeros(num_vals, dtype=np.float32) 79 | 80 | test_states = [None]*num_vals 81 | for i in xrange(num_vals): 82 | test_states[i] = (vals[0,i], vals[1,i], vals[2,i]) 83 | 84 | def bench(obj,name): 85 | print "Running:", name 86 | start = time.clock() 87 | obj.calc_range_many(vals, ranges) 88 | end = time.clock() 89 | dur_np = end - start 90 | print ",,,"+name+" np: finished computing", ranges.shape[0], "ranges in", dur_np, "sec" 91 | start = time.clock() 92 | ranges_slow = map(lambda x: obj.calc_range(*x), test_states) 93 | end = time.clock() 94 | dur = end - start 95 | 96 | diff = np.linalg.norm(ranges - np.array(ranges_slow)) 97 | if diff > 0.001: 98 | print ",,,"+"Numpy result different from slow result, investigation possibly required. norm:", diff 99 | # print "DIFF:", diff 100 | 101 | print ",,,"+name+": finished computing", ranges.shape[0], "ranges in", dur, "sec" 102 | print ",,,"+"Numpy speedup:", dur/dur_np 103 | 104 | bench(bl, "bl") 105 | bench(rm, "rm") 106 | bench(cddt, "cddt") 107 | bench(glt, "glt") 108 | 109 | # ranges_bl = np.zeros(num_vals, dtype=np.float32) 110 | # ranges_rm = np.zeros(num_vals, dtype=np.float32) 111 | # ranges_cddt = np.zeros(num_vals, dtype=np.float32) 112 | # ranges_glt = np.zeros(num_vals, dtype=np.float32) 113 | 114 | # bl.calc_range_np(vals, ranges_bl) 115 | # rm.calc_range_np(vals, ranges_rm) 116 | # cddt.calc_range_np(vals, ranges_cddt) 117 | # glt.calc_range_np(vals, ranges_glt) 118 | 119 | # diff = ranges_rm - ranges_cddt 120 | # norm = np.linalg.norm(diff) 121 | # avg = np.mean(diff) 122 | # min_v = np.min(diff) 123 | # max_v = np.max(diff) 124 | # median = np.median(diff) 125 | # print avg, min_v, max_v, median 126 | 127 | # plt.hist(diff, bins=1000, normed=1, facecolor='green', alpha=0.75) 128 | # plt.show() 129 | 130 | # this is for testing the amount of raw functional call overhead, does not compute ranges 131 | # bench(null, "null") 132 | print "DONE" -------------------------------------------------------------------------------- /vendor/gflags/src/gflags_completions.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright (c) 2008, Google Inc. 4 | # All rights reserved. 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # * Redistributions of source code must retain the above copyright 11 | # notice, this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above 13 | # copyright notice, this list of conditions and the following disclaimer 14 | # in the documentation and/or other materials provided with the 15 | # distribution. 16 | # * Neither the name of Google Inc. nor the names of its 17 | # contributors may be used to endorse or promote products derived from 18 | # this software without specific prior written permission. 19 | # 20 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | # 32 | # --- 33 | # Author: Dave Nicponski 34 | # 35 | # This script is invoked by bash in response to a matching compspec. When 36 | # this happens, bash calls this script using the command shown in the -C 37 | # block of the complete entry, but also appends 3 arguments. They are: 38 | # - The command being used for completion 39 | # - The word being completed 40 | # - The word preceding the completion word. 41 | # 42 | # Here's an example of how you might use this script: 43 | # $ complete -o bashdefault -o default -o nospace -C \ 44 | # '/usr/local/bin/gflags_completions.sh --tab_completion_columns $COLUMNS' \ 45 | # time env binary_name another_binary [...] 46 | 47 | # completion_word_index gets the index of the (N-1)th argument for 48 | # this command line. completion_word gets the actual argument from 49 | # this command line at the (N-1)th position 50 | completion_word_index="$(($# - 1))" 51 | completion_word="${!completion_word_index}" 52 | 53 | # TODO(user): Replace this once gflags_completions.cc has 54 | # a bool parameter indicating unambiguously to hijack the process for 55 | # completion purposes. 56 | if [ -z "$completion_word" ]; then 57 | # Until an empty value for the completion word stops being misunderstood 58 | # by binaries, don't actually execute the binary or the process 59 | # won't be hijacked! 60 | exit 0 61 | fi 62 | 63 | # binary_index gets the index of the command being completed (which bash 64 | # places in the (N-2)nd position. binary gets the actual command from 65 | # this command line at that (N-2)nd position 66 | binary_index="$(($# - 2))" 67 | binary="${!binary_index}" 68 | 69 | # For completions to be universal, we may have setup the compspec to 70 | # trigger on 'harmless pass-through' commands, like 'time' or 'env'. 71 | # If the command being completed is one of those two, we'll need to 72 | # identify the actual command being executed. To do this, we need 73 | # the actual command line that the was pressed on. Bash helpfully 74 | # places this in the $COMP_LINE variable. 75 | if [ "$binary" == "time" ] || [ "$binary" == "env" ]; then 76 | # we'll assume that the first 'argument' is actually the 77 | # binary 78 | 79 | 80 | # TODO(user): This is not perfect - the 'env' command, for instance, 81 | # is allowed to have options between the 'env' and 'the command to 82 | # be executed'. For example, consider: 83 | # $ env FOO="bar" bin/do_something --help 84 | # In this case, we'll mistake the FOO="bar" portion as the binary. 85 | # Perhaps we should continuing consuming leading words until we 86 | # either run out of words, or find a word that is a valid file 87 | # marked as executable. I can't think of any reason this wouldn't 88 | # work. 89 | 90 | # Break up the 'original command line' (not this script's command line, 91 | # rather the one the was pressed on) and find the second word. 92 | parts=( ${COMP_LINE} ) 93 | binary=${parts[1]} 94 | fi 95 | 96 | # Build the command line to use for completion. Basically it involves 97 | # passing through all the arguments given to this script (except the 3 98 | # that bash added), and appending a '--tab_completion_word "WORD"' to 99 | # the arguments. 100 | params="" 101 | for ((i=1; i<=$(($# - 3)); ++i)); do 102 | params="$params \"${!i}\""; 103 | done 104 | params="$params --tab_completion_word \"$completion_word\"" 105 | 106 | # TODO(user): Perhaps stash the output in a temporary file somewhere 107 | # in /tmp, and only cat it to stdout if the command returned a success 108 | # code, to prevent false positives 109 | 110 | # If we think we have a reasonable command to execute, then execute it 111 | # and hope for the best. 112 | candidate=$(type -p "$binary") 113 | if [ ! -z "$candidate" ]; then 114 | eval "$candidate 2>/dev/null $params" 115 | elif [ -f "$binary" ] && [ -x "$binary" ]; then 116 | eval "$binary 2>/dev/null $params" 117 | fi 118 | -------------------------------------------------------------------------------- /vendor/gflags/src/windows_port.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2009, Google Inc. 2 | * All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are 6 | * met: 7 | * 8 | * * Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * * Redistributions in binary form must reproduce the above 11 | * copyright notice, this list of conditions and the following disclaimer 12 | * in the documentation and/or other materials provided with the 13 | * distribution. 14 | * * Neither the name of Google Inc. nor the names of its 15 | * contributors may be used to endorse or promote products derived from 16 | * this software without specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * --- 31 | * Author: Craig Silverstein 32 | * 33 | * These are some portability typedefs and defines to make it a bit 34 | * easier to compile this code under VC++. 35 | * 36 | * Several of these are taken from glib: 37 | * http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html 38 | */ 39 | 40 | #ifndef GFLAGS_WINDOWS_PORT_H_ 41 | #define GFLAGS_WINDOWS_PORT_H_ 42 | 43 | #include "config.h" 44 | 45 | // This must be defined before the windows.h is included. 46 | // It's needed for mutex.h, to give access to the TryLock method. 47 | # if !defined(_WIN32_WINNT) && !(defined( __MINGW32__) || defined(__MINGW64__)) 48 | # define _WIN32_WINNT 0x0400 49 | # endif 50 | // We always want minimal includes 51 | #ifndef WIN32_LEAN_AND_MEAN 52 | # define WIN32_LEAN_AND_MEAN 53 | #endif 54 | #include 55 | #include /* for mkdir */ 56 | #include /* for _putenv, getenv */ 57 | #include /* need this to override stdio's snprintf, also defines _unlink used by unit tests */ 58 | #include /* util.h uses va_copy */ 59 | #include /* for _stricmp and _strdup */ 60 | 61 | /* We can't just use _vsnprintf and _snprintf as drop-in-replacements, 62 | * because they don't always NUL-terminate. :-( We also can't use the 63 | * name vsnprintf, since windows defines that (but not snprintf (!)). 64 | */ 65 | #if !defined(__MINGW32__) && !defined(__MINGW64__) /* mingw already defines */ 66 | #if !(defined(_MSC_VER) && _MSC_VER >= 1900) /* msvc 2015 already defines */ 67 | extern GFLAGS_DLL_DECL int snprintf(char *str, size_t size, 68 | const char *format, ...); 69 | extern int GFLAGS_DLL_DECL safe_vsnprintf(char *str, size_t size, 70 | const char *format, va_list ap); 71 | #define vsnprintf(str, size, format, ap) safe_vsnprintf(str, size, format, ap) 72 | #define va_copy(dst, src) (dst) = (src) 73 | #endif 74 | #endif /* #if !defined(__MINGW32__) && !defined(__MINGW64__) */ 75 | 76 | #ifdef _MSC_VER 77 | # pragma warning(push) 78 | # pragma warning(disable: 4996) // ignore getenv security warning 79 | #endif 80 | inline void setenv(const char* name, const char* value, int) { 81 | // In windows, it's impossible to set a variable to the empty string. 82 | // We handle this by setting it to "0" and the NUL-ing out the \0. 83 | // That is, we putenv("FOO=0") and then find out where in memory the 84 | // putenv wrote "FOO=0", and change it in-place to "FOO=\0". 85 | // c.f. http://svn.apache.org/viewvc/stdcxx/trunk/tests/src/environ.cpp?r1=611451&r2=637508&pathrev=637508 86 | static const char* const kFakeZero = "0"; 87 | if (*value == '\0') 88 | value = kFakeZero; 89 | // Apparently the semantics of putenv() is that the input 90 | // must live forever, so we leak memory here. :-( 91 | const size_t nameval_len = strlen(name) + 1 + strlen(value) + 1; 92 | char* nameval = reinterpret_cast(malloc(nameval_len)); 93 | snprintf(nameval, nameval_len, "%s=%s", name, value); 94 | _putenv(nameval); 95 | if (value == kFakeZero) { 96 | nameval[nameval_len - 2] = '\0'; // works when putenv() makes no copy 97 | if (*getenv(name) != '\0') 98 | *getenv(name) = '\0'; // works when putenv() copies nameval 99 | } 100 | } 101 | #ifdef _MSC_VER 102 | # pragma warning(pop) 103 | #endif 104 | 105 | #define strcasecmp _stricmp 106 | 107 | #if defined(_MSC_VER) && _MSC_VER >= 1400 108 | #define strdup _strdup 109 | #define unlink _unlink 110 | #endif 111 | 112 | #define PRId32 "d" 113 | #define PRIu32 "u" 114 | #define PRId64 "I64d" 115 | #define PRIu64 "I64u" 116 | 117 | #if !defined(__MINGW32__) && !defined(__MINGW64__) 118 | #define strtoq _strtoi64 119 | #define strtouq _strtoui64 120 | #define strtoll _strtoi64 121 | #define strtoull _strtoui64 122 | #define atoll _atoi64 123 | #endif 124 | 125 | #ifndef PATH_MAX 126 | #define PATH_MAX 1024 127 | #endif 128 | 129 | #endif /* GFLAGS_WINDOWS_PORT_H_ */ 130 | -------------------------------------------------------------------------------- /vendor/gflags/src/gflags_declare.h.in: -------------------------------------------------------------------------------- 1 | // Copyright (c) 1999, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | // --- 31 | // 32 | // Revamped and reorganized by Craig Silverstein 33 | // 34 | // This is the file that should be included by any file which declares 35 | // command line flag. 36 | 37 | #ifndef GFLAGS_DECLARE_H_ 38 | #define GFLAGS_DECLARE_H_ 39 | 40 | 41 | // --------------------------------------------------------------------------- 42 | // Namespace of gflags library symbols. 43 | #define GFLAGS_NAMESPACE @GFLAGS_NAMESPACE@ 44 | 45 | // --------------------------------------------------------------------------- 46 | // Windows DLL import/export. 47 | 48 | // Whether gflags library is a DLL. 49 | // 50 | // Set to 1 by default when the shared gflags library was built on Windows. 51 | // Must be overwritten when this header file is used with the optionally also 52 | // built static library instead; set by CMake's INTERFACE_COMPILE_DEFINITIONS. 53 | #ifndef GFLAGS_IS_A_DLL 54 | # define GFLAGS_IS_A_DLL @GFLAGS_IS_A_DLL@ 55 | #endif 56 | 57 | // We always want to import the symbols of the gflags library. 58 | #ifndef GFLAGS_DLL_DECL 59 | # if GFLAGS_IS_A_DLL && defined(_MSC_VER) 60 | # define GFLAGS_DLL_DECL __declspec(dllimport) 61 | # else 62 | # define GFLAGS_DLL_DECL 63 | # endif 64 | #endif 65 | 66 | // We always want to import variables declared in user code. 67 | #ifndef GFLAGS_DLL_DECLARE_FLAG 68 | # if GFLAGS_IS_A_DLL && defined(_MSC_VER) 69 | # define GFLAGS_DLL_DECLARE_FLAG __declspec(dllimport) 70 | # else 71 | # define GFLAGS_DLL_DECLARE_FLAG 72 | # endif 73 | #endif 74 | 75 | // --------------------------------------------------------------------------- 76 | // Flag types 77 | #include 78 | #if @HAVE_STDINT_H@ 79 | # include // the normal place uint32_t is defined 80 | #elif @HAVE_SYS_TYPES_H@ 81 | # include // the normal place u_int32_t is defined 82 | #elif @HAVE_INTTYPES_H@ 83 | # include // a third place for uint32_t or u_int32_t 84 | #endif 85 | 86 | namespace GFLAGS_NAMESPACE { 87 | 88 | #if @GFLAGS_INTTYPES_FORMAT_C99@ // C99 89 | typedef int32_t int32; 90 | typedef uint32_t uint32; 91 | typedef int64_t int64; 92 | typedef uint64_t uint64; 93 | #elif @GFLAGS_INTTYPES_FORMAT_BSD@ // BSD 94 | typedef int32_t int32; 95 | typedef u_int32_t uint32; 96 | typedef int64_t int64; 97 | typedef u_int64_t uint64; 98 | #elif @GFLAGS_INTTYPES_FORMAT_VC7@ // Windows 99 | typedef __int32 int32; 100 | typedef unsigned __int32 uint32; 101 | typedef __int64 int64; 102 | typedef unsigned __int64 uint64; 103 | #else 104 | # error Do not know how to define a 32-bit integer quantity on your system 105 | #endif 106 | 107 | } // namespace GFLAGS_NAMESPACE 108 | 109 | 110 | namespace fLS { 111 | 112 | // The meaning of "string" might be different between now and when the 113 | // macros below get invoked (e.g., if someone is experimenting with 114 | // other string implementations that get defined after this file is 115 | // included). Save the current meaning now and use it in the macros. 116 | typedef std::string clstring; 117 | 118 | } // namespace fLS 119 | 120 | 121 | #define DECLARE_VARIABLE(type, shorttype, name) \ 122 | /* We always want to import declared variables, dll or no */ \ 123 | namespace fL##shorttype { extern GFLAGS_DLL_DECLARE_FLAG type FLAGS_##name; } \ 124 | using fL##shorttype::FLAGS_##name 125 | 126 | #define DECLARE_bool(name) \ 127 | DECLARE_VARIABLE(bool, B, name) 128 | 129 | #define DECLARE_int32(name) \ 130 | DECLARE_VARIABLE(::GFLAGS_NAMESPACE::int32, I, name) 131 | 132 | #define DECLARE_uint32(name) \ 133 | DECLARE_VARIABLE(::GFLAGS_NAMESPACE::uint32, U, name) 134 | 135 | #define DECLARE_int64(name) \ 136 | DECLARE_VARIABLE(::GFLAGS_NAMESPACE::int64, I64, name) 137 | 138 | #define DECLARE_uint64(name) \ 139 | DECLARE_VARIABLE(::GFLAGS_NAMESPACE::uint64, U64, name) 140 | 141 | #define DECLARE_double(name) \ 142 | DECLARE_VARIABLE(double, D, name) 143 | 144 | #define DECLARE_string(name) \ 145 | /* We always want to import declared variables, dll or no */ \ 146 | namespace fLS { \ 147 | using ::fLS::clstring; \ 148 | extern GFLAGS_DLL_DECLARE_FLAG ::fLS::clstring& FLAGS_##name; \ 149 | } \ 150 | using fLS::FLAGS_##name 151 | 152 | 153 | #endif // GFLAGS_DECLARE_H_ 154 | -------------------------------------------------------------------------------- /vendor/gflags/src/gflags_completions.h.in: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2008, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // --- 31 | 32 | // 33 | // Implement helpful bash-style command line flag completions 34 | // 35 | // ** Functional API: 36 | // HandleCommandLineCompletions() should be called early during 37 | // program startup, but after command line flag code has been 38 | // initialized, such as the beginning of HandleCommandLineHelpFlags(). 39 | // It checks the value of the flag --tab_completion_word. If this 40 | // flag is empty, nothing happens here. If it contains a string, 41 | // however, then HandleCommandLineCompletions() will hijack the 42 | // process, attempting to identify the intention behind this 43 | // completion. Regardless of the outcome of this deduction, the 44 | // process will be terminated, similar to --helpshort flag 45 | // handling. 46 | // 47 | // ** Overview of Bash completions: 48 | // Bash can be told to programatically determine completions for the 49 | // current 'cursor word'. It does this by (in this case) invoking a 50 | // command with some additional arguments identifying the command 51 | // being executed, the word being completed, and the previous word 52 | // (if any). Bash then expects a sequence of output lines to be 53 | // printed to stdout. If these lines all contain a common prefix 54 | // longer than the cursor word, bash will replace the cursor word 55 | // with that common prefix, and display nothing. If there isn't such 56 | // a common prefix, bash will display the lines in pages using 'more'. 57 | // 58 | // ** Strategy taken for command line completions: 59 | // If we can deduce either the exact flag intended, or a common flag 60 | // prefix, we'll output exactly that. Otherwise, if information 61 | // must be displayed to the user, we'll take the opportunity to add 62 | // some helpful information beyond just the flag name (specifically, 63 | // we'll include the default flag value and as much of the flag's 64 | // description as can fit on a single terminal line width, as specified 65 | // by the flag --tab_completion_columns). Furthermore, we'll try to 66 | // make bash order the output such that the most useful or relevent 67 | // flags are the most likely to be shown at the top. 68 | // 69 | // ** Additional features: 70 | // To assist in finding that one really useful flag, substring matching 71 | // was implemented. Before pressing a to get completion for the 72 | // current word, you can append one or more '?' to the flag to do 73 | // substring matching. Here's the semantics: 74 | // --foo Show me all flags with names prefixed by 'foo' 75 | // --foo? Show me all flags with 'foo' somewhere in the name 76 | // --foo?? Same as prior case, but also search in module 77 | // definition path for 'foo' 78 | // --foo??? Same as prior case, but also search in flag 79 | // descriptions for 'foo' 80 | // Finally, we'll trim the output to a relatively small number of 81 | // flags to keep bash quiet about the verbosity of output. If one 82 | // really wanted to see all possible matches, appending a '+' to the 83 | // search word will force the exhaustive list of matches to be printed. 84 | // 85 | // ** How to have bash accept completions from a binary: 86 | // Bash requires that it be informed about each command that programmatic 87 | // completion should be enabled for. Example addition to a .bashrc 88 | // file would be (your path to gflags_completions.sh file may differ): 89 | 90 | /* 91 | $ complete -o bashdefault -o default -o nospace -C \ 92 | '/home/build/eng/bash/bash_completions.sh --tab_completion_columns $COLUMNS' \ 93 | time env binary_name another_binary [...] 94 | */ 95 | 96 | // This would allow the following to work: 97 | // $ /path/to/binary_name --vmodule 98 | // Or: 99 | // $ ./bin/path/another_binary --gfs_u 100 | // (etc) 101 | // 102 | // Sadly, it appears that bash gives no easy way to force this behavior for 103 | // all commands. That's where the "time" in the above example comes in. 104 | // If you haven't specifically added a command to the list of completion 105 | // supported commands, you can still get completions by prefixing the 106 | // entire command with "env". 107 | // $ env /some/brand/new/binary --vmod 108 | // Assuming that "binary" is a newly compiled binary, this should still 109 | // produce the expected completion output. 110 | 111 | 112 | #ifndef GFLAGS_COMPLETIONS_H_ 113 | #define GFLAGS_COMPLETIONS_H_ 114 | 115 | namespace @GFLAGS_NAMESPACE@ { 116 | 117 | extern void HandleCommandLineCompletions(void); 118 | 119 | } 120 | 121 | #endif // GFLAGS_COMPLETIONS_H_ 122 | -------------------------------------------------------------------------------- /includes/RangeUtils.h: -------------------------------------------------------------------------------- 1 | #ifndef _RANGE_UTILS_H_INCLUDED_ 2 | #define _RANGE_UTILS_H_INCLUDED_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | namespace utils { 14 | static unsigned long x=123456789, y=362436069, z=521288629; 15 | 16 | unsigned long xorshf96(void) { //period 2^96-1 17 | // return std::rand() / RAND_MAX; 18 | unsigned long t; 19 | x ^= x << 16; 20 | x ^= x >> 5; 21 | x ^= x << 1; 22 | 23 | t = x; 24 | x = y; 25 | y = z; 26 | z = t ^ x ^ y; 27 | 28 | return z; 29 | } 30 | float rgb2gray(float r, float g, float b) { 31 | return 0.229 * r + 0.587 * g + 0.114 * b; 32 | } 33 | int randrange(int min, int max) { 34 | return min + (rand() % (int)(max - min + 1)); 35 | } 36 | std::vector > outline(int x, int y, bool use_corners) { 37 | std::vector > corners; 38 | 39 | corners.push_back(std::make_pair(x+1,y)); 40 | corners.push_back(std::make_pair(x-1,y)); 41 | corners.push_back(std::make_pair(x,y+1)); 42 | corners.push_back(std::make_pair(x,y-1)); 43 | 44 | if (use_corners) { 45 | corners.push_back(std::make_pair(x+1,y+1)); 46 | corners.push_back(std::make_pair(x-1,y+1)); 47 | corners.push_back(std::make_pair(x+1,y-1)); 48 | corners.push_back(std::make_pair(x-1,y-1)); 49 | } 50 | 51 | return corners; 52 | } 53 | template 54 | class KeyMaker 55 | { 56 | public: 57 | KeyMaker() {} 58 | KeyMaker(int width, int height, int theta_discretization) { 59 | y_shift = (int) std::ceil(std::log2(theta_discretization)); 60 | x_shift = (int) std::ceil(std::log2(height)) + y_shift; 61 | int bitness = (int) std::ceil(std::log2(width)) + x_shift; 62 | 63 | if (bitness > std::log2(std::numeric_limits::max())) { 64 | std::cerr << "Key bitness too large for integer packing scheme. Check your KeyMaker template type." << std::endl; 65 | } 66 | 67 | // make bit masks for unpacking the various values 68 | t_mask = std::pow(2, y_shift)-1; 69 | y_mask = std::pow(2, x_shift)-1 - t_mask; 70 | x_mask = std::pow(2, bitness)-1 - y_mask - t_mask; 71 | }; 72 | ~KeyMaker() {}; 73 | key_T make_key(int x, int y, int t) { 74 | return ((key_T)x << x_shift) + ((key_T)y << y_shift) + (key_T)t; 75 | } 76 | std::tuple unpack_key(key_T k) { 77 | return std::make_tuple((int)((k & x_mask) >> x_shift), (int)((k & y_mask) >> y_shift), k & t_mask); 78 | } 79 | private: 80 | int y_shift; 81 | int x_shift; 82 | key_T x_mask; 83 | key_T y_mask; 84 | key_T t_mask; 85 | }; 86 | 87 | bool has(std::string substring, std::string str) { 88 | return str.find(substring) != std::string::npos; 89 | } 90 | 91 | bool has(std::string val, std::vector vstr) { 92 | return std::find(vstr.begin(), vstr.end(),val)!=vstr.end(); 93 | } 94 | 95 | std::vector split(std::string in, char delim) { 96 | std::vector result; 97 | std::stringstream ss(in); 98 | while( ss.good() ) 99 | { 100 | std::string substr; 101 | std::getline( ss, substr, delim ); 102 | result.push_back( substr ); 103 | } 104 | return result; 105 | } 106 | 107 | double norminv(double q) { 108 | if(q == .5) 109 | return 0; 110 | 111 | q = 1.0 - q; 112 | 113 | double p = (q > 0.0 && q < 0.5) ? q : (1.0 - q); 114 | double t = sqrt(log(1.0 / pow(p, 2.0))); 115 | 116 | double c0 = 2.515517; 117 | double c1 = 0.802853; 118 | double c2 = 0.010328; 119 | 120 | double d1 = 1.432788; 121 | double d2 = 0.189269; 122 | double d3 = 0.001308; 123 | 124 | double x = t - (c0 + c1 * t + c2 * pow(t, 2.0)) / 125 | (1.0 + d1 * t + d2 * pow(t, 2.0) + d3 * pow(t, 3.0)); 126 | 127 | if(q > .5) 128 | x *= -1.0; 129 | 130 | return x; 131 | } 132 | 133 | template 134 | struct is_same 135 | { 136 | static const bool value = false; 137 | }; 138 | 139 | template 140 | struct is_same 141 | { 142 | static const bool value = true; 143 | }; 144 | 145 | template 146 | bool eqTypes() { return is_same::value; } 147 | 148 | // http://stackoverflow.com/questions/311703/algorithm-for-sampling-without-replacement 149 | // Here's some code for sampling without replacement based on Algorithm 3.4.2S of Knuth's book Seminumeric Algorithms. 150 | class NonReplacementSampler 151 | { 152 | public: 153 | NonReplacementSampler() { 154 | rand = std::uniform_real_distribution(0.0,1.0); 155 | generator.seed(clock()); 156 | } 157 | ~NonReplacementSampler() {} 158 | 159 | void sample(int populationSize, int sampleSize, std::vector & samples) { 160 | int t = 0; // total input records dealt with 161 | int m = 0; // number of items selected so far 162 | double u; 163 | 164 | while (m < sampleSize) { 165 | // u = rand(generator); 166 | u = std::rand() / (float)RAND_MAX; 167 | if ((populationSize-t)*u >= sampleSize - m) t++; 168 | else { 169 | samples.push_back(t); 170 | t++; m++; 171 | } 172 | } 173 | // samples.push_back(1); 174 | } 175 | 176 | std::uniform_real_distribution rand; 177 | std::default_random_engine generator; 178 | }; 179 | 180 | class FastRand 181 | { 182 | public: 183 | FastRand() : FastRand(10000) {}; 184 | FastRand(int n) : cache_size(n) { 185 | populate(); 186 | repopulate_threshold = 1.0 / cache_size; 187 | } 188 | ~FastRand(){}; 189 | 190 | float rand() { 191 | // return std::rand() / (float)RAND_MAX; 192 | // float v = cache[i]; 193 | if (i++>cache_size-1) i = 0; 194 | // if (v < repopulate_threshold) populate(); 195 | return cache[i]; 196 | } 197 | 198 | void populate() { 199 | // cache.empty(); 200 | // for (int i = 0; i < cache_size; ++i) cache.push_back(std::rand() / (float)RAND_MAX); 201 | for (int i = 0; i < cache_size; ++i) cache[i] = std::rand() / (float)RAND_MAX; 202 | } 203 | int i = 0; 204 | int cache_size; 205 | float repopulate_threshold; 206 | // std::vector cache; 207 | float cache[10000]; 208 | }; 209 | 210 | void serialize(std::vector &vals,std::stringstream* ss) { 211 | if (vals.size() == 0) { 212 | (*ss) << "[]"; 213 | return; 214 | } 215 | (*ss) << "[" << vals[0]; 216 | for (int i = 1; i < vals.size(); ++i) { 217 | (*ss) << "," << vals[i]; 218 | } 219 | (*ss) << "]"; 220 | } 221 | 222 | void serialize(std::vector &vals,std::stringstream* ss) { 223 | if (vals.size() == 0) { 224 | (*ss) << "[]"; 225 | return; 226 | } 227 | (*ss) << "[" << vals[0]; 228 | for (int i = 1; i < vals.size(); ++i) { 229 | (*ss) << "," << vals[i]; 230 | } 231 | (*ss) << "]"; 232 | } 233 | 234 | std::string serialize(std::vector &vals) { 235 | std::stringstream ss; 236 | serialize(vals,&ss); 237 | return ss.str(); 238 | } 239 | 240 | } // namespace utils 241 | 242 | #endif /* _RANGE_UTILS_H_INCLUDED_ */ 243 | -------------------------------------------------------------------------------- /vendor/gflags/cmake/config.cmake.in: -------------------------------------------------------------------------------- 1 | ## gflags CMake configuration file 2 | 3 | # library version information 4 | set (@PACKAGE_PREFIX@_VERSION_STRING "@PACKAGE_VERSION@") 5 | set (@PACKAGE_PREFIX@_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@) 6 | set (@PACKAGE_PREFIX@_VERSION_MINOR @PACKAGE_VERSION_MINOR@) 7 | set (@PACKAGE_PREFIX@_VERSION_PATCH @PACKAGE_VERSION_PATCH@) 8 | 9 | # import targets 10 | include ("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_NAME@.cmake") 11 | 12 | # installation prefix 13 | get_filename_component (CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) 14 | get_filename_component (_INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/@INSTALL_PREFIX_REL2CONFIG_DIR@" ABSOLUTE) 15 | 16 | # include directory 17 | # 18 | # Newer versions of CMake set the INTERFACE_INCLUDE_DIRECTORIES property 19 | # of the imported targets. It is hence not necessary to add this path 20 | # manually to the include search path for targets which link to gflags. 21 | set (@PACKAGE_PREFIX@_INCLUDE_DIR "${_INSTALL_PREFIX}/@INCLUDE_INSTALL_DIR@") 22 | 23 | if (@PACKAGE_NAME@_FIND_COMPONENTS) 24 | foreach (@PACKAGE_NAME@_FIND_COMPONENT IN LISTS @PACKAGE_NAME@_FIND_COMPONENTS) 25 | if (@PACKAGE_NAME@_FIND_REQUIRED_${@PACKAGE_NAME@_FIND_COMPONENT} AND NOT TARGET @PACKAGE_NAME@_${@PACKAGE_NAME@_FIND_COMPONENT}) 26 | message (FATAL_ERROR "Package @PACKAGE_NAME@ was installed without required component ${@PACKAGE_NAME@_FIND_COMPONENT}!") 27 | endif () 28 | endforeach () 29 | list (GET @PACKAGE_NAME@_FIND_COMPONENTS 0 @PACKAGE_NAME@_FIND_COMPONENT) 30 | else () 31 | set (@PACKAGE_NAME@_FIND_COMPONENT) 32 | endif () 33 | 34 | # default settings of @PACKAGE_PREFIX@_SHARED and @PACKAGE_PREFIX@_NOTHREADS 35 | # 36 | # It is recommended to use either one of the following find_package commands 37 | # instead of setting the @PACKAGE_PREFIX@_(SHARED|NOTHREADS) variables: 38 | # - find_package(@PACKAGE_NAME@ REQUIRED) 39 | # - find_package(@PACKAGE_NAME@ COMPONENTS nothreads_static) 40 | # - find_package(@PACKAGE_NAME@ COMPONENTS nothreads_shared) 41 | # - find_package(@PACKAGE_NAME@ COMPONENTS static) 42 | # - find_package(@PACKAGE_NAME@ COMPONENTS shared) 43 | if (NOT DEFINED @PACKAGE_PREFIX@_SHARED) 44 | if (DEFINED @PACKAGE_NAME@_SHARED) 45 | set (@PACKAGE_PREFIX@_SHARED ${@PACKAGE_NAME@_SHARED}) 46 | elseif (@PACKAGE_NAME@_FIND_COMPONENT) 47 | if (@PACKAGE_NAME@_FIND_COMPONENT MATCHES "shared") 48 | set (@PACKAGE_PREFIX@_SHARED TRUE) 49 | else () 50 | set (@PACKAGE_PREFIX@_SHARED FALSE) 51 | endif () 52 | elseif (TARGET @PACKAGE_NAME@_shared OR TARGET @PACKAGE_NAME@_nothreads_shared) 53 | set (@PACKAGE_PREFIX@_SHARED TRUE) 54 | else () 55 | set (@PACKAGE_PREFIX@_SHARED FALSE) 56 | endif () 57 | endif () 58 | if (NOT DEFINED @PACKAGE_PREFIX@_NOTHREADS) 59 | if (DEFINED @PACKAGE_NAME@_NOTHREADS) 60 | set (@PACKAGE_PREFIX@_NOTHREADS ${@PACKAGE_NAME@_NOTHREADS}) 61 | elseif (@PACKAGE_NAME@_FIND_COMPONENT) 62 | if (@PACKAGE_NAME@_FIND_COMPONENT MATCHES "nothreads") 63 | set (@PACKAGE_PREFIX@_NOTHREADS TRUE) 64 | else () 65 | set (@PACKAGE_PREFIX@_NOTHREADS FALSE) 66 | endif () 67 | elseif (TARGET @PACKAGE_NAME@_static OR TARGET @PACKAGE_NAME@_shared) 68 | set (@PACKAGE_PREFIX@_NOTHREADS FALSE) 69 | else () 70 | set (@PACKAGE_PREFIX@_NOTHREADS TRUE) 71 | endif () 72 | endif () 73 | 74 | # choose imported library target 75 | if (NOT @PACKAGE_PREFIX@_TARGET) 76 | if (@PACKAGE_NAME@_TARGET) 77 | set (@PACKAGE_PREFIX@_TARGET ${@PACKAGE_NAME@_TARGET}) 78 | elseif (@PACKAGE_PREFIX@_SHARED) 79 | if (@PACKAGE_PREFIX@_NOTHREADS) 80 | set (@PACKAGE_PREFIX@_TARGET @PACKAGE_NAME@_nothreads_shared) 81 | else () 82 | set (@PACKAGE_PREFIX@_TARGET @PACKAGE_NAME@_shared) 83 | endif () 84 | else () 85 | if (@PACKAGE_PREFIX@_NOTHREADS) 86 | set (@PACKAGE_PREFIX@_TARGET @PACKAGE_NAME@_nothreads_static) 87 | else () 88 | set (@PACKAGE_PREFIX@_TARGET @PACKAGE_NAME@_static) 89 | endif () 90 | endif () 91 | endif () 92 | if (NOT TARGET ${@PACKAGE_PREFIX@_TARGET}) 93 | message (FATAL_ERROR "Your @PACKAGE_NAME@ installation does not contain a ${@PACKAGE_PREFIX@_TARGET} library target!" 94 | " Try a different combination of @PACKAGE_PREFIX@_SHARED and @PACKAGE_PREFIX@_NOTHREADS.") 95 | endif () 96 | 97 | # add more convenient "@PACKAGE_NAME@" import target 98 | if (NOT TARGET @PACKAGE_NAME@) 99 | if (@PACKAGE_PREFIX@_SHARED) 100 | add_library (@PACKAGE_NAME@ SHARED IMPORTED) 101 | else () 102 | add_library (@PACKAGE_NAME@ STATIC IMPORTED) 103 | endif () 104 | # copy INTERFACE_* properties 105 | foreach (_@PACKAGE_PREFIX@_PROPERTY_NAME IN ITEMS 106 | COMPILE_DEFINITIONS 107 | COMPILE_FEATURES 108 | COMPILE_OPTIONS 109 | INCLUDE_DIRECTORIES 110 | LINK_LIBRARIES 111 | POSITION_INDEPENDENT_CODE 112 | ) 113 | get_target_property (_@PACKAGE_PREFIX@_PROPERTY_VALUE ${@PACKAGE_PREFIX@_TARGET} INTERFACE_${_@PACKAGE_PREFIX@_PROPERTY_NAME}) 114 | if (_@PACKAGE_PREFIX@_PROPERTY_VALUE) 115 | set_target_properties(@PACKAGE_NAME@ PROPERTIES 116 | INTERFACE_${_@PACKAGE_PREFIX@_PROPERTY_NAME} "${_@PACKAGE_PREFIX@_PROPERTY_VALUE}" 117 | ) 118 | endif () 119 | endforeach () 120 | # copy IMPORTED_*_ properties 121 | get_target_property (_@PACKAGE_PREFIX@_CONFIGURATIONS ${@PACKAGE_PREFIX@_TARGET} IMPORTED_CONFIGURATIONS) 122 | set_target_properties (@PACKAGE_NAME@ PROPERTIES IMPORTED_CONFIGURATIONS "${_@PACKAGE_PREFIX@_CONFIGURATIONS}") 123 | foreach (_@PACKAGE_PREFIX@_PROPERTY_NAME IN ITEMS 124 | IMPLIB 125 | LOCATION 126 | LINK_DEPENDENT_LIBRARIES 127 | LINK_INTERFACE_LIBRARIES 128 | LINK_INTERFACE_LANGUAGES 129 | LINK_INTERFACE_MULTIPLICITY 130 | NO_SONAME 131 | SONAME 132 | ) 133 | foreach (_@PACKAGE_PREFIX@_CONFIG IN LISTS _@PACKAGE_PREFIX@_CONFIGURATIONS) 134 | get_target_property (_@PACKAGE_PREFIX@_PROPERTY_VALUE ${@PACKAGE_PREFIX@_TARGET} IMPORTED_${_@PACKAGE_PREFIX@_PROPERTY_NAME}_${_@PACKAGE_PREFIX@_CONFIG}) 135 | if (_@PACKAGE_PREFIX@_PROPERTY_VALUE) 136 | set_target_properties(@PACKAGE_NAME@ PROPERTIES 137 | IMPORTED_${_@PACKAGE_PREFIX@_PROPERTY_NAME}_${_@PACKAGE_PREFIX@_CONFIG} "${_@PACKAGE_PREFIX@_PROPERTY_VALUE}" 138 | ) 139 | endif () 140 | endforeach () 141 | endforeach () 142 | unset (_@PACKAGE_PREFIX@_CONFIGURATIONS) 143 | unset (_@PACKAGE_PREFIX@_CONFIG) 144 | unset (_@PACKAGE_PREFIX@_PROPERTY_NAME) 145 | unset (_@PACKAGE_PREFIX@_PROPERTY_VALUE) 146 | endif () 147 | 148 | # alias for default import target to be compatible with older CMake package configurations 149 | set (@PACKAGE_PREFIX@_LIBRARIES "${@PACKAGE_PREFIX@_TARGET}") 150 | 151 | # set @PACKAGE_NAME@_* variables for backwards compatibility 152 | if (NOT "^@PACKAGE_NAME@$" STREQUAL "^@PACKAGE_PREFIX@$") 153 | foreach (_@PACKAGE_PREFIX@_VARIABLE IN ITEMS 154 | VERSION_STRING 155 | VERSION_MAJOR 156 | VERSION_MINOR 157 | VERSION_PATCH 158 | INCLUDE_DIR 159 | LIBRARIES 160 | TARGET 161 | ) 162 | set (@PACKAGE_NAME@_${_@PACKAGE_PREFIX@_VARIABLE} "${@PACKAGE_PREFIX@_${_@PACKAGE_PREFIX@_VARIABLE}}") 163 | endforeach () 164 | unset (_@PACKAGE_PREFIX@_VARIABLE) 165 | endif () 166 | 167 | # unset private variables 168 | unset (@PACKAGE_NAME@_FIND_COMPONENT) 169 | unset (_INSTALL_PREFIX) 170 | -------------------------------------------------------------------------------- /pywrapper/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | from distutils.extension import Extension 3 | from Cython.Distutils import build_ext 4 | import numpy, os, platform, sys 5 | from os.path import join as pjoin 6 | 7 | 8 | # Obtain the numpy include directory. This logic works across numpy versions. 9 | try: 10 | numpy_include = numpy.get_include() 11 | except AttributeError: 12 | numpy_include = numpy.get_numpy_include() 13 | 14 | def check_for_flag(flag_str, truemsg=False, falsemsg=False): 15 | if flag_str in os.environ: 16 | enabled = (os.environ[flag_str].lower() == "on") 17 | else: 18 | enabled = False 19 | 20 | if enabled and not truemsg == False: 21 | print truemsg 22 | elif not enabled and not falsemsg == False: 23 | print falsemsg 24 | print " $ sudo "+flag_str+"=ON python setup.py install" 25 | return enabled 26 | 27 | use_cuda = check_for_flag("WITH_CUDA", \ 28 | "Compiling with CUDA support", \ 29 | "Compiling without CUDA support. To enable CUDA use:") 30 | trace = check_for_flag("TRACE", \ 31 | "Compiling with trace enabled for Bresenham's Line", \ 32 | "Compiling without trace enabled for Bresenham's Line") 33 | 34 | print 35 | print "--------------" 36 | print 37 | 38 | # support for compiling in clang 39 | if platform.system().lower() == "darwin": 40 | os.environ["MACOSX_DEPLOYMENT_TARGET"] = platform.mac_ver()[0] 41 | os.environ["CC"] = "c++" 42 | 43 | def find_in_path(name, path): 44 | "Find a file in a search path" 45 | #adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/ 46 | for dir in path.split(os.pathsep): 47 | binpath = pjoin(dir, name) 48 | if os.path.exists(binpath): 49 | return os.path.abspath(binpath) 50 | return None 51 | 52 | # export CUDAHOME=/usr/local/cuda 53 | def locate_cuda(): 54 | """Locate the CUDA environment on the system 55 | 56 | Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64' 57 | and values giving the absolute path to each directory. 58 | 59 | Starts by looking for the CUDAHOME env variable. If not found, everything 60 | is based on finding 'nvcc' in the PATH. 61 | """ 62 | # print os.environ 63 | # first check if the CUDAHOME env variable is in use 64 | if os.path.isdir("/usr/local/cuda-7.5"): 65 | home = "/usr/local/cuda-7.5" 66 | nvcc = pjoin(home, 'bin', 'nvcc') 67 | elif os.path.isdir("/usr/local/cuda"): 68 | home = "/usr/local/cuda" 69 | nvcc = pjoin(home, 'bin', 'nvcc') 70 | elif 'CUDAHOME' in os.environ: 71 | home = os.environ['CUDAHOME'] 72 | nvcc = pjoin(home, 'bin', 'nvcc') 73 | else: 74 | # otherwise, search the PATH for NVCC 75 | nvcc = find_in_path('nvcc', os.environ['PATH']) 76 | if nvcc is None: 77 | raise EnvironmentError('The nvcc binary could not be ' 78 | 'located in your $PATH. Either add it to your path, or set $CUDAHOME') 79 | home = os.path.dirname(os.path.dirname(nvcc)) 80 | 81 | cudaconfig = {'home':home, 'nvcc':nvcc, 82 | 'include': pjoin(home, 'include'), 83 | 'lib64': pjoin(home, 'lib64')} 84 | for k, v in cudaconfig.iteritems(): 85 | if not os.path.exists(v): 86 | raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v)) 87 | 88 | return cudaconfig 89 | 90 | 91 | ##################### Configuration ############################ 92 | 93 | 94 | # compiler_flags = ["-w","-std=c++11", "-march=native", "-ffast-math", "-fno-math-errno"] 95 | compiler_flags = ["-w","-std=c++11", "-march=native", "-ffast-math", "-fno-math-errno", "-O3"] 96 | nvcc_flags = ['-arch=sm_20', '--ptxas-options=-v', '-c', '--compiler-options', "'-fPIC'", "-w","-std=c++11"] 97 | include_dirs = ["../", numpy_include] 98 | depends = ["../includes/*.h"] 99 | sources = ["RangeLibc.pyx","../vendor/lodepng/lodepng.cpp"] 100 | 101 | CHUNK_SIZE = "262144" 102 | NUM_THREADS = "256" 103 | 104 | if use_cuda: 105 | compiler_flags.append("-DUSE_CUDA=1"); nvcc_flags.append("-DUSE_CUDA=1") 106 | compiler_flags.append("-DCHUNK_SIZE="+CHUNK_SIZE); nvcc_flags.append("-DCHUNK_SIZE="+CHUNK_SIZE) 107 | compiler_flags.append("-DNUM_THREADS="+NUM_THREADS); nvcc_flags.append("-DNUM_THREADS="+NUM_THREADS) 108 | 109 | CUDA = locate_cuda() 110 | include_dirs.append(CUDA['include']) 111 | sources.append("../includes/kernels.cu") 112 | 113 | if trace: 114 | compiler_flags.append("-D_MAKE_TRACE_MAP=1") 115 | 116 | 117 | ################################################################## 118 | 119 | def customize_compiler_for_nvcc(self): 120 | """inject deep into distutils to customize how the dispatch 121 | to gcc/nvcc works. 122 | 123 | If you subclass UnixCCompiler, it's not trivial to get your subclass 124 | injected in, and still have the right customizations (i.e. 125 | distutils.sysconfig.customize_compiler) run on it. So instead of going 126 | the OO route, I have this. Note, it's kindof like a wierd functional 127 | subclassing going on.""" 128 | 129 | # tell the compiler it can processes .cu 130 | self.src_extensions.append('.cu') 131 | 132 | # save references to the default compiler_so and _comple methods 133 | default_compiler_so = self.compiler_so 134 | super = self._compile 135 | 136 | # now redefine the _compile method. This gets executed for each 137 | # object but distutils doesn't have the ability to change compilers 138 | # based on source extension: we add it. 139 | def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): 140 | if os.path.splitext(src)[1] == '.cu': 141 | # use the cuda for .cu files 142 | self.set_executable('compiler_so', CUDA['nvcc']) 143 | # use only a subset of the extra_postargs, which are 1-1 translated 144 | # from the extra_compile_args in the Extension class 145 | postargs = extra_postargs['nvcc'] 146 | else: 147 | postargs = extra_postargs['gcc'] 148 | # postargs = extra_postargs#['gcc'] 149 | 150 | super(obj, src, ext, cc_args, postargs, pp_opts) 151 | # reset the default compiler_so, which we might have changed for cuda 152 | self.compiler_so = default_compiler_so 153 | 154 | # inject our redefined _compile method into the class 155 | self._compile = _compile 156 | 157 | # run the customize_compiler 158 | class custom_build_ext(build_ext): 159 | def build_extensions(self): 160 | customize_compiler_for_nvcc(self.compiler) 161 | build_ext.build_extensions(self) 162 | 163 | if use_cuda: 164 | ext = Extension("range_libc", sources, 165 | extra_compile_args = {'gcc': compiler_flags, 'nvcc': nvcc_flags}, 166 | extra_link_args = ["-std=c++11"], 167 | include_dirs = include_dirs, 168 | library_dirs=[CUDA['lib64']], 169 | libraries=['cudart'], 170 | runtime_library_dirs=[CUDA['lib64']], 171 | depends=depends, 172 | language="c++",) 173 | setup(name='range_libc', 174 | author='Corey Walsh', 175 | version='0.1', 176 | ext_modules = [ext], 177 | # inject our custom trigger 178 | cmdclass={'build_ext': custom_build_ext}) 179 | else: 180 | setup(ext_modules=[ 181 | Extension("range_libc", sources, 182 | extra_compile_args = compiler_flags, 183 | extra_link_args = ["-std=c++11"], 184 | include_dirs = include_dirs, 185 | depends=["../includes/*.h"], 186 | language="c++",)], 187 | name='range_libc', 188 | author='Corey Walsh', 189 | version='0.1', 190 | cmdclass = {'build_ext': build_ext}) 191 | -------------------------------------------------------------------------------- /vendor/gflags/cmake/utils.cmake: -------------------------------------------------------------------------------- 1 | ## Utility CMake functions. 2 | 3 | # ---------------------------------------------------------------------------- 4 | ## Convert boolean value to 0 or 1 5 | macro (bool_to_int VAR) 6 | if (${VAR}) 7 | set (${VAR} 1) 8 | else () 9 | set (${VAR} 0) 10 | endif () 11 | endmacro () 12 | 13 | # ---------------------------------------------------------------------------- 14 | ## Extract version numbers from version string 15 | function (version_numbers version major minor patch) 16 | if (version MATCHES "([0-9]+)(\\.[0-9]+)?(\\.[0-9]+)?(rc[1-9][0-9]*|[a-z]+)?") 17 | if (CMAKE_MATCH_1) 18 | set (_major ${CMAKE_MATCH_1}) 19 | else () 20 | set (_major 0) 21 | endif () 22 | if (CMAKE_MATCH_2) 23 | set (_minor ${CMAKE_MATCH_2}) 24 | string (REGEX REPLACE "^\\." "" _minor "${_minor}") 25 | else () 26 | set (_minor 0) 27 | endif () 28 | if (CMAKE_MATCH_3) 29 | set (_patch ${CMAKE_MATCH_3}) 30 | string (REGEX REPLACE "^\\." "" _patch "${_patch}") 31 | else () 32 | set (_patch 0) 33 | endif () 34 | else () 35 | set (_major 0) 36 | set (_minor 0) 37 | set (_patch 0) 38 | endif () 39 | set ("${major}" "${_major}" PARENT_SCOPE) 40 | set ("${minor}" "${_minor}" PARENT_SCOPE) 41 | set ("${patch}" "${_patch}" PARENT_SCOPE) 42 | endfunction () 43 | 44 | # ---------------------------------------------------------------------------- 45 | ## Determine if cache entry exists 46 | macro (gflags_is_cached retvar varname) 47 | if (DEFINED ${varname}) 48 | get_property (${retvar} CACHE ${varname} PROPERTY TYPE SET) 49 | else () 50 | set (${retvar} FALSE) 51 | endif () 52 | endmacro () 53 | 54 | # ---------------------------------------------------------------------------- 55 | ## Add gflags configuration variable 56 | # 57 | # The default value of the (cached) configuration value can be overridden either 58 | # on the CMake command-line or the super-project by setting the GFLAGS_ 59 | # variable. When gflags is a subproject of another project (GFLAGS_IS_SUBPROJECT), 60 | # the variable is not added to the CMake cache. Otherwise it is cached. 61 | macro (gflags_define type varname docstring default) 62 | if (ARGC GREATER 5) 63 | message (FATAL_ERROR "gflags_variable: Too many macro arguments") 64 | endif () 65 | if (NOT DEFINED GFLAGS_${varname}) 66 | if (GFLAGS_IS_SUBPROJECT AND ARGC EQUAL 5) 67 | set (GFLAGS_${varname} "${ARGV4}") 68 | else () 69 | set (GFLAGS_${varname} "${default}") 70 | endif () 71 | endif () 72 | if (GFLAGS_IS_SUBPROJECT) 73 | if (NOT DEFINED ${varname}) 74 | set (${varname} "${GFLAGS_${varname}}") 75 | endif () 76 | else () 77 | set (${varname} "${GFLAGS_${varname}}" CACHE ${type} "${docstring}") 78 | endif () 79 | endmacro () 80 | 81 | # ---------------------------------------------------------------------------- 82 | ## Set property of cached gflags configuration variable 83 | macro (gflags_property varname property value) 84 | gflags_is_cached (_cached ${varname}) 85 | if (_cached) 86 | if (property STREQUAL ADVANCED) 87 | if (${value}) 88 | mark_as_advanced (FORCE ${varname}) 89 | else () 90 | mark_as_advanced (CLEAR ${varname}) 91 | endif () 92 | else () 93 | set_property (CACHE ${varname} PROPERTY "${property}" "${value}") 94 | endif () 95 | endif () 96 | unset (_cached) 97 | endmacro () 98 | 99 | # ---------------------------------------------------------------------------- 100 | ## Modify value of gflags configuration variable 101 | macro (gflags_set varname value) 102 | gflags_is_cached (_cached ${varname}) 103 | if (_cached) 104 | set_property (CACHE ${varname} PROPERTY VALUE "${value}") 105 | else () 106 | set (${varname} "${value}") 107 | endif () 108 | unset (_cached) 109 | endmacro () 110 | 111 | # ---------------------------------------------------------------------------- 112 | ## Configure public header files 113 | function (configure_headers out) 114 | set (tmp) 115 | foreach (src IN LISTS ARGN) 116 | if (IS_ABSOLUTE "${src}") 117 | list (APPEND tmp "${src}") 118 | elseif (EXISTS "${PROJECT_SOURCE_DIR}/src/${src}.in") 119 | configure_file ("${PROJECT_SOURCE_DIR}/src/${src}.in" "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}" @ONLY) 120 | list (APPEND tmp "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}") 121 | else () 122 | configure_file ("${PROJECT_SOURCE_DIR}/src/${src}" "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}" COPYONLY) 123 | list (APPEND tmp "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}") 124 | endif () 125 | endforeach () 126 | set (${out} "${tmp}" PARENT_SCOPE) 127 | endfunction () 128 | 129 | # ---------------------------------------------------------------------------- 130 | ## Configure source files with .in suffix 131 | function (configure_sources out) 132 | set (tmp) 133 | foreach (src IN LISTS ARGN) 134 | if (src MATCHES ".h$" AND EXISTS "${PROJECT_SOURCE_DIR}/src/${src}.in") 135 | configure_file ("${PROJECT_SOURCE_DIR}/src/${src}.in" "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}" @ONLY) 136 | list (APPEND tmp "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/${src}") 137 | else () 138 | list (APPEND tmp "${PROJECT_SOURCE_DIR}/src/${src}") 139 | endif () 140 | endforeach () 141 | set (${out} "${tmp}" PARENT_SCOPE) 142 | endfunction () 143 | 144 | # ---------------------------------------------------------------------------- 145 | ## Add usage test 146 | # 147 | # Using PASS_REGULAR_EXPRESSION and FAIL_REGULAR_EXPRESSION would 148 | # do as well, but CMake/CTest does not allow us to specify an 149 | # expected exit status. Moreover, the execute_test.cmake script 150 | # sets environment variables needed by the --fromenv/--tryfromenv tests. 151 | macro (add_gflags_test name expected_rc expected_output unexpected_output cmd) 152 | set (args "--test_tmpdir=${PROJECT_BINARY_DIR}/Testing/Temporary" 153 | "--srcdir=${PROJECT_SOURCE_DIR}/test") 154 | add_test ( 155 | NAME ${name} 156 | COMMAND "${CMAKE_COMMAND}" "-DCOMMAND:STRING=$;${args};${ARGN}" 157 | "-DEXPECTED_RC:STRING=${expected_rc}" 158 | "-DEXPECTED_OUTPUT:STRING=${expected_output}" 159 | "-DUNEXPECTED_OUTPUT:STRING=${unexpected_output}" 160 | -P "${PROJECT_SOURCE_DIR}/cmake/execute_test.cmake" 161 | WORKING_DIRECTORY "${GFLAGS_FLAGFILES_DIR}" 162 | ) 163 | endmacro () 164 | 165 | # ------------------------------------------------------------------------------ 166 | ## Register installed package with CMake 167 | # 168 | # This function adds an entry to the CMake registry for packages with the 169 | # path of the directory where the package configuration file of the installed 170 | # package is located in order to help CMake find the package in a custom 171 | # installation prefix. This differs from CMake's export(PACKAGE) command 172 | # which registers the build directory instead. 173 | function (register_gflags_package CONFIG_DIR) 174 | if (NOT IS_ABSOLUTE "${CONFIG_DIR}") 175 | set (CONFIG_DIR "${CMAKE_INSTALL_PREFIX}/${CONFIG_DIR}") 176 | endif () 177 | string (MD5 REGISTRY_ENTRY "${CONFIG_DIR}") 178 | if (WIN32) 179 | install (CODE 180 | "execute_process ( 181 | COMMAND reg add \"HKCU\\\\Software\\\\Kitware\\\\CMake\\\\Packages\\\\${PACKAGE_NAME}\" /v \"${REGISTRY_ENTRY}\" /d \"${CONFIG_DIR}\" /t REG_SZ /f 182 | RESULT_VARIABLE RT 183 | ERROR_VARIABLE ERR 184 | OUTPUT_QUIET 185 | ) 186 | if (RT EQUAL 0) 187 | message (STATUS \"Register: Added HKEY_CURRENT_USER\\\\Software\\\\Kitware\\\\CMake\\\\Packages\\\\${PACKAGE_NAME}\\\\${REGISTRY_ENTRY}\") 188 | else () 189 | string (STRIP \"\${ERR}\" ERR) 190 | message (STATUS \"Register: Failed to add registry entry: \${ERR}\") 191 | endif ()" 192 | ) 193 | elseif (IS_DIRECTORY "$ENV{HOME}") 194 | file (WRITE "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-registry-entry" "${CONFIG_DIR}") 195 | install ( 196 | FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-registry-entry" 197 | DESTINATION "$ENV{HOME}/.cmake/packages/${PACKAGE_NAME}" 198 | RENAME "${REGISTRY_ENTRY}" 199 | ) 200 | endif () 201 | endfunction () 202 | -------------------------------------------------------------------------------- /vendor/gflags/ChangeLog.txt: -------------------------------------------------------------------------------- 1 | * Fri Nov 25 2016 - Andreas Schuh 2 | 3 | - gflags: version 2.2.0 4 | - Merged 178: Implicitly convert dashes in option names to underscores 5 | - Merged 159: CI builds and automatic tests with Travis CI and AppVeyor 6 | - Merged 158: Use enum for flag value types 7 | - Merged 126: File name postfix for static libraries on Windows 8 | - Closed issue 120: Configure and install gflags.pc file for pkg-config users 9 | - Fixed issue 127: snprintf already defined when building with MSVC 2015 10 | - Fixed issue 51/138: Memory leaks reported by valgrind 11 | - Fixed issue 173: Validate flags only once 12 | - Fixed issue 168: Unsigned and signed comparison in gflags_reporting.cc 13 | - Fixed issues 176/153: Add -lpthread link argument to Bazel build, refactor BUILD rules 14 | - Fixed issue 89: Add GFLAGS_IS_A_DLL to imported CMake target INTERFACE_COMPILE_DEFINITIONS 15 | - Fixed issue 104: Set INTERFACE_INCLUDE_DIRECTORIES of exported CMake targets 16 | - Fixed issue 174: Missing gflags-targets.cmake file after installation 17 | - Fixed issue 186: Error linking to gflags IMPLIB with MSVC using CMake 18 | - Closed issue 106: Add example project to test use of gflags library 19 | 20 | * Tue Mar 24 2014 - Andreas Schuh 21 | 22 | - gflags: version 2.1.2 23 | - Moved project to GitHub 24 | - Added GFLAGS_NAMESPACE definition to gflags_declare.h 25 | - Fixed issue 94: Keep "google" as primary namespace and import symbols into "gflags" namespace 26 | - Fixed issue 96: Fix binary ABI compatibility with gflags 2.0 using "google" as primary namespace 27 | - Fixed issue 97/101: Removed (patched) CMake modules and enabled C language instead 28 | - Fixed issue 103: Set CMake policy CMP0042 to silence warning regarding MACOS_RPATH setting 29 | 30 | * Sun Mar 20 2014 - Andreas Schuh 31 | 32 | - gflags: version 2.1.1 33 | - Fixed issue 77: GFLAGS_IS_A_DLL expands to empty string in gflags_declare.h 34 | - Fixed issue 79: GFLAGS_NAMESPACE not expanded to actual namespace in gflags_declare.h 35 | - Fixed issue 80: Allow include path to differ from GFLAGS_NAMESPACE 36 | 37 | * Thu Mar 20 2014 - Andreas Schuh 38 | 39 | - gflags: version 2.1.0 40 | - Build system configuration using CMake instead of autotools 41 | - CPack packaging support for Debian/Ubuntu, Red Hat, and Mac OS X 42 | - Fixed issue 54: Fix "invalid suffix on literal" (C++11) 43 | - Fixed issue 57: Use _strdup instead of strdup on Windows 44 | - Fixed issue 62: Change all preprocessor include guards to start with GFLAGS_ 45 | - Fixed issue 64: Add DEFINE_validator macro 46 | - Fixed issue 73: Warnings in Visual Studio 2010 and unable to compile unit test 47 | 48 | * Wed Jan 25 2012 - Google Inc. 49 | 50 | - gflags: version 2.0 51 | - Changed the 'official' gflags email in setup.py/etc 52 | - Renamed google-gflags.sln to gflags.sln 53 | - Changed copyright text to reflect Google's relinquished ownership 54 | 55 | * Tue Dec 20 2011 - Google Inc. 56 | 57 | - google-gflags: version 1.7 58 | - Add CommandLineFlagInfo::flag_ptr pointing to current storage (musji) 59 | - PORTING: flush after writing to stderr, needed on cygwin 60 | - PORTING: Clean up the GFLAGS_DLL_DECL stuff better 61 | - Fix a bug in StringPrintf() that affected large strings (csilvers) 62 | - Die at configure-time when g++ isn't installed 63 | 64 | * Fri Jul 29 2011 - Google Inc. 65 | 66 | - google-gflags: version 1.6 67 | - BUGFIX: Fix a bug where we were leaving out a required $(top_srcdir) 68 | - Fix definition of clstring (jyrki) 69 | - Split up flag declares into its own file (jyrki) 70 | - Add --version support (csilvers) 71 | - Update the README for gflags with static libs 72 | - Update acx_pthread.m4 for nostdlib 73 | - Change ReparseCommandLineFlags to return void (csilvers) 74 | - Some doc typofixes and example augmentation (various) 75 | 76 | * Mon Jan 24 2011 - Google Inc. 77 | 78 | - google-gflags: version 1.5 79 | - Better reporting of current vs default value (handler) 80 | - Add API for cleaning up of memory at program-exit (jmarantz) 81 | - Fix macros to work inside namespaces (csilvers) 82 | - Use our own string typedef in case string is redefined (csilvers) 83 | - Updated to autoconf 2.65 84 | 85 | * Wed Oct 13 2010 - Google Inc. 86 | 87 | - google-gflags: version 1.4 88 | - Add a check to prevent passing 0 to DEFINE_string (jorg) 89 | - Reduce compile (.o) size (jyrki) 90 | - Some small changes to quiet debug compiles (alexk) 91 | - PORTING: better support static linking on windows (csilvers) 92 | - DOCUMENTATION: change default values, use validators, etc. 93 | - Update the NEWS file to be non-empty 94 | - Add pkg-config (.pc) files for libgflags and libgflags_nothreads 95 | 96 | * Mon Jan 4 2010 - Google Inc. 97 | 98 | - google-gflags: version 1.3 99 | - PORTABILITY: can now build and run tests under MSVC (csilvers) 100 | - Remove the python gflags code, which is now its own package (tansell) 101 | - Clarify that "last flag wins" in the docs (csilvers) 102 | - Comment danger of using GetAllFlags in validators (wojtekm) 103 | - PORTABILITY: Some fixes necessary for c++0x (mboerger) 104 | - Makefile fix: $(srcdir) -> $(top_srcdir) in one place (csilvres) 105 | - INSTALL: autotools to autoconf v2.64 + automake v1.11 (csilvers) 106 | 107 | * Thu Sep 10 2009 - Google Inc. 108 | 109 | - google-gflags: version 1.2 110 | - PORTABILITY: can now build and run tests under mingw (csilvers) 111 | - Using a string arg for a bool flag is a compile-time error (rbayardo) 112 | - Add --helpxml to gflags.py (salcianu) 113 | - Protect against a hypothetical global d'tor mutex problem (csilvers) 114 | - BUGFIX: can now define a flag after 'using namespace google' (hamaji) 115 | 116 | * Tue Apr 14 2009 - Google Inc. 117 | 118 | - google-gflags: version 1.1 119 | - Add both foo and nofoo for boolean flags, with --undefok (andychu) 120 | - Better document how validators work (wojtekm) 121 | - Improve binary-detection for bash-completion (mtamsky) 122 | - Python: Add a concept of "key flags", used with --help (salcianu) 123 | - Python: Robustify flag_values (salcianu) 124 | - Python: Add a new DEFINE_bool alias (keir, andrewliu) 125 | - Python: Do module introspection based on module name (dsturtevant) 126 | - Fix autoconf a bit better, especially on windows and solaris (ajenjo) 127 | - BUG FIX: gflags_nothreads was linking against the wrong lib (ajenjo) 128 | - BUG FIX: threads-detection failed on FreeBSD; replace it (ajenjo) 129 | - PORTABILITY: Quiet an internal compiler error with SUSE 10 (csilvers) 130 | - PORTABILITY: Update deb.sh for more recenty debuilds (csilvers) 131 | - PORTABILITY: #include more headers to satify new gcc's (csilvers) 132 | - INSTALL: Updated to autoconf 2.61 and libtool 1.5.26 (csilvers) 133 | 134 | * Fri Oct 3 2008 - Google Inc. 135 | 136 | - google-gflags: version 1.0 137 | - Add a missing newline to an error string (bcmills) 138 | - (otherwise exactly the same as gflags 1.0rc2) 139 | 140 | * Thu Sep 18 2008 - Google Inc. 141 | 142 | - google-gflags: version 1.0rc2 143 | - Report current flag values in --helpxml (hdn) 144 | - Fix compilation troubles with gcc 4.3.3 (simonb) 145 | - BUG FIX: I was missing a std:: in DECLARE_string (csilvers) 146 | - BUG FIX: Clarify in docs how to specify --bool flags (csilvers) 147 | - BUG FIX: Fix --helpshort for source files not in a subdir (csilvers) 148 | - BUG FIX: Fix python unittest for 64-bit builds (bcmills) 149 | 150 | * Tue Aug 19 2008 - Google Inc. 151 | 152 | - google-gflags: version 1.0rc1 153 | - Move #include files from google/ to gflags/ (csilvers) 154 | - Small optimizations to reduce binary (library) size (jyrki) 155 | - BUGFIX: forgot a std:: in one of the .h files (csilvers) 156 | - Speed up locking by making sure calls are inlined (ajenjo) 157 | - 64-BIT COMPATIBILITY: Use %PRId64 instead of %lld (csilvers) 158 | - PORTABILITY: fix Makefile to work with Cygwin (ajenjo) 159 | - PORTABILITY: fix code to compile under Visual Studio (ajenjo) 160 | - PORTABILITY: fix code to compile under Solaris 10 with CC (csilvers) 161 | 162 | * Mon Jul 21 2008 - Google Inc. 163 | 164 | - google-gflags: version 0.9 165 | - Add the ability to validate a command-line flag (csilvers) 166 | - Add completion support for commandline flags in bash (daven) 167 | - Add -W compile flags to Makefile, when using gcc (csilvers) 168 | - Allow helpstring to be NULL (cristianoc) 169 | - Improved documentation of classes in the .cc file (csilvers) 170 | - Fix python bug with AppendFlagValues + shortnames (jjtswan) 171 | - Use bool instead of int for boolean flags in gflags.py (bcmills) 172 | - Simplify the way we declare flags, now more foolproof (csilvers) 173 | - Better error messages when bool flags collide (colohan) 174 | - Only evaluate DEFINE_foo macro args once (csilvers) 175 | 176 | * Wed Mar 26 2008 - Google Inc. 177 | 178 | - google-gflags: version 0.8 179 | - Export DescribeOneFlag() in the API 180 | - Add support for automatic line wrapping at 80 cols for gflags.py 181 | - Bugfix: do not treat an isolated "-" the same as an isolated "--" 182 | - Update rpm spec to point to Google Code rather than sourceforge (!) 183 | - Improve documentation (including documenting thread-safety) 184 | - Improve #include hygiene 185 | - Improve testing 186 | 187 | * Thu Oct 18 2007 - Google Inc. 188 | 189 | - google-gflags: version 0.7 190 | - Deal even more correctly with libpthread not linked in (csilvers) 191 | - Add STRIP_LOG, an improved DO_NOT_SHOW_COMMANDLINE_HELP (sioffe) 192 | - Be more accurate printing default flag values in --help (dsturtevant) 193 | - Reduce .o file size a bit by using shorter namespace names (jeff) 194 | - Use relative install path, so 'setup.py --home' works (csilvers) 195 | - Notice when a boolean flag has a non-boolean default (bnmouli) 196 | - Broaden --helpshort to match foo-main.cc and foo_main.cc (hendrie) 197 | - Fix "no modules match" message for --helpshort, etc (hendrie) 198 | 199 | * Wed Aug 15 2007 - Google Inc. 200 | 201 | - google-gflags: version 0.6 202 | - Deal correctly with case that libpthread is not linked in (csilvers) 203 | - Update Makefile/tests so we pass "make distcheck" (csilvers) 204 | - Document and test that last assignment to a flag wins (wan) 205 | 206 | * Tue Jun 12 2007 - Google Inc. 207 | 208 | - google-gflags: version 0.5 209 | - Include all m4 macros in the distribution (csilvers) 210 | - Python: Fix broken data_files field in setup.py (sidlon) 211 | - Python: better string serliaizing and unparsing (abo, csimmons) 212 | - Fix checks for NaN and inf to work with Mac OS X (csilvers) 213 | 214 | * Thu Apr 19 2007 - Google Inc. 215 | 216 | - google-gflags: version 0.4 217 | - Remove is_default from GetCommandLineFlagInfo (csilvers) 218 | - Portability fixes: includes, strtoll, gcc4.3 errors (csilvers) 219 | - A few doc typo cleanups (csilvers) 220 | 221 | * Wed Mar 28 2007 - Google Inc. 222 | 223 | - google-gflags: version 0.3 224 | - python portability fix: use popen instead of subprocess (csilvers) 225 | - Add is_default to CommandLineFlagInfo (pchien) 226 | - Make docs a bit prettier (csilvers) 227 | - Actually include the python files in the distribution! :-/ (csilvers) 228 | 229 | * Mon Jan 22 2007 - Google Inc. 230 | 231 | - google-gflags: version 0.2 232 | - added support for python commandlineflags, as well as c++ 233 | - gflags2man, a script to turn flags into a man page (dchristian) 234 | 235 | * Wed Dec 13 2006 - Google Inc. 236 | 237 | - google-gflags: version 0.1 238 | -------------------------------------------------------------------------------- /visualize.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import yaml 4 | from yaml import CLoader as Loader, CDumper as Dumper 5 | import ujson 6 | import itertools 7 | import argparse 8 | import scipy.misc 9 | 10 | # dump = yaml.dump(dummy_data, fh, encoding='utf-8', default_flow_style=False, Dumper=Dumper) 11 | # data = yaml.load(fh, Loader=Loader) 12 | 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument('--path', help='Path to serialized json CDDT data structure') 15 | 16 | class Map(object): 17 | """ Map saved in a serialized CDDT """ 18 | def __init__(self, data): 19 | print "...loading map" 20 | self.path = data["path"] 21 | self.width = data["width"] 22 | self.height = data["height"] 23 | self.data = np.array(data["data"]).transpose() 24 | 25 | def visualize(self): 26 | plt.imshow(-1*self.data, cmap="gray") 27 | plt.show() 28 | 29 | class CDDTSlice(object): 30 | """ Contains a single slice of CDDT corresponding to a single theta value""" 31 | def __init__(self, data): 32 | # print "...loading slice" 33 | self.theta = data["theta"] 34 | self.zeros = data["zeros"] 35 | 36 | def num_zeros(self): 37 | return [len(lut_bin) for lut_bin in self.zeros] 38 | 39 | def ddt_dims(self): 40 | non_empty_zeros = filter(lambda x: len(x) > 0, self.zeros) 41 | min_zero = min(map(min, non_empty_zeros)) 42 | max_zero = max(map(max, non_empty_zeros)) 43 | return [int(np.ceil(max_zero - min_zero))+1,len(self.zeros)] 44 | 45 | def make_ddt(self, saw_tooth=True, reversed_dir=False): 46 | non_empty_zeros = filter(lambda x: len(x) > 0, self.zeros) 47 | if len(non_empty_zeros) == 0: 48 | print "Empty slice, nothing to visualize" 49 | return 50 | 51 | # print map(min, self.zeros) 52 | min_zero = min(map(min, non_empty_zeros)) 53 | max_zero = max(map(max, non_empty_zeros)) 54 | height = int(np.ceil(max_zero - min_zero))+1 55 | 56 | grid_height = len(self.zeros) 57 | # ddt = np.zeros((height,len(self.zeros))) 58 | ddt = np.zeros((grid_height,len(self.zeros))) 59 | offset = int((grid_height - height) / 2.0) 60 | 61 | for x in xrange(len(self.zeros)): 62 | for zp in self.zeros[x]: 63 | y = int(zp - min_zero+offset) 64 | ddt[y,x] = 1 65 | 66 | if saw_tooth: 67 | for x in xrange(len(self.zeros)): 68 | if reversed_dir: 69 | last = -1 70 | for y in reversed(xrange(grid_height)): 71 | if ddt[y,x] == 1: 72 | last = 0 73 | ddt[y,x] = last 74 | elif last >= 0: 75 | last = last + 1 76 | ddt[y,x] = last 77 | else: 78 | # make the no data regions white 79 | ddt[y,x] = -1 80 | else: 81 | last = -1 82 | for y in xrange(grid_height): 83 | if ddt[y,x] == 1: 84 | last = 0 85 | ddt[y,x] = last 86 | elif last >= 0: 87 | last = last + 1 88 | ddt[y,x] = last 89 | else: 90 | # make the no data regions white 91 | ddt[y,x] = -1 92 | 93 | ddt[ddt == -1] = np.max(ddt) 94 | return ddt 95 | 96 | def visualize(): 97 | return plt.imshow(np.sqrt(self.make_ddt()),cmap="gray") 98 | # plt.show() 99 | # print ddt #min_zero, max_zero, height 100 | 101 | 102 | class CDDT(object): 103 | """ Loads a serialized CDDT datastructure for visualization and manipulation """ 104 | def __init__(self, path): 105 | print "Loading CDDT:", path 106 | self.path = path 107 | print "..opening file" 108 | cddt_file = open(path, 'r') 109 | print "..loading json" 110 | cddt_raw = ujson.load(cddt_file) 111 | 112 | if not "cddt" in cddt_raw: 113 | print "Incorrectly formatted data, exiting." 114 | return 115 | 116 | cddt_raw = cddt_raw["cddt"] 117 | print "..parsing" 118 | self.lut_translations = np.array(cddt_raw["lut_translations"]) 119 | self.max_range = cddt_raw["max_range"] 120 | self.theta_discretization = cddt_raw["theta_discretization"] 121 | self.map = Map(cddt_raw["map"]) 122 | print "..loading slices" 123 | self.slices = map(CDDTSlice, cddt_raw["compressed_lut"]) 124 | self.slices = self.slices[:int(len(self.slices)/2)] 125 | 126 | # makes a histogram of number of elements in each LUT bin 127 | def zeros_hist(self): 128 | # print self.slices[0].zeros() 129 | num_zeros = map(lambda x: x.num_zeros(), self.slices) 130 | plt.hist(num_zeros) 131 | plt.show() 132 | # print list(itertools.chain.from_iterable(num_zeros)) 133 | # print num_zeros[0] 134 | 135 | class SliceScroller(object): 136 | def __init__(self, cddt): 137 | # self.fig, (self.ax1,self.ax2) = plt.subplots(2, 1) 138 | self.fig = plt.figure() 139 | self.ax1 = plt.subplot(6,1,1) 140 | self.ax2 = plt.subplot(6,1,2) 141 | 142 | self.ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3) 143 | self.ax2 = plt.subplot2grid((4, 1), (3, 0)) 144 | # ax3 = plt.subplot2grid((6, 1), (2, 0)) 145 | # ax4 = plt.subplot2grid((6, 1), (3, 0)) 146 | # ax5 = plt.subplot2grid((6, 1), (4, 0), rowspan=2) 147 | 148 | # plt.subplot(6,1,3) 149 | # plt.subplot(2,1,2) 150 | # self.ax = ax 151 | # self.fig = fig 152 | self.ax1.set_title('use scroll wheel to navigate images') 153 | self.cddt = cddt 154 | self.ind = 2 155 | 156 | self.fig.canvas.mpl_connect('scroll_event', self.onscroll) 157 | 158 | self.ddts = [None]*len(self.cddt.slices) 159 | 160 | # dims = np.array(map(lambda x: x.ddt_dims(), self.cddt.slices)) 161 | # max_dims = np.max(dims,axis=0) 162 | # print (int(max_dims[1]),int(max_dims[0])) 163 | # self.ddt = np.ones((max_dims[1],max_dims[0])) 164 | # self.ddt = 255*np.random.rand(int(max_dims[0]),int(max_dims[1])) 165 | # self.im = ax.imshow(self.ddt, cmap="gray") 166 | self.update() 167 | 168 | # self.get_viz() 169 | # print self.ddt.shape 170 | # self.im = ax.imshow(self.ddt, cmap="gray") 171 | # self.im.axes.figure.canvas.draw() 172 | 173 | 174 | def onscroll(self, evt): 175 | print("Slice: %s Theta: %s" % (self.ind, self.cddt.slices[self.ind].theta)) 176 | self.ind = int((self.ind + evt.step) % len(self.cddt.slices)) 177 | self.update() 178 | 179 | def update(self): 180 | plt.tight_layout() 181 | self.ax1.cla() 182 | self.ax2.cla() 183 | 184 | self.ax1.axis('off') 185 | 186 | if not isinstance(self.ddts[self.ind], np.ndarray): 187 | # if self.ddts[self.ind] == None: 188 | self.ddts[self.ind] = np.sqrt(self.cddt.slices[self.ind].make_ddt(True)).transpose() 189 | 190 | ys = map(len, self.cddt.slices[self.ind].zeros) 191 | compression_factor = 2*self.cddt.map.width * self.cddt.map.height / (sum(ys)) 192 | 193 | self.ax1.set_title("DDT - Reconstructed from a slice of the PCDDT, compression factor: " + str(compression_factor)) 194 | self.ax1.set_ylabel('Theta = %s' % self.cddt.slices[self.ind].theta) 195 | self.ax1.imshow(self.ddts[self.ind],cmap="gray",interpolation='nearest', aspect='auto') 196 | 197 | 198 | self.ax2.set_title("Number of entries projected into each PCDDT bin") 199 | self.ax2.plot(ys) 200 | self.fig.canvas.draw() 201 | # self.im.set_data(self.ddt) 202 | # self.im.axes.figure.canvas.draw() 203 | 204 | 205 | # ind = 0 206 | # def scroll_slices(saw_tooth=True): 207 | # fig = plt.figure() 208 | # ddt = cddt.slices[10].make_ddt() 209 | # # im = plt.imshow(np.sqrt(ddt), cmap="gray") 210 | # im = plt.imshow(np.ones((100,100)), cmap="gray") 211 | 212 | # def onscroll(evt): 213 | # global ind 214 | # print "Slice:", ind, "theta:", cddt.slices[ind].theta 215 | # ind = int((ind + evt.step) % len(cddt.slices)) 216 | # ddt = cddt.slices[ind].make_ddt() 217 | # im.set_data(ind*np.ones((100,100))) 218 | # im.axes.figure.canvas.draw() 219 | # # cddt.slices[0].visualize() 220 | # # plt.show() 221 | 222 | 223 | # fig.canvas.mpl_connect('scroll_event', onscroll) 224 | # plt.show() 225 | 226 | # generate LUT slice vs DDT graphics 227 | if __name__ == '__main__': 228 | ddt_img = scipy.misc.imread("./paper/ddt_neg_pi_over_4_no_pow.png") 229 | lut_img = scipy.misc.imread("./paper/lut_slice_neg_pi_over_4.png") 230 | 231 | 232 | 233 | ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3) 234 | ax2 = plt.subplot2grid((4, 1), (3, 0)) 235 | # plt.tight_layout() 236 | row_num = 700 237 | ax1.axis('off') 238 | ax2.set_ylim([0,200]) 239 | ax2.set_xlim([0,ddt_img.shape[1]]) 240 | 241 | ddt_img_color = np.zeros((ddt_img.shape[0], ddt_img.shape[1], 3), dtype=np.uint8) 242 | ddt_img_color[:, :, :] = ddt_img[:, :, np.newaxis] 243 | ax2.plot(ddt_img[row_num,:]) 244 | 245 | ddt_img_color[row_num-2:row_num+2,:,:] = (0,0,255) 246 | ddt_img_color[:3,:,:] = (0,0,0) 247 | ddt_img_color[-3:,:,:] = (0,0,0) 248 | 249 | ax1.imshow(ddt_img_color) 250 | 251 | plt.figure() 252 | 253 | ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3) 254 | ax2 = plt.subplot2grid((4, 1), (3, 0)) 255 | # plt.tight_layout() 256 | row_num = 600 257 | ax1.axis('off') 258 | ax2.set_ylim([0,250]) 259 | ax2.set_xlim([0,lut_img.shape[1]]) 260 | ax2.plot(lut_img[row_num,:]) 261 | 262 | lut_img_color = np.zeros((lut_img.shape[0], lut_img.shape[1], 3), dtype=np.uint8) 263 | lut_img_color[:, :, :] = lut_img[:, :, np.newaxis] 264 | lut_img_color[row_num-2:row_num+2,:,:] = (0,0,255) 265 | lut_img_color[:3,:,:] = (0,0,0) 266 | lut_img_color[-3:,:,:] = (0,0,0) 267 | ax1.imshow(lut_img_color, cmap="gray") 268 | 269 | 270 | 271 | 272 | # plt.ylim([0,250]) 273 | # plt.plot(lut_img[600,:]) 274 | # plt.figure() 275 | # lut_img[600,:] = 255 276 | # plt.imshow(lut_img, cmap="gray") 277 | plt.show() 278 | 279 | exit() 280 | 281 | 282 | 283 | if __name__ == '__main__': 284 | args = parser.parse_args() 285 | cddt = CDDT(args.path) 286 | 287 | # plt.imshow(np.sqrt(cddt.slices[3].make_ddt(reversed_dir=True).transpose()), cmap="gray") 288 | w = 1350 289 | img = np.power(cddt.slices[3].make_ddt(reversed_dir=True).transpose()[120:120+w,:w],0.7) 290 | # img = np.power(cddt.slices[3].make_ddt(reversed_dir=True).transpose()[120:120+w,:w],1.0) 291 | plt.imshow(img, cmap="gray") 292 | # scipy.misc.imsave("./paper/ddt_neg_pi_over_4_no_pow.png",img) 293 | # plt.imshow(cddt.slices[3].make_ddt(reversed_dir=True), cmap="gray") 294 | plt.show() 295 | 296 | 297 | # X = np.random.rand(20, 20, 40) 298 | # tracker = SliceScroller(cddt) 299 | # plt.show() 300 | 301 | 302 | # You probably won't need this if you're embedding things in a tkinter plot... 303 | # plt.ion() 304 | 305 | # fig, ax = plt.subplots(1, 1) 306 | # # X = numpy.random.rand(20, 20, 40) 307 | 308 | # scroller = SliceScroller(ax,fig, cddt) 309 | # fig.canvas.mpl_connect('scroll_event', scroller.onscroll) 310 | # plt.show() 311 | 312 | # SliceScroller(cddt) 313 | 314 | # scroll_slices() 315 | 316 | # cddt.slices[0].visualize() 317 | # cddt.map.visualize() 318 | # cddt.zeros_hist() 319 | 320 | 321 | # from __future__ import print_function 322 | # import numpy as np 323 | # import matplotlib.pyplot as plt 324 | 325 | -------------------------------------------------------------------------------- /vendor/gflags/test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | ## gflags tests 2 | 3 | # ---------------------------------------------------------------------------- 4 | # output directories 5 | set (CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") 6 | set (CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") 7 | set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") 8 | 9 | # set working directory of test commands 10 | set (GFLAGS_FLAGFILES_DIR "${CMAKE_CURRENT_SOURCE_DIR}") 11 | 12 | # ---------------------------------------------------------------------------- 13 | # common include directories and link libraries 14 | include_directories ("${CMAKE_CURRENT_SOURCE_DIR}") 15 | include_directories ("${gflags_SOURCE_DIR}/src") 16 | include_directories ("${gflags_BINARY_DIR}/include") 17 | include_directories ("${gflags_BINARY_DIR}/include/gflags") 18 | 19 | if (BUILD_SHARED_LIBS) 20 | set (type shared) 21 | if (GFLAGS_IS_A_DLL) 22 | add_definitions(-DGFLAGS_IS_A_DLL) 23 | endif () 24 | else () 25 | set (type static) 26 | endif () 27 | if (BUILD_gflags_LIB) 28 | link_libraries (gflags_${type}) 29 | else () 30 | link_libraries (gflags_nothreads_${type}) 31 | endif () 32 | 33 | # ---------------------------------------------------------------------------- 34 | # STRIP_FLAG_HELP 35 | add_executable (gflags_strip_flags_test gflags_strip_flags_test.cc) 36 | # Make sure the --help output doesn't print the stripped text. 37 | add_gflags_test (strip_flags_help 1 "" "This text should be stripped out" gflags_strip_flags_test --help) 38 | # Make sure the stripped text isn't in the binary at all. 39 | add_test ( 40 | NAME strip_flags_binary 41 | COMMAND "${CMAKE_COMMAND}" "-DBINARY=$" 42 | -P "${CMAKE_CURRENT_SOURCE_DIR}/gflags_strip_flags_test.cmake" 43 | CONFIGURATIONS Release MinSizeRel 44 | ) 45 | 46 | # ---------------------------------------------------------------------------- 47 | # unit tests 48 | configure_file (gflags_unittest.cc gflags_unittest-main.cc COPYONLY) 49 | configure_file (gflags_unittest.cc gflags_unittest_main.cc COPYONLY) 50 | 51 | add_executable (gflags_unittest gflags_unittest.cc) 52 | add_executable (gflags_unittest-main gflags_unittest-main.cc) 53 | add_executable (gflags_unittest_main gflags_unittest_main.cc) 54 | 55 | if (OS_WINDOWS) 56 | set (SLASH "\\\\") 57 | else () 58 | set (SLASH "/") 59 | endif () 60 | 61 | # First, just make sure the gflags_unittest works as-is 62 | add_gflags_test(unittest 0 "" "" gflags_unittest) 63 | 64 | # --help should show all flags, including flags from gflags_reporting 65 | add_gflags_test(help-reporting 1 "${SLASH}gflags_reporting.cc:" "" gflags_unittest --help) 66 | 67 | # Make sure that --help prints even very long helpstrings. 68 | add_gflags_test(long-helpstring 1 "end of a long helpstring" "" gflags_unittest --help) 69 | 70 | # Make sure --help reflects flag changes made before flag-parsing 71 | add_gflags_test(changed_bool1 1 "-changed_bool1 (changed) type: bool default: true" "" gflags_unittest --help) 72 | add_gflags_test(changed_bool2 1 "-changed_bool2 (changed) type: bool default: false currently: true" "" gflags_unittest --help) 73 | # And on the command-line, too 74 | add_gflags_test(changeable_string_var 1 "-changeable_string_var () type: string default: \"1\" currently: \"2\"" "" gflags_unittest --changeable_string_var 2 --help) 75 | 76 | # --nohelp and --help=false should be as if we didn't say anything 77 | add_gflags_test(nohelp 0 "PASS" "" gflags_unittest --nohelp) 78 | add_gflags_test(help=false 0 "PASS" "" gflags_unittest --help=false) 79 | 80 | # --helpfull is the same as help 81 | add_gflags_test(helpfull 1 "${SLASH}gflags_reporting.cc:" "" gflags_unittest --helpfull) 82 | 83 | # --helpshort should show only flags from the gflags_unittest itself 84 | add_gflags_test(helpshort 1 "${SLASH}gflags_unittest.cc:" "${SLASH}gflags_reporting.cc:" gflags_unittest --helpshort) 85 | 86 | # --helpshort should show the tldflag we created in the gflags_unittest dir 87 | add_gflags_test(helpshort-tldflag1 1 "tldflag1" "${SLASH}google.cc:" gflags_unittest --helpshort) 88 | add_gflags_test(helpshort-tldflag2 1 "tldflag2" "${SLASH}google.cc:" gflags_unittest --helpshort) 89 | 90 | # --helpshort should work if the main source file is suffixed with [_-]main 91 | add_gflags_test(helpshort-main 1 "${SLASH}gflags_unittest-main.cc:" "${SLASH}gflags_reporting.cc:" gflags_unittest-main --helpshort) 92 | add_gflags_test(helpshort_main 1 "${SLASH}gflags_unittest_main.cc:" "${SLASH}gflags_reporting.cc:" gflags_unittest_main --helpshort) 93 | 94 | # --helpon needs an argument 95 | add_gflags_test(helpon 1 "'--helpon' is missing its argument; flag description: show help on" "" gflags_unittest --helpon) 96 | # --helpon argument indicates what file we'll show args from 97 | add_gflags_test(helpon=gflags 1 "${SLASH}gflags.cc:" "${SLASH}gflags_unittest.cc:" gflags_unittest --helpon=gflags) 98 | # another way of specifying the argument 99 | add_gflags_test(helpon_gflags 1 "${SLASH}gflags.cc:" "${SLASH}gflags_unittest.cc:" gflags_unittest --helpon gflags) 100 | # test another argument 101 | add_gflags_test(helpon=gflags_unittest 1 "${SLASH}gflags_unittest.cc:" "${SLASH}gflags.cc:" gflags_unittest --helpon=gflags_unittest) 102 | 103 | # helpmatch is like helpon but takes substrings 104 | add_gflags_test(helpmatch_reporting 1 "${SLASH}gflags_reporting.cc:" "${SLASH}gflags_unittest.cc:" gflags_unittest -helpmatch reporting) 105 | add_gflags_test(helpmatch=unittest 1 "${SLASH}gflags_unittest.cc:" "${SLASH}gflags.cc:" gflags_unittest -helpmatch=unittest) 106 | 107 | # if no flags are found with helpmatch or helpon, suggest --help 108 | add_gflags_test(helpmatch=nosuchsubstring 1 "No modules matched" "${SLASH}gflags_unittest.cc:" gflags_unittest -helpmatch=nosuchsubstring) 109 | add_gflags_test(helpon=nosuchmodule 1 "No modules matched" "${SLASH}gflags_unittest.cc:" gflags_unittest -helpon=nosuchmodule) 110 | 111 | # helppackage shows all the flags in the same dir as this unittest 112 | # --help should show all flags, including flags from google.cc 113 | add_gflags_test(helppackage 1 "${SLASH}gflags_reporting.cc:" "" gflags_unittest --helppackage) 114 | 115 | # xml! 116 | add_gflags_test(helpxml 1 "${SLASH}gflags_unittest.cc" "${SLASH}gflags_unittest.cc:" gflags_unittest --helpxml) 117 | 118 | # just print the version info and exit 119 | add_gflags_test(version-1 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --version) 120 | add_gflags_test(version-2 0 "version test_version" "${SLASH}gflags_unittest.cc:" gflags_unittest --version) 121 | 122 | # --undefok is a fun flag... 123 | add_gflags_test(undefok-1 1 "unknown command line flag 'foo'" "" gflags_unittest --undefok= --foo --unused_bool) 124 | add_gflags_test(undefok-2 0 "PASS" "" gflags_unittest --undefok=foo --foo --unused_bool) 125 | # If you say foo is ok to be undefined, we'll accept --nofoo as well 126 | add_gflags_test(undefok-3 0 "PASS" "" gflags_unittest --undefok=foo --nofoo --unused_bool) 127 | # It's ok if the foo is in the middle 128 | add_gflags_test(undefok-4 0 "PASS" "" gflags_unittest --undefok=fee,fi,foo,fum --foo --unused_bool) 129 | # But the spelling has to be just right... 130 | add_gflags_test(undefok-5 1 "unknown command line flag 'foo'" "" gflags_unittest --undefok=fo --foo --unused_bool) 131 | add_gflags_test(undefok-6 1 "unknown command line flag 'foo'" "" gflags_unittest --undefok=foot --foo --unused_bool) 132 | 133 | # See if we can successfully load our flags from the flagfile 134 | add_gflags_test(flagfile.1 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest "--flagfile=flagfile.1") 135 | add_gflags_test(flagfile.2 0 "PASS" "" gflags_unittest "--flagfile=flagfile.2") 136 | add_gflags_test(flagfile.3 0 "PASS" "" gflags_unittest "--flagfile=flagfile.3") 137 | 138 | # Also try to load flags from the environment 139 | add_gflags_test(fromenv=version 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --fromenv=version) 140 | add_gflags_test(tryfromenv=version 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --tryfromenv=version) 141 | add_gflags_test(fromenv=help 0 "PASS" "" gflags_unittest --fromenv=help) 142 | add_gflags_test(tryfromenv=help 0 "PASS" "" gflags_unittest --tryfromenv=help) 143 | add_gflags_test(fromenv=helpfull 1 "helpfull not found in environment" "" gflags_unittest --fromenv=helpfull) 144 | add_gflags_test(tryfromenv=helpfull 0 "PASS" "" gflags_unittest --tryfromenv=helpfull) 145 | add_gflags_test(tryfromenv=undefok 0 "PASS" "" gflags_unittest --tryfromenv=undefok --foo) 146 | add_gflags_test(tryfromenv=weirdo 1 "unknown command line flag" "" gflags_unittest --tryfromenv=weirdo) 147 | add_gflags_test(tryfromenv-multiple 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --tryfromenv=test_bool,version,unused_bool) 148 | add_gflags_test(fromenv=test_bool 1 "not found in environment" "" gflags_unittest --fromenv=test_bool) 149 | add_gflags_test(fromenv=test_bool-ok 1 "unknown command line flag" "" gflags_unittest --fromenv=test_bool,ok) 150 | # Here, the --version overrides the fromenv 151 | add_gflags_test(version-overrides-fromenv 0 "gflags_unittest" "${SLASH}gflags_unittest.cc:" gflags_unittest --fromenv=test_bool,version,ok) 152 | 153 | # Make sure -- by itself stops argv processing 154 | add_gflags_test(dashdash 0 "PASS" "" gflags_unittest -- --help) 155 | 156 | # And we should die if the flag value doesn't pass the validator 157 | add_gflags_test(always_fail 1 "ERROR: failed validation of new value 'true' for flag 'always_fail'" "" gflags_unittest --always_fail) 158 | 159 | # And if locking in validators fails 160 | # TODO(andreas): Worked on Windows 7 Release configuration, but causes 161 | # debugger abort() intervention in case of Debug configuration. 162 | #add_gflags_test(deadlock_if_cant_lock 0 "PASS" "" gflags_unittest --deadlock_if_cant_lock) 163 | 164 | # ---------------------------------------------------------------------------- 165 | # use gflags_declare.h 166 | add_executable (gflags_declare_test gflags_declare_test.cc gflags_declare_flags.cc) 167 | 168 | add_test(NAME gflags_declare COMMAND gflags_declare_test --message "Hello gflags!") 169 | set_tests_properties(gflags_declare PROPERTIES PASS_REGULAR_EXPRESSION "Hello gflags!") 170 | 171 | # ---------------------------------------------------------------------------- 172 | # configure Python script which configures and builds a test project 173 | if (BUILD_NC_TESTS OR BUILD_CONFIG_TESTS) 174 | find_package (PythonInterp) 175 | if (NOT PYTHON_EXECUTABLE) 176 | message (FATAL_ERROR "No Python installation found! It is required by the (negative) compilation tests." 177 | " Either install Python or set BUILD_NC_TESTS and BUILD_CONFIG_TESTS to FALSE.") 178 | endif () 179 | set (TMPDIR "${PROJECT_BINARY_DIR}/Testing/Temporary") 180 | configure_file (gflags_build.py.in "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/build.py" @ONLY) 181 | function (add_gflags_build_test name srcdir expect_fail) 182 | set (srcdir "${CMAKE_CURRENT_SOURCE_DIR}/${srcdir}") 183 | add_test ( 184 | NAME "${name}" 185 | COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/build.py" 186 | ${name} ${srcdir} ${expect_fail} 187 | ) 188 | endfunction () 189 | endif () 190 | 191 | # ---------------------------------------------------------------------------- 192 | # negative compilation tests 193 | option (BUILD_NC_TESTS "Request addition of negative compilation tests." OFF) 194 | mark_as_advanced (BUILD_NC_TESTS) 195 | if (BUILD_NC_TESTS) 196 | add_gflags_build_test (nc_sanity nc 0) 197 | add_gflags_build_test (nc_swapped_args nc 1) 198 | add_gflags_build_test (nc_int_instead_of_bool nc 1) 199 | add_gflags_build_test (nc_bool_in_quotes nc 1) 200 | add_gflags_build_test (nc_define_string_with_0 nc 1) 201 | endif () 202 | 203 | # ---------------------------------------------------------------------------- 204 | # build configuration test 205 | option (BUILD_CONFIG_TESTS "Request addition of package configuration tests." OFF) 206 | mark_as_advanced (BUILD_CONFIG_TESTS) 207 | if (BUILD_CONFIG_TESTS) 208 | add_gflags_build_test (cmake_config config 0) 209 | endif () 210 | -------------------------------------------------------------------------------- /includes/kernels.cu: -------------------------------------------------------------------------------- 1 | #include "includes/CudaRangeLib.h" 2 | // #include "includes/RangeUtils.h" 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define DIST_THRESHOLD 0.0 13 | #define STEP_COEFF 0.999 14 | 15 | __device__ float distance(int x, int y, float *distMap, int width, int height) { 16 | return distMap[x * height + y]; 17 | } 18 | 19 | __global__ void cuda_ray_marching(float * ins, float * outs, float * distMap, int width, int height, float max_range, int num_casts) { 20 | int ind = blockIdx.x*blockDim.x + threadIdx.x; 21 | if (ind >= num_casts) return; 22 | float x0 = ins[ind*3]; 23 | float y0 = ins[ind*3+1]; 24 | float theta = ins[ind*3+2]; 25 | 26 | float ray_direction_x = cosf(theta); 27 | float ray_direction_y = sinf(theta); 28 | 29 | int px = 0; 30 | int py = 0; 31 | 32 | float t = 0.0; 33 | float out = max_range; 34 | // int iters = 0; 35 | while (t < max_range) { 36 | px = x0 + ray_direction_x * t; 37 | py = y0 + ray_direction_y * t; 38 | 39 | if (px >= width || px < 0 || py < 0 || py >= height) { 40 | out = max_range; 41 | break; 42 | } 43 | 44 | float d = distance(px,py, distMap, width, height); 45 | 46 | if (d <= DIST_THRESHOLD) { 47 | float xd = px - x0; 48 | float yd = py - y0; 49 | out = sqrtf(xd*xd + yd*yd); 50 | break; 51 | } 52 | 53 | t += fmaxf(d * STEP_COEFF, 1.0); 54 | // iters ++; 55 | } 56 | outs[ind] = out; 57 | } 58 | 59 | __global__ void cuda_ray_marching_world_to_grid(float * ins, float * outs, float * distMap, int width, int height, float max_range, int num_casts, float world_origin_x, float world_origin_y, float world_scale, float inv_world_scale, float world_sin_angle, float world_cos_angle, float rotation_const) { 60 | int ind = blockIdx.x*blockDim.x + threadIdx.x; 61 | if (ind >= num_casts) return; 62 | 63 | float x_world = ins[ind*3]; 64 | float y_world = ins[ind*3+1]; 65 | float theta_world = ins[ind*3+2]; 66 | 67 | // convert x0,y0,theta from world to grid space coordinates 68 | float x0 = (x_world - world_origin_x) * inv_world_scale; 69 | float y0 = (y_world - world_origin_y) * inv_world_scale; 70 | float temp = x0; 71 | x0 = world_cos_angle*x0 - world_sin_angle*y0; 72 | y0 = world_sin_angle*temp + world_cos_angle*y0; 73 | float theta = -theta_world + rotation_const; 74 | 75 | // swap components 76 | temp = x0; 77 | x0 = y0; 78 | y0 = temp; 79 | 80 | // do ray casting 81 | float ray_direction_x = cosf(theta); 82 | float ray_direction_y = sinf(theta); 83 | 84 | int px = 0; 85 | int py = 0; 86 | 87 | float t = 0.0; 88 | float out = max_range; 89 | while (t < max_range) { 90 | px = x0 + ray_direction_x * t; 91 | py = y0 + ray_direction_y * t; 92 | 93 | if (px >= width || px < 0 || py < 0 || py >= height) { 94 | out = max_range; 95 | break; 96 | } 97 | 98 | float d = distance(px,py, distMap, width, height); 99 | 100 | if (d <= DIST_THRESHOLD) { 101 | float xd = px - x0; 102 | float yd = py - y0; 103 | out = sqrtf(xd*xd + yd*yd); 104 | break; 105 | } 106 | 107 | t += fmaxf(d * STEP_COEFF, 1.0); 108 | } 109 | outs[ind] = out * world_scale; 110 | } 111 | 112 | __global__ void cuda_ray_marching_angles_world_to_grid(float * ins, float * outs, float * distMap, int width, int height, float max_range, int num_particles, int num_angles, float world_origin_x, float world_origin_y, float world_scale, float inv_world_scale, float world_sin_angle, float world_cos_angle, float rotation_const) { 113 | int ind = blockIdx.x*blockDim.x + threadIdx.x; 114 | if (ind >= num_angles*num_particles) return; 115 | 116 | int angle_ind = fmodf( ind, num_angles ); 117 | int particle_ind = (float) ind / (float) num_angles; 118 | 119 | float x_world = ins[particle_ind*3]; 120 | float y_world = ins[particle_ind*3+1]; 121 | float theta_world = ins[particle_ind*3+2]; 122 | 123 | // convert x0,y0,theta from world to grid space coordinates 124 | float x0 = (x_world - world_origin_x) * inv_world_scale; 125 | float y0 = (y_world - world_origin_y) * inv_world_scale; 126 | float temp = x0; 127 | x0 = world_cos_angle*x0 - world_sin_angle*y0; 128 | y0 = world_sin_angle*temp + world_cos_angle*y0; 129 | float theta = -theta_world + rotation_const - ins[num_particles * 3 + angle_ind]; 130 | 131 | // swap components 132 | temp = x0; 133 | x0 = y0; 134 | y0 = temp; 135 | 136 | // do ray casting 137 | float ray_direction_x = cosf(theta); 138 | float ray_direction_y = sinf(theta); 139 | 140 | int px = 0; 141 | int py = 0; 142 | 143 | float t = 0.0; 144 | float out = max_range; 145 | while (t < max_range) { 146 | px = x0 + ray_direction_x * t; 147 | py = y0 + ray_direction_y * t; 148 | 149 | if (px >= width || px < 0 || py < 0 || py >= height) { 150 | out = max_range; 151 | break; 152 | } 153 | 154 | float d = distance(px,py, distMap, width, height); 155 | 156 | if (d <= DIST_THRESHOLD) { 157 | float xd = px - x0; 158 | float yd = py - y0; 159 | out = sqrtf(xd*xd + yd*yd); 160 | break; 161 | } 162 | t += fmaxf(d * STEP_COEFF, 1.0); 163 | } 164 | outs[ind] = out * world_scale; 165 | } 166 | 167 | __device__ int clamp(float val, float min, float max) { 168 | val = val>max?max:val; 169 | val = val= rays_per_particle) return; 177 | 178 | int r = clamp(obs[ind] * inv_world_scale,0,max_range-1.0); 179 | for (int i = 0; i < particles; ++i) 180 | { 181 | int d = clamp(ranges[ind + ind * i],0,max_range-1.0); 182 | outs[ind+i*rays_per_particle] = sensorTable[r*max_range+d]; 183 | } 184 | } 185 | 186 | // this should be optimized to use shared memory, otherwise the random read performance is not great 187 | // __global__ void cuda_accumulate_weights(float * obs, float * ranges, double * outs, double * sensorTable, int rays_per_particle, int particles, float inv_world_scale, int max_range) { 188 | // int ind = blockIdx.x*blockDim.x + threadIdx.x; 189 | // if (ind >= particles) return; 190 | 191 | // double weight = 1.0; 192 | // for (int i = 0; i < rays_per_particle; ++i) 193 | // { 194 | // weight *= outs[ind*rays_per_particle+i]; 195 | 196 | // } 197 | // } 198 | 199 | void err_check() { 200 | cudaError_t err = cudaGetLastError(); 201 | if (err != cudaSuccess) 202 | printf("Error: %s\n", cudaGetErrorString(err)); 203 | } 204 | 205 | RayMarchingCUDA::RayMarchingCUDA(std::vector > grid, int w, int h, float mr) 206 | : width(w), height(h), max_range(mr) { 207 | cudaMalloc((void **)&d_ins, sizeof(float) * CHUNK_SIZE * 3); 208 | cudaMalloc((void **)&d_outs, sizeof(float) * CHUNK_SIZE); 209 | cudaMalloc((void **)&d_distMap, sizeof(float) * width * height); 210 | 211 | // convert vector format to raw float array, y axis is quickly changing dimension 212 | // float raw_grid[width*height]; 213 | float *raw_grid = new float[width*height]; 214 | for (int i = 0; i < width; ++i) std::copy(grid[i].begin(), grid[i].end(), &raw_grid[i*height]); 215 | 216 | cudaMemcpy(d_distMap, raw_grid, width*height*sizeof(float), cudaMemcpyHostToDevice); 217 | free(raw_grid); 218 | } 219 | 220 | RayMarchingCUDA::~RayMarchingCUDA() { 221 | cudaFree(d_ins); cudaFree(d_outs); cudaFree(d_distMap); 222 | } 223 | 224 | void RayMarchingCUDA::set_sensor_table(double *table, int t_w) { 225 | table_width = t_w; 226 | int table_size = sizeof(double) * table_width * table_width; 227 | cudaMalloc((void **)&d_sensorTable, table_size); 228 | cudaMemcpy(d_sensorTable, table, table_size, cudaMemcpyHostToDevice); 229 | } 230 | 231 | // num_casts must be less than or equal to chunk size 232 | void RayMarchingCUDA::calc_range_many(float *ins, float *outs, int num_casts) { 233 | // copy queries to GPU buffer 234 | cudaMemcpy(d_ins, ins, sizeof(float) * num_casts * 3,cudaMemcpyHostToDevice); 235 | // execute queries on the GPU 236 | cuda_ray_marching<<< CHUNK_SIZE / NUM_THREADS, NUM_THREADS >>>(d_ins,d_outs, d_distMap, width, height, max_range, num_casts); 237 | err_check(); 238 | 239 | // copy results back to CPU 240 | cudaMemcpy(outs,d_outs,sizeof(float)*num_casts,cudaMemcpyDeviceToHost); 241 | cudaDeviceSynchronize(); 242 | } 243 | 244 | // num_casts must be less than or equal to chunk size 245 | void RayMarchingCUDA::numpy_calc_range(float *ins, float *outs, int num_casts) { 246 | #if ROS_WORLD_TO_GRID_CONVERSION == 1 247 | // copy queries to GPU buffer 248 | cudaMemcpy(d_ins, ins, sizeof(float) * num_casts * 3,cudaMemcpyHostToDevice); 249 | // execute queries on the GPU, have to pass coordinate space conversion constants 250 | cuda_ray_marching_world_to_grid<<< CHUNK_SIZE / NUM_THREADS, NUM_THREADS >>>(d_ins,d_outs, d_distMap, width, height, max_range, 251 | num_casts, world_origin_x, world_origin_y, world_scale, inv_world_scale, world_sin_angle, world_cos_angle, rotation_const); 252 | err_check(); 253 | // copy results back to CPU 254 | cudaMemcpy(outs,d_outs,sizeof(float)*num_casts,cudaMemcpyDeviceToHost); 255 | cudaDeviceSynchronize(); 256 | #else 257 | std::cout << "GPU numpy_calc_range only works with ROS world to grid conversion enabled" << std::endl; 258 | #endif 259 | } 260 | 261 | 262 | // num_casts must be less than or equal to chunk size 263 | void RayMarchingCUDA::numpy_calc_range_angles(float * ins, float * angles, float * outs, int num_particles, int num_angles) { 264 | #if ROS_WORLD_TO_GRID_CONVERSION == 1 265 | // copy queries to GPU buffer 266 | cudaMemcpy(d_ins, ins, sizeof(float) * num_particles * 3,cudaMemcpyHostToDevice); 267 | // also copy angles to end of GPU buffer, this assumes there is enough space (which there should be) 268 | cudaMemcpy(&d_ins[num_particles * 3], angles, sizeof(float) * num_angles,cudaMemcpyHostToDevice); 269 | // execute queries on the GPU, have to pass coordinate space conversion constants 270 | cuda_ray_marching_angles_world_to_grid<<< CHUNK_SIZE / NUM_THREADS, NUM_THREADS >>>(d_ins,d_outs, d_distMap, width, height, max_range, 271 | num_particles, num_angles, world_origin_x, world_origin_y, world_scale, inv_world_scale, world_sin_angle, world_cos_angle, rotation_const); 272 | err_check(); 273 | // copy results back to CPU 274 | cudaMemcpy(outs,d_outs,sizeof(float)*num_particles*num_angles,cudaMemcpyDeviceToHost); 275 | cudaDeviceSynchronize(); 276 | #else 277 | std::cout << "GPU numpy_calc_range_angles only works with ROS world to grid conversion enabled" << std::endl; 278 | #endif 279 | } 280 | 281 | void RayMarchingCUDA::calc_range_repeat_angles_eval_sensor_model(float * ins, float * angles, float * obs, double * weights, int num_particles, int num_angles) { 282 | #if ROS_WORLD_TO_GRID_CONVERSION == 1 283 | std::cout << "Do not use calc_range_repeat_angles_eval_sensor_model for GPU, unimplemented" << std::endl; 284 | std::cout << "Instead use numpy_calc_range_angles followed by a standard sensor evaluation method." << std::endl; 285 | // if (!allocated_weights) { 286 | // cudaMalloc((void **)&d_weights, num_particles*num_angles*sizeof(double)); 287 | // allocated_weights = true; 288 | // } 289 | // // copy queries to GPU buffer 290 | // cudaMemcpy(d_ins, ins, sizeof(float) * num_particles * 3,cudaMemcpyHostToDevice); 291 | // // also copy angles to end of GPU buffer, this assumes there is enough space (which there should be) 292 | // cudaMemcpy(&d_ins[num_particles * 3], angles, sizeof(float) * num_angles,cudaMemcpyHostToDevice); 293 | 294 | // // execute queries on the GPU, have to pass coordinate space conversion constants 295 | // cuda_ray_marching_angles_world_to_grid<<< CHUNK_SIZE / NUM_THREADS, NUM_THREADS >>>(d_ins,d_outs, d_distMap, 296 | // width, height, max_range, num_particles, num_angles, world_origin_x, world_origin_y, 297 | // world_scale, inv_world_scale, world_sin_angle, world_cos_angle, rotation_const); 298 | 299 | // cudaMemcpy(d_ins, obs, sizeof(float) * num_angles,cudaMemcpyHostToDevice); 300 | 301 | // // read from sensor table 302 | // cuda_eval_sensor_table<<< CHUNK_SIZE / NUM_THREADS, NUM_THREADS >>>(d_ins, d_outs, d_weights, d_sensorTable, num_angles, num_particles, inv_world_scale, table_width); 303 | 304 | // cuda_eval_sensor_table<<< CHUNK_SIZE / NUM_THREADS, NUM_THREADS >>>(d_ins, d_outs, d_weights, d_sensorTable, num_angles, num_particles, inv_world_scale, table_width); 305 | // // cuda_eval_sensor_table(angles, d_sensorTable) 306 | // // multiplicatively accumulate weights on the GPU 307 | 308 | 309 | // // copy weights back to CPU 310 | // cudaMemcpy(weights,d_weights,sizeof(double)*num_particles,cudaMemcpyDeviceToHost); 311 | // cudaDeviceSynchronize(); 312 | #else 313 | std::cout << "GPU numpy_calc_range_angles only works with ROS world to grid conversion enabled" << std::endl; 314 | #endif 315 | } 316 | -------------------------------------------------------------------------------- /vendor/gflags/README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/gflags/gflags.svg?branch=master)](https://travis-ci.org/gflags/gflags) 2 | [![Build status](https://ci.appveyor.com/api/projects/status/4ctod566ysraus74/branch/master?svg=true)](https://ci.appveyor.com/project/schuhschuh/gflags/branch/master) 3 | 4 | The documentation of the gflags library is available online at https://gflags.github.io/gflags/. 5 | 6 | 25 November 2016 7 | ---------------- 8 | 9 | I've finally released gflags 2.2.0. 10 | 11 | This release adds support for use of the gflags library as external dependency 12 | not only in projects using CMake, but also [Bazel](https://bazel.build/), 13 | or [pkg-config](https://www.freedesktop.org/wiki/Software/pkg-config/). 14 | One new minor feature is added in this release: when a command flag argument 15 | contains dashes, these are implicitly converted to underscores. 16 | This is to allow those used to separate words of the flag name by dashes 17 | to do so, while the flag variable names are required to use underscores. 18 | 19 | Memory leaks reported by valgrind should be resolved by this release. 20 | This release fixes build errors with MS Visual Studio 2015. 21 | 22 | Please report any further issues with this release using the GitHub issue tracker. 23 | 24 | 25 | 24 March 2015 26 | ------------- 27 | 28 | I've just released gflags 2.1.2. 29 | 30 | This release completes the namespace change fixes. In particular, 31 | it restores binary ABI compatibility with release version 2.0. 32 | The deprecated "google" namespace is by default still kept as 33 | primary namespace while symbols are imported into the new "gflags" namespace. 34 | This can be overridden using the CMake variable GFLAGS_NAMESPACE. 35 | 36 | Other fixes of the build configuration are related to the (patched) 37 | CMake modules FindThreads.cmake and CheckTypeSize.cmake. These have 38 | been removed and instead the C language is enabled again even though 39 | gflags is written in C++ only. 40 | 41 | This release also marks the complete move of the gflags project 42 | from Google Code to GitHub. Email addresses of original issue 43 | reporters got lost in the process. Given the age of most issue reports, 44 | this should be negligable. 45 | 46 | Please report any further issues using the GitHub issue tracker. 47 | 48 | 49 | 30 March 2014 50 | ------------- 51 | 52 | I've just released gflags 2.1.1. 53 | 54 | This release fixes a few bugs in the configuration of gflags\_declare.h 55 | and adds a separate GFLAGS\_INCLUDE\_DIR CMake variable to the build configuration. 56 | Setting GFLAGS\_NAMESPACE to "google" no longer changes also the include 57 | path of the public header files. This allows the use of the library with 58 | other Google projects such as glog which still use the deprecated "google" 59 | namespace for the gflags library, but include it as "gflags/gflags.h". 60 | 61 | 20 March 2014 62 | ------------- 63 | 64 | I've just released gflags 2.1. 65 | 66 | The major changes are the use of CMake for the build configuration instead 67 | of the autotools and packaging support through CPack. The default namespace 68 | of all C++ symbols is now "gflags" instead of "google". This can be 69 | configured via the GFLAGS\_NAMESPACE variable. 70 | 71 | This release compiles with all major compilers without warnings and passed 72 | the unit tests on Ubuntu 12.04, Windows 7 (Visual Studio 2008 and 2010, 73 | Cygwin, MinGW), and Mac OS X (Xcode 5.1). 74 | 75 | The SVN repository on Google Code is now frozen and replaced by a Git 76 | repository such that it can be used as Git submodule by projects. The main 77 | hosting of this project remains at Google Code. Thanks to the distributed 78 | character of Git, I can push (and pull) changes from both GitHub and Google Code 79 | in order to keep the two public repositories in sync. 80 | When fixing an issue for a pull request through either of these hosting 81 | platforms, please reference the issue number as 82 | [described here](https://code.google.com/p/support/wiki/IssueTracker#Integration_with_version_control). 83 | For the further development, I am following the 84 | [Git branching model](http://nvie.com/posts/a-successful-git-branching-model/) 85 | with feature branch names prefixed by "feature/" and bugfix branch names 86 | prefixed by "bugfix/", respectively. 87 | 88 | Binary and source [packages](https://github.com/schuhschuh/gflags/releases) are available on GitHub. 89 | 90 | 91 | 14 January 2014 92 | --------------- 93 | 94 | The migration of the build system to CMake is almost complete. 95 | What remains to be done is rewriting the tests in Python such they can be 96 | executed on non-Unix platforms and splitting them up into separate CTest tests. 97 | Though merging these changes into the master branch yet remains to be done, 98 | it is recommended to already start using the 99 | [cmake-migration](https://github.com/schuhschuh/gflags/tree/cmake-migration) branch. 100 | 101 | 102 | 20 April 2013 103 | ------------- 104 | 105 | More than a year has past since I (Andreas) took over the maintenance for 106 | `gflags`. Only few minor changes have been made since then, much to my regret. 107 | To get more involved and stimulate participation in the further 108 | development of the library, I moved the project source code today to 109 | [GitHub](https://github.com/schuhschuh/gflags). 110 | I believe that the strengths of [Git](http://git-scm.com/) will allow for better community collaboration 111 | as well as ease the integration of changes made by others. I encourage everyone 112 | who would like to contribute to send me pull requests. 113 | Git's lightweight feature branches will also provide the right tool for more 114 | radical changes which should only be merged back into the master branch 115 | after these are complete and implement the desired behavior. 116 | 117 | The SVN repository remains accessible at Google Code and I will keep the 118 | master branch of the Git repository hosted at GitHub and the trunk of the 119 | Subversion repository synchronized. Initially, I was going to simply switch the 120 | Google Code project to Git, but in this case the SVN repository would be 121 | frozen and force everyone who would like the latest development changes to 122 | use Git as well. Therefore I decided to host the public Git repository at GitHub 123 | instead. 124 | 125 | Please continue to report any issues with gflags on Google Code. The GitHub project will 126 | only be used to host the Git repository. 127 | 128 | One major change of the project structure I have in mind for the next weeks 129 | is the migration from autotools to [CMake](http://www.cmake.org/). 130 | Check out the (unstable!) 131 | [cmake-migration](https://github.com/schuhschuh/gflags/tree/cmake-migration) 132 | branch on GitHub for details. 133 | 134 | 135 | 25 January 2012 136 | --------------- 137 | 138 | I've just released gflags 2.0. 139 | 140 | The `google-gflags` project has been renamed to `gflags`. I 141 | (csilvers) am stepping down as maintainer, to be replaced by Andreas 142 | Schuh. Welcome to the team, Andreas! I've seen the energy you have 143 | around gflags and the ideas you have for the project going forward, 144 | and look forward to having you on the team. 145 | 146 | I bumped the major version number up to 2 to reflect the new community 147 | ownership of the project. All the [changes](ChangeLog.txt) 148 | are related to the renaming. There are no functional changes from 149 | gflags 1.7. In particular, I've kept the code in the namespace 150 | `google`, though in a future version it should be renamed to `gflags`. 151 | I've also kept the `/usr/local/include/google/` subdirectory as 152 | synonym of `/usr/local/include/gflags/`, though the former name has 153 | been obsolete for some time now. 154 | 155 | 156 | 18 January 2011 157 | --------------- 158 | 159 | The `google-gflags` Google Code page has been renamed to 160 | `gflags`, in preparation for the project being renamed to 161 | `gflags`. In the coming weeks, I'll be stepping down as 162 | maintainer for the gflags project, and as part of that Google is 163 | relinquishing ownership of the project; it will now be entirely 164 | community run. The name change reflects that shift. 165 | 166 | 167 | 20 December 2011 168 | ---------------- 169 | 170 | I've just released gflags 1.7. This is a minor release; the major 171 | change is that `CommandLineFlagInfo` now exports the address in memory 172 | where the flag is located. There has also been a bugfix involving 173 | very long --help strings, and some other minor [changes](ChangeLog.txt). 174 | 175 | 29 July 2011 176 | ------------ 177 | 178 | I've just released gflags 1.6. The major new feature in this release 179 | is support for setting version info, so that --version does something 180 | useful. 181 | 182 | One minor change has required bumping the library number: 183 | `ReparseCommandlineFlags` now returns `void` instead of `int` (the int 184 | return value was always meaningless). Though I doubt anyone ever used 185 | this (meaningless) return value, technically it's a change to the ABI 186 | that requires a version bump. A bit sad. 187 | 188 | There's also a procedural change with this release: I've changed the 189 | internal tools used to integrate Google-supplied patches for gflags 190 | into the opensource release. These new tools should result in more 191 | frequent updates with better change descriptions. They will also 192 | result in future `ChangeLog` entries being much more verbose (for better 193 | or for worse). 194 | 195 | See the [ChangeLog](ChangeLog.txt) for a full list of changes for this release. 196 | 197 | 24 January 2011 198 | --------------- 199 | 200 | I've just released gflags 1.5. This release has only minor changes 201 | from 1.4, including some slightly better reporting in --help, and 202 | an new memory-cleanup function that can help when running gflags-using 203 | libraries under valgrind. The major change is to fix up the macros 204 | (`DEFINE_bool` and the like) to work more reliably inside namespaces. 205 | 206 | If you have not had a problem with these macros, and don't need any of 207 | the other changes described, there is no need to upgrade. See the 208 | [ChangeLog](ChangeLog.txt) for a full list of changes for this release. 209 | 210 | 11 October 2010 211 | --------------- 212 | 213 | I've just released gflags 1.4. This release has only minor changes 214 | from 1.3, including some documentation tweaks and some work to make 215 | the library smaller. If 1.3 is working well for you, there's no 216 | particular reason to upgrade. 217 | 218 | 4 January 2010 219 | -------------- 220 | 221 | I've just released gflags 1.3. gflags now compiles under MSVC, and 222 | all tests pass. I **really** never thought non-unix-y Windows folks 223 | would want gflags, but at least some of them do. 224 | 225 | The major news, though, is that I've separated out the python package 226 | into its own library, [python-gflags](http://code.google.com/p/python-gflags). 227 | If you're interested in the Python version of gflags, that's the place to 228 | get it now. 229 | 230 | 10 September 2009 231 | ----------------- 232 | 233 | I've just released gflags 1.2. The major change from gflags 1.1 is it 234 | now compiles under MinGW (as well as cygwin), and all tests pass. I 235 | never thought Windows folks would want unix-style command-line flags, 236 | since they're so different from the Windows style, but I guess I was 237 | wrong! 238 | 239 | The other changes are minor, such as support for --htmlxml in the 240 | python version of gflags. 241 | 242 | 15 April 2009 243 | ------------- 244 | 245 | I've just released gflags 1.1. It has only minor changes fdrom gflags 246 | 1.0 (see the [ChangeLog](ChangeLog.txt) for details). 247 | The major change is that I moved to a new system for creating .deb and .rpm files. 248 | This allows me to create x86\_64 deb and rpm files. 249 | 250 | In the process of moving to this new system, I noticed an 251 | inconsistency: the tar.gz and .rpm files created libraries named 252 | libgflags.so, but the deb file created libgoogle-gflags.so. I have 253 | fixed the deb file to create libraries like the others. I'm no expert 254 | in debian packaging, but I believe this has caused the package name to 255 | change as well. Please let me know (at 256 | [[mailto:google-gflags@googlegroups.com](mailto:google-gflags@googlegroups.com) 257 | google-gflags@googlegroups.com]) if this causes problems for you -- 258 | especially if you know of a fix! I would be happy to change the deb 259 | packages to add symlinks from the old library name to the new 260 | (libgoogle-gflags.so -> libgflags.so), but that is beyond my knowledge 261 | of how to make .debs. 262 | 263 | If you've tried to install a .rpm or .deb and it doesn't work for you, 264 | let me know. I'm excited to finally have 64-bit package files, but 265 | there may still be some wrinkles in the new system to iron out. 266 | 267 | 1 October 2008 268 | -------------- 269 | 270 | gflags 1.0rc2 was out for a few weeks without any issues, so gflags 271 | 1.0 is now released. This is much like gflags 0.9. The major change 272 | is that the .h files have been moved from `/usr/include/google` to 273 | `/usr/include/gflags`. While I have backwards-compatibility 274 | forwarding headeds in place, please rewrite existing code to say 275 | ``` 276 | #include 277 | ``` 278 | instead of 279 | ``` 280 | #include 281 | ``` 282 | 283 | I've kept the default namespace to google. You can still change with 284 | with the appropriate flag to the configure script (`./configure 285 | --help` to see the flags). If you have feedback as to whether the 286 | default namespace should change to gflags, which would be a 287 | non-backwards-compatible change, send mail to 288 | `google-gflags@googlegroups.com`! 289 | 290 | Version 1.0 also has some neat new features, like support for bash 291 | commandline-completion of help flags. See the [ChangeLog](ChangeLog.txt) 292 | for more details. 293 | 294 | If I don't hear any bad news for a few weeks, I'll release 1.0-final. 295 | -------------------------------------------------------------------------------- /vendor/gflags/src/util.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2011, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // --- 30 | // 31 | // Some generically useful utility routines that in google-land would 32 | // be their own projects. We make a shortened version here. 33 | 34 | #ifndef GFLAGS_UTIL_H_ 35 | #define GFLAGS_UTIL_H_ 36 | 37 | #include "config.h" 38 | 39 | #include 40 | #ifdef HAVE_INTTYPES_H 41 | # include 42 | #endif 43 | #include // for va_* 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #ifdef HAVE_SYS_STAT_H 50 | # include // for mkdir 51 | #endif 52 | 53 | 54 | namespace GFLAGS_NAMESPACE { 55 | 56 | 57 | // This is used for unittests for death-testing. It is defined in gflags.cc. 58 | extern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int); 59 | 60 | // Work properly if either strtoll or strtoq is on this system. 61 | #if defined(strtoll) || defined(HAVE_STRTOLL) 62 | # define strto64 strtoll 63 | # define strtou64 strtoull 64 | #elif defined(HAVE_STRTOQ) 65 | # define strto64 strtoq 66 | # define strtou64 strtouq 67 | // Neither strtoll nor strtoq are defined. I hope strtol works! 68 | #else 69 | # define strto64 strtol 70 | # define strtou64 strtoul 71 | #endif 72 | 73 | // If we have inttypes.h, it will have defined PRId32/etc for us. 74 | // If not, take our best guess. 75 | #ifndef PRId32 76 | # define PRId32 "d" 77 | #endif 78 | #ifndef PRId64 79 | # define PRId64 "lld" 80 | #endif 81 | #ifndef PRIu64 82 | # define PRIu64 "llu" 83 | #endif 84 | 85 | typedef signed char int8; 86 | typedef unsigned char uint8; 87 | 88 | // -- utility macros --------------------------------------------------------- 89 | 90 | template struct CompileAssert; 91 | template <> struct CompileAssert {}; 92 | #define COMPILE_ASSERT(expr, msg) \ 93 | enum { assert_##msg = sizeof(CompileAssert) } 94 | 95 | // Returns the number of elements in an array. 96 | #define arraysize(arr) (sizeof(arr)/sizeof(*(arr))) 97 | 98 | 99 | // -- logging and testing --------------------------------------------------- 100 | 101 | // For now, we ignore the level for logging, and don't show *VLOG's at 102 | // all, except by hand-editing the lines below 103 | #define LOG(level) std::cerr 104 | #define VLOG(level) if (true) {} else std::cerr 105 | #define DVLOG(level) if (true) {} else std::cerr 106 | 107 | // CHECK dies with a fatal error if condition is not true. It is *not* 108 | // controlled by NDEBUG, so the check will be executed regardless of 109 | // compilation mode. Therefore, it is safe to do things like: 110 | // CHECK(fp->Write(x) == 4) 111 | // We allow stream-like objects after this for debugging, but they're ignored. 112 | #define EXPECT_TRUE(condition) \ 113 | if (true) { \ 114 | if (!(condition)) { \ 115 | fprintf(stderr, "Check failed: %s\n", #condition); \ 116 | exit(1); \ 117 | } \ 118 | } else std::cerr << "" 119 | 120 | #define EXPECT_OP(op, val1, val2) \ 121 | if (true) { \ 122 | if (!((val1) op (val2))) { \ 123 | fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \ 124 | exit(1); \ 125 | } \ 126 | } else std::cerr << "" 127 | 128 | #define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2) 129 | #define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2) 130 | #define EXPECT_LE(val1, val2) EXPECT_OP(<=, val1, val2) 131 | #define EXPECT_LT(val1, val2) EXPECT_OP(< , val1, val2) 132 | #define EXPECT_GE(val1, val2) EXPECT_OP(>=, val1, val2) 133 | #define EXPECT_GT(val1, val2) EXPECT_OP(> , val1, val2) 134 | #define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond)) 135 | 136 | // C99 declares isnan and isinf should be macros, so the #ifdef test 137 | // should be reliable everywhere. Of course, it's not, but these 138 | // are testing pertty marginal functionality anyway, so it's ok to 139 | // not-run them even in situations they might, with effort, be made to work. 140 | #ifdef isnan // Some compilers, like sun's for Solaris 10, don't define this 141 | #define EXPECT_NAN(arg) \ 142 | do { \ 143 | if (!isnan(arg)) { \ 144 | fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \ 145 | exit(1); \ 146 | } \ 147 | } while (0) 148 | #else 149 | #define EXPECT_NAN(arg) 150 | #endif 151 | 152 | #ifdef isinf // Some compilers, like sun's for Solaris 10, don't define this 153 | #define EXPECT_INF(arg) \ 154 | do { \ 155 | if (!isinf(arg)) { \ 156 | fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \ 157 | exit(1); \ 158 | } \ 159 | } while (0) 160 | #else 161 | #define EXPECT_INF(arg) 162 | #endif 163 | 164 | #define EXPECT_DOUBLE_EQ(val1, val2) \ 165 | do { \ 166 | if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \ 167 | fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \ 168 | exit(1); \ 169 | } \ 170 | } while (0) 171 | 172 | #define EXPECT_STREQ(val1, val2) \ 173 | do { \ 174 | if (strcmp((val1), (val2)) != 0) { \ 175 | fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \ 176 | exit(1); \ 177 | } \ 178 | } while (0) 179 | 180 | // Call this in a .cc file where you will later call RUN_ALL_TESTS in main(). 181 | #define TEST_INIT \ 182 | static std::vector g_testlist; /* the tests to run */ \ 183 | static int RUN_ALL_TESTS() { \ 184 | std::vector::const_iterator it; \ 185 | for (it = g_testlist.begin(); it != g_testlist.end(); ++it) { \ 186 | (*it)(); /* The test will error-exit if there's a problem. */ \ 187 | } \ 188 | fprintf(stderr, "\nPassed %d tests\n\nPASS\n", \ 189 | static_cast(g_testlist.size())); \ 190 | return 0; \ 191 | } 192 | 193 | // Note that this macro uses a FlagSaver to keep tests isolated. 194 | #define TEST(a, b) \ 195 | struct Test_##a##_##b { \ 196 | Test_##a##_##b() { g_testlist.push_back(&Run); } \ 197 | static void Run() { \ 198 | FlagSaver fs; \ 199 | fprintf(stderr, "Running test %s/%s\n", #a, #b); \ 200 | RunTest(); \ 201 | } \ 202 | static void RunTest(); \ 203 | }; \ 204 | static Test_##a##_##b g_test_##a##_##b; \ 205 | void Test_##a##_##b::RunTest() 206 | 207 | // This is a dummy class that eases the google->opensource transition. 208 | namespace testing { 209 | class Test {}; 210 | } 211 | 212 | // Call this in a .cc file where you will later call EXPECT_DEATH 213 | #define EXPECT_DEATH_INIT \ 214 | static bool g_called_exit; \ 215 | static void CalledExit(int) { g_called_exit = true; } 216 | 217 | #define EXPECT_DEATH(fn, msg) \ 218 | do { \ 219 | g_called_exit = false; \ 220 | gflags_exitfunc = &CalledExit; \ 221 | fn; \ 222 | gflags_exitfunc = &exit; /* set back to its default */ \ 223 | if (!g_called_exit) { \ 224 | fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \ 225 | exit(1); \ 226 | } \ 227 | } while (0) 228 | 229 | #define GTEST_HAS_DEATH_TEST 1 230 | 231 | // -- path routines ---------------------------------------------------------- 232 | 233 | // Tries to create the directory path as a temp-dir. If it fails, 234 | // changes path to some directory it *can* create. 235 | #if defined(__MINGW32__) 236 | #include 237 | inline void MakeTmpdir(std::string* path) { 238 | if (!path->empty()) { 239 | path->append("/gflags_unittest_testdir"); 240 | int err = mkdir(path->c_str()); 241 | if (err == 0 || errno == EEXIST) return; 242 | } 243 | // I had trouble creating a directory in /tmp from mingw 244 | *path = "./gflags_unittest"; 245 | mkdir(path->c_str()); 246 | } 247 | #elif defined(_MSC_VER) 248 | #include 249 | inline void MakeTmpdir(std::string* path) { 250 | if (!path->empty()) { 251 | int err = _mkdir(path->c_str()); 252 | if (err == 0 || errno == EEXIST) return; 253 | } 254 | char tmppath_buffer[1024]; 255 | int tmppath_len = GetTempPathA(sizeof(tmppath_buffer), tmppath_buffer); 256 | assert(tmppath_len > 0 && tmppath_len < sizeof(tmppath_buffer)); 257 | assert(tmppath_buffer[tmppath_len - 1] == '\\'); // API guarantees it 258 | *path = std::string(tmppath_buffer) + "gflags_unittest"; 259 | _mkdir(path->c_str()); 260 | } 261 | #else 262 | inline void MakeTmpdir(std::string* path) { 263 | if (!path->empty()) { 264 | int err = mkdir(path->c_str(), 0755); 265 | if (err == 0 || errno == EEXIST) return; 266 | } 267 | mkdir("/tmp/gflags_unittest", 0755); 268 | } 269 | #endif 270 | 271 | // -- string routines -------------------------------------------------------- 272 | 273 | inline void InternalStringPrintf(std::string* output, const char* format, 274 | va_list ap) { 275 | char space[128]; // try a small buffer and hope it fits 276 | 277 | // It's possible for methods that use a va_list to invalidate 278 | // the data in it upon use. The fix is to make a copy 279 | // of the structure before using it and use that copy instead. 280 | va_list backup_ap; 281 | va_copy(backup_ap, ap); 282 | int bytes_written = vsnprintf(space, sizeof(space), format, backup_ap); 283 | va_end(backup_ap); 284 | 285 | if ((bytes_written >= 0) && (static_cast(bytes_written) < sizeof(space))) { 286 | output->append(space, bytes_written); 287 | return; 288 | } 289 | 290 | // Repeatedly increase buffer size until it fits. 291 | int length = sizeof(space); 292 | while (true) { 293 | if (bytes_written < 0) { 294 | // Older snprintf() behavior. :-( Just try doubling the buffer size 295 | length *= 2; 296 | } else { 297 | // We need exactly "bytes_written+1" characters 298 | length = bytes_written+1; 299 | } 300 | char* buf = new char[length]; 301 | 302 | // Restore the va_list before we use it again 303 | va_copy(backup_ap, ap); 304 | bytes_written = vsnprintf(buf, length, format, backup_ap); 305 | va_end(backup_ap); 306 | 307 | if ((bytes_written >= 0) && (bytes_written < length)) { 308 | output->append(buf, bytes_written); 309 | delete[] buf; 310 | return; 311 | } 312 | delete[] buf; 313 | } 314 | } 315 | 316 | // Clears output before writing to it. 317 | inline void SStringPrintf(std::string* output, const char* format, ...) { 318 | va_list ap; 319 | va_start(ap, format); 320 | output->clear(); 321 | InternalStringPrintf(output, format, ap); 322 | va_end(ap); 323 | } 324 | 325 | inline void StringAppendF(std::string* output, const char* format, ...) { 326 | va_list ap; 327 | va_start(ap, format); 328 | InternalStringPrintf(output, format, ap); 329 | va_end(ap); 330 | } 331 | 332 | inline std::string StringPrintf(const char* format, ...) { 333 | va_list ap; 334 | va_start(ap, format); 335 | std::string output; 336 | InternalStringPrintf(&output, format, ap); 337 | va_end(ap); 338 | return output; 339 | } 340 | 341 | inline bool SafeGetEnv(const char *varname, std::string &valstr) 342 | { 343 | #if defined(_MSC_VER) && _MSC_VER >= 1400 344 | char *val; 345 | size_t sz; 346 | if (_dupenv_s(&val, &sz, varname) != 0 || !val) return false; 347 | valstr = val; 348 | free(val); 349 | #else 350 | const char * const val = getenv(varname); 351 | if (!val) return false; 352 | valstr = val; 353 | #endif 354 | return true; 355 | } 356 | 357 | inline int SafeFOpen(FILE **fp, const char* fname, const char *mode) 358 | { 359 | #if defined(_MSC_VER) && _MSC_VER >= 1400 360 | return fopen_s(fp, fname, mode); 361 | #else 362 | assert(fp != NULL); 363 | *fp = fopen(fname, mode); 364 | // errno only guaranteed to be set on failure 365 | return ((*fp == NULL) ? errno : 0); 366 | #endif 367 | } 368 | 369 | 370 | } // namespace GFLAGS_NAMESPACE 371 | 372 | 373 | #endif // GFLAGS_UTIL_H_ 374 | -------------------------------------------------------------------------------- /vendor/gflags/src/mutex.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Google Inc. 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | // 30 | // --- 31 | // 32 | // A simple mutex wrapper, supporting locks and read-write locks. 33 | // You should assume the locks are *not* re-entrant. 34 | // 35 | // This class is meant to be internal-only and should be wrapped by an 36 | // internal namespace. Before you use this module, please give the 37 | // name of your internal namespace for this module. Or, if you want 38 | // to expose it, you'll want to move it to the Google namespace. We 39 | // cannot put this class in global namespace because there can be some 40 | // problems when we have multiple versions of Mutex in each shared object. 41 | // 42 | // NOTE: by default, we have #ifdef'ed out the TryLock() method. 43 | // This is for two reasons: 44 | // 1) TryLock() under Windows is a bit annoying (it requires a 45 | // #define to be defined very early). 46 | // 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG 47 | // mode. 48 | // If you need TryLock(), and either these two caveats are not a 49 | // problem for you, or you're willing to work around them, then 50 | // feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs 51 | // in the code below. 52 | // 53 | // CYGWIN NOTE: Cygwin support for rwlock seems to be buggy: 54 | // http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html 55 | // Because of that, we might as well use windows locks for 56 | // cygwin. They seem to be more reliable than the cygwin pthreads layer. 57 | // 58 | // TRICKY IMPLEMENTATION NOTE: 59 | // This class is designed to be safe to use during 60 | // dynamic-initialization -- that is, by global constructors that are 61 | // run before main() starts. The issue in this case is that 62 | // dynamic-initialization happens in an unpredictable order, and it 63 | // could be that someone else's dynamic initializer could call a 64 | // function that tries to acquire this mutex -- but that all happens 65 | // before this mutex's constructor has run. (This can happen even if 66 | // the mutex and the function that uses the mutex are in the same .cc 67 | // file.) Basically, because Mutex does non-trivial work in its 68 | // constructor, it's not, in the naive implementation, safe to use 69 | // before dynamic initialization has run on it. 70 | // 71 | // The solution used here is to pair the actual mutex primitive with a 72 | // bool that is set to true when the mutex is dynamically initialized. 73 | // (Before that it's false.) Then we modify all mutex routines to 74 | // look at the bool, and not try to lock/unlock until the bool makes 75 | // it to true (which happens after the Mutex constructor has run.) 76 | // 77 | // This works because before main() starts -- particularly, during 78 | // dynamic initialization -- there are no threads, so a) it's ok that 79 | // the mutex operations are a no-op, since we don't need locking then 80 | // anyway; and b) we can be quite confident our bool won't change 81 | // state between a call to Lock() and a call to Unlock() (that would 82 | // require a global constructor in one translation unit to call Lock() 83 | // and another global constructor in another translation unit to call 84 | // Unlock() later, which is pretty perverse). 85 | // 86 | // That said, it's tricky, and can conceivably fail; it's safest to 87 | // avoid trying to acquire a mutex in a global constructor, if you 88 | // can. One way it can fail is that a really smart compiler might 89 | // initialize the bool to true at static-initialization time (too 90 | // early) rather than at dynamic-initialization time. To discourage 91 | // that, we set is_safe_ to true in code (not the constructor 92 | // colon-initializer) and set it to true via a function that always 93 | // evaluates to true, but that the compiler can't know always 94 | // evaluates to true. This should be good enough. 95 | // 96 | // A related issue is code that could try to access the mutex 97 | // after it's been destroyed in the global destructors (because 98 | // the Mutex global destructor runs before some other global 99 | // destructor, that tries to acquire the mutex). The way we 100 | // deal with this is by taking a constructor arg that global 101 | // mutexes should pass in, that causes the destructor to do no 102 | // work. We still depend on the compiler not doing anything 103 | // weird to a Mutex's memory after it is destroyed, but for a 104 | // static global variable, that's pretty safe. 105 | 106 | #ifndef GFLAGS_MUTEX_H_ 107 | #define GFLAGS_MUTEX_H_ 108 | 109 | #include "gflags/gflags_declare.h" // to figure out pthreads support 110 | 111 | #if defined(NO_THREADS) 112 | typedef int MutexType; // to keep a lock-count 113 | #elif defined(OS_WINDOWS) 114 | # ifndef WIN32_LEAN_AND_MEAN 115 | # define WIN32_LEAN_AND_MEAN // We only need minimal includes 116 | # endif 117 | # ifndef NOMINMAX 118 | # define NOMINMAX // Don't want windows to override min()/max() 119 | # endif 120 | # ifdef GMUTEX_TRYLOCK 121 | // We need Windows NT or later for TryEnterCriticalSection(). If you 122 | // don't need that functionality, you can remove these _WIN32_WINNT 123 | // lines, and change TryLock() to assert(0) or something. 124 | # ifndef _WIN32_WINNT 125 | # define _WIN32_WINNT 0x0400 126 | # endif 127 | # endif 128 | # include 129 | typedef CRITICAL_SECTION MutexType; 130 | #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) 131 | // Needed for pthread_rwlock_*. If it causes problems, you could take it 132 | // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it 133 | // *does* cause problems for FreeBSD, or MacOSX, but isn't needed 134 | // for locking there.) 135 | # ifdef __linux__ 136 | # if _XOPEN_SOURCE < 500 // including not being defined at all 137 | # undef _XOPEN_SOURCE 138 | # define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls 139 | # endif 140 | # endif 141 | # include 142 | typedef pthread_rwlock_t MutexType; 143 | #elif defined(HAVE_PTHREAD) 144 | # include 145 | typedef pthread_mutex_t MutexType; 146 | #else 147 | # error Need to implement mutex.h for your architecture, or #define NO_THREADS 148 | #endif 149 | 150 | #include 151 | #include // for abort() 152 | 153 | #define MUTEX_NAMESPACE gflags_mutex_namespace 154 | 155 | namespace MUTEX_NAMESPACE { 156 | 157 | class Mutex { 158 | public: 159 | // This is used for the single-arg constructor 160 | enum LinkerInitialized { LINKER_INITIALIZED }; 161 | 162 | // Create a Mutex that is not held by anybody. This constructor is 163 | // typically used for Mutexes allocated on the heap or the stack. 164 | inline Mutex(); 165 | // This constructor should be used for global, static Mutex objects. 166 | // It inhibits work being done by the destructor, which makes it 167 | // safer for code that tries to acqiure this mutex in their global 168 | // destructor. 169 | inline Mutex(LinkerInitialized); 170 | 171 | // Destructor 172 | inline ~Mutex(); 173 | 174 | inline void Lock(); // Block if needed until free then acquire exclusively 175 | inline void Unlock(); // Release a lock acquired via Lock() 176 | #ifdef GMUTEX_TRYLOCK 177 | inline bool TryLock(); // If free, Lock() and return true, else return false 178 | #endif 179 | // Note that on systems that don't support read-write locks, these may 180 | // be implemented as synonyms to Lock() and Unlock(). So you can use 181 | // these for efficiency, but don't use them anyplace where being able 182 | // to do shared reads is necessary to avoid deadlock. 183 | inline void ReaderLock(); // Block until free or shared then acquire a share 184 | inline void ReaderUnlock(); // Release a read share of this Mutex 185 | inline void WriterLock() { Lock(); } // Acquire an exclusive lock 186 | inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() 187 | 188 | private: 189 | MutexType mutex_; 190 | // We want to make sure that the compiler sets is_safe_ to true only 191 | // when we tell it to, and never makes assumptions is_safe_ is 192 | // always true. volatile is the most reliable way to do that. 193 | volatile bool is_safe_; 194 | // This indicates which constructor was called. 195 | bool destroy_; 196 | 197 | inline void SetIsSafe() { is_safe_ = true; } 198 | 199 | // Catch the error of writing Mutex when intending MutexLock. 200 | Mutex(Mutex* /*ignored*/) {} 201 | // Disallow "evil" constructors 202 | Mutex(const Mutex&); 203 | void operator=(const Mutex&); 204 | }; 205 | 206 | // Now the implementation of Mutex for various systems 207 | #if defined(NO_THREADS) 208 | 209 | // When we don't have threads, we can be either reading or writing, 210 | // but not both. We can have lots of readers at once (in no-threads 211 | // mode, that's most likely to happen in recursive function calls), 212 | // but only one writer. We represent this by having mutex_ be -1 when 213 | // writing and a number > 0 when reading (and 0 when no lock is held). 214 | // 215 | // In debug mode, we assert these invariants, while in non-debug mode 216 | // we do nothing, for efficiency. That's why everything is in an 217 | // assert. 218 | 219 | Mutex::Mutex() : mutex_(0) { } 220 | Mutex::Mutex(Mutex::LinkerInitialized) : mutex_(0) { } 221 | Mutex::~Mutex() { assert(mutex_ == 0); } 222 | void Mutex::Lock() { assert(--mutex_ == -1); } 223 | void Mutex::Unlock() { assert(mutex_++ == -1); } 224 | #ifdef GMUTEX_TRYLOCK 225 | bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } 226 | #endif 227 | void Mutex::ReaderLock() { assert(++mutex_ > 0); } 228 | void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } 229 | 230 | #elif defined(OS_WINDOWS) 231 | 232 | Mutex::Mutex() : destroy_(true) { 233 | InitializeCriticalSection(&mutex_); 234 | SetIsSafe(); 235 | } 236 | Mutex::Mutex(LinkerInitialized) : destroy_(false) { 237 | InitializeCriticalSection(&mutex_); 238 | SetIsSafe(); 239 | } 240 | Mutex::~Mutex() { if (destroy_) DeleteCriticalSection(&mutex_); } 241 | void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); } 242 | void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); } 243 | #ifdef GMUTEX_TRYLOCK 244 | bool Mutex::TryLock() { return is_safe_ ? 245 | TryEnterCriticalSection(&mutex_) != 0 : true; } 246 | #endif 247 | void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks 248 | void Mutex::ReaderUnlock() { Unlock(); } 249 | 250 | #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) 251 | 252 | #define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ 253 | if (is_safe_ && fncall(&mutex_) != 0) abort(); \ 254 | } while (0) 255 | 256 | Mutex::Mutex() : destroy_(true) { 257 | SetIsSafe(); 258 | if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); 259 | } 260 | Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) { 261 | SetIsSafe(); 262 | if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); 263 | } 264 | Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); } 265 | void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } 266 | void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } 267 | #ifdef GMUTEX_TRYLOCK 268 | bool Mutex::TryLock() { return is_safe_ ? 269 | pthread_rwlock_trywrlock(&mutex_) == 0 : true; } 270 | #endif 271 | void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } 272 | void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } 273 | #undef SAFE_PTHREAD 274 | 275 | #elif defined(HAVE_PTHREAD) 276 | 277 | #define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ 278 | if (is_safe_ && fncall(&mutex_) != 0) abort(); \ 279 | } while (0) 280 | 281 | Mutex::Mutex() : destroy_(true) { 282 | SetIsSafe(); 283 | if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); 284 | } 285 | Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) { 286 | SetIsSafe(); 287 | if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); 288 | } 289 | Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); } 290 | void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } 291 | void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } 292 | #ifdef GMUTEX_TRYLOCK 293 | bool Mutex::TryLock() { return is_safe_ ? 294 | pthread_mutex_trylock(&mutex_) == 0 : true; } 295 | #endif 296 | void Mutex::ReaderLock() { Lock(); } 297 | void Mutex::ReaderUnlock() { Unlock(); } 298 | #undef SAFE_PTHREAD 299 | 300 | #endif 301 | 302 | // -------------------------------------------------------------------------- 303 | // Some helper classes 304 | 305 | // MutexLock(mu) acquires mu when constructed and releases it when destroyed. 306 | class MutexLock { 307 | public: 308 | explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } 309 | ~MutexLock() { mu_->Unlock(); } 310 | private: 311 | Mutex * const mu_; 312 | // Disallow "evil" constructors 313 | MutexLock(const MutexLock&); 314 | void operator=(const MutexLock&); 315 | }; 316 | 317 | // ReaderMutexLock and WriterMutexLock do the same, for rwlocks 318 | class ReaderMutexLock { 319 | public: 320 | explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } 321 | ~ReaderMutexLock() { mu_->ReaderUnlock(); } 322 | private: 323 | Mutex * const mu_; 324 | // Disallow "evil" constructors 325 | ReaderMutexLock(const ReaderMutexLock&); 326 | void operator=(const ReaderMutexLock&); 327 | }; 328 | 329 | class WriterMutexLock { 330 | public: 331 | explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } 332 | ~WriterMutexLock() { mu_->WriterUnlock(); } 333 | private: 334 | Mutex * const mu_; 335 | // Disallow "evil" constructors 336 | WriterMutexLock(const WriterMutexLock&); 337 | void operator=(const WriterMutexLock&); 338 | }; 339 | 340 | // Catch bug where variable name is omitted, e.g. MutexLock (&mu); 341 | #define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name) 342 | #define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name) 343 | #define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name) 344 | 345 | } // namespace MUTEX_NAMESPACE 346 | 347 | 348 | #endif /* #define GFLAGS_MUTEX_H__ */ 349 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RangeLibc 2 | 3 | This library provides for different implementations of 2D raycasting for 2D occupancy grids, including the Compressed Directional Distance Transform (CDDT) algorithm as proposed in [this publication](http://arxiv.org/abs/1705.01167). The code is written and optimized in C++, and Python wrappers are also provided. 4 | 5 | WARNING: this is currently in a slightly weird state in preparation for 6.141 lab 5. I will try to fix up all the compile flags to work with both use cases soon. 6 | 7 | ## Building the Code 8 | 9 | The following has been tested on Ubuntu 14.04, OSX 10.10, and Ubuntu 16.06. Hopefully it will work on other systems as well, or will at least be not too difficult to fix. 10 | 11 | ### C++ code 12 | 13 | ``` 14 | # clone the repository 15 | git clone https://github.com/kctess5/range_libc 16 | cd range_libc 17 | mkdir build 18 | cd build 19 | cmake .. 20 | make 21 | ``` 22 | 23 | If you get an error about having the wrong version of CMake, install a version of CMake that is less than or equal to 3.6 (I use 3.6) from here: https://cmake.org/download/ 24 | 25 | If you don't want to update your system's version of CMake, simply: 26 | 27 | ``` 28 | # unzip cmake download and cd into that directory 29 | mkdir build 30 | cd build 31 | cmake .. 32 | make 33 | # 3.6 should be your cmake version number 34 | sudo ln -s [path to cmake directory]/build/bin/cmake /usr/bin/cmake3.6 35 | ``` 36 | 37 | Then use cmake3.6 instead of cmake in the above instructions for building the range_lib code. 38 | 39 | ### Python Wrappers 40 | 41 | To build the code and its associated Python wrappers for use in Python code, do the following. You may have to install Cython if you do not already have it on your system. 42 | 43 | ``` 44 | # clone the repository 45 | git clone https://github.com/kctess5/range_libc 46 | cd range_libc_dist/pywrapper 47 | # for an in place build, do this: 48 | python setup.py build_ext --inplace 49 | # for a system wide install, do this: 50 | python setup.py install 51 | # to compile with the GPU kernels, do this: 52 | WITH_CUDA=ON python setup.py install 53 | # this should take a few seconds to run 54 | python test.py 55 | ``` 56 | 57 | To see example usage of the Python wrappers (using the ROS specific helpers) see [https://github.com/mit-racecar/particle_filter](https://github.com/mit-racecar/particle_filter). See the [/docs](/docs) folder for documentation. 58 | 59 | ### Building on a RACECAR 60 | 61 | MIT's 6.141 uses this library for accelerating particle filters onboard the RACECAR platform. To install this on the Jetson TX1, do: 62 | 63 | ``` 64 | # Copy the code 65 | cd range_libc 66 | # this part is not strictly necessary, but useful for debugging compilation issues 67 | mkdir build 68 | cmake .. 69 | make 70 | # To build the Python wrappers 71 | sudo apt-get install Cython 72 | cd pywrapper 73 | sudo WITH_CUDA=ON python setup.py install 74 | ``` 75 | 76 | ## License 77 | 78 | This code is licensed under Apache 2.0. Copyright 2017 Corey H. Walsh. 79 | 80 | You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 81 | 82 | Enjoy! 83 | 84 | ## Cite 85 | 86 | This library accompanies the following [publication](http://arxiv.org/abs/1705.01167). 87 | 88 | @article{walsh17, 89 | author = {Corey Walsh and 90 | Sertac Karaman}, 91 | title = {CDDT: Fast Approximate 2D Ray Casting for Accelerated Localization}, 92 | volume = {abs/1705.01167}, 93 | url = {http://arxiv.org/abs/1705.01167}, 94 | year = {2017}} 95 | 96 | ## Code structure 97 | 98 | ``` 99 | range_libc_dist/ 100 | ├── build 101 | │   └── bin # this is where compiled binaries will be placed 102 | ├── CMakeLists.txt # compilation rules - includes, etc 103 | ├── includes 104 | │   ├── lru_cache.h # implementation of LRU_cache, optionally used 105 | │   ├── RangeLib.h # main RangeLib source code 106 | │   ├── CudaRangeLib.h # cuda function header file 107 | │   ├── kernels.cu # cuda kernels for super fast 2D ray casting 108 | │   └── RangeUtils.h # various utility functions 109 | ├── license.txt 110 | ├── main.cpp # example c++ usage and simple benchmarks 111 | ├── make_plots.py # turns fine-grained benchmark information into violin plots 112 | ├── tmp/ # make this directory for saving fine-grained timing information 113 | ├── maps # example PNG maps 114 | │   └── [various .png files] 115 | ├── pywrapper 116 | │   ├── RangeLibc.pyx # wrapper file for using RangeLib from Python 117 | │   ├── setup.py # compilation rules for Cython 118 | │   └── test.py # example Python usage 119 | ├── README.md 120 | └── vendor # various dependencies, see in here for licenses 121 | ├── distance_transform.h # for computing euclidean distance transform 122 | ├── gflags # command line flag library from Google 123 | └── lodepng # simple PNG loading/saving library 124 | ``` 125 | 126 | ## RangeLibc Algorithms Overview 127 | 128 | * [Bresenham's Line (BL)](#bresenhams-line-bl) 129 | * [Ray Marching (RM/RMGPU)](#ray-marching-rm) 130 | * [Compressed Directional Distance Transform (CDDT/PCDDT)](#compressed-directional-distance-transform-cddt-ours) 131 | * [Giant Lookup Table (GLT)](#giant-lookup-table-glt) 132 | 133 | ![Range Method Performance Comparison](./media/comparison.png) 134 | 135 | The above benchmarks were performed on an NVIDIA Jetson TX1 with a single thread. For a better treatment, see the paper associated with this library: [http://arxiv.org/abs/1705.01167](http://arxiv.org/abs/1705.01167) 136 | 137 | 138 | 139 | ### Bresenham's Line (BL) 140 | 141 | Bresenham's line algorithm [1] is one of the most widely used methods for two dimensional ray casting in occupancy grids. The algorithm incrementally determines the set of pixels that approximate the trajectory of a query ray starting from the query point (x,y)_{query} and progressing in the theta_{query} direction one pixel at a time. The algorithm terminates once the nearest occupied pixel is discovered, and the euclidean distance between that occupied pixel and (x,y)_{query} is reported. This algorithm is widely implemented in particle filters due to its simplicity and ability to operate on a dynamic map. The primary disadvantage is that it is slow, potentially requiring hundreds of memory accesses for a single ray cast. While average performance is highly environment dependent, Bresenham's Line algorithm is linear in map size in the worst case. 142 | 143 | 144 | ### Ray Marching (RM/RMGPU) 145 | 146 | Ray marching [2] is a well known algorithm, frequently used to accelerate fractal or volumetric graphical rendering applications. The basic idea can be understood very intuitively. Imagine that you are in an unknown environment, with a blindfold on. If an oracle tells you the distance to the nearest obstacle, you can surely move in any direction by at most that distance without colliding with any obstacle. By applying this concept recursively, one can step along a particular ray by the minimum distance to the nearest obstacle until colliding with some obstacle. The following figure demonstrates this idea graphically (from [3]). 147 | 148 | ![Ray Marching](./media/spheretrace.jpg) 149 | 150 | In the occupancy grid world, it is possible to precompute the distance to the nearest obstacle for every discrete state in the grid via the euclidean distance transform. 151 | 152 | This method is implemented both for the CPU and GPU in RangeLibc. The GPU implementation is the fastest available method for large batches of queries. 153 | 154 | #### Pseudocode: 155 | 156 | ``` 157 | # compute the distance transform of the map 158 | def precomputation(omap): 159 | distance_transform = euclidean_dt(omap) 160 | 161 | # step along the (x,y,theta) ray until colliding with an obstacle 162 | def calc_range(x,y,theta): 163 | t = 0.0 164 | coeff = 0.99 165 | while t < max_range: 166 | px, py = x + cos(theta) * t, y + sin(theta) * t 167 | 168 | if px or py out of map bounds: 169 | return max_range 170 | 171 | dist = distance_transform[px,py] 172 | if dist == 0.0: 173 | return sqrt((x - px)^2 + (y - py)^2) 174 | 175 | t += max(dist*coeff, 1.0) 176 | 177 | ``` 178 | 179 | #### Analysis 180 | 181 | Precomputation: O(|theta_discretization|\*|edge pixels in occupancy grid|+|theta_discretization|\*|occupied pixels|\*log(|occupied pixels|)) 182 | Pruning: O(|map width|\*|map height|\*|theta_discretization|\*log(min(|occupied pixels|, longest map dimension))) 183 | Calc range: O(log(min(|occupied pixels|, longest map dimension))) 184 | Memory: O(|theta_discretization|\*|edge pixels|) - in practice much smaller, due to pruning 185 | 186 | **Pros** 187 | 188 | - Fast calc_range on average 189 | - Space efficent 190 | - Easy to implement, and easy to implement on a GPU 191 | - Fairly fast to compute distance transform 192 | - Extends easily to 3D 193 | 194 | **Cons** 195 | 196 | - Poor worst case performance - degenerate case similar to Bresenham's line 197 | - High degree of control flow divergence (for parallelization) 198 | - Not great for incrementally changing the map 199 | 200 | 201 | 202 | ### Compressed Directional Distance Transform (CDDT/PCDDT) (ours) 203 | 204 | The Compressed Directional Distance Transform (CDDT) algorithm uses a compressed data structure to represent map geometry in a way which allows for fast queries. An optional pruning step removes unneeded elements in the data structure for slightly faster operation (PCDDT). For a full description of the algorithm, see the associated paper: [http://arxiv.org/abs/1705.01167](http://arxiv.org/abs/1705.01167) 205 | 206 | #### Pseudocode: 207 | 208 | ``` 209 | # for the given theta, determine a translation that will ensure the 210 | # y coordinate of every pixel in the rotated map will be positive 211 | def y_offset(theta): 212 | pass 213 | 214 | # give the range of y coordinates that the pixel overlaps with 215 | def y_bounds(pixel): 216 | return range(min(pixel.corners.y), max(pixel.corners.y)) 217 | 218 | # build the CDDT datastructure 219 | def precomputation(omap): 220 | # prune any unimportant geometry from the map 221 | edgeMap = morphological_edge_transform(omap) 222 | 223 | # build the empty LUT data structure 224 | compressed_lut = [] 225 | for each theta in |theta_discretization|: 226 | projection_lut = [] 227 | for each i in range(lut_widths[theta]): 228 | projection_lut.append([]) 229 | compressed_lut.append(projection_lut) 230 | 231 | # populate the LUT data structure 232 | for each theta in |theta_discretization|: 233 | for each occupied pixel (x,y) in omap: 234 | pixel.rotate(theta) 235 | pixel.translate(y_offset(theta)) 236 | lut_indices = y_bounds(pixel) 237 | 238 | for each index in lut_indices: 239 | compressed_lut[theta][index].append(pixel.center.x) 240 | 241 | # sort each LUT bin for faster access via binary search 242 | for each theta in |theta_discretization|: 243 | for each i in compressed_lut[theta].size(): 244 | sort(compressed_lut[theta][i]) 245 | 246 | # (optional) remove unused entries from the LUT to save space 247 | # highly recommended for static maps 248 | def prune(): 249 | # build an empty table of sets to keep track of which 250 | # indices in the CDDT data structure are used 251 | collision_table = [] 252 | for theta in range(theta_discretization): 253 | collision_row = [] 254 | for i in range(compressed_lut[theta].size()): 255 | collision_row.append(set()) 256 | collision_table.append(collision_row) 257 | 258 | # ray cast from every possible (x,y,theta) state, keeping track 259 | # of which LUT entries are used 260 | for x in range(omap.width): 261 | for y in range(omap.height): 262 | for theta in range(theta_discretization): 263 | # keep track of which object in the LUT is found to collide 264 | # with the following ray cast query 265 | calc_range(x,y,theta) implies (lut_bin, lut_bin_index) 266 | collision_table[theta][lut_bin].add(lut_bin_index) 267 | 268 | # remove any element of the LUT that is not in the collision table 269 | for theta in range(theta_discretization): 270 | for i in range(compressed_lut[theta].size()): 271 | new_lut_bin = [] 272 | for obstacle in compressed_lut[theta][i]: 273 | if obstacle in collision_table: 274 | new_lut_bin.append(obstacle) 275 | else: continue 276 | compressed_lut[theta][i] = new_lut_bin 277 | 278 | # compute the distance to the nearest obstacle in the (x,y,theta) direction 279 | def calc_range(x,y,theta): 280 | angle_index, discrete_angle, flipped_search = discretize_theta(theta) 281 | lut_x, lut_y = rotate(x, y, discrete_angle) 282 | 283 | if omap.occupied(x,y): 284 | return 0.0 285 | 286 | lut_bin = compressed_lut[angle_index][(int)lut_y] 287 | if flipped_search: 288 | nearest_obstacle_x = lut_bin.next_lesser_element(lut_x) 289 | else: 290 | nearest_obstacle_x = lut_bin.next_greater_element(lut_x) 291 | 292 | distance = abs(nearest_obstacle_x - lut_x) 293 | return distance 294 | ``` 295 | 296 | #### Analysis 297 | 298 | Precomputation: O(|width|\*|height|) for 2D grid. In general O(dk) where d is the dimensionality of the grid, and k is the number of grid locations. 299 | Calc range: worst case O(|longest map dimension|), on average much faster (close to logarithmic performance in scene size) 300 | Memory: O(|width|\*|height|) for 2D grid. In general O(k) where k is the number of grid locations. 301 | 302 | **Pros** 303 | 304 | - Fast calc_range, in practice nearly constant time 305 | - Radial symmetry optimizations can provide additional speed in the right context 306 | - Potential for online incremental compressed LUT modification for use in SLAM (would need to store additional metadata) 307 | - Space efficent 308 | - Fast construction time 309 | 310 | **Cons** 311 | 312 | - Slow pruning time (optional) 313 | - Approximate due to the discrete theta space 314 | - Can be difficult to implement well 315 | - Curse of dimensionality in higher dimensions 316 | 317 | 318 | 319 | 320 | ### Giant Lookup Table (GLT) 321 | 322 | Precompute distances for all possible (x,y,theta) states and store the results in a big table for fast lookup. 323 | 324 | #### Pseudocode: 325 | 326 | ``` 327 | # For every (x,y,theta) in a predefined grid, use Besenham's line or 328 | # ray maching to build the table 329 | def precomputation(omap): 330 | giant_LUT[width][height][theta_discretization] = -1 331 | for x in range(omap.width): 332 | for y in range(omap.height): 333 | for theta in range(theta_discretization): 334 | giant_LUT[x][y][theta] = calc_range(x,y,theta) 335 | 336 | # simply read from the table 337 | # note: interpolation between the two closest discrete 338 | # thetas would be more accurate but slower 339 | def calc_range(x,y,theta): 340 | return giant_LUT[int(x), int(y), discrete(theta)] 341 | ``` 342 | 343 | #### Analysis 344 | 345 | Precomputation: O(|theta_discretization|\*|width|\*|height|\*O(calc_range)) 346 | Memory: O(|theta_discretization|\*|width|\*|height|) 347 | Calc range: O(1) 348 | 349 | **Pros** 350 | 351 | - Very fast calc_range 352 | - Easy to implement 353 | 354 | **Cons** 355 | 356 | - Very slow construction time 357 | - Approximate due to the discrete theta space 358 | - Very large memory requirement 359 | - Curse of dimensionality in higher dimensions 360 | 361 | 362 | ## References 363 | 364 | 1. J. Bresenham. "Algorithm for Computer Control of a Digital Plotter," IBM Systems Journal, vol. 4, no. 1, pp. 25-30, 1965. 365 | 2. K. Perlin and E. M. Hoffert. "Hypertexture," Computer Graphics, vol 23, no. 3, pp. 297-306, 1989. 366 | 3. M. Pharr, and R. Fernando. "Chapter 8. Per-Pixel Displacement Mapping with Distance Functions" in GPU gems 2: Programming techniques for high-performance graphics and general-purpose computation, 3rd ed. United States: Addison-Wesley Educational Publishers, 2005. 367 | --------------------------------------------------------------------------------