<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// operator_to_plan_transformer.cpp
//
// Identification: src/optimizer/operator_to_plan_transformer.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/plan_generator.h"

#include "optimizer/operator_expression.h"
#include "planner/aggregate_plan.h"
#include "planner/delete_plan.h"
#include "planner/hash_join_plan.h"
#include "planner/hash_plan.h"
#include "planner/index_scan_plan.h"
#include "planner/insert_plan.h"
#include "planner/limit_plan.h"
#include "planner/nested_loop_join_plan.h"
#include "planner/order_by_plan.h"
#include "planner/projection_plan.h"
#include "planner/seq_scan_plan.h"
#include "planner/update_plan.h"
#include "settings/settings_manager.h"
#include "storage/data_table.h"

using std::vector;
using std::make_pair;
using std::string;
using std::to_string;
using std::unique_ptr;
using std::shared_ptr;
using std::move;
using std::make_tuple;
using std::make_pair;
using std::pair;

namespace peloton {
namespace optimizer {

PlanGenerator::PlanGenerator() {}

unique_ptr<planner::AbstractPlan> PlanGenerator::ConvertOpExpression(
    shared_ptr<OperatorExpression> op, shared_ptr<PropertySet> required_props,
    vector<expression::AbstractExpression *> required_cols,
    vector<expression::AbstractExpression *> output_cols,
    vector<unique_ptr<planner::AbstractPlan>> &children_plans,
    vector<ExprMap> children_expr_map) {
  required_props_ = required_props;
  required_cols_ = required_cols;
  output_cols_ = output_cols;
  children_plans_ = move(children_plans);
  children_expr_map_ = move(children_expr_map);
  op->Op().Accept(this);
  BuildProjectionPlan();
  return move(output_plan_);
}

void PlanGenerator::Visit(const DummyScan *) {
  // DummyScan is used in case of SELECT without FROM so that enforcer
  // can enforce a PhysicalProjection on top of DummyScan to generate correct
  // result. But here, no need to translate DummyScan to any physical plan.
  output_plan_ = nullptr;
}

void PlanGenerator::Visit(const PhysicalSeqScan *op) {
  vector<oid_t> column_ids = GenerateColumnsForScan();
  auto predicate = GeneratePredicateForScan(
      expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
      op->table_alias, op->table_);

  output_plan_.reset(new planner::SeqScanPlan(op->table_, predicate.release(), column_ids));
}

void PlanGenerator::Visit(const PhysicalIndexScan *op) {
  vector<oid_t> column_ids = GenerateColumnsForScan();
  auto predicate = GeneratePredicateForScan(
      expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
      op->table_alias, op->table_);

  // TODO build index scan plan
}

void PlanGenerator::Visit(const QueryDerivedScan *) {}

void PlanGenerator::Visit(const PhysicalProject *) {}

void PlanGenerator::Visit(const PhysicalLimit *) {}

void PlanGenerator::Visit(const PhysicalOrderBy *) {
  vector<oid_t> column_ids;
  PL_ASSERT(children_expr_map_.size() == 1);
  auto &child_cols_map = children_expr_map_[0];
  for (size_t i = 0; i < required_cols_.size(); ++i) {
    column_ids.push_back(child_cols_map[required_cols_[i]]);
  }

  auto sort_prop = required_props_->GetPropertyOfType(PropertyType::SORT)
                       ->As<PropertySort>();
  auto sort_columns_size = sort_prop->GetSortColumnSize();
  vector<oid_t> sort_col_ids;
  vector<bool> sort_flags;
  for (size_t i = 0; i < sort_columns_size; ++i) {
    sort_col_ids.push_back(child_cols_map[sort_prop->GetSortColumn(i)]);
    // planner use desc flag
    sort_flags.push_back(!sort_prop->GetSortAscending(i));
  }
  output_plan_.reset(
      new planner::OrderByPlan(sort_col_ids, sort_flags, column_ids));
}

void PlanGenerator::Visit(const PhysicalHashGroupBy *) {}

void PlanGenerator::Visit(const PhysicalSortGroupBy *) {}

void PlanGenerator::Visit(const PhysicalAggregate *) {}

void PlanGenerator::Visit(const PhysicalDistinct *) {}

void PlanGenerator::Visit(const PhysicalFilter *) {}

void PlanGenerator::Visit(const PhysicalInnerNLJoin *) {}

void PlanGenerator::Visit(const PhysicalLeftNLJoin *) {}

void PlanGenerator::Visit(const PhysicalRightNLJoin *) {}

void PlanGenerator::Visit(const PhysicalOuterNLJoin *) {}

void PlanGenerator::Visit(const PhysicalInnerHashJoin *) {}

void PlanGenerator::Visit(const PhysicalLeftHashJoin *) {}

void PlanGenerator::Visit(const PhysicalRightHashJoin *) {}

void PlanGenerator::Visit(const PhysicalOuterHashJoin *) {}

void PlanGenerator::Visit(const PhysicalInsert *) {}

void PlanGenerator::Visit(const PhysicalInsertSelect *) {}

void PlanGenerator::Visit(const PhysicalDelete *) {}

void PlanGenerator::Visit(const PhysicalUpdate *) {}

ExprMap PlanGenerator::GenerateTableExprMap(const std::string &alias,
                                            const storage::DataTable *table) {
  ExprMap expr_map;
  auto db_id = table->GetDatabaseOid();
  oid_t table_id = table->GetOid();
  auto cols = table->GetSchema()->GetColumns();
  size_t num_col = cols.size();
  for (oid_t col_id = 0; col_id < num_col; ++col_id) {
    // Only bound_obj_id is needed for expr_map
    // TODO potential memory leak here?
    expression::TupleValueExpression *col_expr =
        new expression::TupleValueExpression(cols[col_id].column_name.c_str(),
                                             alias.c_str());
    col_expr->SetValueType(table->GetSchema()->GetColumn(col_id).GetType());
    col_expr->SetBoundOid(db_id, table_id, col_id);
    expr_map[col_expr] = col_id;
  }
  return expr_map;
}
// Generate columns for scan plan
vector<oid_t> PlanGenerator::GenerateColumnsForScan() {
  vector<oid_t> column_ids;
  for (oid_t idx = 0; idx < output_cols_.size(); ++idx) {
    auto &output_expr = output_cols_[idx];
    PL_ASSERT(output_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto output_tvexpr =
        reinterpret_cast<expression::TupleValueExpression *>(output_expr);

    // Set column offset
    PL_ASSERT(output_tvexpr->GetIsBound() == true);
    auto col_id = std::get<2>(output_tvexpr->GetBoundOid());
    column_ids.push_back(col_id);
  }

  return column_ids;
}

std::unique_ptr<expression::AbstractExpression>
PlanGenerator::GeneratePredicateForScan(
    const std::shared_ptr<expression::AbstractExpression> predicate_expr,
    const std::string &alias, const storage::DataTable *table) {
  if (predicate_expr == nullptr) {
    return nullptr;
  }
  ExprMap table_expr_map = GenerateTableExprMap(alias, table);
  unique_ptr<expression::AbstractExpression> predicate =
      std::unique_ptr<expression::AbstractExpression>(predicate_expr->Copy());
  expression::ExpressionUtil::EvaluateExpression({table_expr_map},
                                                 predicate.get());
  return predicate;
}

void PlanGenerator::BuildProjectionPlan() {
  bool no_projection = false;
  if (output_cols_.size() == required_cols_.size()) {
    no_projection = true;
    size_t cols_size = output_cols_.size();
    for (size_t idx = 0; idx < cols_size; ++idx) {
      if (output_cols_[idx] != required_cols_[idx]) {
        no_projection = false;
        break;
      }
    }
  }

  if (no_projection) {
    return;
  }
  // TODO Construct projection plan
  // TODO(boweic): For now, we only produce tv exprs and aggregate expr as
  // output column, but we should handle arbitary expressions in the future
  // ExprMap output_cols_map;
  // for (auto &col : output_cols_) {
  //   PL_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE ||
  //             col->GetExpressionType() == ExpressionType::AggregateType);
  //
  // }
}

}  // namespace optimizer
}  // namespace peloton
<commit_msg>Finish build index scan plan in plan generator<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// operator_to_plan_transformer.cpp
//
// Identification: src/optimizer/operator_to_plan_transformer.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/plan_generator.h"

#include "optimizer/operator_expression.h"
#include "planner/aggregate_plan.h"
#include "planner/delete_plan.h"
#include "planner/hash_join_plan.h"
#include "planner/hash_plan.h"
#include "planner/index_scan_plan.h"
#include "planner/insert_plan.h"
#include "planner/limit_plan.h"
#include "planner/nested_loop_join_plan.h"
#include "planner/order_by_plan.h"
#include "planner/projection_plan.h"
#include "planner/seq_scan_plan.h"
#include "planner/update_plan.h"
#include "settings/settings_manager.h"
#include "storage/data_table.h"

using std::vector;
using std::make_pair;
using std::string;
using std::to_string;
using std::unique_ptr;
using std::shared_ptr;
using std::move;
using std::make_tuple;
using std::make_pair;
using std::pair;

namespace peloton {
namespace optimizer {

PlanGenerator::PlanGenerator() {}

unique_ptr<planner::AbstractPlan> PlanGenerator::ConvertOpExpression(
    shared_ptr<OperatorExpression> op, shared_ptr<PropertySet> required_props,
    vector<expression::AbstractExpression *> required_cols,
    vector<expression::AbstractExpression *> output_cols,
    vector<unique_ptr<planner::AbstractPlan>> &children_plans,
    vector<ExprMap> children_expr_map) {
  required_props_ = required_props;
  required_cols_ = required_cols;
  output_cols_ = output_cols;
  children_plans_ = move(children_plans);
  children_expr_map_ = move(children_expr_map);
  op->Op().Accept(this);
  BuildProjectionPlan();
  return move(output_plan_);
}

void PlanGenerator::Visit(const DummyScan *) {
  // DummyScan is used in case of SELECT without FROM so that enforcer
  // can enforce a PhysicalProjection on top of DummyScan to generate correct
  // result. But here, no need to translate DummyScan to any physical plan.
  output_plan_ = nullptr;
}

void PlanGenerator::Visit(const PhysicalSeqScan *op) {
  vector<oid_t> column_ids = GenerateColumnsForScan();
  auto predicate = GeneratePredicateForScan(
      expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
      op->table_alias, op->table_);

  output_plan_.reset(new planner::SeqScanPlan(op->table_, predicate.release(), column_ids));
}

void PlanGenerator::Visit(const PhysicalIndexScan *op) {
  vector<oid_t> column_ids = GenerateColumnsForScan();
  auto predicate = GeneratePredicateForScan(
      expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
      op->table_alias, op->table_);

  auto index = op->table_->GetIndex(op->index_id);
  vector<expression::AbstractExpression *> runtime_keys;

  // Create index scan desc
  planner::IndexScanPlan::IndexScanDesc index_scan_desc(
      index, op->key_column_id_list, op->expr_type_list, op->value_list, runtime_keys);
  output_plan_.reset(new planner::IndexScanPlan(
      op->table_, predicate.release(), column_ids, index_scan_desc, false));
}

void PlanGenerator::Visit(const QueryDerivedScan *) {}

void PlanGenerator::Visit(const PhysicalProject *) {}

void PlanGenerator::Visit(const PhysicalLimit *) {}

void PlanGenerator::Visit(const PhysicalOrderBy *) {
  vector<oid_t> column_ids;
  PL_ASSERT(children_expr_map_.size() == 1);
  auto &child_cols_map = children_expr_map_[0];
  for (size_t i = 0; i < required_cols_.size(); ++i) {
    column_ids.push_back(child_cols_map[required_cols_[i]]);
  }

  auto sort_prop = required_props_->GetPropertyOfType(PropertyType::SORT)
                       ->As<PropertySort>();
  auto sort_columns_size = sort_prop->GetSortColumnSize();
  vector<oid_t> sort_col_ids;
  vector<bool> sort_flags;
  for (size_t i = 0; i < sort_columns_size; ++i) {
    sort_col_ids.push_back(child_cols_map[sort_prop->GetSortColumn(i)]);
    // planner use desc flag
    sort_flags.push_back(!sort_prop->GetSortAscending(i));
  }
  output_plan_.reset(
      new planner::OrderByPlan(sort_col_ids, sort_flags, column_ids));
}

void PlanGenerator::Visit(const PhysicalHashGroupBy *) {}

void PlanGenerator::Visit(const PhysicalSortGroupBy *) {}

void PlanGenerator::Visit(const PhysicalAggregate *) {}

void PlanGenerator::Visit(const PhysicalDistinct *) {}

void PlanGenerator::Visit(const PhysicalFilter *) {}

void PlanGenerator::Visit(const PhysicalInnerNLJoin *) {}

void PlanGenerator::Visit(const PhysicalLeftNLJoin *) {}

void PlanGenerator::Visit(const PhysicalRightNLJoin *) {}

void PlanGenerator::Visit(const PhysicalOuterNLJoin *) {}

void PlanGenerator::Visit(const PhysicalInnerHashJoin *) {}

void PlanGenerator::Visit(const PhysicalLeftHashJoin *) {}

void PlanGenerator::Visit(const PhysicalRightHashJoin *) {}

void PlanGenerator::Visit(const PhysicalOuterHashJoin *) {}

void PlanGenerator::Visit(const PhysicalInsert *) {}

void PlanGenerator::Visit(const PhysicalInsertSelect *) {}

void PlanGenerator::Visit(const PhysicalDelete *) {}

void PlanGenerator::Visit(const PhysicalUpdate *) {}

ExprMap PlanGenerator::GenerateTableExprMap(const std::string &alias,
                                            const storage::DataTable *table) {
  ExprMap expr_map;
  auto db_id = table->GetDatabaseOid();
  oid_t table_id = table->GetOid();
  auto cols = table->GetSchema()->GetColumns();
  size_t num_col = cols.size();
  for (oid_t col_id = 0; col_id < num_col; ++col_id) {
    // Only bound_obj_id is needed for expr_map
    // TODO potential memory leak here?
    expression::TupleValueExpression *col_expr =
        new expression::TupleValueExpression(cols[col_id].column_name.c_str(),
                                             alias.c_str());
    col_expr->SetValueType(table->GetSchema()->GetColumn(col_id).GetType());
    col_expr->SetBoundOid(db_id, table_id, col_id);
    expr_map[col_expr] = col_id;
  }
  return expr_map;
}
// Generate columns for scan plan
vector<oid_t> PlanGenerator::GenerateColumnsForScan() {
  vector<oid_t> column_ids;
  for (oid_t idx = 0; idx < output_cols_.size(); ++idx) {
    auto &output_expr = output_cols_[idx];
    PL_ASSERT(output_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE);
    auto output_tvexpr =
        reinterpret_cast<expression::TupleValueExpression *>(output_expr);

    // Set column offset
    PL_ASSERT(output_tvexpr->GetIsBound() == true);
    auto col_id = std::get<2>(output_tvexpr->GetBoundOid());
    column_ids.push_back(col_id);
  }

  return column_ids;
}

std::unique_ptr<expression::AbstractExpression>
PlanGenerator::GeneratePredicateForScan(
    const std::shared_ptr<expression::AbstractExpression> predicate_expr,
    const std::string &alias, const storage::DataTable *table) {
  if (predicate_expr == nullptr) {
    return nullptr;
  }
  ExprMap table_expr_map = GenerateTableExprMap(alias, table);
  unique_ptr<expression::AbstractExpression> predicate =
      std::unique_ptr<expression::AbstractExpression>(predicate_expr->Copy());
  expression::ExpressionUtil::EvaluateExpression({table_expr_map},
                                                 predicate.get());
  return predicate;
}

void PlanGenerator::BuildProjectionPlan() {
  bool no_projection = false;
  if (output_cols_.size() == required_cols_.size()) {
    no_projection = true;
    size_t cols_size = output_cols_.size();
    for (size_t idx = 0; idx < cols_size; ++idx) {
      if (output_cols_[idx] != required_cols_[idx]) {
        no_projection = false;
        break;
      }
    }
  }

  if (no_projection) {
    return;
  }
  // TODO Construct projection plan
  // TODO(boweic): For now, we only produce tv exprs and aggregate expr as
  // output column, but we should handle arbitary expressions in the future
  // ExprMap output_cols_map;
  // for (auto &col : output_cols_) {
  //   PL_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE ||
  //             col->GetExpressionType() == ExpressionType::AggregateType);
  //
  // }
}

}  // namespace optimizer
}  // namespace peloton
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 odan
 * License: MIT License
 */

#include "LCG.hpp"

namespace PokeRNG {

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
LCG<UIntType, mul, add, mask>::LCG() :
    div(calc_inverse_tmp<UIntType, mul, mask>::value), sub(~(div * add) + 1ULL) { }

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next(UIntType s) const {
    return ((s * mul) + add);
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev(UIntType s) const {
    return ((s * div) + sub);
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::skip_lcg(UIntType s, UIntType n, UIntType a, UIntType b) const {
    while(n) {
        if(n & 1) s = ((s * a) + b);
        b = (a * b + b);
        a = (a * a);
        n >>= 1;
    }

    return s;
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next_n(UIntType s, UIntType n) const {
    return skip_lcg(s, n, mul, add);
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev_n(UIntType s, UIntType n) const {
    return skip_lcg(s, n, div, sub);
}
/*
 * 参考
 * http://plusletool.hatenablog.jp/entry/2014/11/05/230000
 */
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::index(UIntType s) const {
    u64 a = mul;
    u64 b = add;
    u64 n = 0;
    u64 x = 1;

    while(x) {
        if(s & x) {
            n |= x;
            s -= b;
            b *= a;
        }

        b *= a + 1;
        a *= a;
        x <<= 1;
    }

    return n;
}
template class LCG<u64, 0x5D588B656C078965, 0x269EC3, 0xFFFFFFFFFFFFFFFF>;
template class LCG<u32, 0x41C64E6D, 0x6073, 0xFFFFFFFF>;

template class LCG<u64, 0x5D583D6D6C078979, 0x26A693, 0xFFFFFFFFFFFFFFFF>;

} // end PokeRNG
<commit_msg>LCGのindexの計算時に使用する型を変更<commit_after>/*
 * Copyright (c) 2014 odan
 * License: MIT License
 */

#include "LCG.hpp"

namespace PokeRNG {

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
LCG<UIntType, mul, add, mask>::LCG() :
    div(calc_inverse_tmp<UIntType, mul, mask>::value), sub(~(div * add) + 1ULL) { }

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next(UIntType s) const {
    return ((s * mul) + add);
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev(UIntType s) const {
    return ((s * div) + sub);
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::skip_lcg(UIntType s, UIntType n, UIntType a, UIntType b) const {
    while(n) {
        if(n & 1) s = ((s * a) + b);
        b = (a * b + b);
        a = (a * a);
        n >>= 1;
    }

    return s;
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next_n(UIntType s, UIntType n) const {
    return skip_lcg(s, n, mul, add);
}

template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev_n(UIntType s, UIntType n) const {
    return skip_lcg(s, n, div, sub);
}
/*
 * 参考
 * http://plusletool.hatenablog.jp/entry/2014/11/05/230000
 */
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::index(UIntType s) const {
    UIntType a = mul;
    UIntType b = add;
    UIntType n = 0;
    UIntType x = 1;

    while(x) {
        if(s & x) {
            n |= x;
            s -= b;
            b *= a;
        }

        b *= a + 1;
        a *= a;
        x <<= 1;
    }

    return n;
}
template class LCG<u64, 0x5D588B656C078965, 0x269EC3, 0xFFFFFFFFFFFFFFFF>;
template class LCG<u32, 0x41C64E6D, 0x6073, 0xFFFFFFFF>;

template class LCG<u64, 0x5D583D6D6C078979, 0x26A693, 0xFFFFFFFFFFFFFFFF>;

} // end PokeRNG
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetManager.cpp
 */

#include "./JPetManager.h"

#include <cassert>
#include <ctime>
#include <string>

#include "../JPetLoggerInclude.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetCmdParser/JPetCmdParser.h"

#include <TDSet.h>
#include <TThread.h>

JPetManager& JPetManager::getManager()
{
  static JPetManager instance;
  return instance;
}

void JPetManager::run()
{
  INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
  std::vector<JPetTaskExecutor*> executors;
  std::vector<TThread*> threads;
  auto i = 0;
  for (auto opt : fOptions) {
    JPetTaskExecutor* executor = new JPetTaskExecutor(fTaskGeneratorChain, i, opt);
    executors.push_back(executor);
    auto thr = executor->run();
    if (thr) {
      threads.push_back(thr);
    } else {
      ERROR("thread pointer is null");
    }
    i++;
  }
  for (auto thread : threads) {
    thread->Join();
  }
  for (auto executor : executors) {
    delete executor;
  }

  INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
}

void JPetManager::parseCmdLine(int argc, char** argv)
{
  JPetCmdParser parser;
  fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv);
}

JPetManager::~JPetManager()
{
  /**/
}

void JPetManager::registerTask(const TaskGenerator& taskGen)
{
  assert(fTaskGeneratorChain);
  fTaskGeneratorChain->push_back(taskGen);
}
<commit_msg>In JPetManager destructor add cleaning of param caches.<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetManager.cpp
 */

#include "./JPetManager.h"

#include <cassert>
#include <ctime>
#include <string>

#include "../JPetLoggerInclude.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetCmdParser/JPetCmdParser.h"

#include <TDSet.h>
#include <TThread.h>

JPetManager& JPetManager::getManager()
{
  static JPetManager instance;
  return instance;
}

void JPetManager::run()
{
  INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
  std::vector<JPetTaskExecutor*> executors;
  std::vector<TThread*> threads;
  auto i = 0;
  for (auto opt : fOptions) {
    JPetTaskExecutor* executor = new JPetTaskExecutor(fTaskGeneratorChain, i, opt);
    executors.push_back(executor);
    auto thr = executor->run();
    if (thr) {
      threads.push_back(thr);
    } else {
      ERROR("thread pointer is null");
    }
    i++;
  }
  for (auto thread : threads) {
    thread->Join();
  }
  for (auto& executor : executors) {
    if (executor) {
      delete executor;
      executor = 0;
    }
  }

  INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
}

void JPetManager::parseCmdLine(int argc, char** argv)
{
  JPetCmdParser parser;
  fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv);
}

JPetManager::~JPetManager()
{
  /// delete shared caches for paramBanks
  /// @todo I think that should be changed
  JPetDBParamGetter::clearParamCache();
  JPetScopeParamGetter::clearParamCache();
}

void JPetManager::registerTask(const TaskGenerator& taskGen)
{
  assert(fTaskGeneratorChain);
  fTaskGeneratorChain->push_back(taskGen);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: window3.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:36:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#define _SV_WINDOW_CXX

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif

#ifndef _SV_WINDOW_H
#include <window.h>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SV_WAITOBJ_HXX
#include <vcl/waitobj.hxx>
#endif

#ifndef _SV_SALGDI_HXX
#include <vcl/salgdi.hxx>
#endif
#ifndef _SV_NATIVEWIDGETS_HXX
#include <vcl/salnativewidgets.hxx>
#endif
#ifndef _SV_SALCTRLHANDLE_HXX
#include <vcl/salctrlhandle.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

using namespace rtl;

// -----------------------------------------------------------------------
// These functions are mainly passthrough functions that allow access to
// the SalFrame behind a Window object for native widget rendering purposes.
// -----------------------------------------------------------------------

void Window::ImplInitSalControlHandle()
{
    // create SalControlHandle on demand
    // not needed for ordinary windows
    // TODO: move creation to SalGraphics
    //if( !ImplGetWinData()->mpSalControlHandle )
    //    ImplGetWinData()->mpSalControlHandle = new SalControlHandle;
}

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

BOOL Window::IsNativeControlSupported( ControlType nType, ControlPart nPart )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    return( mpGraphics->IsNativeControlSupported(nType, nPart) );
}

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

BOOL Window::HitTestNativeControl( ControlType nType,
                              ControlPart nPart,
                              const Region& rControlRegion,
                              const Point& aPos,
                              BOOL& rIsInside )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    ImplInitSalControlHandle();

    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());

    return( mpGraphics->HitTestNativeControl(nType, nPart, screenRegion, OutputToScreenPixel( aPos ), *ImplGetWinData()->mpSalControlHandle, rIsInside, this ) );
}

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

void Window::ImplMoveControlValue( ControlType nType, const ImplControlValue& aValue, const Point& rDelta ) const
{
    if( aValue.getOptionalVal() )
    {
        switch( nType )
        {
            case CTRL_SCROLLBAR:
            {
                ScrollbarValue* pScVal = reinterpret_cast<ScrollbarValue*>(aValue.getOptionalVal());
                pScVal->maThumbRect.Move( rDelta.X(), rDelta.Y() );
                pScVal->maButton1Rect.Move( rDelta.X(), rDelta.Y() );
                pScVal->maButton2Rect.Move( rDelta.X(), rDelta.Y() );
            }
            break;
            case CTRL_SPINBOX:
            case CTRL_SPINBUTTONS:
            {
                SpinbuttonValue* pSpVal = reinterpret_cast<SpinbuttonValue*>(aValue.getOptionalVal());
                pSpVal->maUpperRect.Move( rDelta.X(), rDelta.Y() );
                pSpVal->maLowerRect.Move( rDelta.X(), rDelta.Y() );
            }
            break;
            case CTRL_TOOLBAR:
            {
                ToolbarValue* pTVal = reinterpret_cast<ToolbarValue*>(aValue.getOptionalVal());
                pTVal->maGripRect.Move( rDelta.X(), rDelta.Y() );
            }
            break;
        }
    }
}

BOOL Window::DrawNativeControl( ControlType nType,
                            ControlPart nPart,
                            const Region& rControlRegion,
                            ControlState nState,
                            const ImplControlValue& aValue,
                            OUString aCaption )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    /*
    if( !IsInPaint() && IsPaintTransparent() )
    {
        // only required if called directly (ie, we're not in Paint() ):
        // force redraw (Paint()) for transparent controls
        // to trigger a repaint of the background
        Region aClipRgn( GetClipRegion() );
        if( !rControlRegion.IsEmpty() )
            aClipRgn.Intersect( rControlRegion );
        Invalidate( aClipRgn, INVALIDATE_UPDATE );
        return TRUE;
    }
    */

    ImplInitSalControlHandle();

    // make sure the current clip region is initialized correctly
    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    if ( mbInitClipRegion )
        ImplInitClipRegion();
    if ( mbOutputClipped )
        return TRUE;

    if ( mbInitLineColor )
        ImplInitLineColor();
    if ( mbInitFillColor )
        ImplInitFillColor();

    // Convert the coordinates from relative to Window-absolute, so we draw
    // in the correct place in platform code
    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());

    // do so for ImplControlValue members, also
    ImplMoveControlValue( nType, aValue, aWinOffs );

    Region aTestRegion( GetActiveClipRegion() );
    aTestRegion.Intersect( rControlRegion );
    if( aTestRegion == rControlRegion )
        nState |= CTRL_CACHING_ALLOWED;   // control is not clipped, caching allowed

    BOOL bRet = mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );

