<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#include "../core/Setup.h"

#include <algorithm>
#include <fstream>
#if defined(_WIN32)
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  include <ShlObj.h>
#  include <Shlwapi.h>
#  include <strsafe.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
#  include <TargetConditionals.h>
#  include <objc/message.h>
#  include <objc/NSObjCRuntime.h>
#  include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
#  include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
#  include <pwd.h>
#endif

#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"

#if defined(__APPLE__)
#  include "CfPointer.hpp"
#endif

namespace ouzel
{
    namespace storage
    {
        FileSystem::FileSystem(Engine& initEngine):
            engine(initEngine)
        {
#if defined(_WIN32)
            HINSTANCE instance = GetModuleHandleW(nullptr);
            if (!instance)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle");
            std::vector<WCHAR> buffer(MAX_PATH + 1);
            for (;;)
            {
                if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
                    throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename");

                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                    buffer.resize(buffer.size() * 2);
                else
                    break;
            }

            const auto executablePath = Path{buffer.data(), Path::Format::Native};
            appPath = executablePath.getDirectory();
            engine.log(Log::Level::Info) << "Application directory: " << appPath;

#elif defined(__APPLE__)
            CFBundleRef bundle = CFBundleGetMainBundle();
            if (!bundle)
                throw std::runtime_error("Failed to get main bundle");

            CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
            if (!relativePath)
                throw std::runtime_error("Failed to get resource directory");

            CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
            CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);

            const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
            std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize));
            const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize);
            if (!result)
                throw std::runtime_error("Failed to get resource directory");

            appPath = Path{resourceDirectory.data(), Path::Format::Native};
            engine.log(Log::Level::Info) << "Application directory: " << appPath;

#elif defined(__ANDROID__)
            // not available for Android

#elif defined(__linux__)
            char executableDirectory[PATH_MAX];

            ssize_t length;
            if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1)
                throw std::system_error(errno, std::system_category(), "Failed to get current directory");

            executableDirectory[length] = '\0';
            const auto executablePath = Path{executableDirectory, Path::Format::Native};
            appPath = executablePath.getDirectory();
            engine.log(Log::Level::Info) << "Application directory: " << appPath;
#endif
        }

        Path FileSystem::getStorageDirectory(const bool user) const
        {
#if defined(_WIN32)
            WCHAR appDataPath[MAX_PATH];

            HRESULT hr;
            if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath)))
                throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory");

            Path path = Path{appDataPath, Path::Format::Native};

            HINSTANCE instance = GetModuleHandleW(nullptr);
            if (!instance)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle");
            std::vector<WCHAR> buffer(MAX_PATH + 1);
            for (;;)
            {
                if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
                    throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename");

                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                    buffer.resize(buffer.size() * 2);
                else
                    break;
            }

            const auto executablePath = Path{buffer.data(), Path::Format::Native};
            DWORD handle;
            const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);
            if (!fileVersionSize)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version size");

            auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);
            if (!GetFileVersionInfoW(executablePath.getNative().c_str(),
                                     handle, fileVersionSize,
                                     fileVersionBuffer.get()))
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version");

            LPWSTR companyName = nullptr;
            LPWSTR productName = nullptr;

            struct LANGANDCODEPAGE final
            {
                WORD wLanguage;
                WORD wCodePage;
            };
            LPVOID translationPointer;
            UINT translationLength;

            if (VerQueryValueW(fileVersionBuffer.get(),
                               L"\\VarFileInfo\\Translation",
                               &translationPointer,
                               &translationLength))
            {
                auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);

                for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i)
                {
                    constexpr size_t subBlockSize = 37;
                    WCHAR subBlock[subBlockSize];

                    StringCchPrintfW(subBlock, subBlockSize,
                                     L"\\StringFileInfo\\040904b0\\CompanyName",
                                     translation[i].wLanguage,
                                     translation[i].wCodePage);

                    LPVOID companyNamePointer;
                    UINT companyNameLength;
                    if (VerQueryValueW(fileVersionBuffer.get(),
                                       subBlock,
                                       &companyNamePointer,
                                       &companyNameLength))
                        companyName = static_cast<LPWSTR>(companyNamePointer);

                    StringCchPrintfW(subBlock, subBlockSize,
                                     L"\\StringFileInfo\\040904b0\\ProductName",
                                     translation[i].wLanguage,
                                     translation[i].wCodePage);

                    LPVOID productNamePointer;
                    UINT productNameLength;
                    if (VerQueryValueW(fileVersionBuffer.get(),
                                       subBlock,
                                       &productNamePointer,
                                       &productNameLength))
                        productName = static_cast<LPWSTR>(productNamePointer);
                }
            }

            if (companyName)
                path /= companyName;
            else
                path /= OUZEL_DEVELOPER_NAME;

            if (!path.isDirectory())
                createDirectory(path);

            if (productName)
                path /= productName;
            else
                path /= OUZEL_APPLICATION_NAME;

            if (!path.isDirectory())
                createDirectory(path);

            return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
            id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));

            constexpr NSUInteger NSDocumentDirectory = 9;
            constexpr NSUInteger NSUserDomainMask = 1;
            constexpr NSUInteger NSLocalDomainMask = 2;

            id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);

            if (!documentDirectory)
                throw std::runtime_error("Failed to get document directory");

            id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
            auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
            return Path{pathUtf8String, Path::Format::Native};
#elif TARGET_OS_MAC
            id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));

            constexpr NSUInteger NSApplicationSupportDirectory = 14;
            constexpr NSUInteger NSUserDomainMask = 1;
            constexpr NSUInteger NSLocalDomainMask = 2;

            id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);

            if (!applicationSupportDirectory)
                throw std::runtime_error("Failed to get application support directory");

            CFBundleRef bundle = CFBundleGetMainBundle();
            CFStringRef identifier = CFBundleGetIdentifier(bundle);

            if (!identifier)
                identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);

            id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
            reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
            id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
            auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
            return Path{pathUtf8String, Path::Format::Native};
#elif defined(__ANDROID__)
            static_cast<void>(user);

            EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
            return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
            Path path;

            const char* homeDirectory = std::getenv("XDG_DATA_HOME");

            if (homeDirectory)
                path = Path{homeDirectory, Path::Format::Native};
            else
            {
                struct passwd pwent;
                struct passwd* pwentp;
                std::vector<char> buffer(1024);
                int e;

                while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE)
                    buffer.resize(buffer.size() * 2);

                if (e != 0)
                    throw std::runtime_error("Failed to get home directory");
                else
                    path = Path{pwent.pw_dir, Path::Format::Native};

                path /= ".local";

                if (!directoryExists(path))
                    createDirectory(path);

                path /= "share";

                if (!directoryExists(path))
                    createDirectory(path);
            }

            path /= OUZEL_DEVELOPER_NAME;

            if (!directoryExists(path))
                createDirectory(path);

            path /= OUZEL_APPLICATION_NAME;

            if (!directoryExists(path))
                createDirectory(path);

            return path;
#else
            return Path{};
#endif
        }

        std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources)
        {
            if (searchResources)
                for (auto& archive : archives)
                    if (archive.second.fileExists(filename))
                        return archive.second.readFile(filename);

#if defined(__ANDROID__)
            if (!filename.isAbsolute())
            {
                EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);

                AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);

                if (!asset)
                    throw std::runtime_error("Failed to open file " + std::string(filename));

                std::vector<std::uint8_t> data;
                std::uint8_t buffer[1024];

                for (;;)
                {
                    const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer));

                    if (bytesRead < 0)
                        throw std::runtime_error("Failed to read from file");
                    else if (bytesRead == 0)
                        break;

                    data.insert(data.end(), buffer, buffer + bytesRead);
                }

                AAsset_close(asset);

                return data;
            }
#endif

            const auto path = getPath(filename, searchResources);

            // file does not exist
            if (path.isEmpty())
                throw std::runtime_error("Failed to find file " + std::string(filename));

            std::ifstream f(path, std::ios::binary);
            return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
        }

        bool FileSystem::resourceFileExists(const Path& filename) const
        {
            if (filename.isAbsolute())
                return fileExists(filename);
            else
            {
                Path result = appPath / filename;

                if (fileExists(result))
                    return true;
                else
                    for (const auto& path : resourcePaths)
                    {
                        if (path.isAbsolute()) // if resource path is absolute
                            result = path / filename;
                        else
                            result = appPath / path / filename;

                        if (fileExists(result))
                            return true;
                    }

                return false;
            }
        }

        bool FileSystem::directoryExists(const Path& dirname) const
        {
#if defined(__ANDROID__)
            EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);

            AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());
            const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr;
            AAssetDir_close(assetDir);

            if (exists) return true;
