<commit_before>#include <ros/ros.h>
#include <humanoid_catching/CalculateTorques.h>
#include <Moby/qpOASES.h>
#include <Ravelin/VectorNd.h>
#include <Ravelin/MatrixNd.h>
#include <Ravelin/Quatd.h>
#include <Ravelin/Opsd.h>
#include <Moby/qpOASES.h>
#include <Ravelin/LinAlgd.h>

namespace {
using namespace std;
using namespace humanoid_catching;
using namespace Ravelin;

static const double GRAVITY = 9.81;

class Balancer {
private:
    //! Node handle
    ros::NodeHandle nh;

    //! Private nh
    ros::NodeHandle pnh;

    //! Balancer Service
    ros::ServiceServer balancerService;

public:
   Balancer() :
     pnh("~") {

       balancerService = nh.advertiseService("/balancer/torques",
            &Balancer::calculateTorques, this);
	}

private:

    /**
     * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d
     * @param v3 geometry_msgs::Vector3
     * @return Ravelin Vector3d
     */
    static Vector3d toVector(const geometry_msgs::Vector3& v3) {
        Vector3d v;
        v[0] = v3.x;
        v[1] = v3.y;
        v[2] = v3.z;
        return v;
    }

    /**
     * Convert a geometry_msgs::Point to a Ravelin::Vector3d
     * @param p geometry_msgs::Point
     * @return Ravelin Vector3d
     */
    static Vector3d toVector(const geometry_msgs::Point& p) {
        Vector3d v;
        v[0] = p.x;
        v[1] = p.y;
        v[2] = p.z;
        return v;
    }

    /**
     * Calculate balancing torques
     * @param req Request
     * @param res Response
     * @return Success
     */
    bool calculateTorques(humanoid_catching::CalculateTorques::Request& req,
                          humanoid_catching::CalculateTorques::Response& res) {

      ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str());

      // x
      // linear velocity of body
      const Vector3d x = toVector(req.body_velocity.linear);

      // w
      // angular velocity of body
      const Vector3d w = toVector(req.body_velocity.angular);

      // v(t)
      // | x |
      // | w |
      VectorNd v(6);
      v.set_sub_vec(0, x);
      v.set_sub_vec(3, w);

      // R
      // Pole rotation matrix
      const Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w));

      // J
      // Pole inertia matrix
      const Matrix3d J = MatrixNd(VectorNd(req.body_inertia_matrix.size(), &req.body_inertia_matrix[0]));

      // JRobot
      // Robot end effector jacobian matrix
      const Matrix3d JRobot = MatrixNd(VectorNd(req.jacobian_matrix.size(), &req.jacobian_matrix[0]));

      // RJR_t
      Matrix3d RJR;
      Matrix3d RTranspose = R.transpose(RTranspose);
      RJR = R.mult(J, RJR).mult(RTranspose, RJR);

      // M
      // | Im   0 |
      // | 0 RJR_t|
      MatrixNd M(6, 6);
      M.set_zero(M.rows(), M.columns());
      M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass);
      M.set_sub_mat(3, 3, RJR);

      // delta t
      double deltaT = req.time_delta.toSec();

      // Working vector
      Vector3d tempVector;

      // fext
      // | g           |
      // | -w x RJR_tw |
      VectorNd fExt(6);
      fExt[0] = 0;
      fExt[1] = 0;
      fExt[2] = GRAVITY;
      fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector)));

      // n_hat
      // x component of ground contact position
      Vector3d nHat;
      nHat[0] = req.ground_contact.x;
      nHat[1] = 0;
      nHat[2] = 0;

      // s_hat
      // s component of contact position
      Vector3d sHat;
      nHat[0] = 0;
      nHat[1] = req.ground_contact.y;
      nHat[2] = 0;

      // t_hat
      // z component of contact position
      Vector3d tHat;
      tHat[0] = 0;
      tHat[1] = 0;
      tHat[2] = req.ground_contact.z;

      // q_hat
      // contact normal
      const Vector3d qHat = toVector(req.contact_normal);

      // p
      // contact point
      const Vector3d p = toVector(req.ground_contact);

      // x_bar
      // pole COM
      const Vector3d xBar = toVector(req.body_com.position);

      // r
      const Vector3d r = p - xBar;

      // N
      // | n_hat     |
      // | r x n_hat |
      VectorNd N(6);
      N.set_sub_vec(0, nHat);
      N.set_sub_vec(3, r.cross(nHat, tempVector));

      // S
      // | s_hat     |
      // | r x s_hat |
      VectorNd S(6);
      S.set_sub_vec(0, sHat);
      S.set_sub_vec(3, r.cross(sHat, tempVector));

      // T
      // | t_hat     |
      // | r x t_hat |
      VectorNd T(6);
      T.set_sub_vec(0, tHat);
      T.set_sub_vec(3, r.cross(tHat, tempVector));

      // Q
      VectorNd Q(6);
      Q.set_sub_vec(0, qHat);
      Q.set_sub_vec(3, -r.cross(qHat, tempVector));

      // Result vector
      // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta)
      const int torqueIdx = 0;
      const int fNIdx = req.torque_limits.size();
      const int fSIdx = fNIdx + 1;
      const int fTIdx = fSIdx + 1;
      const int fRobotIdx = fTIdx + 1;
      const int vTDeltaIdx = fRobotIdx + 1;
      VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6);

      // Set up minimization function
      MatrixNd H(6, z.size());
      H.set_sub_mat(0, vTDeltaIdx, M);

      VectorNd c(6);
      c.set_zero(c.rows());

      // Linear equality constraints
      MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size());
      VectorNd b(1 * 2 + req.torque_limits.size() + 6);

      // Sv(t + t_delta) = 0 (no tangent velocity)
      unsigned idx = 0;
      A.set_sub_mat(idx, vTDeltaIdx, S);
      b.set_sub_vec(idx, VectorNd::zero(1));
      idx += 1;

      // Tv(t + t_delta) = 0 (no tangent velocity)
      A.set_sub_mat(idx, vTDeltaIdx, T);
      b.set_sub_vec(idx, VectorNd::zero(1));
      idx += 1;

      // J_robot(transpose) * Q(transpose) * f_robot = torques
      // Transformed to:
      // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0
      MatrixNd JQ(req.torque_limits.size(), 1);
      MatrixNd Jt(JRobot.columns(), JRobot.rows());
      JRobot.transpose(Jt);
      Jt.mult(MatrixNd(Q, eTranspose), JQ);
      A.set_sub_mat(idx, fRobotIdx, JQ);
      A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate());
      b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size()));
      idx += req.torque_limits.size();

      // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot)
      // Manipulated to fit constraint form
      // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta)
      LinAlgd linAlgd;
      MatrixNd MInverse = M;
      linAlgd.pseudo_invert(MInverse);

      MatrixNd MInverseN(MInverse.rows(), N.columns());
      MInverse.mult(N, MInverseN);
      A.set_sub_mat(idx, fNIdx, MInverseN);

      MatrixNd MInverseS(MInverse.rows(), S.columns());
      MInverse.mult(S, MInverseS);
      A.set_sub_mat(idx, fSIdx, MInverseS);

      MatrixNd MInverseT(MInverse.rows(), T.columns());
      MInverse.mult(T, MInverseT);
      A.set_sub_mat(idx, fTIdx, MInverseT);

      MatrixNd MInverseQ(MInverse.rows(), Q.columns());
      MInverse.mult(Q, MInverseQ);
      MInverseQ *= deltaT;
      A.set_sub_mat(idx, fRobotIdx, MInverseQ);

      A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate());

      VectorNd MInverseFExt(6);
      MInverseFExt.set_zero();
      MInverse.mult(fExt, MInverseFExt, deltaT);
      MInverseFExt.negate() -= v;
      b.set_sub_vec(idx, MInverseFExt);

      // Linear inequality constraints
      MatrixNd Mc(6, z.size());
      VectorNd q(6);

      // Nv(t) >= 0 (non-negative normal velocity)
      Mc.set_sub_mat(0, vTDeltaIdx, N);
      q.set_sub_vec(0, VectorNd::zero(6));

      // Solution variable constraint
      VectorNd lb(z.size());
      VectorNd ub(z.size());

      // Torque constraints
      unsigned int bound = 0;
      for (bound; bound < req.torque_limits.size(); ++bound) {
        lb[bound] = req.torque_limits[bound].minimum;
        ub[bound] = req.torque_limits[bound].maximum;
      }

      // f_n >= 0
      lb[bound] = 0;
      ub[bound] = INFINITY;
      ++bound;

      // f_s (no constraints)
      lb[bound] = INFINITY;
      ub[bound] = INFINITY;
      ++bound;

      // f_t (no constraints)
      lb[bound] = INFINITY;
      ub[bound] = INFINITY;
      ++bound;

      // f_robot >= 0
      lb[bound] = 0;
      ub[bound] = INFINITY;
      ++bound;

      // v_t (no constraints)
      for (bound; bound < z.size(); ++bound) {
        lb[bound] = INFINITY;
        ub[bound] = INFINITY;
      }

      // Call solver
      Moby::QPOASES qp;
      if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){
            ROS_ERROR("QP failed to find feasible point");
            return false;
      }

      ROS_INFO_STREAM("QP solved successfully: " << z);

      // Copy over result
      res.torques.resize(req.torque_limits.size());
      for (unsigned int i = 0; i < z.size(); ++i) {
        res.torques[i] = z[i];
      }
      return true;
    }
  };
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "balancer");
  Balancer bal;
  ros::spin();
}
<commit_msg>Add printing code<commit_after>#include <ros/ros.h>
#include <humanoid_catching/CalculateTorques.h>
#include <Moby/qpOASES.h>
#include <Ravelin/VectorNd.h>
#include <Ravelin/MatrixNd.h>
#include <Ravelin/Quatd.h>
#include <Ravelin/Opsd.h>
#include <Moby/qpOASES.h>
#include <Ravelin/LinAlgd.h>

namespace {
using namespace std;
using namespace humanoid_catching;
using namespace Ravelin;

static const double GRAVITY = 9.81;

class Balancer {
private:
    //! Node handle
    ros::NodeHandle nh;

    //! Private nh
    ros::NodeHandle pnh;

    //! Balancer Service
    ros::ServiceServer balancerService;

public:
   Balancer() :
     pnh("~") {

       balancerService = nh.advertiseService("/balancer/torques",
            &Balancer::calculateTorques, this);
	}

private:

    /**
     * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d
     * @param v3 geometry_msgs::Vector3
     * @return Ravelin Vector3d
     */
    static Vector3d toVector(const geometry_msgs::Vector3& v3) {
        Vector3d v;
        v[0] = v3.x;
        v[1] = v3.y;
        v[2] = v3.z;
        return v;
    }

    /**
     * Convert a geometry_msgs::Point to a Ravelin::Vector3d
     * @param p geometry_msgs::Point
     * @return Ravelin Vector3d
     */
    static Vector3d toVector(const geometry_msgs::Point& p) {
        Vector3d v;
        v[0] = p.x;
        v[1] = p.y;
        v[2] = p.z;
        return v;
    }

    /**
     * Calculate balancing torques
     * @param req Request
     * @param res Response
     * @return Success
     */
    bool calculateTorques(humanoid_catching::CalculateTorques::Request& req,
                          humanoid_catching::CalculateTorques::Response& res) {

      ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str());

      // x
      // linear velocity of body
      ROS_INFO("Calculating x vector");
      const Vector3d x = toVector(req.body_velocity.linear);
      ROS_INFO_STREAM("x: " << x);
      // w
      // angular velocity of body
      ROS_INFO("Calculating w vector");
      const Vector3d w = toVector(req.body_velocity.angular);
      ROS_INFO_STREAM("w: " << w);

      // v(t)
      // | x |
      // | w |
      ROS_INFO("Calculating v vector");
      VectorNd v(6);
      v.set_sub_vec(0, x);
      v.set_sub_vec(3, w);
      ROS_INFO_STREAM("v: " << v);