    // transform back ImplControlValue members
    ImplMoveControlValue( nType, aValue, Point()-aWinOffs );

    return bRet;
}

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

BOOL Window::DrawNativeControlText(ControlType nType,
                            ControlPart nPart,
                            const Region& rControlRegion,
                            ControlState nState,
                            const ImplControlValue& aValue,
                            OUString aCaption )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    ImplInitSalControlHandle();

    // make sure the current clip region is initialized correctly
    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return false;

    if ( mbInitClipRegion )
        ImplInitClipRegion();
    if ( mbOutputClipped )
        return true;

    if ( mbInitLineColor )
        ImplInitLineColor();
    if ( mbInitFillColor )
        ImplInitFillColor();

    // Convert the coordinates from relative to Window-absolute, so we draw
    // in the correct place in platform code
    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
    ImplMoveControlValue( nType, aValue, aWinOffs );

    BOOL bRet = mpGraphics->DrawNativeControlText(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );

    // transform back ImplControlValue members
    ImplMoveControlValue( nType, aValue, Point()-aWinOffs );

    return bRet;
}

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

BOOL Window::GetNativeControlRegion(  ControlType nType,
                                ControlPart nPart,
                                const Region& rControlRegion,
                                ControlState nState,
                                const ImplControlValue& aValue,
                                OUString aCaption,
                                Region &rNativeBoundingRegion,
                                Region &rNativeContentRegion )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    ImplInitSalControlHandle();

    // Convert the coordinates from relative to Window-absolute, so we draw
    // in the correct place in platform code
    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
    ImplMoveControlValue( nType, aValue, aWinOffs );

    BOOL bRet = mpGraphics->GetNativeControlRegion(nType, nPart, screenRegion, nState, aValue,
                                *ImplGetWinData()->mpSalControlHandle, aCaption, rNativeBoundingRegion,
                                rNativeContentRegion, this );
    if( bRet )
    {
        // transform back native regions
        rNativeBoundingRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
        rNativeContentRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
    }
    // transform back ImplControlValue members
    ImplMoveControlValue( nType, aValue, Point()-aWinOffs );

    return bRet;
}

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