#endif

            return isDirectory(dirname);
        }

        bool FileSystem::fileExists(const Path& filename) const
        {
#if defined(__ANDROID__)
            EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);

            AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);

            if (asset)
            {
                AAsset_close(asset);
                return true;
            }
#endif

            return isRegular(filename);
        }
    } // namespace storage
} // namespace ouzel
<commit_msg>Fix the Windows build<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#include "../core/Setup.h"

#include <algorithm>
#include <fstream>
#if defined(_WIN32)
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  include <ShlObj.h>
#  include <Shlwapi.h>
#  include <strsafe.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__APPLE__)
#  include <TargetConditionals.h>
#  include <objc/message.h>
#  include <objc/NSObjCRuntime.h>
#  include <CoreFoundation/CoreFoundation.h>
#elif defined(__ANDROID__)
#  include "../core/android/EngineAndroid.hpp"
#elif defined(__linux__)
#  include <pwd.h>
#endif

#include "FileSystem.hpp"
#include "Archive.hpp"
#include "../core/Engine.hpp"
#include "../utils/Log.hpp"

#if defined(__APPLE__)
#  include "CfPointer.hpp"
#endif

namespace ouzel
{
    namespace storage
    {
        FileSystem::FileSystem(Engine& initEngine):
            engine(initEngine)
        {
#if defined(_WIN32)
            HINSTANCE instance = GetModuleHandleW(nullptr);
            if (!instance)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle");
            std::vector<WCHAR> buffer(MAX_PATH + 1);
            for (;;)
            {
                if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
                    throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename");

                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                    buffer.resize(buffer.size() * 2);
                else
                    break;
            }

            const auto executablePath = Path{buffer.data(), Path::Format::Native};
            appPath = executablePath.getDirectory();
            engine.log(Log::Level::Info) << "Application directory: " << appPath;

#elif defined(__APPLE__)
            CFBundleRef bundle = CFBundleGetMainBundle();
            if (!bundle)
                throw std::runtime_error("Failed to get main bundle");

            CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle);
            if (!relativePath)
                throw std::runtime_error("Failed to get resource directory");

            CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get());
            CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);

            const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());
            std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize));
            const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize);
            if (!result)
                throw std::runtime_error("Failed to get resource directory");

            appPath = Path{resourceDirectory.data(), Path::Format::Native};
            engine.log(Log::Level::Info) << "Application directory: " << appPath;

#elif defined(__ANDROID__)
            // not available for Android

#elif defined(__linux__)
            char executableDirectory[PATH_MAX];

            ssize_t length;
            if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1)
                throw std::system_error(errno, std::system_category(), "Failed to get current directory");

            executableDirectory[length] = '\0';
            const auto executablePath = Path{executableDirectory, Path::Format::Native};
            appPath = executablePath.getDirectory();
            engine.log(Log::Level::Info) << "Application directory: " << appPath;
#endif
        }

        Path FileSystem::getStorageDirectory(const bool user) const
        {
#if defined(_WIN32)
            WCHAR appDataPath[MAX_PATH];

            HRESULT hr;
            if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath)))
                throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory");

            Path path = Path{appDataPath, Path::Format::Native};

            HINSTANCE instance = GetModuleHandleW(nullptr);
            if (!instance)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle");
            std::vector<WCHAR> buffer(MAX_PATH + 1);
            for (;;)
            {
                if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))
                    throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename");

                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                    buffer.resize(buffer.size() * 2);
                else
                    break;
            }

            const auto executablePath = Path{buffer.data(), Path::Format::Native};
            DWORD handle;
            const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);
            if (!fileVersionSize)
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version size");

            auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);
            if (!GetFileVersionInfoW(executablePath.getNative().c_str(),
                                     handle, fileVersionSize,
                                     fileVersionBuffer.get()))
                throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version");

            LPWSTR companyName = nullptr;
            LPWSTR productName = nullptr;

            struct LANGANDCODEPAGE final
            {
                WORD wLanguage;
                WORD wCodePage;
            };
            LPVOID translationPointer;
            UINT translationLength;

            if (VerQueryValueW(fileVersionBuffer.get(),
                               L"\\VarFileInfo\\Translation",
                               &translationPointer,
                               &translationLength))
            {
                auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);

                for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i)
                {
                    constexpr size_t subBlockSize = 37;
                    WCHAR subBlock[subBlockSize];

                    StringCchPrintfW(subBlock, subBlockSize,
                                     L"\\StringFileInfo\\040904b0\\CompanyName",
                                     translation[i].wLanguage,
                                     translation[i].wCodePage);

                    LPVOID companyNamePointer;
                    UINT companyNameLength;
                    if (VerQueryValueW(fileVersionBuffer.get(),
                                       subBlock,
                                       &companyNamePointer,
                                       &companyNameLength))
                        companyName = static_cast<LPWSTR>(companyNamePointer);

                    StringCchPrintfW(subBlock, subBlockSize,
                                     L"\\StringFileInfo\\040904b0\\ProductName",
                                     translation[i].wLanguage,
                                     translation[i].wCodePage);

                    LPVOID productNamePointer;
                    UINT productNameLength;
                    if (VerQueryValueW(fileVersionBuffer.get(),
                                       subBlock,
                                       &productNamePointer,
                                       &productNameLength))
                        productName = static_cast<LPWSTR>(productNamePointer);
                }
            }

            if (companyName)
                path /= companyName;
            else
                path /= OUZEL_DEVELOPER_NAME;

            if (!isDirectory(path))
                createDirectory(path);

            if (productName)
                path /= productName;
            else
                path /= OUZEL_APPLICATION_NAME;

            if (!isDirectory(path))
                createDirectory(path);

            return path;
#elif TARGET_OS_IOS || TARGET_OS_TV
            id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));

            constexpr NSUInteger NSDocumentDirectory = 9;
            constexpr NSUInteger NSUserDomainMask = 1;
            constexpr NSUInteger NSLocalDomainMask = 2;

            id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);

            if (!documentDirectory)
                throw std::runtime_error("Failed to get document directory");

            id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path"));
            auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String"));
            return Path{pathUtf8String, Path::Format::Native};
#elif TARGET_OS_MAC
            id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager"));

            constexpr NSUInteger NSApplicationSupportDirectory = 14;
            constexpr NSUInteger NSUserDomainMask = 1;
            constexpr NSUInteger NSLocalDomainMask = 2;

            id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);

            if (!applicationSupportDirectory)
                throw std::runtime_error("Failed to get application support directory");

            CFBundleRef bundle = CFBundleGetMainBundle();
            CFStringRef identifier = CFBundleGetIdentifier(bundle);

            if (!identifier)
                identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME);

            id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier);
            reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil);
            id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path"));
            auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String"));
            return Path{pathUtf8String, Path::Format::Native};
#elif defined(__ANDROID__)
            static_cast<void>(user);

            EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);
            return engineAndroid.getFilesDirectory();
#elif defined(__linux__)
            Path path;

            const char* homeDirectory = std::getenv("XDG_DATA_HOME");

            if (homeDirectory)
                path = Path{homeDirectory, Path::Format::Native};
            else
            {
                struct passwd pwent;
                struct passwd* pwentp;
                std::vector<char> buffer(1024);
                int e;

                while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE)
                    buffer.resize(buffer.size() * 2);

                if (e != 0)
                    throw std::runtime_error("Failed to get home directory");
                else
                    path = Path{pwent.pw_dir, Path::Format::Native};

                path /= ".local";

                if (!isDirectory(path))
                    createDirectory(path);

                path /= "share";

                if (!isDirectory(path))
                    createDirectory(path);
            }

            path /= OUZEL_DEVELOPER_NAME;

            if (!isDirectory(path))
                createDirectory(path);

            path /= OUZEL_APPLICATION_NAME;

            if (!isDirectory(path))
                createDirectory(path);

            return path;
#else
            return Path{};
#endif
        }

        std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources)
        {
            if (searchResources)
                for (auto& archive : archives)
                    if (archive.second.fileExists(filename))
                        return archive.second.readFile(filename);

#if defined(__ANDROID__)
            if (!filename.isAbsolute())
            {
                EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);

                AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);

                if (!asset)
                    throw std::runtime_error("Failed to open file " + std::string(filename));

                std::vector<std::uint8_t> data;
                std::uint8_t buffer[1024];

                for (;;)
                {
                    const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer));

                    if (bytesRead < 0)
                        throw std::runtime_error("Failed to read from file");
                    else if (bytesRead == 0)
                        break;

                    data.insert(data.end(), buffer, buffer + bytesRead);
                }

                AAsset_close(asset);

                return data;
            }
