<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "TiledMeshGenerator.h"
#include "CastUniquePointer.h"

#include "libmesh/replicated_mesh.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/boundary_info.h"
#include "libmesh/mesh_modification.h"
#include "libmesh/bounding_box.h"
#include "libmesh/mesh_tools.h"
#include "libmesh/point.h"

#include <typeinfo>

registerMooseObject("MooseApp", TiledMeshGenerator);

template <>
InputParameters
validParams<TiledMeshGenerator>()
{
  InputParameters params = validParams<MeshGenerator>();

  params.addRequiredParam<MeshGeneratorName>("input", "The mesh we want to repeat");

  // x boundary names
  params.addParam<BoundaryName>("left_boundary", "left", "name of the left (x) boundary");
  params.addParam<BoundaryName>("right_boundary", "right", "name of the right (x) boundary");

  // y boundary names
  params.addParam<BoundaryName>("top_boundary", "top", "name of the top (y) boundary");
  params.addParam<BoundaryName>("bottom_boundary", "bottom", "name of the bottom (y) boundary");

  // z boundary names
  params.addParam<BoundaryName>("front_boundary", "front", "name of the front (z) boundary");
  params.addParam<BoundaryName>("back_boundary", "back", "name of the back (z) boundary");

  // The number of tiles is 1 in each direction unless otherwise specified.
  // An x_tiles value of 1 means do not stitch any extra meshes together in
  // the x-direction.
  params.addParam<unsigned int>(
      "x_tiles", 1, "Number of tiles to stitch together (left to right) in the x-direction");
  params.addParam<unsigned int>(
      "y_tiles", 1, "Number of tiles to stitch together (top to bottom) in the y-direction");
  params.addParam<unsigned int>(
      "z_tiles", 1, "Number of tiles to stitch together (front to back) in the z-direction");

  params.addClassDescription("Use the supplied mesh and create a tiled grid by repeating this mesh "
                             "in the x,y, and z directions.");

  return params;
}

TiledMeshGenerator::TiledMeshGenerator(const InputParameters & parameters)
  : MeshGenerator(parameters), _input(getMesh("input"))
{
  if (dynamic_pointer_cast<DistributedMesh>(_input) != nullptr)
    mooseError("TiledMeshGenerator only works with ReplicatedMesh.");
}

std::unique_ptr<MeshBase>
TiledMeshGenerator::generate()
{
  std::unique_ptr<MeshBase> initial_mesh = std::move(_input);
  std::unique_ptr<ReplicatedMesh> mesh = dynamic_pointer_cast<ReplicatedMesh>(initial_mesh);

  // Getting the x,y,z widths
  std::set<subdomain_id_type> sub_ids;
  mesh->subdomain_ids(sub_ids);
  BoundingBox bbox(Point(std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max()),
  Point(std::numeric_limits<Real>::lowest(), std::numeric_limits<Real>::lowest(), std::numeric_limits<Real>::lowest()));
  for (auto id : sub_ids)
  {
    BoundingBox sub_bbox = MeshTools::create_subdomain_bounding_box(*mesh, id);
    bbox.union_with(sub_bbox);
  }

  _x_width = bbox.max()(0) - bbox.min()(0);
  _y_width = bbox.max()(1) - bbox.min()(1);
  _z_width = bbox.max()(2) - bbox.min()(2);

  boundary_id_type left =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("left_boundary"));
  boundary_id_type right =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("right_boundary"));
  boundary_id_type top =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("top_boundary"));
  boundary_id_type bottom =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("bottom_boundary"));
  boundary_id_type front =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("front_boundary"));
  boundary_id_type back =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("back_boundary"));

  {
    std::unique_ptr<MeshBase> clone = mesh->clone();

    // Build X Tiles
    for (unsigned int i = 1; i < getParam<unsigned int>("x_tiles"); ++i)
    {
      MeshTools::Modification::translate(*clone, _x_width, 0, 0);
      mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                          right,
                          left,
                          TOLERANCE,
                          /*clear_stitched_boundary_ids=*/true);
    }
  }

  {
    std::unique_ptr<MeshBase> clone = mesh->clone();

    // Build Y Tiles
    for (unsigned int i = 1; i < getParam<unsigned int>("y_tiles"); ++i)
    {
      MeshTools::Modification::translate(*clone, 0, _y_width, 0);
      mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                          top,
                          bottom,
                          TOLERANCE,
                          /*clear_stitched_boundary_ids=*/true);
    }
  }

  {
    std::unique_ptr<MeshBase> clone = mesh->clone();

    // Build Z Tiles
    for (unsigned int i = 1; i < getParam<unsigned int>("z_tiles"); ++i)
    {
      MeshTools::Modification::translate(*clone, 0, 0, _z_width);
      mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                          front,
                          back,
                          TOLERANCE,
                          /*clear_stitched_boundary_ids=*/true);
    }
  }

  return dynamic_pointer_cast<MeshBase>(mesh);
}
<commit_msg>Apply clang-format. Refs #12572.<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "TiledMeshGenerator.h"
#include "CastUniquePointer.h"

#include "libmesh/replicated_mesh.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/boundary_info.h"
#include "libmesh/mesh_modification.h"
#include "libmesh/bounding_box.h"
#include "libmesh/mesh_tools.h"
#include "libmesh/point.h"

#include <typeinfo>

registerMooseObject("MooseApp", TiledMeshGenerator);

template <>
InputParameters
validParams<TiledMeshGenerator>()
{
  InputParameters params = validParams<MeshGenerator>();

  params.addRequiredParam<MeshGeneratorName>("input", "The mesh we want to repeat");

  // x boundary names
  params.addParam<BoundaryName>("left_boundary", "left", "name of the left (x) boundary");
  params.addParam<BoundaryName>("right_boundary", "right", "name of the right (x) boundary");

  // y boundary names
  params.addParam<BoundaryName>("top_boundary", "top", "name of the top (y) boundary");
  params.addParam<BoundaryName>("bottom_boundary", "bottom", "name of the bottom (y) boundary");

  // z boundary names
  params.addParam<BoundaryName>("front_boundary", "front", "name of the front (z) boundary");
  params.addParam<BoundaryName>("back_boundary", "back", "name of the back (z) boundary");

  // The number of tiles is 1 in each direction unless otherwise specified.
  // An x_tiles value of 1 means do not stitch any extra meshes together in
  // the x-direction.
  params.addParam<unsigned int>(
      "x_tiles", 1, "Number of tiles to stitch together (left to right) in the x-direction");
  params.addParam<unsigned int>(
      "y_tiles", 1, "Number of tiles to stitch together (top to bottom) in the y-direction");
  params.addParam<unsigned int>(
      "z_tiles", 1, "Number of tiles to stitch together (front to back) in the z-direction");

  params.addClassDescription("Use the supplied mesh and create a tiled grid by repeating this mesh "
                             "in the x,y, and z directions.");

  return params;
}

TiledMeshGenerator::TiledMeshGenerator(const InputParameters & parameters)
  : MeshGenerator(parameters), _input(getMesh("input"))
{
  if (dynamic_pointer_cast<DistributedMesh>(_input) != nullptr)
    mooseError("TiledMeshGenerator only works with ReplicatedMesh.");
}

std::unique_ptr<MeshBase>
TiledMeshGenerator::generate()
{
  std::unique_ptr<MeshBase> initial_mesh = std::move(_input);
  std::unique_ptr<ReplicatedMesh> mesh = dynamic_pointer_cast<ReplicatedMesh>(initial_mesh);

  // Getting the x,y,z widths
  std::set<subdomain_id_type> sub_ids;
  mesh->subdomain_ids(sub_ids);
  BoundingBox bbox(Point(std::numeric_limits<Real>::max(),
                         std::numeric_limits<Real>::max(),
                         std::numeric_limits<Real>::max()),
                   Point(std::numeric_limits<Real>::lowest(),
                         std::numeric_limits<Real>::lowest(),
                         std::numeric_limits<Real>::lowest()));
  for (auto id : sub_ids)
  {
    BoundingBox sub_bbox = MeshTools::create_subdomain_bounding_box(*mesh, id);
    bbox.union_with(sub_bbox);
  }

  _x_width = bbox.max()(0) - bbox.min()(0);
  _y_width = bbox.max()(1) - bbox.min()(1);
  _z_width = bbox.max()(2) - bbox.min()(2);

  boundary_id_type left =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("left_boundary"));
  boundary_id_type right =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("right_boundary"));
  boundary_id_type top =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("top_boundary"));
  boundary_id_type bottom =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("bottom_boundary"));
  boundary_id_type front =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("front_boundary"));
  boundary_id_type back =
      mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("back_boundary"));

  {
    std::unique_ptr<MeshBase> clone = mesh->clone();

    // Build X Tiles
    for (unsigned int i = 1; i < getParam<unsigned int>("x_tiles"); ++i)
    {
      MeshTools::Modification::translate(*clone, _x_width, 0, 0);
      mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                          right,
                          left,
                          TOLERANCE,
                          /*clear_stitched_boundary_ids=*/true);
    }
  }

  {
    std::unique_ptr<MeshBase> clone = mesh->clone();

    // Build Y Tiles
    for (unsigned int i = 1; i < getParam<unsigned int>("y_tiles"); ++i)
    {
      MeshTools::Modification::translate(*clone, 0, _y_width, 0);
      mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                          top,
                          bottom,
                          TOLERANCE,
                          /*clear_stitched_boundary_ids=*/true);
    }
  }

  {
    std::unique_ptr<MeshBase> clone = mesh->clone();

    // Build Z Tiles
    for (unsigned int i = 1; i < getParam<unsigned int>("z_tiles"); ++i)
    {
      MeshTools::Modification::translate(*clone, 0, 0, _z_width);
      mesh->stitch_meshes(dynamic_cast<ReplicatedMesh &>(*clone),
                          front,
                          back,
                          TOLERANCE,
                          /*clear_stitched_boundary_ids=*/true);
    }
  }

  return dynamic_pointer_cast<MeshBase>(mesh);
}
<|endoftext|>


<commit_before>#pragma once

#include <mtao/types.hpp>

namespace mtao::geometry::trigonometry {