WaitObject::~WaitObject()
{
    if ( mpWindow )
        mpWindow->LeaveWait();
}
<commit_msg>INTEGRATION: CWS mergesvp (1.9.2); FILE MERGED 2007/07/04 15:32:41 pl 1.9.2.1: #i79023# header moving<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: window3.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-24 10:23:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#define _SV_WINDOW_CXX

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif

#ifndef _SV_WINDOW_H
#include <vcl/window.h>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SV_WAITOBJ_HXX
#include <vcl/waitobj.hxx>
#endif

#ifndef _SV_SALGDI_HXX
#include <vcl/salgdi.hxx>
#endif
#ifndef _SV_NATIVEWIDGETS_HXX
#include <vcl/salnativewidgets.hxx>
#endif
#ifndef _SV_SALCTRLHANDLE_HXX
#include <vcl/salctrlhandle.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

using namespace rtl;

// -----------------------------------------------------------------------
// These functions are mainly passthrough functions that allow access to
// the SalFrame behind a Window object for native widget rendering purposes.
// -----------------------------------------------------------------------

void Window::ImplInitSalControlHandle()
{
    // create SalControlHandle on demand
    // not needed for ordinary windows
    // TODO: move creation to SalGraphics
    //if( !ImplGetWinData()->mpSalControlHandle )
    //    ImplGetWinData()->mpSalControlHandle = new SalControlHandle;
}

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