#endif

            const auto path = getPath(filename, searchResources);

            // file does not exist
            if (path.isEmpty())
                throw std::runtime_error("Failed to find file " + std::string(filename));

            std::ifstream f(path, std::ios::binary);
            return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
        }

        bool FileSystem::resourceFileExists(const Path& filename) const
        {
            if (filename.isAbsolute())
                return fileExists(filename);
            else
            {
                Path result = appPath / filename;

                if (fileExists(result))
                    return true;
                else
                    for (const auto& path : resourcePaths)
                    {
                        if (path.isAbsolute()) // if resource path is absolute
                            result = path / filename;
                        else
                            result = appPath / path / filename;

                        if (fileExists(result))
                            return true;
                    }

                return false;
            }
        }

        bool FileSystem::directoryExists(const Path& dirname) const
        {
#if defined(__ANDROID__)
            EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);

            AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());
            const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr;
            AAssetDir_close(assetDir);

            if (exists) return true;
#endif

            return isDirectory(dirname);
        }

        bool FileSystem::fileExists(const Path& filename) const
        {
#if defined(__ANDROID__)
            EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);

            AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);

            if (asset)
            {
                AAsset_close(asset);
                return true;
            }
#endif

            return isRegular(filename);
        }
    } // namespace storage
} // namespace ouzel
<|endoftext|>


<commit_before>typedef unsigned int size_t;
void clean();

void funcTest1()
{
   throw ("my exception!",546);  // BAD
}

void DllMain()
{
  try { throw "my exception!"; } // BAD
  catch (...) {  }
}

void funcTest2()
{
  try { throw "my exception!"; } // GOOD
  catch (...) { clean(); }
}
void TestFunc()
{
  funcTest1();
  DllMain();
  funcTest2();
}
<commit_msg>Update test.cpp<commit_after>namespace std
{
	class exception {
	};

	class runtime_error : public exception {
	public:
		runtime_error(const char *msg);
	};
}

typedef unsigned int size_t;
void clean();

void funcTest1()
{
   throw ("my exception!",546);  // BAD
}

void DllMain()
{
  try { throw "my exception!"; } // BAD
  catch (...) {  }
}

void funcTest2()
{
  try { throw "my exception!"; } // GOOD
  catch (...) { clean(); }
}

void funcTest3()
{
  std::runtime_error("msg error"); // BAD
  throw std::runtime_error("msg error"); // GOOD
}

