<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/tracking.hpp>

#include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>

using Color = cv::Vec4i;
using Image = cv::Mat_<Color>;
using Data = cv::Mat_<uchar>;
using RichData = cv::Mat_<float>;
using Flow = cv::Mat_<cv::Vec2f>;

const Color TRANSPARENT(0,0,0,0);

const int TYPE_NO_DATA = 0;
const int TYPE_NONE = 1;
const int TYPE_CLOUD = 2;
const int TYPE_RAIN = 3;
const int TYPE_STORM = 4;
const int TYPE_HAIL = 5;
const int TYPE_UNKNOWN = 6;

namespace color_detector {

    bool is_cloud_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return b > 0.8*g && g > 0.4*b && b > 3*r;
    }

    bool is_rain_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return b > 3*g && b > 3*r;
    }

    bool is_storm_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return (r > 1.3*g && r > 3*b);
    }

    bool is_hail_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return ((g > 2*r && g > 3*b) // greens
            || (r > 3*g && b > 3*g && r > 0.5*b && b > 0.5*r)); // violets
    }

    bool is_none_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        int a = (r + g + b)/3;
        return (r > 0.8*a && g > 0.8*a && b > 0.8*a && a < 160 && a > 60)  // grays
            || (r > 3*b && g > 3*b && r > 0.8*g && g > 0.8*r);  // yellows
    }

    bool is_no_data_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        int a = (r + g + b)/3;
        return (r > 0.8*a && g > 0.8*a && b > 0.8*a && a >= 160);
    }

    int detect(const Color& color) {
        if (is_hail_color(color))
            return TYPE_HAIL;
        else if (is_storm_color(color))
            return TYPE_STORM;
        else if (is_rain_color(color))
            return TYPE_RAIN;
        else if (is_cloud_color(color))
            return TYPE_CLOUD;
        else if (is_none_color(color))
            return TYPE_NONE;
        else if (is_no_data_color(color))
            return TYPE_NO_DATA;
        else
            return TYPE_UNKNOWN;
    }
}

void colorize(const Data& data, const std::string& filename) {
    static const std::vector<Color> COLORS{
        {0, 0, 0, 255},
        {128, 128, 128, 255},
        {128, 0, 0, 255},
        {255, 0, 0, 255},
        {0, 0, 255, 255},
        {0, 255, 0, 255},
        {255, 0, 255, 255}
    };
    Image im(data.rows, data.cols, TRANSPARENT);
    for (int y = 0; y < data.rows; y++)
        for (int x = 0; x < data.cols; x++) {
            im(y, x) = COLORS[data(y,x)];
        }

    std::vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    cv::imwrite(filename + ".png", im, compression_params);
}

void colorize(const RichData& data, const std::string& filename) {
    Image im(data.rows, data.cols, TRANSPARENT);
    double max, min;
    cv::minMaxLoc(data, &min, &max);
    for (int y = 0; y < data.rows; y++)
        for (int x = 0; x < data.cols; x++) {
            im(y, x) = {(data(y, x) - min)/(max-min)*256, 0, 0, 255};
        }

    std::vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    cv::imwrite(filename + ".png", im, compression_params);
}

void colorize(const Flow& flow, const std::string& filename) {
    cv::Mat3f im(flow.rows, flow.cols, cv::Vec3f(0, 0, 0));
    for (int y = 0; y < flow.rows; y++)
        for (int x = 0; x < flow.cols; x++) {
            float vx = flow(y, x)[0];
            float vy = flow(y, x)[1];
            float v = sqrt(vx*vx + vy*vy);
            float dir = atan2(vy, vx);
            if (dir < 0) dir += 2*M_PI;
            float h = dir / 2 / M_PI * 360;
            float val = (log10(v + 1e-25) + 25) / 10;
            //if (val > 0.5) std::cout << vx << " " << vy << " " << v << std::endl;
            im(y, x) = {h, 1, val};
        }

    cv::Mat4f converted;
    cv::cvtColor(im, converted, cv::COLOR_HSV2BGR, 4);
    Image result = converted * 256;

    std::vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    cv::imwrite(filename + ".png", result, compression_params);
}

template<class T>
void colorize(const std::vector<T>& data, const std::string& filename) {
    for (int i = 0; i < data.size(); i++) {
        char buffer[100];
        sprintf(buffer, filename.c_str(), i);
        colorize(data[i], buffer);
    }
}

bool isFixedColor(const std::vector<Image>& frames, int x, int y) {
    auto col = frames[0](y, x);
    for (const auto& frame: frames) {
        if (frame(y, x) != col)
            return false;
    }
    return true;
}

std::vector<int> makeDd(int max) {
    std::vector<int> dd;
    for (int x = 0; x <= max; x++)
        for (int s: {-1, 1})
            dd.push_back(x * s);
    return dd;
}

template<class M>
bool goodPoint(const M& im, int x, int y) {
    return (x>=0) && (x<im.cols) && (y>=0) && (y<im.rows);
}

std::vector<Image> loadImages(const std::string& filename) {
    std::string fname = filename;
    std::vector<Image> frames;
    for (int frame = 0; frame <= 9; frame++) {
        char buffer[100];
        sprintf(buffer, fname.c_str(), frame);
        frames.push_back(cv::imread(buffer, -1));
    }
    return frames;
}

std::vector<Data> convertToDatas(const std::vector<Image>& frames) {
    Data fixeds = Data::zeros(frames[0].rows, frames[0].cols);
    for (int y = 0; y < fixeds.rows; y++) {
        for (int x = 0; x < fixeds.cols; x++) {
            fixeds(y, x) = isFixedColor(frames, x, y);
        }
    }

    auto dd = makeDd(2);

    std::vector<Data> sourceDataFrames;
    for (const auto& frame: frames) {
        sourceDataFrames.emplace_back(Data::zeros(frame.rows, frame.cols));
        for (int y = 0; y < frame.rows; y++) {
            for (int x = 0; x < frame.cols; x++) {
                sourceDataFrames.back()(y, x) = color_detector::detect(frame(y, x));
            }
        }
    }

    std::vector<Data> dataFrames;
    for (const auto& frame: sourceDataFrames) {
        dataFrames.emplace_back(Data::zeros(frame.rows, frame.cols));
        for (int y = 0; y < frame.rows; y++) {
            for (int x = 0; x < frame.cols; x++) {
                bool found = false;
                bool wasNone = false;
                bool wasNoData = false;
                for (int dx: dd) {
                    for (int dy: dd) {
                        int xx = x + dx;
                        int yy = y + dy;
                        if (goodPoint(frame, xx, yy)) {
                            auto color = frame(yy, xx);
                            if (!fixeds(yy, xx)) {
                                dataFrames.back()(y, x) = color;
                                found = true;
                                break;
                            }
                            wasNone |= (color == TYPE_NONE);
                            wasNoData |= (color == TYPE_NO_DATA);
                        }
                    }
                    if (found) break;
                }
                if (!found) {
                    if (wasNone)
                        dataFrames.back()(y, x) = TYPE_NONE;
                    else if (wasNoData)
                        dataFrames.back()(y, x) = TYPE_NO_DATA;
                    else
                        dataFrames.back()(y, x) = frame(y, x);
                }
            }
        }
    }

    dd = makeDd(dataFrames.size());

    for (int i = 0; i < dataFrames.size(); i++) {
        auto& frame = dataFrames[i];
        for (int y = 0; y < frame.rows; y++) {
            for (int x = 0; x < frame.cols; x++) {
                if (frame(y, x) == TYPE_NO_DATA) {
                    for (int di: dd) {
                        int ii = i + di;
                        if (ii < 0 || ii >= dataFrames.size()) continue;
                        const auto& frame2 = dataFrames[ii];
                        if (frame2(y, x) != TYPE_NO_DATA) {
                            frame(y, x) = frame2(y, x);
                        }
                    }
                }
                if (frame(y, x) == TYPE_NO_DATA)
                    frame(y, x) = TYPE_NONE;
            }
        }
    }

    return dataFrames;
}

RichData makeRichData(const Data& data) {
    cv::Mat padded;
    int m = 2 * cv::getOptimalDFTSize( data.rows );
    int n = 2 * cv::getOptimalDFTSize( data.cols );
    cv::copyMakeBorder(data, padded, 0, m - data.rows, 0, n - data.cols, cv::BORDER_CONSTANT, cv::Scalar::all(TYPE_NONE));

    cv::Mat planes[] = {cv::Mat_<float>(padded), cv::Mat::zeros(padded.size(), CV_32F)};
    cv::Mat complexI;
    cv::merge(planes, 2, complexI);

    cv::dft(complexI, complexI);

    for (int x = 0; x < complexI.cols; x++) {
        for (int y = 0; y < complexI.rows; y++) {
            if (x == 0 && y == 0) {
                complexI.at<cv::Vec2f>(y, x) = 0;
            } else {
                double dx = std::min(x, complexI.cols - x);
                double dy = std::min(y, complexI.rows - y);
                complexI.at<cv::Vec2f>(y, x) = complexI.at<cv::Vec2f>(y, x) / std::pow(std::hypot(dx, dy), 1);
            }
        }
    }

    cv::dft(complexI, complexI, cv::DFT_INVERSE + cv::DFT_SCALE);

    split(complexI, planes);

    std::cout << planes[0].at<float>(0, 0) << " " << planes[1].at<float>(0, 0) << std::endl;

    cv::Rect roi(0, 0, data.cols, data.rows);
    RichData result;
    cv::Mat cropped(planes[0], roi);
    cropped.copyTo(result);

    return result;
}

int main(int argc, char* argv[]) {

    auto images = loadImages(argv[1]);
    auto datas = convertToDatas(images);
    std::vector<RichData> richDatas;
    for (const auto& data: datas)
        richDatas.push_back(makeRichData(data));

    Flow flow;

    cv::calcOpticalFlowFarneback(richDatas[0], richDatas[1], flow, 0.5, 8, 300, 2, 5, 1.3, cv::OPTFLOW_FARNEBACK_GAUSSIAN);

    for (int i = 2; i < richDatas.size(); i++) {
        Flow flow2;
        cv::calcOpticalFlowFarneback(richDatas[i-1], richDatas[i], flow2, 0.5, 8, 300, 2, 5, 1.3, cv::OPTFLOW_FARNEBACK_GAUSSIAN);
        flow += flow2;
    }

    colorize(datas, "data%02d");
    colorize(flow, "test");
    colorize(richDatas, "rdata%02d");

    std::cout << flow(612, 448) << std::endl;

    return 0;
}
<commit_msg>Correct NNOV coordinates<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/tracking.hpp>