      // R
      // Pole rotation matrix
      ROS_INFO("Calculating R matrix");
      const Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w));
      ROS_INFO_STREAM("R: " << R);

      // J
      // Pole inertia matrix
      ROS_INFO("Calculating J matrix");
      ROS_INFO_STREAM("BIM: " << req.body_inertia_matrix.size());
      const Matrix3d J = Matrix3d(&req.body_inertia_matrix[0]);
      ROS_INFO_STREAM("J: " << J);

      // JRobot
      // Robot end effector jacobian matrix
      ROS_INFO("Calculating JRobot");
      const MatrixNd JRobot = MatrixNd(req.torque_limits.size(), 6, &req.jacobian_matrix[0]);
      ROS_INFO_STREAM("JRobot: " << JRobot);

      // RJR_t
      ROS_INFO("Calculating RJR");
      Matrix3d RJR;
      Matrix3d RTranspose = R.transpose(RTranspose);
      RJR = R.mult(J, RJR).mult(RTranspose, RJR);
      ROS_INFO_STREAM("RJR: " << RJR);

      // M
      // | Im   0 |
      // | 0 RJR_t|
      ROS_INFO("Calculating M");
      MatrixNd M(6, 6);
      M.set_zero(M.rows(), M.columns());
      M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass);
      M.set_sub_mat(3, 3, RJR);
      ROS_INFO_STREAM("M: " << M);

      // delta t
      double deltaT = req.time_delta.toSec();

      // Working vector
      Vector3d tempVector;

      // fext
      // | g           |
      // | -w x RJR_tw |
      ROS_INFO("Calculating fExt");
      VectorNd fExt(6);
      fExt[0] = 0;
      fExt[1] = 0;
      fExt[2] = GRAVITY;
      fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector)));
      ROS_INFO_STREAM("fExt: " << fExt);

      // n_hat
      // x component of ground contact position
      ROS_INFO("Calculating nHat");
      Vector3d nHat;
      nHat[0] = req.ground_contact.x;
      nHat[1] = 0;
      nHat[2] = 0;
      ROS_INFO_STREAM("nHat: " << nHat);

      // s_hat
      // s component of contact position
      ROS_INFO("Calculating sHat");
      Vector3d sHat;
      nHat[0] = 0;
      nHat[1] = req.ground_contact.y;
      nHat[2] = 0;
      ROS_INFO_STREAM("sHat: " << sHat);

      // t_hat
      // z component of contact position
      ROS_INFO("Calculating tHat");
      Vector3d tHat;
      tHat[0] = 0;
      tHat[1] = 0;
      tHat[2] = req.ground_contact.z;
      ROS_INFO_STREAM("tHat: " << tHat);

      // q_hat
      // contact normal
      ROS_INFO("Calculating qHat");
      const Vector3d qHat = toVector(req.contact_normal);
      ROS_INFO_STREAM("qHat: " << qHat);

      // p
      // contact point
      ROS_INFO("Calculating P");
      const Vector3d p = toVector(req.ground_contact);
      ROS_INFO_STREAM("p: " << p);

      // x_bar
      // pole COM
      ROS_INFO("Calculating xBar");
      const Vector3d xBar = toVector(req.body_com.position);
      ROS_INFO_STREAM("xBar: " << xBar);

      // r
      ROS_INFO("Calculating r");
      const Vector3d r = p - xBar;
      ROS_INFO_STREAM("r: " << r);

      // N
      // | n_hat     |
      // | r x n_hat |
      ROS_INFO("Calculating N");
      VectorNd N(6);
      N.set_sub_vec(0, nHat);
      N.set_sub_vec(3, r.cross(nHat, tempVector));
      ROS_INFO_STREAM("N: " << N);

      // S
      // | s_hat     |
      // | r x s_hat |
      ROS_INFO("Calculating S");
      VectorNd S(6);
      S.set_sub_vec(0, sHat);
      S.set_sub_vec(3, r.cross(sHat, tempVector));
      ROS_INFO_STREAM("S: " << S);

      // T
      // | t_hat     |
      // | r x t_hat |
      ROS_INFO("Calculating T");
      VectorNd T(6);
      T.set_sub_vec(0, tHat);
      T.set_sub_vec(3, r.cross(tHat, tempVector));
      ROS_INFO_STREAM("T: " << T);

      // Q
      ROS_INFO("Calculating Q");
      VectorNd Q(6);
      Q.set_sub_vec(0, qHat);
      Q.set_sub_vec(3, -r.cross(qHat, tempVector));
      ROS_INFO_STREAM("Q: " << Q);

      // Result vector
      // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta)
      const int torqueIdx = 0;
      const int fNIdx = req.torque_limits.size();
      const int fSIdx = fNIdx + 1;
      const int fTIdx = fSIdx + 1;
      const int fRobotIdx = fTIdx + 1;
      const int vTDeltaIdx = fRobotIdx + 1;
      VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6);

      // Set up minimization function
      ROS_INFO("Calculating H");
      MatrixNd H(6, z.size());
      H.set_sub_mat(0, vTDeltaIdx, M);
      ROS_INFO_STREAM("H: " << H);

      ROS_INFO("Calculating c");
      VectorNd c(6);
      c.set_zero(c.rows());
      ROS_INFO_STREAM("c: " << c);

      // Linear equality constraints
      ROS_INFO("Calculating A + b");
      MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size());
      VectorNd b(1 * 2 + req.torque_limits.size() + 6);

      ROS_INFO("Setting Sv constraint");
      // Sv(t + t_delta) = 0 (no tangent velocity)
      unsigned idx = 0;
      A.set_sub_mat(idx, vTDeltaIdx, S);
      b.set_sub_vec(idx, VectorNd::zero(1));
      idx += 1;

      ROS_INFO("Setting Tv constraint");
      // Tv(t + t_delta) = 0 (no tangent velocity)
      A.set_sub_mat(idx, vTDeltaIdx, T);
      b.set_sub_vec(idx, VectorNd::zero(1));
      idx += 1;

      ROS_INFO("Setting torque constraint");
      // J_robot(transpose) * Q(transpose) * f_robot = torques
      // Transformed to:
      // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0
      MatrixNd JQ(req.torque_limits.size(), 1);
      MatrixNd Jt = JRobot;
      Jt.transpose();
      MatrixNd Qt(Q, eTranspose);
      Jt.mult(Qt, JQ);
      A.set_sub_mat(idx, fRobotIdx, JQ);
      A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate());
      b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size()));
      idx += req.torque_limits.size();

      ROS_INFO("Setting velocity constraint");
      // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot)
      // Manipulated to fit constraint form
      // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta)
      LinAlgd linAlgd;
      MatrixNd MInverse = M;
      linAlgd.pseudo_invert(MInverse);

      MatrixNd MInverseN(MInverse.rows(), N.columns());
      MInverse.mult(N, MInverseN);
      A.set_sub_mat(idx, fNIdx, MInverseN);

      MatrixNd MInverseS(MInverse.rows(), S.columns());
      MInverse.mult(S, MInverseS);
      A.set_sub_mat(idx, fSIdx, MInverseS);

      MatrixNd MInverseT(MInverse.rows(), T.columns());
      MInverse.mult(T, MInverseT);
      A.set_sub_mat(idx, fTIdx, MInverseT);

      MatrixNd MInverseQ(MInverse.rows(), Q.columns());
      MInverse.mult(Q, MInverseQ);
      MInverseQ *= deltaT;
      A.set_sub_mat(idx, fRobotIdx, MInverseQ);

      A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate());

      VectorNd MInverseFExt(6);
      MInverseFExt.set_zero();
      MInverse.mult(fExt, MInverseFExt, deltaT);
      MInverseFExt.negate() -= v;
      b.set_sub_vec(idx, MInverseFExt);
      ROS_INFO_STREAM("A: " << A);
      ROS_INFO_STREAM("b: " << b);

      // Linear inequality constraints
      ROS_INFO("Calculating Mc and q");
      MatrixNd Mc(6, z.size());
      VectorNd q(6);

      // Nv(t) >= 0 (non-negative normal velocity)
      Mc.set_sub_mat(0, vTDeltaIdx, N);
      q.set_sub_vec(0, VectorNd::zero(6));
      ROS_INFO_STREAM("Mc: " << Mc);
      ROS_INFO_STREAM("q: " << q);

      // Solution variable constraint
      ROS_INFO("Calculating lb and ub");
      VectorNd lb(z.size());
      VectorNd ub(z.size());

      // Torque constraints
      unsigned int bound = 0;
      for (bound; bound < req.torque_limits.size(); ++bound) {
        lb[bound] = req.torque_limits[bound].minimum;
        ub[bound] = req.torque_limits[bound].maximum;
      }

      // f_n >= 0
      lb[bound] = 0;
      ub[bound] = INFINITY;
      ++bound;

      // f_s (no constraints)
      lb[bound] = INFINITY;
      ub[bound] = INFINITY;
      ++bound;

      // f_t (no constraints)
      lb[bound] = INFINITY;
      ub[bound] = INFINITY;
      ++bound;

      // f_robot >= 0
      lb[bound] = 0;
      ub[bound] = INFINITY;
      ++bound;

      // v_t (no constraints)
      for (bound; bound < z.size(); ++bound) {
        lb[bound] = INFINITY;
        ub[bound] = INFINITY;
      }
      ROS_INFO_STREAM("lb: " << lb);
      ROS_INFO_STREAM("ub: " << ub);

      // Call solver
      ROS_INFO("Calling solver");
      Moby::QPOASES qp;
      if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){
            ROS_ERROR("QP failed to find feasible point");
            return false;
      }

      ROS_INFO_STREAM("QP solved successfully: " << z);

      // Copy over result
      res.torques.resize(req.torque_limits.size());
      for (unsigned int i = 0; i < z.size(); ++i) {
        res.torques[i] = z[i];
      }
      return true;
    }
  };
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "balancer");
  Balancer bal;
  ros::spin();
}
<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup foundationLibrary
 *
 * @brief #TTDictionaryTest is an class used for unit tests of the #TTDictionary class.
 *
 * @details
 *
 * @authors Théo de la Hogue, Tim Place
 *
 * @copyright Copyright © 2013, Théo de la Hogue, Tim Place @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTDictionary.test.h"

#define thisTTClass			TTDictionaryTest
#define thisTTClassName		"dictionary.test"
#define thisTTClassTags		"test, foundation"

TT_OBJECT_CONSTRUCTOR
{;}

TTDictionaryTest::~TTDictionaryTest()
{;}

void TTDictionaryTestBasic(int& errorCount, int& testAssertionCount)
{
	TTTestLog("\n");
	TTTestLog("Testing dictionary creation");

    // creation using a random name
    TTDictionary d1;

	TTTestAssertion("TTDictionary random name : Test fails if the dictionary have no name",
					d1.name() != kTTSymEmpty,
					testAssertionCount,
					errorCount);

    // creation using a specific string name
    TTDictionary   d2("dictionary2");

    TTTestAssertion("TTDictionary string name : Test fails if the dictionary name is not \"dictionary2\"",
					d2.name() == TTSymbol("dictionary2"),
					testAssertionCount,
					errorCount);

    // creation using a specific symbol name
    TTDictionary   d3(kTTSym_symbol);

    TTTestAssertion("TTDictionary symbol name : Test fails if the dictionary name is not \"symbol\"",
					d2.name() == kTTSym_symbol,
					testAssertionCount,
					errorCount);

    TTTestLog("\n");
	TTTestLog("Testing dictionary schema");

    TTTestAssertion("TTDictionary schema : dictionary schema should default to 'none' ",
					d1.getSchema() == "none",
					testAssertionCount,
					errorCount);

    d1.setSchema(TTSymbol("aSchemaName"));

    TTTestAssertion("TTDictionary schema : Test fails if the dictionary schema is not \"aSchemaName\"",
					d1.getSchema() == TTSymbol("aSchemaName"),
					testAssertionCount,
					errorCount);

    TTTestLog("\n");
	TTTestLog("Testing dictionary value");

    TTValue v;
    d1.getValue(v);

    TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not empty",
					v == kTTValNONE,
					testAssertionCount,
					errorCount);

    d1.setValue(kTTVal1);
    d1.getValue(v);

    TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not kTTVal1",
					v == kTTVal1,
					testAssertionCount,
					errorCount);

    TTTestLog("\n");
	TTTestLog("Testing dictionary keys");

    d1.append(kTTSym_gain, kTTVal1);
    TTErr err = d1.lookup(kTTSym_gain, v);

    TTTestAssertion("TTDictionary append key : Test fails if the dictionary key \"gain\" doesn't exist or its value is not kTTVal1",
                    err == kTTErrNone &&
					v == kTTVal1,
					testAssertionCount,
					errorCount);

    d1.getKeys(v);
    TTSymbol k1 = v[0];
    TTSymbol k2 = v[1];
    TTSymbol k3 = v[2];

    TTTestAssertion("TTDictionary get keys : Test fails if the dictionary keys are not \"schema\", \"value\" and \"gain\" or the size is not 3",
                    k1 == kTTSym_schema &&
                    k2 == kTTSym_value &&
                    k3 == kTTSym_gain &&
                    d1.size() == 3,
					testAssertionCount,
					errorCount);

    d1.remove(kTTSym_gain);
    d1.getKeys(v);
    k1 = v[0];
    k2 = v[1];

    TTTestAssertion("TTDictionary remove key : Test fails if the dictionary keys are not \"schema\" and \"value\" or the size is not 2",
                    k1 == kTTSym_schema &&
                    k2 == kTTSym_value  &&
                    d1.size() == 2,
					testAssertionCount,
					errorCount);

    d1.clear();

    TTTestAssertion("TTDictionary clear keys : Test fails if the dictionary keys are not empty or the size is not 0",
                    d1.empty() &&
                    d1.size() == 0,
					testAssertionCount,
					errorCount);
}