void TestFunc()
{
  funcTest1();
  DllMain();
  funcTest2();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2018 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cartographer/mapping/2d/tsdf_range_data_inserter_2d.h"

#include "cartographer/mapping/internal/2d/normal_estimation_2d.h"
#include "cartographer/mapping/internal/2d/ray_to_pixel_mask.h"

namespace cartographer {
namespace mapping {
namespace {

// Factor for subpixel accuracy of start and end point for ray casts.
constexpr int kSubpixelScale = 1000;
// Minimum distance between range observation and origin. Otherwise, range
// observations are discarded.
constexpr float kMinRangeMeters = 1e-6f;
const float kSqrtTwoPi = std::sqrt(2.0 * M_PI);

void GrowAsNeeded(const sensor::RangeData& range_data,
                  const float truncation_distance, TSDF2D* const tsdf) {
  Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>());
  for (const sensor::RangefinderPoint& hit : range_data.returns) {
    const Eigen::Vector3f direction =
        (hit.position - range_data.origin).normalized();
    const Eigen::Vector3f end_position =
        hit.position + truncation_distance * direction;
    bounding_box.extend(end_position.head<2>());
  }
  // Padding around bounding box to avoid numerical issues at cell boundaries.
  constexpr float kPadding = 1e-6f;
  tsdf->GrowLimits(bounding_box.min() - kPadding * Eigen::Vector2f::Ones());
  tsdf->GrowLimits(bounding_box.max() + kPadding * Eigen::Vector2f::Ones());
}

float GaussianKernel(const float x, const float sigma) {
  return 1.0 / (kSqrtTwoPi * sigma) * std::exp(-0.5 * x * x / (sigma * sigma));
}

std::pair<Eigen::Array2i, Eigen::Array2i> SuperscaleRay(
    const Eigen::Vector2f& begin, const Eigen::Vector2f& end,
    TSDF2D* const tsdf) {
  const MapLimits& limits = tsdf->limits();
  const double superscaled_resolution = limits.resolution() / kSubpixelScale;
  const MapLimits superscaled_limits(
      superscaled_resolution, limits.max(),
      CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale,
                 limits.cell_limits().num_y_cells * kSubpixelScale));

  const Eigen::Array2i superscaled_begin =
      superscaled_limits.GetCellIndex(begin);
  const Eigen::Array2i superscaled_end = superscaled_limits.GetCellIndex(end);
  return std::make_pair(superscaled_begin, superscaled_end);
}

struct RangeDataSorter {
  RangeDataSorter(Eigen::Vector3f origin) { origin_ = origin.head<2>(); }
  bool operator()(const sensor::RangefinderPoint& lhs,
                  const sensor::RangefinderPoint& rhs) {
    const Eigen::Vector2f delta_lhs =
        (lhs.position.head<2>() - origin_).normalized();
    const Eigen::Vector2f delta_rhs =
        (lhs.position.head<2>() - origin_).normalized();
    if ((delta_lhs[1] < 0.f) != (delta_rhs[1] < 0.f)) {
      return delta_lhs[1] < 0.f;
    } else if (delta_lhs[1] < 0.f) {
      return delta_lhs[0] < delta_rhs[0];
    } else {
      return delta_lhs[0] > delta_rhs[0];
    }
  }

 private:
  Eigen::Vector2f origin_;
};

float ComputeRangeWeightFactor(float range, int exponent) {
  float weight = 0.f;
  if (std::abs(range) > kMinRangeMeters) {
    weight = 1.f / (std::pow(range, exponent));
  }
  return weight;
}
}  // namespace

proto::TSDFRangeDataInserterOptions2D CreateTSDFRangeDataInserterOptions2D(
    common::LuaParameterDictionary* parameter_dictionary) {
  proto::TSDFRangeDataInserterOptions2D options;
  options.set_truncation_distance(
      parameter_dictionary->GetDouble("truncation_distance"));
  options.set_maximum_weight(parameter_dictionary->GetDouble("maximum_weight"));
  options.set_update_free_space(
      parameter_dictionary->GetBool("update_free_space"));
  *options
       .mutable_normal_estimation_options() = CreateNormalEstimationOptions2D(
      parameter_dictionary->GetDictionary("normal_estimation_options").get());
  options.set_project_sdf_distance_to_scan_normal(
      parameter_dictionary->GetBool("project_sdf_distance_to_scan_normal"));
  options.set_update_weight_range_exponent(
      parameter_dictionary->GetInt("update_weight_range_exponent"));
  options.set_update_weight_angle_scan_normal_to_ray_kernel_bandwidth(
      parameter_dictionary->GetDouble(
          "update_weight_angle_scan_normal_to_ray_kernel_bandwidth"));
  options.set_update_weight_distance_cell_to_hit_kernel_bandwidth(
      parameter_dictionary->GetDouble(
          "update_weight_distance_cell_to_hit_kernel_bandwidth"));
  return options;
}

TSDFRangeDataInserter2D::TSDFRangeDataInserter2D(
    const proto::TSDFRangeDataInserterOptions2D& options)
    : options_(options) {}

// Casts a ray from origin towards hit for each hit in range data.
// If 'options.update_free_space' is 'true', all cells along the ray
// until 'truncation_distance' behind hit are updated. Otherwise, only the cells
// within 'truncation_distance' around hit are updated.
void TSDFRangeDataInserter2D::Insert(const sensor::RangeData& range_data,
                                     GridInterface* grid) const {
  const float truncation_distance =
      static_cast<float>(options_.truncation_distance());
  TSDF2D* tsdf = static_cast<TSDF2D*>(grid);
  GrowAsNeeded(range_data, truncation_distance, tsdf);

  // Compute normals if needed.
  bool scale_update_weight_angle_scan_normal_to_ray =
      options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f;
  sensor::RangeData sorted_range_data = range_data;
  std::vector<float> normals;
  if (options_.project_sdf_distance_to_scan_normal() ||
      scale_update_weight_angle_scan_normal_to_ray) {
    std::sort(sorted_range_data.returns.begin(),
              sorted_range_data.returns.end(),
              RangeDataSorter(sorted_range_data.origin));
    normals = EstimateNormals(sorted_range_data,
                              options_.normal_estimation_options());
  }

  const Eigen::Vector2f origin = sorted_range_data.origin.head<2>();
  for (size_t hit_index = 0; hit_index < sorted_range_data.returns.size();
       ++hit_index) {
    const Eigen::Vector2f hit =
        sorted_range_data.returns[hit_index].position.head<2>();
    const float normal = normals.empty()
                             ? std::numeric_limits<float>::quiet_NaN()
                             : normals[hit_index];
    InsertHit(options_, hit, origin, normal, tsdf);
  }
  tsdf->FinishUpdate();
}

void TSDFRangeDataInserter2D::InsertHit(
    const proto::TSDFRangeDataInserterOptions2D& options,
    const Eigen::Vector2f& hit, const Eigen::Vector2f& origin, float normal,
    TSDF2D* tsdf) const {
  const Eigen::Vector2f ray = hit - origin;
  const float range = ray.norm();
  const float truncation_distance =
      static_cast<float>(options_.truncation_distance());
  if (range < truncation_distance) return;
  const float truncation_ratio = truncation_distance / range;
  const Eigen::Vector2f ray_begin =
      options_.update_free_space() ? origin
                                   : origin + (1.0f - truncation_ratio) * ray;
  const Eigen::Vector2f ray_end = origin + (1.0f + truncation_ratio) * ray;
  std::pair<Eigen::Array2i, Eigen::Array2i> superscaled_ray =
      SuperscaleRay(ray_begin, ray_end, tsdf);
  std::vector<Eigen::Array2i> ray_mask = RayToPixelMask(
      superscaled_ray.first, superscaled_ray.second, kSubpixelScale);

  // Precompute weight factors.
  float weight_factor_angle_ray_normal = 1.f;
  if (options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() !=
      0.f) {
    const Eigen::Vector2f negative_ray = -ray;
    float angle_ray_normal =
        common::NormalizeAngleDifference(normal - common::atan2(negative_ray));
    weight_factor_angle_ray_normal = GaussianKernel(
        angle_ray_normal,
        options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth());
  }
  float weight_factor_range = 1.f;
  if (options_.update_weight_range_exponent() != 0) {
    weight_factor_range = ComputeRangeWeightFactor(
        range, options_.update_weight_range_exponent());
  }

  // Update Cells.
  for (const Eigen::Array2i& cell_index : ray_mask) {
    if (tsdf->CellIsUpdated(cell_index)) continue;
    Eigen::Vector2f cell_center = tsdf->limits().GetCellCenter(cell_index);
    float distance_cell_to_origin = (cell_center - origin).norm();
    float update_tsd = range - distance_cell_to_origin;
    if (options_.project_sdf_distance_to_scan_normal()) {
      float normal_orientation = normal;
      update_tsd = (cell_center - hit)
                       .dot(Eigen::Vector2f{std::cos(normal_orientation),
                                            std::sin(normal_orientation)});
    }
    update_tsd =
        common::Clamp(update_tsd, -truncation_distance, truncation_distance);
    float update_weight = weight_factor_range * weight_factor_angle_ray_normal;
    if (options_.update_weight_distance_cell_to_hit_kernel_bandwidth() != 0.f) {
      update_weight *= GaussianKernel(
          update_tsd,
          options_.update_weight_distance_cell_to_hit_kernel_bandwidth());
    }
    UpdateCell(cell_index, update_tsd, update_weight, tsdf);
  }
}

void TSDFRangeDataInserter2D::UpdateCell(const Eigen::Array2i& cell,
                                         float update_sdf, float update_weight,
                                         TSDF2D* tsdf) const {
  if (update_weight == 0.f) return;
  const std::pair<float, float> tsd_and_weight = tsdf->GetTSDAndWeight(cell);
  float updated_weight = tsd_and_weight.second + update_weight;
  float updated_sdf = (tsd_and_weight.first * tsd_and_weight.second +
                       update_sdf * update_weight) /
                      updated_weight;
  updated_weight =
      std::min(updated_weight, static_cast<float>(options_.maximum_weight()));
  tsdf->SetCell(cell, updated_sdf, updated_weight);
}

}  // namespace mapping
}  // namespace cartographer
<commit_msg>Fix typo in tsdf_range_data_inserter_2d.cc (#1612)<commit_after>/*
 * Copyright 2018 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cartographer/mapping/2d/tsdf_range_data_inserter_2d.h"

#include "cartographer/mapping/internal/2d/normal_estimation_2d.h"
#include "cartographer/mapping/internal/2d/ray_to_pixel_mask.h"

namespace cartographer {
namespace mapping {
namespace {

// Factor for subpixel accuracy of start and end point for ray casts.
constexpr int kSubpixelScale = 1000;
// Minimum distance between range observation and origin. Otherwise, range
// observations are discarded.
constexpr float kMinRangeMeters = 1e-6f;
const float kSqrtTwoPi = std::sqrt(2.0 * M_PI);

void GrowAsNeeded(const sensor::RangeData& range_data,
                  const float truncation_distance, TSDF2D* const tsdf) {
  Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>());
  for (const sensor::RangefinderPoint& hit : range_data.returns) {
    const Eigen::Vector3f direction =
        (hit.position - range_data.origin).normalized();
    const Eigen::Vector3f end_position =
        hit.position + truncation_distance * direction;
    bounding_box.extend(end_position.head<2>());
  }
  // Padding around bounding box to avoid numerical issues at cell boundaries.
  constexpr float kPadding = 1e-6f;
  tsdf->GrowLimits(bounding_box.min() - kPadding * Eigen::Vector2f::Ones());
  tsdf->GrowLimits(bounding_box.max() + kPadding * Eigen::Vector2f::Ones());
}

float GaussianKernel(const float x, const float sigma) {
  return 1.0 / (kSqrtTwoPi * sigma) * std::exp(-0.5 * x * x / (sigma * sigma));
}

std::pair<Eigen::Array2i, Eigen::Array2i> SuperscaleRay(
    const Eigen::Vector2f& begin, const Eigen::Vector2f& end,
    TSDF2D* const tsdf) {
  const MapLimits& limits = tsdf->limits();
  const double superscaled_resolution = limits.resolution() / kSubpixelScale;
  const MapLimits superscaled_limits(
      superscaled_resolution, limits.max(),
      CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale,
                 limits.cell_limits().num_y_cells * kSubpixelScale));

  const Eigen::Array2i superscaled_begin =
      superscaled_limits.GetCellIndex(begin);
  const Eigen::Array2i superscaled_end = superscaled_limits.GetCellIndex(end);
  return std::make_pair(superscaled_begin, superscaled_end);
}

struct RangeDataSorter {
  RangeDataSorter(Eigen::Vector3f origin) { origin_ = origin.head<2>(); }
  bool operator()(const sensor::RangefinderPoint& lhs,
                  const sensor::RangefinderPoint& rhs) {
    const Eigen::Vector2f delta_lhs =
        (lhs.position.head<2>() - origin_).normalized();
    const Eigen::Vector2f delta_rhs =
        (rhs.position.head<2>() - origin_).normalized();
    if ((delta_lhs[1] < 0.f) != (delta_rhs[1] < 0.f)) {
      return delta_lhs[1] < 0.f;
    } else if (delta_lhs[1] < 0.f) {
      return delta_lhs[0] < delta_rhs[0];
    } else {
      return delta_lhs[0] > delta_rhs[0];
    }
  }

 private:
  Eigen::Vector2f origin_;
};

float ComputeRangeWeightFactor(float range, int exponent) {
  float weight = 0.f;
  if (std::abs(range) > kMinRangeMeters) {
    weight = 1.f / (std::pow(range, exponent));
  }
  return weight;
}
}  // namespace

proto::TSDFRangeDataInserterOptions2D CreateTSDFRangeDataInserterOptions2D(
    common::LuaParameterDictionary* parameter_dictionary) {
  proto::TSDFRangeDataInserterOptions2D options;
  options.set_truncation_distance(
      parameter_dictionary->GetDouble("truncation_distance"));
  options.set_maximum_weight(parameter_dictionary->GetDouble("maximum_weight"));
  options.set_update_free_space(
      parameter_dictionary->GetBool("update_free_space"));
  *options
       .mutable_normal_estimation_options() = CreateNormalEstimationOptions2D(
      parameter_dictionary->GetDictionary("normal_estimation_options").get());
  options.set_project_sdf_distance_to_scan_normal(
      parameter_dictionary->GetBool("project_sdf_distance_to_scan_normal"));
  options.set_update_weight_range_exponent(
      parameter_dictionary->GetInt("update_weight_range_exponent"));
  options.set_update_weight_angle_scan_normal_to_ray_kernel_bandwidth(
      parameter_dictionary->GetDouble(
          "update_weight_angle_scan_normal_to_ray_kernel_bandwidth"));
  options.set_update_weight_distance_cell_to_hit_kernel_bandwidth(
      parameter_dictionary->GetDouble(
          "update_weight_distance_cell_to_hit_kernel_bandwidth"));
  return options;
}

TSDFRangeDataInserter2D::TSDFRangeDataInserter2D(
    const proto::TSDFRangeDataInserterOptions2D& options)
    : options_(options) {}

// Casts a ray from origin towards hit for each hit in range data.
// If 'options.update_free_space' is 'true', all cells along the ray
// until 'truncation_distance' behind hit are updated. Otherwise, only the cells
// within 'truncation_distance' around hit are updated.
void TSDFRangeDataInserter2D::Insert(const sensor::RangeData& range_data,
                                     GridInterface* grid) const {
  const float truncation_distance =
      static_cast<float>(options_.truncation_distance());
  TSDF2D* tsdf = static_cast<TSDF2D*>(grid);
  GrowAsNeeded(range_data, truncation_distance, tsdf);

  // Compute normals if needed.
  bool scale_update_weight_angle_scan_normal_to_ray =
      options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f;
  sensor::RangeData sorted_range_data = range_data;
  std::vector<float> normals;
  if (options_.project_sdf_distance_to_scan_normal() ||
      scale_update_weight_angle_scan_normal_to_ray) {
    std::sort(sorted_range_data.returns.begin(),
              sorted_range_data.returns.end(),
              RangeDataSorter(sorted_range_data.origin));
    normals = EstimateNormals(sorted_range_data,
                              options_.normal_estimation_options());
  }

  const Eigen::Vector2f origin = sorted_range_data.origin.head<2>();
  for (size_t hit_index = 0; hit_index < sorted_range_data.returns.size();
       ++hit_index) {
    const Eigen::Vector2f hit =
        sorted_range_data.returns[hit_index].position.head<2>();
    const float normal = normals.empty()
                             ? std::numeric_limits<float>::quiet_NaN()
                             : normals[hit_index];
    InsertHit(options_, hit, origin, normal, tsdf);
  }
  tsdf->FinishUpdate();
}

void TSDFRangeDataInserter2D::InsertHit(
    const proto::TSDFRangeDataInserterOptions2D& options,
    const Eigen::Vector2f& hit, const Eigen::Vector2f& origin, float normal,
    TSDF2D* tsdf) const {
  const Eigen::Vector2f ray = hit - origin;
  const float range = ray.norm();
  const float truncation_distance =
      static_cast<float>(options_.truncation_distance());
  if (range < truncation_distance) return;
  const float truncation_ratio = truncation_distance / range;
  const Eigen::Vector2f ray_begin =
      options_.update_free_space() ? origin
                                   : origin + (1.0f - truncation_ratio) * ray;
  const Eigen::Vector2f ray_end = origin + (1.0f + truncation_ratio) * ray;
  std::pair<Eigen::Array2i, Eigen::Array2i> superscaled_ray =
      SuperscaleRay(ray_begin, ray_end, tsdf);
  std::vector<Eigen::Array2i> ray_mask = RayToPixelMask(
      superscaled_ray.first, superscaled_ray.second, kSubpixelScale);

  // Precompute weight factors.
  float weight_factor_angle_ray_normal = 1.f;
  if (options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() !=
      0.f) {
    const Eigen::Vector2f negative_ray = -ray;
    float angle_ray_normal =
        common::NormalizeAngleDifference(normal - common::atan2(negative_ray));
    weight_factor_angle_ray_normal = GaussianKernel(
        angle_ray_normal,
        options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth());
  }
  float weight_factor_range = 1.f;
  if (options_.update_weight_range_exponent() != 0) {
    weight_factor_range = ComputeRangeWeightFactor(
        range, options_.update_weight_range_exponent());
  }

  // Update Cells.
  for (const Eigen::Array2i& cell_index : ray_mask) {
    if (tsdf->CellIsUpdated(cell_index)) continue;
    Eigen::Vector2f cell_center = tsdf->limits().GetCellCenter(cell_index);
    float distance_cell_to_origin = (cell_center - origin).norm();
    float update_tsd = range - distance_cell_to_origin;
    if (options_.project_sdf_distance_to_scan_normal()) {
      float normal_orientation = normal;
      update_tsd = (cell_center - hit)
                       .dot(Eigen::Vector2f{std::cos(normal_orientation),
                                            std::sin(normal_orientation)});
    }
    update_tsd =
        common::Clamp(update_tsd, -truncation_distance, truncation_distance);
    float update_weight = weight_factor_range * weight_factor_angle_ray_normal;
    if (options_.update_weight_distance_cell_to_hit_kernel_bandwidth() != 0.f) {
      update_weight *= GaussianKernel(
          update_tsd,
          options_.update_weight_distance_cell_to_hit_kernel_bandwidth());
    }
    UpdateCell(cell_index, update_tsd, update_weight, tsdf);
  }
}

void TSDFRangeDataInserter2D::UpdateCell(const Eigen::Array2i& cell,
                                         float update_sdf, float update_weight,
                                         TSDF2D* tsdf) const {
  if (update_weight == 0.f) return;
  const std::pair<float, float> tsd_and_weight = tsdf->GetTSDAndWeight(cell);
  float updated_weight = tsd_and_weight.second + update_weight;
  float updated_sdf = (tsd_and_weight.first * tsd_and_weight.second +
                       update_sdf * update_weight) /
                      updated_weight;
  updated_weight =
      std::min(updated_weight, static_cast<float>(options_.maximum_weight()));
  tsdf->SetCell(cell, updated_sdf, updated_weight);
}

}  // namespace mapping
}  // namespace cartographer
<|endoftext|>


