<commit_before>#include "OpenFlipper.hh"
#include "PyModules/PyMeshType.hh"
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <ObjectTypes/PolyMesh/PolyMesh.hh>
#include <ObjectTypes/TriangleMesh/TriangleMesh.hh>
#include <ACG/Utils/SmartPointer.hh>

#include <pybind11/pybind11.h>
#include <pybind11/operators.h>

#include <OpenFlipper/BasePlugin/RPCWrappers.hh>
#include <OpenFlipper/common/UpdateType.hh>

#include <algorithm>
#include <functional>
#include <unordered_map>

namespace py = pybind11;

const std::unordered_map < std::string, std::function<QScriptValue(QScriptEngine* e, const py::object&) >> type_conversion_map =
{
    { "QString",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(QString(py::cast<std::string>(obj).c_str())); } },
        { "int",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<int>(obj)); } },
        { "uint" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<uint>(obj)); } },
        { "bool" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<bool>(obj)); } },
        { "IdList" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<IdList>(obj)); } },
        { "Vector" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector>(obj)); } },
        { "Vector4" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector4>(obj)); } },
        { "UpdateType" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<UpdateType>(obj)); } },
};

py::dict create_dict_from_ids(const std::vector<int>& ids)
{
    py::dict d;
    for (int i : ids)
    {
        TriMeshObject* triobj;
        PolyMeshObject* polyobj;
        if (PluginFunctions::getObject(i, triobj))
        {
            PyTriMesh* m = reinterpret_cast<PyTriMesh*>(triobj->mesh());
            d[triobj->name().toLatin1()] = py::cast(m);
        }
        else if (PluginFunctions::getObject(i, polyobj))
        {
            PyPolyMesh* m = reinterpret_cast<PyPolyMesh*>(polyobj->mesh());
            d[polyobj->name().toLatin1()] = py::cast(m);
        }

    }
    return d;
}

py::dict targets()
{
    std::vector<int> ids;
    PluginFunctions::getTargetIdentifiers(ids);
    return create_dict_from_ids(ids);
}

py::dict sources()
{
    std::vector<int> ids;
    PluginFunctions::getSourceIdentifiers(ids);
    return create_dict_from_ids(ids);
}

py::dict meshes()
{
    std::vector<int> ids;
    PluginFunctions::getAllMeshes(ids);
    return create_dict_from_ids(ids);
}

py::object rpc_call(const char* plugin_name, const char* function_name, std::vector<QScriptValue> params)
{
    QScriptValue ret = RPC::callFunction(plugin_name, function_name, std::move(params));
    if (ret.isNumber())
        return py::cast(ret.toInt32());

    return py::none();
}

py::object rpc_call(const char* plugin_name, const char* function_name, const py::list& py_params/*{ QString:"value",... }*/)
{
    std::vector<QScriptValue> q_params;
    // convert parameters to scriptvalues

    QScriptEngine* engine = RPC::getScriptEngine();
    for (py::ssize_t i = 0; i < py::len(py_params); i+=2)
    {
        std::string type_name = py::cast<std::string>(py_params[i]);

        auto it = type_conversion_map.find(type_name);
        if (it == std::end(type_conversion_map)) //todo: raise exception
        {
            const QString err = QString("In function %1, parameter #%2 is can not be converted to %3.").arg(QString(function_name), QString::number(i / 2), QString(type_name.c_str()));
            PyErr_SetString(PyExc_ValueError, err.toLatin1());
            return py::none();
        }
        auto cast_f = it->second;

        q_params.push_back(cast_f(engine, py_params[i+1]));
    }
    if (PyErr_Occurred())
    	return py::none();
    return rpc_call(plugin_name, function_name, std::move(q_params));
}

py::object rpc_call(const char* plugin_name, const char* function_name)
{
    std::vector<QScriptValue> params;
    return rpc_call(plugin_name, function_name, std::move(params));
}

py::object getMesh(int id)
{
    PolyMesh* polymesh = nullptr;
    if (PluginFunctions::getMesh(id, polymesh))
        return py::cast(reinterpret_cast<PyPolyMesh*>(polymesh));

    TriMesh* trimesh = nullptr;
    if (PluginFunctions::getMesh(id, trimesh))
        return py::cast(reinterpret_cast<PyTriMesh*>(trimesh));

    // error case
    PyErr_SetString(PyExc_ValueError, "Passed Id is not a PolyMesh");
    return py::none();
}

template<typename Mesh>
py::object getID(void* addr)
{
    IdList idlist;
    PluginFunctions::getAllMeshes(idlist);
    auto iter = std::find_if(std::begin(idlist), std::end(idlist), [&addr](int id)
    {
        Mesh* mesh;
        if (!PluginFunctions::getMesh(id, mesh))
            return false;
        return ((void*)mesh == (void*)addr);
    });
    if (iter == std::end(idlist))
        return py::cast(-1); //todo raise exception
    return py::cast(int(*iter));
}

PYBIND11_MODULE(openflipper, m)
{
    m.def("targets", &targets);
    m.def("sources", &sources);
    m.def("meshes", &meshes);

    m.def("get_mesh", &getMesh);
    m.def("get_id", [](PyTriMesh* m) {return getID<TriMesh>(m); });
    m.def("get_id", [](PyPolyMesh* m) {return getID<PolyMesh>(m); });

    py::object (*rpc_callArgs)(const char*, const char*, const py::list&) = rpc_call;
    py::object (*rpc_callNoArgs)(const char* , const char* ) = rpc_call;
    m.def("rpc_call", rpc_callArgs);
    m.def("rpc_call", rpc_callNoArgs);

    py::class_<UpdateType> update_type(m, "Update");
    update_type
        .def(py::init<>())
        .def(py::init<UpdateType>())
        .def(py::self | py::self)
        .def(py::self |= py::self)
        .def("__contains__", &UpdateType::contains, py::is_operator())
        .def_property_readonly_static("none", [](py::object) {return UPDATE_NONE;})
        .def_property_readonly_static("ALL", [](py::object) {return UPDATE_ALL;})
        .def_property_readonly_static("VISIBILITY", [](py::object) {return UPDATE_VISIBILITY;})
        .def_property_readonly_static("GEOMETRY", [](py::object) {return UPDATE_GEOMETRY;})
        .def_property_readonly_static("TOPOLOGY", [](py::object) {return UPDATE_TOPOLOGY;})
        .def_property_readonly_static("SELECTION", [](py::object) {return UPDATE_SELECTION;})
        .def_property_readonly_static("SELECTION_VERTICES", [](py::object) {return UPDATE_SELECTION_VERTICES;})
        .def_property_readonly_static("SELECTION_EDGES", [](py::object) {return UPDATE_SELECTION_EDGES;})
        .def_property_readonly_static("SELECTION_HALFEDGES", [](py::object) {return UPDATE_SELECTION_HALFEDGES;})
        .def_property_readonly_static("SELECTION_FACES", [](py::object) {return UPDATE_SELECTION_FACES;})
        .def_property_readonly_static("SELECTION_KNOTS", [](py::object) {return UPDATE_SELECTION_KNOTS;})
        .def_property_readonly_static("COLOR", [](py::object) {return UPDATE_COLOR;})
        .def_property_readonly_static("TEXTURE", [](py::object) {return UPDATE_TEXTURE;})
        .def_property_readonly_static("STATE", [](py::object) {return UPDATE_STATE;})
        .def_property_readonly_static("UNUSED", [](py::object) {return UPDATE_UNUSED;;});
}

#if (PY_MAJOR_VERSION == 2)
    PyObject* (*openflipper_pyinit_function)(void) = &initopenflipper;//untested
#else
    PyObject* (*openflipper_pyinit_function)(void) = &PyInit_openflipper;
#endif
<commit_msg>capital<commit_after>#include "OpenFlipper.hh"
#include "PyModules/PyMeshType.hh"
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <ObjectTypes/PolyMesh/PolyMesh.hh>
#include <ObjectTypes/TriangleMesh/TriangleMesh.hh>
#include <ACG/Utils/SmartPointer.hh>

#include <pybind11/pybind11.h>
#include <pybind11/operators.h>

#include <OpenFlipper/BasePlugin/RPCWrappers.hh>
#include <OpenFlipper/common/UpdateType.hh>

#include <algorithm>
#include <functional>
#include <unordered_map>

namespace py = pybind11;

const std::unordered_map < std::string, std::function<QScriptValue(QScriptEngine* e, const py::object&) >> type_conversion_map =
{
    { "QString",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(QString(py::cast<std::string>(obj).c_str())); } },
        { "int",[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<int>(obj)); } },
        { "uint" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<uint>(obj)); } },
        { "bool" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<bool>(obj)); } },
        { "IdList" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<IdList>(obj)); } },
        { "Vector" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector>(obj)); } },
        { "Vector4" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<Vector4>(obj)); } },
        { "UpdateType" ,[](QScriptEngine* e, const py::object& obj) {return e->toScriptValue(py::cast<UpdateType>(obj)); } },
};

py::dict create_dict_from_ids(const std::vector<int>& ids)
{
    py::dict d;
    for (int i : ids)
    {
        TriMeshObject* triobj;
        PolyMeshObject* polyobj;
        if (PluginFunctions::getObject(i, triobj))
        {
            PyTriMesh* m = reinterpret_cast<PyTriMesh*>(triobj->mesh());
            d[triobj->name().toLatin1()] = py::cast(m);
        }
        else if (PluginFunctions::getObject(i, polyobj))
        {
            PyPolyMesh* m = reinterpret_cast<PyPolyMesh*>(polyobj->mesh());
            d[polyobj->name().toLatin1()] = py::cast(m);
        }

    }
    return d;
}