    // pushes an angle to the range [0,2*M_PI)
    template <typename S>
    S angle_clamp_positive(S ang) {
        while(ang > 2* M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < 0) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // pushes an angle to the range [-M_PI,M_PI)
    template <typename S>
    S angle_clamp_pi(S ang) {
        while(ang > M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < -M_PI) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // Returns the angle between a vector and [1,0]^*
    template <typename S>
        S angle_scalar(S x, S y) {
            return angle_clamp_positive(std::atan2(y,x));
        }

    // Returns the angle for each vector in a ColVector and returns a rowvector
    template <typename Derived>
        auto angle(const Eigen::MatrixBase<Derived>& P) {
            using S = typename Derived::Scalar;
            Eigen::Matrix<S,1,Derived::ColsAtCompileTime> A(1,P.cols());

#ifdef TODO_CHECK_WHEN_THIS_IS_OK
            A = P.row(0).binaryExpr(P.row(1), std::function(angle_scalar<S>));
#else
            auto a = P.row(0);
            auto b = P.row(1);
            for(int i = 0; i < P.cols(); ++i) {
                A(i) = angle_scalar<S>(a(i),b(i));
            }
#endif
            return A;
        }

    // Returns the angle of between each col from A to B clockwise
    template <typename Derived, typename Derived1>
        auto angle(const Eigen::MatrixBase<Derived>& A, const Eigen::MatrixBase<Derived1>& B) {
            using S = typename Derived::Scalar;
            auto R = (angle(B) - angle(A)).eval();
            R.noalias() = R.unaryExpr(std::function(angle_clamp_positive<S>));
            return R;
        }

    // The interior angle of a polygon with size vertices/edges
    template <typename T = double>
        T interior_angle_sum(int size) {
            return  M_PI * ( size - 2);
        }
    // The exterior angle of a polygon with size vertices/edges
    template <typename T = double>
        T exterior_angle_sum(int size) {
            return  M_PI * ( size + 2);
        }

    // The sum of angles generated by a collection of points.
    // Should be equal to interior_angle_sum(n) or exterior_angle_sum(n)
    // for n = std::distance(beginit,endit)
    template <typename Derived,typename BeginIt, typename EndIt>
        typename Derived::Scalar angle_sum(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {
            using S = typename Derived::Scalar;
            S ang_sum = 0;
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                auto a = V.col(*it);
                auto b = V.col(*it1);
                auto c = V.col(*it2);
                double ang = angle(c-b,a-b)(0);
                ang_sum += ang;
            }

            return ang_sum;
        }
    template <typename Derived,typename Container>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return angle_sum(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return angle_sum(V,C.begin(),C.end());
        }

    template <typename Derived,typename BeginIt, typename EndIt>
        bool clockwise_cell(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {

            using S = typename Derived::Scalar;
            int size =  std::distance(beginit,endit);
            S ang = angle_sum(V,beginit,endit);

            /*
            //counteract size when we have degenerate cells
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                    auto a = V.col(*it);
                    auto b = V.col(*it1);
                    auto c = V.col(*it2);
                    double ang = angle(c-b,a-b)(0);
            }
            */
            S expected=  interior_angle_sum<S>(size);
            bool ret = std::abs(ang - expected) < 1e-5;

            if(ret) {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) > 1e-5);
            } else {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) < 1e-5);
            }
            return ret;
        }
    template <typename Derived,typename Container>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
}
<commit_msg>fix random osx thing<commit_after>#pragma once

#include <mtao/types.hpp>

namespace mtao::geometry::trigonometry {

    // pushes an angle to the range [0,2*M_PI)
    template <typename S>
    S angle_clamp_positive(S ang) {
        while(ang > 2* M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < 0) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // pushes an angle to the range [-M_PI,M_PI)
    template <typename S>
    S angle_clamp_pi(S ang) {
        while(ang > M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < -M_PI) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // Returns the angle between a vector and [1,0]^*
    template <typename S>
        S angle_scalar(S x, S y) {
            return angle_clamp_positive(std::atan2(y,x));
        }

    // Returns the angle for each vector in a ColVector and returns a rowvector
    template <typename Derived>
        auto angle(const Eigen::MatrixBase<Derived>& P) {
            using S = typename Derived::Scalar;
            Eigen::Matrix<S,1,Derived::ColsAtCompileTime> A(1,P.cols());

#ifdef TODO_CHECK_WHEN_THIS_IS_OK
            A = P.row(0).binaryExpr(P.row(1), std::function(angle_scalar<S>));
#else
            auto a = P.row(0);
            auto b = P.row(1);
            for(int i = 0; i < P.cols(); ++i) {
                A(i) = angle_scalar<S>(a(i),b(i));
            }
#endif
            return A;
        }

    // Returns the angle of between each col from A to B clockwise
    template <typename Derived, typename Derived1>
        auto angle(const Eigen::MatrixBase<Derived>& A, const Eigen::MatrixBase<Derived1>& B) {
            using S = typename Derived::Scalar;
            auto R = (angle(B) - angle(A)).eval();
#ifdef TODO_CHECK_WHEN_THIS_IS_OK
            R.noalias() = R.unaryExpr(std::function(angle_clamp_positive<S>));
#else
            for(int i = 0; i < R.size(); ++i) {
                R(i) = angle_clamp_positive(R(i));
            }
#endif
            return R;
        }

    // The interior angle of a polygon with size vertices/edges
    template <typename T = double>
        T interior_angle_sum(int size) {
            return  M_PI * ( size - 2);
        }
    // The exterior angle of a polygon with size vertices/edges
    template <typename T = double>
        T exterior_angle_sum(int size) {
            return  M_PI * ( size + 2);
        }

    // The sum of angles generated by a collection of points.
    // Should be equal to interior_angle_sum(n) or exterior_angle_sum(n)
    // for n = std::distance(beginit,endit)
    template <typename Derived,typename BeginIt, typename EndIt>
        typename Derived::Scalar angle_sum(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {
            using S = typename Derived::Scalar;
            S ang_sum = 0;
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                auto a = V.col(*it);
                auto b = V.col(*it1);
                auto c = V.col(*it2);
                double ang = angle(c-b,a-b)(0);
                ang_sum += ang;
            }

            return ang_sum;
        }
    template <typename Derived,typename Container>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return angle_sum(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return angle_sum(V,C.begin(),C.end());
        }

    template <typename Derived,typename BeginIt, typename EndIt>
        bool clockwise_cell(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {

            using S = typename Derived::Scalar;
            int size =  std::distance(beginit,endit);
            S ang = angle_sum(V,beginit,endit);

            /*
            //counteract size when we have degenerate cells
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                    auto a = V.col(*it);
                    auto b = V.col(*it1);
                    auto c = V.col(*it2);
                    double ang = angle(c-b,a-b)(0);
            }
            */
            S expected=  interior_angle_sum<S>(size);
            bool ret = std::abs(ang - expected) < 1e-5;

            if(ret) {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) > 1e-5);
            } else {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) < 1e-5);
            }
            return ret;
        }
    template <typename Derived,typename Container>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
}
<|endoftext|>


<commit_before>/* SPDX-License-Identifier: Apache-2.0 */

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

#ifndef __STUMPLESS_TEST_HELPER_LEVEL_DISABLED_HPP
#  define __STUMPLESS_TEST_HELPER_LEVEL_DISABLED_HPP

#  include <gtest/gtest.h>
#  include <stumpless.h>

#  define TEST_LEVEL_DISABLED( LEVEL_NAME, LEVEL_LETTER )                      \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME ) {                                \
  int result;                                                                  \
  result = stump_##LEVEL_LETTER( "simple message id: glorious kumquat" );      \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##SideEffects ) {                   \
  int result;                                                                  \
  int before_val = 3;                                                          \
                                                                               \
  result = stump_##LEVEL_LETTER( "simple message id #%d: glorious kumquat",    \
                                 before_val++ );                               \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 3 );                                                  \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##Entry ) {                         \
  int result;                                                                  \
                                                                               \
  result = stump_##LEVEL_LETTER##_entry( target,                               \
                                         basic_entry );                        \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##Log ) {                           \
  int result;                                                                  \
                                                                               \
  result = stump_##LEVEL_LETTER##_log( target,                                 \
                                       STUMPLESS_FACILITY_KERN |               \
                                       STUMPLESS_SEVERITY_INFO,                \
                                       "message id: inchworm bingo" );         \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##LogSideEffects ) {                \
  int result;                                                                  \
  int before_val = 555;                                                        \
                                                                               \
  result = stump_##LEVEL_LETTER##_log( target,                                 \
                                       STUMPLESS_FACILITY_KERN |               \
                                       STUMPLESS_SEVERITY_INFO,                \
                                       "message id #%d: inchworm bingo",       \
                                       before_val++ );                         \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 555 );                                                \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##Message ) {                       \
  int result;                                                                  \
                                                                               \
  result = stump_##LEVEL_LETTER##_message( target,                             \
                                           "message id: inchworm bingo" );     \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##MessageSideEffects ) {            \
  int result;                                                                  \
  int before_val = 555;                                                        \
                                                                               \
  result = stump_##LEVEL_LETTER##_message( target,                             \
                                           "message id #%d: inchworm bingo",   \
                                           before_val++ );                     \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 555 );                                                \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stumplog##LEVEL_NAME ) {                             \
  stumplog_##LEVEL_LETTER( STUMPLESS_FACILITY_KERN |                           \
                           STUMPLESS_SEVERITY_INFO,                            \
                           "message id: inchworm bingo" );                     \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stumplog##LEVEL_NAME##SideEffects ) {                \
  int result;                                                                  \
  int before_val = 555;                                                        \
                                                                               \
  stumplog_##LEVEL_LETTER( STUMPLESS_FACILITY_KERN |                           \
                           STUMPLESS_SEVERITY_INFO,                            \
                           "message id #%d: inchworm bingo",                   \
                           before_val++ );                                     \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 555 );                                                \
}