<commit_before>#include <osg/Notify>
#include <string>

using namespace std;

osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;
std::auto_ptr<ofstream> osg::g_NotifyNulStream;
bool osg::g_NotifyInit = false;

void osg::setNotifyLevel(osg::NotifySeverity severity)
{
    osg::initNotifyLevel();
    g_NotifyLevel = severity;
}

osg::NotifySeverity osg::getNotifyLevel()
{
    osg::initNotifyLevel();
    return g_NotifyLevel;
}

bool osg::initNotifyLevel()
{
    if (g_NotifyInit) return true;

    g_NotifyInit = true;

    // set up global notify null stream for inline notify
#if defined(WIN32) && !defined(__CYGWIN__)
    g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream ("nul"));
#else
    g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null"));
#endif

    // g_NotifyLevel
    // =============

    g_NotifyLevel = osg::NOTICE; // Default value

    char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL");
    if(OSGNOTIFYLEVEL)
    {

        std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);

        // Convert to upper case
        for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();
            i!=stringOSGNOTIFYLEVEL.end();
            ++i)
        {
            *i=toupper(*i);
        }

        if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos)          g_NotifyLevel=osg::ALWAYS;
        else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos)      g_NotifyLevel=osg::FATAL;
        else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos)       g_NotifyLevel=osg::WARN;
        else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos)     g_NotifyLevel=osg::NOTICE;
        else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos)       g_NotifyLevel=osg::INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos)   g_NotifyLevel=osg::DEBUG_FP;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos)      g_NotifyLevel=osg::DEBUG_INFO;

    }

    return true;

}
<commit_msg>Changed the Windows gauard around so that it only works for VisualStudio and not Cygwin/Mingw.<commit_after>#include <osg/Notify>
#include <string>

using namespace std;

osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;
std::auto_ptr<ofstream> osg::g_NotifyNulStream;
bool osg::g_NotifyInit = false;

void osg::setNotifyLevel(osg::NotifySeverity severity)
{
    osg::initNotifyLevel();
    g_NotifyLevel = severity;
}

osg::NotifySeverity osg::getNotifyLevel()
{
    osg::initNotifyLevel();
    return g_NotifyLevel;
}

bool osg::initNotifyLevel()
{
    if (g_NotifyInit) return true;

    g_NotifyInit = true;

    // set up global notify null stream for inline notify
#if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__))
    g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream ("nul"));
#else
    g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null"));