#include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>

using Color = cv::Vec4i;
using Image = cv::Mat_<Color>;
using Data = cv::Mat_<uchar>;
using RichData = cv::Mat_<float>;
using Flow = cv::Mat_<cv::Vec2f>;

const Color TRANSPARENT(0,0,0,0);

const int TYPE_NO_DATA = 0;
const int TYPE_NONE = 1;
const int TYPE_CLOUD = 2;
const int TYPE_RAIN = 3;
const int TYPE_STORM = 4;
const int TYPE_HAIL = 5;
const int TYPE_UNKNOWN = 6;

namespace color_detector {

    bool is_cloud_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return b > 0.8*g && g > 0.4*b && b > 3*r;
    }

    bool is_rain_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return b > 3*g && b > 3*r;
    }

    bool is_storm_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return (r > 1.3*g && r > 3*b);
    }

    bool is_hail_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        return ((g > 2*r && g > 3*b) // greens
            || (r > 3*g && b > 3*g && r > 0.5*b && b > 0.5*r)); // violets
    }

    bool is_none_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        int a = (r + g + b)/3;
        return (r > 0.8*a && g > 0.8*a && b > 0.8*a && a < 160 && a > 60)  // grays
            || (r > 3*b && g > 3*b && r > 0.8*g && g > 0.8*r);  // yellows
    }

    bool is_no_data_color(const Color& color) {
        int r = color[2];
        int g = color[1];
        int b = color[0];
        int a = (r + g + b)/3;
        return (r > 0.8*a && g > 0.8*a && b > 0.8*a && a >= 160);
    }

    int detect(const Color& color) {
        if (is_hail_color(color))
            return TYPE_HAIL;
        else if (is_storm_color(color))
            return TYPE_STORM;
        else if (is_rain_color(color))
            return TYPE_RAIN;
        else if (is_cloud_color(color))
            return TYPE_CLOUD;
        else if (is_none_color(color))
            return TYPE_NONE;
        else if (is_no_data_color(color))
            return TYPE_NO_DATA;
        else
            return TYPE_UNKNOWN;
    }
}

void colorize(const Data& data, const std::string& filename) {
    static const std::vector<Color> COLORS{
        {0, 0, 0, 255},
        {128, 128, 128, 255},
        {128, 0, 0, 255},
        {255, 0, 0, 255},
        {0, 0, 255, 255},
        {0, 255, 0, 255},
        {255, 0, 255, 255}
    };
    Image im(data.rows, data.cols, TRANSPARENT);
    for (int y = 0; y < data.rows; y++)
        for (int x = 0; x < data.cols; x++) {
            im(y, x) = COLORS[data(y,x)];
        }

    std::vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    cv::imwrite(filename + ".png", im, compression_params);
}

void colorize(const RichData& data, const std::string& filename) {
    Image im(data.rows, data.cols, TRANSPARENT);
    double max, min;
    cv::minMaxLoc(data, &min, &max);
    for (int y = 0; y < data.rows; y++)
        for (int x = 0; x < data.cols; x++) {
            im(y, x) = {(data(y, x) - min)/(max-min)*256, 0, 0, 255};
        }

    std::vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    cv::imwrite(filename + ".png", im, compression_params);
}

void colorize(const Flow& flow, const std::string& filename) {
    cv::Mat3f im(flow.rows, flow.cols, cv::Vec3f(0, 0, 0));
    for (int y = 0; y < flow.rows; y++)
        for (int x = 0; x < flow.cols; x++) {
            float vx = flow(y, x)[0];
            float vy = flow(y, x)[1];
            float v = sqrt(vx*vx + vy*vy);
            float dir = atan2(vy, vx);
            if (dir < 0) dir += 2*M_PI;
            float h = dir / 2 / M_PI * 360;
            float val = (log10(v + 1e-25) + 25) / 10;
            //if (val > 0.5) std::cout << vx << " " << vy << " " << v << std::endl;
            im(y, x) = {h, 1, val};
        }

    cv::Mat4f converted;
    cv::cvtColor(im, converted, cv::COLOR_HSV2BGR, 4);
    Image result = converted * 256;

    std::vector<int> compression_params;
    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    cv::imwrite(filename + ".png", result, compression_params);
}

template<class T>
void colorize(const std::vector<T>& data, const std::string& filename) {
    for (int i = 0; i < data.size(); i++) {
        char buffer[100];
        sprintf(buffer, filename.c_str(), i);
        colorize(data[i], buffer);
    }
}

bool isFixedColor(const std::vector<Image>& frames, int x, int y) {
    auto col = frames[0](y, x);
    for (const auto& frame: frames) {
        if (frame(y, x) != col)
            return false;
    }
    return true;
}

std::vector<int> makeDd(int max) {
    std::vector<int> dd;
    for (int x = 0; x <= max; x++)
        for (int s: {-1, 1})
            dd.push_back(x * s);
    return dd;
}

template<class M>
bool goodPoint(const M& im, int x, int y) {
    return (x>=0) && (x<im.cols) && (y>=0) && (y<im.rows);
}

std::vector<Image> loadImages(const std::string& filename) {
    std::string fname = filename;
    std::vector<Image> frames;
    for (int frame = 0; frame <= 9; frame++) {
        char buffer[100];
        sprintf(buffer, fname.c_str(), frame);
        frames.push_back(cv::imread(buffer, -1));
    }
    return frames;
}

std::vector<Data> convertToDatas(const std::vector<Image>& frames) {
    Data fixeds = Data::zeros(frames[0].rows, frames[0].cols);
    for (int y = 0; y < fixeds.rows; y++) {
        for (int x = 0; x < fixeds.cols; x++) {
            fixeds(y, x) = isFixedColor(frames, x, y);
        }
    }

    auto dd = makeDd(2);

    std::vector<Data> sourceDataFrames;
    for (const auto& frame: frames) {
        sourceDataFrames.emplace_back(Data::zeros(frame.rows, frame.cols));
        for (int y = 0; y < frame.rows; y++) {
            for (int x = 0; x < frame.cols; x++) {
                sourceDataFrames.back()(y, x) = color_detector::detect(frame(y, x));
            }
        }
    }

    std::vector<Data> dataFrames;
    for (const auto& frame: sourceDataFrames) {
        dataFrames.emplace_back(Data::zeros(frame.rows, frame.cols));
        for (int y = 0; y < frame.rows; y++) {
            for (int x = 0; x < frame.cols; x++) {
                bool found = false;
                bool wasNone = false;
                bool wasNoData = false;
                for (int dx: dd) {
                    for (int dy: dd) {
                        int xx = x + dx;
                        int yy = y + dy;
                        if (goodPoint(frame, xx, yy)) {
                            auto color = frame(yy, xx);
                            if (!fixeds(yy, xx)) {
                                dataFrames.back()(y, x) = color;
                                found = true;
                                break;
                            }
                            wasNone |= (color == TYPE_NONE);
                            wasNoData |= (color == TYPE_NO_DATA);
                        }
                    }
                    if (found) break;
                }
                if (!found) {
                    if (wasNone)
                        dataFrames.back()(y, x) = TYPE_NONE;
                    else if (wasNoData)
                        dataFrames.back()(y, x) = TYPE_NO_DATA;
                    else
                        dataFrames.back()(y, x) = frame(y, x);
                }
            }
        }
    }

    dd = makeDd(dataFrames.size());

    for (int i = 0; i < dataFrames.size(); i++) {
        auto& frame = dataFrames[i];
        for (int y = 0; y < frame.rows; y++) {
            for (int x = 0; x < frame.cols; x++) {
                if (frame(y, x) == TYPE_NO_DATA) {
                    for (int di: dd) {
                        int ii = i + di;
                        if (ii < 0 || ii >= dataFrames.size()) continue;
                        const auto& frame2 = dataFrames[ii];
                        if (frame2(y, x) != TYPE_NO_DATA) {
                            frame(y, x) = frame2(y, x);
                        }
                    }
                }
                if (frame(y, x) == TYPE_NO_DATA)
                    frame(y, x) = TYPE_NONE;
            }
        }
    }

    return dataFrames;
}

RichData makeRichData(const Data& data) {
    cv::Mat padded;
    int m = 2 * cv::getOptimalDFTSize( data.rows );
    int n = 2 * cv::getOptimalDFTSize( data.cols );
    cv::copyMakeBorder(data, padded, 0, m - data.rows, 0, n - data.cols, cv::BORDER_CONSTANT, cv::Scalar::all(TYPE_NONE));

    cv::Mat planes[] = {cv::Mat_<float>(padded), cv::Mat::zeros(padded.size(), CV_32F)};
    cv::Mat complexI;
    cv::merge(planes, 2, complexI);

    cv::dft(complexI, complexI);

    for (int x = 0; x < complexI.cols; x++) {
        for (int y = 0; y < complexI.rows; y++) {
            if (x == 0 && y == 0) {
                complexI.at<cv::Vec2f>(y, x) = 0;
            } else {
                double dx = std::min(x, complexI.cols - x);
                double dy = std::min(y, complexI.rows - y);
                complexI.at<cv::Vec2f>(y, x) = complexI.at<cv::Vec2f>(y, x) / std::pow(std::hypot(dx, dy), 1);
            }
        }
    }

    cv::dft(complexI, complexI, cv::DFT_INVERSE + cv::DFT_SCALE);

    split(complexI, planes);

    std::cout << planes[0].at<float>(0, 0) << " " << planes[1].at<float>(0, 0) << std::endl;

    cv::Rect roi(0, 0, data.cols, data.rows);
    RichData result;
    cv::Mat cropped(planes[0], roi);
    cropped.copyTo(result);

    return result;
}