TTErr TTDictionaryTest::test(TTValue& returnedTestInfo)
{
	int	errorCount = 0;
	int testAssertionCount = 0;

	TTDictionaryTestBasic(errorCount, testAssertionCount);

	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<commit_msg>Fixing a bad test<commit_after>/** @file
 *
 * @ingroup foundationLibrary
 *
 * @brief #TTDictionaryTest is an class used for unit tests of the #TTDictionary class.
 *
 * @details
 *
 * @authors Théo de la Hogue, Tim Place
 *
 * @copyright Copyright © 2013, Théo de la Hogue, Tim Place @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTDictionary.test.h"

#define thisTTClass			TTDictionaryTest
#define thisTTClassName		"dictionary.test"
#define thisTTClassTags		"test, foundation"

TT_OBJECT_CONSTRUCTOR
{;}

TTDictionaryTest::~TTDictionaryTest()
{;}

void TTDictionaryTestBasic(int& errorCount, int& testAssertionCount)
{
	TTTestLog("\n");
	TTTestLog("Testing dictionary creation");

    // creation using a random name
    TTDictionary d1;

	TTTestAssertion("TTDictionary random name : Test fails if the dictionary have no name",
					d1.name() != kTTSymEmpty,
					testAssertionCount,
					errorCount);

    // creation using a specific string name
    TTDictionary   d2("dictionary2");

    TTTestAssertion("TTDictionary string name : Test fails if the dictionary name is not \"dictionary2\"",
					d2.name() == TTSymbol("dictionary2"),
					testAssertionCount,
					errorCount);

    // creation using a specific symbol name
    TTDictionary   d3(kTTSym_symbol);

    TTTestAssertion("TTDictionary symbol name : Test fails if the dictionary name is not \"symbol\"",
					d3.name() == kTTSym_symbol,
					testAssertionCount,
					errorCount);

    TTTestLog("\n");
	TTTestLog("Testing dictionary schema");

    TTTestAssertion("TTDictionary schema : dictionary schema should default to 'none' ",
					d1.getSchema() == "none",
					testAssertionCount,
					errorCount);

    d1.setSchema(TTSymbol("aSchemaName"));

    TTTestAssertion("TTDictionary schema : Test fails if the dictionary schema is not \"aSchemaName\"",
					d1.getSchema() == TTSymbol("aSchemaName"),
					testAssertionCount,
					errorCount);

    TTTestLog("\n");
	TTTestLog("Testing dictionary value");

    TTValue v;
    d1.getValue(v);

    TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not empty",
					v == kTTValNONE,
					testAssertionCount,
					errorCount);

    d1.setValue(kTTVal1);
    d1.getValue(v);

    TTTestAssertion("TTDictionary value : Test fails if the dictionary value is not kTTVal1",
					v == kTTVal1,
					testAssertionCount,
					errorCount);

    TTTestLog("\n");
	TTTestLog("Testing dictionary keys");

    d1.append(kTTSym_gain, kTTVal1);
    TTErr err = d1.lookup(kTTSym_gain, v);

    TTTestAssertion("TTDictionary append key : Test fails if the dictionary key \"gain\" doesn't exist or its value is not kTTVal1",
                    err == kTTErrNone &&
					v == kTTVal1,
					testAssertionCount,
					errorCount);

    d1.getKeys(v);
    TTSymbol k1 = v[0];
    TTSymbol k2 = v[1];
    TTSymbol k3 = v[2];

    TTTestAssertion("TTDictionary get keys : Test fails if the dictionary keys are not \"schema\", \"value\" and \"gain\" or the size is not 3",
                    k1 == kTTSym_schema &&
                    k2 == kTTSym_value &&
                    k3 == kTTSym_gain &&
                    d1.size() == 3,
					testAssertionCount,
					errorCount);

    d1.remove(kTTSym_gain);
    d1.getKeys(v);
    k1 = v[0];
    k2 = v[1];

    TTTestAssertion("TTDictionary remove key : Test fails if the dictionary keys are not \"schema\" and \"value\" or the size is not 2",
                    k1 == kTTSym_schema &&
                    k2 == kTTSym_value  &&
                    d1.size() == 2,
					testAssertionCount,
					errorCount);

    d1.clear();

    TTTestAssertion("TTDictionary clear keys : Test fails if the dictionary keys are not empty or the size is not 0",
                    d1.empty() &&
                    d1.size() == 0,
					testAssertionCount,
					errorCount);
}

TTErr TTDictionaryTest::test(TTValue& returnedTestInfo)
{
	int	errorCount = 0;
	int testAssertionCount = 0;

	TTDictionaryTestBasic(errorCount, testAssertionCount);

	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<|endoftext|>


<commit_before>/**
 * @file llcolorswatch.cpp
 * @brief LLColorSwatch class implementation
 *
 * $LicenseInfo:firstyear=2001&license=viewergpl$
 *
 * Copyright (c) 2001-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

// File include
#include "llcolorswatch.h"

// Linden library includes
#include "v4color.h"
#include "llwindow.h"	// setCursor()

// Project includes
#include "llui.h"
#include "llrender.h"
#include "lluiconstants.h"
#include "llviewercontrol.h"
#include "llbutton.h"
#include "lltextbox.h"
#include "llfloatercolorpicker.h"
#include "llviewborder.h"
#include "llviewertexturelist.h"
#include "llfocusmgr.h"

static LLDefaultChildRegistry::Register<LLColorSwatchCtrl> r("color_swatch");

LLColorSwatchCtrl::Params::Params()
:	color("color", LLColor4::white),
	can_apply_immediately("can_apply_immediately", false),
	alpha_background_image("alpha_background_image"),
	border_color("border_color"),
    label_width("label_width", -1),
	caption_text("caption_text"),
	border("border")
{
	name = "colorswatch";
}

LLColorSwatchCtrl::LLColorSwatchCtrl(const Params& p)
:	LLUICtrl(p),
	mValid( TRUE ),
	mColor(p.color()),
	mCanApplyImmediately(p.can_apply_immediately),
	mAlphaGradientImage(p.alpha_background_image),
	mOnCancelCallback(p.cancel_callback()),
	mOnSelectCallback(p.select_callback()),
	mBorderColor(p.border_color()),
	mLabelWidth(p.label_width)
{
	LLTextBox::Params tp = p.caption_text;
	// label_width is specified, not -1
	if(mLabelWidth!= -1)
	{
		tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, mLabelWidth, 0 ));
	}
	else
	{
		tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, getRect().getWidth(), 0 ));
	}

	tp.initial_value(p.label());
	mCaption = LLUICtrlFactory::create<LLTextBox>(tp);
	addChild( mCaption );

	LLRect border_rect = getLocalRect();
	border_rect.mTop -= 1;
	border_rect.mRight -=1;
	border_rect.mBottom += BTN_HEIGHT_SMALL;

	LLViewBorder::Params params = p.border;
	params.rect(border_rect);
	mBorder = LLUICtrlFactory::create<LLViewBorder> (params);
	addChild(mBorder);
}

LLColorSwatchCtrl::~LLColorSwatchCtrl ()
{
	// parent dialog is destroyed so we are too and we need to cancel selection
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->cancelSelection();
		pickerp->closeFloater();
	}
}

BOOL LLColorSwatchCtrl::handleDoubleClick(S32 x, S32 y, MASK mask)
{
	return handleMouseDown(x, y, mask);
}

BOOL LLColorSwatchCtrl::handleHover(S32 x, S32 y, MASK mask)
{
	getWindow()->setCursor(UI_CURSOR_HAND);
	return TRUE;
}

BOOL LLColorSwatchCtrl::handleUnicodeCharHere(llwchar uni_char)
{
	if( ' ' == uni_char )
	{
		showPicker(TRUE);
	}
	return LLUICtrl::handleUnicodeCharHere(uni_char);
}

// forces color of this swatch and any associated floater to the input value, if currently invalid
void LLColorSwatchCtrl::setOriginal(const LLColor4& color)
{
	mColor = color;
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->setOrigRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]);
	}
}

void LLColorSwatchCtrl::set(const LLColor4& color, BOOL update_picker, BOOL from_event)
{
	mColor = color;
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp && update_picker)
	{
		pickerp->setCurRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]);
	}
	if (!from_event)
	{
		setControlValue(mColor.getValue());
	}
}

void LLColorSwatchCtrl::setLabel(const std::string& label)
{
	mCaption->setText(label);
}

BOOL LLColorSwatchCtrl::handleMouseDown(S32 x, S32 y, MASK mask)
{
	// Route future Mouse messages here preemptively.  (Release on mouse up.)
	// No handler is needed for capture lost since this object has no state that depends on it.
	gFocusMgr.setMouseCapture( this );

	return TRUE;
}

BOOL LLColorSwatchCtrl::handleMouseUp(S32 x, S32 y, MASK mask)
{
	// We only handle the click if the click both started and ended within us
	if( hasMouseCapture() )
	{
		// Release the mouse
		gFocusMgr.setMouseCapture( NULL );

		// If mouseup in the widget, it's been clicked
		if ( pointInView(x, y) )
		{
			llassert(getEnabled());
			llassert(getVisible());

			showPicker(FALSE);
		}
	}

	return TRUE;
}

// assumes GL state is set for 2D
void LLColorSwatchCtrl::draw()
{
	F32 alpha = getDrawContext().mAlpha;
	mBorder->setKeyboardFocusHighlight(hasFocus());
	// Draw border
	LLRect border( 0, getRect().getHeight(), getRect().getWidth(), BTN_HEIGHT_SMALL );
	gl_rect_2d( border, mBorderColor.get(), FALSE );

	LLRect interior = border;
	interior.stretch( -1 );

	// Check state
	if ( mValid )
	{
		// Draw the color swatch
		gl_rect_2d_checkerboard( interior );
		gl_rect_2d(interior, mColor, TRUE);
		LLColor4 opaque_color = mColor;
		opaque_color.mV[VALPHA] = 1.f;
		gGL.color4fv(opaque_color.mV);
		if (mAlphaGradientImage.notNull())
		{
			gGL.pushMatrix();
			{
				mAlphaGradientImage->draw(interior, mColor);
			}
			gGL.popMatrix();
		}
	}
	else
	{
		if (!mFallbackImageName.empty())
		{
			LLPointer<LLViewerFetchedTexture> fallback_image = LLViewerTextureManager::getFetchedTextureFromFile(mFallbackImageName, TRUE,
				LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE);
			if( fallback_image->getComponents() == 4 )
			{
				gl_rect_2d_checkerboard( interior );
			}
			gl_draw_scaled_image( interior.mLeft, interior.mBottom, interior.getWidth(), interior.getHeight(), fallback_image, LLColor4::white % alpha);
			fallback_image->addTextureStats( (F32)(interior.getWidth() * interior.getHeight()) );
		}
		else
		{
			// Draw grey and an X
			gl_rect_2d(interior, LLColor4::grey % alpha, TRUE);

			gl_draw_x(interior, LLColor4::black % alpha);
		}
	}

	LLUICtrl::draw();
}

void LLColorSwatchCtrl::setEnabled( BOOL enabled )
{
	mCaption->setEnabled( enabled );
	LLView::setEnabled( enabled );

	if (!enabled)
	{
		LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
		if (pickerp)
		{
			pickerp->cancelSelection();
			pickerp->closeFloater();
		}
	}
}

void LLColorSwatchCtrl::setValue(const LLSD& value)
{
	set(LLColor4(value), TRUE, TRUE);
}

//////////////////////////////////////////////////////////////////////////////
// called (infrequently) when the color changes so the subject of the swatch can be updated.
void LLColorSwatchCtrl::onColorChanged ( void* data, EColorPickOp pick_op )
{
	LLColorSwatchCtrl* subject = ( LLColorSwatchCtrl* )data;
	if ( subject )
	{
		LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)subject->mPickerHandle.get();
		if (pickerp)
		{
			// move color across from selector to internal widget storage
			LLColor4 updatedColor ( pickerp->getCurR (),
									pickerp->getCurG (),
									pickerp->getCurB (),
									subject->mColor.mV[VALPHA] ); // keep current alpha
			subject->mColor = updatedColor;
			subject->setControlValue(updatedColor.getValue());

			if (pick_op == COLOR_CANCEL && subject->mOnCancelCallback)
			{
				subject->mOnCancelCallback( subject, LLSD());
			}
			else if (pick_op == COLOR_SELECT && subject->mOnSelectCallback)
			{
				subject->mOnSelectCallback( subject, LLSD() );
			}
			else
			{
				// just commit change
				subject->onCommit ();
			}
		}
	}
}

// This is called when the main floatercustomize panel is closed.
// Since this class has pointers up to its parents, we need to cleanup
// this class first in order to avoid a crash.
void LLColorSwatchCtrl::onParentFloaterClosed()
{
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->setSwatch(NULL);
		pickerp->closeFloater();
	}

	mPickerHandle.markDead();
}

void LLColorSwatchCtrl::setValid(BOOL valid )
{
	mValid = valid;

	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->setActive(valid);
	}
}

void LLColorSwatchCtrl::showPicker(BOOL take_focus)
{
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (!pickerp)
	{
		pickerp = new LLFloaterColorPicker(this, mCanApplyImmediately);
		//gFloaterView->getParentFloater(this)->addDependentFloater(pickerp);
		mPickerHandle = pickerp->getHandle();
	}

	// initialize picker with current color
	pickerp->initUI ( mColor.mV [ VRED ], mColor.mV [ VGREEN ], mColor.mV [ VBLUE ] );

	// display it
	pickerp->showUI ();

	if (take_focus)
	{
		pickerp->setFocus(TRUE);
	}
}

<commit_msg>EXT-7736 FIXED Reverted fix for EXT-2819 (crash in color picker).<commit_after>/**
 * @file llcolorswatch.cpp
 * @brief LLColorSwatch class implementation
 *
 * $LicenseInfo:firstyear=2001&license=viewergpl$
 *
 * Copyright (c) 2001-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

// File include
#include "llcolorswatch.h"

// Linden library includes
#include "v4color.h"
#include "llwindow.h"	// setCursor()

// Project includes
#include "llui.h"
#include "llrender.h"
#include "lluiconstants.h"
#include "llviewercontrol.h"
#include "llbutton.h"
#include "lltextbox.h"
#include "llfloatercolorpicker.h"
#include "llviewborder.h"
#include "llviewertexturelist.h"
#include "llfocusmgr.h"

static LLDefaultChildRegistry::Register<LLColorSwatchCtrl> r("color_swatch");

LLColorSwatchCtrl::Params::Params()
:	color("color", LLColor4::white),
	can_apply_immediately("can_apply_immediately", false),
	alpha_background_image("alpha_background_image"),
	border_color("border_color"),
    label_width("label_width", -1),
	caption_text("caption_text"),
	border("border")
{
	name = "colorswatch";
}

LLColorSwatchCtrl::LLColorSwatchCtrl(const Params& p)
:	LLUICtrl(p),
	mValid( TRUE ),
	mColor(p.color()),
	mCanApplyImmediately(p.can_apply_immediately),
	mAlphaGradientImage(p.alpha_background_image),
	mOnCancelCallback(p.cancel_callback()),
	mOnSelectCallback(p.select_callback()),
	mBorderColor(p.border_color()),
	mLabelWidth(p.label_width)
{
	LLTextBox::Params tp = p.caption_text;
	// label_width is specified, not -1
	if(mLabelWidth!= -1)
	{
		tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, mLabelWidth, 0 ));
	}
	else
	{
		tp.rect(LLRect( 0, BTN_HEIGHT_SMALL, getRect().getWidth(), 0 ));
	}

	tp.initial_value(p.label());
	mCaption = LLUICtrlFactory::create<LLTextBox>(tp);
	addChild( mCaption );

	LLRect border_rect = getLocalRect();
	border_rect.mTop -= 1;
	border_rect.mRight -=1;
	border_rect.mBottom += BTN_HEIGHT_SMALL;

	LLViewBorder::Params params = p.border;
	params.rect(border_rect);
	mBorder = LLUICtrlFactory::create<LLViewBorder> (params);
	addChild(mBorder);
}

LLColorSwatchCtrl::~LLColorSwatchCtrl ()
{
	// parent dialog is destroyed so we are too and we need to cancel selection
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->cancelSelection();
		pickerp->closeFloater();
	}
}

BOOL LLColorSwatchCtrl::handleDoubleClick(S32 x, S32 y, MASK mask)
{
	return handleMouseDown(x, y, mask);
}

BOOL LLColorSwatchCtrl::handleHover(S32 x, S32 y, MASK mask)
{
	getWindow()->setCursor(UI_CURSOR_HAND);
	return TRUE;
}

BOOL LLColorSwatchCtrl::handleUnicodeCharHere(llwchar uni_char)
{
	if( ' ' == uni_char )
	{
		showPicker(TRUE);
	}
	return LLUICtrl::handleUnicodeCharHere(uni_char);
}

// forces color of this swatch and any associated floater to the input value, if currently invalid
void LLColorSwatchCtrl::setOriginal(const LLColor4& color)
{
	mColor = color;
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->setOrigRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]);
	}
}

void LLColorSwatchCtrl::set(const LLColor4& color, BOOL update_picker, BOOL from_event)
{
	mColor = color;
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp && update_picker)
	{
		pickerp->setCurRgb(mColor.mV[VRED], mColor.mV[VGREEN], mColor.mV[VBLUE]);
	}
	if (!from_event)
	{
		setControlValue(mColor.getValue());
	}
}

void LLColorSwatchCtrl::setLabel(const std::string& label)
{
	mCaption->setText(label);
}

BOOL LLColorSwatchCtrl::handleMouseDown(S32 x, S32 y, MASK mask)
{
	// Route future Mouse messages here preemptively.  (Release on mouse up.)
	// No handler is needed for capture lost since this object has no state that depends on it.
	gFocusMgr.setMouseCapture( this );

	return TRUE;
}

BOOL LLColorSwatchCtrl::handleMouseUp(S32 x, S32 y, MASK mask)
{
	// We only handle the click if the click both started and ended within us
	if( hasMouseCapture() )
	{
		// Release the mouse
		gFocusMgr.setMouseCapture( NULL );

		// If mouseup in the widget, it's been clicked
		if ( pointInView(x, y) )
		{
			llassert(getEnabled());
			llassert(getVisible());

			showPicker(FALSE);
		}
	}

	return TRUE;
}

// assumes GL state is set for 2D
void LLColorSwatchCtrl::draw()
{
	F32 alpha = getDrawContext().mAlpha;
	mBorder->setKeyboardFocusHighlight(hasFocus());
	// Draw border
	LLRect border( 0, getRect().getHeight(), getRect().getWidth(), BTN_HEIGHT_SMALL );
	gl_rect_2d( border, mBorderColor.get(), FALSE );

	LLRect interior = border;
	interior.stretch( -1 );

	// Check state
	if ( mValid )
	{
		// Draw the color swatch
		gl_rect_2d_checkerboard( interior );
		gl_rect_2d(interior, mColor, TRUE);
		LLColor4 opaque_color = mColor;
		opaque_color.mV[VALPHA] = 1.f;
		gGL.color4fv(opaque_color.mV);
		if (mAlphaGradientImage.notNull())
		{
			gGL.pushMatrix();
			{
				mAlphaGradientImage->draw(interior, mColor);
			}
			gGL.popMatrix();
		}
	}
	else
	{
		if (!mFallbackImageName.empty())
		{
			LLPointer<LLViewerFetchedTexture> fallback_image = LLViewerTextureManager::getFetchedTextureFromFile(mFallbackImageName, TRUE,
				LLViewerTexture::BOOST_NONE, LLViewerTexture::LOD_TEXTURE);
			if( fallback_image->getComponents() == 4 )
			{
				gl_rect_2d_checkerboard( interior );
			}
			gl_draw_scaled_image( interior.mLeft, interior.mBottom, interior.getWidth(), interior.getHeight(), fallback_image, LLColor4::white % alpha);
			fallback_image->addTextureStats( (F32)(interior.getWidth() * interior.getHeight()) );
		}
		else
		{
			// Draw grey and an X
			gl_rect_2d(interior, LLColor4::grey % alpha, TRUE);

			gl_draw_x(interior, LLColor4::black % alpha);
		}
	}

	LLUICtrl::draw();
}

void LLColorSwatchCtrl::setEnabled( BOOL enabled )
{
	mCaption->setEnabled( enabled );
	LLView::setEnabled( enabled );

	if (!enabled)
	{
		LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
		if (pickerp)
		{
			pickerp->cancelSelection();
			pickerp->closeFloater();
		}
	}
}

void LLColorSwatchCtrl::setValue(const LLSD& value)
{
	set(LLColor4(value), TRUE, TRUE);
}

//////////////////////////////////////////////////////////////////////////////
// called (infrequently) when the color changes so the subject of the swatch can be updated.
void LLColorSwatchCtrl::onColorChanged ( void* data, EColorPickOp pick_op )
{
	LLColorSwatchCtrl* subject = ( LLColorSwatchCtrl* )data;
	if ( subject )
	{
		LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)subject->mPickerHandle.get();
		if (pickerp)
		{
			// move color across from selector to internal widget storage
			LLColor4 updatedColor ( pickerp->getCurR (),
									pickerp->getCurG (),
									pickerp->getCurB (),
									subject->mColor.mV[VALPHA] ); // keep current alpha
			subject->mColor = updatedColor;
			subject->setControlValue(updatedColor.getValue());

			if (pick_op == COLOR_CANCEL && subject->mOnCancelCallback)
			{
				subject->mOnCancelCallback( subject, LLSD());
			}
			else if (pick_op == COLOR_SELECT && subject->mOnSelectCallback)
			{
				subject->mOnSelectCallback( subject, LLSD() );
			}
			else
			{
				// just commit change
				subject->onCommit ();
			}
		}
	}
}

// This is called when the main floatercustomize panel is closed.
// Since this class has pointers up to its parents, we need to cleanup
// this class first in order to avoid a crash.
void LLColorSwatchCtrl::onParentFloaterClosed()
{
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->setSwatch(NULL);
		pickerp->closeFloater();
	}

	mPickerHandle.markDead();
}

void LLColorSwatchCtrl::setValid(BOOL valid )
{
	mValid = valid;

	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (pickerp)
	{
		pickerp->setActive(valid);
	}
}

void LLColorSwatchCtrl::showPicker(BOOL take_focus)
{
	LLFloaterColorPicker* pickerp = (LLFloaterColorPicker*)mPickerHandle.get();
	if (!pickerp)
	{
		pickerp = new LLFloaterColorPicker(this, mCanApplyImmediately);
		LLFloater* parent = gFloaterView->getParentFloater(this);
		if (parent)
		{
			parent->addDependentFloater(pickerp);
		}
		mPickerHandle = pickerp->getHandle();
	}

	// initialize picker with current color
	pickerp->initUI ( mColor.mV [ VRED ], mColor.mV [ VGREEN ], mColor.mV [ VBLUE ] );

	// display it
	pickerp->showUI ();

	if (take_focus)
	{
		pickerp->setFocus(TRUE);
	}
}

<|endoftext|>


<commit_before>#include "model/PhysicsCar.h"

#include "model/PhysicsWorld.h"

#include <btBulletDynamicsCommon.h>

#include <sstream>
#include <iostream>

namespace Rally { namespace Model {

    namespace {
        const btVector3 CAR_DIMENSIONS(2.0f, 1.0f, 4.0f);
        const float CAR_MASS = 1.0f;

        // The rolling torque from each wheel is scaled with this (to prevent rollover).
        // 0.0f = no rolling, 1.0f = rolling like in reality.
        const float ROLL_INFLUENCE = 0.1f;

        const float SUSPENSION_REST_LENGTH = 0.6f; // (see also maxSuspensionTravelCm)
        const float WHEEL_RADIUS = 0.5f;
        // (There is no wheel width.)

        // The wheel distance is calculated from the origin = center of the car.
        // The wheel (including radius) should be located inside the car body:
        //  - Below the car and it might sink into the ground (rays goes into infinity)
        //  - Above the car and it confuses the body with the ground => weird behavior.
        //    (The official demo does this though... Maybe the suspension is included?)
        // Values below represent the right wheel (mirrored in the yz-plane for left).
        const btVector3 FRONT_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.3f - WHEEL_RADIUS);
        const btVector3 BACK_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.1f - WHEEL_RADIUS);
    }

    PhysicsCar::PhysicsCar() :
            dynamicsWorld(NULL),
            bodyShape(NULL),
            bodyMotionState(btTransform(btQuaternion(0.0f, 0.0f, 0.0f, 1.0f), btVector3(0.0f, 10.0f, 0.0f))),
            bodyConstructionInfo(NULL),
            bodyRigidBody(NULL),
            vehicleRaycaster(NULL),
            raycastVehicle(NULL),
            leftFrontWheel(NULL),
            rightFrontWheel(NULL),
            leftBackWheel(NULL),
            rightBackWheel(NULL) {
    }

    PhysicsCar::~PhysicsCar() {
    }

    void PhysicsCar::initializeConstructionInfo() {
        if(bodyConstructionInfo != NULL) {
            return;
        }

        bodyShape = new btBoxShape(CAR_DIMENSIONS / 2); // Takes half-extents

        // Initialize what I think is the diagonal in the inertia tensor
        btVector3 inertia(0, 0, 0);
        bodyShape->calculateLocalInertia(CAR_MASS, inertia); // TODO: We might want to lower/move center of gravity...

        bodyConstructionInfo = new btRigidBody::btRigidBodyConstructionInfo(CAR_MASS, &bodyMotionState, bodyShape, inertia);
    }

    void PhysicsCar::attachTo(PhysicsWorld& physicsWorld) {
        dynamicsWorld = physicsWorld.getDynamicsWorld();

        // Create car body
        this->initializeConstructionInfo();
        bodyRigidBody = new btRigidBody(*bodyConstructionInfo);
        bodyRigidBody->setActivationState(DISABLE_DEACTIVATION); // Needed for btRaycastVehicles
        dynamicsWorld->addRigidBody(bodyRigidBody);

        // Tuning for car (applied to all the wheels internally).
        btRaycastVehicle::btVehicleTuning tuning;
        tuning.m_suspensionStiffness = 20.0f;
        tuning.m_suspensionDamping = 2.3f;
        tuning.m_suspensionCompression = 4.4f;
        tuning.m_frictionSlip = 0.8f;// no drift = 1000.0f;
        // rollInfluence cannot be set here, so we have to apply it to every wheel individually.

        // Create the raycasting part for the "wheels"
        vehicleRaycaster = new btDefaultVehicleRaycaster(dynamicsWorld);
        raycastVehicle = new btRaycastVehicle(tuning, bodyRigidBody, vehicleRaycaster);
        dynamicsWorld->addVehicle(raycastVehicle);

        // Create the actual wheels:
        const btVector3 wheelDirection(0, -1.0f, 0); // This is the direction of the raycast.
        const btVector3 wheelAxle(-1.0f, 0, 0); // This is spinning direction (using right hand rule).

        // Right front wheel.
        rightFrontWheel = &raycastVehicle->addWheel(
            FRONT_WHEEL_DISTANCE, // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            true // isFrontWheel
        );
        rightFrontWheel->m_rollInfluence = ROLL_INFLUENCE;

        // Left front wheel.
        leftFrontWheel = &raycastVehicle->addWheel(
            btVector3(-FRONT_WHEEL_DISTANCE.x(), FRONT_WHEEL_DISTANCE.y(), -FRONT_WHEEL_DISTANCE.z()), // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            true // isFrontWheel
        );
        leftFrontWheel->m_rollInfluence = ROLL_INFLUENCE;

        // Right back wheel.
        rightBackWheel = &raycastVehicle->addWheel(
            BACK_WHEEL_DISTANCE, // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            false // isFrontWheel
        );
        rightBackWheel->m_rollInfluence = ROLL_INFLUENCE;

        // Left back wheel.
        leftBackWheel = &raycastVehicle->addWheel(
            btVector3(-BACK_WHEEL_DISTANCE.x(), BACK_WHEEL_DISTANCE.y(), -BACK_WHEEL_DISTANCE.z()), // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            false // isFrontWheel
        );
        leftBackWheel->m_rollInfluence = ROLL_INFLUENCE;
    }

    Rally::Vector3 PhysicsCar::getPosition() const {
        // Note that we cannot ask the rigidbody or use raycastVehicle->getForwardVector(),
        // as we won't get interpolated values then. That's motion-state exclusive info.
        const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans;
        const btVector3& position = graphicsTransform.getOrigin();
        return Rally::Vector3(position.x(), position.y(), position.z());
    }

    Rally::Vector3 PhysicsCar::getOrientation() const {
        const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans;
        return Rally::Vector3(
            graphicsTransform.getBasis()[0][2], // The z-column basis vector
            graphicsTransform.getBasis()[1][2], // The z-column basis vector
            graphicsTransform.getBasis()[2][2] // The z-column basis vector
        );
        //const btQuaternion orientation = graphicsTransform.getRotation();
        //return Rally::Quaternion(orientation.x(), orientation.y(), orientation.z(), orientation.w());
    }

    Rally::Vector3 PhysicsCar::getVelocity() const {
        if(bodyRigidBody == NULL) {
            return Rally::Vector3(0, 0, 0);
        }

        const btVector3 velocity = bodyRigidBody->getLinearVelocity();
        return Rally::Vector3(velocity.x(), velocity.y(), velocity.z());
    }

    float PhysicsCar::getRightFrontWheelTraction() const {
        return rightFrontWheel->m_skidInfo;
    }

    float PhysicsCar::getLeftFrontWheelTraction() const {
        return leftFrontWheel->m_skidInfo;
    }

    float PhysicsCar::getRightBackWheelTraction() const {
        return rightBackWheel->m_skidInfo;
    }

    float PhysicsCar::getLeftBackWheelTraction() const {
        return leftBackWheel->m_skidInfo;
    }

} }
<commit_msg>Fixed rallycar bug: left wheels pointing in the wrong direction.<commit_after>#include "model/PhysicsCar.h"

#include "model/PhysicsWorld.h"

#include <btBulletDynamicsCommon.h>

#include <sstream>
#include <iostream>

namespace Rally { namespace Model {

    namespace {
        const btVector3 CAR_DIMENSIONS(2.0f, 1.0f, 4.0f);
        const float CAR_MASS = 1.0f;

        // The rolling torque from each wheel is scaled with this (to prevent rollover).
        // 0.0f = no rolling, 1.0f = rolling like in reality.
        const float ROLL_INFLUENCE = 0.1f;

        const float SUSPENSION_REST_LENGTH = 0.6f; // (see also maxSuspensionTravelCm)
        const float WHEEL_RADIUS = 0.5f;
        // (There is no wheel width.)

        // The wheel distance is calculated from the origin = center of the car.
        // The wheel (including radius) should be located inside the car body:
        //  - Below the car and it might sink into the ground (rays goes into infinity)
        //  - Above the car and it confuses the body with the ground => weird behavior.
        //    (The official demo does this though... Maybe the suspension is included?)
        // Values below represent the right wheel (mirrored in the yz-plane for left).
        const btVector3 FRONT_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.3f - WHEEL_RADIUS);
        const btVector3 BACK_WHEEL_DISTANCE(CAR_DIMENSIONS.x()/2 - 0.1f, 0.f, CAR_DIMENSIONS.z()/2 - 0.1f - WHEEL_RADIUS);
    }

    PhysicsCar::PhysicsCar() :
            dynamicsWorld(NULL),
            bodyShape(NULL),
            bodyMotionState(btTransform(btQuaternion(0.0f, 0.0f, 0.0f, 1.0f), btVector3(0.0f, 10.0f, 0.0f))),
            bodyConstructionInfo(NULL),
            bodyRigidBody(NULL),
            vehicleRaycaster(NULL),
            raycastVehicle(NULL),
            leftFrontWheel(NULL),
            rightFrontWheel(NULL),
            leftBackWheel(NULL),
            rightBackWheel(NULL) {
    }

    PhysicsCar::~PhysicsCar() {
    }

    void PhysicsCar::initializeConstructionInfo() {
        if(bodyConstructionInfo != NULL) {
            return;
        }

        bodyShape = new btBoxShape(CAR_DIMENSIONS / 2); // Takes half-extents

        // Initialize what I think is the diagonal in the inertia tensor
        btVector3 inertia(0, 0, 0);
        bodyShape->calculateLocalInertia(CAR_MASS, inertia); // TODO: We might want to lower/move center of gravity...

        bodyConstructionInfo = new btRigidBody::btRigidBodyConstructionInfo(CAR_MASS, &bodyMotionState, bodyShape, inertia);
    }

    void PhysicsCar::attachTo(PhysicsWorld& physicsWorld) {
        dynamicsWorld = physicsWorld.getDynamicsWorld();

        // Create car body
        this->initializeConstructionInfo();
        bodyRigidBody = new btRigidBody(*bodyConstructionInfo);
        bodyRigidBody->setActivationState(DISABLE_DEACTIVATION); // Needed for btRaycastVehicles
        dynamicsWorld->addRigidBody(bodyRigidBody);

        // Tuning for car (applied to all the wheels internally).
        btRaycastVehicle::btVehicleTuning tuning;
        tuning.m_suspensionStiffness = 20.0f;
        tuning.m_suspensionDamping = 2.3f;
        tuning.m_suspensionCompression = 4.4f;
        tuning.m_frictionSlip = 0.8f;// no drift = 1000.0f;
        // rollInfluence cannot be set here, so we have to apply it to every wheel individually.

        // Create the raycasting part for the "wheels"
        vehicleRaycaster = new btDefaultVehicleRaycaster(dynamicsWorld);
        raycastVehicle = new btRaycastVehicle(tuning, bodyRigidBody, vehicleRaycaster);
        dynamicsWorld->addVehicle(raycastVehicle);

        // Create the actual wheels:
        const btVector3 wheelDirection(0, -1.0f, 0); // This is the direction of the raycast.
        const btVector3 wheelAxle(-1.0f, 0, 0); // This is spinning direction (using right hand rule).

        // Right front wheel.
        rightFrontWheel = &raycastVehicle->addWheel(
            FRONT_WHEEL_DISTANCE, // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            true // isFrontWheel
        );
        rightFrontWheel->m_rollInfluence = ROLL_INFLUENCE;

        // Left front wheel.
        leftFrontWheel = &raycastVehicle->addWheel(
            btVector3(-FRONT_WHEEL_DISTANCE.x(), FRONT_WHEEL_DISTANCE.y(), FRONT_WHEEL_DISTANCE.z()), // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            true // isFrontWheel
        );
        leftFrontWheel->m_rollInfluence = ROLL_INFLUENCE;

        // Right back wheel.
        rightBackWheel = &raycastVehicle->addWheel(
            BACK_WHEEL_DISTANCE, // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            false // isFrontWheel
        );
        rightBackWheel->m_rollInfluence = ROLL_INFLUENCE;

        // Left back wheel.
        leftBackWheel = &raycastVehicle->addWheel(
            btVector3(-BACK_WHEEL_DISTANCE.x(), BACK_WHEEL_DISTANCE.y(), BACK_WHEEL_DISTANCE.z()), // connection point
            wheelDirection, // wheel direction
            wheelAxle, // axle
            SUSPENSION_REST_LENGTH,
            WHEEL_RADIUS,
            tuning,
            false // isFrontWheel
        );
        leftBackWheel->m_rollInfluence = ROLL_INFLUENCE;
    }

    Rally::Vector3 PhysicsCar::getPosition() const {
        // Note that we cannot ask the rigidbody or use raycastVehicle->getForwardVector(),
        // as we won't get interpolated values then. That's motion-state exclusive info.
        const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans;
        const btVector3& position = graphicsTransform.getOrigin();
        return Rally::Vector3(position.x(), position.y(), position.z());
    }

    Rally::Vector3 PhysicsCar::getOrientation() const {
        const btTransform& graphicsTransform = bodyMotionState.m_graphicsWorldTrans;
        return Rally::Vector3(
            graphicsTransform.getBasis()[0][2], // The z-column basis vector
            graphicsTransform.getBasis()[1][2], // The z-column basis vector
            graphicsTransform.getBasis()[2][2] // The z-column basis vector
        );
        //const btQuaternion orientation = graphicsTransform.getRotation();
        //return Rally::Quaternion(orientation.x(), orientation.y(), orientation.z(), orientation.w());
    }

    Rally::Vector3 PhysicsCar::getVelocity() const {
        if(bodyRigidBody == NULL) {
            return Rally::Vector3(0, 0, 0);
        }

        const btVector3 velocity = bodyRigidBody->getLinearVelocity();
        return Rally::Vector3(velocity.x(), velocity.y(), velocity.z());
    }

    float PhysicsCar::getRightFrontWheelTraction() const {
        return rightFrontWheel->m_skidInfo;
    }

    float PhysicsCar::getLeftFrontWheelTraction() const {
        return leftFrontWheel->m_skidInfo;
    }

    float PhysicsCar::getRightBackWheelTraction() const {
        return rightBackWheel->m_skidInfo;
    }

    float PhysicsCar::getLeftBackWheelTraction() const {
        return leftBackWheel->m_skidInfo;
    }

} }
<|endoftext|>


<commit_before>//
//  TexturesHandler.hpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 19/06/12.
//  Copyright (c) 2012 IGO Software SL. All rights reserved.
//

#ifndef G3MiOSSDK_TexturesHandler_hpp
#define G3MiOSSDK_TexturesHandler_hpp

#include <string>
#include <vector>
#include "TextureBuilder.hpp"

#include "TextureHolder.hpp"

class IImage;
class RenderContext;
//class TextureHolder;
class IGL;
class IFactory;

class TexturesHandler {
private:
  std::vector<TextureHolder*> _textureHolders;

  IGL * const _gl;
  const IFactory * const _factory;
  const TextureBuilder* _texBuilder;

  const bool _verbose;

public:

  TexturesHandler(IGL* const  gl,
                  const IFactory const * factory,
                  const TextureBuilder* texBuilder,
                  bool verbose):
  _gl(gl),
  _factory(factory),
  _texBuilder(texBuilder),
  _verbose(verbose)
  {
  }

  ~TexturesHandler();

  int getTextureIdFromFileName(const std::string& filename,
                               int textureWidth,
                               int textureHeight);

  int getTextureId(const std::vector<const IImage*>& images,
                   const std::string& textureId,
                   int textureWidth,
                   int textureHeight);

  int getTextureId(const std::vector<const IImage*>& images,
                   const std::vector<const Rectangle*>& rectangles,
                   const std::string& textureId,
                   int textureWidth,
                   int textureHeight);

  int getTextureId(const IImage* image,
                   const std::string& textureId,
                   int textureWidth,
                   int textureHeight);

  int getTextureIdIfAvailable(const std::string& textureId,
                              int textureWidth,
                              int textureHeight);

  void takeTexture(int glTextureId);

};

#endif
<commit_msg>Java conversion tasks<commit_after>//
//  TexturesHandler.hpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 19/06/12.
//  Copyright (c) 2012 IGO Software SL. All rights reserved.
//

#ifndef G3MiOSSDK_TexturesHandler_hpp
#define G3MiOSSDK_TexturesHandler_hpp

#include <string>
#include <vector>
#include "TextureBuilder.hpp"

class IImage;
class RenderContext;
class TextureHolder;
class IGL;
class IFactory;

class TexturesHandler {
private:
  std::vector<TextureHolder*> _textureHolders;

  IGL * const _gl;
  const IFactory * const _factory;
  const TextureBuilder* _texBuilder;

  const bool _verbose;

public:

  TexturesHandler(IGL* const  gl,
                  const IFactory const * factory,
                  const TextureBuilder* texBuilder,
                  bool verbose):
  _gl(gl),
  _factory(factory),
  _texBuilder(texBuilder),
  _verbose(verbose)
  {
  }

  ~TexturesHandler();

  int getTextureIdFromFileName(const std::string& filename,
                               int textureWidth,
                               int textureHeight);

  int getTextureId(const std::vector<const IImage*>& images,
                   const std::string& textureId,
                   int textureWidth,
                   int textureHeight);

  int getTextureId(const std::vector<const IImage*>& images,
                   const std::vector<const Rectangle*>& rectangles,
                   const std::string& textureId,
                   int textureWidth,
                   int textureHeight);

  int getTextureId(const IImage* image,
                   const std::string& textureId,
                   int textureWidth,
                   int textureHeight);

  int getTextureIdIfAvailable(const std::string& textureId,
                              int textureWidth,
                              int textureHeight);

  void takeTexture(int glTextureId);

};

#endif
<|endoftext|>


<commit_before>#include "Sketch.h"

#include "chr/gl/draw/Torus.h"
#include "chr/gl/draw/Sphere.h"

using namespace std;
using namespace chr;
using namespace gl;
using namespace draw;

Sketch::Sketch()
:
shader(InputSource::resource("Shader.vert"), InputSource::resource("Shader.frag"))
{}

void Sketch::setup()
{
  Torus()
    .setFrontFace(CW)
    .setSliceCount(20)
    .setLoopCount(60)
    .setInnerRadius(25)
    .setOuterRadius(100)
    .append(modelBatch, Matrix());

  lightBatch
    .setShader(colorShader)
    .setShaderColor(1, 1, 1, 1);

  // ---

  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glDepthMask(GL_TRUE);

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

void Sketch::resize()
{
  camera
    .setFov(60)
    .setClip(0.1f, 1000.0f)
    .setWindowSize(windowInfo.size);
}

void Sketch::draw()
{
  glClearColor(0.5f, 0.5f, 0.5f, 1);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // ---

  camera.getViewMatrix()
    .setIdentity()
    .translate(0, 0, -300)
    .rotateY(clock()->getTime() * 0.125f);

  //

  float t = clock()->getTime() * 1.0f;
  float radius = 150;
  float x = cosf(t) * radius;
  float y = 0;
  float z = sinf(t) * radius;
  glm::vec3 lightPosition(x, y, z);

  //

  State()
    .setShaderMatrix<MVP>(camera.getViewProjectionMatrix())
    .apply();

  lightBatch.clear();
  Sphere()
    .setFrontFace(CW)
    .setSectorCount(16)
    .setStackCount(8)
    .setRadius(4)
    .append(lightBatch, Matrix().setTranslate(lightPosition));
  lightBatch.flush();

  //

  State()
    .setShader(shader)
    .setShaderMatrix<MODEL>(Matrix())
    .setShaderMatrix<VIEW>(camera.getViewMatrix())
    .setShaderMatrix<PROJECTION>(camera.getProjectionMatrix())
    .setShaderMatrix<NORMAL>(camera.getNormalMatrix())
    .setShaderUniform("u_light_position", lightPosition)
    .setShaderUniform("u_light_color", glm::vec3(1.0, 1.0, 1.0))
    .setShaderUniform("u_light_intensity", 1.0f)
    .setShaderUniform("u_ambient_color", glm::vec3(0, 0, 0))
    .setShaderUniform("u_diffuse_color", glm::vec3(1.0f, 0.5f, 0.0f))
    .setShaderUniform("u_specular_color", glm::vec3(1, 1, 1))
    .setShaderUniform("u_shininess", 25.0f)
    .apply();

  modelBatch.flush();
}
<commit_msg>TestingLighting: Cosmetic tweaks<commit_after>#include "Sketch.h"

#include "chr/gl/draw/Torus.h"
#include "chr/gl/draw/Sphere.h"

using namespace std;
using namespace chr;
using namespace gl;
using namespace draw;

Sketch::Sketch()
:
shader(InputSource::resource("Shader.vert"), InputSource::resource("Shader.frag"))
{}

void Sketch::setup()
{
  Torus()
    .setFrontFace(CW)
    .setSliceCount(20)
    .setLoopCount(60)
    .setInnerRadius(25)
    .setOuterRadius(100)
    .append(modelBatch, Matrix());

  modelBatch.setShader(shader);

  lightBatch
    .setShader(colorShader)
    .setShaderColor(1, 1, 1, 1);

  // ---

  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glDepthMask(GL_TRUE);

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

void Sketch::resize()
{
  camera
    .setFov(60)
    .setClip(0.1f, 1000.0f)
    .setWindowSize(windowInfo.size);
}

void Sketch::draw()
{
  glClearColor(0.5f, 0.5f, 0.5f, 1);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // ---

  camera.getViewMatrix()
    .setIdentity()
    .translate(0, 0, -300)
    .rotateY(clock()->getTime() * 0.125f);

  //

  float t = clock()->getTime() * 1.0f;
  float radius = 150;
  float x = cosf(t) * radius;
  float y = 0;
  float z = sinf(t) * radius;
  glm::vec3 lightPosition(x, y, z);

  //

  State()
    .setShaderMatrix<MVP>(camera.getViewProjectionMatrix())
    .apply();

  lightBatch.clear();
  Sphere()
    .setFrontFace(CW)
    .setSectorCount(16)
    .setStackCount(8)
    .setRadius(4)
    .append(lightBatch, Matrix().translate(lightPosition));
  lightBatch.flush();

  //

  State()
    .setShaderMatrix<MODEL>(Matrix())
    .setShaderMatrix<VIEW>(camera.getViewMatrix())
    .setShaderMatrix<PROJECTION>(camera.getProjectionMatrix())
    .setShaderMatrix<NORMAL>(camera.getNormalMatrix())
    .setShaderUniform("u_light_position", lightPosition)
    .setShaderUniform("u_light_color", glm::vec3(1.0, 1.0, 1.0))
    .setShaderUniform("u_light_intensity", 1.0f)
    .setShaderUniform("u_ambient_color", glm::vec3(0, 0, 0))
    .setShaderUniform("u_diffuse_color", glm::vec3(1.0f, 0.5f, 0.0f))
    .setShaderUniform("u_specular_color", glm::vec3(1, 1, 1))
    .setShaderUniform("u_shininess", 25.0f)
    .apply();

  modelBatch.flush();
}
<|endoftext|>


<commit_before>/*!
 * \file x11/RandR/iRandR_reload.cpp
 * \brief \b Classes: \a iRandR
 */
/*
 * Copyright (C) 2015 EEnginE project
 *
 * 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.
 */

#if D_LOG_XRANDR

#include "iRandR.hpp"
#include "uLog.hpp"
#include "eCMDColor.hpp"

namespace e_engine {

namespace unix_x11 {

namespace {

/*!
 * \brief Fill a string with chars until it has a specific size.
 *
 * \param _str  [in] The string to resize
 * \param _size [in] The wished size
 * \param _fill [in] Fill it with these chars
 *
 * \returns The result
 */
std::string placeStringLeft( std::string _str, unsigned int _size, char _fill ) {
   if ( _str.size() == _size )
      return _str;

   std::string lResult_str = _str;
   if ( lResult_str.size() > _size ) {
      lResult_str.resize( _size );
      return lResult_str;
   }

   lResult_str.append( _size - lResult_str.size(), _fill );
   return lResult_str;
}
}

/*!
 * \brief Prints a (more or less) fancy table with all XRandR information
 */
void iRandR::printRandRStatus() {
   if ( !vIsRandRSupported_B )
      return;

   reload( false );

   std::wstring lOFF_C = eCMDColor::color( 'O', 'W' );
   std::wstring lBW_C  = eCMDColor::color( 'B', 'W' );
   std::wstring lBR_C  = eCMDColor::color( 'B', 'R' );
   std::wstring lBG_C  = eCMDColor::color( 'B', 'G' );
   std::wstring lBB_C  = eCMDColor::color( 'B', 'B' );
   std::wstring lBC_C  = eCMDColor::color( 'B', 'C' );

   std::wstring lR_C = eCMDColor::color( 'O', 'R' );
   std::wstring lG_C = eCMDColor::color( 'O', 'G' );
   std::wstring lB_C = eCMDColor::color( 'O', 'B' );
   std::wstring lC_C = eCMDColor::color( 'O', 'C' );

   //
   //   -- HEADDER
   //
   //    |============|======|=========|===========|============|=========================|
   //    |   Output   | CRTC | Primary | Connected |  Position  |          MODE           |
   //    |            |      |         |           |            |  Resolutions  |  Rates  |
   //    |------------|------|---------|-----------|------------|---------------|---------|
   iLOG( "RandR Info -- Screen Size: ", lBG_C, vScreenWidth_uI, 'x', vScreenHeight_uI, "\n" );

   LOG( _hD, "|============|======|=========|===========|============|=========================|" );
   LOG( _hD,
        "|   ",
        lBW_C,
        "Output",
        lOFF_C,
        "   | ",
        lBW_C,
        "CRTC",
        lOFF_C,
        " | ",
        lBW_C,
        "Primary",
        lOFF_C,
        " | ",
        lBW_C,
        "Connected",
        lOFF_C,
        " |  ",
        lBW_C,
        "Position",
        lOFF_C,
        "  |          ",
        lBW_C,
        "MODE",
        lOFF_C,
        "           |" );
   LOG( _hD,
        "|            |      |         |           |            |  ",
        lBW_C,
        "Resolutions",
        lOFF_C,
        "  |  ",
        lBW_C,
        "Rates",
        lOFF_C,
        "  |" );
   LOG( _hD, "|------------|------|---------|-----------|------------|---------------|---------|" );
   //
   //   -- Entries
   //
   for ( internal::_output const &fOutput : vOutput_V_RandR ) {
      internal::_crtc lCRTC_RandR;

      std::string lCRTC_str    = ( fOutput.crtc == 0 ) ? "OFF" : std::to_string( fOutput.crtc );
      std::string lPrimary_str = ( vLatestConfig_RandR.primary == fOutput.id ) ? "YES" : "NO";
      std::string lConnected_str =
            ( fOutput.connection == 0 ) ? "YES" : ( fOutput.connection == 2 ) ? "???" : "NO";
      std::string lPosition_str = "   NONE";

      char lBold_C = ( fOutput.connection == 0 ) ? 'B' : 'O';
      char lCRTC_C = ( lCRTC_str != "OFF" ) ? 'G' : 'R';

      if ( !( fOutput.crtc == 0 ) ) {
         for ( internal::_crtc const &fCRTC : vCRTC_V_RandR ) {
            if ( fCRTC.id == fOutput.crtc ) {
               lCRTC_RandR   = fCRTC;
               lPosition_str = "";
               if ( fCRTC.posX >= 0 )
                  lPosition_str += '+';

               lPosition_str += std::to_string( fCRTC.posX );

               if ( fCRTC.posY >= 0 )
                  lPosition_str += '+';

               lPosition_str += std::to_string( fCRTC.posY );
               break;
            }
         }
      }

      std::wstring lCO_C = eCMDColor::color( 'O', 'W' );
      std::wstring lC1_C = eCMDColor::color( lBold_C, 'W' );
      std::wstring lC2_C = eCMDColor::color( lBold_C, lCRTC_C );

      if ( lBold_C == 'B' ) {
         LOG( _hD,
              "|            |      |         |           |            |               |       "
              "  |" );
      }

      if ( lBold_C == 'O' || fOutput.modes.size() == 0 ) {
         LOG( _hD,
              "| ",
              lC1_C,
              placeStringLeft( fOutput.name, 11, ' ' ),
              lCO_C,
              "| ",
              lC2_C,
              placeStringLeft( lCRTC_str, 5, ' ' ),
              lCO_C,
              "|   ",
              lC1_C,
              placeStringLeft( lPrimary_str, 6, ' ' ),
              lCO_C,
              "|    ",
              lC1_C,
              placeStringLeft( lConnected_str, 7, ' ' ),
              lCO_C,
              "| ",
              lC1_C,
              placeStringLeft( lPosition_str, 11, ' ' ),
              lCO_C,
              "|    OFFLINE    |   OFF   |" );
      }

      unsigned int lWidth_uI  = 0;
      unsigned int lHeight_uI = 0;

      std::string lModeSize_str;
      // Unfortunately std::to_string doesn't support precision, so we must use sprintf if we want
      // to avoid the slow stringstreams
      char lModeFreq_CSTR[15];
      std::string lModeFreq_str;

      bool lIsFirstModePrinted_B = true;

      //
      //   -- Modes
      //
      for ( internal::_mode const &fMode : vMode_V_RandR ) {
         bool lFoundMode_B            = false;
         bool lModePrefered_B         = false;
         char lAtrib_C                = 'O';
         char lColor_C                = 'W';
         unsigned int lModeCounter_uI = 0; //!< Needed for preferred check

         // Check if the mode is supported by the output
         for ( RRMode const &fTempMode : fOutput.modes ) {
            ++lModeCounter_uI;
            if ( fTempMode == fMode.id ) {
               lFoundMode_B = true;

               if ( lModeCounter_uI == static_cast<unsigned int>( fOutput.npreferred ) )
                  lModePrefered_B = true;

               break;
            }
         }

         if ( !lFoundMode_B )
            continue;

         if ( fMode.width == lWidth_uI && fMode.height == lHeight_uI ) {
            lModeSize_str.clear();
         } else {
            lWidth_uI     = fMode.width;
            lHeight_uI    = fMode.height;
            lModeSize_str = std::to_string( lWidth_uI ) + 'x' + std::to_string( lHeight_uI );
         }

         snprintf( lModeFreq_CSTR, 15, "%.2f", fMode.refresh );
         lModeFreq_str = lModeFreq_CSTR;

         // This should never happen
         if ( !lFoundMode_B ) {
            lModeSize_str = "RandR";
            lModeFreq_str = "ERROR";
         }

         // This is a (!) mode with the current width and height of the CRTC
         if ( lWidth_uI == lCRTC_RandR.width && lHeight_uI == lCRTC_RandR.height ) {
            lAtrib_C = 'B';
            if ( !lModeSize_str.empty() )
               lModeSize_str += '*';
         }

         // This is the (!) mode of the CRTC
         if ( fMode.id == lCRTC_RandR.mode ) {
            lAtrib_C = 'B';
            lModeFreq_str += '*';
         }

         // This is the preferred mode
         if ( lModePrefered_B ) {
            lColor_C = 'G';
            lModeFreq_str += '+';
         }

         std::wstring lC3_C = eCMDColor::color( lAtrib_C, lColor_C );

         if ( !lIsFirstModePrinted_B ) {
            LOG( _hD,
                 "|            |      |         |           |            |   ",
                 lC3_C,
                 placeStringLeft( lModeSize_str, 12, ' ' ),
                 lCO_C,
                 "| ",
                 lC3_C,
                 placeStringLeft( lModeFreq_str, 8, ' ' ),
                 lCO_C,
                 '|' );
         } else {
            LOG( _hD,
                 "| ",
                 lC1_C,
                 placeStringLeft( fOutput.name, 11, ' ' ),
                 lCO_C,
                 "| ",
                 lC2_C,
                 placeStringLeft( lCRTC_str, 5, ' ' ),
                 lCO_C,
                 "|   ",
                 lC1_C,
                 placeStringLeft( lPrimary_str, 6, ' ' ),
                 lCO_C,
                 "|    ",
                 lC1_C,
                 placeStringLeft( lConnected_str, 7, ' ' ),
                 lCO_C,
                 "| ",
                 lC1_C,
                 placeStringLeft( lPosition_str, 11, ' ' ),
                 lCO_C,
                 "|   ",
                 lC3_C,
                 placeStringLeft( lModeSize_str, 12, ' ' ),
                 lCO_C,
                 "| ",
                 lC3_C,
                 placeStringLeft( lModeFreq_str, 8, ' ' ),
                 lCO_C,
                 '|' );
         }

         lIsFirstModePrinted_B = false;
      }
   }

   LOG( _hD,
        "|============|======|=========|===========|============|=========================|\n\n" );
}

} // unix_x11

} // e_engine

#endif // D_LOG_XRANDR

// kate: indent-mode cstyle; indent-width 3; replace-tabs on; line-numbers on;
<commit_msg>Fix log activated build.<commit_after>/*!
 * \file x11/RandR/iRandR_reload.cpp
 * \brief \b Classes: \a iRandR
 */
/*
 * Copyright (C) 2015 EEnginE project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "defines.hpp"

#if D_LOG_XRANDR

#include "iRandR.hpp"
#include "uLog.hpp"
#include "eCMDColor.hpp"

namespace e_engine {

namespace unix_x11 {

namespace {

/*!
 * \brief Fill a string with chars until it has a specific size.
 *
 * \param _str  [in] The string to resize
 * \param _size [in] The wished size
 * \param _fill [in] Fill it with these chars
 *
 * \returns The result
 */
std::string placeStringLeft( std::string _str, unsigned int _size, char _fill ) {
   if ( _str.size() == _size )
      return _str;

   std::string lResult_str = _str;
   if ( lResult_str.size() > _size ) {
      lResult_str.resize( _size );
      return lResult_str;
   }

   lResult_str.append( _size - lResult_str.size(), _fill );
   return lResult_str;
}
}

