<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License as
  published by the Free Software Foundation, and provided that the
  following conditions are met:

      * Redistributions of source code must retain this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below).

      * Redistributions in binary form must reproduce this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below) in the documentation and/or other materials
        provided with the distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.

COPYRIGHT NOTICE:

  TokuDB, Tokutek Fractal Tree Indexing Library.
  Copyright (C) 2007-2013 Tokutek, Inc.

DISCLAIMER:

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

UNIVERSITY PATENT NOTICE:

  The technology is licensed by the Massachusetts Institute of
  Technology, Rutgers State University of New Jersey, and the Research
  Foundation of State University of New York at Stony Brook under
  United States of America Serial No. 11/760379 and to the patents
  and/or patent applications resulting from it.

PATENT MARKING NOTICE:

  This software is covered by US Patent No. 8,185,551.
  This software is covered by US Patent No. 8,489,638.

PATENT RIGHTS GRANT:

  "THIS IMPLEMENTATION" means the copyrightable works distributed by
  Tokutek as part of the Fractal Tree project.

  "PATENT CLAIMS" means the claims of patents that are owned or
  licensable by Tokutek, both currently or in the future; and that in
  the absence of this license would be infringed by THIS
  IMPLEMENTATION or by using or running THIS IMPLEMENTATION.

  "PATENT CHALLENGE" shall mean a challenge to the validity,
  patentability, enforceability and/or non-infringement of any of the
  PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.

  Tokutek hereby grants to you, for the term and geographical scope of
  the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
  irrevocable (except as stated in this section) patent license to
  make, have made, use, offer to sell, sell, import, transfer, and
  otherwise run, modify, and propagate the contents of THIS
  IMPLEMENTATION, where such license applies only to the PATENT
  CLAIMS.  This grant does not include claims that would be infringed
  only as a consequence of further modifications of THIS
  IMPLEMENTATION.  If you or your agent or licensee institute or order
  or agree to the institution of patent litigation against any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  THIS IMPLEMENTATION constitutes direct or contributory patent
  infringement, or inducement of patent infringement, then any rights
  granted to you under this License shall terminate as of the date
  such litigation is filed.  If you or your agent or exclusive
  licensee institute or order or agree to the institution of a PATENT
  CHALLENGE, then Tokutek may terminate any rights granted to you
  under this License.
*/

#ident "Copyright (c) 2007-2013 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

// Create a rollback log with a rollinclude log entry, crash after the txn commits and before the last checkpoint.
// Recovery crashes 7.1.0, should succeed.

#include "test.h"
#include <endian.h>

// Insert max_rows key/val pairs into the db

// We want to force a rollinclude so we use a child transaction and insert enough rows so that it spills.
// It spills at about 144K and 289K rows.
static void do_inserts(DB_ENV *env, DB *db, uint64_t max_rows, size_t val_size) {
    char val_data[val_size]; memset(val_data, 0, val_size);
    int r;
    DB_TXN *parent = nullptr;
    r = env->txn_begin(env, nullptr, &parent, 0);
    CKERR(r);

    DB_TXN *child = nullptr;
    r = env->txn_begin(env, parent, &child, 0);
    CKERR(r);

    for (uint64_t i = 0; i < max_rows; i++) {
        // pick a sequential key but it does not matter for this test.
        uint64_t k[2] = {
            htonl(i), random64(),
        };

        DBT key = { .data = k, .size = sizeof k };
        DBT val = { .data = val_data, .size = (uint32_t) val_size };
        r = db->put(db, child, &key, &val, 0);
        CKERR(r);

        if (i == max_rows-1) {
            r = child->commit(child, 0);
            CKERR(r);

            r = env->txn_checkpoint(env, 0, 0, 0);
            CKERR(r);
        }
    }

    r = parent->commit(parent, 0);
    CKERR(r);
}

static void run_test(uint64_t num_rows, size_t val_size, bool do_crash) {
    int r;

    DB_ENV *env = nullptr;
    r = db_env_create(&env, 0);
    CKERR(r);
    r = env->set_cachesize(env, 8, 0, 1);
    CKERR(r);
    r = env->open(env, TOKU_TEST_FILENAME,
                  DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE,
                  S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    DB *db = nullptr;
    r = db_create(&db, env, 0);
    CKERR(r);
    r = db->open(db, nullptr, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    r = env->txn_checkpoint(env, 0, 0, 0);
    CKERR(r);

    do_inserts(env, db, num_rows, val_size);

    if (do_crash)
        assert(0); // crash on purpose

    r = db->close(db, 0);
    CKERR(r);

    r = env->close(env, 0);
    CKERR(r);
}

static void do_verify(DB_ENV *env, DB *db, uint64_t num_rows, size_t val_size UU()) {
    int r;
    DB_TXN *txn = nullptr;
    r = env->txn_begin(env, nullptr, &txn, 0);
    CKERR(r);

    DBC *c = nullptr;
    r = db->cursor(db, txn, &c, 0);
    CKERR(r);

    uint64_t i = 0;
    while (1) {
        DBT key = {};
        DBT val = {};
        r = c->c_get(c, &key, &val, DB_NEXT);
        if (r == DB_NOTFOUND)
            break;
        CKERR(r);
        assert(key.size == 16);
        uint64_t k[2];
        memcpy(k, key.data, key.size);
        assert(htonl(k[0]) == i);
        assert(val.size == val_size);
        i++;
    }
    assert(i == num_rows);

    r = c->c_close(c);
    CKERR(r);

    r = txn->commit(txn, 0);
    CKERR(r);
}

static void run_recover(uint64_t num_rows, size_t val_size) {
    int r;

    DB_ENV *env = nullptr;
    r = db_env_create(&env, 0);
    CKERR(r);
    r = env->set_cachesize(env, 8, 0, 1);
    CKERR(r);
    r = env->open(env, TOKU_TEST_FILENAME,
                  DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE | DB_RECOVER,
                  S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    DB *db = nullptr;
    r = db_create(&db, env, 0);
    CKERR(r);
    r = db->open(db, nullptr, "foo.db", 0, DB_BTREE, 0, S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    do_verify(env, db, num_rows, val_size);

    r = db->close(db, 0);
    CKERR(r);

    r = env->close(env, 0);
    CKERR(r);
}

int test_main (int argc, char *const argv[]) {
    bool do_test = false;
    bool do_recover = false;
    bool do_crash = true;
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0) {
            verbose++;
            continue;
        }
        if (strcmp(argv[i], "-q") == 0) {
            if (verbose > 0) verbose--;
            continue;
        }
        if (strcmp(argv[i], "--test") == 0) {
            do_test = true;
            continue;
        }
        if (strcmp(argv[i], "--recover") == 0) {
            do_recover = true;
            continue;
        }
        if (strcmp(argv[i], "--crash") == 0 && i+1 < argc) {
            do_crash = atoi(argv[++i]);
            continue;
        }
    }

    uint64_t num_rows = 300000;
    size_t val_size = 1;

    if (do_test) {
        // init the env directory
        toku_os_recursive_delete(TOKU_TEST_FILENAME);
        int r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO);
        CKERR(r);
        run_test(num_rows, val_size, do_crash);
    }
    if (do_recover) {
        run_recover(num_rows, val_size);
    }

    return 0;
}
<commit_msg>FT-548 fix dirty upgrade build on osx problem<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:

  This program is free software; you can redistribute it and/or modify
  it under the terms of version 2 of the GNU General Public License as
  published by the Free Software Foundation, and provided that the
  following conditions are met:

      * Redistributions of source code must retain this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below).

      * Redistributions in binary form must reproduce this COPYING
        CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
        DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
        PATENT MARKING NOTICE (below), and the PATENT RIGHTS
        GRANT (below) in the documentation and/or other materials
        provided with the distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301, USA.

COPYRIGHT NOTICE:

  TokuDB, Tokutek Fractal Tree Indexing Library.
  Copyright (C) 2007-2013 Tokutek, Inc.

DISCLAIMER:

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

UNIVERSITY PATENT NOTICE:

  The technology is licensed by the Massachusetts Institute of
  Technology, Rutgers State University of New Jersey, and the Research
  Foundation of State University of New York at Stony Brook under
  United States of America Serial No. 11/760379 and to the patents
  and/or patent applications resulting from it.

PATENT MARKING NOTICE:

  This software is covered by US Patent No. 8,185,551.
  This software is covered by US Patent No. 8,489,638.