#endif /* __STUMPLESS_TEST_HELPER_LEVEL_DISABLED_HPP */
<commit_msg>remove unused variable (#84)<commit_after>/* SPDX-License-Identifier: Apache-2.0 */

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

#ifndef __STUMPLESS_TEST_HELPER_LEVEL_DISABLED_HPP
#  define __STUMPLESS_TEST_HELPER_LEVEL_DISABLED_HPP

#  include <gtest/gtest.h>
#  include <stumpless.h>

#  define TEST_LEVEL_DISABLED( LEVEL_NAME, LEVEL_LETTER )                      \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME ) {                                \
  int result;                                                                  \
  result = stump_##LEVEL_LETTER( "simple message id: glorious kumquat" );      \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##SideEffects ) {                   \
  int result;                                                                  \
  int before_val = 3;                                                          \
                                                                               \
  result = stump_##LEVEL_LETTER( "simple message id #%d: glorious kumquat",    \
                                 before_val++ );                               \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 3 );                                                  \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##Entry ) {                         \
  int result;                                                                  \
                                                                               \
  result = stump_##LEVEL_LETTER##_entry( target,                               \
                                         basic_entry );                        \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##Log ) {                           \
  int result;                                                                  \
                                                                               \
  result = stump_##LEVEL_LETTER##_log( target,                                 \
                                       STUMPLESS_FACILITY_KERN |               \
                                       STUMPLESS_SEVERITY_INFO,                \
                                       "message id: inchworm bingo" );         \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##LogSideEffects ) {                \
  int result;                                                                  \
  int before_val = 555;                                                        \
                                                                               \
  result = stump_##LEVEL_LETTER##_log( target,                                 \
                                       STUMPLESS_FACILITY_KERN |               \
                                       STUMPLESS_SEVERITY_INFO,                \
                                       "message id #%d: inchworm bingo",       \
                                       before_val++ );                         \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 555 );                                                \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##Message ) {                       \
  int result;                                                                  \
                                                                               \
  result = stump_##LEVEL_LETTER##_message( target,                             \
                                           "message id: inchworm bingo" );     \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stump##LEVEL_NAME##MessageSideEffects ) {            \
  int result;                                                                  \
  int before_val = 555;                                                        \
                                                                               \
  result = stump_##LEVEL_LETTER##_message( target,                             \
                                           "message id #%d: inchworm bingo",   \
                                           before_val++ );                     \
  EXPECT_EQ( result, 0 );                                                      \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 555 );                                                \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stumplog##LEVEL_NAME ) {                             \
  stumplog_##LEVEL_LETTER( STUMPLESS_FACILITY_KERN |                           \
                           STUMPLESS_SEVERITY_INFO,                            \
                           "message id: inchworm bingo" );                     \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
}                                                                              \
                                                                               \
TEST_F( LevelEnabledTest, Stumplog##LEVEL_NAME##SideEffects ) {                \
  int before_val = 555;                                                        \
                                                                               \
  stumplog_##LEVEL_LETTER( STUMPLESS_FACILITY_KERN |                           \
                           STUMPLESS_SEVERITY_INFO,                            \
                           "message id #%d: inchworm bingo",                   \
                           before_val++ );                                     \
                                                                               \
  EXPECT_TRUE( buffer[0] == '\0' );                                            \
  EXPECT_EQ( before_val, 555 );                                                \
}

#endif /* __STUMPLESS_TEST_HELPER_LEVEL_DISABLED_HPP */
<|endoftext|>


<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "local_rpc_monitor_map.h"
#include "sbenv.h"
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/log/log.h>
LOG_SETUP(".slobrok.server.local_rpc_monitor_map");

namespace slobrok {

#pragma GCC diagnostic ignored "-Winline"

LocalRpcMonitorMap::LocalRpcMonitorMap(FRT_Supervisor &supervisor)
  : _delete(supervisor.GetScheduler()),
    _map(),
    _dispatcher(),
    _history(),
    _supervisor(supervisor),
    _subscription(MapSubscription::subscribe(_dispatcher, _history))
{
}

LocalRpcMonitorMap::~LocalRpcMonitorMap() = default;

LocalRpcMonitorMap::PerService &
LocalRpcMonitorMap::lookup(ManagedRpcServer *rpcsrv) {
    auto iter = _map.find(rpcsrv->getName());
    LOG_ASSERT(iter != _map.end());
    PerService & psd = iter->second;
    LOG_ASSERT(psd.srv.get() == rpcsrv);
    return psd;
}

ServiceMapHistory & LocalRpcMonitorMap::history() {
    return _history;
}

void LocalRpcMonitorMap::addLocal(const ServiceMapping &mapping,
                                  std::unique_ptr<ScriptCommand> inflight)
{
    LOG(debug, "try local add: mapping %s->%s",
        mapping.name.c_str(), mapping.spec.c_str());
    auto old = _map.find(mapping.name);
    if (old != _map.end()) {
        const PerService & exists = old->second;
        if (exists.spec() == mapping.spec) {
            LOG(debug, "added mapping %s->%s was already present",
                mapping.name.c_str(), mapping.spec.c_str());
            inflight->doneHandler(OkState(0, "already registered"));
            return;
        }
        LOG(warning, "tried addLocal for mapping %s->%s, but already had conflicting mapping %s->%s",
            mapping.name.c_str(), mapping.spec.c_str(),
            exists.name().c_str(), exists.spec().c_str());
        inflight->doneHandler(OkState(FRTE_RPC_METHOD_FAILED, "conflict"));
        return;
    }
    auto [ iter, was_inserted ] =
        _map.try_emplace(mapping.name, localService(mapping, std::move(inflight)));
    LOG_ASSERT(was_inserted);
}

void LocalRpcMonitorMap::add(const ServiceMapping &mapping) {
    LOG(debug, "try add: mapping %s->%s",
        mapping.name.c_str(), mapping.spec.c_str());
    auto old = _map.find(mapping.name);
    if (old != _map.end()) {
        PerService & exists = old->second;
        if (exists.spec() == mapping.spec) {
            LOG(debug, "added mapping %s->%s was already present",
                mapping.name.c_str(), mapping.spec.c_str());
            exists.localOnly = false;
            return;
        }
        PerService removed = std::move(exists);
        _map.erase(old);
        LOG(warning, "added mapping %s->%s, but already had conflicting mapping %s->%s",
            mapping.name.c_str(), mapping.spec.c_str(),
            removed.name().c_str(), removed.spec().c_str());
        if (removed.inflight) {
            auto target = std::move(removed.inflight);
            target->doneHandler(OkState(13, "conflict during initialization"));
        }
        if (removed.up) {
            _dispatcher.remove(removed.mapping());
        }
        _delete.later(std::move(removed.srv));
    }
    auto [ iter, was_inserted ] =
        _map.try_emplace(mapping.name, globalService(mapping));
    LOG_ASSERT(was_inserted);
}

void LocalRpcMonitorMap::remove(const ServiceMapping &mapping) {
    auto iter = _map.find(mapping.name);
    if (iter != _map.end()) {
        PerService removed = std::move(iter->second);
        _map.erase(iter);
        LOG(debug, "remove: mapping %s->%s", mapping.name.c_str(), mapping.spec.c_str());
        if (mapping.spec != removed.spec()) {
            LOG(warning, "inconsistent specs for name '%s': had '%s', but was asked to remove '%s'",
                mapping.name.c_str(),
                removed.spec().c_str(),
                mapping.spec.c_str());
        }
        if (removed.inflight) {
            auto target = std::move(removed.inflight);
            target->doneHandler(OkState(13, "removed during initialization"));
        }
        if (removed.up) {
            _dispatcher.remove(removed.mapping());
        }
        _delete.later(std::move(removed.srv));
    } else {
        LOG(debug, "tried to remove non-existing mapping %s->%s",
            mapping.name.c_str(), mapping.spec.c_str());
    }
}

void LocalRpcMonitorMap::notifyFailedRpcSrv(ManagedRpcServer *rpcsrv, std::string) {
    auto &psd = lookup(rpcsrv);
    LOG(debug, "failed: %s->%s", psd.name().c_str(), psd.spec().c_str());
    if (psd.inflight) {
        auto target = std::move(psd.inflight);
        target->doneHandler(OkState(13, "failed check using listNames callback"));
    }
    if (psd.localOnly) {
        PerService removed = std::move(psd);
        auto iter = _map.find(removed.name());
        _map.erase(iter);
        if (removed.up) {
            _dispatcher.remove(removed.mapping());
        }
        _delete.later(std::move(removed.srv));
    } else if (psd.up) {
        psd.up = false;
        _dispatcher.remove(psd.mapping());
    }
}

void LocalRpcMonitorMap::notifyOkRpcSrv(ManagedRpcServer *rpcsrv) {
    auto &psd = lookup(rpcsrv);
    LOG(debug, "ok: %s->%s", psd.name().c_str(), psd.spec().c_str());
    if (psd.inflight) {
        auto target = std::move(psd.inflight);
        target->doneHandler(OkState());
    }
    if (! psd.up) {
        psd.up = true;
        _dispatcher.add(psd.mapping());
    }
}

FRT_Supervisor * LocalRpcMonitorMap::getSupervisor() {
    return &_supervisor;
}

} // namespace slobrok
<commit_msg>only use "delete later" in notifyFailed callback<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "local_rpc_monitor_map.h"
#include "sbenv.h"
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/log/log.h>
LOG_SETUP(".slobrok.server.local_rpc_monitor_map");