/*!
 * \brief Prints a (more or less) fancy table with all XRandR information
 */
void iRandR::printRandRStatus() {
   if ( !vIsRandRSupported_B )
      return;

   reload( false );

   std::wstring lOFF_C = eCMDColor::color( 'O', 'W' );
   std::wstring lBW_C  = eCMDColor::color( 'B', 'W' );
   std::wstring lBR_C  = eCMDColor::color( 'B', 'R' );
   std::wstring lBG_C  = eCMDColor::color( 'B', 'G' );
   std::wstring lBB_C  = eCMDColor::color( 'B', 'B' );
   std::wstring lBC_C  = eCMDColor::color( 'B', 'C' );

   std::wstring lR_C = eCMDColor::color( 'O', 'R' );
   std::wstring lG_C = eCMDColor::color( 'O', 'G' );
   std::wstring lB_C = eCMDColor::color( 'O', 'B' );
   std::wstring lC_C = eCMDColor::color( 'O', 'C' );

   //
   //   -- HEADDER
   //
   //    |============|======|=========|===========|============|=========================|
   //    |   Output   | CRTC | Primary | Connected |  Position  |          MODE           |
   //    |            |      |         |           |            |  Resolutions  |  Rates  |
   //    |------------|------|---------|-----------|------------|---------------|---------|
   iLOG( "RandR Info -- Screen Size: ", lBG_C, vScreenWidth_uI, 'x', vScreenHeight_uI, "\n" );

   LOG( _hD, "|============|======|=========|===========|============|=========================|" );
   LOG( _hD,
        "|   ",
        lBW_C,
        "Output",
        lOFF_C,
        "   | ",
        lBW_C,
        "CRTC",
        lOFF_C,
        " | ",
        lBW_C,
        "Primary",
        lOFF_C,
        " | ",
        lBW_C,
        "Connected",
        lOFF_C,
        " |  ",
        lBW_C,
        "Position",
        lOFF_C,
        "  |          ",
        lBW_C,
        "MODE",
        lOFF_C,
        "           |" );
   LOG( _hD,
        "|            |      |         |           |            |  ",
        lBW_C,
        "Resolutions",
        lOFF_C,
        "  |  ",
        lBW_C,
        "Rates",
        lOFF_C,
        "  |" );
   LOG( _hD, "|------------|------|---------|-----------|------------|---------------|---------|" );
   //
   //   -- Entries
   //
   for ( internal::_output const &fOutput : vOutput_V_RandR ) {
      internal::_crtc lCRTC_RandR;

      std::string lCRTC_str    = ( fOutput.crtc == 0 ) ? "OFF" : std::to_string( fOutput.crtc );
      std::string lPrimary_str = ( vLatestConfig_RandR.primary == fOutput.id ) ? "YES" : "NO";
      std::string lConnected_str =
            ( fOutput.connection == 0 ) ? "YES" : ( fOutput.connection == 2 ) ? "???" : "NO";
      std::string lPosition_str = "   NONE";

      char lBold_C = ( fOutput.connection == 0 ) ? 'B' : 'O';
      char lCRTC_C = ( lCRTC_str != "OFF" ) ? 'G' : 'R';

      if ( !( fOutput.crtc == 0 ) ) {
         for ( internal::_crtc const &fCRTC : vCRTC_V_RandR ) {
            if ( fCRTC.id == fOutput.crtc ) {
               lCRTC_RandR   = fCRTC;
               lPosition_str = "";
               if ( fCRTC.posX >= 0 )
                  lPosition_str += '+';

               lPosition_str += std::to_string( fCRTC.posX );

               if ( fCRTC.posY >= 0 )
                  lPosition_str += '+';

               lPosition_str += std::to_string( fCRTC.posY );
               break;
            }
         }
      }

      std::wstring lCO_C = eCMDColor::color( 'O', 'W' );
      std::wstring lC1_C = eCMDColor::color( lBold_C, 'W' );
      std::wstring lC2_C = eCMDColor::color( lBold_C, lCRTC_C );

      if ( lBold_C == 'B' ) {
         LOG( _hD,
              "|            |      |         |           |            |               |       "
              "  |" );
      }

      if ( lBold_C == 'O' || fOutput.modes.size() == 0 ) {
         LOG( _hD,
              "| ",
              lC1_C,
              placeStringLeft( fOutput.name, 11, ' ' ),
              lCO_C,
              "| ",
              lC2_C,
              placeStringLeft( lCRTC_str, 5, ' ' ),
              lCO_C,
              "|   ",
              lC1_C,
              placeStringLeft( lPrimary_str, 6, ' ' ),
              lCO_C,
              "|    ",
              lC1_C,
              placeStringLeft( lConnected_str, 7, ' ' ),
              lCO_C,
              "| ",
              lC1_C,
              placeStringLeft( lPosition_str, 11, ' ' ),
              lCO_C,
              "|    OFFLINE    |   OFF   |" );
      }

      unsigned int lWidth_uI  = 0;
      unsigned int lHeight_uI = 0;

      std::string lModeSize_str;
      // Unfortunately std::to_string doesn't support precision, so we must use sprintf if we want
      // to avoid the slow stringstreams
      char lModeFreq_CSTR[15];
      std::string lModeFreq_str;

      bool lIsFirstModePrinted_B = true;

      //
      //   -- Modes
      //
      for ( internal::_mode const &fMode : vMode_V_RandR ) {
         bool lFoundMode_B            = false;
         bool lModePrefered_B         = false;
         char lAtrib_C                = 'O';
         char lColor_C                = 'W';
         unsigned int lModeCounter_uI = 0; //!< Needed for preferred check

         // Check if the mode is supported by the output
         for ( RRMode const &fTempMode : fOutput.modes ) {
            ++lModeCounter_uI;
            if ( fTempMode == fMode.id ) {
               lFoundMode_B = true;

               if ( lModeCounter_uI == static_cast<unsigned int>( fOutput.npreferred ) )
                  lModePrefered_B = true;

               break;
            }
         }

         if ( !lFoundMode_B )
            continue;

         if ( fMode.width == lWidth_uI && fMode.height == lHeight_uI ) {
            lModeSize_str.clear();
         } else {
            lWidth_uI     = fMode.width;
            lHeight_uI    = fMode.height;
            lModeSize_str = std::to_string( lWidth_uI ) + 'x' + std::to_string( lHeight_uI );
         }

         snprintf( lModeFreq_CSTR, 15, "%.2f", fMode.refresh );
         lModeFreq_str = lModeFreq_CSTR;

         // This should never happen
         if ( !lFoundMode_B ) {
            lModeSize_str = "RandR";
            lModeFreq_str = "ERROR";
         }

         // This is a (!) mode with the current width and height of the CRTC
         if ( lWidth_uI == lCRTC_RandR.width && lHeight_uI == lCRTC_RandR.height ) {
            lAtrib_C = 'B';
            if ( !lModeSize_str.empty() )
               lModeSize_str += '*';
         }

         // This is the (!) mode of the CRTC
         if ( fMode.id == lCRTC_RandR.mode ) {
            lAtrib_C = 'B';
            lModeFreq_str += '*';
         }

         // This is the preferred mode
         if ( lModePrefered_B ) {
            lColor_C = 'G';
            lModeFreq_str += '+';
         }

         std::wstring lC3_C = eCMDColor::color( lAtrib_C, lColor_C );

         if ( !lIsFirstModePrinted_B ) {
            LOG( _hD,
                 "|            |      |         |           |            |   ",
                 lC3_C,
                 placeStringLeft( lModeSize_str, 12, ' ' ),
                 lCO_C,
                 "| ",
                 lC3_C,
                 placeStringLeft( lModeFreq_str, 8, ' ' ),
                 lCO_C,
                 '|' );
         } else {
            LOG( _hD,
                 "| ",
                 lC1_C,
                 placeStringLeft( fOutput.name, 11, ' ' ),
                 lCO_C,
                 "| ",
                 lC2_C,
                 placeStringLeft( lCRTC_str, 5, ' ' ),
                 lCO_C,
                 "|   ",
                 lC1_C,
                 placeStringLeft( lPrimary_str, 6, ' ' ),
                 lCO_C,
                 "|    ",
                 lC1_C,
                 placeStringLeft( lConnected_str, 7, ' ' ),
                 lCO_C,
                 "| ",
                 lC1_C,
                 placeStringLeft( lPosition_str, 11, ' ' ),
                 lCO_C,
                 "|   ",
                 lC3_C,
                 placeStringLeft( lModeSize_str, 12, ' ' ),
                 lCO_C,
                 "| ",
                 lC3_C,
                 placeStringLeft( lModeFreq_str, 8, ' ' ),
                 lCO_C,
                 '|' );
         }

         lIsFirstModePrinted_B = false;
      }
   }

   LOG( _hD,
        "|============|======|=========|===========|============|=========================|\n\n" );
}

} // unix_x11

} // e_engine