py::dict targets()
{
    std::vector<int> ids;
    PluginFunctions::getTargetIdentifiers(ids);
    return create_dict_from_ids(ids);
}

py::dict sources()
{
    std::vector<int> ids;
    PluginFunctions::getSourceIdentifiers(ids);
    return create_dict_from_ids(ids);
}

py::dict meshes()
{
    std::vector<int> ids;
    PluginFunctions::getAllMeshes(ids);
    return create_dict_from_ids(ids);
}

py::object rpc_call(const char* plugin_name, const char* function_name, std::vector<QScriptValue> params)
{
    QScriptValue ret = RPC::callFunction(plugin_name, function_name, std::move(params));
    if (ret.isNumber())
        return py::cast(ret.toInt32());

    return py::none();
}

py::object rpc_call(const char* plugin_name, const char* function_name, const py::list& py_params/*{ QString:"value",... }*/)
{
    std::vector<QScriptValue> q_params;
    // convert parameters to scriptvalues

    QScriptEngine* engine = RPC::getScriptEngine();
    for (py::ssize_t i = 0; i < py::len(py_params); i+=2)
    {
        std::string type_name = py::cast<std::string>(py_params[i]);

        auto it = type_conversion_map.find(type_name);
        if (it == std::end(type_conversion_map)) //todo: raise exception
        {
            const QString err = QString("In function %1, parameter #%2 is can not be converted to %3.").arg(QString(function_name), QString::number(i / 2), QString(type_name.c_str()));
            PyErr_SetString(PyExc_ValueError, err.toLatin1());
            return py::none();
        }
        auto cast_f = it->second;

        q_params.push_back(cast_f(engine, py_params[i+1]));
    }
    if (PyErr_Occurred())
    	return py::none();
    return rpc_call(plugin_name, function_name, std::move(q_params));
}

py::object rpc_call(const char* plugin_name, const char* function_name)
{
    std::vector<QScriptValue> params;
    return rpc_call(plugin_name, function_name, std::move(params));
}

py::object getMesh(int id)
{
    PolyMesh* polymesh = nullptr;
    if (PluginFunctions::getMesh(id, polymesh))
        return py::cast(reinterpret_cast<PyPolyMesh*>(polymesh));

    TriMesh* trimesh = nullptr;
    if (PluginFunctions::getMesh(id, trimesh))
        return py::cast(reinterpret_cast<PyTriMesh*>(trimesh));

    // error case
    PyErr_SetString(PyExc_ValueError, "Passed Id is not a PolyMesh");
    return py::none();
}

template<typename Mesh>
py::object getID(void* addr)
{
    IdList idlist;
    PluginFunctions::getAllMeshes(idlist);
    auto iter = std::find_if(std::begin(idlist), std::end(idlist), [&addr](int id)
    {
        Mesh* mesh;
        if (!PluginFunctions::getMesh(id, mesh))
            return false;
        return ((void*)mesh == (void*)addr);
    });
    if (iter == std::end(idlist))
        return py::cast(-1); //todo raise exception
    return py::cast(int(*iter));
}

PYBIND11_MODULE(openflipper, m)
{
    m.def("targets", &targets);
    m.def("sources", &sources);
    m.def("meshes", &meshes);

    m.def("get_mesh", &getMesh);
    m.def("get_id", [](PyTriMesh* m) {return getID<TriMesh>(m); });
    m.def("get_id", [](PyPolyMesh* m) {return getID<PolyMesh>(m); });

    py::object (*rpc_callArgs)(const char*, const char*, const py::list&) = rpc_call;
    py::object (*rpc_callNoArgs)(const char* , const char* ) = rpc_call;
    m.def("rpc_call", rpc_callArgs);
    m.def("rpc_call", rpc_callNoArgs);

    py::class_<UpdateType> update_type(m, "Update");
    update_type
        .def(py::init<>())
        .def(py::init<UpdateType>())
        .def(py::self | py::self)
        .def(py::self |= py::self)
        .def("__contains__", &UpdateType::contains, py::is_operator())
        .def_property_readonly_static("NONE", [](py::object) {return UPDATE_NONE;})
        .def_property_readonly_static("ALL", [](py::object) {return UPDATE_ALL;})
        .def_property_readonly_static("VISIBILITY", [](py::object) {return UPDATE_VISIBILITY;})
        .def_property_readonly_static("GEOMETRY", [](py::object) {return UPDATE_GEOMETRY;})
        .def_property_readonly_static("TOPOLOGY", [](py::object) {return UPDATE_TOPOLOGY;})
        .def_property_readonly_static("SELECTION", [](py::object) {return UPDATE_SELECTION;})
        .def_property_readonly_static("SELECTION_VERTICES", [](py::object) {return UPDATE_SELECTION_VERTICES;})
        .def_property_readonly_static("SELECTION_EDGES", [](py::object) {return UPDATE_SELECTION_EDGES;})
        .def_property_readonly_static("SELECTION_HALFEDGES", [](py::object) {return UPDATE_SELECTION_HALFEDGES;})
        .def_property_readonly_static("SELECTION_FACES", [](py::object) {return UPDATE_SELECTION_FACES;})
        .def_property_readonly_static("SELECTION_KNOTS", [](py::object) {return UPDATE_SELECTION_KNOTS;})
        .def_property_readonly_static("COLOR", [](py::object) {return UPDATE_COLOR;})
        .def_property_readonly_static("TEXTURE", [](py::object) {return UPDATE_TEXTURE;})
        .def_property_readonly_static("STATE", [](py::object) {return UPDATE_STATE;})
        .def_property_readonly_static("UNUSED", [](py::object) {return UPDATE_UNUSED;;});
}

#if (PY_MAJOR_VERSION == 2)
    PyObject* (*openflipper_pyinit_function)(void) = &initopenflipper;//untested
#else
    PyObject* (*openflipper_pyinit_function)(void) = &PyInit_openflipper;
#endif
<|endoftext|>


