<commit_before>#include <bitbots_ros_control/wolfgang_hardware_interface.h>

namespace bitbots_ros_control {

/**
 * This class provides a combination of multiple hardware interfaces to construct a complete Wolfgang robot.
 * It is similar to a CombinedRobotHw class as specified in ros_control, but it is changed a bit to make sharing of
 * a common bus driver over multiple hardware interfaces possible.
 */
WolfgangHardwareInterface::WolfgangHardwareInterface(rclcpp::Node::SharedPtr nh) : servo_interface_(nh) {
  nh_ = nh;
  first_ping_error_ = true;
  speak_pub_ = nh->create_publisher<humanoid_league_msgs::msg::Audio>("/speak", 1);

  // load parameters
  nh_->get_parameter("only_imu", only_imu_);
  nh_->get_parameter("only_pressure", only_pressure_);
  if (only_imu_) RCLCPP_WARN(nh_->get_logger(), "Starting in only IMU mode");
  if (only_pressure_) RCLCPP_WARN(nh_->get_logger(), "starting in only pressure sensor mode");

  if (only_pressure_ && only_imu_) {
    RCLCPP_ERROR(nh_->get_logger(), "only_imu AND only_pressure was set to true");
    exit(1);
  }

  // get list of all bus devices
  rcl_interfaces::msg::ListParametersResult device_name_list = nh_->list_parameters({"device_info"}, 3);

  // Convert dxls to native type: a vector of tuples with name and id for sorting purposes
  std::vector<std::pair<std::string, int>> dxl_devices;
  for (const std::string &parameter_name: device_name_list.names) {
    // we get directly the parameters and not the groups. use id parameter to identify them
    if (parameter_name.find(".id")!=std::string::npos) {
      int id = nh->get_parameter(parameter_name).as_int();
      // remove "device_info." and ".id"
      std::string device_name = parameter_name.substr(12, parameter_name.size() - 3 - 12);
      dxl_devices.emplace_back(device_name, id);
    }
  }

  // sort the devices by id. This way the devices will always be read and written in ID order later, making debug easier.
  std::sort(dxl_devices.begin(), dxl_devices.end(),
            [](std::pair<std::string, int> &a, std::pair<std::string, int> &b) { return a.second < b.second; });

  // create overall servo interface since we need a single interface for the controllers
  servo_interface_ = DynamixelServoHardwareInterface(nh);

  // try to ping all devices on the list, add them to the driver and create corresponding hardware interfaces
  // try until interruption to enable the user to turn on the power
  while (rclcpp::ok()) {
    if (create_interfaces(dxl_devices)) {
      break;
    }
    nh_->get_clock()->sleep_for(rclcpp::Duration::from_seconds(3));
  }
}

bool WolfgangHardwareInterface::create_interfaces(std::vector<std::pair<std::string, int>> dxl_devices) {
  interfaces_ = std::vector<std::vector<bitbots_ros_control::HardwareInterface * >>();
  // init bus drivers
  std::vector<std::string> pinged;
  rcl_interfaces::msg::ListParametersResult port_list = nh_->list_parameters({"port_info"}, 3);
  for (const std::string &parameter_name: port_list.names) {
    // we get directly the parameters and not the groups. use id parameter to identify them
    if (parameter_name.find(".device_file")!=std::string::npos) {
      std::string port_name = parameter_name.substr(10, parameter_name.size() - 11 - 11);
      // read bus driver specifications from config
      std::string device_file = nh_->get_parameter("port_info." + port_name + ".device_file").as_string();
      int baudrate = nh_->get_parameter("port_info." + port_name + ".baudrate").as_int();
      int protocol_version = nh_->get_parameter("port_info." + port_name + ".protocol_version").as_int();
      auto driver = std::make_shared<DynamixelDriver>();
      if (!driver->init(device_file.c_str(), uint32_t(baudrate))) {
        RCLCPP_ERROR(nh_->get_logger(), "Error opening serial port %s", device_file.c_str());
        speakError(speak_pub_, "Error opening serial port");
        sleep(1);
        exit(1);
      }
      // some interface seem to produce some gitter directly after connecting. wait or it will interfere with pings
      // uncomment the following line if you are using such an interface
      // sleep(1);
      driver->setPacketHandler(protocol_version);
      std::vector<bitbots_ros_control::HardwareInterface *> interfaces_on_port;
      // iterate over all devices and ping them to see what is connected to this bus
      std::vector<std::tuple<int, std::string, float, float>> servos_on_port;
      for (std::pair<std::string, int> &device: dxl_devices) {
        RCLCPP_INFO_STREAM(nh_->get_logger(), device.first);
        std::string name = device.first;
        int id = device.second;
        if (std::find(pinged.begin(), pinged.end(), device.first)!=pinged.end()) {
          // we already found this and don't have to search again
        } else {
          int model_number_specified;
          nh_->get_parameter("device_info." + name + ".model_number", model_number_specified);
          // some devices provide more than one type of interface, e.g. the IMU provides additionally buttons and LEDs
          std::string interface_type;
          nh_->get_parameter("device_info." + name + ".interface_type", interface_type);
          uint16_t model_number_specified_16 = uint16_t(model_number_specified);
          uint16_t *model_number_returned_16 = new uint16_t;
          if (driver->ping(uint8_t(id), model_number_returned_16)) {
            // check if the specified model number matches the actual model number of the device
            if (model_number_specified_16!=*model_number_returned_16) {
              RCLCPP_WARN(nh_->get_logger(), "Model number of id %d does not match", id);
            }
            // ping was successful, add device correspondingly
            // only add them if the mode is set correspondingly
            // TODO maybe move more of the parameter stuff in the init of the modules instead of doing everything here
            if (model_number_specified==0xABBA && interface_type=="CORE") {
              // CORE
              int read_rate;
              nh_->get_parameter("device_info." + name + ".read_rate", read_rate);
              driver->setTools(model_number_specified_16, id);
              CoreHardwareInterface *interface = new CoreHardwareInterface(nh_, driver, id, read_rate);
              // turn on power, just to be sure
              interface->write(nh_->get_clock()->now(), rclcpp::Duration::from_nanoseconds(1e9*0));
              interfaces_on_port.push_back(interface);
            } else if (model_number_specified==0 && !only_imu_) {//model number is currently 0 on foot sensors
              // bitfoot
              std::string topic;
              if (!nh_->get_parameter("device_info." + name + ".topic", topic)) {
                RCLCPP_WARN(nh_->get_logger(), "Bitfoot topic not specified");
              }
              BitFootHardwareInterface *interface = new BitFootHardwareInterface(nh_, driver, id, topic, name);
              interfaces_on_port.push_back(interface);
            } else if (model_number_specified==0xBAFF && interface_type=="IMU" && !only_pressure_) {
              //IMU
              std::string topic;
              if (!nh_->get_parameter("device_info." + name + ".topic", topic)) {
                RCLCPP_WARN(nh_->get_logger(), "IMU topic not specified");
              }
              std::string frame;
              if (!nh_->get_parameter("device_info." + name + ".frame", frame)) {
                RCLCPP_WARN(nh_->get_logger(), "IMU frame not specified");
              }
              driver->setTools(model_number_specified_16, id);
              ImuHardwareInterface *interface = new ImuHardwareInterface(nh_, driver, id, topic, frame, name);
              /* Hardware interfaces must be registered at the main RobotHW class.
               * Therefore, a pointer to this class is passed down to the RobotHW classes
               * registering further interfaces */
              interfaces_on_port.push_back(interface);
            } else if (model_number_specified==0xBAFF && interface_type=="Button" && !only_pressure_) {
              // Buttons
              std::string topic;
              if (!nh_->get_parameter("device_info." + name + ".topic", topic)) {
                RCLCPP_WARN(nh_->get_logger(), "Button topic not specified");
              }
              int read_rate;
              nh_->get_parameter("device_info." + name + ".read_rate", read_rate);
              interfaces_on_port.push_back(new ButtonHardwareInterface(nh_, driver, id, topic, read_rate));
            } else if ((model_number_specified==0xBAFF || model_number_specified==0xABBA) && interface_type=="LED"
                && !only_pressure_) {
              // LEDs
              int number_of_LEDs, start_number;
              nh_->get_parameter("device_info." + name + ".number_of_LEDs", number_of_LEDs);
              nh_->get_parameter("device_info." + name + ".start_number", start_number);
              interfaces_on_port.push_back(new LedsHardwareInterface(nh_, driver, id, number_of_LEDs, start_number));
            } else if ((model_number_specified==311 || model_number_specified==321 || model_number_specified==1100)
                && !only_pressure_
                && !only_imu_) {
              // Servos
              // We need to add the tool to the driver for later reading and writing
              driver->setTools(model_number_specified_16, id);
              float mounting_offset;
              nh_->get_parameter("device_info." + name + ".mounting_offset", mounting_offset);
              float joint_offset;
              nh_->get_parameter("device_info." + name + ".joint_offset", joint_offset);
              servos_on_port.push_back(std::make_tuple(id, name, mounting_offset, joint_offset));
            } else {
              if (!only_pressure_ && !only_imu_) {
                RCLCPP_WARN(nh_->get_logger(), "Could not identify device for ID %d", id);
              }
            }
            pinged.push_back(name);
          }
          delete model_number_returned_16;
        }
      }
      // create a servo bus interface if there were servos found on this bus
      if (servos_on_port.size() > 0) {
        ServoBusInterface *interface = new ServoBusInterface(nh_, driver, servos_on_port);
        interfaces_on_port.push_back(interface);
        servo_interface_.addBusInterface(interface);
      }
      // add vector of interfaces on this port to overall collection of interfaces
      interfaces_.push_back(interfaces_on_port);
    }
  }

  if (pinged.size()!=dxl_devices.size()) {
    // when we only have 1 or two devices it's only the core
    if (pinged.empty() || pinged.size()==1 || pinged.size()==2) {
      RCLCPP_ERROR_THROTTLE(nh_->get_logger(), *nh_->get_clock(), 5000, "Could not start ros control. Power is off!");
      speakError(speak_pub_, "Could not start ros control. Power is off!");
    } else {
      if (first_ping_error_) {
        first_ping_error_ = false;
      } else {
        RCLCPP_ERROR(nh_->get_logger(), "Could not ping all devices!");
        speakError(speak_pub_, "error starting ros control");
        // check which devices were not pinged successful
        for (std::pair<std::string, int> &device: dxl_devices) {
          if (std::find(pinged.begin(), pinged.end(), device.first)!=pinged.end()) {
          } else {
            RCLCPP_ERROR(nh_->get_logger(), "%s with id %d missing", device.first.c_str(), device.second);
          }
        }
      }
    }
    return false;
  } else {
    speakError(speak_pub_, "ross control startup successful");
    return true;
  }
}

void threaded_init(std::vector<HardwareInterface *> &port_interfaces, rclcpp::Node::SharedPtr &nh, int &success) {
  success = true;
  for (HardwareInterface *interface: port_interfaces) {
    success &= interface->init();
  }
}

bool WolfgangHardwareInterface::init() {
  // iterate through all ports
  std::vector<std::thread> threads;
  std::vector<int *> successes;
  int i = 0;
  for (std::vector<HardwareInterface *> &port_interfaces: interfaces_) {
    // iterate through all interfaces on this port
    // we use an int instead of bool, since std::ref can't handle bool
    int suc = 0;
    successes.push_back(&suc);
    threads.push_back(std::thread(threaded_init, std::ref(port_interfaces), std::ref(nh_), std::ref(suc)));
    i++;
  }
  // wait for all inits to finish
  for (std::thread &thread: threads) {
    thread.join();
  }
  // see if all inits were successful
  bool success = true;
  for (bool s: successes) {
    success &= s;
  }
  // init servo interface last after all servo busses are there
  success &= servo_interface_.init();
  return success;
}

void threaded_read(std::vector<HardwareInterface *> &port_interfaces,
                   const rclcpp::Time &t,
                   const rclcpp::Duration &dt) {
  for (HardwareInterface *interface: port_interfaces) {
    interface->read(t, dt);
  }
}

void WolfgangHardwareInterface::read(const rclcpp::Time &t, const rclcpp::Duration &dt) {
  std::vector<std::thread> threads;
  // start all reads
  for (std::vector<HardwareInterface *> &port_interfaces: interfaces_) {
    threads.push_back(std::thread(threaded_read, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
  }
  // wait for all reads to finish
  for (std::thread &thread: threads) {
    thread.join();
  }
  // aggregate all servo values for controller
  servo_interface_.read(t, dt);
}

void threaded_write(std::vector<HardwareInterface *> &port_interfaces,
                    const rclcpp::Time &t,
                    const rclcpp::Duration &dt) {
  for (HardwareInterface *interface: port_interfaces) {
    interface->write(t, dt);
  }
}

void WolfgangHardwareInterface::write(const rclcpp::Time &t, const rclcpp::Duration &dt) {
  // write all controller values to interfaces
  servo_interface_.write(t, dt);
  std::vector<std::thread> threads;
  // start all writes
  for (std::vector<HardwareInterface *> &port_interfaces: interfaces_) {
    threads.push_back(std::thread(threaded_write, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
  }

  // wait for all writes to finish
  for (std::thread &thread: threads) {
    thread.join();
  }
}
}<commit_msg>use default param as well<commit_after>#include <bitbots_ros_control/wolfgang_hardware_interface.h>

namespace bitbots_ros_control {

/**
 * This class provides a combination of multiple hardware interfaces to construct a complete Wolfgang robot.
 * It is similar to a CombinedRobotHw class as specified in ros_control, but it is changed a bit to make sharing of
 * a common bus driver over multiple hardware interfaces possible.
 */
WolfgangHardwareInterface::WolfgangHardwareInterface(rclcpp::Node::SharedPtr nh) : servo_interface_(nh) {
  nh_ = nh;
  first_ping_error_ = true;
  speak_pub_ = nh->create_publisher<humanoid_league_msgs::msg::Audio>("/speak", 1);

  // load parameters
  nh_->get_parameter("only_imu", only_imu_);
  nh_->get_parameter("only_pressure", only_pressure_);
  if (only_imu_) RCLCPP_WARN(nh_->get_logger(), "Starting in only IMU mode");
  if (only_pressure_) RCLCPP_WARN(nh_->get_logger(), "starting in only pressure sensor mode");

  if (only_pressure_ && only_imu_) {
    RCLCPP_ERROR(nh_->get_logger(), "only_imu AND only_pressure was set to true");
    exit(1);
  }

  // get list of all bus devices
  rcl_interfaces::msg::ListParametersResult device_name_list = nh_->list_parameters({"device_info"}, 3);

  // Convert dxls to native type: a vector of tuples with name and id for sorting purposes
  std::vector<std::pair<std::string, int>> dxl_devices;
  for (const std::string &parameter_name: device_name_list.names) {
    // we get directly the parameters and not the groups. use id parameter to identify them
    if (parameter_name.find(".id")!=std::string::npos) {
      int id = nh->get_parameter(parameter_name).as_int();
      // remove "device_info." and ".id"
      std::string device_name = parameter_name.substr(12, parameter_name.size() - 3 - 12);
      dxl_devices.emplace_back(device_name, id);
    }
  }

  // sort the devices by id. This way the devices will always be read and written in ID order later, making debug easier.
  std::sort(dxl_devices.begin(), dxl_devices.end(),
            [](std::pair<std::string, int> &a, std::pair<std::string, int> &b) { return a.second < b.second; });

  // create overall servo interface since we need a single interface for the controllers
  servo_interface_ = DynamixelServoHardwareInterface(nh);

  // try to ping all devices on the list, add them to the driver and create corresponding hardware interfaces
  // try until interruption to enable the user to turn on the power
  while (rclcpp::ok()) {
    if (create_interfaces(dxl_devices)) {
      break;
    }
    nh_->get_clock()->sleep_for(rclcpp::Duration::from_seconds(3));
  }
}

bool WolfgangHardwareInterface::create_interfaces(std::vector<std::pair<std::string, int>> dxl_devices) {
  interfaces_ = std::vector<std::vector<bitbots_ros_control::HardwareInterface * >>();
  // init bus drivers
  std::vector<std::string> pinged;
  rcl_interfaces::msg::ListParametersResult port_list = nh_->list_parameters({"port_info"}, 3);
  for (const std::string &parameter_name: port_list.names) {
    // we get directly the parameters and not the groups. use id parameter to identify them
    if (parameter_name.find(".device_file")!=std::string::npos) {
      std::string port_name = parameter_name.substr(10, parameter_name.size() - 11 - 11);
      // read bus driver specifications from config
      std::string device_file = nh_->get_parameter("port_info." + port_name + ".device_file").as_string();
      int baudrate = nh_->get_parameter("port_info." + port_name + ".baudrate").as_int();
      int protocol_version = nh_->get_parameter("port_info." + port_name + ".protocol_version").as_int();
      auto driver = std::make_shared<DynamixelDriver>();
      if (!driver->init(device_file.c_str(), uint32_t(baudrate))) {
        RCLCPP_ERROR(nh_->get_logger(), "Error opening serial port %s", device_file.c_str());
        speakError(speak_pub_, "Error opening serial port");
        sleep(1);
        exit(1);
      }
      // some interface seem to produce some gitter directly after connecting. wait or it will interfere with pings
      // uncomment the following line if you are using such an interface
      // sleep(1);
      driver->setPacketHandler(protocol_version);
      std::vector<bitbots_ros_control::HardwareInterface *> interfaces_on_port;
      // iterate over all devices and ping them to see what is connected to this bus
      std::vector<std::tuple<int, std::string, float, float>> servos_on_port;
      for (std::pair<std::string, int> &device: dxl_devices) {
        RCLCPP_INFO_STREAM(nh_->get_logger(), device.first);
        std::string name = device.first;
        int id = device.second;
        if (std::find(pinged.begin(), pinged.end(), device.first)!=pinged.end()) {
          // we already found this and don't have to search again
        } else {
          int model_number_specified;
          nh_->get_parameter("device_info." + name + ".model_number", model_number_specified);
          // some devices provide more than one type of interface, e.g. the IMU provides additionally buttons and LEDs
          std::string interface_type;
          nh_->get_parameter("device_info." + name + ".interface_type", interface_type);
          uint16_t model_number_specified_16 = uint16_t(model_number_specified);
          uint16_t *model_number_returned_16 = new uint16_t;
          if (driver->ping(uint8_t(id), model_number_returned_16)) {
            // check if the specified model number matches the actual model number of the device
            if (model_number_specified_16!=*model_number_returned_16) {
              RCLCPP_WARN(nh_->get_logger(), "Model number of id %d does not match", id);
            }
            // ping was successful, add device correspondingly
            // only add them if the mode is set correspondingly
            // TODO maybe move more of the parameter stuff in the init of the modules instead of doing everything here
            if (model_number_specified==0xABBA && interface_type=="CORE") {
              // CORE
              int read_rate;
              nh_->get_parameter("device_info." + name + ".read_rate", read_rate);
              driver->setTools(model_number_specified_16, id);
              CoreHardwareInterface *interface = new CoreHardwareInterface(nh_, driver, id, read_rate);
              // turn on power, just to be sure
              interface->write(nh_->get_clock()->now(), rclcpp::Duration::from_nanoseconds(1e9*0));
              interfaces_on_port.push_back(interface);
            } else if (model_number_specified==0 && !only_imu_) {//model number is currently 0 on foot sensors
              // bitfoot
              std::string topic;
              if (!nh_->get_parameter("device_info." + name + ".topic", topic)) {
                RCLCPP_WARN(nh_->get_logger(), "Bitfoot topic not specified");
              }
              BitFootHardwareInterface *interface = new BitFootHardwareInterface(nh_, driver, id, topic, name);
              interfaces_on_port.push_back(interface);
            } else if (model_number_specified==0xBAFF && interface_type=="IMU" && !only_pressure_) {
              //IMU
              std::string topic;
              if (!nh_->get_parameter("device_info." + name + ".topic", topic)) {
                RCLCPP_WARN(nh_->get_logger(), "IMU topic not specified");
              }
              std::string frame;
              if (!nh_->get_parameter("device_info." + name + ".frame", frame)) {
                RCLCPP_WARN(nh_->get_logger(), "IMU frame not specified");
              }
              driver->setTools(model_number_specified_16, id);
              ImuHardwareInterface *interface = new ImuHardwareInterface(nh_, driver, id, topic, frame, name);
              /* Hardware interfaces must be registered at the main RobotHW class.
               * Therefore, a pointer to this class is passed down to the RobotHW classes
               * registering further interfaces */
              interfaces_on_port.push_back(interface);
            } else if (model_number_specified==0xBAFF && interface_type=="Button" && !only_pressure_) {
              // Buttons
              std::string topic;
              if (!nh_->get_parameter("device_info." + name + ".topic", topic)) {
                RCLCPP_WARN(nh_->get_logger(), "Button topic not specified");
              }
              int read_rate;
              nh_->get_parameter("device_info." + name + ".read_rate", read_rate);
              interfaces_on_port.push_back(new ButtonHardwareInterface(nh_, driver, id, topic, read_rate));
            } else if ((model_number_specified==0xBAFF || model_number_specified==0xABBA) && interface_type=="LED"
                && !only_pressure_) {
              // LEDs
              int number_of_LEDs, start_number;
              nh_->get_parameter("device_info." + name + ".number_of_LEDs", number_of_LEDs);
              nh_->get_parameter("device_info." + name + ".start_number", start_number);
              interfaces_on_port.push_back(new LedsHardwareInterface(nh_, driver, id, number_of_LEDs, start_number));
            } else if ((model_number_specified==311 || model_number_specified==321 || model_number_specified==1100)
                && !only_pressure_
                && !only_imu_) {
              // Servos
              // We need to add the tool to the driver for later reading and writing
              driver->setTools(model_number_specified_16, id);
              float mounting_offset;
              nh_->get_parameter_or("device_info." + name + ".mounting_offset", mounting_offset, 0.0f);
              float joint_offset;
              nh_->get_parameter_or("device_info." + name + ".joint_offset", joint_offset, 0.0f);
              servos_on_port.push_back(std::make_tuple(id, name, mounting_offset, joint_offset));
            } else {
              if (!only_pressure_ && !only_imu_) {
                RCLCPP_WARN(nh_->get_logger(), "Could not identify device for ID %d", id);
              }
            }
            pinged.push_back(name);
          }
          delete model_number_returned_16;
        }
      }
      // create a servo bus interface if there were servos found on this bus
      if (servos_on_port.size() > 0) {
        ServoBusInterface *interface = new ServoBusInterface(nh_, driver, servos_on_port);
        interfaces_on_port.push_back(interface);
        servo_interface_.addBusInterface(interface);
      }
      // add vector of interfaces on this port to overall collection of interfaces
      interfaces_.push_back(interfaces_on_port);
    }
  }

  if (pinged.size()!=dxl_devices.size()) {
    // when we only have 1 or two devices it's only the core
    if (pinged.empty() || pinged.size()==1 || pinged.size()==2) {
      RCLCPP_ERROR_THROTTLE(nh_->get_logger(), *nh_->get_clock(), 5000, "Could not start ros control. Power is off!");
      speakError(speak_pub_, "Could not start ros control. Power is off!");
    } else {
      if (first_ping_error_) {
        first_ping_error_ = false;
      } else {
        RCLCPP_ERROR(nh_->get_logger(), "Could not ping all devices!");
        speakError(speak_pub_, "error starting ros control");
        // check which devices were not pinged successful
        for (std::pair<std::string, int> &device: dxl_devices) {
          if (std::find(pinged.begin(), pinged.end(), device.first)!=pinged.end()) {
          } else {
            RCLCPP_ERROR(nh_->get_logger(), "%s with id %d missing", device.first.c_str(), device.second);
          }
        }
      }
    }
    return false;
  } else {
    speakError(speak_pub_, "ross control startup successful");
    return true;
  }
}

void threaded_init(std::vector<HardwareInterface *> &port_interfaces, rclcpp::Node::SharedPtr &nh, int &success) {
  success = true;
  for (HardwareInterface *interface: port_interfaces) {
    success &= interface->init();
  }
}

bool WolfgangHardwareInterface::init() {
  // iterate through all ports
  std::vector<std::thread> threads;
  std::vector<int *> successes;
  int i = 0;
  for (std::vector<HardwareInterface *> &port_interfaces: interfaces_) {
    // iterate through all interfaces on this port
    // we use an int instead of bool, since std::ref can't handle bool
    int suc = 0;
    successes.push_back(&suc);
    threads.push_back(std::thread(threaded_init, std::ref(port_interfaces), std::ref(nh_), std::ref(suc)));
    i++;
  }
  // wait for all inits to finish
  for (std::thread &thread: threads) {
    thread.join();
  }
  // see if all inits were successful
  bool success = true;
  for (bool s: successes) {
    success &= s;
  }
  // init servo interface last after all servo busses are there
  success &= servo_interface_.init();
  return success;
}

void threaded_read(std::vector<HardwareInterface *> &port_interfaces,
                   const rclcpp::Time &t,
                   const rclcpp::Duration &dt) {
  for (HardwareInterface *interface: port_interfaces) {
    interface->read(t, dt);
  }
}

void WolfgangHardwareInterface::read(const rclcpp::Time &t, const rclcpp::Duration &dt) {
  std::vector<std::thread> threads;
  // start all reads
  for (std::vector<HardwareInterface *> &port_interfaces: interfaces_) {
    threads.push_back(std::thread(threaded_read, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
  }
  // wait for all reads to finish
  for (std::thread &thread: threads) {
    thread.join();
  }
  // aggregate all servo values for controller
  servo_interface_.read(t, dt);
}

void threaded_write(std::vector<HardwareInterface *> &port_interfaces,
                    const rclcpp::Time &t,
                    const rclcpp::Duration &dt) {
  for (HardwareInterface *interface: port_interfaces) {
    interface->write(t, dt);
  }
}

void WolfgangHardwareInterface::write(const rclcpp::Time &t, const rclcpp::Duration &dt) {
  // write all controller values to interfaces
  servo_interface_.write(t, dt);
  std::vector<std::thread> threads;
  // start all writes
  for (std::vector<HardwareInterface *> &port_interfaces: interfaces_) {
    threads.push_back(std::thread(threaded_write, std::ref(port_interfaces), std::ref(t), std::ref(dt)));
  }

  // wait for all writes to finish
  for (std::thread &thread: threads) {
    thread.join();
  }
}
}<|endoftext|>


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

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/string16.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "content/shell/shell.h"
#include "content/test/layout_browsertest.h"
#include "content/test/content_browser_test_utils.h"
#include "googleurl/src/gurl.h"

// Tests playback and seeking of an audio or video file over file or http based
// on a test parameter.  Test starts with playback, then, after X seconds or the
// ended event fires, seeks near end of file; see player.html for details.  The
// test completes when either the last 'ended' or an 'error' event fires.
class MediaTest
    : public testing::WithParamInterface<bool>,
      public content::ContentBrowserTest {
 public:
  // Play specified audio over http:// or file:// depending on |http| setting.
  void PlayAudio(const char* media_file, bool http) {
    ASSERT_NO_FATAL_FAILURE(PlayMedia("audio", media_file, http));
  }

  // Play specified video over http:// or file:// depending on |http| setting.
  void PlayVideo(const char* media_file, bool http) {
    ASSERT_NO_FATAL_FAILURE(PlayMedia("video", media_file, http));
  }

 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // TODO(dalecurtis): Not all Buildbots have viable audio devices, so disable
    // audio to prevent tests from hanging; e.g., a device which is hardware
    // muted.  See http://crbug.com/120749
    command_line->AppendSwitch(switches::kDisableAudio);
  }

 private:
  GURL GetTestURL(const char* tag, const char* media_file, bool http) {
    if (http) {
      return test_server()->GetURL(
          base::StringPrintf("files/media/player.html?%s=%s", tag, media_file));
    }

    FilePath test_file_path = content::GetTestFilePath("media", "player.html");
    std::string query = base::StringPrintf("%s=%s", tag, media_file);
    return content::GetFileUrlWithQuery(test_file_path, query);
  }

  void PlayMedia(const char* tag, const char* media_file, bool http) {
    if (http)
      ASSERT_TRUE(test_server()->Start());

    GURL player_gurl = GetTestURL(tag, media_file, http);

    // Allow the media file to be loaded.
    const string16 kEnded = ASCIIToUTF16("ENDED");
    const string16 kError = ASCIIToUTF16("ERROR");
    const string16 kFailed = ASCIIToUTF16("FAILED");
    content::TitleWatcher title_watcher(shell()->web_contents(), kEnded);
    title_watcher.AlsoWaitForTitle(kFailed);
    title_watcher.AlsoWaitForTitle(kError);

    content::NavigateToURL(shell(), player_gurl);

    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(kEnded, final_title);
  }
};

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearTheora) {
  PlayVideo("bear.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentTheora) {
  PlayVideo("bear_silent.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWebm) {
  PlayVideo("bear.webm", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentWebm) {
  PlayVideo("bear_silent.webm", GetParam());
}

#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMp4) {
  PlayVideo("bear.mp4", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentMp4) {
  PlayVideo("bear_silent.mp4", GetParam());
}

// While we support the big endian (be) PCM codecs on Chromium, Quicktime seems
// to be the only creator of this format and only for .mov files.
// TODO(dalecurtis/ihf): Find or create some .wav test cases for "be" format.
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS16be) {
  PlayVideo("bear_pcm_s16be.mov", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS24be) {
  PlayVideo("bear_pcm_s24be.mov", GetParam());
}
#endif

#if defined(OS_CHROMEOS)
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Mpeg4) {
  PlayVideo("bear_mpeg4_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Divx) {
  PlayVideo("bear_divx_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAacH264) {
  PlayVideo("bear_h264_aac.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAmrnbMpeg4) {
  PlayVideo("bear_mpeg4_amrnb.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavGsmms) {
  PlayAudio("bear_gsm_ms.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavMulaw) {
  PlayAudio("bear_mulaw.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearFlac) {
  PlayAudio("bear.flac", GetParam());
}
#endif
#endif

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm) {
  PlayAudio("bear_pcm.wav", GetParam());
}

#if defined(OS_MACOSX)
// TODO(dalecurtis): Flaky on Mac 10.6.  http://crbug.com/142896
IN_PROC_BROWSER_TEST_P(MediaTest, FLAKY_VideoTulipWebm) {
  PlayVideo("tulip2.webm", GetParam());
}
#else
IN_PROC_BROWSER_TEST_P(MediaTest, VideoTulipWebm) {
  PlayVideo("tulip2.webm", GetParam());
}
#endif

INSTANTIATE_TEST_CASE_P(File, MediaTest, ::testing::Values(false));
INSTANTIATE_TEST_CASE_P(Http, MediaTest, ::testing::Values(true));

class MediaLayoutTest : public InProcessBrowserLayoutTest {
 protected:
  MediaLayoutTest() : InProcessBrowserLayoutTest(
      FilePath(), FilePath().AppendASCII("media")) {
  }
  virtual ~MediaLayoutTest() {}

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // TODO(dalecurtis): Not all Buildbots have viable audio devices, so disable
    // audio to prevent tests from hanging; e.g., a device which is hardware
    // muted.  See http://crbug.com/120749
    command_line->AppendSwitch(switches::kDisableAudio);
  }

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture();
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("content"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("media-file.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("media-fullscreen.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("video-paint-test.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("video-played.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("video-test.js"));
  }
};

// Each browser test can only correspond to a single layout test, otherwise the
// 45 second timeout per test is not long enough for N tests on debug/asan/etc
// builds.

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoAutoplayTest) {
  RunLayoutTest("video-autoplay.html");
}

// Broke after a large WebKit roll - http://crbug.com/148525
#if defined(OS_MACOSX)
#define MAYBE_VideoLoopTest DISABLED_VideoLoopTest
#else
#define MAYBE_VideoLoopTest VideoLoopTest
#endif
IN_PROC_BROWSER_TEST_F(MediaLayoutTest, MAYBE_VideoLoopTest) {
  RunLayoutTest("video-loop.html");
}

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoNoAutoplayTest) {
  RunLayoutTest("video-no-autoplay.html");
}
<commit_msg>Re-enable MediaLayoutTest.VideoLoopTest<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/string16.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test_utils.h"
#include "content/shell/shell.h"
#include "content/test/layout_browsertest.h"
#include "content/test/content_browser_test_utils.h"
#include "googleurl/src/gurl.h"

// Tests playback and seeking of an audio or video file over file or http based
// on a test parameter.  Test starts with playback, then, after X seconds or the
// ended event fires, seeks near end of file; see player.html for details.  The
// test completes when either the last 'ended' or an 'error' event fires.
class MediaTest
    : public testing::WithParamInterface<bool>,
      public content::ContentBrowserTest {
 public:
  // Play specified audio over http:// or file:// depending on |http| setting.
  void PlayAudio(const char* media_file, bool http) {
    ASSERT_NO_FATAL_FAILURE(PlayMedia("audio", media_file, http));
  }

  // Play specified video over http:// or file:// depending on |http| setting.
  void PlayVideo(const char* media_file, bool http) {
    ASSERT_NO_FATAL_FAILURE(PlayMedia("video", media_file, http));
  }

 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // TODO(dalecurtis): Not all Buildbots have viable audio devices, so disable
    // audio to prevent tests from hanging; e.g., a device which is hardware
    // muted.  See http://crbug.com/120749
    command_line->AppendSwitch(switches::kDisableAudio);
  }

 private:
  GURL GetTestURL(const char* tag, const char* media_file, bool http) {
    if (http) {
      return test_server()->GetURL(
          base::StringPrintf("files/media/player.html?%s=%s", tag, media_file));
    }

    FilePath test_file_path = content::GetTestFilePath("media", "player.html");
    std::string query = base::StringPrintf("%s=%s", tag, media_file);
    return content::GetFileUrlWithQuery(test_file_path, query);
  }

  void PlayMedia(const char* tag, const char* media_file, bool http) {
    if (http)
      ASSERT_TRUE(test_server()->Start());

    GURL player_gurl = GetTestURL(tag, media_file, http);

    // Allow the media file to be loaded.
    const string16 kEnded = ASCIIToUTF16("ENDED");
    const string16 kError = ASCIIToUTF16("ERROR");
    const string16 kFailed = ASCIIToUTF16("FAILED");
    content::TitleWatcher title_watcher(shell()->web_contents(), kEnded);
    title_watcher.AlsoWaitForTitle(kFailed);
    title_watcher.AlsoWaitForTitle(kError);

    content::NavigateToURL(shell(), player_gurl);

    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(kEnded, final_title);
  }
};

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearTheora) {
  PlayVideo("bear.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentTheora) {
  PlayVideo("bear_silent.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWebm) {
  PlayVideo("bear.webm", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentWebm) {
  PlayVideo("bear_silent.webm", GetParam());
}

#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMp4) {
  PlayVideo("bear.mp4", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentMp4) {
  PlayVideo("bear_silent.mp4", GetParam());
}

// While we support the big endian (be) PCM codecs on Chromium, Quicktime seems
// to be the only creator of this format and only for .mov files.
// TODO(dalecurtis/ihf): Find or create some .wav test cases for "be" format.
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS16be) {
  PlayVideo("bear_pcm_s16be.mov", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS24be) {
  PlayVideo("bear_pcm_s24be.mov", GetParam());
}
#endif

#if defined(OS_CHROMEOS)
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Mpeg4) {
  PlayVideo("bear_mpeg4_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Divx) {
  PlayVideo("bear_divx_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAacH264) {
  PlayVideo("bear_h264_aac.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAmrnbMpeg4) {
  PlayVideo("bear_mpeg4_amrnb.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavGsmms) {
  PlayAudio("bear_gsm_ms.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavMulaw) {
  PlayAudio("bear_mulaw.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearFlac) {
  PlayAudio("bear.flac", GetParam());
}
#endif
#endif

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm) {
  PlayAudio("bear_pcm.wav", GetParam());
}

#if defined(OS_MACOSX)
// TODO(dalecurtis): Flaky on Mac 10.6.  http://crbug.com/142896
IN_PROC_BROWSER_TEST_P(MediaTest, FLAKY_VideoTulipWebm) {
  PlayVideo("tulip2.webm", GetParam());
}
#else
IN_PROC_BROWSER_TEST_P(MediaTest, VideoTulipWebm) {
  PlayVideo("tulip2.webm", GetParam());
}
#endif

INSTANTIATE_TEST_CASE_P(File, MediaTest, ::testing::Values(false));
INSTANTIATE_TEST_CASE_P(Http, MediaTest, ::testing::Values(true));

class MediaLayoutTest : public InProcessBrowserLayoutTest {
 protected:
  MediaLayoutTest() : InProcessBrowserLayoutTest(
      FilePath(), FilePath().AppendASCII("media")) {
  }
  virtual ~MediaLayoutTest() {}

  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // TODO(dalecurtis): Not all Buildbots have viable audio devices, so disable
    // audio to prevent tests from hanging; e.g., a device which is hardware
    // muted.  See http://crbug.com/120749
    command_line->AppendSwitch(switches::kDisableAudio);
  }

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture();
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("content"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("media-file.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("media-fullscreen.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("video-paint-test.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("video-played.js"));
    AddResourceForLayoutTest(FilePath().AppendASCII("media"),
                             FilePath().AppendASCII("video-test.js"));
  }
};

// Each browser test can only correspond to a single layout test, otherwise the
// 45 second timeout per test is not long enough for N tests on debug/asan/etc
// builds.

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoAutoplayTest) {
  RunLayoutTest("video-autoplay.html");
}

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoLoopTest) {
  RunLayoutTest("video-loop.html");
}

IN_PROC_BROWSER_TEST_F(MediaLayoutTest, VideoNoAutoplayTest) {
  RunLayoutTest("video-no-autoplay.html");
}
<|endoftext|>


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

#include "browser/platform_notification_service_impl.h"

#include "browser/notification_presenter.h"

#include "content/public/browser/desktop_notification_delegate.h"

namespace brightray {

// static
PlatformNotificationServiceImpl*
PlatformNotificationServiceImpl::GetInstance() {
  return Singleton<PlatformNotificationServiceImpl>::get();
}

PlatformNotificationServiceImpl::PlatformNotificationServiceImpl() {}
PlatformNotificationServiceImpl::~PlatformNotificationServiceImpl() {}

NotificationPresenter* PlatformNotificationServiceImpl::notification_presenter() {
  if (!notification_presenter_)
    notification_presenter_.reset(NotificationPresenter::Create());
  return notification_presenter_.get();
}

blink::WebNotificationPermission PlatformNotificationServiceImpl::CheckPermissionOnUIThread(
    content::BrowserContext* browser_context,
    const GURL& origin,
    int render_process_id) {
  return blink::WebNotificationPermissionAllowed;
}

blink::WebNotificationPermission PlatformNotificationServiceImpl::CheckPermissionOnIOThread(
    content::ResourceContext* resource_context,
    const GURL& origin,
    int render_process_id) {
  return blink::WebNotificationPermissionAllowed;
}

void PlatformNotificationServiceImpl::DisplayNotification(
    content::BrowserContext* browser_context,
    const GURL& origin,
    const SkBitmap& icon,
    const content::PlatformNotificationData& notification_data,
    scoped_ptr<content::DesktopNotificationDelegate> delegate,
    base::Closure* cancel_callback) {
  auto presenter = notification_presenter();
  if (presenter)
    presenter->ShowNotification(notification_data, icon, delegate.Pass(), cancel_callback);
}

void PlatformNotificationServiceImpl::DisplayPersistentNotification(
    content::BrowserContext* browser_context,
    int64_t service_worker_registration_id,
    const GURL& origin,
    const SkBitmap& icon,
    const content::PlatformNotificationData& notification_data) {
}

void PlatformNotificationServiceImpl::ClosePersistentNotification(
    content::BrowserContext* browser_context,
    int64_t persistent_notification_id) {
}

bool PlatformNotificationServiceImpl::GetDisplayedPersistentNotifications(
    content::BrowserContext* browser_context,
    std::set<std::string>* displayed_notifications) {
  return false;
}

}  // namespace brightray
<commit_msg>Ensure Notifications are Windows 8 and up only<commit_after>// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/platform_notification_service_impl.h"

#include "browser/notification_presenter.h"

#include "content/public/browser/desktop_notification_delegate.h"

#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

namespace brightray {

// static
PlatformNotificationServiceImpl*
PlatformNotificationServiceImpl::GetInstance() {
  return Singleton<PlatformNotificationServiceImpl>::get();
}

PlatformNotificationServiceImpl::PlatformNotificationServiceImpl() {}
PlatformNotificationServiceImpl::~PlatformNotificationServiceImpl() {}

NotificationPresenter* PlatformNotificationServiceImpl::notification_presenter() {
  if (!notification_presenter_) {
    #if defined(OS_WIN)
    // Bail out if on Windows 7 or even lower, no operating will follow
    if (base::win::GetVersion() < base::win::VERSION_WIN8) {
      return notification_presenter_.get();
    }
    #endif
    // Create a new presenter if on OS X, Linux, or Windows 8+
    notification_presenter_.reset(NotificationPresenter::Create());
  }
  return notification_presenter_.get();
}

blink::WebNotificationPermission PlatformNotificationServiceImpl::CheckPermissionOnUIThread(
    content::BrowserContext* browser_context,
    const GURL& origin,
    int render_process_id) {
  return blink::WebNotificationPermissionAllowed;
}

blink::WebNotificationPermission PlatformNotificationServiceImpl::CheckPermissionOnIOThread(
    content::ResourceContext* resource_context,
    const GURL& origin,
    int render_process_id) {
  return blink::WebNotificationPermissionAllowed;
}

void PlatformNotificationServiceImpl::DisplayNotification(
    content::BrowserContext* browser_context,
    const GURL& origin,
    const SkBitmap& icon,
    const content::PlatformNotificationData& notification_data,
    scoped_ptr<content::DesktopNotificationDelegate> delegate,
    base::Closure* cancel_callback) {
  auto presenter = notification_presenter();
  if (presenter)
    presenter->ShowNotification(notification_data, icon, delegate.Pass(), cancel_callback);
}

void PlatformNotificationServiceImpl::DisplayPersistentNotification(
    content::BrowserContext* browser_context,
    int64_t service_worker_registration_id,
    const GURL& origin,
    const SkBitmap& icon,
    const content::PlatformNotificationData& notification_data) {
}

void PlatformNotificationServiceImpl::ClosePersistentNotification(
    content::BrowserContext* browser_context,
    int64_t persistent_notification_id) {
}

bool PlatformNotificationServiceImpl::GetDisplayedPersistentNotifications(
    content::BrowserContext* browser_context,
    std::set<std::string>* displayed_notifications) {
  return false;
}

}  // namespace brightray
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_LA_SOLVER_HH
#define DUNE_STUFF_LA_SOLVER_HH

#include <string>
#include <vector>

#include <dune/common/deprecated.hh>

#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/parallel/helper.hh>

namespace Dune {
namespace Stuff {
namespace Exceptions {

class linear_solver_failed_bc_data_did_not_fulfill_requirements :      public linear_solver_failed {};
class
  DUNE_DEPRECATED_MSG("Use linear_solver_failed_bc_data_did_not_fulfill_requirements instead (10.11.2014)!")
      linear_solver_failed_bc_matrix_did_not_fulfill_requirements :    public linear_solver_failed_bc_data_did_not_fulfill_requirements {};
class linear_solver_failed_bc_it_did_not_converge :                    public linear_solver_failed {};
class linear_solver_failed_bc_it_was_not_set_up_correctly :            public linear_solver_failed {};
class linear_solver_failed_bc_the_solution_does_not_solve_the_system : public linear_solver_failed {};

} // namespace Exceptions
namespace LA {
namespace internal {

static const constexpr size_t max_size_to_print = 5;

} // namespace internal

class SolverUtils
{
public:
  static void check_given(const std::string& type, const std::vector< std::string >& opts)
  {
    if (std::find(opts.begin(), opts.end(), type) == opts.end()) {
      std::stringstream ss;
      for (auto opt : opts)
        ss << opt << " ";
      DUNE_THROW(Exceptions::configuration_error,
                 "Given type '" << type << "' not supported (see below for a list of supported ones). "
                 << "Call options() first!\n" << ss.str());
    }
  }
};

template< class MatrixImp, class CommunicatorType = SequentialCommunication >
class Solver
{
  static_assert(AlwaysFalse< MatrixImp >::value, "This is the unspecialized version of LA::Solver< ... >. Please include the correct header for your matrix implementation!");
public:
  typedef MatrixImp MatrixType;

  Solver(const MatrixType& /*matrix*/)
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  static std::vector< std::string > types()
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  static Common::Configuration options(const std::string /*type*/ = "")
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  /**
   *  Throws any of the above exceptions, if there was a problem. If none was thrown we beleive that a suitable solution
   *  was found (given the current options).
   */
  template< class RhsType, class SolutionType >
  void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/) const
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  template< class RhsType, class SolutionType >
  void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const std::string& /*type*/) const
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  template< class RhsType, class SolutionType >
  void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const Common::Configuration& /*options*/) const
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }
}; // class Solver

} // namespace LA
} // namespace Stuff
} // namespace Dune

#include "solver/common.hh"
#include "solver/eigen.hh"
#include "solver/istl.hh"

#endif // DUNE_STUFF_LA_SOLVER_HH
<commit_msg>[la.solver] removes deprecated exception<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_LA_SOLVER_HH
#define DUNE_STUFF_LA_SOLVER_HH

#include <string>
#include <vector>

#include <dune/common/deprecated.hh>

#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/stuff/common/parallel/helper.hh>

namespace Dune {
namespace Stuff {
namespace Exceptions {

class linear_solver_failed_bc_data_did_not_fulfill_requirements :      public linear_solver_failed {};
class linear_solver_failed_bc_it_did_not_converge :                    public linear_solver_failed {};
class linear_solver_failed_bc_it_was_not_set_up_correctly :            public linear_solver_failed {};
class linear_solver_failed_bc_the_solution_does_not_solve_the_system : public linear_solver_failed {};

} // namespace Exceptions
namespace LA {
namespace internal {

static const constexpr size_t max_size_to_print = 5;

} // namespace internal

class SolverUtils
{
public:
  static void check_given(const std::string& type, const std::vector< std::string >& opts)
  {
    if (std::find(opts.begin(), opts.end(), type) == opts.end()) {
      std::stringstream ss;
      for (auto opt : opts)
        ss << opt << " ";
      DUNE_THROW(Exceptions::configuration_error,
                 "Given type '" << type << "' not supported (see below for a list of supported ones). "
                 << "Call options() first!\n" << ss.str());
    }
  }
};

template< class MatrixImp, class CommunicatorType = SequentialCommunication >
class Solver
{
  static_assert(AlwaysFalse< MatrixImp >::value, "This is the unspecialized version of LA::Solver< ... >. Please include the correct header for your matrix implementation!");
public:
  typedef MatrixImp MatrixType;

  Solver(const MatrixType& /*matrix*/)
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  static std::vector< std::string > types()
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  static Common::Configuration options(const std::string /*type*/ = "")
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  /**
   *  Throws any of the above exceptions, if there was a problem. If none was thrown we beleive that a suitable solution
   *  was found (given the current options).
   */
  template< class RhsType, class SolutionType >
  void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/) const
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  template< class RhsType, class SolutionType >
  void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const std::string& /*type*/) const
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }

  template< class RhsType, class SolutionType >
  void apply(const RhsType& /*rhs*/, SolutionType& /*solution*/, const Common::Configuration& /*options*/) const
  {
    DUNE_THROW(NotImplemented,
               "This is the unspecialized version of LA::Solver< ... >. "
               "Please include the correct header for your matrix implementation '"
               << Common::Typename< MatrixType >::value() << "'!");
  }
}; // class Solver

} // namespace LA
} // namespace Stuff
} // namespace Dune

#include "solver/common.hh"
#include "solver/eigen.hh"
#include "solver/istl.hh"

#endif // DUNE_STUFF_LA_SOLVER_HH
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                         *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <TMath.h>

#include "AliITSgeom.h"
#include "AliITSresponseSDD.h"
#include "AliITS.h"
#include "AliRun.h"

class AliITS;

//___________________________________________
ClassImp(AliITSresponseSDD)

AliITSresponseSDD::AliITSresponseSDD()
{
  // constructor
   SetMaxAdc();
   SetDiffCoeff();
   SetQref();
   SetDriftSpeed();
   // SetClock();
   SetNoiseParam();
   SetMagicValue();
   SetMinVal();
   SetParamOptions();
   SetZeroSupp();
   SetDataType();
   SetFilenames();
   SetOutputOption();

}

//__________________________________________________________________________
AliITSresponseSDD::AliITSresponseSDD(const AliITSresponseSDD &source){
  //     Copy Constructor
  Int_t i;
  if(&source == this) return;
  for(i=0,i<8,i++){this->fCPar[i] = source.fCPar[i];}
  this->fNoise = source.fNoise;
  this->fBaseline = source.fBaseline;
  this->fTopValue = source.fTopValue;
  this->fTemperature = source.fTemperature;
  this->fDriftSpeed = source.fDriftSpeed;
  this->fMaxAdc = source.fMaxAdc;
  this->fDiffCoeff = source.fDiffCoeff;
  this->fQref = source.fQref;
  this->fZeroSuppFlag = source.fZeroSuppFlag;
  this->fMinVal = source.fMinVal;
  this->fWrite = source.fWrite;
  this->fOption = source.fOption;
  this->fParam1 = source.fParam1;
  return;
}

//_________________________________________________________________________
AliITSresponseSDD&
  AliITSresponseSDD::operator=(const AliITSresponseSDD &source) {
  //    Assignment operator
  Int_t i;
  if(&source == this) return *this;
  for(i=0,i<8,i++){this->fCPar[i] = source.fCPar[i];}
  this->fNoise = source.fNoise;
  this->fBaseline = source.fBaseline;
  this->fTopValue = source.fTopValue;
  this->fTemperature = source.fTemperature;
  this->fDriftSpeed = source.fDriftSpeed;
  this->fMaxAdc = source.fMaxAdc;
  this->fDiffCoeff = source.fDiffCoeff;
  this->fQref = source.fQref;
  this->fZeroSuppFlag = source.fZeroSuppFlag;
  this->fMinVal = source.fMinVal;
  this->fWrite = source.fWrite;
  this->fOption = source.fOption;
  this->fParam1 = source.fParam1;
  return *this;
}

void AliITSresponseSDD::SetCompressParam(Int_t  cp[8])
{
  // set compression param
    Int_t i;
    for(i=0; i<8; i++) {
	fCPar[i]=cp[i];
	//printf("\n CompressPar %d %d \n",i,fCPar[i]);

    }
}
void AliITSresponseSDD::GiveCompressParam(Int_t  cp[8])
{
  // give compression param
    Int_t i;
    for(i=0; i<8; i++) {
	cp[i]=fCPar[i];
    }
}
//______________________________________________________________________________
void AliITSresponseSDD::Streamer(TBuffer &R__b)
{
   // Stream an object of class AliITSresponseSDD.

   if (R__b.IsReading()) {
      Version_t R__v = R__b.ReadVersion(); if (R__v) { }
      AliITSresponse::Streamer(R__b);
      R__b.ReadStaticArray(fCPar);
      R__b >> fNoise;
      R__b >> fBaseline;
      R__b >> fTopValue;
      R__b >> fTemperature;
      R__b >> fDriftSpeed;
      R__b >> fMaxAdc;
      R__b >> fDiffCoeff;
      R__b >> fQref;
      R__b >> fZeroSuppFlag;
      R__b >> fMinVal;
      R__b >> fWrite;
      //R__b.ReadArray(fOption); // Not to be printed out?
      //R__b.ReadArray(fParam1); // Not to be printed out?
      //R__b.ReadArray(fParam2); // Not to be printed out?
      fDataType.Streamer(R__b);
      fFileName1.Streamer(R__b);
      fFileName2.Streamer(R__b);
      fFileName3.Streamer(R__b);
   } else {
      R__b.WriteVersion(AliITSresponseSDD::IsA());
      AliITSresponse::Streamer(R__b);
      R__b.WriteArray(fCPar, 8);
      R__b << fNoise;
      R__b << fBaseline;
      R__b << fTopValue;
      R__b << fTemperature;
      R__b << fDriftSpeed;
      R__b << fMaxAdc;
      R__b << fDiffCoeff;
      R__b << fQref;
      R__b << fZeroSuppFlag;
      R__b << fMinVal;
      R__b << fWrite;
      //R__b.WriteArray(fOption, __COUNTER__); // Not to be printed out?
      //R__b.WriteArray(fParam1, __COUNTER__); // Not to be printed out?
      //R__b.WriteArray(fParam2, __COUNTER__); // Not to be printed out?
      fDataType.Streamer(R__b);
      fFileName1.Streamer(R__b);
      fFileName2.Streamer(R__b);
      fFileName3.Streamer(R__b);
   }
}
<commit_msg>Another problem with the HP compiler fixed.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                         *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <TMath.h>

#include "AliITSgeom.h"
#include "AliITSresponseSDD.h"
#include "AliITS.h"
#include "AliRun.h"

class AliITS;

//___________________________________________
ClassImp(AliITSresponseSDD)

AliITSresponseSDD::AliITSresponseSDD()
{
  // constructor
   SetMaxAdc();
   SetDiffCoeff();
   SetQref();
   SetDriftSpeed();
   // SetClock();
   SetNoiseParam();
   SetMagicValue();
   SetMinVal();
   SetParamOptions();
   SetZeroSupp();
   SetDataType();
   SetFilenames();
   SetOutputOption();

}

//__________________________________________________________________________
AliITSresponseSDD::AliITSresponseSDD(const AliITSresponseSDD &source){
  //     Copy Constructor
  Int_t i;
  if(&source == this) return;
  for(i=0;i<8;i++){this->fCPar[i] = source.fCPar[i];}
  this->fNoise = source.fNoise;
  this->fBaseline = source.fBaseline;
  this->fTopValue = source.fTopValue;
  this->fTemperature = source.fTemperature;
  this->fDriftSpeed = source.fDriftSpeed;
  this->fMaxAdc = source.fMaxAdc;
  this->fDiffCoeff = source.fDiffCoeff;
  this->fQref = source.fQref;
  this->fZeroSuppFlag = source.fZeroSuppFlag;
  this->fMinVal = source.fMinVal;
  this->fWrite = source.fWrite;
  this->fOption = source.fOption;
  this->fParam1 = source.fParam1;
  return;
}

//_________________________________________________________________________
AliITSresponseSDD&
  AliITSresponseSDD::operator=(const AliITSresponseSDD &source) {
  //    Assignment operator
  Int_t i;
  if(&source == this) return *this;
  for(i=0;i<8;i++){this->fCPar[i] = source.fCPar[i];}
  this->fNoise = source.fNoise;
  this->fBaseline = source.fBaseline;
  this->fTopValue = source.fTopValue;
  this->fTemperature = source.fTemperature;
  this->fDriftSpeed = source.fDriftSpeed;
  this->fMaxAdc = source.fMaxAdc;
  this->fDiffCoeff = source.fDiffCoeff;
  this->fQref = source.fQref;
  this->fZeroSuppFlag = source.fZeroSuppFlag;
  this->fMinVal = source.fMinVal;
  this->fWrite = source.fWrite;
  this->fOption = source.fOption;
  this->fParam1 = source.fParam1;
  return *this;
}

void AliITSresponseSDD::SetCompressParam(Int_t  cp[8])
{
  // set compression param
    Int_t i;
    for(i=0; i<8; i++) {
	fCPar[i]=cp[i];
	//printf("\n CompressPar %d %d \n",i,fCPar[i]);

    }
}
void AliITSresponseSDD::GiveCompressParam(Int_t  cp[8])
{
  // give compression param
    Int_t i;
    for(i=0; i<8; i++) {
	cp[i]=fCPar[i];
    }
}
//______________________________________________________________________________
void AliITSresponseSDD::Streamer(TBuffer &R__b)
{
   // Stream an object of class AliITSresponseSDD.

   if (R__b.IsReading()) {
      Version_t R__v = R__b.ReadVersion(); if (R__v) { }
      AliITSresponse::Streamer(R__b);
      R__b.ReadStaticArray(fCPar);
      R__b >> fNoise;
      R__b >> fBaseline;
      R__b >> fTopValue;
      R__b >> fTemperature;
      R__b >> fDriftSpeed;
      R__b >> fMaxAdc;
      R__b >> fDiffCoeff;
      R__b >> fQref;
      R__b >> fZeroSuppFlag;
      R__b >> fMinVal;
      R__b >> fWrite;
      //R__b.ReadArray(fOption); // Not to be printed out?
      //R__b.ReadArray(fParam1); // Not to be printed out?
      //R__b.ReadArray(fParam2); // Not to be printed out?
      fDataType.Streamer(R__b);
      fFileName1.Streamer(R__b);
      fFileName2.Streamer(R__b);
      fFileName3.Streamer(R__b);
   } else {
      R__b.WriteVersion(AliITSresponseSDD::IsA());
      AliITSresponse::Streamer(R__b);
      R__b.WriteArray(fCPar, 8);
      R__b << fNoise;
      R__b << fBaseline;
      R__b << fTopValue;
      R__b << fTemperature;
      R__b << fDriftSpeed;
      R__b << fMaxAdc;
      R__b << fDiffCoeff;
      R__b << fQref;
      R__b << fZeroSuppFlag;
      R__b << fMinVal;
      R__b << fWrite;
      //R__b.WriteArray(fOption, __COUNTER__); // Not to be printed out?
      //R__b.WriteArray(fParam1, __COUNTER__); // Not to be printed out?
      //R__b.WriteArray(fParam2, __COUNTER__); // Not to be printed out?
      fDataType.Streamer(R__b);
      fFileName1.Streamer(R__b);
      fFileName2.Streamer(R__b);
      fFileName3.Streamer(R__b);
   }
}
<|endoftext|>


<commit_before>// GeoSetBuilder.cpp

#if defined(WIN32) && !defined(__CYGWIN__)
#pragma warning( disable : 4786 )
#endif

#include "flt.h"
#include "FltFile.h"
#include "Pool.h"
#include "opcodes.h"
#include "GeoSetBuilder.h"

#include <osg/Object>
#include <osg/LOD>
#include <osg/Transparency>
#include <osg/Geode>
#include <osg/GeoSet>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture>
#include <osg/TexEnv>
#include <osg/CullFace>
#include <osg/PolygonOffset>
#include <osg/Point>
#include <osg/Notify>

#include <map>
#include <algorithm>

using namespace flt;

////////////////////////////////////////////////////////////////////
//
//                       DynGeoSet
//
////////////////////////////////////////////////////////////////////

#define APPEND_DynGeoSet_List(list)                     \
    if (source->list.size() > 0)                        \
        list.insert(list.end(),                         \
            source->list.begin(), source->list.end());

void DynGeoSet::append(DynGeoSet* source)
{
    APPEND_DynGeoSet_List(_primLenList)
    APPEND_DynGeoSet_List(_coordList)
    APPEND_DynGeoSet_List(_normalList)
    APPEND_DynGeoSet_List(_colorList)
    APPEND_DynGeoSet_List(_tcoordList)
}

#define VERIFY_DynGeoSet_Binding(binding,list)          \
        switch (binding)                                \
        {                                               \
        case osg::GeoSet::BIND_PERVERTEX:               \
            if (list.size() < _coordList.size()) {      \
                binding = osg::GeoSet::BIND_OFF;        \
                list.clear(); }                         \
            break;                                      \
        case osg::GeoSet::BIND_PERPRIM:                 \
            if (list.size() < _primLenList.size()) {    \
                binding = osg::GeoSet::BIND_OFF;        \
                list.clear(); }                         \
            break;                                      \
        case osg::GeoSet::BIND_OVERALL:                 \
            if (list.size() < 1) {                      \
                binding = osg::GeoSet::BIND_OFF;        \
                list.clear(); }                         \
            break;                                      \
        }

DynGeoSet::DynGeoSet():osg::GeoSet()
{
	// disable the attribute delete functor since the vectors contained in DynGeoSet
	// will delete the memory for us.
	_adf = NULL;
}

void DynGeoSet::setBinding()
{
    VERIFY_DynGeoSet_Binding(_normal_binding, _normalList)
    VERIFY_DynGeoSet_Binding(_color_binding, _colorList)
    VERIFY_DynGeoSet_Binding(_texture_binding, _tcoordList)

    // Set bindings
    setNormalBinding(_normal_binding);
    setColorBinding(_color_binding);
    setTextureBinding(_texture_binding);

    osg::StateSet* stateset = getStateSet();
    if (stateset)
    {
        if (_normal_binding == osg::GeoSet::BIND_OFF)
            stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
    }
}

bool DynGeoSet::setLists()
{
    if ((_primLenList.size() > 0) && (_coordList.size() > 0))
    {
        setPrimLengths(_primLenList.begin());
        setCoords(_coordList.begin());

        if ((_normalList.size() > 0)
        &&  (getNormalBinding() != osg::GeoSet::BIND_OFF))
            setNormals(_normalList.begin());

        if ((_colorList.size() > 0)
        &&  (getColorBinding() != osg::GeoSet::BIND_OFF))
            setColors(_colorList.begin());

        if ((_tcoordList.size() > 0)
        &&  (getTextureBinding() != osg::GeoSet::BIND_OFF))
            setTextureCoords(_tcoordList.begin());

        return true;
    }

    return false;
}

////////////////////////////////////////////////////////////////////
//
//                       GeoSetBuilder
//
////////////////////////////////////////////////////////////////////

// OpenFlight don't save data in GeoSets.  This class tries to find
// existing GeoSets with matching state before creating a new GeoSet.

GeoSetBuilder::GeoSetBuilder(osg::Geode* geode)
{
    _geode = geode;
    initPrimData();
}

void GeoSetBuilder::initPrimData()
{
    _dynGeoSet = new DynGeoSet;
    _dynGeoSet->setStateSet(new osg::StateSet);
}

osg::Geode* GeoSetBuilder::createOsgGeoSets()
{
    for(DynGeoSetList::iterator itr=_dynGeoSetList.begin();
        itr!=_dynGeoSetList.end();
        ++itr)
    {
        DynGeoSet* dgset = itr->get();
        if (dgset)
        {
            int prims = dgset->primLenListSize();
            if (prims > 0)
            {
                dgset->setLists();
                dgset->setNumPrims(prims);
                _geode.get()->addDrawable(dgset);
            }
        }
    }

    return _geode.get();
}

bool GeoSetBuilder::addPrimitive()
{
    DynGeoSet* dgset = getDynGeoSet();  // This is the new geoset we want to add

    if (dgset->getPrimType() == osg::GeoSet::NO_TYPE)
        dgset->setPrimType(findPrimType(dgset->coordListSize()));

    // Still no primitive type?
    if (dgset->getPrimType() == osg::GeoSet::NO_TYPE)
        return false;

    dgset->setBinding();

    DynGeoSet* match = findMatchingGeoSet();
    if (match)
        match->append(dgset);
    else
        _dynGeoSetList.push_back(dgset);

    initPrimData();     // initialize _dynGeoSet
    return true;
}

DynGeoSet* GeoSetBuilder::findMatchingGeoSet()
{
    DynGeoSet* new_dgset = getDynGeoSet();
    for(DynGeoSetList::iterator itr=_dynGeoSetList.begin();
        itr!=_dynGeoSetList.end();
        ++itr)
    {
        DynGeoSet* dgset = itr->get();
        if (*new_dgset == *dgset)
            return dgset;
    }

    return NULL;
}

osg::GeoSet::PrimitiveType GeoSetBuilder::findPrimType(const int nVertices)
{
    switch (nVertices)
    {
        case 1: return osg::GeoSet::POINTS;
        case 2: return osg::GeoSet::LINES;
        case 3: return osg::GeoSet::TRIANGLES;
        case 4: return osg::GeoSet::QUADS;
    }

    if (nVertices >= 5) return osg::GeoSet::POLYGON;
    return osg::GeoSet::NO_TYPE;
}

<commit_msg>Changed the use of std::vector<..>.begin() to &vector<..>.front() in code from passing the vector contents to the GeoSet::setPrimLengths(..) etc. methods.  This has been done to fix the compile under the MS .NET compiler which has changed the definiation of the std::vector<..>::iterator to a class rather than a pointer.<commit_after>// GeoSetBuilder.cpp

#if defined(WIN32) && !defined(__CYGWIN__)
#pragma warning( disable : 4786 )
#endif

#include "flt.h"
#include "FltFile.h"
#include "Pool.h"
#include "opcodes.h"
#include "GeoSetBuilder.h"

#include <osg/Object>
#include <osg/LOD>
#include <osg/Transparency>
#include <osg/Geode>
#include <osg/GeoSet>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture>
#include <osg/TexEnv>
#include <osg/CullFace>
#include <osg/PolygonOffset>
#include <osg/Point>
#include <osg/Notify>

#include <map>
#include <algorithm>

using namespace flt;

////////////////////////////////////////////////////////////////////
//
//                       DynGeoSet
//
////////////////////////////////////////////////////////////////////

#define APPEND_DynGeoSet_List(list)                     \
    if (source->list.size() > 0)                        \
        list.insert(list.end(),                         \
            source->list.begin(), source->list.end());

void DynGeoSet::append(DynGeoSet* source)
{
    APPEND_DynGeoSet_List(_primLenList)
    APPEND_DynGeoSet_List(_coordList)
    APPEND_DynGeoSet_List(_normalList)
    APPEND_DynGeoSet_List(_colorList)
    APPEND_DynGeoSet_List(_tcoordList)
}

#define VERIFY_DynGeoSet_Binding(binding,list)          \
        switch (binding)                                \
        {                                               \
        case osg::GeoSet::BIND_PERVERTEX:               \
            if (list.size() < _coordList.size()) {      \
                binding = osg::GeoSet::BIND_OFF;        \
                list.clear(); }                         \
            break;                                      \
        case osg::GeoSet::BIND_PERPRIM:                 \
            if (list.size() < _primLenList.size()) {    \
                binding = osg::GeoSet::BIND_OFF;        \
                list.clear(); }                         \
            break;                                      \
        case osg::GeoSet::BIND_OVERALL:                 \
            if (list.size() < 1) {                      \
                binding = osg::GeoSet::BIND_OFF;        \
                list.clear(); }                         \
            break;                                      \
        }

DynGeoSet::DynGeoSet():osg::GeoSet()
{
	// disable the attribute delete functor since the vectors contained in DynGeoSet
	// will delete the memory for us.
	_adf = NULL;
}

void DynGeoSet::setBinding()
{
    VERIFY_DynGeoSet_Binding(_normal_binding, _normalList)
    VERIFY_DynGeoSet_Binding(_color_binding, _colorList)
    VERIFY_DynGeoSet_Binding(_texture_binding, _tcoordList)

    // Set bindings
    setNormalBinding(_normal_binding);
    setColorBinding(_color_binding);
    setTextureBinding(_texture_binding);

    osg::StateSet* stateset = getStateSet();
    if (stateset)
    {
        if (_normal_binding == osg::GeoSet::BIND_OFF)
            stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
    }
}

bool DynGeoSet::setLists()
{
    if ((_primLenList.size() > 0) && (_coordList.size() > 0))
    {
        setPrimLengths(&_primLenList.front());
        setCoords(&_coordList.front());

        if ((_normalList.size() > 0)
        &&  (getNormalBinding() != osg::GeoSet::BIND_OFF))
            setNormals(&_normalList.front());

        if ((_colorList.size() > 0)
        &&  (getColorBinding() != osg::GeoSet::BIND_OFF))
            setColors(&_colorList.front());

        if ((_tcoordList.size() > 0)
        &&  (getTextureBinding() != osg::GeoSet::BIND_OFF))
            setTextureCoords(&_tcoordList.front());

        return true;
    }

    return false;
}

////////////////////////////////////////////////////////////////////
//
//                       GeoSetBuilder
//
////////////////////////////////////////////////////////////////////

// OpenFlight don't save data in GeoSets.  This class tries to find
// existing GeoSets with matching state before creating a new GeoSet.

GeoSetBuilder::GeoSetBuilder(osg::Geode* geode)
{
    _geode = geode;
    initPrimData();
}

void GeoSetBuilder::initPrimData()
{
    _dynGeoSet = new DynGeoSet;
    _dynGeoSet->setStateSet(new osg::StateSet);
}

osg::Geode* GeoSetBuilder::createOsgGeoSets()
{
    for(DynGeoSetList::iterator itr=_dynGeoSetList.begin();
        itr!=_dynGeoSetList.end();
        ++itr)
    {
        DynGeoSet* dgset = itr->get();
        if (dgset)
        {
            int prims = dgset->primLenListSize();
            if (prims > 0)
            {
                dgset->setLists();
                dgset->setNumPrims(prims);
                _geode.get()->addDrawable(dgset);
            }
        }
    }

    return _geode.get();
}

bool GeoSetBuilder::addPrimitive()
{
    DynGeoSet* dgset = getDynGeoSet();  // This is the new geoset we want to add

    if (dgset->getPrimType() == osg::GeoSet::NO_TYPE)
        dgset->setPrimType(findPrimType(dgset->coordListSize()));

    // Still no primitive type?
    if (dgset->getPrimType() == osg::GeoSet::NO_TYPE)
        return false;

    dgset->setBinding();

    DynGeoSet* match = findMatchingGeoSet();
    if (match)
        match->append(dgset);
    else
        _dynGeoSetList.push_back(dgset);

    initPrimData();     // initialize _dynGeoSet
    return true;
}

DynGeoSet* GeoSetBuilder::findMatchingGeoSet()
{
    DynGeoSet* new_dgset = getDynGeoSet();
    for(DynGeoSetList::iterator itr=_dynGeoSetList.begin();
        itr!=_dynGeoSetList.end();
        ++itr)
    {
        DynGeoSet* dgset = itr->get();
        if (*new_dgset == *dgset)
            return dgset;
    }

    return NULL;
}

osg::GeoSet::PrimitiveType GeoSetBuilder::findPrimType(const int nVertices)
{
    switch (nVertices)
    {
        case 1: return osg::GeoSet::POINTS;
        case 2: return osg::GeoSet::LINES;
        case 3: return osg::GeoSet::TRIANGLES;
        case 4: return osg::GeoSet::QUADS;
    }

    if (nVertices >= 5) return osg::GeoSet::POLYGON;
    return osg::GeoSet::NO_TYPE;
}

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS presenterview (1.57.46); FILE MERGED 2008/03/26 10:47:26 cl 1.57.46.5: RESYNC: (1.60-1.62); FILE MERGED 2008/02/26 09:04:05 af 1.57.46.4: RESYNC: (1.59-1.60); FILE MERGED 2007/07/24 12:00:33 af 1.57.46.3: RESYNC: (1.58-1.59); FILE MERGED 2007/07/11 09:13:13 af 1.57.46.2: RESYNC: (1.57-1.58); FILE MERGED 2007/07/10 13:28:22 af 1.57.46.1: #i18486# Converted ViewShellManager, ToolBarManager, and EventMultiplexer of ViewShellBase to shared_ptrs.<commit_after><|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include "AliGenPythiaEventHeader.h"
ClassImp(AliGenPythiaEventHeader)

AliGenPythiaEventHeader::AliGenPythiaEventHeader():
    fProcessType(0),
    fTrials(0),
    fNJets(0),
    fNUQJets(0),
    fXJet(-1.),
    fYJet(-1.),
    fInMediumLength(0.),
    fImpactParameter(-1),
    fPtHard(0.)
{
// Default Constructor
    for (Int_t i = 0; i < 4; i++) fZquench[i] = 0.;
    for (Int_t i = 0; i < 4; i++)
      for (Int_t j = 0; j < 10; j++) {
	fJets[i][j] = 0.;
	fUQJets[i][j] = 0.;
      }
}

AliGenPythiaEventHeader::AliGenPythiaEventHeader(const char* name):
    AliGenEventHeader(name),
    fProcessType(0),
    fTrials(0),
    fNJets(0),
    fNUQJets(0),
    fXJet(-1.),
    fYJet(-1.),
    fInMediumLength(0.),
    fImpactParameter(-1),
    fPtHard(0.)
{
// Constructor
    for (Int_t i = 0; i < 4; i++) fZquench[i] = 0.;
    for (Int_t i = 0; i < 4; i++)
      for (Int_t j = 0; j < 10; j++) {
	fJets[i][j] = 0.;
	fUQJets[i][j] = 0.;
      }
}

void AliGenPythiaEventHeader::AddJet(Float_t px, Float_t py, Float_t pz, Float_t e)
{
//
//  Add a jet
//
    if (fNJets < 10) {
	fJets[0][fNJets] = px;
	fJets[1][fNJets] = py;
	fJets[2][fNJets] = pz;
	fJets[3][fNJets] = e;
	fNJets++;
    } else {
	printf("\nWarning: More than 10 jets triggered !!\n");
    }
}

void AliGenPythiaEventHeader::AddUQJet(Float_t px, Float_t py, Float_t pz, Float_t e)
{
//
//  Add a jet
//
    if (fNUQJets < 10) {
	fUQJets[0][fNUQJets] = px;
	fUQJets[1][fNUQJets] = py;
	fUQJets[2][fNUQJets] = pz;
	fUQJets[3][fNUQJets] = e;
	fNUQJets++;
    } else {
	printf("\nWarning: More than 10 jets triggered !!\n");
    }
}

void AliGenPythiaEventHeader::SetZQuench(Double_t z[4])
{
    //
    // Set quenching fraction
    //
    for (Int_t i = 0; i < 4; i++) fZquench[i] = z[i];
}

void AliGenPythiaEventHeader::GetZQuench(Double_t z[4]) const
{
    //
    // Get quenching fraction
    //
    for (Int_t i = 0; i < 4; i++) z[i] = fZquench[i];
}

void AliGenPythiaEventHeader::TriggerJet(Int_t i, Float_t p[4])
{
//
// Give back jet #i
//
    if (i >= fNJets) {
	printf("\nWarning: TriggerJet, index out of Range!!\n");
    } else {
	p[0] = fJets[0][i];
	p[1] = fJets[1][i];
	p[2] = fJets[2][i];
	p[3] = fJets[3][i];
    }
}

void AliGenPythiaEventHeader::UQJet(Int_t i, Float_t p[4])
{
//
// Give back jet #i
//
    if (i >= fNUQJets) {
	printf("\nWarning: Unquenched Jets, index out of Range!!\n");
    } else {
	p[0] = fUQJets[0][i];
	p[1] = fUQJets[1][i];
	p[2] = fUQJets[2][i];
	p[3] = fUQJets[3][i];
    }
}

void AliGenPythiaEventHeader::SetXYJet(Double_t x, Double_t y)
{

//
//  Add jet production point
//
    fXJet = x;
    fYJet = y;
}
<commit_msg>Initialisation fixed A. Aiola<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include "AliGenPythiaEventHeader.h"
ClassImp(AliGenPythiaEventHeader)

AliGenPythiaEventHeader::AliGenPythiaEventHeader():
    fProcessType(0),
    fTrials(0),
    fNJets(0),
    fNUQJets(0),
    fXJet(-1.),
    fYJet(-1.),
    fInMediumLength(0.),
    fImpactParameter(-1),
    fPtHard(0.),
    fXsection(0)
{
// Default Constructor
    for (Int_t i = 0; i < 4; i++) fZquench[i] = 0.;
    for (Int_t i = 0; i < 4; i++)
      for (Int_t j = 0; j < 10; j++) {
	fJets[i][j] = 0.;
	fUQJets[i][j] = 0.;
      }
}

AliGenPythiaEventHeader::AliGenPythiaEventHeader(const char* name):
    AliGenEventHeader(name),
    fProcessType(0),
    fTrials(0),
    fNJets(0),
    fNUQJets(0),
    fXJet(-1.),
    fYJet(-1.),
    fInMediumLength(0.),
    fImpactParameter(-1),
    fPtHard(0.),
    fXsection(0)
{
// Constructor
    for (Int_t i = 0; i < 4; i++) fZquench[i] = 0.;
    for (Int_t i = 0; i < 4; i++)
      for (Int_t j = 0; j < 10; j++) {
	fJets[i][j] = 0.;
	fUQJets[i][j] = 0.;
      }
}

void AliGenPythiaEventHeader::AddJet(Float_t px, Float_t py, Float_t pz, Float_t e)
{
//
//  Add a jet
//
    if (fNJets < 10) {
	fJets[0][fNJets] = px;
	fJets[1][fNJets] = py;
	fJets[2][fNJets] = pz;
	fJets[3][fNJets] = e;
	fNJets++;
    } else {
	printf("\nWarning: More than 10 jets triggered !!\n");
    }
}

void AliGenPythiaEventHeader::AddUQJet(Float_t px, Float_t py, Float_t pz, Float_t e)
{
//
//  Add a jet
//
    if (fNUQJets < 10) {
	fUQJets[0][fNUQJets] = px;
	fUQJets[1][fNUQJets] = py;
	fUQJets[2][fNUQJets] = pz;
	fUQJets[3][fNUQJets] = e;
	fNUQJets++;
    } else {
	printf("\nWarning: More than 10 jets triggered !!\n");
    }
}

void AliGenPythiaEventHeader::SetZQuench(Double_t z[4])
{
    //
    // Set quenching fraction
    //
    for (Int_t i = 0; i < 4; i++) fZquench[i] = z[i];
}

void AliGenPythiaEventHeader::GetZQuench(Double_t z[4]) const
{
    //
    // Get quenching fraction
    //
    for (Int_t i = 0; i < 4; i++) z[i] = fZquench[i];
}

void AliGenPythiaEventHeader::TriggerJet(Int_t i, Float_t p[4])
{
//
// Give back jet #i
//
    if (i >= fNJets) {
	printf("\nWarning: TriggerJet, index out of Range!!\n");
    } else {
	p[0] = fJets[0][i];
	p[1] = fJets[1][i];
	p[2] = fJets[2][i];
	p[3] = fJets[3][i];
    }
}

void AliGenPythiaEventHeader::UQJet(Int_t i, Float_t p[4])
{
//
// Give back jet #i
//
    if (i >= fNUQJets) {
	printf("\nWarning: Unquenched Jets, index out of Range!!\n");
    } else {
	p[0] = fUQJets[0][i];
	p[1] = fUQJets[1][i];
	p[2] = fUQJets[2][i];
	p[3] = fUQJets[3][i];
    }
}

void AliGenPythiaEventHeader::SetXYJet(Double_t x, Double_t y)
{

//
//  Add jet production point
//
    fXJet = x;
    fYJet = y;
}
<|endoftext|>


<commit_before><commit_msg>tdf#91259 - fix help browser focus issue post dispose.<commit_after><|endoftext|>


<commit_before><commit_msg>WaE: 'e' : unreferenced local variable<commit_after><|endoftext|>