#endif // D_LOG_XRANDR

// kate: indent-mode cstyle; indent-width 3; replace-tabs on; line-numbers on;
<|endoftext|>


<commit_before>// dui-demo.cpp : main source file
//

#include "stdafx.h"
#include "DuiSystem.h"

#ifdef _DEBUG
#include <vld.h>//ʹVitural Leaker Detectorڴй©Դhttp://vld.codeplex.com/
#endif

#include "MainDlg.h"

#ifndef DLL_SOUI
#include "../render-skia/render-skia.h"
#include "../imgdecoder-wic/imgdecoder-wic.h"

#ifdef _DEBUG
#pragma comment(lib,"utilities_d.lib")
#pragma comment(lib,"render-skia_d.lib")
#pragma comment(lib,"imgdecoder-wic_d.lib")
#pragma comment(lib,"skcore_d.lib")
#else
#pragma comment(lib,"utilities.lib")
#pragma comment(lib,"render-skia.lib")
#pragma comment(lib,"imgdecoder-wic.lib")
#pragma comment(lib,"skcore.lib")
#endif
#endif

int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpstrCmdLine*/, int /*nCmdShow*/)
{
	HRESULT hRes = OleInitialize(NULL);
	DUIASSERT(SUCCEEDED(hRes));

    CAutoRefPtr<SOUI::IImgDecoderFactory> pImgDecoderFactory;
    CAutoRefPtr<SOUI::IRenderFactory> pRenderFactory;

#ifndef _LIB
#ifdef _DEBUG
    HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic_d.dll"));
    HMODULE hRender = LoadLibrary(_T("render-skia_d.dll"));
#else
    HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic.dll"));
    HMODULE hRender = LoadLibrary(_T("render-skia.dll"));
#endif
    typedef BOOL (*fnCreateImgDecoderFactory)(SOUI::IImgDecoderFactory**);
    fnCreateImgDecoderFactory funImg = (fnCreateImgDecoderFactory)GetProcAddress(hImgDecoder,"CreateImgDecoderFactory");
    funImg(&pImgDecoderFactory);

    typedef BOOL (*fnCreateRenderFactory)(SOUI::IRenderFactory **,SOUI::IImgDecoderFactory *);
    fnCreateRenderFactory funRender = (fnCreateRenderFactory)GetProcAddress(hRender,"CreateRenderFactory");
    funRender(&pRenderFactory,pImgDecoderFactory);
#else
    SOUI::CreateImgDecoderFactory(&pImgDecoderFactory);
    RENDER_SKIA::CreateRenderFactory(&pRenderFactory,pImgDecoderFactory);
#endif

	DuiSystem *pDuiSystem=new DuiSystem(pRenderFactory,hInstance);

#if 1
    TCHAR szCurrentDir[MAX_PATH]; memset( szCurrentDir, 0, sizeof(szCurrentDir) );
    GetModuleFileName( NULL, szCurrentDir, sizeof(szCurrentDir) );
    LPTSTR lpInsertPos = _tcsrchr( szCurrentDir, _T('\\') );
    *lpInsertPos = _T('\0');
    _tcscat( szCurrentDir, _T("\\..\\demo\\skin") );

    DuiResProviderFiles *pResProvider=new DuiResProviderFiles;
    if(!pResProvider->Init(szCurrentDir))
    {
        DUIASSERT(0);
        return 1;
    }
#else
    DuiResProviderPE *pResProvider = new DuiResProviderPE(hInstance);
#endif

    pDuiSystem->AddResProvider(pResProvider);

	BOOL bOK=pDuiSystem->Init(_T("IDR_DUI_INIT")); //ʼDUIϵͳ,ԭϵͳʼʽȻʹá
	pDuiSystem->SetMsgBoxTemplate(_T("IDR_DUI_MSGBOX"));

	int nRet = 0;
	// BLOCK: Run application
	{
		CMainDlg dlgMain;
		nRet = dlgMain.DoModal();
	}

	delete pDuiSystem;

    delete pResProvider;

    pRenderFactory=NULL;
    pImgDecoderFactory=NULL;

	OleUninitialize();
	return nRet;
}
<commit_msg><commit_after>// dui-demo.cpp : main source file
//