PATENT RIGHTS GRANT:

  "THIS IMPLEMENTATION" means the copyrightable works distributed by
  Tokutek as part of the Fractal Tree project.

  "PATENT CLAIMS" means the claims of patents that are owned or
  licensable by Tokutek, both currently or in the future; and that in
  the absence of this license would be infringed by THIS
  IMPLEMENTATION or by using or running THIS IMPLEMENTATION.

  "PATENT CHALLENGE" shall mean a challenge to the validity,
  patentability, enforceability and/or non-infringement of any of the
  PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.

  Tokutek hereby grants to you, for the term and geographical scope of
  the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
  irrevocable (except as stated in this section) patent license to
  make, have made, use, offer to sell, sell, import, transfer, and
  otherwise run, modify, and propagate the contents of THIS
  IMPLEMENTATION, where such license applies only to the PATENT
  CLAIMS.  This grant does not include claims that would be infringed
  only as a consequence of further modifications of THIS
  IMPLEMENTATION.  If you or your agent or licensee institute or order
  or agree to the institution of patent litigation against any entity
  (including a cross-claim or counterclaim in a lawsuit) alleging that
  THIS IMPLEMENTATION constitutes direct or contributory patent
  infringement, or inducement of patent infringement, then any rights
  granted to you under this License shall terminate as of the date
  such litigation is filed.  If you or your agent or exclusive
  licensee institute or order or agree to the institution of a PATENT
  CHALLENGE, then Tokutek may terminate any rights granted to you
  under this License.
*/

#ident "Copyright (c) 2007-2013 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

// Create a rollback log with a rollinclude log entry, crash after the txn commits and before the last checkpoint.
// Recovery crashes 7.1.0, should succeed.

#include "test.h"

// Insert max_rows key/val pairs into the db

// We want to force a rollinclude so we use a child transaction and insert enough rows so that it spills.
// It spills at about 144K and 289K rows.
static void do_inserts(DB_ENV *env, DB *db, uint64_t max_rows, size_t val_size) {
    char val_data[val_size]; memset(val_data, 0, val_size);
    int r;
    DB_TXN *parent = nullptr;
    r = env->txn_begin(env, nullptr, &parent, 0);
    CKERR(r);

    DB_TXN *child = nullptr;
    r = env->txn_begin(env, parent, &child, 0);
    CKERR(r);

    for (uint64_t i = 0; i < max_rows; i++) {
        // pick a sequential key but it does not matter for this test.
        uint64_t k[2] = {
            htonl(i), random64(),
        };

        DBT key = { .data = k, .size = sizeof k };
        DBT val = { .data = val_data, .size = (uint32_t) val_size };
        r = db->put(db, child, &key, &val, 0);
        CKERR(r);

        if (i == max_rows-1) {
            r = child->commit(child, 0);
            CKERR(r);

            r = env->txn_checkpoint(env, 0, 0, 0);
            CKERR(r);
        }
    }

    r = parent->commit(parent, 0);
    CKERR(r);
}