BOOL Window::IsNativeControlSupported( ControlType nType, ControlPart nPart )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    return( mpGraphics->IsNativeControlSupported(nType, nPart) );
}

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

BOOL Window::HitTestNativeControl( ControlType nType,
                              ControlPart nPart,
                              const Region& rControlRegion,
                              const Point& aPos,
                              BOOL& rIsInside )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    ImplInitSalControlHandle();

    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());

    return( mpGraphics->HitTestNativeControl(nType, nPart, screenRegion, OutputToScreenPixel( aPos ), *ImplGetWinData()->mpSalControlHandle, rIsInside, this ) );
}

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

void Window::ImplMoveControlValue( ControlType nType, const ImplControlValue& aValue, const Point& rDelta ) const
{
    if( aValue.getOptionalVal() )
    {
        switch( nType )
        {
            case CTRL_SCROLLBAR:
            {
                ScrollbarValue* pScVal = reinterpret_cast<ScrollbarValue*>(aValue.getOptionalVal());
                pScVal->maThumbRect.Move( rDelta.X(), rDelta.Y() );
                pScVal->maButton1Rect.Move( rDelta.X(), rDelta.Y() );
                pScVal->maButton2Rect.Move( rDelta.X(), rDelta.Y() );
            }
            break;
            case CTRL_SPINBOX:
            case CTRL_SPINBUTTONS:
            {
                SpinbuttonValue* pSpVal = reinterpret_cast<SpinbuttonValue*>(aValue.getOptionalVal());
                pSpVal->maUpperRect.Move( rDelta.X(), rDelta.Y() );
                pSpVal->maLowerRect.Move( rDelta.X(), rDelta.Y() );
            }
            break;
            case CTRL_TOOLBAR:
            {
                ToolbarValue* pTVal = reinterpret_cast<ToolbarValue*>(aValue.getOptionalVal());
                pTVal->maGripRect.Move( rDelta.X(), rDelta.Y() );
            }
            break;
        }
    }
}

BOOL Window::DrawNativeControl( ControlType nType,
                            ControlPart nPart,
                            const Region& rControlRegion,
                            ControlState nState,
                            const ImplControlValue& aValue,
                            OUString aCaption )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    /*
    if( !IsInPaint() && IsPaintTransparent() )
    {
        // only required if called directly (ie, we're not in Paint() ):
        // force redraw (Paint()) for transparent controls
        // to trigger a repaint of the background
        Region aClipRgn( GetClipRegion() );
        if( !rControlRegion.IsEmpty() )
            aClipRgn.Intersect( rControlRegion );
        Invalidate( aClipRgn, INVALIDATE_UPDATE );
        return TRUE;
    }
    */

    ImplInitSalControlHandle();

    // make sure the current clip region is initialized correctly
    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    if ( mbInitClipRegion )
        ImplInitClipRegion();
    if ( mbOutputClipped )
        return TRUE;

    if ( mbInitLineColor )
        ImplInitLineColor();
    if ( mbInitFillColor )
        ImplInitFillColor();

    // Convert the coordinates from relative to Window-absolute, so we draw
    // in the correct place in platform code
    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());

    // do so for ImplControlValue members, also
    ImplMoveControlValue( nType, aValue, aWinOffs );

    Region aTestRegion( GetActiveClipRegion() );
    aTestRegion.Intersect( rControlRegion );
    if( aTestRegion == rControlRegion )
        nState |= CTRL_CACHING_ALLOWED;   // control is not clipped, caching allowed

    BOOL bRet = mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );

    // transform back ImplControlValue members
    ImplMoveControlValue( nType, aValue, Point()-aWinOffs );

    return bRet;
}

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

BOOL Window::DrawNativeControlText(ControlType nType,
                            ControlPart nPart,
                            const Region& rControlRegion,
                            ControlState nState,
                            const ImplControlValue& aValue,
                            OUString aCaption )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    ImplInitSalControlHandle();

    // make sure the current clip region is initialized correctly
    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return false;

    if ( mbInitClipRegion )
        ImplInitClipRegion();
    if ( mbOutputClipped )
        return true;

    if ( mbInitLineColor )
        ImplInitLineColor();
    if ( mbInitFillColor )
        ImplInitFillColor();

    // Convert the coordinates from relative to Window-absolute, so we draw
    // in the correct place in platform code
    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
    ImplMoveControlValue( nType, aValue, aWinOffs );

    BOOL bRet = mpGraphics->DrawNativeControlText(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );

    // transform back ImplControlValue members
    ImplMoveControlValue( nType, aValue, Point()-aWinOffs );

    return bRet;
}

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

BOOL Window::GetNativeControlRegion(  ControlType nType,
                                ControlPart nPart,
                                const Region& rControlRegion,
                                ControlState nState,
                                const ImplControlValue& aValue,
                                OUString aCaption,
                                Region &rNativeBoundingRegion,
                                Region &rNativeContentRegion )
{
    if( !IsNativeWidgetEnabled() )
        return FALSE;

    if ( !mpGraphics )
        if ( !ImplGetGraphics() )
            return FALSE;

    ImplInitSalControlHandle();

    // Convert the coordinates from relative to Window-absolute, so we draw
    // in the correct place in platform code
    Point aWinOffs;
    aWinOffs = OutputToScreenPixel( aWinOffs );
    Region screenRegion( rControlRegion );
    screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
    ImplMoveControlValue( nType, aValue, aWinOffs );

    BOOL bRet = mpGraphics->GetNativeControlRegion(nType, nPart, screenRegion, nState, aValue,
                                *ImplGetWinData()->mpSalControlHandle, aCaption, rNativeBoundingRegion,
                                rNativeContentRegion, this );
    if( bRet )
    {
        // transform back native regions
        rNativeBoundingRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
        rNativeContentRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
    }
    // transform back ImplControlValue members
    ImplMoveControlValue( nType, aValue, Point()-aWinOffs );

    return bRet;
}

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

WaitObject::~WaitObject()
{
    if ( mpWindow )
        mpWindow->LeaveWait();
}
<|endoftext|>


<commit_before>#pragma once

#include "jsd_core.hpp"
#include "jsd_check.hpp"
#include "jsd_options.hpp"

namespace JSON
{
	template <typename T>
    void try_parse(T& obj, std::string const& name, PropertyTree const& tree, ParsingOptions const& options = DEFAULT_PARSER_OPTIONS,
                   typename std::enable_if <Internal::can_parse<T>::value, void>::type* = nullptr)
    {
        parse(obj, name, tree, options);
    }

    template <typename T>
    void try_parse(T&, std::string const&, PropertyTree const&, ParsingOptions const& = DEFAULT_PARSER_OPTIONS,
                   typename std::enable_if <!Internal::can_parse<T>::value, int>::type* = nullptr)
    {
        static_assert (Internal::can_parse<T>::value, "the object you try to parse has no applicable interface");
    }

    template <typename T>
    T make_from_json(std::istream& stream)
    {
        T res;
        JSON::parse(res, "", JSON::parse_json(stream));
        return res;
    }

    template <typename T>
    T make_from_json(std::string const& str)
    {
        T res;
        JSON::parse(res, "", JSON::parse_json(str));
        return res;
    }
}