namespace slobrok {

#pragma GCC diagnostic ignored "-Winline"

LocalRpcMonitorMap::LocalRpcMonitorMap(FRT_Supervisor &supervisor)
  : _delete(supervisor.GetScheduler()),
    _map(),
    _dispatcher(),
    _history(),
    _supervisor(supervisor),
    _subscription(MapSubscription::subscribe(_dispatcher, _history))
{
}

LocalRpcMonitorMap::~LocalRpcMonitorMap() = default;

LocalRpcMonitorMap::PerService &
LocalRpcMonitorMap::lookup(ManagedRpcServer *rpcsrv) {
    auto iter = _map.find(rpcsrv->getName());
    LOG_ASSERT(iter != _map.end());
    PerService & psd = iter->second;
    LOG_ASSERT(psd.srv.get() == rpcsrv);
    return psd;
}

ServiceMapHistory & LocalRpcMonitorMap::history() {
    return _history;
}

void LocalRpcMonitorMap::addLocal(const ServiceMapping &mapping,
                                  std::unique_ptr<ScriptCommand> inflight)
{
    LOG(debug, "try local add: mapping %s->%s",
        mapping.name.c_str(), mapping.spec.c_str());
    auto old = _map.find(mapping.name);
    if (old != _map.end()) {
        const PerService & exists = old->second;
        if (exists.spec() == mapping.spec) {
            LOG(debug, "added mapping %s->%s was already present",
                mapping.name.c_str(), mapping.spec.c_str());
            inflight->doneHandler(OkState(0, "already registered"));
            return;
        }
        LOG(warning, "tried addLocal for mapping %s->%s, but already had conflicting mapping %s->%s",
            mapping.name.c_str(), mapping.spec.c_str(),
            exists.name().c_str(), exists.spec().c_str());
        inflight->doneHandler(OkState(FRTE_RPC_METHOD_FAILED, "conflict"));
        return;
    }
    auto [ iter, was_inserted ] =
        _map.try_emplace(mapping.name, localService(mapping, std::move(inflight)));
    LOG_ASSERT(was_inserted);
}

void LocalRpcMonitorMap::add(const ServiceMapping &mapping) {
    LOG(debug, "try add: mapping %s->%s",
        mapping.name.c_str(), mapping.spec.c_str());
    auto old = _map.find(mapping.name);
    if (old != _map.end()) {
        PerService & exists = old->second;
        if (exists.spec() == mapping.spec) {
            LOG(debug, "added mapping %s->%s was already present",
                mapping.name.c_str(), mapping.spec.c_str());
            exists.localOnly = false;
            return;
        }
        PerService removed = std::move(exists);
        _map.erase(old);
        LOG(warning, "added mapping %s->%s, but already had conflicting mapping %s->%s",
            mapping.name.c_str(), mapping.spec.c_str(),
            removed.name().c_str(), removed.spec().c_str());
        if (removed.inflight) {
            auto target = std::move(removed.inflight);
            target->doneHandler(OkState(13, "conflict during initialization"));
        }
        if (removed.up) {
            _dispatcher.remove(removed.mapping());
        }
    }
    auto [ iter, was_inserted ] =
        _map.try_emplace(mapping.name, globalService(mapping));
    LOG_ASSERT(was_inserted);
}

void LocalRpcMonitorMap::remove(const ServiceMapping &mapping) {
    auto iter = _map.find(mapping.name);
    if (iter != _map.end()) {
        PerService removed = std::move(iter->second);
        _map.erase(iter);
        LOG(debug, "remove: mapping %s->%s", mapping.name.c_str(), mapping.spec.c_str());
        if (mapping.spec != removed.spec()) {
            LOG(warning, "inconsistent specs for name '%s': had '%s', but was asked to remove '%s'",
                mapping.name.c_str(),
                removed.spec().c_str(),
                mapping.spec.c_str());
        }
        if (removed.inflight) {
            auto target = std::move(removed.inflight);
            target->doneHandler(OkState(13, "removed during initialization"));
        }
        if (removed.up) {
            _dispatcher.remove(removed.mapping());
        }
    } else {
        LOG(debug, "tried to remove non-existing mapping %s->%s",
            mapping.name.c_str(), mapping.spec.c_str());
    }
}

void LocalRpcMonitorMap::notifyFailedRpcSrv(ManagedRpcServer *rpcsrv, std::string) {
    auto &psd = lookup(rpcsrv);
    LOG(debug, "failed: %s->%s", psd.name().c_str(), psd.spec().c_str());
    if (psd.inflight) {
        auto target = std::move(psd.inflight);
        target->doneHandler(OkState(13, "failed check using listNames callback"));
    }
    if (psd.localOnly) {
        PerService removed = std::move(psd);
        auto iter = _map.find(removed.name());
        _map.erase(iter);
        if (removed.up) {
            _dispatcher.remove(removed.mapping());
        }
        _delete.later(std::move(removed.srv));
    } else if (psd.up) {
        psd.up = false;
        _dispatcher.remove(psd.mapping());
    }
}

void LocalRpcMonitorMap::notifyOkRpcSrv(ManagedRpcServer *rpcsrv) {
    auto &psd = lookup(rpcsrv);
    LOG(debug, "ok: %s->%s", psd.name().c_str(), psd.spec().c_str());
    if (psd.inflight) {
        auto target = std::move(psd.inflight);
        target->doneHandler(OkState());
    }
    if (! psd.up) {
        psd.up = true;
        _dispatcher.add(psd.mapping());
    }
}

FRT_Supervisor * LocalRpcMonitorMap::getSupervisor() {
    return &_supervisor;
}

} // namespace slobrok
<|endoftext|>


<commit_before>/*
 * D3D11RenderSystem_Textures.cpp
 *
 * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
 * See "LICENSE.txt" for license information.
 */

#include "D3D11RenderSystem.h"
#include "D3D11Types.h"
#include "../DXCommon/DXCore.h"
#include "../CheckedCast.h"
#include "../Assertion.h"
#include "../../Core/Helper.h"

namespace LLGL
{

/* ----- Textures ----- */

Texture* D3D11RenderSystem::CreateTexture(const TextureDescriptor& textureDesc, const ImageDescriptor* imageDesc)
{
    /* Create texture object and store type */
    auto texture = MakeUnique<D3D11Texture>(textureDesc.type);

    /* Modify number of layers */
    auto descD3D = textureDesc;

    switch (descD3D.type)
    {
        case TextureType::Texture1D:
            descD3D.texture1DDesc.layers = 1;
            break;
        case TextureType::Texture2D:
            descD3D.texture2DDesc.layers = 1;
            break;
        case TextureType::TextureCube:
            descD3D.textureCubeDesc.layers = 6;
            break;
        case TextureType::TextureCubeArray:
            descD3D.textureCubeDesc.layers *= 6;
            break;
        default:
            break;
    }

    /* Bulid generic texture */
    switch (descD3D.type)
    {
        case TextureType::Texture1D:
        case TextureType::Texture1DArray:
            BuildGenericTexture1D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS);
            break;
        case TextureType::Texture2D:
        case TextureType::Texture2DArray:
            BuildGenericTexture2D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS);
            break;
        case TextureType::Texture3D:
            BuildGenericTexture3D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS);
            break;
        case TextureType::TextureCube:
        case TextureType::TextureCubeArray:
            BuildGenericTexture2D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS | D3D11_RESOURCE_MISC_TEXTURECUBE);
            break;
        default:
            throw std::invalid_argument("failed to create texture with invalid texture type");
            break;
    }

    return TakeOwnership(textures_, std::move(texture));
}

void D3D11RenderSystem::Release(Texture& texture)
{
    RemoveFromUniqueSet(textures_, &texture);
}

TextureDescriptor D3D11RenderSystem::QueryTextureDescriptor(const Texture& texture)
{
    /* Get D3D hardware texture resource */
    auto& textureD3D = LLGL_CAST(const D3D11Texture&, texture);
    const auto& hwTex = textureD3D.GetHardwareTexture();

    /* Initialize texture descriptor */
    TextureDescriptor texDesc;

    texDesc.type = texture.GetType();

    /* Get resource dimension to query the respective D3D descriptor */
    D3D11_RESOURCE_DIMENSION dimension;
    hwTex.resource->GetType(&dimension);

    switch (dimension)
    {
        case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
        {
            /* Query descriptor from 1D texture */
            D3D11_TEXTURE1D_DESC desc;
            hwTex.tex1D->GetDesc(&desc);

            texDesc.format                  = D3D11Types::Unmap(desc.Format);
            texDesc.texture1DDesc.width     = static_cast<int>(desc.Width);
            texDesc.texture1DDesc.layers    = desc.ArraySize;
        }
        break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
        {
            /* Query descriptor from 2D texture */
            D3D11_TEXTURE2D_DESC desc;
            hwTex.tex2D->GetDesc(&desc);

            texDesc.format                  = D3D11Types::Unmap(desc.Format);
            texDesc.texture2DDesc.width     = static_cast<int>(desc.Width);
            texDesc.texture2DDesc.height    = static_cast<int>(desc.Height);
            texDesc.texture2DDesc.layers    = desc.ArraySize;

            if (texDesc.type == TextureType::TextureCube || texDesc.type == TextureType::TextureCubeArray)
                texDesc.textureCubeDesc.layers /= 6;
        }
        break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
        {
            /* Query descriptor from 3D texture */
            D3D11_TEXTURE3D_DESC desc;
            hwTex.tex3D->GetDesc(&desc);

            texDesc.format                  = D3D11Types::Unmap(desc.Format);
            texDesc.texture3DDesc.width     = static_cast<int>(desc.Width);
            texDesc.texture3DDesc.height    = static_cast<int>(desc.Height);
            texDesc.texture3DDesc.depth     = static_cast<int>(desc.Depth);
        }
        break;
    }

    return texDesc;
}

void D3D11RenderSystem::WriteTexture(Texture& texture, const SubTextureDescriptor& subTextureDesc, const ImageDescriptor& imageDesc)
{
    /* Determine update region */
    Gs::Vector3i position, size;

    switch (texture.GetType())
    {
        case TextureType::Texture1D:
            position.x  = subTextureDesc.texture1DDesc.x;
            size.x      = subTextureDesc.texture1DDesc.width;
            size.y      = 1;
            size.z      = 1;
            break;

        case TextureType::Texture2D:
            position.x  = subTextureDesc.texture2DDesc.x;
            position.y  = subTextureDesc.texture2DDesc.y;
            size.x      = subTextureDesc.texture2DDesc.width;
            size.y      = subTextureDesc.texture2DDesc.height;
            size.z      = 1;
            break;

        case TextureType::Texture3D:
            position.x  = subTextureDesc.texture3DDesc.x;
            position.y  = subTextureDesc.texture3DDesc.y;
            position.z  = subTextureDesc.texture3DDesc.z;
            size.x      = subTextureDesc.texture3DDesc.width;
            size.y      = subTextureDesc.texture3DDesc.height;
            size.z      = subTextureDesc.texture3DDesc.depth;
            break;

        case TextureType::TextureCube:
            position.x  = subTextureDesc.textureCubeDesc.x;
            position.y  = subTextureDesc.textureCubeDesc.y;
            position.z  = static_cast<int>(subTextureDesc.textureCubeDesc.cubeFaceOffset);
            size.x      = subTextureDesc.textureCubeDesc.width;
            size.y      = subTextureDesc.textureCubeDesc.height;
            size.z      = 1;
            break;

        case TextureType::Texture1DArray:
            position.x  = subTextureDesc.texture1DDesc.x;
            position.y  = static_cast<int>(subTextureDesc.texture1DDesc.layerOffset);
            position.z  = 0;
            size.x      = subTextureDesc.texture1DDesc.width;
            size.y      = static_cast<int>(subTextureDesc.texture1DDesc.layers);
            size.z      = 1;
            break;

        case TextureType::Texture2DArray:
            position.x  = subTextureDesc.texture2DDesc.x;
            position.y  = subTextureDesc.texture2DDesc.y;
            position.z  = static_cast<int>(subTextureDesc.texture2DDesc.layerOffset);
            size.x      = subTextureDesc.texture2DDesc.width;
            size.y      = subTextureDesc.texture2DDesc.height;
            size.z      = static_cast<int>(subTextureDesc.texture2DDesc.layers);
            break;

        case TextureType::TextureCubeArray:
            position.x  = subTextureDesc.textureCubeDesc.x;
            position.y  = subTextureDesc.textureCubeDesc.y;
            position.z  = subTextureDesc.textureCubeDesc.layerOffset * 6 + static_cast<int>(subTextureDesc.textureCubeDesc.cubeFaceOffset);
            size.x      = subTextureDesc.textureCubeDesc.width;
            size.y      = subTextureDesc.textureCubeDesc.height;
            size.z      = subTextureDesc.textureCubeDesc.cubeFaces;
            break;
    }

    /* Update generic texture at determined region */
    UpdateGenericTexture(texture, subTextureDesc.mipLevel, 0, position, size, imageDesc);
}