static void run_test(uint64_t num_rows, size_t val_size, bool do_crash) {
    int r;

    DB_ENV *env = nullptr;
    r = db_env_create(&env, 0);
    CKERR(r);
    r = env->set_cachesize(env, 8, 0, 1);
    CKERR(r);
    r = env->open(env, TOKU_TEST_FILENAME,
                  DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE,
                  S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    DB *db = nullptr;
    r = db_create(&db, env, 0);
    CKERR(r);
    r = db->open(db, nullptr, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    r = env->txn_checkpoint(env, 0, 0, 0);
    CKERR(r);

    do_inserts(env, db, num_rows, val_size);

    if (do_crash)
        assert(0); // crash on purpose

    r = db->close(db, 0);
    CKERR(r);

    r = env->close(env, 0);
    CKERR(r);
}

static void do_verify(DB_ENV *env, DB *db, uint64_t num_rows, size_t val_size UU()) {
    int r;
    DB_TXN *txn = nullptr;
    r = env->txn_begin(env, nullptr, &txn, 0);
    CKERR(r);

    DBC *c = nullptr;
    r = db->cursor(db, txn, &c, 0);
    CKERR(r);

    uint64_t i = 0;
    while (1) {
        DBT key = {};
        DBT val = {};
        r = c->c_get(c, &key, &val, DB_NEXT);
        if (r == DB_NOTFOUND)
            break;
        CKERR(r);
        assert(key.size == 16);
        uint64_t k[2];
        memcpy(k, key.data, key.size);
        assert(htonl(k[0]) == i);
        assert(val.size == val_size);
        i++;
    }
    assert(i == num_rows);

    r = c->c_close(c);
    CKERR(r);

    r = txn->commit(txn, 0);
    CKERR(r);
}

static void run_recover(uint64_t num_rows, size_t val_size) {
    int r;

    DB_ENV *env = nullptr;
    r = db_env_create(&env, 0);
    CKERR(r);
    r = env->set_cachesize(env, 8, 0, 1);
    CKERR(r);
    r = env->open(env, TOKU_TEST_FILENAME,
                  DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE | DB_RECOVER,
                  S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    DB *db = nullptr;
    r = db_create(&db, env, 0);
    CKERR(r);
    r = db->open(db, nullptr, "foo.db", 0, DB_BTREE, 0, S_IRWXU+S_IRWXG+S_IRWXO);
    CKERR(r);

    do_verify(env, db, num_rows, val_size);

    r = db->close(db, 0);
    CKERR(r);

    r = env->close(env, 0);
    CKERR(r);
}

int test_main (int argc, char *const argv[]) {
    bool do_test = false;
    bool do_recover = false;
    bool do_crash = true;
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0) {
            verbose++;
            continue;
        }
        if (strcmp(argv[i], "-q") == 0) {
            if (verbose > 0) verbose--;
            continue;
        }
        if (strcmp(argv[i], "--test") == 0) {
            do_test = true;
            continue;
        }
        if (strcmp(argv[i], "--recover") == 0) {
            do_recover = true;
            continue;
        }
        if (strcmp(argv[i], "--crash") == 0 && i+1 < argc) {
            do_crash = atoi(argv[++i]);
            continue;
        }
    }

    uint64_t num_rows = 300000;
    size_t val_size = 1;

    if (do_test) {
        // init the env directory
        toku_os_recursive_delete(TOKU_TEST_FILENAME);
        int r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO);
        CKERR(r);
        run_test(num_rows, val_size, do_crash);
    }
    if (do_recover) {
        run_recover(num_rows, val_size);
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <taichi/taichi>
#include <set>
#include "../ir.h"

TLANG_NAMESPACE_BEGIN

class BasicBlockEliminate : public IRVisitor {
 public:
  Block *block;

  int current_stmt_id;
  std::set<int> &visited;

  BasicBlockEliminate(Block *block, std::set<int> &visited)
      : block(block), visited(visited) {
    allow_undefined_visitor = true;
    invoke_default_visitor = false;
    run();
  }

  bool is_done(Stmt *stmt) {
    return visited.find(stmt->instance_id) != visited.end();
  }

  void set_done(Stmt *stmt) {
    visited.insert(stmt->instance_id);
  }

  void run() {
    for (int i = 0; i < (int)block->statements.size(); i++) {
      current_stmt_id = i;
      block->statements[i]->accept(this);
    }
  }

  void visit(Stmt *stmt) override {
    if (stmt->is_container_statement())
      return;
    else {
      TC_ERROR("Visitor for non-container stmt undefined.");
    }
  }

  void visit(GlobalPtrStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<GlobalPtrStmt>();
          bool same = true;
          for (int l = 0; l < stmt->width(); l++) {
            if (stmt->snodes[l] != bstmt_->snodes[l]) {
              same = false;
              break;
            }
          }
          if (stmt->indices.size() != bstmt_->indices.size()) {
            same = false;
          } else {
            for (int j = 0; j < (int)stmt->indices.size(); j++) {
              if (stmt->indices[j] != bstmt_->indices[j])
                same = false;
            }
          }
          if (same) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(ConstStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      auto &bstmt_data = *bstmt;
      if (typeid(bstmt_data) == typeid(*stmt)) {
        if (stmt->width() == bstmt->width()) {
          auto bstmt_ = bstmt->as<ConstStmt>();
          bool same = true;
          for (int l = 0; l < stmt->width(); l++) {
            if (!stmt->val[l].equal_type_and_value(bstmt_->val[l])) {
              same = false;
              break;
            }
          }
          if (same) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(AllocaStmt *stmt) override {
    return;
  }

  void visit(ElementShuffleStmt *stmt) override {
    if (is_done(stmt))
      return;
    // is this stmt necessary?
    {
      bool same_source = true;
      bool inc_index = true;
      for (int l = 0; l < stmt->width(); l++) {
        if (stmt->elements[l].stmt != stmt->elements[0].stmt)
          same_source = false;
        if (stmt->elements[l].index != l)
          inc_index = false;
      }
      if (same_source && inc_index &&
          stmt->elements[0].stmt->ret_type == stmt->ret_type) {
        // useless shuffle.
        stmt->replace_with(stmt->elements[0].stmt);
        stmt->parent->erase(current_stmt_id);
        throw IRModifiedException();
      }
    }

    // find dup
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<ElementShuffleStmt>();
          bool same = true;
          for (int l = 0; l < stmt->width(); l++) {
            if (stmt->elements[l].stmt != bstmt_->elements[l].stmt ||
                stmt->elements[l].index != bstmt_->elements[l].index) {
              same = false;
              break;
            }
          }
          if (same) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(LocalLoadStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<LocalLoadStmt>();
          bool same = true;
          std::vector<Stmt *> vars;
          for (int l = 0; l < stmt->width(); l++) {
            vars.push_back(stmt->ptr[l].var);
            if (stmt->ptr[l].var != bstmt_->ptr[l].var ||
                stmt->ptr[l].offset != bstmt_->ptr[l].offset) {
              same = false;
              break;
            }
          }
          if (same) {
            // no store to the var?
            bool has_related_store = false;
            for (int j = i + 1; j < current_stmt_id; j++) {
              if (block->statements[j]
                      ->is_container_statement()) {  // no if, while, etc..
                has_related_store = true;
                break;
              }
              if (block->statements[j]->is<LocalStoreStmt>()) {
                auto st = block->statements[j]->as<LocalStoreStmt>();
                for (auto var : vars) {
                  if (st->ptr == var) {
                    has_related_store = true;
                    break;
                  }
                }
              }
            }
            if (!has_related_store) {
              stmt->replace_with(bstmt.get());
              stmt->parent->erase(current_stmt_id);
              throw IRModifiedException();
            }
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(LocalStoreStmt *stmt) override {
    return;
  }

  // Do not eliminate global data access
  void visit(GlobalLoadStmt *stmt) override {
    return;
  }

  void visit(GlobalStoreStmt *stmt) override {
    return;
  }

  void visit(SNodeOpStmt *stmt) override {
    return;
  }

  void visit(UnaryOpStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<UnaryOpStmt>();
          if (bstmt_->same_operation(stmt) && bstmt_->rhs == stmt->rhs) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(BinaryOpStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<BinaryOpStmt>();
          if (bstmt_->op_type == stmt->op_type && bstmt_->lhs == stmt->lhs &&
              bstmt_->rhs == stmt->rhs) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(TrinaryOpStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<TrinaryOpStmt>();
          if (bstmt_->op_type == stmt->op_type && bstmt_->op1 == stmt->op1 &&
              bstmt_->op2 == stmt->op2 && bstmt_->op3 == stmt->op3) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(OffsetAndExtractBitsStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<OffsetAndExtractBitsStmt>();
          if (bstmt_->input == stmt->input &&
              bstmt_->bit_begin == stmt->bit_begin &&
              bstmt_->bit_end == stmt->bit_end &&
              bstmt_->offset == stmt->offset) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  template <typename T>
  static bool identical_vectors(const std::vector<T> &a,
                                const std::vector<T> &b) {
    if (a.size() != b.size()) {
      return false;
    } else {
      for (int i = 0; i < (int)a.size(); i++) {
        if (a[i] != b[i])
          return false;
      }
    }
    return true;
  }

  void visit(LinearizeStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<LinearizeStmt>();
          if (identical_vectors(bstmt_->inputs, stmt->inputs) &&
              identical_vectors(bstmt_->strides, stmt->strides) &&
              identical_vectors(bstmt_->offsets, stmt->offsets)) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(AtomicOpStmt *stmt) override {
    return;
  }

  void visit(PrintStmt *stmt) override {
    return;
  }

  void visit(RandStmt *stmt) override {
    return;
  }

  void visit(WhileControlStmt *stmt) override {
    return;
  }

  void visit(RangeAssumptionStmt *stmt) override {
    return;
  }
};

class EliminateDup : public IRVisitor {
 public:
  EliminateDup(IRNode *node) {
    allow_undefined_visitor = true;
    invoke_default_visitor = true;
    node->accept(this);
  }

  void visit(Block *block) override {
    std::set<int> visited;
    while (true) {
      try {
        BasicBlockEliminate _(block, visited);
      } catch (IRModifiedException) {
        continue;
      }
      break;
    }
    for (auto &stmt : block->statements) {
      stmt->accept(this);
    }
  }

  void visit(IfStmt *if_stmt) override {
    if (if_stmt->true_statements)
      if_stmt->true_statements->accept(this);
    if (if_stmt->false_statements) {
      if_stmt->false_statements->accept(this);
    }
  }

  void visit(RangeForStmt *for_stmt) override {
    for_stmt->body->accept(this);
  }

  void visit(StructForStmt *for_stmt) override {
    for_stmt->body->accept(this);
  }

  void visit(WhileStmt *stmt) override {
    stmt->body->accept(this);
  }
};

namespace irpass {

void eliminate_dup(IRNode *root) {
  EliminateDup _(root);
}

}  // namespace irpass

TLANG_NAMESPACE_END
<commit_msg>eliminated dup access: 7851 inst.<commit_after>#include <taichi/taichi>
#include <set>
#include "../ir.h"

TLANG_NAMESPACE_BEGIN

class BasicBlockEliminate : public IRVisitor {
 public:
  Block *block;

  int current_stmt_id;
  std::set<int> &visited;

  BasicBlockEliminate(Block *block, std::set<int> &visited)
      : block(block), visited(visited) {
    allow_undefined_visitor = true;
    invoke_default_visitor = false;
    run();
  }

  bool is_done(Stmt *stmt) {
    return visited.find(stmt->instance_id) != visited.end();
  }

  void set_done(Stmt *stmt) {
    visited.insert(stmt->instance_id);
  }

  void run() {
    for (int i = 0; i < (int)block->statements.size(); i++) {
      current_stmt_id = i;
      block->statements[i]->accept(this);
    }
  }

  void visit(Stmt *stmt) override {
    if (stmt->is_container_statement())
      return;
    else {
      TC_ERROR("Visitor for non-container stmt undefined.");
    }
  }

  void visit(GlobalPtrStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<GlobalPtrStmt>();
          bool same = true;
          for (int l = 0; l < stmt->width(); l++) {
            if (stmt->snodes[l] != bstmt_->snodes[l]) {
              same = false;
              break;
            }
          }
          if (stmt->indices.size() != bstmt_->indices.size()) {
            same = false;
          } else {
            for (int j = 0; j < (int)stmt->indices.size(); j++) {
              if (stmt->indices[j] != bstmt_->indices[j])
                same = false;
            }
          }
          if (same) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(ConstStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      auto &bstmt_data = *bstmt;
      if (typeid(bstmt_data) == typeid(*stmt)) {
        if (stmt->width() == bstmt->width()) {
          auto bstmt_ = bstmt->as<ConstStmt>();
          bool same = true;
          for (int l = 0; l < stmt->width(); l++) {
            if (!stmt->val[l].equal_type_and_value(bstmt_->val[l])) {
              same = false;
              break;
            }
          }
          if (same) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(AllocaStmt *stmt) override {
    return;
  }

  void visit(ElementShuffleStmt *stmt) override {
    if (is_done(stmt))
      return;
    // is this stmt necessary?
    {
      bool same_source = true;
      bool inc_index = true;
      for (int l = 0; l < stmt->width(); l++) {
        if (stmt->elements[l].stmt != stmt->elements[0].stmt)
          same_source = false;
        if (stmt->elements[l].index != l)
          inc_index = false;
      }
      if (same_source && inc_index &&
          stmt->elements[0].stmt->ret_type == stmt->ret_type) {
        // useless shuffle.
        stmt->replace_with(stmt->elements[0].stmt);
        stmt->parent->erase(current_stmt_id);
        throw IRModifiedException();
      }
    }

    // find dup
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<ElementShuffleStmt>();
          bool same = true;
          for (int l = 0; l < stmt->width(); l++) {
            if (stmt->elements[l].stmt != bstmt_->elements[l].stmt ||
                stmt->elements[l].index != bstmt_->elements[l].index) {
              same = false;
              break;
            }
          }
          if (same) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(LocalLoadStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<LocalLoadStmt>();
          bool same = true;
          std::vector<Stmt *> vars;
          for (int l = 0; l < stmt->width(); l++) {
            vars.push_back(stmt->ptr[l].var);
            if (stmt->ptr[l].var != bstmt_->ptr[l].var ||
                stmt->ptr[l].offset != bstmt_->ptr[l].offset) {
              same = false;
              break;
            }
          }
          if (same) {
            // no store to the var?
            bool has_related_store = false;
            for (int j = i + 1; j < current_stmt_id; j++) {
              if (block->statements[j]
                      ->is_container_statement()) {  // no if, while, etc..
                has_related_store = true;
                break;
              }
              if (block->statements[j]->is<LocalStoreStmt>()) {
                auto st = block->statements[j]->as<LocalStoreStmt>();
                for (auto var : vars) {
                  if (st->ptr == var) {
                    has_related_store = true;
                    break;
                  }
                }
              }
            }
            if (!has_related_store) {
              stmt->replace_with(bstmt.get());
              stmt->parent->erase(current_stmt_id);
              throw IRModifiedException();
            }
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(LocalStoreStmt *stmt) override {
    return;
  }

  // Do not eliminate global data access
  void visit(GlobalLoadStmt *stmt) override {
    return;
  }

  void visit(GlobalStoreStmt *stmt) override {
    return;
  }

  void visit(SNodeOpStmt *stmt) override {
    return;
  }

  void visit(UnaryOpStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<UnaryOpStmt>();
          if (bstmt_->same_operation(stmt) && bstmt_->rhs == stmt->rhs) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(BinaryOpStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<BinaryOpStmt>();
          if (bstmt_->op_type == stmt->op_type && bstmt_->lhs == stmt->lhs &&
              bstmt_->rhs == stmt->rhs) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(TrinaryOpStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<TrinaryOpStmt>();
          if (bstmt_->op_type == stmt->op_type && bstmt_->op1 == stmt->op1 &&
              bstmt_->op2 == stmt->op2 && bstmt_->op3 == stmt->op3) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(OffsetAndExtractBitsStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<OffsetAndExtractBitsStmt>();
          if (bstmt_->input == stmt->input &&
              bstmt_->bit_begin == stmt->bit_begin &&
              bstmt_->bit_end == stmt->bit_end &&
              bstmt_->offset == stmt->offset) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  template <typename T>
  static bool identical_vectors(const std::vector<T> &a,
                                const std::vector<T> &b) {
    if (a.size() != b.size()) {
      return false;
    } else {
      for (int i = 0; i < (int)a.size(); i++) {
        if (a[i] != b[i])
          return false;
      }
    }
    return true;
  }

  void visit(LinearizeStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<LinearizeStmt>();
          if (identical_vectors(bstmt_->inputs, stmt->inputs) &&
              identical_vectors(bstmt_->strides, stmt->strides) &&
              identical_vectors(bstmt_->offsets, stmt->offsets)) {
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(SNodeLookupStmt *stmt) override {
    if (is_done(stmt))
      return;
    for (int i = 0; i < current_stmt_id; i++) {
      auto &bstmt = block->statements[i];
      if (stmt->ret_type == bstmt->ret_type) {
        auto &bstmt_data = *bstmt;
        if (typeid(bstmt_data) == typeid(*stmt)) {
          auto bstmt_ = bstmt->as<SNodeLookupStmt>();
          if (bstmt_->snode == stmt->snode &&
              bstmt_->input_snode == stmt->input_snode &&
              bstmt_->input_index == stmt->input_index &&
              bstmt_->chid == stmt->chid &&
              identical_vectors(bstmt_->global_indices, stmt->global_indices) &&
              bstmt_->activate == stmt->activate) {
            TC_INFO("eliminated");
            stmt->replace_with(bstmt.get());
            stmt->parent->erase(current_stmt_id);
            throw IRModifiedException();
          }
        }
      }
    }
    set_done(stmt);
  }

  void visit(AtomicOpStmt *stmt) override {
    return;
  }

  void visit(PrintStmt *stmt) override {
    return;
  }

  void visit(RandStmt *stmt) override {
    return;
  }

  void visit(WhileControlStmt *stmt) override {
    return;
  }

  void visit(RangeAssumptionStmt *stmt) override {
    return;
  }
};

class EliminateDup : public IRVisitor {
 public:
  EliminateDup(IRNode *node) {
    allow_undefined_visitor = true;
    invoke_default_visitor = true;
    node->accept(this);
  }

  void visit(Block *block) override {
    std::set<int> visited;
    while (true) {
      try {
        BasicBlockEliminate _(block, visited);
      } catch (IRModifiedException) {
        continue;
      }
      break;
    }
    for (auto &stmt : block->statements) {
      stmt->accept(this);
    }
  }

  void visit(IfStmt *if_stmt) override {
    if (if_stmt->true_statements)
      if_stmt->true_statements->accept(this);
    if (if_stmt->false_statements) {
      if_stmt->false_statements->accept(this);
    }
  }

  void visit(RangeForStmt *for_stmt) override {
    for_stmt->body->accept(this);
  }

  void visit(StructForStmt *for_stmt) override {
    for_stmt->body->accept(this);
  }

  void visit(WhileStmt *stmt) override {
    stmt->body->accept(this);
  }
};

namespace irpass {

void eliminate_dup(IRNode *root) {
  EliminateDup _(root);
}

}  // namespace irpass

TLANG_NAMESPACE_END
<|endoftext|>


<commit_before>#include "SlugsPadCameraControl.h"
#include "ui_SlugsPadCameraControl.h"
#include <QMouseEvent>
#include <QDebug>
#include <qmath.h>
#include <QPainter>

SlugsPadCameraControl::SlugsPadCameraControl(QWidget *parent) :
   QWidget(parent), //QGraphicsView(parent),
    ui(new Ui::SlugsPadCameraControl),
     dragging(0)
{
    ui->setupUi(this);
    x1= 0;
    y1 = 0;
    bearingPad = 0;
    distancePad = 0;
    directionPad = "no";

}

SlugsPadCameraControl::~SlugsPadCameraControl()
{
    delete ui;
}

void SlugsPadCameraControl::mouseMoveEvent(QMouseEvent *event)
{
    //emit mouseMoveCoord(event->x(),event->y());
    if(dragging)
    {
        if(abs(x1-event->x())>20 || abs(y1-event->y())>20)
        {

            getDeltaPositionPad(event->x(), event->y());
            x1 = event->x();
            y1 = event->y();
        }
    }

}

void SlugsPadCameraControl::mousePressEvent(QMouseEvent *event)
{
    //emit mousePressCoord(event->x(),event->y());
    dragging = true;
    x1 = event->x();
    y1 = event->y();

}

void SlugsPadCameraControl::mouseReleaseEvent(QMouseEvent *event)
{
     dragging = false;
    //emit mouseReleaseCoord(event->x(),event->y());
    //getDeltaPositionPad(event->x(), event->y());

     xFin = event->x();
     yFin = event->y();

}

void SlugsPadCameraControl::paintEvent(QPaintEvent *pe)
{
    Q_UNUSED(pe);
    QPainter painter(this);
    painter.setPen(Qt::blue);
    painter.setFont(QFont("Arial", 30));

//    QRectF rectangle(tL.x(), tL.y(), ui->padCamContro_frame->width(), ui->padCamContro_frame->height());
//     int startAngle = 30 * 16;
//     int spanAngle = 120 * 16;

    painter.drawLine(QPoint(ui->frame->width()/2,ui->frame->geometry().topLeft().y()),
                     QPoint(ui->frame->width()/2,ui->frame->geometry().bottomRight().y()));

    painter.drawLine(QPoint(ui->frame->geometry().topLeft().x(),ui->frame->height()/2),
                     QPoint(ui->frame->geometry().bottomRight().x(),ui->frame->height()/2));

    painter.setPen(Qt::white);

    //QPointF coordTemp = getPointBy_BearingDistance(ui->frame->width()/2,ui->frame->height()/2,bearingPad,distancePad);

    painter.drawLine(QPoint(ui->frame->width()/2,ui->frame->height()/2),
                     QPoint(xFin,yFin));

   // painter.drawLine(QPoint());
    //painter.drawLines(padLines);

    // painter.drawPie(rectangle, startAngle, spanAngle);

    //painter.drawText(rect(), Qt::AlignCenter, "Qt");
}

void SlugsPadCameraControl::getDeltaPositionPad(int x2, int y2)
{

    QString dir = "nd";
    QPointF localMeasures = ObtenerMarcacionDistanciaPixel(y1,x1,y2,x2);

    double bearing = localMeasures.x();
    double dist = getDistPixel(y1,x1,y2,x2);

    if(((bearing > 330)&&(bearing < 360)) || ((bearing >= 0)&&(bearing <= 30)))
    {
         emit dirCursorText("up");
        //bearing = 315;
        dir = "up";
    }
    else
    {
        if((bearing > 30)&&(bearing <= 60) )
        {
            emit dirCursorText("right up");
            //bearing = 315;
            dir = "right up";
        }
        else
        {
            if((bearing > 60)&&(bearing <= 105) )
            {
               emit dirCursorText("right");
                //bearing = 315;
                dir = "right";
            }
            else
            {
                if((bearing > 105)&&(bearing <= 150) )
                {
                   emit dirCursorText("right down");
                    //bearing = 315;
                    dir = "right down";
                }
                else
                {
                    if((bearing > 150)&&(bearing <= 195) )
                    {
                       emit dirCursorText("down");
                        //bearing = 315;
                        dir = "down";
                    }
                    else
                    {
                        if((bearing > 195)&&(bearing <= 240) )
                        {
                            emit dirCursorText("left down");
                            //bearing = 315;
                            dir = "left down";
                        }
                        else
                        {
                            if((bearing > 240)&&(bearing <= 300) )
                            {
                               emit dirCursorText("left");
                                //bearing = 315;
                                dir = "left";
                            }
                            else
                            {
                                if((bearing > 300)&&(bearing <= 330) )
                                {
                                    emit dirCursorText("left up");
                                    //bearing = 315;
                                    dir = "left up";
                                }

                            }

                        }

                    }

                }

            }

        }

    }

    bearingPad = bearing;
    distancePad = dist;
    directionPad = dir;
    emit changeCursorPosition(bearing, dist, dir);

    update();

}

double SlugsPadCameraControl::getDistPixel(int x1, int y1, int x2, int y2)
{
    double cateto_opuesto,cateto_adyacente;
     //latitud y longitud del primer punto

    cateto_opuesto = abs((x1-x2)); //diferencia de latitudes entre PCR1 y PCR2
    cateto_adyacente = abs((y1-y2));//diferencia de longitudes entre PCR1 y PCR2

    return  sqrt(pow(cateto_opuesto,2) + pow(cateto_adyacente,2));

      // distancia = (float) hipotenusa;
}

/**
                * Esta funcin xxxxxxxxx
                * @param double lat1 -->
                * @param double lon1 -->
                * @param double lat2 -->
                * @param double lon2 -->
                * @param ref double rumbo -->
                * @param ref double distancia -->
                */
QPointF SlugsPadCameraControl::ObtenerMarcacionDistanciaPixel(double lon1, double lat1, double lon2, double lat2)
{
    double cateto_opuesto,cateto_adyacente, hipotenusa, distancia, marcacion;

    //latitude and longitude first point

    if(lat1<0) lat1= lat1*(-1);
    if(lat2<0) lat2= lat2*(-1);
    if(lon1<0) lon1= lon1*(-1);
    if(lon2<0) lon1= lon1*(-1);

    cateto_opuesto = abs((lat1-lat2));
    cateto_adyacente = abs((lon1-lon2));

    hipotenusa = sqrt(pow(cateto_opuesto,2) + pow(cateto_adyacente,2));
    distancia = hipotenusa*60;

    if ((lat1 < lat2) && (lon1 > lon2)) //primer cuadrante
        marcacion = 360 -((asin(cateto_adyacente/hipotenusa))/ 0.017453292);
    else if ((lat1 < lat2) && (lon1 < lon2)) //segundo cuadrante
        marcacion = (asin(cateto_adyacente/hipotenusa))/ 0.017453292;
    else if((lat1 > lat2) && (lon1 < lon2)) //tercer cuadrante
        marcacion = 180 -((asin(cateto_adyacente/hipotenusa))/ 0.017453292);
    else if((lat1 > lat2) && (lon1 > lon2)) //cuarto cuadrante
        marcacion = 180 +((asin(cateto_adyacente/hipotenusa))/ 0.017453292);
    else if((lat1 < lat2) && (lon1 == lon2)) //360
        marcacion = 360;
    else if((lat1 == lat2) && (lon1 > lon2)) //270
        marcacion = 270;
    else if((lat1 > lat2) && (lon1 == lon2)) //180
        marcacion = 180;
    else if((lat1 == lat2) && (lon1 < lon2)) //90
        marcacion =90;
    else if((lat1 == lat2) && (lon1 == lon2)) //0
        marcacion = 0.0;

    // this only convert real bearing to frame widget bearing
    marcacion = marcacion +90;
    if(marcacion>= 360) marcacion = marcacion - 360;

    return QPointF(marcacion,distancia);

}

QPointF SlugsPadCameraControl::getPointBy_BearingDistance(double lat1, double lon1, double rumbo, double distancia)
{
    double lon2 = 0;
    double lat2 = 0;
    double rad= M_PI/180;

    rumbo = rumbo*rad;
    lon2=(lon1 + ((distancia/60) * (sin(rumbo))));
    lat2=(lat1 + ((distancia/60) * (cos(rumbo))));

    return QPointF(lon2,lat2);
}

<commit_msg>clean code<commit_after>#include "SlugsPadCameraControl.h"
#include "ui_SlugsPadCameraControl.h"
#include <QMouseEvent>
#include <QDebug>
#include <qmath.h>
#include <QPainter>

SlugsPadCameraControl::SlugsPadCameraControl(QWidget *parent) :
   QWidget(parent), //QGraphicsView(parent),
    ui(new Ui::SlugsPadCameraControl),
     dragging(0)
{
    ui->setupUi(this);
    x1= 0;
    y1 = 0;
    bearingPad = 0;
    distancePad = 0;
    directionPad = "no";

}

SlugsPadCameraControl::~SlugsPadCameraControl()
{
    delete ui;
}

void SlugsPadCameraControl::mouseMoveEvent(QMouseEvent *event)
{
    //emit mouseMoveCoord(event->x(),event->y());
    if(dragging)
    {

      // getDeltaPositionPad(event->x(), event->y());

    }

}

void SlugsPadCameraControl::mousePressEvent(QMouseEvent *event)
{
    //emit mousePressCoord(event->x(),event->y());
    dragging = true;
    x1 = event->x();
    y1 = event->y();

}

void SlugsPadCameraControl::mouseReleaseEvent(QMouseEvent *event)
{
     dragging = false;
    //emit mouseReleaseCoord(event->x(),event->y());
    getDeltaPositionPad(event->x(), event->y());

     xFin = event->x();
     yFin = event->y();

}

void SlugsPadCameraControl::paintEvent(QPaintEvent *pe)
{
    Q_UNUSED(pe);
    QPainter painter(this);
    painter.setPen(Qt::blue);
    painter.setFont(QFont("Arial", 30));

//    QRectF rectangle(tL.x(), tL.y(), ui->padCamContro_frame->width(), ui->padCamContro_frame->height());
//     int startAngle = 30 * 16;
//     int spanAngle = 120 * 16;

    painter.drawLine(QPoint(ui->frame->width()/2,ui->frame->geometry().topLeft().y()),
                     QPoint(ui->frame->width()/2,ui->frame->geometry().bottomRight().y()));

    painter.drawLine(QPoint(ui->frame->geometry().topLeft().x(),ui->frame->height()/2),
                     QPoint(ui->frame->geometry().bottomRight().x(),ui->frame->height()/2));

    painter.setPen(Qt::white);

    //QPointF coordTemp = getPointBy_BearingDistance(ui->frame->width()/2,ui->frame->height()/2,bearingPad,distancePad);

    painter.drawLine(QPoint(ui->frame->width()/2,ui->frame->height()/2),
                     QPoint(xFin,yFin));

   // painter.drawLine(QPoint());
    //painter.drawLines(padLines);

    // painter.drawPie(rectangle, startAngle, spanAngle);

    //painter.drawText(rect(), Qt::AlignCenter, "Qt");
}

void SlugsPadCameraControl::getDeltaPositionPad(int x2, int y2)
{

    QString dir = "nd";
    QPointF localMeasures = ObtenerMarcacionDistanciaPixel(y1,x1,y2,x2);

    double bearing = localMeasures.x();
    double dist = getDistPixel(y1,x1,y2,x2);

    // this only convert real bearing to frame widget bearing
    bearing = bearing +90;
    if(bearing>= 360) bearing = bearing - 360;

    if(((bearing > 330)&&(bearing < 360)) || ((bearing >= 0)&&(bearing <= 30)))
    {
         emit dirCursorText("up");
        //bearing = 315;
        dir = "up";
    }
    else
    {
        if((bearing > 30)&&(bearing <= 60) )
        {
            emit dirCursorText("right up");
            //bearing = 315;
            dir = "right up";
        }
        else
        {
            if((bearing > 60)&&(bearing <= 105) )
            {
               emit dirCursorText("right");
                //bearing = 315;
                dir = "right";
            }
            else
            {
                if((bearing > 105)&&(bearing <= 150) )
                {
                   emit dirCursorText("right down");
                    //bearing = 315;
                    dir = "right down";
                }
                else
                {
                    if((bearing > 150)&&(bearing <= 195) )
                    {
                       emit dirCursorText("down");
                        //bearing = 315;
                        dir = "down";
                    }
                    else
                    {
                        if((bearing > 195)&&(bearing <= 240) )
                        {
                            emit dirCursorText("left down");
                            //bearing = 315;
                            dir = "left down";
                        }
                        else
                        {
                            if((bearing > 240)&&(bearing <= 300) )
                            {
                               emit dirCursorText("left");
                                //bearing = 315;
                                dir = "left";
                            }
                            else
                            {
                                if((bearing > 300)&&(bearing <= 330) )
                                {
                                    emit dirCursorText("left up");
                                    //bearing = 315;
                                    dir = "left up";
                                }

                            }

                        }

                    }

                }

            }

        }

    }

    bearingPad = bearing;
    distancePad = dist;
    directionPad = dir;
    emit changeCursorPosition(bearing, dist, dir);

    update();

}

double SlugsPadCameraControl::getDistPixel(int x1, int y1, int x2, int y2)
{
    double cateto_opuesto,cateto_adyacente;
     //latitud y longitud del primer punto

    cateto_opuesto = abs((x1-x2)); //diferencia de latitudes entre PCR1 y PCR2
    cateto_adyacente = abs((y1-y2));//diferencia de longitudes entre PCR1 y PCR2

    return  sqrt(pow(cateto_opuesto,2) + pow(cateto_adyacente,2));

      // distancia = (float) hipotenusa;
}

QPointF SlugsPadCameraControl::ObtenerMarcacionDistanciaPixel(double lon1, double lat1,
                                                              double lon2, double lat2)
{
    double cateto_opuesto,cateto_adyacente, hipotenusa, distancia, marcacion;

    //latitude and longitude first point

    if(lat1<0) lat1= lat1*(-1);
    if(lat2<0) lat2= lat2*(-1);
    if(lon1<0) lon1= lon1*(-1);
    if(lon2<0) lon1= lon1*(-1);

    cateto_opuesto = abs((lat1-lat2));
    cateto_adyacente = abs((lon1-lon2));

    hipotenusa = sqrt(pow(cateto_opuesto,2) + pow(cateto_adyacente,2));
    distancia = hipotenusa*60;

    if ((lat1 < lat2) && (lon1 > lon2)) //primer cuadrante
        marcacion = 360 -((asin(cateto_adyacente/hipotenusa))/ 0.017453292);
    else if ((lat1 < lat2) && (lon1 < lon2)) //segundo cuadrante
        marcacion = (asin(cateto_adyacente/hipotenusa))/ 0.017453292;
    else if((lat1 > lat2) && (lon1 < lon2)) //tercer cuadrante
        marcacion = 180 -((asin(cateto_adyacente/hipotenusa))/ 0.017453292);
    else if((lat1 > lat2) && (lon1 > lon2)) //cuarto cuadrante
        marcacion = 180 +((asin(cateto_adyacente/hipotenusa))/ 0.017453292);
    else if((lat1 < lat2) && (lon1 == lon2)) //360
        marcacion = 360;
    else if((lat1 == lat2) && (lon1 > lon2)) //270
        marcacion = 270;
    else if((lat1 > lat2) && (lon1 == lon2)) //180
        marcacion = 180;
    else if((lat1 == lat2) && (lon1 < lon2)) //90
        marcacion =90;
    else if((lat1 == lat2) && (lon1 == lon2)) //0
        marcacion = 0.0;

    return QPointF(marcacion,distancia);

}

QPointF SlugsPadCameraControl::getPointBy_BearingDistance(double lat1, double lon1, double rumbo, double distancia)
{
    double lon2 = 0;
    double lat2 = 0;
    double rad= M_PI/180;

    rumbo = rumbo*rad;
    lon2=(lon1 + ((distancia/60) * (sin(rumbo))));
    lat2=(lat1 + ((distancia/60) * (cos(rumbo))));

    return QPointF(lon2,lat2);
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#elif _WIN32
#include <GL/glew.h>
#else
#include <GL/glew.h>
#include <GL/gl.h>
#endif

#include "glsl.h"

#include <sstream>
#include <iostream>

// TODO: Lot of other GLSL helper methods from synColor will be added here.

namespace
{
    void CheckStatus()
    {
        const GLenum glErr = glGetError();
        if(glErr!=GL_NO_ERROR)
        {
#ifdef __APPLE__
            // TODO: Improve the error message
            throw OCIO::Exception("OpenGL Error");
#else
            throw OCIO::Exception((const char*)gluErrorString(glErr));
#endif
        }
    }

    void SetTextureParameters(GLenum textureType, OCIO::Interpolation interpolation)
    {
        if(interpolation==OCIO::INTERP_NEAREST)
        {
            glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        }
        else
        {
            glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        }

        glTexParameteri(textureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(textureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(textureType, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    }

    void AllocateTexture3D(unsigned index, unsigned & texId,
                           OCIO::Interpolation interpolation,
                           unsigned edgelen, const float * values)
    {
        if(values==0x0)
        {
            throw OCIO::Exception("Missing texture data");
        }

        glGenTextures(1, &texId);

        glActiveTexture(GL_TEXTURE0 + index);

        glBindTexture(GL_TEXTURE_3D, texId);

        SetTextureParameters(GL_TEXTURE_3D, interpolation);

        glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F_ARB,
                     edgelen, edgelen, edgelen, 0, GL_RGB, GL_FLOAT, values);
    }

    void AllocateTexture2D(unsigned index, unsigned & texId, unsigned width, unsigned height,
                           OCIO::Interpolation interpolation, const float * values)
    {
        if(values==0x0)
        {
            throw OCIO::Exception("Missing texture data");
        }

        glGenTextures(1, &texId);

        glActiveTexture(GL_TEXTURE0 + index);

        if(height>1)
        {
            glBindTexture(GL_TEXTURE_2D, texId);

            SetTextureParameters(GL_TEXTURE_2D, interpolation);

            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F_ARB, width, height, 0, GL_RGB, GL_FLOAT, values);
        }
        else
        {
            glBindTexture(GL_TEXTURE_1D, texId);

            SetTextureParameters(GL_TEXTURE_1D, interpolation);

            glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB32F_ARB, width, 0, GL_RGB, GL_FLOAT, values);
        }
    }

    GLuint CompileShaderText(GLenum shaderType, const char * text)
    {
        CheckStatus();

        if(!text || !*text)
        {
            throw OCIO::Exception("Invalid fragment shader program");
        }

        GLuint shader;
        GLint stat;

        shader = glCreateShader(shaderType);
        glShaderSource(shader, 1, (const GLchar **) &text, NULL);
        glCompileShader(shader);
        glGetShaderiv(shader, GL_COMPILE_STATUS, &stat);

        if (!stat)
        {
            GLchar log[1000];
            GLsizei len;
            glGetShaderInfoLog(shader, 1000, &len, log);

            std::string err("OCIO Shader program compilation failed: ");
            err += log;
            err += "\n";
            err += text;

            throw OCIO::Exception(err.c_str());
        }

        return shader;
    }

    void LinkShaders(GLuint program, GLuint fragShader)
    {
        CheckStatus();

        if (!fragShader)
        {
            throw OCIO::Exception("Missing shader program");
        }
        else
        {
            glAttachShader(program, fragShader);
        }

        glLinkProgram(program);

        GLint stat;
        glGetProgramiv(program, GL_LINK_STATUS, &stat);
        if (!stat)
        {
            GLchar log[1000];
            GLsizei len;
            glGetProgramInfoLog(program, 1000, &len, log);

            std::string err("Shader link error:\n");
            err += log;
            throw OCIO::Exception(err.c_str());
        }
    }
}

OpenGLBuilderRcPtr OpenGLBuilder::Create(const OCIO::GpuShaderDescRcPtr & shaderDesc)
{
    return OpenGLBuilderRcPtr(new OpenGLBuilder(shaderDesc));
}

OpenGLBuilder::OpenGLBuilder(const OCIO::GpuShaderDescRcPtr & shaderDesc)
    :   m_shaderDesc(shaderDesc)
    ,   m_startIndex(0)
    ,   m_fragShader(0)
    ,   m_program(glCreateProgram())
    ,   m_verbose(false)
{
}

OpenGLBuilder::~OpenGLBuilder()
{
    deleteAllTextures();

    if(m_fragShader)
    {
        glDetachShader(m_program, m_fragShader);
        glDeleteShader(m_fragShader);
        m_fragShader = 0;
    }

    if(m_program)
    {
        glDeleteProgram(m_program);
        m_program = 0;
    }
}

void OpenGLBuilder::allocateAllTextures(unsigned startIndex)
{
    deleteAllTextures();

    // This is the first available index for the textures
    m_startIndex = startIndex;
    unsigned currIndex = m_startIndex;

    // Process the 3D LUT first

    const unsigned maxTexture3D = m_shaderDesc->getNum3DTextures();
    for(unsigned idx=0; idx<maxTexture3D; ++idx)
    {
        // 1. Get the information of the 3D LUT

        const char* name = 0x0;
        const char* uid  = 0x0;
        unsigned edgelen = 0;
        OCIO::Interpolation interpolation = OCIO::INTERP_LINEAR;
        m_shaderDesc->get3DTexture(idx, name, uid, edgelen, interpolation);

        if(!name || !*name || !uid || !*uid || edgelen==0)
        {
            throw OCIO::Exception("The texture data are corrupted");
        }

        const float* values = 0x0;
        m_shaderDesc->get3DTextureValues(idx, values);
        if(!values)
        {
            throw OCIO::Exception("The texture values are missing");
        }

        // 2. Allocate the 3D LUT

        unsigned texId = 0;
        AllocateTexture3D(currIndex, texId, interpolation, edgelen, values);

        // 3. Keep the texture id & name for the later enabling

        m_textureIds.push_back(TextureId(texId, name, GL_TEXTURE_3D));

        currIndex++;
    }

    // Process the 1D LUTs

    const unsigned maxTexture2D = m_shaderDesc->getNumTextures();
    for(unsigned idx=0; idx<maxTexture2D; ++idx)
    {
        // 1. Get the information of the 1D LUT

        const char* name = 0x0;
        const char* uid  = 0x0;
        unsigned width = 0;
        unsigned height = 0;
        OCIO::GpuShaderDesc::TextureType channel = OCIO::GpuShaderDesc::TEXTURE_RGB_CHANNEL;
        OCIO::Interpolation interpolation = OCIO::INTERP_LINEAR;
        m_shaderDesc->getTexture(idx, name, uid, width, height, channel, interpolation);

        if(!name || !*name || !uid || !*uid || width==0)
        {
            throw OCIO::Exception("The texture data are corrupted");
        }

        const float * values = 0x0;
        m_shaderDesc->getTextureValues(idx, values);
        if(!values)
        {
            throw OCIO::Exception("The texture values are missing");
        }

        // 2. Allocate the 1D LUT (a 2D texture is needed to hold large LUTs)

        unsigned texId = 0;
        AllocateTexture2D(currIndex, texId, width, height, interpolation, values);

        // 3. Keep the texture id & name for the later enabling

        unsigned type = (height > 1) ? GL_TEXTURE_2D : GL_TEXTURE_1D;
        m_textureIds.push_back(TextureId(texId, name, type));
        currIndex++;
    }
}

void OpenGLBuilder::deleteAllTextures()
{
    const size_t max = m_textureIds.size();
    for(size_t idx=0; idx<max; ++idx)
    {
        const TextureId& data = m_textureIds[idx];
        glDeleteTextures(1, &data.id);
    }

    m_textureIds.clear();
}

void OpenGLBuilder::useAllTextures()
{
    const size_t max = m_textureIds.size();
    for(size_t idx=0; idx<max; ++idx)
    {
        const TextureId& data = m_textureIds[idx];
        glActiveTexture(GL_TEXTURE0 + m_startIndex + idx);
        glBindTexture(data.type, data.id);
        glUniform1i(
            glGetUniformLocation(m_program,
                                 data.name.c_str()),
                                 GLint(m_startIndex + idx) );
    }
}

unsigned OpenGLBuilder::buildProgram(const std::string & clientShaderProgram)
{
    const std::string shaderCacheID = m_shaderDesc->getCacheID();
    if(shaderCacheID!=m_shaderCacheID)
    {
        if(m_fragShader)
        {
            glDetachShader(m_program, m_fragShader);
            glDeleteShader(m_fragShader);
        }

        std::ostringstream os;
        os  << m_shaderDesc->getShaderText() << std::endl
            << clientShaderProgram << std::endl;

        if(m_verbose)
        {
            std::cout << std::endl;
            std::cout << "GPU Shader Program:" << std::endl;
            std::cout << std::endl;
            std::cout << os.str() << std::endl;
            std::cout << std::endl;
        }

        m_fragShader = CompileShaderText(GL_FRAGMENT_SHADER, os.str().c_str());

        LinkShaders(m_program, m_fragShader);

        m_shaderCacheID = shaderCacheID;
    }

    return m_program;
}

void OpenGLBuilder::useProgram()
{
    glUseProgram(m_program);
}

unsigned OpenGLBuilder::getProgramHandle()
{
    return m_program;
}

unsigned OpenGLBuilder::GetTextureMaxWidth()
{
    // Arbitrary huge number only to find the limit
    static unsigned maxTextureSize = 256 * 1024;

    CheckStatus();

    unsigned w = maxTextureSize;
    unsigned h = 1;

    while(w>1)
    {
        glTexImage2D(GL_PROXY_TEXTURE_2D, 0,
                     GL_RGB32F_ARB,
                     w, h, 0,
                     GL_RGB, GL_FLOAT, NULL);

        bool texValid = true;
        GLenum glErr = GL_NO_ERROR;

        while((glErr=glGetError()) != GL_NO_ERROR)
        {
            if(glErr==GL_INVALID_VALUE)
            {
                texValid = false;
            }
        }

#ifndef __APPLE__
        //
        // In case of Linux, if glTexImage2D() succeed
        //  glGetTexLevelParameteriv() could fail.
        //
        // In case of OSX, glTexImage2D() will provide the right result,
        //  and glGetTexLevelParameteriv() always fails.
        //  So do not try glGetTexLevelParameteriv().
        //
        if(texValid)
        {
            GLint format = 0;
            glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0,
                                     GL_TEXTURE_COMPONENTS, &format);

            texValid = texValid && (GL_RGB32F_ARB==format);

            while((glErr=glGetError()) != GL_NO_ERROR);
        }
#endif

        if(texValid) break;

        w = w >> 1;
        h = h << 1;
    }

    if(w==1)
    {
        throw OCIO::Exception("Maximum texture size unknown");
    }

    CheckStatus();

    return w;
}

<commit_msg>Adsk Contrib - Fix a compilation warning (#645)<commit_after>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#elif _WIN32
#include <GL/glew.h>
#else
#include <GL/glew.h>
#include <GL/gl.h>
#endif

#include "glsl.h"

#include <sstream>
#include <iostream>

namespace
{
    void CheckStatus()
    {
        const GLenum glErr = glGetError();
        if(glErr!=GL_NO_ERROR)
        {
#ifdef __APPLE__
            // TODO: Improve the error message
            throw OCIO::Exception("OpenGL Error");
#else
            throw OCIO::Exception((const char*)gluErrorString(glErr));
#endif
        }
    }

    void SetTextureParameters(GLenum textureType, OCIO::Interpolation interpolation)
    {
        if(interpolation==OCIO::INTERP_NEAREST)
        {
            glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        }
        else
        {
            glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        }

        glTexParameteri(textureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(textureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(textureType, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    }

    void AllocateTexture3D(unsigned index, unsigned & texId,
                           OCIO::Interpolation interpolation,
                           unsigned edgelen, const float * values)
    {
        if(values==0x0)
        {
            throw OCIO::Exception("Missing texture data");
        }

        glGenTextures(1, &texId);

        glActiveTexture(GL_TEXTURE0 + index);

        glBindTexture(GL_TEXTURE_3D, texId);

        SetTextureParameters(GL_TEXTURE_3D, interpolation);

        glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB32F_ARB,
                     edgelen, edgelen, edgelen, 0, GL_RGB, GL_FLOAT, values);
    }

    void AllocateTexture2D(unsigned index, unsigned & texId, unsigned width, unsigned height,
                           OCIO::Interpolation interpolation, const float * values)
    {
        if(values==0x0)
        {
            throw OCIO::Exception("Missing texture data");
        }

        glGenTextures(1, &texId);

        glActiveTexture(GL_TEXTURE0 + index);

        if(height>1)
        {
            glBindTexture(GL_TEXTURE_2D, texId);

            SetTextureParameters(GL_TEXTURE_2D, interpolation);

            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F_ARB, width, height, 0, GL_RGB, GL_FLOAT, values);
        }
        else
        {
            glBindTexture(GL_TEXTURE_1D, texId);

            SetTextureParameters(GL_TEXTURE_1D, interpolation);

            glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB32F_ARB, width, 0, GL_RGB, GL_FLOAT, values);
        }
    }

    GLuint CompileShaderText(GLenum shaderType, const char * text)
    {
        CheckStatus();

        if(!text || !*text)
        {
            throw OCIO::Exception("Invalid fragment shader program");
        }

        GLuint shader;
        GLint stat;

        shader = glCreateShader(shaderType);
        glShaderSource(shader, 1, (const GLchar **) &text, NULL);
        glCompileShader(shader);
        glGetShaderiv(shader, GL_COMPILE_STATUS, &stat);

        if (!stat)
        {
            GLchar log[1000];
            GLsizei len;
            glGetShaderInfoLog(shader, 1000, &len, log);

            std::string err("OCIO Shader program compilation failed: ");
            err += log;
            err += "\n";
            err += text;

            throw OCIO::Exception(err.c_str());
        }

        return shader;
    }

    void LinkShaders(GLuint program, GLuint fragShader)
    {
        CheckStatus();

        if (!fragShader)
        {
            throw OCIO::Exception("Missing shader program");
        }
        else
        {
            glAttachShader(program, fragShader);
        }

        glLinkProgram(program);

        GLint stat;
        glGetProgramiv(program, GL_LINK_STATUS, &stat);
        if (!stat)
        {
            GLchar log[1000];
            GLsizei len;
            glGetProgramInfoLog(program, 1000, &len, log);

            std::string err("Shader link error:\n");
            err += log;
            throw OCIO::Exception(err.c_str());
        }
    }
}

OpenGLBuilderRcPtr OpenGLBuilder::Create(const OCIO::GpuShaderDescRcPtr & shaderDesc)
{
    return OpenGLBuilderRcPtr(new OpenGLBuilder(shaderDesc));
}

OpenGLBuilder::OpenGLBuilder(const OCIO::GpuShaderDescRcPtr & shaderDesc)
    :   m_shaderDesc(shaderDesc)
    ,   m_startIndex(0)
    ,   m_fragShader(0)
    ,   m_program(glCreateProgram())
    ,   m_verbose(false)
{
}

OpenGLBuilder::~OpenGLBuilder()
{
    deleteAllTextures();

    if(m_fragShader)
    {
        glDetachShader(m_program, m_fragShader);
        glDeleteShader(m_fragShader);
        m_fragShader = 0;
    }

    if(m_program)
    {
        glDeleteProgram(m_program);
        m_program = 0;
    }
}

void OpenGLBuilder::allocateAllTextures(unsigned startIndex)
{
    deleteAllTextures();

    // This is the first available index for the textures
    m_startIndex = startIndex;
    unsigned currIndex = m_startIndex;

    // Process the 3D LUT first

    const unsigned maxTexture3D = m_shaderDesc->getNum3DTextures();
    for(unsigned idx=0; idx<maxTexture3D; ++idx)
    {
        // 1. Get the information of the 3D LUT

        const char* name = 0x0;
        const char* uid  = 0x0;
        unsigned edgelen = 0;
        OCIO::Interpolation interpolation = OCIO::INTERP_LINEAR;
        m_shaderDesc->get3DTexture(idx, name, uid, edgelen, interpolation);

        if(!name || !*name || !uid || !*uid || edgelen==0)
        {
            throw OCIO::Exception("The texture data are corrupted");
        }

        const float* values = 0x0;
        m_shaderDesc->get3DTextureValues(idx, values);
        if(!values)
        {
            throw OCIO::Exception("The texture values are missing");
        }

        // 2. Allocate the 3D LUT

        unsigned texId = 0;
        AllocateTexture3D(currIndex, texId, interpolation, edgelen, values);

        // 3. Keep the texture id & name for the later enabling

        m_textureIds.push_back(TextureId(texId, name, GL_TEXTURE_3D));

        currIndex++;
    }

    // Process the 1D LUTs

    const unsigned maxTexture2D = m_shaderDesc->getNumTextures();
    for(unsigned idx=0; idx<maxTexture2D; ++idx)
    {
        // 1. Get the information of the 1D LUT

        const char* name = 0x0;
        const char* uid  = 0x0;
        unsigned width = 0;
        unsigned height = 0;
        OCIO::GpuShaderDesc::TextureType channel = OCIO::GpuShaderDesc::TEXTURE_RGB_CHANNEL;
        OCIO::Interpolation interpolation = OCIO::INTERP_LINEAR;
        m_shaderDesc->getTexture(idx, name, uid, width, height, channel, interpolation);

        if(!name || !*name || !uid || !*uid || width==0)
        {
            throw OCIO::Exception("The texture data are corrupted");
        }

        const float * values = 0x0;
        m_shaderDesc->getTextureValues(idx, values);
        if(!values)
        {
            throw OCIO::Exception("The texture values are missing");
        }

        // 2. Allocate the 1D LUT (a 2D texture is needed to hold large LUTs)

        unsigned texId = 0;
        AllocateTexture2D(currIndex, texId, width, height, interpolation, values);

        // 3. Keep the texture id & name for the later enabling

        unsigned type = (height > 1) ? GL_TEXTURE_2D : GL_TEXTURE_1D;
        m_textureIds.push_back(TextureId(texId, name, type));
        currIndex++;
    }
}

void OpenGLBuilder::deleteAllTextures()
{
    const size_t max = m_textureIds.size();
    for(size_t idx=0; idx<max; ++idx)
    {
        const TextureId& data = m_textureIds[idx];
        glDeleteTextures(1, &data.id);
    }

    m_textureIds.clear();
}

void OpenGLBuilder::useAllTextures()
{
    const size_t max = m_textureIds.size();
    for(size_t idx=0; idx<max; ++idx)
    {
        const TextureId& data = m_textureIds[idx];
        glActiveTexture((GLenum)(GL_TEXTURE0 + m_startIndex + idx));
        glBindTexture(data.type, data.id);
        glUniform1i(
            glGetUniformLocation(m_program,
                                 data.name.c_str()),
                                 GLint(m_startIndex + idx) );
    }
}

unsigned OpenGLBuilder::buildProgram(const std::string & clientShaderProgram)
{
    const std::string shaderCacheID = m_shaderDesc->getCacheID();
    if(shaderCacheID!=m_shaderCacheID)
    {
        if(m_fragShader)
        {
            glDetachShader(m_program, m_fragShader);
            glDeleteShader(m_fragShader);
        }

        std::ostringstream os;
        os  << m_shaderDesc->getShaderText() << std::endl
            << clientShaderProgram << std::endl;

        if(m_verbose)
        {
            std::cout << std::endl;
            std::cout << "GPU Shader Program:" << std::endl;
            std::cout << std::endl;
            std::cout << os.str() << std::endl;
            std::cout << std::endl;
        }

        m_fragShader = CompileShaderText(GL_FRAGMENT_SHADER, os.str().c_str());

        LinkShaders(m_program, m_fragShader);

        m_shaderCacheID = shaderCacheID;
    }

    return m_program;
}

void OpenGLBuilder::useProgram()
{
    glUseProgram(m_program);
}

unsigned OpenGLBuilder::getProgramHandle()
{
    return m_program;
}

unsigned OpenGLBuilder::GetTextureMaxWidth()
{
    // Arbitrary huge number only to find the limit
    static unsigned maxTextureSize = 256 * 1024;

    CheckStatus();

    unsigned w = maxTextureSize;
    unsigned h = 1;

    while(w>1)
    {
        glTexImage2D(GL_PROXY_TEXTURE_2D, 0,
                     GL_RGB32F_ARB,
                     w, h, 0,
                     GL_RGB, GL_FLOAT, NULL);

        bool texValid = true;
        GLenum glErr = GL_NO_ERROR;

        while((glErr=glGetError()) != GL_NO_ERROR)
        {
            if(glErr==GL_INVALID_VALUE)
            {
                texValid = false;
            }
        }

#ifndef __APPLE__
        //
        // In case of Linux, if glTexImage2D() succeed
        //  glGetTexLevelParameteriv() could fail.
        //
        // In case of OSX, glTexImage2D() will provide the right result,
        //  and glGetTexLevelParameteriv() always fails.
        //  So do not try glGetTexLevelParameteriv().
        //
        if(texValid)
        {
            GLint format = 0;
            glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0,
                                     GL_TEXTURE_COMPONENTS, &format);

            texValid = texValid && (GL_RGB32F_ARB==format);

            while((glErr=glGetError()) != GL_NO_ERROR);
        }
#endif

        if(texValid) break;

        w = w >> 1;
        h = h << 1;
    }

    if(w==1)
    {
        throw OCIO::Exception("Maximum texture size unknown");
    }

    CheckStatus();

    return w;
}

<|endoftext|>