#endif

    // g_NotifyLevel
    // =============

    g_NotifyLevel = osg::NOTICE; // Default value

    char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL");
    if(OSGNOTIFYLEVEL)
    {

        std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);

        // Convert to upper case
        for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();
            i!=stringOSGNOTIFYLEVEL.end();
            ++i)
        {
            *i=toupper(*i);
        }

        if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos)          g_NotifyLevel=osg::ALWAYS;
        else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos)      g_NotifyLevel=osg::FATAL;
        else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos)       g_NotifyLevel=osg::WARN;
        else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos)     g_NotifyLevel=osg::NOTICE;
        else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos)       g_NotifyLevel=osg::INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos)   g_NotifyLevel=osg::DEBUG_FP;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos)      g_NotifyLevel=osg::DEBUG_INFO;

    }

    return true;

}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by ScyllaDB
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <deque>

namespace utils {

/**
 * bounded threadsafe deque
 */
class bounded_stats_deque {
private:
    std::deque<long> _deque;
    long _sum = 0;
    int _max_size;
public:
    bounded_stats_deque(int size)
        : _max_size(size) {
    }

    int size() {
        return _deque.size();
    }

    void add(long i) {
        if (size() >= _max_size) {
            auto removed = _deque.front();
            _deque.pop_front();
            _sum -= removed;
        }
        _deque.push_back(i);
        _sum += i;
    }

    long sum() {
        return _sum;
    }

    double mean() {
        return size() > 0 ? ((double) sum()) / size() : 0;
    }

    const std::deque<long>& deque() const {
        return _deque;
    }
};

}
<commit_msg>bounded_stats_queue: add missing const qualifiers<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by ScyllaDB
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <deque>

namespace utils {

/**
 * bounded threadsafe deque
 */
class bounded_stats_deque {
private:
    std::deque<long> _deque;
    long _sum = 0;
    int _max_size;
public:
    bounded_stats_deque(int size)
        : _max_size(size) {
    }

    int size() const {
        return _deque.size();
    }

    void add(long i) {
        if (size() >= _max_size) {
            auto removed = _deque.front();
            _deque.pop_front();
            _sum -= removed;
        }
        _deque.push_back(i);
        _sum += i;
    }

    long sum() const {
        return _sum;
    }

    double mean() const {
        return size() > 0 ? ((double) sum()) / size() : 0;
    }

    const std::deque<long>& deque() const {
        return _deque;
    }
};

}
<|endoftext|>


<commit_before>/*
 * C S O U N D   V S T
 *
 * A VST plugin version of Csound, with Python scripting.
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef RANDOM_H
#define RANDOM_H
#if defined(_MSC_VER) && !defined(__GNUC__)
#pragma warning (disable:4786)
#endif

#include "Platform.hpp"
#ifdef SWIG
%module CsoundAC
%{
#include "Node.hpp"
#include <boost/random.hpp>
#include <boost/random/variate_generator.hpp>
#include <cmath>
  %}
#else
#include "Node.hpp"
#include <boost/random.hpp>
#include <boost/random/variate_generator.hpp>
#include <cmath>
using namespace boost::numeric;
#endif

namespace csound
{

  /**
   * A random value will be sampled from the specified distribution,
   * translated and scaled as specified,
   * and set in the specified row and column of the local coordinates.
   * The resulting matrix will be used in place of the local coordinates
   * when traversing the music graph.
   * If eventCount is greater than zero, a new event will be created
   * for each of eventCount samples,
   * which will be transformed by the newly sampled local coordinates.
   */
  class SILENCE_PUBLIC Random :
    public Node
  {
  protected:
#if !defined(SWIG)
    void *generator_;
    boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator;
    boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator;
    boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator;
    boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator;
  public:
    static boost::mt19937 mersenneTwister;
#endif
    std::string distribution;
    int row;
    int column;
    int eventCount;
    bool incrementTime;
    double minimum;
    double maximum;
    double q;
    double a;
    double b;
    double c;
    double Lambda;
    double mean;
    double sigma;
    Random();
    virtual ~Random();
    virtual double sample() const;
    virtual ublas::matrix<double> getLocalCoordinates() const;
    virtual void createDistribution(std::string distribution);
    virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates);
    static void seed(int s);
  };
}
#endif
<commit_msg>Restore necessary functions to "public".<commit_after>/*
 * C S O U N D   V S T
 *
 * A VST plugin version of Csound, with Python scripting.
 *
 * L I C E N S E
 *
 * This software is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef RANDOM_H
#define RANDOM_H

#include "Platform.hpp"
#ifdef SWIG
%module CsoundAC
%{
#include "Node.hpp"
  %}
#else
#include "Node.hpp"
#include <boost/random.hpp>
#include <boost/random/variate_generator.hpp>
#include <cmath>
using namespace boost::numeric;
#endif

namespace csound
{

  /**
   * A random value will be sampled from the specified distribution,
   * translated and scaled as specified,
   * and set in the specified row and column of the local coordinates.
   * The resulting matrix will be used in place of the local coordinates
   * when traversing the music graph.
   * If eventCount is greater than zero, a new event will be created
   * for each of eventCount samples,
   * which will be transformed by the newly sampled local coordinates.
   */
  class SILENCE_PUBLIC Random :
    public Node
  {
  protected:
#if !defined(SWIG)
    void *generator_;
    boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator;
    boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator;
    boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator;
    boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator;
    boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator;
  public:
    static boost::mt19937 mersenneTwister;
#endif
  public:
    std::string distribution;
    int row;
    int column;
    int eventCount;
    bool incrementTime;
    double minimum;
    double maximum;
    double q;
    double a;
    double b;
    double c;
    double Lambda;
    double mean;
    double sigma;
    Random();
    virtual ~Random();
    virtual double sample() const;
    virtual ublas::matrix<double> getLocalCoordinates() const;
    virtual void createDistribution(std::string distribution);
    virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates);
    static void seed(int s);
  };
}
#endif
<|endoftext|>


<commit_before>/*
syslog.cpp

   :-)

*/

/* Revision: 1.14 25.07.2001 $ */

/*
Modify:
  25.07.2001 SVS
    -     VC
  24.07.2001 SVS
    +     (IsDebuggerPresent),
       LOG-  (OutputDebugString)
      !   98-  .
  04.07.2001 SVS
    !   LOG- :-)
    +
  27.06.2001 SVS
    !   LOG- :-)
           %FAR%\$Log
      Far.YYYYMMDD.BILD.log - BILD=%05d
  25.06.2001 SVS
    !    StrFTime  .
  16.05.2001 SVS
    ! DumpExceptionInfo -> farexcpt.cpp
    + _SYSLOG_KM()
  09.05.2001 OT
    ! ,  _D(x),
  07.05.2001 SVS
    +  DumpExceptionInfo      FAR_VERSION
  06.05.2001 DJ
    !  #include
  06.05.2001 SVS
    !    SysLog* ;-)
  29.04.2001
    +  NWZ
  28.04.2001 SVS
    -   ,   CONTEXT_INTEGER
      CONTEXT_SEGMENTS
    !     SysLog()
    +     SysLogDump()
          = NULL,      ,
          .
  26.01.2001 SVS
    ! DumpExeptionInfo -> DumpExceptionInfo ;-)
  23.01.2001 SVS
    + DumpExeptionInfo()
  22.12.2000 SVS
    +
*/

#include "headers.hpp"
#pragma hdrstop

#include "plugin.hpp"
#include "global.hpp"
#include "fn.hpp"
#include "plugins.hpp"

#if !defined(SYSLOG)
 #if defined(SYSLOG_OT) || defined(SYSLOG_SVS) || defined(SYSLOG_DJ) || defined(VVM) || defined(SYSLOG_AT) || defined(SYSLOG_IS) || defined(SYSLOG_tran) || defined(SYSLOG_SKV) || defined(SYSLOG_NWZ) || defined(SYSLOG_KM)
  #define SYSLOG
 #endif
#endif

#if defined(SYSLOG)
char         LogFileName[MAX_FILE];
static FILE *LogStream=0;
static int   Indent=0;
static char *PrintTime(char *timebuf);

extern "C" {
WINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID);
};

#endif

#if defined(SYSLOG)
char *MakeSpace(void)
{
  static char Buf[60]=" ";
  if(Indent)
    memset(Buf+1,0xB3,Indent);
  Buf[1+Indent]=0;
  return Buf;
}
#endif

FILE * OpenLogStream(char *file)
{
#if defined(SYSLOG)
  time_t t;
  struct tm *time_now;
  char RealLogName[NM*2];
  SYSTEMTIME st;

  GetLocalTime(&st);
  sprintf(RealLogName,"%s\\Far.%04d%02d%02d.%05d.log",
      file,st.wYear,st.wMonth,st.wDay,HIWORD(FAR_VERSION));
  return _fsopen(RealLogName,"a+t",SH_DENYWR);
#else
  return NULL;
#endif
}