#define json_deserialize(NAME) JSON::try_parse(#NAME, NAME)
#define json_deserialize_opt(NAME, OPTIONS) JSON::try_parse(#NAME, NAME, OPTIONS)
<commit_msg>Fixed for rvalues.<commit_after>#pragma once

#include "jsd_core.hpp"
#include "jsd_check.hpp"
#include "jsd_options.hpp"

namespace JSON
{
	template <typename T>
    void try_parse(T& obj, std::string const& name, PropertyTree const& tree, ParsingOptions const& options = DEFAULT_PARSER_OPTIONS,
                   typename std::enable_if <Internal::can_parse<T>::value, void>::type* = nullptr)
    {
        parse(obj, name, tree, options);
    }

    template <typename T>
    void try_parse(T&, std::string const&, PropertyTree const&, ParsingOptions const& = DEFAULT_PARSER_OPTIONS,
                   typename std::enable_if <!Internal::can_parse<T>::value, int>::type* = nullptr)
    {
        static_assert (Internal::can_parse<T>::value, "the object you try to parse has no applicable interface");
    }

    template <typename T>
    T make_from_json(std::istream&& stream)
    {
        T res;
        JSON::parse(res, "", JSON::parse_json(stream));
        return res;
    }

    template <typename T>
    T make_from_json(std::istream& stream)
    {
        T res;
        JSON::parse(res, "", JSON::parse_json(stream));
        return res;
    }

    template <typename T>
    T make_from_json(std::string const& str)
    {
        T res;
        JSON::parse(res, "", JSON::parse_json(str));
        return res;
    }
}

#define json_deserialize(NAME) JSON::try_parse(#NAME, NAME)
#define json_deserialize_opt(NAME, OPTIONS) JSON::try_parse(#NAME, NAME, OPTIONS)
<|endoftext|>


<commit_before>/*
*
* Copyright (C) 2004 Mekensleep
*
*    Mekensleep
*    24 rue vieille du temple
*    75004 Paris
*       licensing@mekensleep.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* Author:
*  Igor Kravtchenko <igor@obraz.net>
*
*/

#include "hdrloader.h"

#include <math.h>
#include <memory.h>
#include <stdio.h>

typedef unsigned char RGBE[4];
#define R            0
#define G            1
#define B            2
#define E            3

#define  MINELEN    8                // minimum scanline length for encoding
#define  MAXELEN    0x7fff            // maximum scanline length for encoding

static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);

bool HDRLoader::isHDRFile(const char *_fileName)
{
    FILE *file;
    file = fopen(_fileName, "rb");
    if (!file)
        return false;

    char str[10];
    fread(str, 10, 1, file);
    fclose(file);

    if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
        return false;

    return true;
}

bool HDRLoader::load(const char *_fileName, HDRLoaderResult &_res)
{
    int i;
    char str[200];
    FILE *file;

    file = fopen(_fileName, "rb");
    if (!file)
        return false;

    fread(str, 10, 1, file);
    if (memcmp(str, "#?RADIANCE", 10)) {
        fseek(file, 0, SEEK_SET);
        fread(str, 6, 1, file);
        if (memcmp(str, "#?RGBE", 6)) {
            fclose(file);
            return false;
        }
    }
    fseek(file, 1, SEEK_CUR);

    char cmd[2000];
    i = 0;
    char c = 0, oldc;
    while(true) {
        oldc = c;
        c = fgetc(file);
        if (c == 0xa && oldc == 0xa)
            break;
        cmd[i++] = c;
    }

    char reso[2000];
    i = 0;
    while(true) {
        c = fgetc(file);
        reso[i++] = c;
        if (c == 0xa)
            break;
    }

    int w, h;
    if (!sscanf(reso, "-Y %ld +X %ld", &h, &w)) {
        fclose(file);
        return false;
    }

    _res.width = w;
    _res.height = h;

    float *cols = new float[w * h * 3];
    _res.cols = cols;

    RGBE *scanline = new RGBE[w];
    if (!scanline) {
        fclose(file);
        return false;
    }

    // convert image
    cols += (h-1) * w * 3;
    for (int y = h - 1; y >= 0; y--) {
        if (decrunch(scanline, w, file) == false)
            break;
        workOnRGBE(scanline, w, cols);
        cols -= w * 3;
    }

    delete [] scanline;
    fclose(file);

    return true;
}

float convertComponent(int _expo, int _val)
{
    float v = _val / 256.0f;
    float d = powf(2, _expo);
    return v * d;
}

void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
    int ii = 0;
    while (_len-- > 0) {
        int expo = _scan[0][E] - 128;
        _cols[0] = convertComponent(expo, _scan[0][R]);
        _cols[1] = convertComponent(expo, _scan[0][G]);
        _cols[2] = convertComponent(expo, _scan[0][B]);
        _cols += 3;
        _scan++;
        ii++;
    }
}

bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
    int  i, j;

    if (_len < MINELEN || _len > MAXELEN)
        return oldDecrunch(_scanline, _len, _file);

    i = fgetc(_file);
    if (i != 2) {
        fseek(_file, -1, SEEK_CUR);
        return oldDecrunch(_scanline, _len, _file);
    }

    _scanline[0][G] = fgetc(_file);
    _scanline[0][B] = fgetc(_file);
    i = fgetc(_file);

    if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
        _scanline[0][R] = 2;
        _scanline[0][E] = i;
        return oldDecrunch(_scanline + 1, _len - 1, _file);
    }

    // read each component
    for (i = 0; i < 4; i++) {
        for (j = 0; j < _len; ) {
            unsigned char code = fgetc(_file);
            if (code > 128) { // run
                code &= 127;
                unsigned char val = fgetc(_file);
                while (code--)
                    _scanline[j++][i] = val;
            }
            else  {    // non-run
                while(code--)
                    _scanline[j++][i] = fgetc(_file);
            }
        }
    }

    return feof(_file) ? false : true;
}

bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
    int i;
    int rshift = 0;

    while (_len > 0) {
        _scanline[0][R] = fgetc(_file);
        _scanline[0][G] = fgetc(_file);
        _scanline[0][B] = fgetc(_file);
        _scanline[0][E] = fgetc(_file);
        if (feof(_file))
            return false;

        if (_scanline[0][R] == 1 &&
            _scanline[0][G] == 1 &&
            _scanline[0][B] == 1) {
                for (i = _scanline[0][E] << rshift; i > 0; i--) {
                    memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
                    _scanline++;
                    _len--;
                }
                rshift += 8;
            }
        else {
            _scanline++;
            _len--;
            rshift = 0;
        }
    }
    return true;
}
<commit_msg>Warning fixes by Mike Weiblen + Robert Osfield<commit_after>/*
*
* Copyright (C) 2004 Mekensleep
*
*    Mekensleep
*    24 rue vieille du temple
*    75004 Paris
*       licensing@mekensleep.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* Author:
*  Igor Kravtchenko <igor@obraz.net>
*
*/

#include "hdrloader.h"

#include <math.h>
#include <memory.h>
#include <stdio.h>

typedef unsigned char RGBE[4];
#define R            0
#define G            1
#define B            2
#define E            3

#define  MINELEN    8                // minimum scanline length for encoding
#define  MAXELEN    0x7fff            // maximum scanline length for encoding

static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);

bool HDRLoader::isHDRFile(const char *_fileName)
{
    FILE *file;
    file = fopen(_fileName, "rb");
    if (!file)
        return false;

    char str[10];
    fread(str, 10, 1, file);
    fclose(file);

    if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
        return false;

    return true;
}

bool HDRLoader::load(const char *_fileName, HDRLoaderResult &_res)
{
    int i;
    char str[200];
    FILE *file;

    file = fopen(_fileName, "rb");
    if (!file)
        return false;

    fread(str, 10, 1, file);
    if (memcmp(str, "#?RADIANCE", 10)) {
        fseek(file, 0, SEEK_SET);
        fread(str, 6, 1, file);
        if (memcmp(str, "#?RGBE", 6)) {
            fclose(file);
            return false;
        }
    }
    fseek(file, 1, SEEK_CUR);

    char cmd[2000];
    i = 0;
    char c = 0, oldc;
    while(true) {
        oldc = c;
        c = fgetc(file);
        if (c == 0xa && oldc == 0xa)
            break;
        cmd[i++] = c;
    }

    char reso[2000];
    i = 0;
    while(true) {
        c = fgetc(file);
        reso[i++] = c;
        if (c == 0xa)
            break;
    }

    int w, h;
    if (!sscanf(reso, "-Y %d +X %d", &h, &w)) {
        fclose(file);
        return false;
    }

    _res.width = w;
    _res.height = h;

    float *cols = new float[w * h * 3];
    _res.cols = cols;

    RGBE *scanline = new RGBE[w];
    if (!scanline) {
        fclose(file);
        return false;
    }

    // convert image
    cols += (h-1) * w * 3;
    for (int y = h - 1; y >= 0; y--) {
        if (decrunch(scanline, w, file) == false)
            break;
        workOnRGBE(scanline, w, cols);
        cols -= w * 3;
    }

    delete [] scanline;
    fclose(file);

    return true;
}

float convertComponent(int _expo, int _val)
{
    float v = _val / 256.0f;
    float d = powf(2.0f, (float)_expo);
    return v * d;
}