void D3D11RenderSystem::ReadTexture(const Texture& texture, int mipLevel, ImageFormat imageFormat, DataType dataType, void* buffer)
{
    LLGL_ASSERT_PTR(buffer);

    auto& textureD3D = LLGL_CAST(const D3D11Texture&, texture);

    //todo...
}

void D3D11RenderSystem::GenerateMips(Texture& texture)
{
    /* Generate MIP-maps for SRV of specified texture */
    auto& textureD3D = LLGL_CAST(D3D11Texture&, texture);
    context_->GenerateMips(textureD3D.GetSRV());
}

/*
 * ======= Private: =======
 */

void D3D11RenderSystem::BuildGenericTexture1D(
    D3D11Texture& textureD3D, const TextureDescriptor& descD3D,
    const ImageDescriptor* imageDesc, UINT cpuAccessFlags, UINT miscFlags)
{
    /* Setup D3D texture descriptor */
    D3D11_TEXTURE1D_DESC texDesc;
    {
        texDesc.Width           = static_cast<UINT>(descD3D.texture1DDesc.width);
        texDesc.MipLevels       = 0;
        texDesc.ArraySize       = descD3D.texture1DDesc.layers;
        texDesc.Format          = D3D11Types::Map(descD3D.format);
        texDesc.Usage           = D3D11_USAGE_DEFAULT;
        texDesc.BindFlags       = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
        texDesc.CPUAccessFlags  = cpuAccessFlags;
        texDesc.MiscFlags       = miscFlags;
    }

    /* Create D3D texture resource */
    textureD3D.CreateTexture1D(device_.Get(), texDesc);

    if (imageDesc)
    {
        textureD3D.UpdateSubresource(
            context_.Get(), 0, 0,
            CD3D11_BOX(0, 0, 0, descD3D.texture1DDesc.width, descD3D.texture1DDesc.layers, 1),
            *imageDesc, GetConfiguration().threadCount
        );
    }
    else
    {
        //TODO -> fill texture with default data
    }
}

void D3D11RenderSystem::BuildGenericTexture2D(
    D3D11Texture& textureD3D, const TextureDescriptor& descD3D,
    const ImageDescriptor* imageDesc, UINT cpuAccessFlags, UINT miscFlags)
{
    /* Setup D3D texture descriptor */
    D3D11_TEXTURE2D_DESC texDesc;
    {
        texDesc.Width               = static_cast<UINT>(descD3D.texture2DDesc.width);
        texDesc.Height              = static_cast<UINT>(descD3D.texture2DDesc.height);
        texDesc.MipLevels           = 0;
        texDesc.ArraySize           = descD3D.texture2DDesc.layers;
        texDesc.Format              = D3D11Types::Map(descD3D.format);
        texDesc.SampleDesc.Count    = 1;
        texDesc.SampleDesc.Quality  = 0;
        texDesc.Usage               = D3D11_USAGE_DEFAULT;
        texDesc.BindFlags           = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
        texDesc.CPUAccessFlags      = cpuAccessFlags;
        texDesc.MiscFlags           = miscFlags;
    }

    /* Create D3D texture resource */
    textureD3D.CreateTexture2D(device_.Get(), texDesc);

    if (imageDesc)
    {
        textureD3D.UpdateSubresource(
            context_.Get(), 0, 0,
            CD3D11_BOX(0, 0, 0, descD3D.texture2DDesc.width, descD3D.texture2DDesc.height, descD3D.texture2DDesc.layers),
            *imageDesc, GetConfiguration().threadCount
        );
    }
    else
    {
        //TODO -> fill texture with default data
    }
}

void D3D11RenderSystem::BuildGenericTexture3D(
    D3D11Texture& textureD3D, const TextureDescriptor& descD3D,
    const ImageDescriptor* imageDesc, UINT cpuAccessFlags, UINT miscFlags)
{
    /* Setup D3D texture descriptor */
    D3D11_TEXTURE3D_DESC texDesc;
    {
        texDesc.Width           = static_cast<UINT>(descD3D.texture3DDesc.width);
        texDesc.Height          = static_cast<UINT>(descD3D.texture3DDesc.height);
        texDesc.Depth           = static_cast<UINT>(descD3D.texture3DDesc.depth);
        texDesc.MipLevels       = 0;
        texDesc.Format          = D3D11Types::Map(descD3D.format);
        texDesc.Usage           = D3D11_USAGE_DEFAULT;
        texDesc.BindFlags       = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
        texDesc.CPUAccessFlags  = cpuAccessFlags;
        texDesc.MiscFlags       = miscFlags;
    }

    /* Create D3D texture resource */
    textureD3D.CreateTexture3D(device_.Get(), texDesc);

    if (imageDesc)
    {
        textureD3D.UpdateSubresource(
            context_.Get(), 0, 0,
            CD3D11_BOX(0, 0, 0, descD3D.texture3DDesc.width, descD3D.texture3DDesc.height, descD3D.texture3DDesc.depth),
            *imageDesc, GetConfiguration().threadCount
        );
    }
    else
    {
        //TODO -> fill texture with default data
    }
}

void D3D11RenderSystem::UpdateGenericTexture(
    Texture& texture, int mipLevel, unsigned int layer, const Gs::Vector3i& position, const Gs::Vector3i& size, const ImageDescriptor& imageDesc)
{
    /* Get D3D texture and update subresource */
    auto& textureD3D = LLGL_CAST(D3D11Texture&, texture);
    textureD3D.UpdateSubresource(
        context_.Get(), static_cast<UINT>(mipLevel), layer,
        CD3D11_BOX(
            position.x, position.y, position.z,
            position.x + size.x, position.y + size.y, position.z + size.z
        ),
        imageDesc, GetConfiguration().threadCount
    );
}

} // /namespace LLGL

// ================================================================================
<commit_msg>Fixed "BuildGenericTexture1D/2D" functions in D3D11RenderSystem class.<commit_after>/*
 * D3D11RenderSystem_Textures.cpp
 *
 * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
 * See "LICENSE.txt" for license information.
 */

#include "D3D11RenderSystem.h"
#include "D3D11Types.h"
#include "../DXCommon/DXCore.h"
#include "../CheckedCast.h"
#include "../Assertion.h"
#include "../../Core/Helper.h"

namespace LLGL
{

/* ----- Textures ----- */

Texture* D3D11RenderSystem::CreateTexture(const TextureDescriptor& textureDesc, const ImageDescriptor* imageDesc)
{
    /* Create texture object and store type */
    auto texture = MakeUnique<D3D11Texture>(textureDesc.type);

    /* Modify number of layers */
    auto descD3D = textureDesc;

    switch (descD3D.type)
    {
        case TextureType::Texture1D:
            descD3D.texture1DDesc.layers = 1;
            break;
        case TextureType::Texture2D:
            descD3D.texture2DDesc.layers = 1;
            break;
        case TextureType::TextureCube:
            descD3D.textureCubeDesc.layers = 6;
            break;
        case TextureType::TextureCubeArray:
            descD3D.textureCubeDesc.layers *= 6;
            break;
        default:
            break;
    }

    /* Bulid generic texture */
    switch (descD3D.type)
    {
        case TextureType::Texture1D:
        case TextureType::Texture1DArray:
            BuildGenericTexture1D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS);
            break;
        case TextureType::Texture2D:
        case TextureType::Texture2DArray:
            BuildGenericTexture2D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS);
            break;
        case TextureType::Texture3D:
            BuildGenericTexture3D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS);
            break;
        case TextureType::TextureCube:
        case TextureType::TextureCubeArray:
            BuildGenericTexture2D(*texture, descD3D, imageDesc, 0, D3D11_RESOURCE_MISC_GENERATE_MIPS | D3D11_RESOURCE_MISC_TEXTURECUBE);
            break;
        default:
            throw std::invalid_argument("failed to create texture with invalid texture type");
            break;
    }

    return TakeOwnership(textures_, std::move(texture));
}

void D3D11RenderSystem::Release(Texture& texture)
{
    RemoveFromUniqueSet(textures_, &texture);
}

TextureDescriptor D3D11RenderSystem::QueryTextureDescriptor(const Texture& texture)
{
    /* Get D3D hardware texture resource */
    auto& textureD3D = LLGL_CAST(const D3D11Texture&, texture);
    const auto& hwTex = textureD3D.GetHardwareTexture();

    /* Initialize texture descriptor */
    TextureDescriptor texDesc;

    texDesc.type = texture.GetType();

    /* Get resource dimension to query the respective D3D descriptor */
    D3D11_RESOURCE_DIMENSION dimension;
    hwTex.resource->GetType(&dimension);

    switch (dimension)
    {
        case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
        {
            /* Query descriptor from 1D texture */
            D3D11_TEXTURE1D_DESC desc;
            hwTex.tex1D->GetDesc(&desc);

            texDesc.format                  = D3D11Types::Unmap(desc.Format);
            texDesc.texture1DDesc.width     = static_cast<int>(desc.Width);
            texDesc.texture1DDesc.layers    = desc.ArraySize;
        }
        break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
        {
            /* Query descriptor from 2D texture */
            D3D11_TEXTURE2D_DESC desc;
            hwTex.tex2D->GetDesc(&desc);

            texDesc.format                  = D3D11Types::Unmap(desc.Format);
            texDesc.texture2DDesc.width     = static_cast<int>(desc.Width);
            texDesc.texture2DDesc.height    = static_cast<int>(desc.Height);
            texDesc.texture2DDesc.layers    = desc.ArraySize;

            if (texDesc.type == TextureType::TextureCube || texDesc.type == TextureType::TextureCubeArray)
                texDesc.textureCubeDesc.layers /= 6;
        }
        break;

        case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
        {
            /* Query descriptor from 3D texture */
            D3D11_TEXTURE3D_DESC desc;
            hwTex.tex3D->GetDesc(&desc);

            texDesc.format                  = D3D11Types::Unmap(desc.Format);
            texDesc.texture3DDesc.width     = static_cast<int>(desc.Width);
            texDesc.texture3DDesc.height    = static_cast<int>(desc.Height);
            texDesc.texture3DDesc.depth     = static_cast<int>(desc.Depth);
        }
        break;
    }

    return texDesc;
}