#include "stdafx.h"
#include "DuiSystem.h"

#ifdef _DEBUG
#include <vld.h>//ʹVitural Leaker Detectorڴй©Դhttp://vld.codeplex.com/
#endif

#include "MainDlg.h"

#ifndef DLL_SOUI
#include "../render-skia/render-skia.h"
#include "../imgdecoder-wic/imgdecoder-wic.h"

#ifdef _DEBUG
#pragma comment(lib,"utilities_d.lib")
#pragma comment(lib,"render-skia_d.lib")
#pragma comment(lib,"imgdecoder-wic_d.lib")
#pragma comment(lib,"skcore_d.lib")
#else
#pragma comment(lib,"utilities.lib")
#pragma comment(lib,"render-skia.lib")
#pragma comment(lib,"imgdecoder-wic.lib")
#pragma comment(lib,"skcore.lib")
#endif
#endif

int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpstrCmdLine*/, int /*nCmdShow*/)
{
	HRESULT hRes = OleInitialize(NULL);
	DUIASSERT(SUCCEEDED(hRes));

    CAutoRefPtr<SOUI::IImgDecoderFactory> pImgDecoderFactory;
    CAutoRefPtr<SOUI::IRenderFactory> pRenderFactory;

#ifndef _LIB
#ifdef _DEBUG
    HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic_d.dll"));
    HMODULE hRender = LoadLibrary(_T("render-skia_d.dll"));
#else
    HMODULE hImgDecoder = LoadLibrary(_T("imgdecoder-wic.dll"));
    HMODULE hRender = LoadLibrary(_T("render-skia.dll"));
#endif
    typedef BOOL (*fnCreateImgDecoderFactory)(SOUI::IImgDecoderFactory**,BOOL);
    fnCreateImgDecoderFactory funImg = (fnCreateImgDecoderFactory)GetProcAddress(hImgDecoder,"CreateImgDecoderFactory_WIC");
    funImg(&pImgDecoderFactory,TRUE);

    typedef BOOL (*fnCreateRenderFactory)(SOUI::IRenderFactory **,SOUI::IImgDecoderFactory *);
    fnCreateRenderFactory funRender = (fnCreateRenderFactory)GetProcAddress(hRender,"CreateRenderFactory");
    funRender(&pRenderFactory,pImgDecoderFactory);
#else
    SOUI::CreateImgDecoderFactory_WIC(&pImgDecoderFactory,TRUE);
    RENDER_SKIA::CreateRenderFactory(&pRenderFactory,pImgDecoderFactory);
#endif

	DuiSystem *pDuiSystem=new DuiSystem(pRenderFactory,hInstance);

#if 1
    TCHAR szCurrentDir[MAX_PATH]; memset( szCurrentDir, 0, sizeof(szCurrentDir) );
    GetModuleFileName( NULL, szCurrentDir, sizeof(szCurrentDir) );
    LPTSTR lpInsertPos = _tcsrchr( szCurrentDir, _T('\\') );
    *lpInsertPos = _T('\0');
    _tcscat( szCurrentDir, _T("\\..\\demo\\skin") );

    DuiResProviderFiles *pResProvider=new DuiResProviderFiles;
    if(!pResProvider->Init(szCurrentDir))
    {
        DUIASSERT(0);
        return 1;
    }
#else
    DuiResProviderPE *pResProvider = new DuiResProviderPE(hInstance);
#endif

    pDuiSystem->AddResProvider(pResProvider);

	BOOL bOK=pDuiSystem->Init(_T("IDR_DUI_INIT")); //ʼDUIϵͳ,ԭϵͳʼʽȻʹá
	pDuiSystem->SetMsgBoxTemplate(_T("IDR_DUI_MSGBOX"));

	int nRet = 0;
	// BLOCK: Run application
	{
		CMainDlg dlgMain;
		nRet = dlgMain.DoModal();
	}

	delete pDuiSystem;

    delete pResProvider;

    pRenderFactory=NULL;
    pImgDecoderFactory=NULL;

	OleUninitialize();
	return nRet;
}
<|endoftext|>