void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
    int ii = 0;
    while (_len-- > 0) {
        int expo = _scan[0][E] - 128;
        _cols[0] = convertComponent(expo, _scan[0][R]);
        _cols[1] = convertComponent(expo, _scan[0][G]);
        _cols[2] = convertComponent(expo, _scan[0][B]);
        _cols += 3;
        _scan++;
        ii++;
    }
}

bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
    int  i, j;

    if (_len < MINELEN || _len > MAXELEN)
        return oldDecrunch(_scanline, _len, _file);

    i = fgetc(_file);
    if (i != 2) {
        fseek(_file, -1, SEEK_CUR);
        return oldDecrunch(_scanline, _len, _file);
    }

    _scanline[0][G] = fgetc(_file);
    _scanline[0][B] = fgetc(_file);
    i = fgetc(_file);

    if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
        _scanline[0][R] = 2;
        _scanline[0][E] = i;
        return oldDecrunch(_scanline + 1, _len - 1, _file);
    }

    // read each component
    for (i = 0; i < 4; i++) {
        for (j = 0; j < _len; ) {
            unsigned char code = fgetc(_file);
            if (code > 128) { // run
                code &= 127;
                unsigned char val = fgetc(_file);
                while (code--)
                    _scanline[j++][i] = val;
            }
            else  {    // non-run
                while(code--)
                    _scanline[j++][i] = fgetc(_file);
            }
        }
    }

    return feof(_file) ? false : true;
}

bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
    int i;
    int rshift = 0;

    while (_len > 0) {
        _scanline[0][R] = fgetc(_file);
        _scanline[0][G] = fgetc(_file);
        _scanline[0][B] = fgetc(_file);
        _scanline[0][E] = fgetc(_file);
        if (feof(_file))
            return false;

        if (_scanline[0][R] == 1 &&
            _scanline[0][G] == 1 &&
            _scanline[0][B] == 1) {
                for (i = _scanline[0][E] << rshift; i > 0; i--) {
                    memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
                    _scanline++;
                    _len--;
                }
                rshift += 8;
            }
        else {
            _scanline++;
            _len--;
            rshift = 0;
        }
    }
    return true;
}
<|endoftext|>


<commit_before>#include <testutilscxx.h>
#include <stdexcept>

void
assert_equals(CuTest *tc,
              const Frame &f1,
              const Frame &f2)
{
	real pos = f1.position().distance(f2.position());
	CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);
	real tan = f1.tangent().distance(f2.tangent());
	CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
	real norm = f1.normal().distance(f2.normal());
	CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
	real binorm = f1.binormal().distance(f2.binormal());
	CuAssertDblEquals(tc, 0, binorm, POINT_EPSILON);
}

void
assert_equals(CuTest *tc,
              const FrameSeq &fs1,
              const FrameSeq &fs2)
{
	CuAssertIntEquals(tc, (int) fs1.size(), (int) fs2.size());
	for (size_t i = 0; i < fs1.size(); i++)
		assert_equals(tc, fs1.at(i), fs2.at(i));
}

void
assert_orthogonal(CuTest *tc,
                  const Vec3 &v1,
                  const Vec3 &v2)
{
	real angle = v1.angle(v2);
	CuAssertDblEquals(tc, 90, angle, ANGLE_EPSILON);
}

void
frames_frameseq_copy_ctor(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));

	// When
	FrameSeq copy(frames);

	// Then
	assert_equals(tc, frames, copy);
}

void
frames_frameseq_move_ctor(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));
	FrameSeq toBeMoved(frames);

	// When
	FrameSeq move(std::move(toBeMoved));

	// Then
	assert_equals(tc, frames, move);
	CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}

void
frames_frameseq_copy_assign(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));
	FrameSeq copy;

	// When
	copy = frames;

	// Then
	assert_equals(tc, frames, copy);
}

void
frames_frameseq_move_assign(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));
	FrameSeq toBeMoved(frames);
	FrameSeq move;

	// When
	move = std::move(toBeMoved);

	// Then
	assert_equals(tc, frames, move);
	CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}

void
frames_vectors(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	vector<real> knots = spline.uniformKnotSeq(100);

	// When
	FrameSeq frames = spline.computeRMF(knots);

	// Then
	for (size_t i = 0; i < knots.size(); i++) {
		Frame frame = frames.at(i);

		real pos = spline(knots[i])
		           .resultVec3()
		           .distance(frame.position());
		CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);

		real tan = spline.derive()(knots[i])
		           .resultVec3()
		           .normalize()
		           .distance(frame.tangent());
		CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);

		assert_orthogonal(tc, frame.normal(), frame.tangent());
		assert_orthogonal(tc, frame.normal(), frame.binormal());
		assert_orthogonal(tc, frame.binormal(), frame.tangent());
	}
}

void
frames_frameseq_invalid_idx(CuTest *tc)
{
	FrameSeq frames;

	try {
		frames.at(1);
	} catch (out_of_range &ex) {
		string what(ex.what());
		CuAssertTrue(tc, what.length() > 0);
		return;
	}
	CuFail(tc, "Expected exception");
}

void
frames_frameseq_to_string(CuTest *tc)
{
	// When
	FrameSeq frames;

	// When
	string s = frames.toString();

	// Then
	CuAssertTrue(tc, s.length() > 0);
}

CuSuite *
get_frames_suite()
{
	CuSuite* suite = CuSuiteNew();
	SUITE_ADD_TEST(suite, frames_vectors);
	SUITE_ADD_TEST(suite, frames_frameseq_copy_ctor);
	SUITE_ADD_TEST(suite, frames_frameseq_move_ctor);
	SUITE_ADD_TEST(suite, frames_frameseq_copy_assign);
	SUITE_ADD_TEST(suite, frames_frameseq_move_assign);
	SUITE_ADD_TEST(suite, frames_frameseq_invalid_idx);
	SUITE_ADD_TEST(suite, frames_frameseq_to_string);
	return suite;
}
<commit_msg>fixed test case for norm<commit_after>#include <testutilscxx.h>
#include <stdexcept>

void
assert_equals(CuTest *tc,
              const Frame &f1,
              const Frame &f2)
{
	real pos = f1.position().distance(f2.position());
	CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);
	real tan = f1.tangent().distance(f2.tangent());
	CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
	real norm = f1.normal().distance(f2.normal());
	CuAssertDblEquals(tc, 0, norm, POINT_EPSILON);
	real binorm = f1.binormal().distance(f2.binormal());
	CuAssertDblEquals(tc, 0, binorm, POINT_EPSILON);
}

void
assert_equals(CuTest *tc,
              const FrameSeq &fs1,
              const FrameSeq &fs2)
{
	CuAssertIntEquals(tc, (int) fs1.size(), (int) fs2.size());
	for (size_t i = 0; i < fs1.size(); i++)
		assert_equals(tc, fs1.at(i), fs2.at(i));
}

void
assert_orthogonal(CuTest *tc,
                  const Vec3 &v1,
                  const Vec3 &v2)
{
	real angle = v1.angle(v2);
	CuAssertDblEquals(tc, 90, angle, ANGLE_EPSILON);
}

void
frames_frameseq_copy_ctor(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));

	// When
	FrameSeq copy(frames);

	// Then
	assert_equals(tc, frames, copy);
}

void
frames_frameseq_move_ctor(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));
	FrameSeq toBeMoved(frames);

	// When
	FrameSeq move(std::move(toBeMoved));

	// Then
	assert_equals(tc, frames, move);
	CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}

void
frames_frameseq_copy_assign(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));
	FrameSeq copy;

	// When
	copy = frames;

	// Then
	assert_equals(tc, frames, copy);
}

void
frames_frameseq_move_assign(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	FrameSeq frames = spline.computeRMF(
		spline.uniformKnotSeq(10));
	FrameSeq toBeMoved(frames);
	FrameSeq move;

	// When
	move = std::move(toBeMoved);

	// Then
	assert_equals(tc, frames, move);
	CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}

void
frames_vectors(CuTest *tc)
{
	// Given
	BSpline spline(7, 2);
	spline.setControlPoints({
			120, 100, // P1
			270, 40,  // P2
			370, 490, // P3
			590, 40,  // P4
			570, 490, // P5
			420, 480, // P6
			220, 500  // P7
		});
	vector<real> knots = spline.uniformKnotSeq(100);

	// When
	FrameSeq frames = spline.computeRMF(knots);

	// Then
	for (size_t i = 0; i < knots.size(); i++) {
		Frame frame = frames.at(i);

		real pos = spline(knots[i])
		           .resultVec3()
		           .distance(frame.position());
		CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);

		real tan = spline.derive()(knots[i])
		           .resultVec3()
		           .normalize()
		           .distance(frame.tangent());
		CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);

		assert_orthogonal(tc, frame.normal(), frame.tangent());
		assert_orthogonal(tc, frame.normal(), frame.binormal());
		assert_orthogonal(tc, frame.binormal(), frame.tangent());
	}
}

void
frames_frameseq_invalid_idx(CuTest *tc)
{
	FrameSeq frames;

	try {
		frames.at(1);
	} catch (out_of_range &ex) {
		string what(ex.what());
		CuAssertTrue(tc, what.length() > 0);
		return;
	}
	CuFail(tc, "Expected exception");
}

void
frames_frameseq_to_string(CuTest *tc)
{
	// When
	FrameSeq frames;

	// When
	string s = frames.toString();

	// Then
	CuAssertTrue(tc, s.length() > 0);
}