void D3D11RenderSystem::WriteTexture(Texture& texture, const SubTextureDescriptor& subTextureDesc, const ImageDescriptor& imageDesc)
{
    /* Determine update region */
    Gs::Vector3i position, size;

    switch (texture.GetType())
    {
        case TextureType::Texture1D:
            position.x  = subTextureDesc.texture1DDesc.x;
            size.x      = subTextureDesc.texture1DDesc.width;
            size.y      = 1;
            size.z      = 1;
            break;

        case TextureType::Texture2D:
            position.x  = subTextureDesc.texture2DDesc.x;
            position.y  = subTextureDesc.texture2DDesc.y;
            size.x      = subTextureDesc.texture2DDesc.width;
            size.y      = subTextureDesc.texture2DDesc.height;
            size.z      = 1;
            break;

        case TextureType::Texture3D:
            position.x  = subTextureDesc.texture3DDesc.x;
            position.y  = subTextureDesc.texture3DDesc.y;
            position.z  = subTextureDesc.texture3DDesc.z;
            size.x      = subTextureDesc.texture3DDesc.width;
            size.y      = subTextureDesc.texture3DDesc.height;
            size.z      = subTextureDesc.texture3DDesc.depth;
            break;

        case TextureType::TextureCube:
            position.x  = subTextureDesc.textureCubeDesc.x;
            position.y  = subTextureDesc.textureCubeDesc.y;
            position.z  = static_cast<int>(subTextureDesc.textureCubeDesc.cubeFaceOffset);
            size.x      = subTextureDesc.textureCubeDesc.width;
            size.y      = subTextureDesc.textureCubeDesc.height;
            size.z      = 1;
            break;

        case TextureType::Texture1DArray:
            position.x  = subTextureDesc.texture1DDesc.x;
            position.y  = static_cast<int>(subTextureDesc.texture1DDesc.layerOffset);
            position.z  = 0;
            size.x      = subTextureDesc.texture1DDesc.width;
            size.y      = static_cast<int>(subTextureDesc.texture1DDesc.layers);
            size.z      = 1;
            break;

        case TextureType::Texture2DArray:
            position.x  = subTextureDesc.texture2DDesc.x;
            position.y  = subTextureDesc.texture2DDesc.y;
            position.z  = static_cast<int>(subTextureDesc.texture2DDesc.layerOffset);
            size.x      = subTextureDesc.texture2DDesc.width;
            size.y      = subTextureDesc.texture2DDesc.height;
            size.z      = static_cast<int>(subTextureDesc.texture2DDesc.layers);
            break;

        case TextureType::TextureCubeArray:
            position.x  = subTextureDesc.textureCubeDesc.x;
            position.y  = subTextureDesc.textureCubeDesc.y;
            position.z  = subTextureDesc.textureCubeDesc.layerOffset * 6 + static_cast<int>(subTextureDesc.textureCubeDesc.cubeFaceOffset);
            size.x      = subTextureDesc.textureCubeDesc.width;
            size.y      = subTextureDesc.textureCubeDesc.height;
            size.z      = subTextureDesc.textureCubeDesc.cubeFaces;
            break;
    }

    /* Update generic texture at determined region */
    UpdateGenericTexture(texture, subTextureDesc.mipLevel, 0, position, size, imageDesc);
}

void D3D11RenderSystem::ReadTexture(const Texture& texture, int mipLevel, ImageFormat imageFormat, DataType dataType, void* buffer)
{
    LLGL_ASSERT_PTR(buffer);

    auto& textureD3D = LLGL_CAST(const D3D11Texture&, texture);

    //todo...
}

void D3D11RenderSystem::GenerateMips(Texture& texture)
{
    /* Generate MIP-maps for SRV of specified texture */
    auto& textureD3D = LLGL_CAST(D3D11Texture&, texture);
    context_->GenerateMips(textureD3D.GetSRV());
}

/*
 * ======= Private: =======
 */

void D3D11RenderSystem::BuildGenericTexture1D(
    D3D11Texture& textureD3D, const TextureDescriptor& descD3D,
    const ImageDescriptor* imageDesc, UINT cpuAccessFlags, UINT miscFlags)
{
    /* Setup D3D texture descriptor */
    D3D11_TEXTURE1D_DESC texDesc;
    {
        texDesc.Width           = static_cast<UINT>(descD3D.texture1DDesc.width);
        texDesc.MipLevels       = 0;
        texDesc.ArraySize       = descD3D.texture1DDesc.layers;
        texDesc.Format          = D3D11Types::Map(descD3D.format);
        texDesc.Usage           = D3D11_USAGE_DEFAULT;
        texDesc.BindFlags       = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
        texDesc.CPUAccessFlags  = cpuAccessFlags;
        texDesc.MiscFlags       = miscFlags;
    }

    /* Create D3D texture resource */
    textureD3D.CreateTexture1D(device_.Get(), texDesc);

    if (imageDesc)
    {
        /* Update only the first MIP-map level for each array slice */
        auto subImageDesc = *imageDesc;
        auto subImageStride = descD3D.texture1DDesc.width * ImageFormatSize(subImageDesc.format) * DataTypeSize(subImageDesc.dataType);

        for (unsigned int arraySlice = 0; arraySlice < descD3D.texture1DDesc.layers; ++arraySlice)
        {
            textureD3D.UpdateSubresource(
                context_.Get(), 0, 0,
                CD3D11_BOX(0, 0, 0, descD3D.texture1DDesc.width, 1, 1),
                subImageDesc, GetConfiguration().threadCount
            );

            subImageDesc.buffer = reinterpret_cast<const char*>(subImageDesc.buffer) + subImageStride;
        }
    }
    else
    {
        //TODO -> fill texture with default data
    }
}

void D3D11RenderSystem::BuildGenericTexture2D(
    D3D11Texture& textureD3D, const TextureDescriptor& descD3D,
    const ImageDescriptor* imageDesc, UINT cpuAccessFlags, UINT miscFlags)
{
    /* Setup D3D texture descriptor */
    D3D11_TEXTURE2D_DESC texDesc;
    {
        texDesc.Width               = static_cast<UINT>(descD3D.texture2DDesc.width);
        texDesc.Height              = static_cast<UINT>(descD3D.texture2DDesc.height);
        texDesc.MipLevels           = 0;
        texDesc.ArraySize           = descD3D.texture2DDesc.layers;
        texDesc.Format              = D3D11Types::Map(descD3D.format);
        texDesc.SampleDesc.Count    = 1;
        texDesc.SampleDesc.Quality  = 0;
        texDesc.Usage               = D3D11_USAGE_DEFAULT;
        texDesc.BindFlags           = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
        texDesc.CPUAccessFlags      = cpuAccessFlags;
        texDesc.MiscFlags           = miscFlags;
    }

    /* Create D3D texture resource */
    textureD3D.CreateTexture2D(device_.Get(), texDesc);

    if (imageDesc)
    {
        /* Update only the first MIP-map level for each array slice */
        auto subImageDesc = *imageDesc;
        auto subImageStride = descD3D.texture2DDesc.width * descD3D.texture2DDesc.height * ImageFormatSize(subImageDesc.format) * DataTypeSize(subImageDesc.dataType);

        for (unsigned int arraySlice = 0; arraySlice < descD3D.texture2DDesc.layers; ++arraySlice)
        {
            textureD3D.UpdateSubresource(
                context_.Get(), 0, arraySlice,
                CD3D11_BOX(0, 0, 0, descD3D.texture2DDesc.width, descD3D.texture2DDesc.height, 1),
                subImageDesc, GetConfiguration().threadCount
            );

            subImageDesc.buffer = reinterpret_cast<const char*>(subImageDesc.buffer) + subImageStride;
        }
    }
    else
    {
        //TODO -> fill texture with default data
    }
}

void D3D11RenderSystem::BuildGenericTexture3D(
    D3D11Texture& textureD3D, const TextureDescriptor& descD3D,
    const ImageDescriptor* imageDesc, UINT cpuAccessFlags, UINT miscFlags)
{
    /* Setup D3D texture descriptor */
    D3D11_TEXTURE3D_DESC texDesc;
    {
        texDesc.Width           = static_cast<UINT>(descD3D.texture3DDesc.width);
        texDesc.Height          = static_cast<UINT>(descD3D.texture3DDesc.height);
        texDesc.Depth           = static_cast<UINT>(descD3D.texture3DDesc.depth);
        texDesc.MipLevels       = 0;
        texDesc.Format          = D3D11Types::Map(descD3D.format);
        texDesc.Usage           = D3D11_USAGE_DEFAULT;
        texDesc.BindFlags       = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
        texDesc.CPUAccessFlags  = cpuAccessFlags;
        texDesc.MiscFlags       = miscFlags;
    }

    /* Create D3D texture resource */
    textureD3D.CreateTexture3D(device_.Get(), texDesc);

    if (imageDesc)
    {
        textureD3D.UpdateSubresource(
            context_.Get(), 0, 0,
            CD3D11_BOX(0, 0, 0, descD3D.texture3DDesc.width, descD3D.texture3DDesc.height, descD3D.texture3DDesc.depth),
            *imageDesc, GetConfiguration().threadCount
        );
    }
    else
    {
        //TODO -> fill texture with default data
    }
}

void D3D11RenderSystem::UpdateGenericTexture(
    Texture& texture, int mipLevel, unsigned int layer, const Gs::Vector3i& position, const Gs::Vector3i& size, const ImageDescriptor& imageDesc)
{
    /* Get D3D texture and update subresource */
    auto& textureD3D = LLGL_CAST(D3D11Texture&, texture);
    textureD3D.UpdateSubresource(
        context_.Get(), static_cast<UINT>(mipLevel), layer,
        CD3D11_BOX(
            position.x, position.y, position.z,
            position.x + size.x, position.y + size.y, position.z + size.z
        ),
        imageDesc, GetConfiguration().threadCount
    );
}

} // /namespace LLGL

// ================================================================================
<|endoftext|>


<commit_before>//  Natron
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "AnimationButton.h"

#include <QMouseEvent>
#include <QApplication>
#include <QDragEnterEvent>
#include <QDragLeaveEvent>
#include <QDropEvent>
#include <QDrag>
#include <QPainter>
#include <QMimeData>
#include "Gui/KnobGui.h"
#include "Engine/Project.h"
#include "Engine/Knob.h"
#include "Engine/AppManager.h"