void OpenSysLog()
{
#if defined(SYSLOG)
  if ( LogStream )
      fclose(LogStream);
  DWORD Attr;

  GetModuleFileName(NULL,LogFileName,sizeof(LogFileName));
  char *Ptr=strrchr(LogFileName,'\\');
  strcpy(Ptr,"\\$Log");
  Attr=GetFileAttributes(LogFileName);
  if(Attr == -1)
  {
    if(!CreateDirectory(LogFileName,NULL))
      *Ptr=0;
  }
  else if(!(Attr&FILE_ATTRIBUTE_DIRECTORY))
    *Ptr=0;
  LogStream=OpenLogStream(LogFileName);
  //if ( !LogStream )
  //{
  //    fprintf(stderr,"Can't open log file '%s'\n",LogFileName);
  //}
#endif
}

void CloseSysLog(void)
{
#if defined(SYSLOG)
    fclose(LogStream);
    LogStream=0;
#endif
}

void ShowHeap()
{
#if defined(SYSLOG) && defined(HEAPLOG)
  _HEAPINFO hi;

  SysLog( "   Size   Status" );
  SysLog( "   ----   ------" );
  DWORD Sz=0;
  hi._pentry=NULL;
//    int     *__pentry;
  while( _rtl_heapwalk( &hi ) == _HEAPOK )
  {
    SysLog( "%7u    %s  (%p)", hi._size, (hi._useflag ? "used" : "free"),hi.__pentry);
    Sz+=hi._useflag?hi._size:0;
  }
  SysLog( "   ----   ------" );
  SysLog( "%7u      ", Sz);

#endif
}

void CheckHeap(int NumLine)
{
#if defined(SYSLOG) && defined(HEAPLOG)
  if (_heapchk()==_HEAPBADNODE)
  {
    SysLog("Error: Heap broken, Line=%d",NumLine);
  }
#endif
}

void SysLog(int i)
{
#if defined(SYSLOG)
    Indent+=i;
    if ( Indent<0 )
        Indent=0;
#endif
}

#if defined(SYSLOG)
static char *PrintTime(char *timebuf)
{
  SYSTEMTIME st;
  GetLocalTime(&st);
//  sprintf(timebuf,"%02d.%02d.%04d %2d:%02d:%02d.%03d",
//      st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
  sprintf(timebuf,"%02d:%02d:%02d.%03d",st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
  return timebuf;
}
#endif

void SysLog(char *fmt,...)
{
#if defined(SYSLOG)
  char msg[MAX_LOG_LINE];

  va_list argptr;
  va_start( argptr, fmt );

  vsprintf( msg, fmt, argptr );
  va_end(argptr);

  OpenSysLog();
  if ( LogStream )
  {
    char timebuf[64];
    fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg);
    fflush(LogStream);
  }
  CloseSysLog();
  if(IsDebuggerPresent())
  {
    OutputDebugString(msg);
  }
#endif
}

///
void SysLog(int l,char *fmt,...)
{
#if defined(SYSLOG)
  char msg[MAX_LOG_LINE];

  va_list argptr;
  va_start( argptr, fmt );

  vsprintf( msg, fmt, argptr );
  va_end(argptr);

  SysLog(l);
  OpenSysLog();
  if ( LogStream )
  {
    char timebuf[64];
    fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg);
    fflush(LogStream);
  }
  CloseSysLog();
  if(IsDebuggerPresent())
  {
    OutputDebugString(msg);
  }
#endif
}
///

void SysLogDump(char *Title,DWORD StartAddress,LPBYTE Buf,int SizeBuf,FILE *fp)
{
#if defined(SYSLOG)
  int CY=(SizeBuf+15)/16;
  int X,Y;
  int InternalLog=fp==NULL?TRUE:FALSE;

//  char msg[MAX_LOG_LINE];

  if(InternalLog)
  {
    OpenSysLog();
    fp=LogStream;
    if(fp)
    {
      char timebuf[64];
      fprintf(fp,"%s %s(%s)\n",PrintTime(timebuf),MakeSpace(),NullToEmpty(Title));
    }
  }

  if (fp)
  {
    char TmpBuf[17];
    int I;
    TmpBuf[16]=0;
    if(!InternalLog && Title && *Title)
      fprintf(fp,"%s\n",Title);
    for(Y=0; Y < CY; ++Y)
    {
      memset(TmpBuf,' ',16);
      fprintf(fp, " %08X: ",StartAddress+Y*16);
      for(X=0; X < 16; ++X)
      {
        if((I=Y*16+X < SizeBuf) != 0)
          fprintf(fp,"%02X ",Buf[Y*16+X]&0xFF);
        else
          fprintf(fp,"   ");
        TmpBuf[X]=I?(Buf[Y*16+X] < 32?'.':Buf[Y*16+X]):' ';
        if(X == 7)
          fprintf(fp, " ");
      }
      fprintf(fp,"| %s\n",TmpBuf);
    }
    fprintf(fp,"\n");
    fflush(fp);
  }

  if(InternalLog)
    CloseSysLog();
#endif
}
<commit_msg>FAR patch 00903.OutputDebugString Дата              : 15.08.2001 Сделал            : Oleg Taranenko Описание          : "Перевод строки" в дебагере среды VC Измененные файлы  : syslog.cpp Новые файлы       : Удаленные файлы   : Состав            : 00903.OutputDebugString.txt                     syslog.cpp.903.diff Основан на патче  : 902 Дополнение        :<commit_after>/*
syslog.cpp

   :-)

*/

/* Revision: 1.15 15.08.2001 $ */

/*
Modify:
  15.08.2001 OT
    - " "    VC
  25.07.2001 SVS
    -     VC
  24.07.2001 SVS
    +     (IsDebuggerPresent),
       LOG-  (OutputDebugString)
      !   98-  .
  04.07.2001 SVS
    !   LOG- :-)
    +
  27.06.2001 SVS
    !   LOG- :-)
           %FAR%\$Log
      Far.YYYYMMDD.BILD.log - BILD=%05d
  25.06.2001 SVS
    !    StrFTime  .
  16.05.2001 SVS
    ! DumpExceptionInfo -> farexcpt.cpp
    + _SYSLOG_KM()
  09.05.2001 OT
    ! ,  _D(x),
  07.05.2001 SVS
    +  DumpExceptionInfo      FAR_VERSION
  06.05.2001 DJ
    !  #include
  06.05.2001 SVS
    !    SysLog* ;-)
  29.04.2001
    +  NWZ
  28.04.2001 SVS
    -   ,   CONTEXT_INTEGER
      CONTEXT_SEGMENTS
    !     SysLog()
    +     SysLogDump()
          = NULL,      ,
          .
  26.01.2001 SVS
    ! DumpExeptionInfo -> DumpExceptionInfo ;-)
  23.01.2001 SVS
    + DumpExeptionInfo()
  22.12.2000 SVS
    +
*/

#include "headers.hpp"
#pragma hdrstop

#include "plugin.hpp"
#include "global.hpp"
#include "fn.hpp"
#include "plugins.hpp"

#if !defined(SYSLOG)
 #if defined(SYSLOG_OT) || defined(SYSLOG_SVS) || defined(SYSLOG_DJ) || defined(VVM) || defined(SYSLOG_AT) || defined(SYSLOG_IS) || defined(SYSLOG_tran) || defined(SYSLOG_SKV) || defined(SYSLOG_NWZ) || defined(SYSLOG_KM)
  #define SYSLOG
 #endif
#endif

#if defined(SYSLOG)
char         LogFileName[MAX_FILE];
static FILE *LogStream=0;
static int   Indent=0;
static char *PrintTime(char *timebuf);

extern "C" {
WINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID);
};

#endif

#if defined(SYSLOG)
char *MakeSpace(void)
{
  static char Buf[60]=" ";
  if(Indent)
    memset(Buf+1,0xB3,Indent);
  Buf[1+Indent]=0;
  return Buf;
}
#endif

FILE * OpenLogStream(char *file)
{
#if defined(SYSLOG)
  time_t t;
  struct tm *time_now;
  char RealLogName[NM*2];
  SYSTEMTIME st;

  GetLocalTime(&st);
  sprintf(RealLogName,"%s\\Far.%04d%02d%02d.%05d.log",
      file,st.wYear,st.wMonth,st.wDay,HIWORD(FAR_VERSION));
  return _fsopen(RealLogName,"a+t",SH_DENYWR);
#else
  return NULL;
#endif
}