int main(int argc, char* argv[]) {

    auto images = loadImages(argv[1]);
    auto datas = convertToDatas(images);
    std::vector<RichData> richDatas;
    for (const auto& data: datas)
        richDatas.push_back(makeRichData(data));

    Flow flow;

    cv::calcOpticalFlowFarneback(richDatas[0], richDatas[1], flow, 0.5, 8, 300, 2, 5, 1.3, cv::OPTFLOW_FARNEBACK_GAUSSIAN);

    for (int i = 2; i < richDatas.size(); i++) {
        Flow flow2;
        cv::calcOpticalFlowFarneback(richDatas[i-1], richDatas[i], flow2, 0.5, 8, 300, 2, 5, 1.3, cv::OPTFLOW_FARNEBACK_GAUSSIAN);
        flow += flow2;
    }

    for (auto& data: datas) {
        data(448, 612) = TYPE_UNKNOWN;
        data(449, 612) = TYPE_UNKNOWN;
        data(448, 613) = TYPE_UNKNOWN;
        data(449, 613) = TYPE_UNKNOWN;
    }

    colorize(datas, "data%02d");
    colorize(flow, "test");
    colorize(richDatas, "rdata%02d");

    std::cout << flow(448, 612) << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*!
 *  \file File componentAnimationController.cpp
 *  \brief Implementation of componentAnimationController class
 *
 *  The class implemented here is a controller for the animations
 *
 *  \sa componentAnimationController.hpp
 */

#include <componentAnimationController.hpp>
#include <gameObject.hpp>
#include <camera.hpp>
#include <game.hpp>

#include <assert.h>

//#include <inputManager.hpp>

//! A constructor.
  /*!
  This is a constructor method of CompAnimControl class
  */

CompAnimControl::CompAnimControl(string filename, CompCollider* collider) {
  LOG_METHOD_START("CompAnimControl::CompAnimControl");
  LOG_VARIABLE("filename", filename);
  LOG_VARIABLE("collider", collider.to_string());

  assert(collider != NULL);
  assert(filename != "");

  ifstream in(ANIMATION_PATH + filename + ".txt");

  // Checks if the animation's .txt file is already opened
  if (!in.is_open()) {
    cerr << "Erro ao abrir arquivo de grupo de animações '" << filename << "'";
    cerr << endl;
  }
  else {
    string name = "";
    string animation_filename = "";

    in >> name;
    in >> animation_filename;

    prev = name;
    cur = prev;

    animations[name] = make_unique<CompAnim>(animation_filename, collider);

    while (in >> name >> animation_filename) {
      animations[name] = make_unique<CompAnim>(animation_filename, collider);
    }

    in.close();
  }

  LOG_METHOD_CLOSE("CompAnimControl::CompAnimControl", "constructor");
}

//! A destructor.
  /*!
  This is a destructor method of CompAnimControl class
  */

CompAnimControl::~CompAnimControl() {
  LOG_METHOD_START("CompAnimControl::~CompAnimControl");
  LOG_METHOD_CLOSE("CompAnimControl::~CompAnimControl", "destructor");
}

/*!
  @fn       bool CompAnimControl::kills_component(float time)
  @brief    Method for rendering player's death animation
  @param    float time value
  @return   boolean value
  @warning  TODO: alternative flux in condition structures
*/

bool CompAnimControl::kills_component(float time) { // range: unknown
  LOG_METHOD_START("CompAnimControl::kills_component");
  LOG_VARIABLE("time", time);
  UNUSED(time);

  // Checks if die animation isn't in animations
  if (!animations.count("die")) {
    return true;
  }
  else {
    // Do nothing
  }

  // Checks if player is dying
  if (dying) {

    // Makes method return true if current animation isn't player's death
    if (cur != "die") {
      LOG_METHOD_CLOSE("CompAnimControl::kills_component", "true");
      return true;
    }
    else {
      // Do nothing
    }
  }
  else {
    change_current("die", false);
    dying = true;
  }

  LOG_METHOD_CLOSE("CompAnimControl::kills_component", "false");
  return false;
}

/*!
  @fn       void CompAnimControl::change_current(string anim, bool rep)
  @brief    Changes current animation
  @param    string anim, bool rep
  @return   void
  @warning  none
*/

void CompAnimControl::change_current(string animation_name,
                            bool repeat_animation) {// repeats animation if true
  LOG_METHOD_START("CompAnimControl::change_current");
  LOG_VARIABLE("animation_name", animation_name);
  LOG_VARIABLE("repeat_animation", repeat_animation);

  assert(animation_name != "");

  // Checks if animations vector has anything
  if (animations.count(animation_name)) {

    // TODO: add else (do nothing)
    // Checks if current animation is the one to be shown
    if (cur != animation_name) {

      // If true, makes the animation repeat itself
      if (repeat) {
        prev = cur;
      }
      else {
        // Do nothing
      }

      repeat = repeat_animation;
      cur = animation_name;

      get_current().set_current_frame(0);
      get_current().sp.looped = false;
      get_current().own(GO(entity));
    }
    else {
      // Do nothing
    }
  }
  else {
    cerr << "Erro: Controle de animação nao tem animação '";
    cerr << animation_name;
    cerr << "' entity uid = " << entity << endl;
  }

  LOG_METHOD_CLOSE("CompAnimControl::change_current", "void");
}

/*!
  @fn       void CompAnimControl::update(float time)
  @brief    Updates the animation according to time
  @param    float value resembling time
  @return   void
  @warning  none
*/

void CompAnimControl::update(float time) {
  LOG_METHOD_START("CompAnimControl::update");
  LOG_VARIABLE("time", time);

  // Checks if current animation is in the 'library'
  if (animations.count(cur)) {
    get_current().update(time);

    // Checks if current animation is a looped type or set to repeat
    if (!repeat and get_current().is_looped()) {

      // Defines current frame as 'dead' if Mayumi dies
      if (dying) {
        cur = "dead";
      }
      else {
        change_current(prev);

        get_current().sp.looped = false;
        get_current().update(time);
      }
    }
    else {
      // Do nothing
    }
  }
  else {
    // Do nothing
  }
  LOG_METHOD_CLOSE("CompAnimControl::update", "void");
}

/*!
  @fn       void CompAnimControl::render()
  @brief    Renders current animation
  @param    none
  @return   void
  @warning  none
*/

void CompAnimControl::render() {
  LOG_METHOD_START("CompAnimControl::render");

  // Tries to find the current animation on animations vector, render if found
  if (animations.count(cur)) {
    get_current().render();
  }
  else {
    // Do nothing
  }
  LOG_METHOD_CLOSE("CompAnimControl::render", "void");
}

/*!
  @fn       void CompAnimControl::own(GameObject *go)
  @brief    Sets ownage of animation to a Game Object
  @param    GameObject object
  @return   void
  @warning  none
*/

void CompAnimControl::own(GameObject *game_object) {
  LOG_METHOD_START("CompAnimControl::own");
  LOG_VARIABLE("game_object", game_object.to_string());

  assert(game_object != NULL);

  entity = go->uid;

  for (auto &anim:animations) {
    anim.second->own(go);
  }

  get_current().own(go);
  LOG_METHOD_CLOSE("CompAnimControl::own", "void");
}

/*!
  @fn
  @brief    Returns current animation object
  @param    none
  @return   CompAnim& type animation object pointer
  @warning  none
*/

CompAnim &CompAnimControl::get_current() {
  LOG_METHOD_START("CompAnimControl::get_current");
  LOG_METHOD_CLOSE("CompAnimControl::get_current", "pointer to current animation");

  return *animations[cur];
}

/*!
  @fn       const string& CompAnimControl::get_current_name()const
  @brief    Returns current animation's name as a constant
  @param    none
  @return   const string with animation name
  @warning  none
*/

const string &CompAnimControl::get_current_name() const {
  LOG_METHOD_START("CompAnimControl::get_current_name");
  LOG_METHOD_CLOSE("CompAnimControl::get_current_name", current);

  return current;
}

/*!
  @fn       string& CompAnimControl::get_current_name()
  @brief    Returns current animation's name
  @param    none
  @return   string with current animation's name
  @warning  none
*/

string &CompAnimControl::get_current_name() {
  LOG_METHOD_START("CompAnimControl::get_current_name");
  LOG_METHOD_CLOSE("CompAnimControl::get_current_name", current);

  return current;
}

/*!
  @fn       Component::type CompAnimControl::get_type()const
  @brief    Returns type of component (or animation) as a constant
  @param    none
  @return   const Component::type
  @warning  none
*/

Component::type CompAnimControl::get_type()const {
  LOG_METHOD_START("CompAnimControl::get_type");
  LOG_METHOD_CLOSE("CompAnimControl::get_type", Component::type::t_animation_control.to_string());

  return Component::type::t_animation_control;
}
<commit_msg>[CHECK RETURN] applies technique at file componentAnimationController.cpp<commit_after>/*!
 *  \file File componentAnimationController.cpp
 *  \brief Implementation of componentAnimationController class
 *
 *  The class implemented here is a controller for the animations
 *
 *  \sa componentAnimationController.hpp
 */

#include <componentAnimationController.hpp>
#include <gameObject.hpp>
#include <camera.hpp>
#include <game.hpp>

#include <assert.h>

//#include <inputManager.hpp>

//! A constructor.
  /*!
  This is a constructor method of CompAnimControl class
  */

CompAnimControl::CompAnimControl(string filename, CompCollider* collider) {
  LOG_METHOD_START("CompAnimControl::CompAnimControl");
  LOG_VARIABLE("filename", filename);
  LOG_VARIABLE("collider", collider.to_string());

  assert(collider != NULL);
  assert(filename != "");

  ifstream in(ANIMATION_PATH + filename + ".txt");

  // Checks if the animation's .txt file is already opened
  if (!in.is_open()) {
    cerr << "Erro ao abrir arquivo de grupo de animações '" << filename << "'";
    cerr << endl;
  }
  else {
    string name = "";
    string animation_filename = "";

    in >> name;
    in >> animation_filename;

    prev = name;
    cur = prev;

    animations[name] = make_unique<CompAnim>(animation_filename, collider);

    while (in >> name >> animation_filename) {
      animations[name] = make_unique<CompAnim>(animation_filename, collider);
    }

    in.close();
  }

  LOG_METHOD_CLOSE("CompAnimControl::CompAnimControl", "constructor");
}

//! A destructor.
  /*!
  This is a destructor method of CompAnimControl class
  */

CompAnimControl::~CompAnimControl() {
  LOG_METHOD_START("CompAnimControl::~CompAnimControl");
  LOG_METHOD_CLOSE("CompAnimControl::~CompAnimControl", "destructor");
}

/*!
  @fn       bool CompAnimControl::kills_component(float time)
  @brief    Method for rendering player's death animation
  @param    float time value
  @return   boolean value
  @warning  TODO: alternative flux in condition structures
*/

bool CompAnimControl::kills_component(float time) { // range: unknown
  LOG_METHOD_START("CompAnimControl::kills_component");
  LOG_VARIABLE("time", time);
  UNUSED(time);

  // Checks if die animation isn't in animations
  if (!animations.count("die")) {
    return true;
  }
  else {
    // Do nothing
  }

  // Checks if player is dying
  if (dying) {

    // Makes method return true if current animation isn't player's death
    if (cur != "die") {
      LOG_METHOD_CLOSE("CompAnimControl::kills_component", "true");
      return true;
    }
    else {
      // Do nothing
    }
  }
  else {
    change_current("die", false);
    dying = true;
  }

  LOG_METHOD_CLOSE("CompAnimControl::kills_component", "false");
  return false;
}

/*!
  @fn       void CompAnimControl::change_current(string anim, bool rep)
  @brief    Changes current animation
  @param    string anim, bool rep
  @return   void
  @warning  none
*/

void CompAnimControl::change_current(string animation_name,
                            bool repeat_animation) {// repeats animation if true
  LOG_METHOD_START("CompAnimControl::change_current");
  LOG_VARIABLE("animation_name", animation_name);
  LOG_VARIABLE("repeat_animation", repeat_animation);

  assert(animation_name != "");

  // Checks if animations vector has anything
  if (animations.count(animation_name)) {

    // TODO: add else (do nothing)
    // Checks if current animation is the one to be shown
    if (cur != animation_name) {

      // If true, makes the animation repeat itself
      if (repeat) {
        prev = cur;
      }
      else {
        // Do nothing
      }

      repeat = repeat_animation;
      cur = animation_name;

      get_current().set_current_frame(0);
      get_current().sp.looped = false;
      get_current().own(GO(entity));
    }
    else {
      // Do nothing
    }
  }
  else {
    cerr << "Erro: Controle de animação nao tem animação '";
    cerr << animation_name;
    cerr << "' entity uid = " << entity << endl;
  }

  LOG_METHOD_CLOSE("CompAnimControl::change_current", "void");
}

/*!
  @fn       void CompAnimControl::update(float time)
  @brief    Updates the animation according to time
  @param    float value resembling time
  @return   void
  @warning  none
*/

void CompAnimControl::update(float time) {
  LOG_METHOD_START("CompAnimControl::update");
  LOG_VARIABLE("time", time);

  // Checks if current animation is in the 'library'
  if (animations.count(cur)) {
    get_current().update(time);

    // Checks if current animation is a looped type or set to repeat
    if (!repeat and get_current().is_looped()) {

      // Defines current frame as 'dead' if Mayumi dies
      if (dying) {
        cur = "dead";
      }
      else {
        change_current(prev);

        get_current().sp.looped = false;
        get_current().update(time);
      }
    }
    else {
      // Do nothing
    }
  }
  else {
    // Do nothing
  }
  LOG_METHOD_CLOSE("CompAnimControl::update", "void");
}

/*!
  @fn       void CompAnimControl::render()
  @brief    Renders current animation
  @param    none
  @return   void
  @warning  none
*/

void CompAnimControl::render() {
  LOG_METHOD_START("CompAnimControl::render");

  // Tries to find the current animation on animations vector, render if found
  if (animations.count(cur)) {
    get_current().render();
  }
  else {
    // Do nothing
  }
  LOG_METHOD_CLOSE("CompAnimControl::render", "void");
}

/*!
  @fn       void CompAnimControl::own(GameObject *go)
  @brief    Sets ownage of animation to a Game Object
  @param    GameObject object
  @return   void
  @warning  none
*/

void CompAnimControl::own(GameObject *game_object) {
  LOG_METHOD_START("CompAnimControl::own");
  LOG_VARIABLE("game_object", game_object.to_string());

  assert(game_object != NULL);

  entity = go->uid;

  for (auto &anim:animations) {
    anim.second->own(go);
  }

  get_current().own(go);
  LOG_METHOD_CLOSE("CompAnimControl::own", "void");
}

/*!
  @fn
  @brief    Returns current animation object
  @param    none
  @return   CompAnim& type animation object pointer
  @warning  none
*/

CompAnim &CompAnimControl::get_current() {
  LOG_METHOD_START("CompAnimControl::get_current");
  LOG_METHOD_CLOSE("CompAnimControl::get_current", "pointer to current animation");

  assert(*animations[cur] != NULL);
  return *animations[cur];
}

/*!
  @fn       const string& CompAnimControl::get_current_name()const
  @brief    Returns current animation's name as a constant
  @param    none
  @return   const string with animation name
  @warning  none
*/

const string &CompAnimControl::get_current_name() const {
  LOG_METHOD_START("CompAnimControl::get_current_name");
  LOG_METHOD_CLOSE("CompAnimControl::get_current_name", current);
  assert(current != '');
  return current;
}

/*!
  @fn       string& CompAnimControl::get_current_name()
  @brief    Returns current animation's name
  @param    none
  @return   string with current animation's name
  @warning  none
*/

string &CompAnimControl::get_current_name() {
  LOG_METHOD_START("CompAnimControl::get_current_name");
  LOG_METHOD_CLOSE("CompAnimControl::get_current_name", current);
  assert(current != "");
  return current;
}

/*!
  @fn       Component::type CompAnimControl::get_type()const
  @brief    Returns type of component (or animation) as a constant
  @param    none
  @return   const Component::type
  @warning  none
*/

Component::type CompAnimControl::get_type()const {
  LOG_METHOD_START("CompAnimControl::get_type");
  LOG_METHOD_CLOSE("CompAnimControl::get_type", Component::type::t_animation_control.to_string());
  assert(Component::type::t_animation_control != NULL);
  return Component::type::t_animation_control;
}
<|endoftext|>


<commit_before>#pragma once

// ----------------------------------------------------------------------

namespace tree
{

// ----------------------------------------------------------------------

    template <typename N, typename F1> inline void iterate_leaf(N& aNode, F1 f_name)
    {
        if (aNode.is_leaf()) {
            f_name(aNode);
        }
        else {
            for (auto& node: aNode.subtree) {
                iterate_leaf(node, f_name);
            }
        }
    }

// ----------------------------------------------------------------------

      // stops iterating if f_name returns true
    template <typename N, typename F1> inline bool iterate_leaf_stop(N& aNode, F1 f_name)
    {
        bool stop = false;
        if (aNode.is_leaf()) {
            stop = f_name(aNode);
        }
        else {
            for (auto& node: aNode.subtree) {
                if ((stop = iterate_leaf_stop(node, f_name)))
                    break;
            }
        }
        return stop;
    }

// ----------------------------------------------------------------------

    template <typename N, typename F1, typename F3> inline void iterate_leaf_post(N& aNode, F1 f_name, F3 f_subtree_post)
    {
        if (aNode.is_leaf()) {
            f_name(aNode);
        }
        else {
            for (auto& node: aNode.subtree) {
                iterate_leaf_post(node, f_name, f_subtree_post);
            }
            f_subtree_post(aNode);
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F1, typename F2> inline void iterate_leaf_pre(N& aNode, F1 f_name, F2 f_subtree_pre)
    {
        if (aNode.is_leaf()) {
            f_name(aNode);
        }
        else {
            f_subtree_pre(aNode);
            for (auto& node: aNode.subtree) {
                iterate_leaf_pre(node, f_name, f_subtree_pre);
            }
        }
    }

// ----------------------------------------------------------------------

      // Stop descending the tree if f_subtree_pre returned false
    template <typename N, typename F1, typename F2> inline void iterate_leaf_pre_stop(N& aNode, F1 f_name, F2 f_subtree_pre)
    {
        if (aNode.is_leaf()) {
            f_name(aNode);
        }
        else {
            if (f_subtree_pre(aNode)) {
                for (auto& node: aNode.subtree) {
                    iterate_leaf_pre_stop(node, f_name, f_subtree_pre);
                }
            }
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F3> inline void iterate_pre(N& aNode, F3 f_subtree_pre)
    {
        if (!aNode.is_leaf()) {
            f_subtree_pre(aNode);
            for (auto& node: aNode.subtree) {
                iterate_pre(node, f_subtree_pre);
            }
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F3> inline void iterate_post(N& aNode, F3 f_subtree_post)
    {
        if (!aNode.is_leaf()) {
            for (auto& node: aNode.subtree) {
                iterate_post(node, f_subtree_post);
            }
            f_subtree_post(aNode);
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F1, typename F2, typename F3> inline void iterate_leaf_pre_post(N& aNode, F1 f_name, F2 f_subtree_pre, F3 f_subtree_post)
    {
        if (aNode.is_leaf()) {
            f_name(aNode);
        }
        else {
            f_subtree_pre(aNode);
            for (auto node = aNode.subtree.begin(); node != aNode.subtree.end(); ++node) {
                iterate_leaf_pre_post(*node, f_name, f_subtree_pre, f_subtree_post);
            }
            f_subtree_post(aNode);
        }
    }

// ----------------------------------------------------------------------

} // namespace tree

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>template arguments improvements<commit_after>#pragma once

// ----------------------------------------------------------------------

namespace tree
{

// ----------------------------------------------------------------------

    template <typename N, typename F1> inline void iterate_leaf(N&& aNode, F1&& f_name)
    {
        if (aNode.is_leaf()) {
            f_name(std::forward<N>(aNode));
        }
        else {
            for (auto& node: aNode.subtree) {
                iterate_leaf(node, std::forward<F1>(f_name));
            }
        }
    }

// ----------------------------------------------------------------------

      // stops iterating if f_name returns true
    template <typename N, typename F1> inline bool iterate_leaf_stop(N&& aNode, F1&& f_name)
    {
        bool stop = false;
        if (aNode.is_leaf()) {
            stop = f_name(std::forward<N>(aNode));
        }
        else {
            for (auto& node: aNode.subtree) {
                if ((stop = iterate_leaf_stop(node, f_name)))
                    break;
            }
        }
        return stop;
    }

// ----------------------------------------------------------------------

    template <typename N, typename F1, typename F3> inline void iterate_leaf_post(N&& aNode, F1&& f_name, F3&& f_subtree_post)
    {
        if (aNode.is_leaf()) {
            f_name(std::forward<N>(aNode));
        }
        else {
            for (auto& node: aNode.subtree) {
                iterate_leaf_post(node, std::forward<F1>(f_name), std::forward<F3>(f_subtree_post));
            }
            f_subtree_post(std::forward<N>(aNode));
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F1, typename F2> inline void iterate_leaf_pre(N&& aNode, F1&& f_name, F2&& f_subtree_pre)
    {
        if (aNode.is_leaf()) {
            f_name(std::forward<N>(aNode));
        }
        else {
            f_subtree_pre(std::forward<N>(aNode));
            for (auto& node: aNode.subtree) {
                iterate_leaf_pre(node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre));
            }
        }
    }

// ----------------------------------------------------------------------

      // Stop descending the tree if f_subtree_pre returned false
    template <typename N, typename F1, typename F2> inline void iterate_leaf_pre_stop(N&& aNode, F1&& f_name, F2&& f_subtree_pre)
    {
        if (aNode.is_leaf()) {
            f_name(std::forward<N>(aNode));
        }
        else {
            if (f_subtree_pre(std::forward<N>(aNode))) {
                for (auto& node: aNode.subtree) {
                    iterate_leaf_pre_stop(node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre));
                }
            }
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F3> inline void iterate_pre(N&& aNode, F3&& f_subtree_pre)
    {
        if (!aNode.is_leaf()) {
            f_subtree_pre(std::forward<N>(aNode));
            for (auto& node: aNode.subtree) {
                iterate_pre(node, std::forward<F3>(f_subtree_pre));
            }
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F3> inline void iterate_post(N&& aNode, F3&& f_subtree_post)
    {
        if (!aNode.is_leaf()) {
            for (auto& node: aNode.subtree) {
                iterate_post(node, std::forward<F3>(f_subtree_post));
            }
            f_subtree_post(std::forward<N>(aNode));
        }
    }

// ----------------------------------------------------------------------

    template <typename N, typename F1, typename F2, typename F3> inline void iterate_leaf_pre_post(N&& aNode, F1&& f_name, F2&& f_subtree_pre, F3&& f_subtree_post)
    {
        if (aNode.is_leaf()) {
            f_name(std::forward<N>(aNode));
        }
        else {
            f_subtree_pre(std::forward<N>(aNode));
            for (auto node = aNode.subtree.begin(); node != aNode.subtree.end(); ++node) {
                iterate_leaf_pre_post(*node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre), std::forward<F3>(f_subtree_post));
            }
            f_subtree_post(std::forward<N>(aNode));
        }
    }

// ----------------------------------------------------------------------

} // namespace tree

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>
/*************************************************************************
> File Name: main.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Main entry of Hearthstone++ tool.
> Created Time: 2018/08/21
> Copyright (c) 2018, Chan-Ho Chris Ohk
*************************************************************************/
int main()
{
    return 0;
}<commit_msg>[ci skip] Implement basic structure<commit_after>
/*************************************************************************
> File Name: main.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Main entry of Hearthstone++ tool.
> Created Time: 2018/08/21
> Copyright (c) 2018, Chan-Ho Chris Ohk
*************************************************************************/
#include <clara.hpp>

#include <fstream>
#include <iostream>
#include <string>

inline std::string ToString(const clara::Opt& opt)
{
    std::ostringstream oss;
    oss << (clara::Parser() | opt);
    return oss.str();
}

inline std::string ToString(const clara::Parser& p)
{
    std::ostringstream oss;
    oss << p;
    return oss.str();
}

inline void ExportFile(const std::string& fileName)
{
    std::ofstream outputFile(fileName + ".md");
    if (outputFile)
    {
        // TODO: export card data
    }
    else
    {
        fprintf(stderr, "Failed to write file %s\n", fileName.c_str());
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char* argv[])
{
    // Parse command
    bool showHelp = false;
    bool exportAllCard = false;
    std::string cardSetName;

    // Parsing
    auto parser = clara::Help(showHelp) |
                  clara::Opt(exportAllCard)["-a"]["--all"](
                      "Export all card set list to markdown format") |
                  clara::Opt(cardSetName, "cardSet")["-c"]["--cardset"](
                      "Export specific card set list to markdown format");

    auto result = parser.parse(clara::Args(argc, argv));
    if (!result)
    {
        std::cerr << "Error in command line: " << result.errorMessage() << '\n';
        exit(EXIT_FAILURE);
    }

    if (showHelp)
    {
        std::cout << ToString(parser) << '\n';
        exit(EXIT_SUCCESS);
    }

    if (exportAllCard)
    {

    }
    else if (!cardSetName.empty())
    {

    }

    exit(EXIT_SUCCESS);
}<|endoftext|>


<commit_before><commit_msg>fdo#57417: remove LDAP choice from non windows platform<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: standardcontrol.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 16:03:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_
#define _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_

#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#include "commoncontrol.hxx"
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _LONGCURR_HXX
#include <vcl/longcurr.hxx>
#endif
#ifndef _CTRLBOX_HXX
#include <svtools/ctrlbox.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif

class PushButton;
class MultiLineEdit;
//............................................................................
namespace pcr
{
//............................................................................

    //========================================================================
    //= OTimeControl
    //========================================================================
    class OTimeControl : public OCommonBehaviourControl, TimeField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OTimeControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;
    };

    //========================================================================
    //= ODateControl
    //========================================================================
    class ODateControl : public OCommonBehaviourControl, DateField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            ODateControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;
    };

    //========================================================================
    //= OEditControl
    //========================================================================
    class OEditControl : public OCommonBehaviourControl, Edit
    {
    protected:
        sal_Bool                            m_bIsPassword : 1;

    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OEditControl(Window* _pParent, sal_Bool _bPassWord, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

    protected:
            virtual void modified(Window* _pSource);
    };

    //========================================================================
    //= OCurrencyControl
    //========================================================================
    class OCurrencyControl : public OCommonBehaviourControl, LongCurrencyField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OCurrencyControl( Window* pParent,sal_uInt16 nDigits,
                                                        WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;
    };

    //========================================================================
    //= ONumericControl
    //========================================================================
    class ONumericControl : public OCommonBehaviourControl, NumericField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            ONumericControl( Window* pParent,sal_uInt16 nDigits, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            void                            SetMin(sal_Int32 _nMin) { NumericField::SetMin(_nMin); }
            void                            SetMax(sal_Int32 _nMax) { NumericField::SetMax(_nMax); }
    };

    //========================================================================
    //= OColorControl
    //========================================================================
    class OColorControl : public OCommonBehaviourControl, ColorListBox
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OColorControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP |WB_DROPDOWN|WB_AUTOSIZE);

            // property value handling
            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            // list handling
            virtual sal_Bool                HasList();
            virtual void                    ClearList();
            virtual void                    InsertCtrEntry( const ::rtl::OUString& rString, sal_uInt16 nPos = LISTBOX_APPEND );

            virtual void                    SetCtrSize(const Size& rSize);

    protected:
            virtual void modified(Window* _pSource);
    };

    //========================================================================
    //= OListboxControl
    //========================================================================
    class OListboxControl : public OCommonBehaviourControl, ListBox
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OListboxControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP|WB_SORT|WB_DROPDOWN|WB_AUTOSIZE);

            // property value handling
            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            // list handling
            virtual sal_Bool                HasList();
            virtual void                    ClearList();
            virtual void                    InsertCtrEntry( const ::rtl::OUString& rString, sal_uInt16 nPos = LISTBOX_APPEND );

            virtual void                    SetCtrSize(const Size& rSize);

    protected:
            virtual void modified(Window* _pSource);
    };

    //========================================================================
    //= OComboboxControl
    //========================================================================
    class OComboboxControl : public OCommonBehaviourControl, ComboBox
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OComboboxControl( Window* pParent,
                                                    WinBits nWinStyle = WB_TABSTOP | WB_SORT | WB_DROPDOWN | WB_AUTOSIZE);

            // property value handling
            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            // list handling
            virtual sal_Bool                HasList();
            virtual void                    ClearList();
            virtual void                    InsertCtrEntry( const ::rtl::OUString& rString, sal_uInt16 nPos = LISTBOX_APPEND );

            virtual void                    SetCtrSize(const Size& rSize);

    };

    //========================================================================
    //= OMultilineEditControl
    //========================================================================
    class OMultilineFloatingEdit;
    class OMultilineEditControl : public OCommonBehaviourControl, Control
    {
            OMultilineFloatingEdit*             m_pFloatingEdit;
            MultiLineEdit*                      m_pImplEdit;
            PushButton*                         m_pDropdownButton;
            sal_Bool                            m_bDropdown :1;
            sal_Bool                            m_bEdit     :1;

            DECL_LINK(ReturnHdl,OMultilineFloatingEdit*);
            DECL_LINK(DropDownHdl, PushButton*);

    protected:

            virtual long                    PreNotify( NotifyEvent& rNEvt );
            void                            Resize();

            long                            FindPos(long nSinglePos);

    public:
                                            OMultilineEditControl( Window* pParent,sal_Bool bEdit,
                                                        WinBits nWinStyle = WB_TABSTOP | WB_DROPDOWN);

                                            ~OMultilineEditControl();

            virtual void                    GetFocus();
            virtual sal_Bool                ShowDropDown( sal_Bool bShow );

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            virtual void                    SetLocked(sal_Bool bLocked=sal_True);
    protected:
            virtual void modified(Window* _pSource);
    };
//............................................................................
} // namespace pcr
//............................................................................

#endif // _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_

<commit_msg>INTEGRATION: CWS formdesign01 (1.2.68); FILE MERGED 2004/01/09 13:42:37 fs 1.2.68.5: #i22878# moved TimeDurationInput to usercontrol.* 2004/01/07 14:36:01 fs 1.2.68.4: #100000# make compile with Linux gcc 2003/12/19 14:31:33 fs 1.2.68.3: #22878# TimeDurationInput for inputting, well, time durations 2003/12/03 10:06:43 fs 1.2.68.2: #i22878# measurement units for Width and RowHeight 2003/11/27 14:47:29 fs 1.2.68.1: #i22878# file URL display and date input<commit_after>/*************************************************************************
 *
 *  $RCSfile: standardcontrol.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-19 12:06:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_
#define _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_

#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#include "commoncontrol.hxx"
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _LONGCURR_HXX
#include <vcl/longcurr.hxx>
#endif
#ifndef _CTRLBOX_HXX
#include <svtools/ctrlbox.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif
#ifndef _CALENDAR_HXX
#include <svtools/calendar.hxx>
#endif

class PushButton;
class MultiLineEdit;
//............................................................................
namespace pcr
{
//............................................................................

    //========================================================================
    //= OTimeControl
    //========================================================================
    class OTimeControl : public OCommonBehaviourControl, TimeField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OTimeControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;
    };

    //========================================================================
    //= ODateControl
    //========================================================================
    class ODateControl : public OCommonBehaviourControl, CalendarField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            ODateControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;
    };

    //========================================================================
    //= OEditControl
    //========================================================================
    class OEditControl : public OCommonBehaviourControl, Edit
    {
    protected:
        sal_Bool                            m_bIsPassword : 1;

    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OEditControl(Window* _pParent, sal_Bool _bPassWord, WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

    protected:
            virtual void modified(Window* _pSource);
    };

    //========================================================================
    //= OCurrencyControl
    //========================================================================
    class OCurrencyControl : public OCommonBehaviourControl, LongCurrencyField
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OCurrencyControl( Window* pParent,sal_uInt16 nDigits,
                                                        WinBits nWinStyle = WB_TABSTOP);

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;
    };

    //========================================================================
    //= ONumericControl
    //========================================================================
    class ONumericControl : public OCommonBehaviourControl, MetricField
    {
    private:
        FieldUnit   m_eValueUnit;

    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
            ONumericControl( Window* pParent, sal_uInt16 nDigits, WinBits nWinStyle = WB_TABSTOP );

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            void                            SetMin(sal_Int32 _nMin) { MetricField::SetMin(_nMin); }
            void                            SetMax(sal_Int32 _nMax) { MetricField::SetMax(_nMax); }
            void                            SetFieldUnit( FieldUnit _eUnit ) { MetricField::SetUnit( _eUnit ); }
            void                            SetValueUnit( FieldUnit _eUnit ) { m_eValueUnit = _eUnit; }

    protected:
        MetricField::SetUnit;
        MetricField::SetCustomUnitText;
        MetricField::GetCurUnitText;
        MetricField::SetValue;
    protected:
    inline long  GetLastValue() const { return mnLastValue; }
    };

    //========================================================================
    //= OColorControl
    //========================================================================
    class OColorControl : public OCommonBehaviourControl, ColorListBox
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OColorControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP |WB_DROPDOWN|WB_AUTOSIZE);

            // property value handling
            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            // list handling
            virtual sal_Bool                HasList();
            virtual void                    ClearList();
            virtual void                    InsertCtrEntry( const ::rtl::OUString& rString, sal_uInt16 nPos = LISTBOX_APPEND );

            virtual void                    SetCtrSize(const Size& rSize);

    protected:
            virtual void modified(Window* _pSource);
    };

    //========================================================================
    //= OListboxControl
    //========================================================================
    class OListboxControl : public OCommonBehaviourControl, ListBox
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OListboxControl( Window* pParent, WinBits nWinStyle = WB_TABSTOP|WB_SORT|WB_DROPDOWN|WB_AUTOSIZE);

            // property value handling
            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            // list handling
            virtual sal_Bool                HasList();
            virtual void                    ClearList();
            virtual void                    InsertCtrEntry( const ::rtl::OUString& rString, sal_uInt16 nPos = LISTBOX_APPEND );

            virtual void                    SetCtrSize(const Size& rSize);

    protected:
            virtual void modified(Window* _pSource);
    };

    //========================================================================
    //= OComboboxControl
    //========================================================================
    class OComboboxControl : public OCommonBehaviourControl, ComboBox
    {
    protected:
            virtual long                    PreNotify( NotifyEvent& rNEvt );

    public:
                                            OComboboxControl( Window* pParent,
                                                    WinBits nWinStyle = WB_TABSTOP | WB_SORT | WB_DROPDOWN | WB_AUTOSIZE);

            // property value handling
            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            // list handling
            virtual sal_Bool                HasList();
            virtual void                    ClearList();
            virtual void                    InsertCtrEntry( const ::rtl::OUString& rString, sal_uInt16 nPos = LISTBOX_APPEND );

            virtual void                    SetCtrSize(const Size& rSize);

    };

    //========================================================================
    //= OMultilineEditControl
    //========================================================================
    class OMultilineFloatingEdit;
    class OMultilineEditControl : public OCommonBehaviourControl, Control
    {
            OMultilineFloatingEdit*             m_pFloatingEdit;
            MultiLineEdit*                      m_pImplEdit;
            PushButton*                         m_pDropdownButton;
            sal_Bool                            m_bDropdown :1;
            sal_Bool                            m_bEdit     :1;

            DECL_LINK(ReturnHdl,OMultilineFloatingEdit*);
            DECL_LINK(DropDownHdl, PushButton*);

    protected:

            virtual long                    PreNotify( NotifyEvent& rNEvt );
            void                            Resize();

            long                            FindPos(long nSinglePos);

    public:
                                            OMultilineEditControl( Window* pParent,sal_Bool bEdit,
                                                        WinBits nWinStyle = WB_TABSTOP | WB_DROPDOWN);

                                            ~OMultilineEditControl();

            virtual void                    GetFocus();
            virtual sal_Bool                ShowDropDown( sal_Bool bShow );

            virtual void                    SetProperty(const ::rtl::OUString &rString,sal_Bool bIsUnknown=sal_False);
            virtual ::rtl::OUString         GetProperty()const;

            virtual void                    SetLocked(sal_Bool bLocked=sal_True);
    protected:
            virtual void modified(Window* _pSource);
    };

//............................................................................
} // namespace pcr
//............................................................................

#endif // _EXTENSIONS_PROPCTRLR_STANDARDCONTROL_HXX_

<|endoftext|>


<commit_before>#include "Platform.h"
#include <Log.h>

Platform::Platform(const glm::ivec2& pos, TileType type)
    : GameObject(pos, type)
{
    switch (type)
    {
    case Platformv:
        m_speed = 0.001f;
        m_endPos = m_startPos + glm::ivec2(0, 5);
        m_direction = glm::vec3(0.0f, 1.0f, 0.0f);
        break;
    case PlatformV:
        m_speed = 0.2f;
        m_endPos = m_startPos + glm::ivec2(0, 8);
        m_direction = glm::vec3(0.0f, 1.0f, 0.0f);
        break;
    case Platformh:
        m_speed = 0.1f;
        m_endPos = m_startPos + glm::ivec2(5, 0);
        m_direction = glm::vec3(1.0f, 0.0f, 0.0f);
        break;
    case PlatformH:
        m_speed = 0.2f;
        m_endPos = m_startPos + glm::ivec2(8, 0);
        m_direction = glm::vec3(1.0f, 0.0f, 0.0f);
        break;
    }

    auto& grid = Drawable3DGrid::get();
    //m_currentPos = m_startPos;
    setSize(grid.getTileSize());
    setImage("game_common", "ground");

    //glm::ivec2 v = m_currentPos - grid.getCursor();
    glm::ivec2 v = m_startPos - grid.getCursor();
    glm::vec3 v3 = grid.indexesToCoords(v) + grid.getPosition();

    setPosition(v3);
}

Platform::~Platform()
{
}

void Platform::update(int dt)
{
}

void Platform::fixedUpdate(int dt)
{
    auto& grid = Drawable3DGrid::get();

    //float y = m_pos.y;
    //glm::ivec2 v = m_currentPos - grid.getCursor();
    glm::ivec2 v = m_startPos - grid.getCursor();
    glm::vec3 v3 = grid.indexesToCoords(v) + grid.getPosition();
    //glm::vec3 v3 = m_pos - grid.indexesToCoords(grid.getCursor());
    //LOGI("currentPos=(%d %d)", m_currentPos.x, m_currentPos.y);

    m_movementOffset += m_direction * m_speed;
    LOGI("m_movementOffset=(%f %f) m_direction.y=%f m_speed=%f", m_movementOffset.x, m_movementOffset.y, m_direction.y, m_speed);
    v3 += m_movementOffset;

    glm::ivec2 cp = grid.coordsToIndexes(m_pos, true) + grid.getCursor();
    if ((m_direction.y > 0 && cp.y > m_endPos.y - 1) ||
        (m_direction.y < 0 && cp.y < m_startPos.y))
    {
        m_direction = -m_direction;
    }
    //m_currentPos = grid.coordsToIndexes(m_pos, true) + grid.getCursor();
    //LOGI("cp=(%d %d)\n", cp.x, cp.y);

    setPosition(v3);

    /*glm::ivec2 v = m_currentPos - grid.getCursor();

    bool visible = v.x >= 0 && v.x <= GRID_WIDTH - 1 &&
                   v.y >= 0 && v.y <= GRID_HEIGHT - 1;
    setVisible(visible);
    if (!visible)
        return;

    //const glm::vec3& v3 = convertGridToScreen(m_currentPos);
    glm::vec2 v2 = glm::vec2(v.x, v.y);
    v2 *= grid.getTileSize();
    glm::vec3 v3 = glm::vec3(v2.x, v2.y, 0.0f) + grid.getPosition();

    // movement
    glm::vec3 movement = m_direction * m_speed * 2.0f;
    v3 += movement;
    LOGI("movement=(%f %f) m_speed=%f", movement.x, movement.y, m_speed);
    LOGI("v3=(%f %f)", v3.x, v3.y);

    //if (v3.x <= m_startPos.x || v3.x >= m_endPos.x ||*/
    /*if(v3.y <= m_startPos.y *  ||
       v3.y >= m_endPos.y)
        m_direction = -m_direction;*/

    //setPosition(v3);

    //m_currentPos = grid.coordsToIndexes(m_pos) - grid.getCursor();
//    LOGI("m_currentPos=(%d %d)", m_currentPos.x, m_currentPos.y);
}

void Platform::render() const
{
    Drawable3DImage::render();
}
<commit_msg>update<commit_after>#include "Platform.h"
#include <Log.h>

Platform::Platform(const glm::ivec2& pos, TileType type)
    : GameObject(pos, type)
{
    switch (type)
    {
    case Platformv:
        m_speed = 0.001f;
        m_endPos = m_startPos + glm::ivec2(0, 5);
        m_direction = glm::vec3(0.0f, 1.0f, 0.0f);
        break;
    case PlatformV:
        m_speed = 0.01f;
        m_endPos = m_startPos + glm::ivec2(0, 8);
        m_direction = glm::vec3(0.0f, 1.0f, 0.0f);
        break;
    case Platformh:
        m_speed = 0.001f;
        m_endPos = m_startPos + glm::ivec2(5, 0);
        m_direction = glm::vec3(1.0f, 0.0f, 0.0f);
        break;
    case PlatformH:
        m_speed = 0.01f;
        m_endPos = m_startPos + glm::ivec2(8, 0);
        m_direction = glm::vec3(1.0f, 0.0f, 0.0f);
        break;
    }

    auto& grid = Drawable3DGrid::get();
    //m_currentPos = m_startPos;
    setSize(grid.getTileSize());
    setImage("game_common", "ground");

    glm::ivec2 v = m_startPos - grid.getCursor();
    glm::vec3 v3 = grid.indexesToCoords(v) + grid.getPosition();

    setPosition(v3);
}

Platform::~Platform()
{
}

void Platform::update(int dt)
{
}

void Platform::fixedUpdate(int dt)
{
    auto& grid = Drawable3DGrid::get();

    glm::ivec2 v = m_startPos - grid.getCursor();

    /*bool visible = v.x >= 0 && v.x <= GRID_WIDTH - 1 &&
                   v.y >= 0 && v.y <= GRID_HEIGHT - 1;
    setVisible(visible);
    if (!visible)
        return;*/

    glm::vec3 newPos = grid.indexesToCoords(v) + grid.getPosition();

    m_movementOffset += m_direction * m_speed;
    newPos += m_movementOffset;

    auto negative = [](const glm::vec3& v) {
        return v.x < 0.0f || v.y < 0.0f;
    };

    //glm::ivec2 cp = grid.coordsToIndexes(m_pos, true) + grid.getCursor();
    glm::ivec2 cp = grid.coordsToIndexes(newPos, true) + grid.getCursor();
    if (
        (!negative(m_direction) &&
            glm::length(cp) > glm::length(m_endPos) - 1) ||
        (negative(m_direction) &&
            glm::length(cp) <= glm::length(m_startPos))
    )
    {
        m_direction = -m_direction;
    }
    LOGI("neg(direction)=%d (true?)", negative(m_direction));
    LOGI("len(cp) < len(startPos): %d < %d -> %d\n",
         glm::length(cp), glm::length(m_startPos),
         (glm::length(cp) <= glm::length(m_startPos))
    );
    //m_currentPos = grid.coordsToIndexes(m_pos, true) + grid.getCursor();
    //LOGI("cp=(%d %d)\n", cp.x, cp.y);

    setPosition(newPos);

    /*glm::ivec2 v = m_currentPos - grid.getCursor();

    bool visible = v.x >= 0 && v.x <= GRID_WIDTH - 1 &&
                   v.y >= 0 && v.y <= GRID_HEIGHT - 1;
    setVisible(visible);
    if (!visible)
        return;

    //const glm::vec3& v3 = convertGridToScreen(m_currentPos);
    glm::vec2 v2 = glm::vec2(v.x, v.y);
    v2 *= grid.getTileSize();
    glm::vec3 v3 = glm::vec3(v2.x, v2.y, 0.0f) + grid.getPosition();

    // movement
    glm::vec3 movement = m_direction * m_speed * 2.0f;
    v3 += movement;
    LOGI("movement=(%f %f) m_speed=%f", movement.x, movement.y, m_speed);
    LOGI("v3=(%f %f)", v3.x, v3.y);

    //if (v3.x <= m_startPos.x || v3.x >= m_endPos.x ||*/
    /*if(v3.y <= m_startPos.y *  ||
       v3.y >= m_endPos.y)
        m_direction = -m_direction;*/

    //setPosition(v3);

    //m_currentPos = grid.coordsToIndexes(m_pos) - grid.getCursor();
//    LOGI("m_currentPos=(%d %d)", m_currentPos.x, m_currentPos.y);
}

void Platform::render() const
{
    Drawable3DImage::render();
}
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2009, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "condor_debug.h"
#include "read_user_log.h"
#include "write_user_log.h"
#include <time.h>
#include "MyString.h"
#include "condor_config.h"
#include "stat_wrapper.h"
#include "user_log_header.h"

//
// UserLogHeader (base class) methods
//

// Simple constructor for the user log header
UserLogHeader::UserLogHeader( void )
{
	m_sequence = 0;
	m_ctime = 0;
	m_size = 0;
	m_num_events = 0;
	m_file_offset = 0;
	m_event_offset = 0;
	m_max_rotation = -1;
	m_creator_name = "";
	m_valid = false;
}

// Copy constructor for the user log header
UserLogHeader::UserLogHeader( const UserLogHeader &other )
{
	setId(          other.getId() );
	setSequence(    other.getSequence() );
	setCtime(       other.getCtime() );
	setSize(        other.getSize() );
	setNumEvents(   other.getNumEvents() );
	setFileOffset(  other.getFileOffset() );
	setEventOffset( other.getEventOffset() );
	setMaxRotation( other.getMaxRotation() );
	setCreatorName( other.getCreatorName() );

	m_valid = other.IsValid( );
}

// Extract info from an event
int
UserLogHeader::ExtractEvent( const ULogEvent *event )
{
	// Not a generic event -- ignore it
	if ( ULOG_GENERIC != event->eventNumber ) {
		return ULOG_NO_EVENT;
	}

	const GenericEvent	*generic = dynamic_cast <const GenericEvent*>( event );
	if ( ! generic ) {
		dprintf( D_ALWAYS, "Can't pointer cast generic event!\n" );
		return ULOG_UNK_ERROR;
	}
	{
		char	buf[1024];
		memset( buf, 0, sizeof(buf) );
		strncpy( buf, generic->info, sizeof(buf)-1 );
		buf[COUNTOF(buf)-1] = 0; // make sure it's null terminated.
		int size = strlen( buf );
		while( isspace(buf[size-1]) )
			buf[--size] = '\0';
		::dprintf( D_FULLDEBUG,
				   "UserLogHeader::ExtractEvent(): parsing '%s'\n",
				   buf );
	}

	char		 id[256];
	char		 name[256];
	int			 ctime;

	id[0] = '\0';
	name[0] = '\0';
	int n = sscanf( generic->info,
					"Global JobLog:"
					" ctime=%d"
					" id=%255s"
					" sequence=%d"
					" size=" FILESIZE_T_FORMAT""
					" events=%" PRId64""
					" offset=" FILESIZE_T_FORMAT""
					" event_off=%" PRId64""
					" max_rotation=%d"
					" creator_name=<%255[^>]>",
					&ctime,
					id,
					&m_sequence,
					&m_size,
					&m_num_events,
					&m_file_offset,
					&m_event_offset,
					&m_max_rotation,
					name
					);
	if ( n >= 3 ) {
		m_ctime = ctime;
		m_id = id;
		m_valid = true;

		if ( n >= 8 ) {
			m_creator_name = name;
		}
		else {
			m_creator_name = "";
			m_max_rotation = -1;
		}

		if (IsFulldebug(D_FULLDEBUG)) {
			dprint( D_FULLDEBUG, "UserLogHeader::ExtractEvent(): parsed ->" );
		}
		return ULOG_OK;
	}
	else {
		::dprintf( D_FULLDEBUG,
				   "UserLogHeader::ExtractEvent(): can't parse '%s' => %d\n",
				   generic->info, n );
		return ULOG_NO_EVENT;
	}
}

// sprintf() method
void
UserLogHeader::sprint_cat( MyString &buf ) const
{
	if ( m_valid ) {
		buf.formatstr_cat( "id=%s"
						 " seq=%d"
						 " ctime=%lu"
						 " size=" FILESIZE_T_FORMAT
						 " num=%" PRIi64
						 " file_offset=" FILESIZE_T_FORMAT
						 " event_offset=%" PRIi64
						 " max_rotation=%d"
						 " creator_name=<%s>",
						 m_id.Value(),
						 m_sequence,
						 (unsigned long) m_ctime,
						 m_size,
						 m_num_events,
						 m_file_offset,
						 m_event_offset,
						 m_max_rotation,
						 m_creator_name.Value()
						 );
	}
	else {
		buf += "invalid";
	}
}

// dprint() method
void
UserLogHeader::dprint( int level, MyString &buf ) const
{
	if ( ! IsDebugCatAndVerbosity(level) ) {
		return;
	}

	sprint_cat( buf );
	::dprintf( level, "%s\n", buf.Value() );
}

// dprint() method
void
UserLogHeader::dprint( int level, const char *label ) const
{
	if ( ! IsDebugCatAndVerbosity(level) ) {
		return;
	}

	if ( NULL == label ) {
		label = "";
	}

	MyString	buf;
	buf.formatstr( "%s header:", label );
	this->dprint( level, buf );
}

//
// ReadUserLogHeader methods
//
int
ReadUserLogHeader::Read(
	ReadUserLog	&reader )
{

	// Now, read the event itself
	ULogEvent			*event = NULL;
	ULogEventOutcome	outcome = reader.readEvent( event );

	if ( ULOG_OK != outcome ) {
		::dprintf( D_FULLDEBUG,
				   "ReadUserLogHeader::Read(): readEvent() failed\n" );
		delete event;
		return outcome;
	}
	if ( ULOG_GENERIC != event->eventNumber ) {
		::dprintf( D_FULLDEBUG,
				   "ReadUserLogHeader::Read(): event #%d should be %d\n",
				   event->eventNumber, ULOG_GENERIC );
		delete event;
		return ULOG_NO_EVENT;
	}

	int rval = ExtractEvent( event );
	delete event;

	if ( rval != ULOG_OK) {
		::dprintf( D_FULLDEBUG,
				   "ReadUserLogHeader::Read(): failed to extract event\n" );
	}
	return rval;
}

//
// WriteUserLogHeader methods
//

// Write a header event
int
WriteUserLogHeader::Write( WriteUserLog &writer, int fd )
{
	GenericEvent	event;

	if ( 0 == m_ctime ) {
		m_ctime = time( NULL );
	}
	if ( !GenerateEvent( event ) ) {
		return ULOG_UNK_ERROR;
	}
	return writer.writeGlobalEvent( event, fd, true );
}

// Generate a header event
bool
WriteUserLogHeader::GenerateEvent( GenericEvent &event )
{
	int len = snprintf( event.info, COUNTOF(event.info),
			  "Global JobLog:"
			  " ctime=%d"
			  " id=%s"
			  " sequence=%d"
			  " size=" FILESIZE_T_FORMAT""
			  " events=%" PRId64""
			  " offset=" FILESIZE_T_FORMAT""
			  " event_off=%" PRId64""
			  " max_rotation=%d"
			  " creator_name=<%s>",
			  (int) getCtime(),
			  getId().Value(),
			  getSequence(),
			  getSize(),
			  getNumEvents(),
			  getFileOffset(),
			  getEventOffset(),
			  getMaxRotation(),
			  getCreatorName().Value()
			  );
	if (len < 0 || len == sizeof(event.info)) {
		// not enough room in the buffer
		len = (int)COUNTOF(event.info)-1;
		event.info[len] = 0; // make sure it's null terminated.
		::dprintf( D_FULLDEBUG, "Generated (truncated) log header: '%s'\n", event.info );
	}  else {
		::dprintf( D_FULLDEBUG, "Generated log header: '%s'\n", event.info );
		while( len < 256 ) {
			event.info[len++] = ' ';
			event.info[len] = 0;
		}
	}

	return true;
}
<commit_msg>Remove useless dprintf<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2009, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "condor_debug.h"
#include "read_user_log.h"
#include "write_user_log.h"
#include <time.h>
#include "MyString.h"
#include "condor_config.h"
#include "stat_wrapper.h"
#include "user_log_header.h"

//
// UserLogHeader (base class) methods
//

// Simple constructor for the user log header
UserLogHeader::UserLogHeader( void )
{
	m_sequence = 0;
	m_ctime = 0;
	m_size = 0;
	m_num_events = 0;
	m_file_offset = 0;
	m_event_offset = 0;
	m_max_rotation = -1;
	m_creator_name = "";
	m_valid = false;
}

// Copy constructor for the user log header
UserLogHeader::UserLogHeader( const UserLogHeader &other )
{
	setId(          other.getId() );
	setSequence(    other.getSequence() );
	setCtime(       other.getCtime() );
	setSize(        other.getSize() );
	setNumEvents(   other.getNumEvents() );
	setFileOffset(  other.getFileOffset() );
	setEventOffset( other.getEventOffset() );
	setMaxRotation( other.getMaxRotation() );
	setCreatorName( other.getCreatorName() );

	m_valid = other.IsValid( );
}

// Extract info from an event
int
UserLogHeader::ExtractEvent( const ULogEvent *event )
{
	// Not a generic event -- ignore it
	if ( ULOG_GENERIC != event->eventNumber ) {
		return ULOG_NO_EVENT;
	}

	const GenericEvent	*generic = dynamic_cast <const GenericEvent*>( event );
	if ( ! generic ) {
		dprintf( D_ALWAYS, "Can't pointer cast generic event!\n" );
		return ULOG_UNK_ERROR;
	}

	char		 id[256];
	char		 name[256];
	int			 ctime;

	id[0] = '\0';
	name[0] = '\0';
	int n = sscanf( generic->info,
					"Global JobLog:"
					" ctime=%d"
					" id=%255s"
					" sequence=%d"
					" size=" FILESIZE_T_FORMAT""
					" events=%" PRId64""
					" offset=" FILESIZE_T_FORMAT""
					" event_off=%" PRId64""
					" max_rotation=%d"
					" creator_name=<%255[^>]>",
					&ctime,
					id,
					&m_sequence,
					&m_size,
					&m_num_events,
					&m_file_offset,
					&m_event_offset,
					&m_max_rotation,
					name
					);
	if ( n >= 3 ) {
		m_ctime = ctime;
		m_id = id;
		m_valid = true;

		if ( n >= 8 ) {
			m_creator_name = name;
		}
		else {
			m_creator_name = "";
			m_max_rotation = -1;
		}

		if (IsFulldebug(D_FULLDEBUG)) {
			dprint( D_FULLDEBUG, "UserLogHeader::ExtractEvent(): parsed ->" );
		}
		return ULOG_OK;
	}
	else {
		::dprintf( D_FULLDEBUG,
				   "UserLogHeader::ExtractEvent(): can't parse '%s' => %d\n",
				   generic->info, n );
		return ULOG_NO_EVENT;
	}
}

// sprintf() method
void
UserLogHeader::sprint_cat( MyString &buf ) const
{
	if ( m_valid ) {
		buf.formatstr_cat( "id=%s"
						 " seq=%d"
						 " ctime=%lu"
						 " size=" FILESIZE_T_FORMAT
						 " num=%" PRIi64
						 " file_offset=" FILESIZE_T_FORMAT
						 " event_offset=%" PRIi64
						 " max_rotation=%d"
						 " creator_name=<%s>",
						 m_id.Value(),
						 m_sequence,
						 (unsigned long) m_ctime,
						 m_size,
						 m_num_events,
						 m_file_offset,
						 m_event_offset,
						 m_max_rotation,
						 m_creator_name.Value()
						 );
	}
	else {
		buf += "invalid";
	}
}

// dprint() method
void
UserLogHeader::dprint( int level, MyString &buf ) const
{
	if ( ! IsDebugCatAndVerbosity(level) ) {
		return;
	}

	sprint_cat( buf );
	::dprintf( level, "%s\n", buf.Value() );
}

// dprint() method
void
UserLogHeader::dprint( int level, const char *label ) const
{
	if ( ! IsDebugCatAndVerbosity(level) ) {
		return;
	}

	if ( NULL == label ) {
		label = "";
	}

	MyString	buf;
	buf.formatstr( "%s header:", label );
	this->dprint( level, buf );
}

//
// ReadUserLogHeader methods
//
int
ReadUserLogHeader::Read(
	ReadUserLog	&reader )
{

	// Now, read the event itself
	ULogEvent			*event = NULL;
	ULogEventOutcome	outcome = reader.readEvent( event );

	if ( ULOG_OK != outcome ) {
		::dprintf( D_FULLDEBUG,
				   "ReadUserLogHeader::Read(): readEvent() failed\n" );
		delete event;
		return outcome;
	}
	if ( ULOG_GENERIC != event->eventNumber ) {
		::dprintf( D_FULLDEBUG,
				   "ReadUserLogHeader::Read(): event #%d should be %d\n",
				   event->eventNumber, ULOG_GENERIC );
		delete event;
		return ULOG_NO_EVENT;
	}

	int rval = ExtractEvent( event );
	delete event;

	if ( rval != ULOG_OK) {
		::dprintf( D_FULLDEBUG,
				   "ReadUserLogHeader::Read(): failed to extract event\n" );
	}
	return rval;
}

//
// WriteUserLogHeader methods
//

// Write a header event
int
WriteUserLogHeader::Write( WriteUserLog &writer, int fd )
{
	GenericEvent	event;

	if ( 0 == m_ctime ) {
		m_ctime = time( NULL );
	}
	if ( !GenerateEvent( event ) ) {
		return ULOG_UNK_ERROR;
	}
	return writer.writeGlobalEvent( event, fd, true );
}

// Generate a header event
bool
WriteUserLogHeader::GenerateEvent( GenericEvent &event )
{
	int len = snprintf( event.info, COUNTOF(event.info),
			  "Global JobLog:"
			  " ctime=%d"
			  " id=%s"
			  " sequence=%d"
			  " size=" FILESIZE_T_FORMAT""
			  " events=%" PRId64""
			  " offset=" FILESIZE_T_FORMAT""
			  " event_off=%" PRId64""
			  " max_rotation=%d"
			  " creator_name=<%s>",
			  (int) getCtime(),
			  getId().Value(),
			  getSequence(),
			  getSize(),
			  getNumEvents(),
			  getFileOffset(),
			  getEventOffset(),
			  getMaxRotation(),
			  getCreatorName().Value()
			  );
	if (len < 0 || len == sizeof(event.info)) {
		// not enough room in the buffer
		len = (int)COUNTOF(event.info)-1;
		event.info[len] = 0; // make sure it's null terminated.
		::dprintf( D_FULLDEBUG, "Generated (truncated) log header: '%s'\n", event.info );
	}  else {
		::dprintf( D_FULLDEBUG, "Generated log header: '%s'\n", event.info );
		while( len < 256 ) {
			event.info[len++] = ' ';
			event.info[len] = 0;
		}
	}

	return true;
}
<|endoftext|>