CuSuite *
get_frames_suite()
{
	CuSuite* suite = CuSuiteNew();
	SUITE_ADD_TEST(suite, frames_vectors);
	SUITE_ADD_TEST(suite, frames_frameseq_copy_ctor);
	SUITE_ADD_TEST(suite, frames_frameseq_move_ctor);
	SUITE_ADD_TEST(suite, frames_frameseq_copy_assign);
	SUITE_ADD_TEST(suite, frames_frameseq_move_assign);
	SUITE_ADD_TEST(suite, frames_frameseq_invalid_idx);
	SUITE_ADD_TEST(suite, frames_frameseq_to_string);
	return suite;
}
<|endoftext|>


<commit_before>#include "IShader.h"

#include "common/Exception.h"

#include <gl/glew.h>
#include <stdio.h>
#include <assert.h>

namespace d2d
{

IShader::IShader()
{
	m_prog = 0;
}

IShader::~IShader()
{
	DeleteShader();
}

void IShader::InitShader(const char* VS, const char* FS)
{
	GLuint prog = glCreateProgram();

	GLuint vs = CompileShader(VS, GL_VERTEX_SHADER);
	if (vs == 0) {
		return;
	} else {
		glAttachShader(prog, vs);
	}

	GLuint fs = CompileShader(FS, GL_FRAGMENT_SHADER);
	if (fs == 0) {
		return;
	} else {
		glAttachShader(prog, fs);
	}

	BindAttrib(prog);

	// link
	GLint status;
	glLinkProgram(prog);

	glGetProgramiv(prog, GL_LINK_STATUS, &status);
	if (status == GL_FALSE) {
		char buf[1024];
		glGetProgramInfoLog(prog, 1024, NULL, buf);
		throw d2d::Exception("link failed:%s\n", buf);
	}

	// detatch
	glDetachShader(prog, fs);
	glDeleteShader(fs);
	glDetachShader(prog, vs);
	glDeleteShader(vs);

	m_prog = prog;
}

void IShader::DeleteShader()
{
	glUseProgram(0);
	glDeleteProgram(m_prog);
}

GLuint IShader::CompileShader(const char* source, GLuint type)
{
	GLint status;

	GLuint shader = glCreateShader(type);
	glShaderSource(shader, 1, &source, NULL);
	glCompileShader(shader);

	glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

	if (status == GL_FALSE) {
		char buf[1024];
		glGetShaderInfoLog(shader, 1024, NULL, buf);
		glDeleteShader(shader);
		throw d2d::Exception("compile failed:%s\n, source:\n %s\n", buf, source);
	}

	return shader;
}

}<commit_msg>[FIXED] 调整调BindAttrib的时机<commit_after>#include "IShader.h"

#include "common/Exception.h"

#include <gl/glew.h>
#include <stdio.h>
#include <assert.h>

namespace d2d
{

IShader::IShader()
{
	m_prog = 0;
}

IShader::~IShader()
{
	DeleteShader();
}

void IShader::InitShader(const char* VS, const char* FS)
{
	GLuint prog = glCreateProgram();

	GLuint vs = CompileShader(VS, GL_VERTEX_SHADER);
	if (vs == 0) {
		return;
	} else {
		glAttachShader(prog, vs);
	}

	GLuint fs = CompileShader(FS, GL_FRAGMENT_SHADER);
	if (fs == 0) {
		return;
	} else {
		glAttachShader(prog, fs);
	}

//	BindAttrib(prog);

	// link
	GLint status;
	glLinkProgram(prog);

	glGetProgramiv(prog, GL_LINK_STATUS, &status);
	if (status == GL_FALSE) {
		char buf[1024];
		glGetProgramInfoLog(prog, 1024, NULL, buf);
		throw d2d::Exception("link failed:%s\n", buf);
	}

	// detatch
	glDetachShader(prog, fs);
	glDeleteShader(fs);
	glDetachShader(prog, vs);
	glDeleteShader(vs);

	m_prog = prog;

	BindAttrib(prog);
}

void IShader::DeleteShader()
{
	glUseProgram(0);
	glDeleteProgram(m_prog);
}

GLuint IShader::CompileShader(const char* source, GLuint type)
{
	GLint status;

	GLuint shader = glCreateShader(type);
	glShaderSource(shader, 1, &source, NULL);
	glCompileShader(shader);

	glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

	if (status == GL_FALSE) {
		char buf[1024];
		glGetShaderInfoLog(shader, 1024, NULL, buf);
		glDeleteShader(shader);
		throw d2d::Exception("compile failed:%s\n, source:\n %s\n", buf, source);
	}

	return shader;
}

}<|endoftext|>