void AnimationButton::mousePressEvent(QMouseEvent* event){
    if (event->button() == Qt::LeftButton) {
        _dragPos = event->pos();
        _dragging = true;
    }
    QPushButton::mousePressEvent(event);
}

void AnimationButton::mouseMoveEvent(QMouseEvent* event){

    if(_dragging){
        // If the left button isn't pressed anymore then return
        if (!(event->buttons() & Qt::LeftButton))
            return;
        // If the distance is too small then return
        if ((event->pos() - _dragPos).manhattanLength() < QApplication::startDragDistance())
            return;

        // initiate Drag

        _knob->onCopyAnimationActionTriggered();
        QDrag* drag = new QDrag(this);
        QMimeData* mimeData = new QMimeData;
        mimeData->setData("Animation", "");
        drag->setMimeData(mimeData);

        QFontMetrics fmetrics = fontMetrics();
        QString textFirstLine("Copying animation from:");
        QString textSecondLine(_knob->getKnob()->getDescription().c_str());
        QString textThirdLine("Drag it to another animation button.");

        int textWidth = std::max(std::max(fmetrics.width(textFirstLine), fmetrics.width(textSecondLine)),fmetrics.width(textThirdLine));

        QImage dragImg(textWidth,(fmetrics.height() + 5) * 3,QImage::Format_ARGB32);
        dragImg.fill(QColor(243,137,0));
        QPainter p(&dragImg);
        p.drawText(QPointF(0,dragImg.height() - 2.5), textThirdLine);
        p.drawText(QPointF(0,dragImg.height() - fmetrics.height() - 5), textSecondLine);
        p.drawText(QPointF(0,dragImg.height() - fmetrics.height()*2 - 10), textFirstLine);

        drag->setPixmap(QPixmap::fromImage(dragImg));

        drag->exec();
    }else{
        QPushButton::mouseMoveEvent(event);
    }
}

void AnimationButton::mouseReleaseEvent(QMouseEvent* event) {
    _dragging = false;
    QPushButton::mouseReleaseEvent(event);
}

void AnimationButton::dragEnterEvent(QDragEnterEvent* event){

    if(event->source() == this){
        return;
    }
    QStringList formats = event->mimeData()->formats();
    if (formats.contains("Animation")) {
        setCursor(Qt::DragCopyCursor);
        event->acceptProposedAction();
    }
}

void AnimationButton::dragLeaveEvent(QDragLeaveEvent* /*event*/){

}

void AnimationButton::dropEvent(QDropEvent* event){
    event->accept();
    QStringList formats = event->mimeData()->formats();
    if (formats.contains("Animation")) {
        _knob->onPasteActionTriggered();
        event->acceptProposedAction();
    }
}

void AnimationButton::dragMoveEvent(QDragMoveEvent* event) {

    QStringList formats = event->mimeData()->formats();
    if (formats.contains("Animation")) {
        event->acceptProposedAction();
    }
}

void AnimationButton::enterEvent(QEvent* /*event*/){
    if (cursor().shape() != Qt::OpenHandCursor) {
        setCursor(Qt::OpenHandCursor);
    }
}

void AnimationButton::leaveEvent(QEvent* /*event*/){
    if (cursor().shape() == Qt::OpenHandCursor) {
        setCursor(Qt::ArrowCursor);
    }
}
<commit_msg>fix warning<commit_after>//  Natron
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "AnimationButton.h"

#include "Global/Macros.h"
CLANG_DIAG_OFF(unused-private-field)
// /opt/local/include/QtGui/qmime.h:119:10: warning: private field 'type' is not used [-Wunused-private-field]
#include <QMouseEvent>
CLANG_DIAG_ON(unused-private-field)
#include <QApplication>
#include <QDragEnterEvent>
#include <QDragLeaveEvent>
#include <QDropEvent>
#include <QDrag>
#include <QPainter>
#include <QMimeData>
#include "Gui/KnobGui.h"
#include "Engine/Project.h"
#include "Engine/Knob.h"
#include "Engine/AppManager.h"

void AnimationButton::mousePressEvent(QMouseEvent* event){
    if (event->button() == Qt::LeftButton) {
        _dragPos = event->pos();
        _dragging = true;
    }
    QPushButton::mousePressEvent(event);
}

void AnimationButton::mouseMoveEvent(QMouseEvent* event){

    if(_dragging){
        // If the left button isn't pressed anymore then return
        if (!(event->buttons() & Qt::LeftButton))
            return;
        // If the distance is too small then return
        if ((event->pos() - _dragPos).manhattanLength() < QApplication::startDragDistance())
            return;

        // initiate Drag

        _knob->onCopyAnimationActionTriggered();
        QDrag* drag = new QDrag(this);
        QMimeData* mimeData = new QMimeData;
        mimeData->setData("Animation", "");
        drag->setMimeData(mimeData);

        QFontMetrics fmetrics = fontMetrics();
        QString textFirstLine("Copying animation from:");
        QString textSecondLine(_knob->getKnob()->getDescription().c_str());
        QString textThirdLine("Drag it to another animation button.");

        int textWidth = std::max(std::max(fmetrics.width(textFirstLine), fmetrics.width(textSecondLine)),fmetrics.width(textThirdLine));

        QImage dragImg(textWidth,(fmetrics.height() + 5) * 3,QImage::Format_ARGB32);
        dragImg.fill(QColor(243,137,0));
        QPainter p(&dragImg);
        p.drawText(QPointF(0,dragImg.height() - 2.5), textThirdLine);
        p.drawText(QPointF(0,dragImg.height() - fmetrics.height() - 5), textSecondLine);
        p.drawText(QPointF(0,dragImg.height() - fmetrics.height()*2 - 10), textFirstLine);

        drag->setPixmap(QPixmap::fromImage(dragImg));

        drag->exec();
    }else{
        QPushButton::mouseMoveEvent(event);
    }
}

void AnimationButton::mouseReleaseEvent(QMouseEvent* event) {
    _dragging = false;
    QPushButton::mouseReleaseEvent(event);
}

void AnimationButton::dragEnterEvent(QDragEnterEvent* event){

    if(event->source() == this){
        return;
    }
    QStringList formats = event->mimeData()->formats();
    if (formats.contains("Animation")) {
        setCursor(Qt::DragCopyCursor);
        event->acceptProposedAction();
    }
}

void AnimationButton::dragLeaveEvent(QDragLeaveEvent* /*event*/){

}

void AnimationButton::dropEvent(QDropEvent* event){
    event->accept();
    QStringList formats = event->mimeData()->formats();
    if (formats.contains("Animation")) {
        _knob->onPasteActionTriggered();
        event->acceptProposedAction();
    }
}

void AnimationButton::dragMoveEvent(QDragMoveEvent* event) {

    QStringList formats = event->mimeData()->formats();
    if (formats.contains("Animation")) {
        event->acceptProposedAction();
    }
}

void AnimationButton::enterEvent(QEvent* /*event*/){
    if (cursor().shape() != Qt::OpenHandCursor) {
        setCursor(Qt::OpenHandCursor);
    }
}

void AnimationButton::leaveEvent(QEvent* /*event*/){
    if (cursor().shape() == Qt::OpenHandCursor) {
        setCursor(Qt::ArrowCursor);
    }
}
<|endoftext|>


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

#include <config.h>

// When defined, different heap allocators can be used via an environment
// variable set before running the program.  This may reduce the amount
// of inlining that we get with malloc/free/etc.  Disabling makes it
// so that only tcmalloc can be used.
#define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING

// TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth
// from the "user code" so that debugging tools (HeapChecker) can work.

// __THROW is defined in glibc systems.  It means, counter-intuitively,
// "This function will never throw an exception."  It's an optional
// optimization tool, but we may need to use it to match glibc prototypes.
#ifndef __THROW    // I guess we're not on a glibc system
# define __THROW   // __THROW is just an optimization, so ok to make it ""
#endif

// new_mode behaves similarly to MSVC's _set_new_mode.
// If flag is 0 (default), calls to malloc will behave normally.
// If flag is 1, calls to malloc will behave like calls to new,
// and the std_new_handler will be invoked on failure.
// Can be set by calling _set_new_mode().
static int new_mode = 0;

typedef enum {
  TCMALLOC,    // TCMalloc is the default allocator.
  JEMALLOC,    // JEMalloc
  WINDEFAULT,  // Windows Heap
  WINLFH,      // Windows LFH Heap
} Allocator;

// This is the default allocator.
static Allocator allocator = JEMALLOC;

// We include tcmalloc and the win_allocator to get as much inlining as
// possible.
#include "tcmalloc.cc"
#include "win_allocator.cc"

// Forward declarations from jemalloc.
extern "C" {
void* je_malloc(size_t s);
void* je_realloc(void* p, size_t s);
void je_free(void* s);
size_t je_msize(void* p);
bool je_malloc_init_hard();
}

extern "C" {

// Call the new handler, if one has been set.
// Returns true on successfully calling the handler, false otherwise.
inline bool call_new_handler(bool nothrow) {
  // Get the current new handler.  NB: this function is not
  // thread-safe.  We make a feeble stab at making it so here, but
  // this lock only protects against tcmalloc interfering with
  // itself, not with other libraries calling set_new_handler.
  std::new_handler nh;
  {
    SpinLockHolder h(&set_new_handler_lock);
    nh = std::set_new_handler(0);
    (void) std::set_new_handler(nh);
  }
#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
  if (!nh)
    return false;
  // Since exceptions are disabled, we don't really know if new_handler
  // failed.  Assume it will abort if it fails.
  (*nh)();
  return false;  // break out of the retry loop.
#else
  // If no new_handler is established, the allocation failed.
  if (!nh) {
    if (nothrow)
      return 0;
    throw std::bad_alloc();
  }
  // Otherwise, try the new_handler.  If it returns, retry the
  // allocation.  If it throws std::bad_alloc, fail the allocation.
  // if it throws something else, don't interfere.
  try {
    (*nh)();
  } catch (const std::bad_alloc&) {
    if (!nothrow)
      throw;
    return p;
  }
#endif  // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
}

void* malloc(size_t size) __THROW {
  void* ptr;
  for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
    switch (allocator) {
      case JEMALLOC:
        ptr = je_malloc(size);
        break;
      case WINDEFAULT:
      case WINLFH:
        ptr = win_heap_malloc(size);
        break;
      case TCMALLOC:
      default:
        ptr = do_malloc(size);
        break;
    }
#else
    // TCMalloc case.
    ptr = do_malloc(size);
#endif
    if (ptr)
      return ptr;

    if (!new_mode || !call_new_handler(true))
      break;
  }
  return ptr;
}