void OpenSysLog()
{
#if defined(SYSLOG)
  if ( LogStream )
      fclose(LogStream);
  DWORD Attr;

  GetModuleFileName(NULL,LogFileName,sizeof(LogFileName));
  char *Ptr=strrchr(LogFileName,'\\');
  strcpy(Ptr,"\\$Log");
  Attr=GetFileAttributes(LogFileName);
  if(Attr == -1)
  {
    if(!CreateDirectory(LogFileName,NULL))
      *Ptr=0;
  }
  else if(!(Attr&FILE_ATTRIBUTE_DIRECTORY))
    *Ptr=0;
  LogStream=OpenLogStream(LogFileName);
  //if ( !LogStream )
  //{
  //    fprintf(stderr,"Can't open log file '%s'\n",LogFileName);
  //}
#endif
}

void CloseSysLog(void)
{
#if defined(SYSLOG)
    fclose(LogStream);
    LogStream=0;
#endif
}

void ShowHeap()
{
#if defined(SYSLOG) && defined(HEAPLOG)
  _HEAPINFO hi;

  SysLog( "   Size   Status" );
  SysLog( "   ----   ------" );
  DWORD Sz=0;
  hi._pentry=NULL;
//    int     *__pentry;
  while( _rtl_heapwalk( &hi ) == _HEAPOK )
  {
    SysLog( "%7u    %s  (%p)", hi._size, (hi._useflag ? "used" : "free"),hi.__pentry);
    Sz+=hi._useflag?hi._size:0;
  }
  SysLog( "   ----   ------" );
  SysLog( "%7u      ", Sz);

#endif
}

void CheckHeap(int NumLine)
{
#if defined(SYSLOG) && defined(HEAPLOG)
  if (_heapchk()==_HEAPBADNODE)
  {
    SysLog("Error: Heap broken, Line=%d",NumLine);
  }
#endif
}

void SysLog(int i)
{
#if defined(SYSLOG)
    Indent+=i;
    if ( Indent<0 )
        Indent=0;
#endif
}

#if defined(SYSLOG)
static char *PrintTime(char *timebuf)
{
  SYSTEMTIME st;
  GetLocalTime(&st);
//  sprintf(timebuf,"%02d.%02d.%04d %2d:%02d:%02d.%03d",
//      st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
  sprintf(timebuf,"%02d:%02d:%02d.%03d",st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
  return timebuf;
}
#endif

void SysLog(char *fmt,...)
{
#if defined(SYSLOG)
  char msg[MAX_LOG_LINE];

  va_list argptr;
  va_start( argptr, fmt );

  vsprintf( msg, fmt, argptr );
  va_end(argptr);

  OpenSysLog();
  if ( LogStream )
  {
    char timebuf[64];
    fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg);
    fflush(LogStream);
  }
  CloseSysLog();
  if(IsDebuggerPresent())
  {
    OutputDebugString(msg);
#ifdef _MSC_VER
    OutputDebugString("\n");
#endif _MSC_VER
  }
#endif
}

///
void SysLog(int l,char *fmt,...)
{
#if defined(SYSLOG)
  char msg[MAX_LOG_LINE];

  va_list argptr;
  va_start( argptr, fmt );

  vsprintf( msg, fmt, argptr );
  va_end(argptr);

  SysLog(l);
  OpenSysLog();
  if ( LogStream )
  {
    char timebuf[64];
    fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg);
    fflush(LogStream);
  }
  CloseSysLog();
  if(IsDebuggerPresent())
  {
    OutputDebugString(msg);
  }
#endif
}
///

void SysLogDump(char *Title,DWORD StartAddress,LPBYTE Buf,int SizeBuf,FILE *fp)
{
#if defined(SYSLOG)
  int CY=(SizeBuf+15)/16;
  int X,Y;
  int InternalLog=fp==NULL?TRUE:FALSE;

//  char msg[MAX_LOG_LINE];

  if(InternalLog)
  {
    OpenSysLog();
    fp=LogStream;
    if(fp)
    {
      char timebuf[64];
      fprintf(fp,"%s %s(%s)\n",PrintTime(timebuf),MakeSpace(),NullToEmpty(Title));
    }
  }

  if (fp)
  {
    char TmpBuf[17];
    int I;
    TmpBuf[16]=0;
    if(!InternalLog && Title && *Title)
      fprintf(fp,"%s\n",Title);
    for(Y=0; Y < CY; ++Y)
    {
      memset(TmpBuf,' ',16);
      fprintf(fp, " %08X: ",StartAddress+Y*16);
      for(X=0; X < 16; ++X)
      {
        if((I=Y*16+X < SizeBuf) != 0)
          fprintf(fp,"%02X ",Buf[Y*16+X]&0xFF);
        else
          fprintf(fp,"   ");
        TmpBuf[X]=I?(Buf[Y*16+X] < 32?'.':Buf[Y*16+X]):' ';
        if(X == 7)
          fprintf(fp, " ");
      }
      fprintf(fp,"| %s\n",TmpBuf);
    }
    fprintf(fp,"\n");
    fflush(fp);
  }

  if(InternalLog)
    CloseSysLog();
#endif
}
<|endoftext|>


<commit_before>#include <osg/Notify>
#include <string>

using namespace std;

osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;
std::auto_ptr<ofstream> osg::g_NotifyNulStream;
bool osg::g_NotifyInit = false;

void osg::setNotifyLevel(osg::NotifySeverity severity)
{
    osg::initNotifyLevel();
    g_NotifyLevel = severity;
}

osg::NotifySeverity osg::getNotifyLevel()
{
    osg::initNotifyLevel();
    return g_NotifyLevel;
}

bool osg::initNotifyLevel()
{
    if (g_NotifyInit) return true;

    g_NotifyInit = true;

    // set up global notify null stream for inline notify
#if defined(WIN32) && !defined(__CYGWIN__)
    g_NotifyNulStream.reset(osgNew std::ofstream ("nul"));
#else
    g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null"));
#endif

    // g_NotifyLevel
    // =============

    g_NotifyLevel = osg::NOTICE; // Default value

    char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL");
    if(OSGNOTIFYLEVEL)
    {

        std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);

        // Convert to upper case
        for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();
            i!=stringOSGNOTIFYLEVEL.end();
            ++i)
        {
            *i=toupper(*i);
        }

        if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos)          g_NotifyLevel=osg::ALWAYS;
        else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos)      g_NotifyLevel=osg::FATAL;
        else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos)       g_NotifyLevel=osg::WARN;
        else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos)     g_NotifyLevel=osg::NOTICE;
        else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos)       g_NotifyLevel=osg::INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos)   g_NotifyLevel=osg::DEBUG_FP;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos)      g_NotifyLevel=osg::DEBUG_INFO;

    }

    return true;

}
<commit_msg>Fix for VisualStudio's lack of auto_ptr::reset.<commit_after>#include <osg/Notify>
#include <string>

using namespace std;

osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;
std::auto_ptr<ofstream> osg::g_NotifyNulStream;
bool osg::g_NotifyInit = false;

void osg::setNotifyLevel(osg::NotifySeverity severity)
{
    osg::initNotifyLevel();
    g_NotifyLevel = severity;
}

osg::NotifySeverity osg::getNotifyLevel()
{
    osg::initNotifyLevel();
    return g_NotifyLevel;
}

bool osg::initNotifyLevel()
{
    if (g_NotifyInit) return true;

    g_NotifyInit = true;

    // set up global notify null stream for inline notify
#if defined(WIN32) && !defined(__CYGWIN__)
    g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream ("nul"));
#else
    g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null"));
#endif

    // g_NotifyLevel
    // =============

    g_NotifyLevel = osg::NOTICE; // Default value

    char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL");
    if(OSGNOTIFYLEVEL)
    {

        std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);

        // Convert to upper case
        for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();
            i!=stringOSGNOTIFYLEVEL.end();
            ++i)
        {
            *i=toupper(*i);
        }

        if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos)          g_NotifyLevel=osg::ALWAYS;
        else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos)      g_NotifyLevel=osg::FATAL;
        else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos)       g_NotifyLevel=osg::WARN;
        else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos)     g_NotifyLevel=osg::NOTICE;
        else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos)       g_NotifyLevel=osg::INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos)   g_NotifyLevel=osg::DEBUG_FP;
        else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos)      g_NotifyLevel=osg::DEBUG_INFO;

    }

    return true;

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FileAPI) {
  ASSERT_TRUE(RunExtensionTest("fileapi")) << message_;
}
<commit_msg>mark FileAPI failing for the moment to continue triaging webkit roll.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_FileAPI) {
  ASSERT_TRUE(RunExtensionTest("fileapi")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

// TODO(jcampan): http://crbug.com/27216 disabled because failing.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<commit_msg>Re-enable the ExtensionApiTest.Storage test.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<|endoftext|>