<commit_before>/* dtkComposerNodeMatrixSquareRealOperatorBinary.cpp ---
 *
 * Author: slekout
 * Copyright (C) 2011 - Babette lekouta, Inria.
 * Created: Thu Apr 26 15:58:22 2012 (+0200)
 * Version: $Id$
 * Last-Updated:
 *           By:
 *     Update #:
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerNodeMatrixSquareRealOperatorBinary.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"

#include <dtkMath>

#include <dtkLog/dtkLog>

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary
// /////////////////////////////////////////////////////////////////

class dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate
{
public:
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_lhs;
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_rhs;

public:
    dtkComposerTransmitterEmitter<dtkMatrixSquareReal> emitter_matrix;

public:
    dtkMatrixSquareReal *matrix;
};

dtkComposerNodeMatrixSquareRealOperatorBinary::dtkComposerNodeMatrixSquareRealOperatorBinary(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate)
{
    d->matrix = NULL;

    this->appendReceiver(&d->receiver_lhs);
    this->appendReceiver(&d->receiver_rhs);
    this->appendEmitter(&d->emitter_matrix);
}

dtkComposerNodeMatrixSquareRealOperatorBinary::~dtkComposerNodeMatrixSquareRealOperatorBinary(void)
{
    if (d->matrix)
        delete d->matrix;

    d->matrix = NULL;

    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV
// /////////////////////////////////////////////////////////////////

class dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate
{
public:
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
    dtkComposerTransmitterReceiver<dtkVectorReal>       receiver_vector;

public:
    dtkComposerTransmitterEmitter<dtkVectorReal>        emitter_vector;

public:
    dtkVectorReal *vector;
};

dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate)
{
    d->vector = NULL;

    this->appendReceiver(&d->receiver_matrix);
    this->appendReceiver(&d->receiver_vector);
    this->appendEmitter(&d->emitter_vector);
}

dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::~dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void)
{
    if (d->vector)
        delete d->vector;

    d->vector = NULL;

    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector
// /////////////////////////////////////////////////////////////////////////////

class dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate
{
public:
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
    dtkComposerTransmitterReceiver<dtkVectorReal>       receiver_vector;
    dtkComposerTransmitterVariant                       receiver_index;

public:
    dtkComposerTransmitterEmitter<dtkMatrixSquareReal>   emitter_matrix;
};

dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate)
{
    this->appendReceiver(&d->receiver_matrix);
    this->appendReceiver(&d->receiver_vector);

    QList<int> variant_list;

    variant_list << QMetaType::LongLong;
    d->receiver_index.setDataTypes(variant_list);
    this->appendReceiver(&d->receiver_index);

    this->appendEmitter(&d->emitter_matrix);
}

dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::~dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void)
{
    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Sum
// /////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinarySum::run(void)
{
    if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->matrix)
            d->matrix->deallocate();

    } else {

        if (!d->matrix) {
            d->matrix = new dtkMatrixSquareReal();
            d->emitter_matrix.setData(d->matrix);
        }

        dtkMatrixSquareReal *m_lhs = d->receiver_lhs.data();
        dtkMatrixSquareReal *m_rhs = d->receiver_rhs.data();

        if (m_lhs->size() != m_rhs->size()) {
            dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
            d->matrix->deallocate();
        } else {
            *(d->matrix) = (*m_lhs + *m_rhs);
        }
    }
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Substract
// /////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinarySubstract::run(void)
{
    if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->matrix)
            d->matrix->deallocate();

    } else {

        if (!d->matrix) {
            d->matrix = new dtkMatrixSquareReal();
            d->emitter_matrix.setData(d->matrix);
        }

        dtkMatrixSquareReal *m_lhs = d->receiver_lhs.data();
        dtkMatrixSquareReal *m_rhs = d->receiver_rhs.data();

        if (m_lhs->size() != m_rhs->size()) {
            dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
            d->matrix->deallocate();
        } else {
            *(d->matrix) = (*m_lhs - *m_rhs);
        }
    }
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Mult
// /////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryMult::run(void)
{
    if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->matrix)
            d->matrix->deallocate();

    } else {

        if (!d->matrix) {
            d->matrix = new dtkMatrixSquareReal();
            d->emitter_matrix.setData(d->matrix);
        }

        dtkMatrixSquareReal *m_lhs = d->receiver_lhs.data();
        dtkMatrixSquareReal *m_rhs = d->receiver_rhs.data();

        if (m_lhs->size() != m_rhs->size()) {
            dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
            d->matrix->deallocate();
        } else {
            *(d->matrix) = (*m_lhs - *m_rhs);
        }
    }
}

// ///////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Matrix Vector
// //////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryRightProductMV::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->vector)
            d->vector->deallocate();

    } else {

        if (!d->vector) {
            d->vector = new dtkVectorReal();
            d->emitter_vector.setData(d->vector);
        }

        dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
        dtkVectorReal       *vector = d->receiver_vector.data();

        if ( matrix->size() != vector->size() ) {
            dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
            d->vector->deallocate();
        } else {
            *d->vector = (*matrix) * (*vector);
        }
    }
}

// /////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Vector Matrix
// ////////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryLeftProductVM::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->vector)
            d->vector->deallocate();

    } else {

        dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
        dtkVectorReal       *vector = d->receiver_vector.data();

        if (!d->vector) {
            d->vector = new dtkVectorReal();
            d->emitter_vector.setData(d->vector);
        }

        if ( matrix->size() != vector->size() ) {
            dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
            d->vector->deallocate();
        } else {
            d->vector->allocate(vector->size());

            for(qlonglong i = 0; i < matrix->size(); ++i) {
                for(qlonglong j = 0; j < vector->size(); ++j) {
                    (*d->vector)[i] += (*vector)[j] * (*matrix)[j][i] ;
                }
            }
        }
    }
}

// ///////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector  Replace Row to Matrix
// ///////////////////////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowMatrixByVector::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        d->emitter_matrix.clearData();

    } else {

        qlonglong row_index = *d->receiver_index.data<qlonglong>();
        dtkMatrixSquareReal *matrix = d->receiver_matrix.data();

        if (row_index >= matrix->size()) {
            dtkWarn() << "Row index = " << row_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";

            d->emitter_matrix.clearData();

        } else {

            dtkVectorReal *vector = d->receiver_vector.data();

            for(qlonglong j = 0; j < matrix->size(); ++j)
                (*matrix)[row_index][j] = (*vector)[j];

            d->emitter_matrix.setData(matrix);
        }
    }
}

// ////////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector - Replace Col to Matrix
// ////////////////////////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColMatrixByVector::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        d->emitter_matrix.clearData();

    } else {

        qlonglong col_index = *d->receiver_index.data<qlonglong>();
        dtkMatrixSquareReal *matrix = d->receiver_matrix.data();

        if (col_index >= matrix->size()) {
            dtkWarn() << "Column index = " << col_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";

            d->emitter_matrix.clearData();

        } else {

            dtkVectorReal *vector = d->receiver_vector.data();

            for(qlonglong i = 0; i < matrix->size(); ++i)
                (*matrix)[i][col_index] = (*vector)[i];

            d->emitter_matrix.setData(matrix);
        }
    }
}
<commit_msg>Fix bugs.<commit_after>/* dtkComposerNodeMatrixSquareRealOperatorBinary.cpp ---
 *
 * Author: slekout
 * Copyright (C) 2011 - Babette lekouta, Inria.
 * Created: Thu Apr 26 15:58:22 2012 (+0200)
 * Version: $Id$
 * Last-Updated:
 *           By:
 *     Update #:
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerNodeMatrixSquareRealOperatorBinary.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"

#include <dtkMath>

#include <dtkLog/dtkLog>

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary
// /////////////////////////////////////////////////////////////////

class dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate
{
public:
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_lhs;
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_rhs;

public:
    dtkComposerTransmitterEmitter<dtkMatrixSquareReal> emitter_matrix;

public:
    dtkMatrixSquareReal *matrix;
};

dtkComposerNodeMatrixSquareRealOperatorBinary::dtkComposerNodeMatrixSquareRealOperatorBinary(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate)
{
    d->matrix = NULL;

    this->appendReceiver(&d->receiver_lhs);
    this->appendReceiver(&d->receiver_rhs);
    this->appendEmitter(&d->emitter_matrix);
}

dtkComposerNodeMatrixSquareRealOperatorBinary::~dtkComposerNodeMatrixSquareRealOperatorBinary(void)
{
    if (d->matrix)
        delete d->matrix;

    d->matrix = NULL;

    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV
// /////////////////////////////////////////////////////////////////

class dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate
{
public:
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
    dtkComposerTransmitterReceiver<dtkVectorReal>       receiver_vector;

public:
    dtkComposerTransmitterEmitter<dtkVectorReal>        emitter_vector;

public:
    dtkVectorReal *vector;
};

dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate)
{
    d->vector = NULL;

    this->appendReceiver(&d->receiver_matrix);
    this->appendReceiver(&d->receiver_vector);
    this->appendEmitter(&d->emitter_vector);
}

dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::~dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void)
{
    if (d->vector)
        delete d->vector;

    d->vector = NULL;

    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector
// /////////////////////////////////////////////////////////////////////////////

class dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate
{
public:
    dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
    dtkComposerTransmitterReceiver<dtkVectorReal>       receiver_vector;
    dtkComposerTransmitterVariant                       receiver_index;

public:
    dtkComposerTransmitterEmitter<dtkMatrixSquareReal>   emitter_matrix;
};

dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate)
{
    this->appendReceiver(&d->receiver_matrix);
    this->appendReceiver(&d->receiver_vector);

    QList<int> variant_list;

    variant_list << QMetaType::LongLong;
    d->receiver_index.setDataTypes(variant_list);
    this->appendReceiver(&d->receiver_index);

    this->appendEmitter(&d->emitter_matrix);
}

dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::~dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void)
{
    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Sum
// /////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinarySum::run(void)
{
    if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->matrix)
            d->matrix->deallocate();

    } else {

        if (!d->matrix) {
            d->matrix = new dtkMatrixSquareReal();
            d->emitter_matrix.setData(d->matrix);
        }

        const dtkMatrixSquareReal *m_lhs = d->receiver_lhs.constData();
        const dtkMatrixSquareReal *m_rhs = d->receiver_rhs.constData();

        if (m_lhs->size() != m_rhs->size()) {
            dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
            d->matrix->deallocate();
        } else {
            *(d->matrix) = (*m_lhs + *m_rhs);
        }
    }
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Substract
// /////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinarySubstract::run(void)
{
    if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->matrix)
            d->matrix->deallocate();

    } else {

        if (!d->matrix) {
            d->matrix = new dtkMatrixSquareReal();
            d->emitter_matrix.setData(d->matrix);
        }

        const dtkMatrixSquareReal *m_lhs = d->receiver_lhs.constData();
        const dtkMatrixSquareReal *m_rhs = d->receiver_rhs.constData();

        if (m_lhs->size() != m_rhs->size()) {
            dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
            d->matrix->deallocate();
        } else {
            *(d->matrix) = (*m_lhs - *m_rhs);
        }
    }
}

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Mult
// /////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryMult::run(void)
{
    if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->matrix)
            d->matrix->deallocate();

    } else {

        if (!d->matrix) {
            d->matrix = new dtkMatrixSquareReal();
            d->emitter_matrix.setData(d->matrix);
        }

        const dtkMatrixSquareReal *m_lhs = d->receiver_lhs.constData();
        const dtkMatrixSquareReal *m_rhs = d->receiver_rhs.constData();

        if (m_lhs->size() != m_rhs->size()) {
            dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
            d->matrix->deallocate();
        } else {
            *(d->matrix) = (*m_lhs * *m_rhs);
        }
    }
}

// ///////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Matrix Vector
// //////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryRightProductMV::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->vector)
            d->vector->deallocate();

    } else {

        if (!d->vector) {
            d->vector = new dtkVectorReal();
            d->emitter_vector.setData(d->vector);
        }

        const dtkMatrixSquareReal *matrix = d->receiver_matrix.constData();
        const dtkVectorReal       *vector = d->receiver_vector.constData();

        if ( matrix->size() != vector->size() ) {
            dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
            d->vector->deallocate();
        } else {
            *d->vector = (*matrix) * (*vector);
        }
    }
}

// /////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Vector Matrix
// ////////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryLeftProductVM::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        if (d->vector)
            d->vector->deallocate();

    } else {

        const dtkMatrixSquareReal *matrix = d->receiver_matrix.constData();
        const dtkVectorReal       *vector = d->receiver_vector.constData();

        if (!d->vector) {
            d->vector = new dtkVectorReal();
            d->emitter_vector.setData(d->vector);
        }

        if ( matrix->size() != vector->size() ) {
            dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
            d->vector->deallocate();
        } else {
            d->vector->allocate(vector->size());

            for(qlonglong i = 0; i < matrix->size(); ++i) {
                for(qlonglong j = 0; j < vector->size(); ++j) {
                    (*d->vector)[i] += (*vector)[j] * (*matrix)[j][i] ;
                }
            }
        }
    }
}

// ///////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector  Replace Row to Matrix
// ///////////////////////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowMatrixByVector::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        d->emitter_matrix.clearData();

    } else {

        qlonglong row_index = *d->receiver_index.data<qlonglong>();
        dtkMatrixSquareReal *matrix = d->receiver_matrix.data();

        if (row_index >= matrix->size()) {
            dtkWarn() << "Row index = " << row_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";

            d->emitter_matrix.clearData();

        } else {

            const dtkVectorReal *vector = d->receiver_vector.constData();

            for(qlonglong j = 0; j < matrix->size(); ++j)
                (*matrix)[row_index][j] = (*vector)[j];

            d->emitter_matrix.setData(matrix);
        }
    }
}

// ////////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector - Replace Col to Matrix
// ////////////////////////////////////////////////////////////////////////////////////////////////////

void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColMatrixByVector::run(void)
{
    if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
        dtkWarn() << "Inputs not specified. Nothing is done";

        d->emitter_matrix.clearData();

    } else {

        qlonglong col_index = *d->receiver_index.data<qlonglong>();
        dtkMatrixSquareReal *matrix = d->receiver_matrix.data();

        if (col_index >= matrix->size()) {
            dtkWarn() << "Column index = " << col_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";

            d->emitter_matrix.clearData();

        } else {

            const dtkVectorReal *vector = d->receiver_vector.constData();

            for(qlonglong i = 0; i < matrix->size(); ++i)
                (*matrix)[i][col_index] = (*vector)[i];

            d->emitter_matrix.setData(matrix);
        }
    }
}
<|endoftext|>