<commit_before>/*
 *  AvanceDB - an in-memory database similar to Apache CouchDB
 *  Copyright (C) 2015-2017 Ripcord Software
 *
 *  This program 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.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "http_server_log.h"

#include <iostream>
#include <cstdio>

#include <boost/format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/atomic.hpp>
#include <boost/thread.hpp>

#include "termcolor/termcolor.hpp"

#include "set_thread_name.h"

static const unsigned cumulativeSecsPerMonth[12] = { 2678400, 5097600, 7776000, 10368000, 13046400, 15638400, 18316800, 20995200, 23587200, 26265600, 28857600, 31536000 };
static const unsigned cumulativeSecsPerMonthLeap[12] = { 2678400, 5184000, 7862400, 10454400, 13132800, 15724800, 18403200, 21081600, 23673600, 26352000, 28944000, 31622400 };

struct LogRow {
    LogRow() : status(0) {
        data[0] = 0;
    }

    int status;
    char data[2048];
};

static const unsigned maxLogRows = 4096;
static LogRow logRows[maxLogRows];
static boost::atomic<unsigned> writeRowIndex;
static unsigned readRowIndex = 0;

static void streamWriterThread() {
    SetThreadName::Set("HttpServerLog");

    try {
        while (true) {
            boost::this_thread::sleep_for(boost::chrono::seconds(2));

            int lastStatus = 200;
            auto lastRowIndex = writeRowIndex.load();

            while (readRowIndex < lastRowIndex) {
                for (auto i = readRowIndex; i < lastRowIndex; ++i) {
                    auto& row = logRows[i % maxLogRows];

                    if (row.status != lastStatus) {
                        if (row.status >= 500) {
                            std::cout << termcolor::red;
                        } else if (row.status >= 400) {
                            std::cout << termcolor::grey << termcolor::bold;
                        } else if (row.status >= 300) {
                            std::cout << termcolor::yellow;
                        } else {
                            std::cout << termcolor::reset;
                        }

                        lastStatus = row.status;
                    }

                    std::cout << row.data << "\n";
                }

                readRowIndex = lastRowIndex;
                lastRowIndex = writeRowIndex.load();
            }

            std::cout << termcolor::reset << std::flush;
        }
    } catch (boost::thread_interrupted&) {
    }
}

static boost::thread logThread(streamWriterThread);

void HttpServerLog::Append(rs::httpserver::socket_ptr socket, rs::httpserver::request_ptr request, rs::httpserver::response_ptr response, const std::time_t& start, long duration) {

    int year, month, day, hour, min, sec;
    GetTimestamp(start, year, month, day, hour, min, sec);

    const auto queryString = request->getHeaders()->getQueryString();

    const auto localAddr = socket->getLocalEndpoint().address().to_string();
    const auto remoteAddr = socket->getRemoteEndpoint().address().to_string();

    auto index = writeRowIndex++;
    index %= maxLogRows;

    // TODO: optimize the string formatting to reduce ad-hoc allocations and re-use already known string values (dates, etc.)
    logRows[index].status = response->getStatusCode();
    std::snprintf(logRows[index].data, sizeof(logRows[0].data),
        "%04d-%02d-%02d %02d:%02d:%02dZ %s %s %s %s %u %s %s %d %u",
        year, month, day, hour, min, sec,
        localAddr.c_str(),
        request->getMethod().c_str(),
        request->getUri().c_str(),
        queryString.size() > 0 ? queryString.c_str() : "-",
        socket->getLocalEndpoint().port(),
        remoteAddr.c_str(),
        boost::replace_all_copy(request->getHeaders()->getUserAgent(), " ", "+").c_str(),
        response->getStatusCode(),
        duration);
}

void HttpServerLog::GetTimestamp(const std::time_t& time, int& year, int& month, int& day, int& hour, int& min, int& sec) {
    auto totalDays = time / 86400;
    auto elapsedYears = (long)(totalDays / 365.25);
    auto leapYears = ((long)elapsedYears) / 4;
    auto yearStart = ((elapsedYears - leapYears) * 31536000) + (leapYears * 31622400);
    auto elapsedSecondsThisYear = time - yearStart;

    year = 1970 + elapsedYears;
    auto isLeap = (year % 4) == 0;
    month = GetMonth(elapsedSecondsThisYear, isLeap);
    day = GetDay(elapsedSecondsThisYear, month, isLeap);

    ++month;
    ++day;

    hour = (time % (24 * 60 * 60)) / (60 * 60);
    min = (time % (60 * 60)) / 60;
    sec = time % 60;
}

unsigned HttpServerLog::GetMonth(long elapsedSeconds, bool isLeap) {
    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;

    int i = 6, left = 0, right = 12;
    for (; left < right; i = left + ((right - left) / 2)) {
        if (elapsedSeconds < lookup[i]) {
            right = i - 1;
        } else {
            left = i + 1;
        }
    }

    return i;
}

unsigned HttpServerLog::GetDay(long elapsedSeconds, unsigned month, bool isLeap) {
    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;

    auto dayMod = month > 0 ? elapsedSeconds - lookup[month - 1] : elapsedSeconds;
    auto day = dayMod / 86400;
    return day;
}<commit_msg>Start the log thread from Append not from a static * on fork() the thread is lost and no logging happens<commit_after>/*
 *  AvanceDB - an in-memory database similar to Apache CouchDB
 *  Copyright (C) 2015-2017 Ripcord Software
 *
 *  This program 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.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "http_server_log.h"

#include <iostream>
#include <cstdio>

#include <boost/format.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/atomic.hpp>
#include <boost/thread.hpp>

#include "termcolor/termcolor.hpp"

#include "set_thread_name.h"

static const unsigned cumulativeSecsPerMonth[12] = { 2678400, 5097600, 7776000, 10368000, 13046400, 15638400, 18316800, 20995200, 23587200, 26265600, 28857600, 31536000 };
static const unsigned cumulativeSecsPerMonthLeap[12] = { 2678400, 5184000, 7862400, 10454400, 13132800, 15724800, 18403200, 21081600, 23673600, 26352000, 28944000, 31622400 };

struct LogRow {
    LogRow() : status(0) {
        data[0] = 0;
    }

    int status;
    char data[2048];
};

static const unsigned maxLogRows = 4096;
static LogRow logRows[maxLogRows];
static boost::atomic<unsigned> writeRowIndex;
static unsigned readRowIndex = 0;

static boost::once_flag startThreadOnce = BOOST_ONCE_INIT;

static void StreamWriterThread() {
    SetThreadName::Set("avancedb-httplog");

    try {
        while (true) {
            boost::this_thread::sleep_for(boost::chrono::seconds(2));

            int lastStatus = 200;
            auto lastRowIndex = writeRowIndex.load();

            while (readRowIndex < lastRowIndex) {
                for (auto i = readRowIndex; i < lastRowIndex; ++i) {
                    auto& row = logRows[i % maxLogRows];

                    if (row.status != lastStatus) {
                        if (row.status >= 500) {
                            std::cout << termcolor::red;
                        } else if (row.status >= 400) {
                            std::cout << termcolor::grey << termcolor::bold;
                        } else if (row.status >= 300) {
                            std::cout << termcolor::yellow;
                        } else {
                            std::cout << termcolor::reset;
                        }

                        lastStatus = row.status;
                    }

                    std::cout << row.data << "\n";
                }

                readRowIndex = lastRowIndex;
                lastRowIndex = writeRowIndex.load();
            }

            std::cout << termcolor::reset << std::flush;
        }
    } catch (boost::thread_interrupted&) {
    }
}

static void StartStreamWriterThread() {
    boost::thread logThread(StreamWriterThread);
    logThread.detach();
}

void HttpServerLog::Append(rs::httpserver::socket_ptr socket, rs::httpserver::request_ptr request, rs::httpserver::response_ptr response, const std::time_t& start, long duration) {
    // start the log thread if it isn't already running
    boost::call_once(StartStreamWriterThread, startThreadOnce);

    int year, month, day, hour, min, sec;
    GetTimestamp(start, year, month, day, hour, min, sec);

    const auto queryString = request->getHeaders()->getQueryString();

    const auto localAddr = socket->getLocalEndpoint().address().to_string();
    const auto remoteAddr = socket->getRemoteEndpoint().address().to_string();

    auto index = writeRowIndex++;
    index %= maxLogRows;

    // TODO: optimize the string formatting to reduce ad-hoc allocations and re-use already known string values (dates, etc.)
    logRows[index].status = response->getStatusCode();
    std::snprintf(logRows[index].data, sizeof(logRows[0].data),
        "%04d-%02d-%02d %02d:%02d:%02dZ %s %s %s %s %u %s %s %d %u",
        year, month, day, hour, min, sec,
        localAddr.c_str(),
        request->getMethod().c_str(),
        request->getUri().c_str(),
        queryString.size() > 0 ? queryString.c_str() : "-",
        socket->getLocalEndpoint().port(),
        remoteAddr.c_str(),
        boost::replace_all_copy(request->getHeaders()->getUserAgent(), " ", "+").c_str(),
        response->getStatusCode(),
        duration);
}

void HttpServerLog::GetTimestamp(const std::time_t& time, int& year, int& month, int& day, int& hour, int& min, int& sec) {
    auto totalDays = time / 86400;
    auto elapsedYears = (long)(totalDays / 365.25);
    auto leapYears = ((long)elapsedYears) / 4;
    auto yearStart = ((elapsedYears - leapYears) * 31536000) + (leapYears * 31622400);
    auto elapsedSecondsThisYear = time - yearStart;

    year = 1970 + elapsedYears;
    auto isLeap = (year % 4) == 0;
    month = GetMonth(elapsedSecondsThisYear, isLeap);
    day = GetDay(elapsedSecondsThisYear, month, isLeap);

    ++month;
    ++day;

    hour = (time % (24 * 60 * 60)) / (60 * 60);
    min = (time % (60 * 60)) / 60;
    sec = time % 60;
}

unsigned HttpServerLog::GetMonth(long elapsedSeconds, bool isLeap) {
    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;

    int i = 6, left = 0, right = 12;
    for (; left < right; i = left + ((right - left) / 2)) {
        if (elapsedSeconds < lookup[i]) {
            right = i - 1;
        } else {
            left = i + 1;
        }
    }

    return i;
}

unsigned HttpServerLog::GetDay(long elapsedSeconds, unsigned month, bool isLeap) {
    const unsigned* lookup = isLeap ? cumulativeSecsPerMonthLeap : cumulativeSecsPerMonth;

    auto dayMod = month > 0 ? elapsedSeconds - lookup[month - 1] : elapsedSeconds;
    auto day = dayMod / 86400;
    return day;
}<|endoftext|>


<commit_before>#include "window.hpp"
#include "desktop-opencv.hpp"
#include <chrono>
#include <fmo/assert.hpp>
#include <fmo/pointset.hpp>
#include <fmo/stats.hpp>

#define TOSTR_INNER(x) #x
#define TOSTR(x) TOSTR_INNER(x)

namespace {
    const char* const windowName = TOSTR(FMO_BINARY_NAME);
    const char* const keyHelp =
        "[space] pause | [enter] step | [,][.] jump 10 frames | [esc] quit";

    constexpr Colour colourFp = Colour::lightMagenta();
    constexpr Colour colourFn = Colour::lightRed();
    constexpr Colour colourTp = Colour::lightGreen();

    cv::Vec3b toCv(Colour c) { return {c.b, c.g, c.r}; }

    struct PutColor {
        cv::Vec3b color;
        cv::Mat mat;

        void operator()(fmo::Pos pt) { mat.at<cv::Vec3b>({pt.x, pt.y}) = color; }
    };
}

Window::~Window() { close(); }

void Window::open(fmo::Dims dims) {
    if (mOpen) return;
    mOpen = true;
    cv::namedWindow(windowName, cv::WINDOW_NORMAL);

    if (dims.height > 800) {
        dims.width /= 2;
        dims.height /= 2;
    }

    cv::resizeWindow(windowName, dims.width, dims.height);
}

void Window::close() {
    if (!mOpen) return;
    mOpen = false;
    cv::destroyWindow(windowName);
}

void Window::display(fmo::Mat& image) {
    open(image.dims());
    cv::Mat mat = image.wrap();
    printText(mat);
    cv::imshow(windowName, mat);
}

void Window::printText(cv::Mat& mat) {
    if (mLines.empty()) return;
    int fontFace = cv::FONT_HERSHEY_SIMPLEX;
    double fontScale = mat.rows / 1000.;
    int thick = 2;
    int lineWidth = 0;
    int lineHeight = 0;
    int baseline = 0;

    for (auto& line : mLines) {
        auto lineSize = cv::getTextSize(line, fontFace, fontScale, thick, &baseline);
        lineWidth = std::max(lineWidth, lineSize.width);
        lineHeight = std::max(lineHeight, lineSize.height);
    }
    int above = (9 * lineHeight / 14) + (lineHeight / 2);
    int below = 5 * lineHeight / 14;
    int pad = lineHeight / 2;

    // darken the area for the text
    int xMax = 2 * pad + lineWidth;
    int yMax = 2 * pad + int(mLines.size()) * (above + below);
    cv::Rect rect{0, 0, xMax, yMax};
    mat(rect) = 0.3 * mat(rect);

    // render the text
    cv::Scalar color(mColour.b, mColour.g, mColour.r);
    int y = pad;
    for (auto& line : mLines) {
        y += above;
        cv::Point origin = {pad, y};
        cv::putText(mat, line, origin, fontFace, fontScale, color, thick);
        y += below;
    }
    mLines.clear();

    // render key help
    int helpRectHeight = (above + below) + 2 * pad;
    cv::Rect helpRect{0, mat.rows - helpRectHeight - 1, mat.cols, helpRectHeight};
    mat(helpRect) = 0.3 * mat(helpRect);
    cv::Point helpOrigin{pad, mat.rows - pad - below};
    cv::putText(mat, keyHelp, helpOrigin, fontFace, fontScale, color, thick);
}

Command Window::getCommand(bool block) {
    int waitMs = 1;

    if (block) {
        waitMs = 0;
    } else {
        int64_t sinceLastKeyTime = fmo::nanoTime() - mLastKeyTime;
        int64_t waitNs = mFrameTimeNs - sinceLastKeyTime;
        if (waitNs > 1'000'000) { waitMs = int(waitNs / 1'000'000); }
    }

    int keyCode = cv::waitKey(waitMs);
    mLastKeyTime = fmo::nanoTime();
    return encodeKey(keyCode);
}

Command Window::encodeKey(int keyCode) {
    switch (keyCode) {
    case 27: // escape
        return Command::QUIT;
    case 13: // cr
    case 10: // lf
        return Command::STEP;
    case ' ':
        return Command::PAUSE;
    case ',':
        return Command::JUMP_BACKWARD;
    case '.':
        return Command::JUMP_FORWARD;
    default:
        return Command::NONE;
    };
}

void drawPoints(const fmo::PointSet& points, fmo::Mat& target, Colour colour) {
    FMO_ASSERT(target.format() == fmo::Format::BGR, "bad format");
    cv::Mat mat = target.wrap();
    cv::Vec3b vec = {colour.b, colour.g, colour.r};

    for (auto& pt : points) { mat.at<cv::Vec3b>({pt.x, pt.y}) = vec; }
}

void drawPointsGt(const fmo::PointSet& ps, const fmo::PointSet& gt, fmo::Mat& target) {
    FMO_ASSERT(target.format() == fmo::Format::BGR, "bad format");
    cv::Mat mat = target.wrap();
    PutColor c1{toCv(colourFp), mat};
    PutColor c2{toCv(colourFn), mat};
    PutColor c3{toCv(colourTp), mat};
    fmo::pointSetCompare(ps, gt, c1, c2, c3);
}
<commit_msg>Adjust font thickness<commit_after>#include "window.hpp"
#include "desktop-opencv.hpp"
#include <chrono>
#include <fmo/assert.hpp>
#include <fmo/pointset.hpp>
#include <fmo/stats.hpp>

#define TOSTR_INNER(x) #x
#define TOSTR(x) TOSTR_INNER(x)

namespace {
    const char* const windowName = TOSTR(FMO_BINARY_NAME);
    const char* const keyHelp =
        "[space] pause | [enter] step | [,][.] jump 10 frames | [esc] quit";

    constexpr Colour colourFp = Colour::lightMagenta();
    constexpr Colour colourFn = Colour::lightRed();
    constexpr Colour colourTp = Colour::lightGreen();

    constexpr int downscaleThresh = 800;

    cv::Vec3b toCv(Colour c) { return {c.b, c.g, c.r}; }

    struct PutColor {
        cv::Vec3b color;
        cv::Mat mat;

        void operator()(fmo::Pos pt) { mat.at<cv::Vec3b>({pt.x, pt.y}) = color; }
    };
}

Window::~Window() { close(); }

void Window::open(fmo::Dims dims) {
    if (mOpen) return;
    mOpen = true;
    cv::namedWindow(windowName, cv::WINDOW_NORMAL);

    if (dims.height > downscaleThresh) {
        dims.width /= 2;
        dims.height /= 2;
    }

    cv::resizeWindow(windowName, dims.width, dims.height);
}

void Window::close() {
    if (!mOpen) return;
    mOpen = false;
    cv::destroyWindow(windowName);
}

void Window::display(fmo::Mat& image) {
    open(image.dims());
    cv::Mat mat = image.wrap();
    printText(mat);
    cv::imshow(windowName, mat);
}

void Window::printText(cv::Mat& mat) {
    if (mLines.empty()) return;
    int fontFace = cv::FONT_HERSHEY_SIMPLEX;
    double fontScale = mat.rows / 1000.;
    int thick = (mat.rows > downscaleThresh) ? 2 : 1;
    int lineWidth = 0;
    int lineHeight = 0;
    int baseline = 0;

    for (auto& line : mLines) {
        auto lineSize = cv::getTextSize(line, fontFace, fontScale, thick, &baseline);
        lineWidth = std::max(lineWidth, lineSize.width);
        lineHeight = std::max(lineHeight, lineSize.height);
    }
    int above = (9 * lineHeight / 14) + (lineHeight / 2);
    int below = 5 * lineHeight / 14;
    int pad = lineHeight / 2;

    // darken the area for the text
    int xMax = 2 * pad + lineWidth;
    int yMax = 2 * pad + int(mLines.size()) * (above + below);
    cv::Rect rect{0, 0, xMax, yMax};
    mat(rect) = 0.3 * mat(rect);

    // render the text
    cv::Scalar color(mColour.b, mColour.g, mColour.r);
    int y = pad;
    for (auto& line : mLines) {
        y += above;
        cv::Point origin = {pad, y};
        cv::putText(mat, line, origin, fontFace, fontScale, color, thick);
        y += below;
    }
    mLines.clear();

    // render key help
    int helpRectHeight = (above + below) + 2 * pad;
    cv::Rect helpRect{0, mat.rows - helpRectHeight - 1, mat.cols, helpRectHeight};
    mat(helpRect) = 0.3 * mat(helpRect);
    cv::Point helpOrigin{pad, mat.rows - pad - below};
    cv::putText(mat, keyHelp, helpOrigin, fontFace, fontScale, color, thick);
}

Command Window::getCommand(bool block) {
    int waitMs = 1;

    if (block) {
        waitMs = 0;
    } else {
        int64_t sinceLastKeyTime = fmo::nanoTime() - mLastKeyTime;
        int64_t waitNs = mFrameTimeNs - sinceLastKeyTime;
        if (waitNs > 1'000'000) { waitMs = int(waitNs / 1'000'000); }
    }

    int keyCode = cv::waitKey(waitMs);
    mLastKeyTime = fmo::nanoTime();
    return encodeKey(keyCode);
}

Command Window::encodeKey(int keyCode) {
    switch (keyCode) {
    case 27: // escape
        return Command::QUIT;
    case 13: // cr
    case 10: // lf
        return Command::STEP;
    case ' ':
        return Command::PAUSE;
    case ',':
        return Command::JUMP_BACKWARD;
    case '.':
        return Command::JUMP_FORWARD;
    default:
        return Command::NONE;
    };
}

void drawPoints(const fmo::PointSet& points, fmo::Mat& target, Colour colour) {
    FMO_ASSERT(target.format() == fmo::Format::BGR, "bad format");
    cv::Mat mat = target.wrap();
    cv::Vec3b vec = {colour.b, colour.g, colour.r};

    for (auto& pt : points) { mat.at<cv::Vec3b>({pt.x, pt.y}) = vec; }
}

void drawPointsGt(const fmo::PointSet& ps, const fmo::PointSet& gt, fmo::Mat& target) {
    FMO_ASSERT(target.format() == fmo::Format::BGR, "bad format");
    cv::Mat mat = target.wrap();
    PutColor c1{toCv(colourFp), mat};
    PutColor c2{toCv(colourFn), mat};
    PutColor c3{toCv(colourTp), mat};
    fmo::pointSetCompare(ps, gt, c1, c2, c3);
}
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "TiffEntryBE.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library 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 of the License, or (at your option) any later version.

    This library 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 library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

TiffEntryBE::TiffEntryBE(FileMap* f, uint32 offset) : mDataSwapped(false) {
  type = TIFF_UNDEFINED;  // We set type to undefined to avoid debug assertion errors.
  data = f->getDataWrt(offset);
  tag = (TiffTag)getShort();
  data += 2;
  TiffDataType _type = (TiffDataType)getShort();
  data += 2;
  count = getInt();
  type = _type;         //Now we can set it to the proper type

  if (type > 13)
    ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type);
  uint32 bytesize = count << datashifts[type];
  if (bytesize <= 4) {
    data = f->getDataWrt(offset + 8);
  } else { // offset
    data = f->getDataWrt(offset + 8);
    data_offset = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];
    CHECKSIZE(data_offset + bytesize);
    data = f->getDataWrt(data_offset);
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}

TiffEntryBE::~TiffEntryBE(void) {
}

unsigned int TiffEntryBE::getInt() {
  if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_UNDEFINED))
    ThrowTPE("TIFF, getInt: Wrong type 0x%x encountered. Expected Int", type);
  if (type == TIFF_SHORT)
    return getShort();
  return (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];
}

unsigned short TiffEntryBE::getShort() {
  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))
    ThrowTPE("TIFF, getShort: Wrong type 0x%x encountered. Expected Short", type);
  return (unsigned short)data[0] << 8 | (unsigned short)data[1];
}

const unsigned int* TiffEntryBE::getIntArray() {
  //TODO: Make critical section to avoid clashes.
  if (!(type == TIFF_LONG || type == TIFF_UNDEFINED || type == TIFF_RATIONAL ||  type == TIFF_SRATIONAL))
    ThrowTPE("TIFF, getIntArray: Wrong type 0x%x encountered. Expected Int", type);
  if (mDataSwapped)
    return (unsigned int*)&data[0];

  unsigned int* d = (unsigned int*) & data[0];
  for (uint32 i = 0; i < count; i++) {
    d[i] = (unsigned int)data[i*4+0] << 24 | (unsigned int)data[i*4+1] << 16 | (unsigned int)data[i*4+2] << 8 | (unsigned int)data[i*4+3];
  }
  mDataSwapped = true;
  return d;
}

const unsigned short* TiffEntryBE::getShortArray() {
  //TODO: Make critical section to avoid clashes.
  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))
    ThrowTPE("TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short", type);

  if (mDataSwapped)
    return (unsigned short*)&data[0];

  unsigned short* d = (unsigned short*) & data[0];
  for (uint32 i = 0; i < count; i++) {
    d[i] = (unsigned short)data[i*2+0] << 8 | (unsigned short)data[i*2+1];
  }
  mDataSwapped = true;
  return d;
}

} // namespace RawSpeed
<commit_msg>Swap all elements of rational fields on platforms where endianess isn't the same as image. Check if data has been swapped when returning a single value.<commit_after>#include "StdAfx.h"
#include "TiffEntryBE.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library 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 of the License, or (at your option) any later version.

    This library 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 library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

TiffEntryBE::TiffEntryBE(FileMap* f, uint32 offset) : mDataSwapped(false) {
  type = TIFF_UNDEFINED;  // We set type to undefined to avoid debug assertion errors.
  data = f->getDataWrt(offset);
  tag = (TiffTag)getShort();
  data += 2;
  TiffDataType _type = (TiffDataType)getShort();
  data += 2;
  count = getInt();
  type = _type;         //Now we can set it to the proper type

  if (type > 13)
    ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type);
  uint32 bytesize = count << datashifts[type];
  if (bytesize <= 4) {
    data = f->getDataWrt(offset + 8);
  } else { // offset
    data = f->getDataWrt(offset + 8);
    data_offset = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];
    CHECKSIZE(data_offset + bytesize);
    data = f->getDataWrt(data_offset);
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}

TiffEntryBE::~TiffEntryBE(void) {
}

unsigned int TiffEntryBE::getInt() {
  if (!(type == TIFF_LONG || type == TIFF_SHORT || type == TIFF_UNDEFINED))
    ThrowTPE("TIFF, getInt: Wrong type 0x%x encountered. Expected Int", type);
  if (type == TIFF_SHORT)
    return getShort();
  if (mDataSwapped)
    return *(unsigned int*)&data[0];
  return (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];
}

unsigned short TiffEntryBE::getShort() {
  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))
    ThrowTPE("TIFF, getShort: Wrong type 0x%x encountered. Expected Short", type);
  if (mDataSwapped)
    return *(unsigned short*)&data[0];
  return (unsigned short)data[0] << 8 | (unsigned short)data[1];
}

const unsigned int* TiffEntryBE::getIntArray() {
  //TODO: Make critical section to avoid clashes.
  if (!(type == TIFF_LONG || type == TIFF_UNDEFINED || type == TIFF_RATIONAL ||  type == TIFF_SRATIONAL))
    ThrowTPE("TIFF, getIntArray: Wrong type 0x%x encountered. Expected Int", type);
  if (mDataSwapped)
    return (unsigned int*)&data[0];

  unsigned int* d = (unsigned int*) & data[0];
  uint32 ncount = count * ((type == TIFF_RATIONAL ||  type == TIFF_SRATIONAL) ? 2 : 1);
  for (uint32 i = 0; i < ncount; i++) {
    d[i] = (unsigned int)data[i*4+0] << 24 | (unsigned int)data[i*4+1] << 16 | (unsigned int)data[i*4+2] << 8 | (unsigned int)data[i*4+3];
  }
  mDataSwapped = true;
  return d;
}

const unsigned short* TiffEntryBE::getShortArray() {
  //TODO: Make critical section to avoid clashes.
  if (!(type == TIFF_SHORT || type == TIFF_UNDEFINED))
    ThrowTPE("TIFF, getShortArray: Wrong type 0x%x encountered. Expected Short", type);

  if (mDataSwapped)
    return (unsigned short*)&data[0];

  unsigned short* d = (unsigned short*) & data[0];
  for (uint32 i = 0; i < count; i++) {
    d[i] = (unsigned short)data[i*2+0] << 8 | (unsigned short)data[i*2+1];
  }
  mDataSwapped = true;
  return d;
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Fresco Project.
 * Copyright (C) 2002 Tobias Hunger <tobias@fresco.org>
 * http://www.fresco.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include <Prague/Sys/Tracer.hh>
#include "Drawable.hh"
#include "Extension.hh"
#include "Pointer.hh"

// ---------------------------------------------------------------
// class SDL::Pointer (implementation)
// ---------------------------------------------------------------

Fresco::Raster_ptr SDL::Pointer::raster()
{
  Prague::Trace trace("SDL::Pointer::raster()");

  return Fresco::Raster::_duplicate(_raster);
}

bool SDL::Pointer::intersects(Fresco::Coord l, Fresco::Coord r,
			      Fresco::Coord t, Fresco::Coord b)
{
  Prague::Trace trace("SDL::Pointer::intersects(...)");

  return
    l/_scale[0] <= _position[0] + _size[0] &&
    r/_scale[0] >= _position[0] &&
    t/_scale[1] <= _position[1] + _size[1] &&
    b/_scale[1] >= _position[1];
}

void SDL::Pointer::move(Fresco::Coord x, Fresco::Coord y)
{
  Prague::Trace trace("SDL::Pointer::move(...)");

  restore();

  // update position
  _position[0] =
    static_cast<Fresco::PixelCoord>
    (std::max(static_cast<Fresco::PixelCoord>(x/_scale[0]),
	      _origin[0]));
  _position[1] =
    static_cast<Fresco::PixelCoord>
    (std::max(static_cast<Fresco::PixelCoord>(y/_scale[1]),
	      _origin[1]));

  save();
  draw();
}

// ---------------------------------------------------------------
// class SDL::nonGLPointer (implementation)
// ---------------------------------------------------------------

SDL::nonGLPointer::nonGLPointer(Drawable * drawable, Fresco::Raster_ptr raster) :
  _screen(dynamic_cast<SDL::Drawable *>(drawable))
{
  Prague::Trace trace("SDL::nonGLPointer::nonGLPointer(...)");

  // copy over the Raster:
  _raster = Fresco::Raster::_duplicate(raster);

  // Disable SDL default mousecursor
  SDL_ShowCursor(0);

  // Copy the raster over into the Drawable:
  Fresco::Raster::Info info = raster->header();
  Fresco::Raster::ColorSeq_var pixels;
  Fresco::Raster::Index lower, upper;
  lower.x = lower.y = 0;
  upper.x = info.width, upper.y = info.height;
  raster->store_pixels(lower, upper, pixels);
  _origin[0] = _origin[1] = 0;
  _size[0] = info.width;
  _size[1] = info.height;
  _scale[0] = 1.0/_screen->resolution(Fresco::xaxis);
  _scale[1] = 1.0/_screen->resolution(Fresco::yaxis);

  Fresco::Drawable::PixelFormat format = _screen->pixel_format();

  unsigned depth =  format.size >> 3;
  _cursor = new SDL::Drawable("mouse cursor", _size[0], _size[1], 4);

  Renderer * renderer = new SDL::Renderer();
  renderer->attach(_cursor);

  for (unsigned short y = 0; y != _size[1]; y++)
    for (unsigned short x = 0; x != _size[0]; x++)
      {
        renderer->set_color(*(pixels->get_buffer() + y * info.width + x));
	renderer->draw_pixel(x, y);
      }

  // set up save_area
  _saved_area = new SDL::Drawable("save area", _size[0], _size[1], depth);

  // set position
  _position[0] = _position[1] = 8;
  _old_x = _position[0] - _origin[0];
  _old_y = _position[1] - _origin[1];

  // set SDL_Alpha:
  SDL_SetAlpha(_cursor->surface(), SDL_SRCALPHA, 128);
}

SDL::nonGLPointer::~nonGLPointer()
{
  restore();
}

void SDL::nonGLPointer::save()
{
  Prague::Trace trace("SDL::nonGLPointer::save()");

  Fresco::PixelCoord x = _position[0] - _origin[0];
  Fresco::PixelCoord y = _position[1] - _origin[1];
  Fresco::PixelCoord size_x, size_y;
  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];
  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];
  _saved_area->blit(*_screen, x, y, size_x, size_y, 0, 0);
}

void SDL::nonGLPointer::restore()
{
  Prague::Trace trace("SDL::nonGLPointer::restore()");

  Fresco::PixelCoord x = _position[0] - _origin[0];
  Fresco::PixelCoord y = _position[1] - _origin[1];
  Fresco::PixelCoord size_x, size_y;
  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];
  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];
  _screen->blit(*_saved_area, 0, 0, size_x, size_y, x, y);
  _old_x = x;
  _old_y = y;
  _old_size_x = size_x;
  _old_size_y = size_y;
}

void SDL::nonGLPointer::draw()
{
  Prague::Trace trace("SDL::nonGLPointer::draw()");

  Fresco::PixelCoord x = _position[0] - _origin[0];
  Fresco::PixelCoord y = _position[1] - _origin[1];
  Fresco::PixelCoord size_x, size_y;
  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];
  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];
  _screen->blit(*_cursor, 0, 0, size_x, size_y, x, y);
  // flush the area we worked on:
  Fresco::PixelCoord x1 = std::min(_old_x, x);
  Fresco::PixelCoord y1 = std::min(_old_y, y);
  Fresco::PixelCoord x2 = std::max(_old_x + _old_size_x, x + size_x);
  Fresco::PixelCoord y2 = std::max(_old_y + _old_size_y, y + size_y);
  _screen->flush(x1, y1, x2 - x1, y2 - y1);
}

<commit_msg>Fix uninitialized member variables when draw() is called before restore(). Thanks valgrind.<commit_after>/*$Id$
 *
 * This source file is a part of the Fresco Project.
 * Copyright (C) 2002 Tobias Hunger <tobias@fresco.org>
 * http://www.fresco.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include <Prague/Sys/Tracer.hh>
#include "Drawable.hh"
#include "Extension.hh"
#include "Pointer.hh"

// ---------------------------------------------------------------
// class SDL::Pointer (implementation)
// ---------------------------------------------------------------

Fresco::Raster_ptr SDL::Pointer::raster()
{
  Prague::Trace trace("SDL::Pointer::raster()");

  return Fresco::Raster::_duplicate(_raster);
}

bool SDL::Pointer::intersects(Fresco::Coord l, Fresco::Coord r,
			      Fresco::Coord t, Fresco::Coord b)
{
  Prague::Trace trace("SDL::Pointer::intersects(...)");

  return
    l/_scale[0] <= _position[0] + _size[0] &&
    r/_scale[0] >= _position[0] &&
    t/_scale[1] <= _position[1] + _size[1] &&
    b/_scale[1] >= _position[1];
}

void SDL::Pointer::move(Fresco::Coord x, Fresco::Coord y)
{
  Prague::Trace trace("SDL::Pointer::move(...)");

  restore();

  // update position
  _position[0] =
    static_cast<Fresco::PixelCoord>
    (std::max(static_cast<Fresco::PixelCoord>(x/_scale[0]),
	      _origin[0]));
  _position[1] =
    static_cast<Fresco::PixelCoord>
    (std::max(static_cast<Fresco::PixelCoord>(y/_scale[1]),
	      _origin[1]));

  save();
  draw();
}

// ---------------------------------------------------------------
// class SDL::nonGLPointer (implementation)
// ---------------------------------------------------------------

SDL::nonGLPointer::nonGLPointer(Drawable * drawable, Fresco::Raster_ptr raster) :
  _screen(dynamic_cast<SDL::Drawable *>(drawable))
{
  Prague::Trace trace("SDL::nonGLPointer::nonGLPointer(...)");

  // copy over the Raster:
  _raster = Fresco::Raster::_duplicate(raster);

  // Disable SDL default mousecursor
  SDL_ShowCursor(0);

  // Copy the raster over into the Drawable:
  Fresco::Raster::Info info = raster->header();
  Fresco::Raster::ColorSeq_var pixels;
  Fresco::Raster::Index lower, upper;
  lower.x = lower.y = 0;
  upper.x = info.width, upper.y = info.height;
  raster->store_pixels(lower, upper, pixels);
  _origin[0] = _origin[1] = 0;
  _size[0] = info.width;
  _size[1] = info.height;
  _scale[0] = 1.0/_screen->resolution(Fresco::xaxis);
  _scale[1] = 1.0/_screen->resolution(Fresco::yaxis);

  Fresco::Drawable::PixelFormat format = _screen->pixel_format();

  unsigned depth =  format.size >> 3;
  _cursor = new SDL::Drawable("mouse cursor", _size[0], _size[1], 4);

  Renderer * renderer = new SDL::Renderer();
  renderer->attach(_cursor);

  for (unsigned short y = 0; y != _size[1]; y++)
    for (unsigned short x = 0; x != _size[0]; x++)
      {
        renderer->set_color(*(pixels->get_buffer() + y * info.width + x));
	renderer->draw_pixel(x, y);
      }

  // set up save_area
  _saved_area = new SDL::Drawable("save area", _size[0], _size[1], depth);

  // set position
  _position[0] = _position[1] = 8;
  _old_x = _position[0] - _origin[0];
  _old_y = _position[1] - _origin[1];
  _old_size_x = _size[0];
  _old_size_y = _size[1];

  // set SDL_Alpha:
  SDL_SetAlpha(_cursor->surface(), SDL_SRCALPHA, 128);
}

SDL::nonGLPointer::~nonGLPointer()
{
  restore();
}

void SDL::nonGLPointer::save()
{
  Prague::Trace trace("SDL::nonGLPointer::save()");

  Fresco::PixelCoord x = _position[0] - _origin[0];
  Fresco::PixelCoord y = _position[1] - _origin[1];
  Fresco::PixelCoord size_x, size_y;
  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];
  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];
  _saved_area->blit(*_screen, x, y, size_x, size_y, 0, 0);
}

void SDL::nonGLPointer::restore()
{
  Prague::Trace trace("SDL::nonGLPointer::restore()");

  Fresco::PixelCoord x = _position[0] - _origin[0];
  Fresco::PixelCoord y = _position[1] - _origin[1];
  Fresco::PixelCoord size_x, size_y;
  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];
  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];
  _screen->blit(*_saved_area, 0, 0, size_x, size_y, x, y);
  _old_x = x;
  _old_y = y;
  _old_size_x = size_x;
  _old_size_y = size_y;
}

void SDL::nonGLPointer::draw()
{
  Prague::Trace trace("SDL::nonGLPointer::draw()");

  Fresco::PixelCoord x = _position[0] - _origin[0];
  Fresco::PixelCoord y = _position[1] - _origin[1];
  Fresco::PixelCoord size_x, size_y;
  size_x = (_size[0] + x > _screen->width()) ? _screen->width()-x : _size[0];
  size_y = (_size[1] + y > _screen->height()) ? _screen->height()-y : _size[1];
  _screen->blit(*_cursor, 0, 0, size_x, size_y, x, y);
  // flush the area we worked on:
  Fresco::PixelCoord x1 = std::min(_old_x, x);
  Fresco::PixelCoord y1 = std::min(_old_y, y);
  Fresco::PixelCoord x2 = std::max(_old_x + _old_size_x, x + size_x);
  Fresco::PixelCoord y2 = std::max(_old_y + _old_size_y, y + size_y);
  _screen->flush(x1, y1, x2 - x1, y2 - y1);
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2009 Jrgen Riegel <juergen.riegel@web.de>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include "ui_TaskSketcherGeneral.h"
#include "TaskSketcherGeneral.h"
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Base/UnitsApi.h>

#include "ViewProviderSketch.h"

using namespace SketcherGui;
using namespace Gui::TaskView;

TaskSketcherGeneral::TaskSketcherGeneral(ViewProviderSketch *sketchView)
    : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Edit controls"),true, 0)
    , sketchView(sketchView)
{
    // we need a separate container widget to add all controls to
    proxy = new QWidget(this);
    ui = new Ui_TaskSketcherGeneral();
    ui->setupUi(proxy);
    QMetaObject::connectSlotsByName(this);

    this->groupLayout()->addWidget(proxy);

    // connecting the needed signals
    QObject::connect(
        ui->checkBoxShowGrid, SIGNAL(toggled(bool)),
        this           , SLOT(toggleGridView(bool))
        );
    QObject::connect(
        ui->checkBoxGridSnap, SIGNAL(stateChanged(int)),
        this              , SLOT  (toggleGridSnap(int))
       );

    QObject::connect(
        ui->comboBoxGridSize, SIGNAL(currentIndexChanged(QString)),
        this              , SLOT  (setGridSize(QString))
       );

    QObject::connect(
        ui->checkBoxAutoconstraints, SIGNAL(stateChanged(int)),
        this              , SLOT  (toggleAutoconstraints(int))
       );

    Gui::Selection().Attach(this);

    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Sketcher/General");
    ui->checkBoxShowGrid->setChecked(hGrp->GetBool("ShowGrid", true));
}

TaskSketcherGeneral::~TaskSketcherGeneral()
{
    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Sketcher/General");
    hGrp->SetBool("ShowGrid", ui->checkBoxShowGrid->isChecked());
    delete ui;
    Gui::Selection().Detach(this);
}

void TaskSketcherGeneral::toggleGridView(bool on)
{
    ui->label->setEnabled(on);
    ui->comboBoxGridSize->setEnabled(on);
    ui->checkBoxGridSnap->setEnabled(on);
    sketchView->ShowGrid.setValue(on);
}

void TaskSketcherGeneral::setGridSize(const QString& val)
{
    float gridSize = (float) Base::UnitsApi::translateUnit(val);
    if (gridSize > 0)
        sketchView->GridSize.setValue(gridSize);
}

void TaskSketcherGeneral::toggleGridSnap(int state)
{
    setGridSize(ui->comboBoxGridSize->currentText()); // Ensure consistency
    sketchView->GridSnap.setValue(state == Qt::Checked);
}

void TaskSketcherGeneral::toggleAutoconstraints(int state)
{
    sketchView->Autoconstraints.setValue(state == Qt::Checked);
}

void TaskSketcherGeneral::changeEvent(QEvent *e)
{
    TaskBox::changeEvent(e);
    if (e->type() == QEvent::LanguageChange) {
        ui->retranslateUi(proxy);
    }
}

/// @cond DOXERR
void TaskSketcherGeneral::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,
                              Gui::SelectionSingleton::MessageType Reason)
{
    //if (Reason.Type == SelectionChanges::AddSelection ||
    //    Reason.Type == SelectionChanges::RmvSelection ||
    //    Reason.Type == SelectionChanges::SetSelection ||
    //    Reason.Type == SelectionChanges::ClrSelection) {
    //}
}
/// @endcond DOXERR

#include "moc_TaskSketcherGeneral.cpp"
<commit_msg>0001245: Wrong grid size shown in task dialog<commit_after>/***************************************************************************
 *   Copyright (c) 2009 Jrgen Riegel <juergen.riegel@web.de>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include "ui_TaskSketcherGeneral.h"
#include "TaskSketcherGeneral.h"
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/BitmapFactory.h>
#include <Gui/ViewProvider.h>
#include <Gui/WaitCursor.h>
#include <Base/UnitsApi.h>

#include "ViewProviderSketch.h"

using namespace SketcherGui;
using namespace Gui::TaskView;

TaskSketcherGeneral::TaskSketcherGeneral(ViewProviderSketch *sketchView)
    : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Edit controls"),true, 0)
    , sketchView(sketchView)
{
    // we need a separate container widget to add all controls to
    proxy = new QWidget(this);
    ui = new Ui_TaskSketcherGeneral();
    ui->setupUi(proxy);
    QMetaObject::connectSlotsByName(this);

    this->groupLayout()->addWidget(proxy);

    // connecting the needed signals
    QObject::connect(
        ui->checkBoxShowGrid, SIGNAL(toggled(bool)),
        this           , SLOT(toggleGridView(bool))
        );
    QObject::connect(
        ui->checkBoxGridSnap, SIGNAL(stateChanged(int)),
        this              , SLOT  (toggleGridSnap(int))
       );

    QObject::connect(
        ui->comboBoxGridSize, SIGNAL(currentIndexChanged(QString)),
        this              , SLOT  (setGridSize(QString))
       );

    QObject::connect(
        ui->checkBoxAutoconstraints, SIGNAL(stateChanged(int)),
        this              , SLOT  (toggleAutoconstraints(int))
       );

    Gui::Selection().Attach(this);

    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Sketcher/General");
    ui->checkBoxShowGrid->setChecked(hGrp->GetBool("ShowGrid", true));

    QString size = ui->comboBoxGridSize->currentText();
    size = QString::fromAscii(hGrp->GetASCII("GridSize", (const char*)size.toAscii()).c_str());
    ui->comboBoxGridSize->setCurrentIndex(ui->comboBoxGridSize->findText(size));

    ui->checkBoxGridSnap->setChecked(hGrp->GetBool("GridSnap", ui->checkBoxGridSnap->isChecked()));
    ui->checkBoxAutoconstraints->setChecked(hGrp->GetBool("AutoConstraints", ui->checkBoxAutoconstraints->isChecked()));
}

TaskSketcherGeneral::~TaskSketcherGeneral()
{
    Base::Reference<ParameterGrp> hGrp = App::GetApplication().GetUserParameter()
        .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Sketcher/General");
    hGrp->SetBool("ShowGrid", ui->checkBoxShowGrid->isChecked());

    QString size = ui->comboBoxGridSize->currentText();
    hGrp->SetASCII("GridSize", (const char*)size.toAscii());

    hGrp->SetBool("GridSnap", ui->checkBoxGridSnap->isChecked());
    hGrp->SetBool("AutoConstraints", ui->checkBoxAutoconstraints->isChecked());

    delete ui;
    Gui::Selection().Detach(this);
}

void TaskSketcherGeneral::toggleGridView(bool on)
{
    ui->label->setEnabled(on);
    ui->comboBoxGridSize->setEnabled(on);
    ui->checkBoxGridSnap->setEnabled(on);
    sketchView->ShowGrid.setValue(on);
}

void TaskSketcherGeneral::setGridSize(const QString& val)
{
    float gridSize = (float) Base::UnitsApi::translateUnit(val);
    if (gridSize > 0)
        sketchView->GridSize.setValue(gridSize);
}

void TaskSketcherGeneral::toggleGridSnap(int state)
{
    setGridSize(ui->comboBoxGridSize->currentText()); // Ensure consistency
    sketchView->GridSnap.setValue(state == Qt::Checked);
}

void TaskSketcherGeneral::toggleAutoconstraints(int state)
{
    sketchView->Autoconstraints.setValue(state == Qt::Checked);
}

void TaskSketcherGeneral::changeEvent(QEvent *e)
{
    TaskBox::changeEvent(e);
    if (e->type() == QEvent::LanguageChange) {
        ui->retranslateUi(proxy);
    }
}

/// @cond DOXERR
void TaskSketcherGeneral::OnChange(Gui::SelectionSingleton::SubjectType &rCaller,
                              Gui::SelectionSingleton::MessageType Reason)
{
    //if (Reason.Type == SelectionChanges::AddSelection ||
    //    Reason.Type == SelectionChanges::RmvSelection ||
    //    Reason.Type == SelectionChanges::SetSelection ||
    //    Reason.Type == SelectionChanges::ClrSelection) {
    //}
}
/// @endcond DOXERR

#include "moc_TaskSketcherGeneral.cpp"
<|endoftext|>


<commit_before>#include "dreal/contractor/contractor_status.h"

#include <utility>

#include "dreal/util/assert.h"
#include "dreal/util/logging.h"

using std::move;
using std::unordered_set;
using std::vector;

namespace dreal {

ContractorStatus::ContractorStatus(Box box, const int branching_point)
    : box_{move(box)},
      branching_point_{branching_point},
      output_{ibex::BitSet::empty(box_.size())} {
  DREAL_ASSERT(!box_.empty());
  DREAL_ASSERT(branching_point_ >= -1 && branching_point_ < box_.size());
}

const Box& ContractorStatus::box() const { return box_; }

Box& ContractorStatus::mutable_box() { return box_; }

int ContractorStatus::branching_point() const { return branching_point_; }

int& ContractorStatus::mutable_branching_point() { return branching_point_; }

const ibex::BitSet& ContractorStatus::output() const { return output_; }

ibex::BitSet& ContractorStatus::mutable_output() { return output_; }

void ContractorStatus::AddUsedConstraint(const Formula& f) {
  DREAL_LOG_DEBUG("ContractorStatus::AddUsedConstraint({}) box is empty? {}", f,
                  box_.empty());
  if (box_.empty()) {
    for (const Variable& v : f.GetFreeVariables()) {
      AddUnsatWitness(v);
    }
  }
  used_constraints_.insert(f);
}

void ContractorStatus::AddUsedConstraint(const vector<Formula>& formulas) {
  for (const Formula& f : formulas) {
    AddUsedConstraint(f);
  }
}

void ContractorStatus::AddUnsatWitness(const Variable& var) {
  DREAL_LOG_DEBUG("ContractorStatus::AddUnsatWitness({})", var);
  unsat_witness_.insert(var);
}

unordered_set<Formula, hash_value<Formula>> GenerateExplanation(
    const Variables& unsat_witness,
    const unordered_set<Formula, hash_value<Formula>>& used_constraints) {
  if (unsat_witness.empty()) {
    return {};
  }
  // Set up the initial explanation based on variables.
  unordered_set<Formula, hash_value<Formula>> explanation;
  for (const Formula& f_i : used_constraints) {
    if (HaveIntersection(unsat_witness, f_i.GetFreeVariables())) {
      explanation.insert(f_i);
    }
  }

  bool keep_going = true;
  while (keep_going) {
    keep_going = false;
    for (const Formula& f_i : explanation) {
      const Variables variables_in_f_i{f_i.GetFreeVariables()};
      for (const Formula& f_j : used_constraints) {
        if (explanation.count(f_j) > 0) {
          continue;
        }
        if (HaveIntersection(variables_in_f_i, f_j.GetFreeVariables())) {
          explanation.insert(f_j);
          keep_going = true;
        }
      }
    }
  }
  return explanation;
}

unordered_set<Formula, hash_value<Formula>> ContractorStatus::Explanation()
    const {
  return GenerateExplanation(unsat_witness_, used_constraints_);
}

ContractorStatus& ContractorStatus::InplaceJoin(
    const ContractorStatus& contractor_status) {
  box_.InplaceUnion(contractor_status.box());
  output_ |= contractor_status.output();
  unsat_witness_.insert(contractor_status.unsat_witness_.begin(),
                        contractor_status.unsat_witness_.end());
  used_constraints_.insert(contractor_status.used_constraints_.begin(),
                           contractor_status.used_constraints_.end());
  return *this;
}

ContractorStatus Join(ContractorStatus contractor_status1,
                      const ContractorStatus& contractor_status2) {
  // This function updates `contractor_status1`, which is passed by value, and
  // returns it.
  return contractor_status1.InplaceJoin(contractor_status2);
}

}  // namespace dreal
<commit_msg>fix(contractor/contractor_status.cc): Compiler error<commit_after>#include "dreal/contractor/contractor_status.h"

#include <utility>

#include "dreal/util/assert.h"
#include "dreal/util/logging.h"

using std::move;
using std::unordered_set;
using std::vector;

namespace dreal {

ContractorStatus::ContractorStatus(Box box, const int branching_point)
    : box_{move(box)},
      branching_point_{branching_point},
      output_{ibex::BitSet::empty(box_.size())} {
  DREAL_ASSERT(!box_.empty());
  DREAL_ASSERT(branching_point_ >= -1 && branching_point_ < box_.size());
}

const Box& ContractorStatus::box() const { return box_; }

Box& ContractorStatus::mutable_box() { return box_; }

int ContractorStatus::branching_point() const { return branching_point_; }

int& ContractorStatus::mutable_branching_point() { return branching_point_; }

const ibex::BitSet& ContractorStatus::output() const { return output_; }

ibex::BitSet& ContractorStatus::mutable_output() { return output_; }

void ContractorStatus::AddUsedConstraint(const Formula& f) {
  DREAL_LOG_DEBUG("ContractorStatus::AddUsedConstraint({}) box is empty? {}", f,
                  box_.empty());
  if (box_.empty()) {
    for (const Variable& v : f.GetFreeVariables()) {
      AddUnsatWitness(v);
    }
  }
  used_constraints_.insert(f);
}

void ContractorStatus::AddUsedConstraint(const vector<Formula>& formulas) {
  for (const Formula& f : formulas) {
    AddUsedConstraint(f);
  }
}

void ContractorStatus::AddUnsatWitness(const Variable& var) {
  DREAL_LOG_DEBUG("ContractorStatus::AddUnsatWitness({})", var);
  unsat_witness_.insert(var);
}

unordered_set<Formula, hash_value<Formula>> GenerateExplanation(
    const Variables& unsat_witness,
    const unordered_set<Formula, hash_value<Formula>>& used_constraints) {
  if (unsat_witness.empty()) {
    return unordered_set<Formula, hash_value<Formula>>();
  }
  // Set up the initial explanation based on variables.
  unordered_set<Formula, hash_value<Formula>> explanation;
  for (const Formula& f_i : used_constraints) {
    if (HaveIntersection(unsat_witness, f_i.GetFreeVariables())) {
      explanation.insert(f_i);
    }
  }

  bool keep_going = true;
  while (keep_going) {
    keep_going = false;
    for (const Formula& f_i : explanation) {
      const Variables variables_in_f_i{f_i.GetFreeVariables()};
      for (const Formula& f_j : used_constraints) {
        if (explanation.count(f_j) > 0) {
          continue;
        }
        if (HaveIntersection(variables_in_f_i, f_j.GetFreeVariables())) {
          explanation.insert(f_j);
          keep_going = true;
        }
      }
    }
  }
  return explanation;
}

unordered_set<Formula, hash_value<Formula>> ContractorStatus::Explanation()
    const {
  return GenerateExplanation(unsat_witness_, used_constraints_);
}

ContractorStatus& ContractorStatus::InplaceJoin(
    const ContractorStatus& contractor_status) {
  box_.InplaceUnion(contractor_status.box());
  output_ |= contractor_status.output();
  unsat_witness_.insert(contractor_status.unsat_witness_.begin(),
                        contractor_status.unsat_witness_.end());
  used_constraints_.insert(contractor_status.used_constraints_.begin(),
                           contractor_status.used_constraints_.end());
  return *this;
}

ContractorStatus Join(ContractorStatus contractor_status1,
                      const ContractorStatus& contractor_status2) {
  // This function updates `contractor_status1`, which is passed by value, and
  // returns it.
  return contractor_status1.InplaceJoin(contractor_status2);
}

}  // namespace dreal
<|endoftext|>


<commit_before>#include "RayControl.h"
#include "ObjectParticles.h"
#include "Engine.h"
#include "Game.h"
#include "Object.h"
#include "Player.h"
#include "Common.h"
#include "App.h"<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "RayControl.h"
#include "ObjectParticles.h"
#include "Engine.h"
#include "Game.h"
#include "Object.h"
#include "Player.h"
#include "Common.h"
#include "App.h"

CRayControl::CRayControl(void)
{
	m_pStarNormal = NULL;
	Init();
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
// Class header file...
#include "XalanStdOutputStream.hpp"

#include <cerrno>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <strstream.h>
#else
#include <iostream>
#include <strstream>
#endif

#include <PlatformSupport/DOMStringHelper.hpp>

#if !defined(XALAN_NO_NAMESPACES)
using std::ostream;
using std::cerr;
#endif

XalanStdOutputStream::XalanStdOutputStream(ostream&	theOutputStream) :
	XalanOutputStream(),
	m_outputStream(theOutputStream)
{
	// This will make sure that cerr is not buffered...
	if (&m_outputStream == &cerr)
	{
		setBufferSize(0);
	}
}

XalanStdOutputStream::~XalanStdOutputStream()
{
}

void
XalanStdOutputStream::doFlush()
{
	// Don't try to flush if the stream is in a bad state...
	if(m_outputStream)
	{
		m_outputStream.flush();

		if(!m_outputStream)
		{
			throw XalanStdOutputStreamWriteException(errno);
		}
	}
}

void
XalanStdOutputStream::writeData(
			const char*		theBuffer,
			size_type		theBufferLength)
{
	assert(StreamSizeType(theBufferLength) == theBufferLength);

	m_outputStream.write(theBuffer, StreamSizeType(theBufferLength));

	if(!m_outputStream)
	{
		throw XalanStdOutputStreamWriteException(errno);
	}
}

static XalanDOMString
FormatMessageLocal(
			const char*		theMessage,
			int				theErrorCode)
{
#if !defined(XALAN_NO_NAMESPACES)
using std::ostrstream;
#endif

	XalanDOMString	theResult(TranscodeFromLocalCodePage(theMessage));

	ostrstream   theFormatter;

	theFormatter << ".  The error code was "
				 << theErrorCode
				 << "." << '\0';

	append(theResult, theFormatter.str());

	delete theFormatter.str();

	return theResult;
}

XalanStdOutputStream::XalanStdOutputStreamWriteException::XalanStdOutputStreamWriteException(
		int					theErrorCode) :
	XalanOutputStreamException(FormatMessageLocal("Error writing to standard stream!",
													   theErrorCode),
								    TranscodeFromLocalCodePage("XercesStdOutputStreamWriteException"))
{
}

XalanStdOutputStream::XalanStdOutputStreamWriteException::~XalanStdOutputStreamWriteException()
{
}
<commit_msg>Better gcc compatibility.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
// Class header file...
#include "XalanStdOutputStream.hpp"

#include <cerrno>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#include <strstream.h>
#else
#include <iostream>
#include <strstream>
#endif

#include <PlatformSupport/DOMStringHelper.hpp>

#if !defined(XALAN_NO_NAMESPACES)
using std::ostream;
using std::cerr;
#endif

XalanStdOutputStream::XalanStdOutputStream(ostream&	theOutputStream) :
	XalanOutputStream(),
	m_outputStream(theOutputStream)
{
	// This will make sure that cerr is not buffered...
	if (&m_outputStream == &cerr)
	{
		setBufferSize(0);
	}
}

XalanStdOutputStream::~XalanStdOutputStream()
{
}

void
XalanStdOutputStream::doFlush()
{
	// Don't try to flush if the stream is in a bad state...
	if(m_outputStream)
	{
		m_outputStream.flush();

		if(!m_outputStream)
		{
			throw XalanStdOutputStreamWriteException(errno);
		}
	}
}

void
XalanStdOutputStream::writeData(
			const char*		theBuffer,
			size_type		theBufferLength)
{
	assert(StreamSizeType(theBufferLength) == theBufferLength);

	m_outputStream.write(theBuffer, StreamSizeType(theBufferLength));

	if(!m_outputStream)
	{
		throw XalanStdOutputStreamWriteException(errno);
	}
}

static XalanDOMString
FormatMessageLocal(
			const char*		theMessage,
			int				theErrorCode)
{
#if !defined(XALAN_NO_NAMESPACES)
using std::ostrstream;
#endif

	XalanDOMString	theResult(TranscodeFromLocalCodePage(theMessage));

	ostrstream   theFormatter;

	theFormatter << ".  The error code was "
				 << theErrorCode
				 << "." << '\0';

	append(theResult, theFormatter.str());

	delete theFormatter.str();

	return theResult;
}

XalanStdOutputStream::XalanStdOutputStreamWriteException::XalanStdOutputStreamWriteException(
		int					theErrorCode) :
	XalanOutputStreamException(FormatMessageLocal("Error writing to standard stream!",
													   theErrorCode),
								    TranscodeFromLocalCodePage("XercesStdOutputStreamWriteException"))
{
}

XalanStdOutputStream::XalanStdOutputStreamWriteException::~XalanStdOutputStreamWriteException()
{
}
<|endoftext|>