void free(void* p) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  switch (allocator) {
    case JEMALLOC:
      je_free(p);
      return;
    case WINDEFAULT:
    case WINLFH:
      win_heap_free(p);
      return;
  }
#endif
  // TCMalloc case.
  do_free(p);
}

void* realloc(void* ptr, size_t size) __THROW {
  void* new_ptr;
  for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
    switch (allocator) {
      case JEMALLOC:
        new_ptr = je_realloc(ptr, size);
        break;
      case WINDEFAULT:
      case WINLFH:
        new_ptr = win_heap_realloc(ptr, size);
        break;
      case TCMALLOC:
      default:
        new_ptr = do_realloc(ptr, size);
        break;
    }
#else
    // TCMalloc case.
    new_ptr = do_realloc(ptr, size);
#endif

    // Subtle warning:  NULL return does not alwas indicate out-of-memory.  If
    // the requested new size is zero, realloc should free the ptr and return
    // NULL.
    if (new_ptr || !size)
      return new_ptr;
    if (!new_mode || !call_new_handler(true))
      break;
  }
  return new_ptr;
}

// TODO(mbelshe): Implement this for other allocators.
void malloc_stats(void) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  switch (allocator) {
    case JEMALLOC:
      // No stats.
      return;
    case WINDEFAULT:
    case WINLFH:
      // No stats.
      return;
  }
#endif
  tc_malloc_stats();
}

#ifdef WIN32

extern "C" size_t _msize(void* p) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  switch (allocator) {
    case JEMALLOC:
      return je_msize(p);
    case WINDEFAULT:
    case WINLFH:
      return win_heap_msize(p);
  }
#endif
  return MallocExtension::instance()->GetAllocatedSize(p);
}

// This is included to resolve references from libcmt.
extern "C" intptr_t _get_heap_handle() {
  return 0;
}

// The CRT heap initialization stub.
extern "C" int _heap_init() {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  const char* override = GetenvBeforeMain("CHROME_ALLOCATOR");
  if (override) {
    if (!stricmp(override, "jemalloc"))
      allocator = JEMALLOC;
    else if (!stricmp(override, "winheap"))
      allocator = WINDEFAULT;
    else if (!stricmp(override, "winlfh"))
      allocator = WINLFH;
    else if (!stricmp(override, "tcmalloc"))
      allocator = TCMALLOC;
  }

  switch (allocator) {
    case JEMALLOC:
      return je_malloc_init_hard() ? 0 : 1;
    case WINDEFAULT:
      return win_heap_init(false) ? 1 : 0;
    case WINLFH:
      return win_heap_init(true) ? 1 : 0;
    case TCMALLOC:
    default:
      // fall through
      break;
  }
#endif
  // Initializing tcmalloc.
  // We intentionally leak this object.  It lasts for the process
  // lifetime.  Trying to teardown at _heap_term() is so late that
  // you can't do anything useful anyway.
  new TCMallocGuard();
  return 1;
}

// The CRT heap cleanup stub.
extern "C" void _heap_term() {}

// We set this to 1 because part of the CRT uses a check of _crtheap != 0
// to test whether the CRT has been initialized.  Once we've ripped out
// the allocators from libcmt, we need to provide this definition so that
// the rest of the CRT is still usable.
extern "C" void* _crtheap = reinterpret_cast<void*>(1);

#endif  // WIN32

#include "generic_allocators.cc"

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

#include <config.h>

// When defined, different heap allocators can be used via an environment
// variable set before running the program.  This may reduce the amount
// of inlining that we get with malloc/free/etc.  Disabling makes it
// so that only tcmalloc can be used.
#define ENABLE_DYNAMIC_ALLOCATOR_SWITCHING

// TODO(mbelshe): Ensure that all calls to tcmalloc have the proper call depth
// from the "user code" so that debugging tools (HeapChecker) can work.

// __THROW is defined in glibc systems.  It means, counter-intuitively,
// "This function will never throw an exception."  It's an optional
// optimization tool, but we may need to use it to match glibc prototypes.
#ifndef __THROW    // I guess we're not on a glibc system
# define __THROW   // __THROW is just an optimization, so ok to make it ""
#endif

// new_mode behaves similarly to MSVC's _set_new_mode.
// If flag is 0 (default), calls to malloc will behave normally.
// If flag is 1, calls to malloc will behave like calls to new,
// and the std_new_handler will be invoked on failure.
// Can be set by calling _set_new_mode().
static int new_mode = 0;

typedef enum {
  TCMALLOC,    // TCMalloc is the default allocator.
  JEMALLOC,    // JEMalloc
  WINDEFAULT,  // Windows Heap
  WINLFH,      // Windows LFH Heap
} Allocator;

// This is the default allocator.
static Allocator allocator = TCMALLOC;

// We include tcmalloc and the win_allocator to get as much inlining as
// possible.
#include "tcmalloc.cc"
#include "win_allocator.cc"

// Forward declarations from jemalloc.
extern "C" {
void* je_malloc(size_t s);
void* je_realloc(void* p, size_t s);
void je_free(void* s);
size_t je_msize(void* p);
bool je_malloc_init_hard();
}

extern "C" {

// Call the new handler, if one has been set.
// Returns true on successfully calling the handler, false otherwise.
inline bool call_new_handler(bool nothrow) {
  // Get the current new handler.  NB: this function is not
  // thread-safe.  We make a feeble stab at making it so here, but
  // this lock only protects against tcmalloc interfering with
  // itself, not with other libraries calling set_new_handler.
  std::new_handler nh;
  {
    SpinLockHolder h(&set_new_handler_lock);
    nh = std::set_new_handler(0);
    (void) std::set_new_handler(nh);
  }
#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
  if (!nh)
    return false;
  // Since exceptions are disabled, we don't really know if new_handler
  // failed.  Assume it will abort if it fails.
  (*nh)();
  return false;  // break out of the retry loop.
#else
  // If no new_handler is established, the allocation failed.
  if (!nh) {
    if (nothrow)
      return 0;
    throw std::bad_alloc();
  }
  // Otherwise, try the new_handler.  If it returns, retry the
  // allocation.  If it throws std::bad_alloc, fail the allocation.
  // if it throws something else, don't interfere.
  try {
    (*nh)();
  } catch (const std::bad_alloc&) {
    if (!nothrow)
      throw;
    return p;
  }
#endif  // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
}

void* malloc(size_t size) __THROW {
  void* ptr;
  for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
    switch (allocator) {
      case JEMALLOC:
        ptr = je_malloc(size);
        break;
      case WINDEFAULT:
      case WINLFH:
        ptr = win_heap_malloc(size);
        break;
      case TCMALLOC:
      default:
        ptr = do_malloc(size);
        break;
    }
#else
    // TCMalloc case.
    ptr = do_malloc(size);
#endif
    if (ptr)
      return ptr;

    if (!new_mode || !call_new_handler(true))
      break;
  }
  return ptr;
}

void free(void* p) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  switch (allocator) {
    case JEMALLOC:
      je_free(p);
      return;
    case WINDEFAULT:
    case WINLFH:
      win_heap_free(p);
      return;
  }
#endif
  // TCMalloc case.
  do_free(p);
}

void* realloc(void* ptr, size_t size) __THROW {
  void* new_ptr;
  for (;;) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
    switch (allocator) {
      case JEMALLOC:
        new_ptr = je_realloc(ptr, size);
        break;
      case WINDEFAULT:
      case WINLFH:
        new_ptr = win_heap_realloc(ptr, size);
        break;
      case TCMALLOC:
      default:
        new_ptr = do_realloc(ptr, size);
        break;
    }
#else
    // TCMalloc case.
    new_ptr = do_realloc(ptr, size);
#endif

    // Subtle warning:  NULL return does not alwas indicate out-of-memory.  If
    // the requested new size is zero, realloc should free the ptr and return
    // NULL.
    if (new_ptr || !size)
      return new_ptr;
    if (!new_mode || !call_new_handler(true))
      break;
  }
  return new_ptr;
}

// TODO(mbelshe): Implement this for other allocators.
void malloc_stats(void) __THROW {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  switch (allocator) {
    case JEMALLOC:
      // No stats.
      return;
    case WINDEFAULT:
    case WINLFH:
      // No stats.
      return;
  }
#endif
  tc_malloc_stats();
}

#ifdef WIN32

extern "C" size_t _msize(void* p) {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  switch (allocator) {
    case JEMALLOC:
      return je_msize(p);
    case WINDEFAULT:
    case WINLFH:
      return win_heap_msize(p);
  }
#endif
  return MallocExtension::instance()->GetAllocatedSize(p);
}

// This is included to resolve references from libcmt.
extern "C" intptr_t _get_heap_handle() {
  return 0;
}

// The CRT heap initialization stub.
extern "C" int _heap_init() {
#ifdef ENABLE_DYNAMIC_ALLOCATOR_SWITCHING
  const char* override = GetenvBeforeMain("CHROME_ALLOCATOR");
  if (override) {
    if (!stricmp(override, "jemalloc"))
      allocator = JEMALLOC;
    else if (!stricmp(override, "winheap"))
      allocator = WINDEFAULT;
    else if (!stricmp(override, "winlfh"))
      allocator = WINLFH;
    else if (!stricmp(override, "tcmalloc"))
      allocator = TCMALLOC;
  }

  switch (allocator) {
    case JEMALLOC:
      return je_malloc_init_hard() ? 0 : 1;
    case WINDEFAULT:
      return win_heap_init(false) ? 1 : 0;
    case WINLFH:
      return win_heap_init(true) ? 1 : 0;
    case TCMALLOC:
    default:
      // fall through
      break;
  }
#endif
  // Initializing tcmalloc.
  // We intentionally leak this object.  It lasts for the process
  // lifetime.  Trying to teardown at _heap_term() is so late that
  // you can't do anything useful anyway.
  new TCMallocGuard();
  return 1;
}

// The CRT heap cleanup stub.
extern "C" void _heap_term() {}

// We set this to 1 because part of the CRT uses a check of _crtheap != 0
// to test whether the CRT has been initialized.  Once we've ripped out
// the allocators from libcmt, we need to provide this definition so that
// the rest of the CRT is still usable.
extern "C" void* _crtheap = reinterpret_cast<void*>(1);

#endif  // WIN32

#include "generic_allocators.cc"

}  // extern C
<|endoftext|>