text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_CarRpcLibClient_hpp #define air_CarRpcLibClient_hpp #include "common/Common.hpp" #include <functional> #include "common/CommonStructs.hpp" #include "vehicles/car/api/CarApiBase.hpp" #include "api/RpcLibClientBase.hpp" #include "common/ImageCaptureBase.hpp" namespace msr { namespace airlib { class CarRpcLibClient : public RpcLibClientBase { public: CarRpcLibClient(const string& ip_address = "localhost", uint16_t port = RpcLibPort, float timeout_sec = 60); void setCarControls(const CarApiBase::CarControls& controls, const std::string& vehicle_name = ""); CarApiBase::CarState getCarState(const std::string& vehicle_name = ""); CarApiBase::CarControls getCarControls(const std::string& vehicle_name = ""); virtual ~CarRpcLibClient(); //required for pimpl }; } } //namespace #endif
AirSim/AirLib/include/vehicles/car/api/CarRpcLibClient.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/car/api/CarRpcLibClient.hpp", "repo_id": "AirSim", "token_count": 348 }
14
#ifndef msr_airlib_ArduCopterSoloApi_h #define msr_airlib_ArduCopterSoloApi_h #include "AdHocConnection.hpp" #include "vehicles/multirotor/MultiRotorPhysicsBody.hpp" #include "vehicles/multirotor/firmwares/mavlink/MavLinkMultirotorApi.hpp" namespace msr { namespace airlib { class ArduCopterSoloApi : public MavLinkMultirotorApi { public: virtual ~ArduCopterSoloApi() { closeAllConnection(); } virtual void update() { if (sensors_ == nullptr) return; // send GPS and other sensor updates const uint count_gps_sensors = getSensors().size(SensorBase::SensorType::Gps); if (count_gps_sensors != 0) { const auto& gps_output = getGpsData(""); const auto& imu_output = getImuData(""); SensorMessage packet; packet.timestamp = clock()->nowNanos() / 1000; packet.latitude = gps_output.gnss.geo_point.latitude; packet.longitude = gps_output.gnss.geo_point.longitude; packet.altitude = gps_output.gnss.geo_point.altitude; common_utils::Utils::log("Current LLA: " + gps_output.gnss.geo_point.to_string(), common_utils::Utils::kLogLevelInfo); packet.speedN = gps_output.gnss.velocity[0]; packet.speedE = gps_output.gnss.velocity[1]; packet.speedD = gps_output.gnss.velocity[2]; packet.xAccel = imu_output.linear_acceleration[0]; packet.yAccel = imu_output.linear_acceleration[1]; packet.zAccel = imu_output.linear_acceleration[2]; float yaw; float pitch; float roll; VectorMath::toEulerianAngle(imu_output.orientation, pitch, roll, yaw); packet.yawDeg = yaw * 180.0 / M_PI; packet.pitchDeg = pitch * 180.0 / M_PI; packet.rollDeg = roll * 180.0 / M_PI; Vector3r bodyRPY(roll, pitch, yaw); // In the Unreal world, yaw is rotation around Z, so this seems to be RPY, like PySim Vector3r bodyVelocityRPY(imu_output.angular_velocity[0], imu_output.angular_velocity[1], imu_output.angular_velocity[2]); Vector3r earthRPY = bodyAnglesToEarthAngles(bodyRPY, bodyVelocityRPY); packet.rollRate = earthRPY[0] * 180.0 / M_PI; packet.pitchRate = earthRPY[1] * 180.0 / M_PI; packet.yawRate = earthRPY[2] * 180.0 / M_PI; // Heading appears to be unused by AruPilot. But use yaw for now packet.heading = yaw; packet.airspeed = std::sqrt( packet.speedN * packet.speedN + packet.speedE * packet.speedE + packet.speedD * packet.speedD); packet.magic = 0x4c56414f; if (udpSocket_ != nullptr) { std::vector<uint8_t> msg(sizeof(packet)); memcpy(msg.data(), &packet, sizeof(packet)); udpSocket_->sendMessage(msg); } } } virtual void close() { MavLinkMultirotorApi::close(); if (udpSocket_ != nullptr) { udpSocket_->close(); udpSocket_->unsubscribe(rotorSubscriptionId_); udpSocket_ = nullptr; } } protected: virtual void connect() { if (!is_simulation_mode_) { MavLinkMultirotorApi::connect(); } else { const std::string& ip = connection_info_.udp_address; int port = connection_info_.udp_port; close(); if (ip == "") { throw std::invalid_argument("UdpIp setting is invalid."); } if (port == 0) { throw std::invalid_argument("UdpPort setting has an invalid value."); } Utils::log(Utils::stringf("Using UDP port %d, local IP %s, remote IP %s for sending sensor data", port, connection_info_.local_host_ip.c_str(), ip.c_str()), Utils::kLogLevelInfo); Utils::log(Utils::stringf("Using UDP port %d for receiving rotor power", connection_info_.control_port_local, connection_info_.local_host_ip.c_str(), ip.c_str()), Utils::kLogLevelInfo); udpSocket_ = mavlinkcom::AdHocConnection::connectLocalUdp("ArduCopterSoloConnector", ip, connection_info_.control_port_local); mavlinkcom::AdHocMessageHandler handler = [this](std::shared_ptr<mavlinkcom::AdHocConnection> connection, const std::vector<uint8_t>& msg) { this->rotorPowerMessageHandler(connection, msg); }; rotorSubscriptionId_ = udpSocket_->subscribe(handler); } } private: #ifdef __linux__ struct __attribute__((__packed__)) SensorMessage { #else #pragma pack(push, 1) struct SensorMessage { #endif // this is the packet sent by the simulator // to the APM executable to update the simulator state // All values are little-endian uint64_t timestamp; double latitude, longitude; // degrees double altitude; // MSL double heading; // degrees double speedN, speedE, speedD; // m/s double xAccel, yAccel, zAccel; // m/s/s in body frame double rollRate, pitchRate, yawRate; // degrees/s/s in earth frame double rollDeg, pitchDeg, yawDeg; // euler angles, degrees double airspeed; // m/s uint32_t magic; // 0x4c56414f }; #ifndef __linux__ #pragma pack(pop) #endif static const int kArduCopterRotorControlCount = 11; struct RotorControlMessage { // ArduPilot Solo rotor control datagram format uint16_t pwm[kArduCopterRotorControlCount]; uint16_t speed, direction, turbulance; }; std::shared_ptr<mavlinkcom::AdHocConnection> udpSocket_; int rotorSubscriptionId_; virtual void normalizeRotorControls() { // change 1000-2000 to 0-1. for (size_t i = 0; i < Utils::length(rotor_controls_); ++i) { rotor_controls_[i] = (rotor_controls_[i] - 1000.0f) / 1000.0f; } } void rotorPowerMessageHandler(std::shared_ptr<mavlinkcom::AdHocConnection> connection, const std::vector<uint8_t>& msg) { if (msg.size() != sizeof(RotorControlMessage)) { Utils::log("Got rotor control message of size " + std::to_string(msg.size()) + " when we were expecting size " + std::to_string(sizeof(RotorControlMessage)), Utils::kLogLevelError); return; } RotorControlMessage rotorControlMessage; memcpy(&rotorControlMessage, msg.data(), sizeof(RotorControlMessage)); std::lock_guard<std::mutex> guard_actuator(hil_controls_mutex_); //use same mutex as HIL_CONTROl for (auto i = 0; i < RotorControlsCount && i < kArduCopterRotorControlCount; ++i) { rotor_controls_[i] = rotorControlMessage.pwm[i]; } normalizeRotorControls(); } Vector3r bodyAnglesToEarthAngles(Vector3r bodyRPY, Vector3r bodyVelocityRPY) { float p = bodyVelocityRPY[0]; float q = bodyVelocityRPY[1]; float r = bodyVelocityRPY[2]; // Roll, pitch, yaw float phi = bodyRPY[0]; float theta = bodyRPY[1]; float phiDot = p + tan(theta) * (q * sin(phi) + r * cos(phi)); float thetaDot = q * cos(phi) - r * sin(phi); if (fabs(cos(theta)) < 1.0e-20) { theta += 1.0e-10f; } float psiDot = (q * sin(phi) + r * cos(phi)) / cos(theta); return Vector3r(phiDot, thetaDot, psiDot); } }; } } //namespace #endif
AirSim/AirLib/include/vehicles/multirotor/firmwares/mavlink/ArduCopterSoloApi.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/mavlink/ArduCopterSoloApi.hpp", "repo_id": "AirSim", "token_count": 4095 }
15
#pragma once #include <vector> #include <algorithm> #include "Params.hpp" #include "interfaces/CommonStructs.hpp" namespace simple_flight { class Mixer { public: Mixer(const Params* params) : params_(params) { } void getMotorOutput(const Axis4r& controls, std::vector<float>& motor_outputs) const { if (controls.throttle() < params_->motor.min_angling_throttle) { motor_outputs.assign(params_->motor.motor_count, controls.throttle()); return; } for (int motor_index = 0; motor_index < kMotorCount; ++motor_index) { motor_outputs[motor_index] = controls.throttle() * mixerQuadX[motor_index].throttle + controls.pitch() * mixerQuadX[motor_index].pitch + controls.roll() * mixerQuadX[motor_index].roll + controls.yaw() * mixerQuadX[motor_index].yaw; } float min_motor = *std::min_element(motor_outputs.begin(), motor_outputs.begin() + kMotorCount); if (min_motor < params_->motor.min_motor_output) { float undershoot = params_->motor.min_motor_output - min_motor; for (int motor_index = 0; motor_index < kMotorCount; ++motor_index) motor_outputs[motor_index] += undershoot; } float max_motor = *std::max_element(motor_outputs.begin(), motor_outputs.begin() + kMotorCount); float scale = max_motor / params_->motor.max_motor_output; if (scale > params_->motor.max_motor_output) { for (int motor_index = 0; motor_index < kMotorCount; ++motor_index) motor_outputs[motor_index] /= scale; } for (int motor_index = 0; motor_index < kMotorCount; ++motor_index) motor_outputs[motor_index] = std::max(params_->motor.min_motor_output, std::min(motor_outputs[motor_index], params_->motor.max_motor_output)); } private: const int kMotorCount = 4; const Params* params_; // Custom mixer data per motor typedef struct motorMixer_t { float throttle; float roll; float pitch; float yaw; } motorMixer_t; //only thing that this matrix does is change the sign const motorMixer_t mixerQuadX[4] = { //QuadX config { 1.0f, -1.0f, 1.0f, 1.0f }, // FRONT_R { 1.0f, 1.0f, -1.0f, 1.0f }, // REAR_L { 1.0f, 1.0f, 1.0f, -1.0f }, // FRONT_L { 1.0f, -1.0f, -1.0f, -1.0f }, // REAR_R }; }; } //namespace
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/Mixer.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/Mixer.hpp", "repo_id": "AirSim", "token_count": 1192 }
16
#pragma once namespace simple_flight { class IBoardSensors { public: virtual void readAccel(float accel[3]) const = 0; //accel in m/s^2 virtual void readGyro(float gyro[3]) const = 0; //angular velocity vector rad/sec virtual ~IBoardSensors() = default; }; }
AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IBoardSensors.hpp/0
{ "file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IBoardSensors.hpp", "repo_id": "AirSim", "token_count": 103 }
17
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. //in header only mode, control library is not available #ifndef AIRLIB_HEADER_ONLY #include "vehicles/multirotor/api/MultirotorApiBase.hpp" #include <functional> #include <exception> #include <vector> #include <iostream> #include <fstream> namespace msr { namespace airlib { void MultirotorApiBase::resetImplementation() { cancelLastTask(); SingleTaskCall lock(this); //cancel previous tasks } bool MultirotorApiBase::takeoff(float timeout_sec) { SingleTaskCall lock(this); auto kinematics = getKinematicsEstimated(); if (kinematics.twist.linear.norm() > approx_zero_vel_) { throw VehicleMoveException(Utils::stringf( "Cannot perform takeoff because vehicle is already moving with velocity %f m/s", kinematics.twist.linear.norm())); } bool ret = moveToPosition(kinematics.pose.position.x(), kinematics.pose.position.y(), kinematics.pose.position.z() + getTakeoffZ(), 0.5f, timeout_sec, DrivetrainType::MaxDegreeOfFreedom, YawMode::Zero(), -1, 1); //last command is to hold on to position //commandPosition(0, 0, getTakeoffZ(), YawMode::Zero()); return ret; } bool MultirotorApiBase::land(float timeout_sec) { SingleTaskCall lock(this); //after landing we detect if drone has stopped moving int near_zero_vel_count = 0; return waitForFunction([&]() { moveByVelocityInternal(0, 0, landing_vel_, YawMode::Zero()); float z_vel = getVelocity().z(); if (z_vel <= approx_zero_vel_) ++near_zero_vel_count; else near_zero_vel_count = 0; if (near_zero_vel_count > 10) return true; else { moveByVelocityInternal(0, 0, landing_vel_, YawMode::Zero()); return false; } }, timeout_sec) .isComplete(); } bool MultirotorApiBase::goHome(float timeout_sec) { SingleTaskCall lock(this); return moveToPosition(0, 0, 0, 0.5f, timeout_sec, DrivetrainType::MaxDegreeOfFreedom, YawMode::Zero(), -1, 1); } bool MultirotorApiBase::moveByVelocityBodyFrame(float vx, float vy, float vz, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode) { SingleTaskCall lock(this); if (duration <= 0) return true; float pitch, roll, yaw; VectorMath::toEulerianAngle(getKinematicsEstimated().pose.orientation, pitch, roll, yaw); float vx_new = (vx * (float)std::cos(yaw)) - (vy * (float)std::sin(yaw)); float vy_new = (vx * (float)std::sin(yaw)) + (vy * (float)std::cos(yaw)); YawMode adj_yaw_mode(yaw_mode.is_rate, yaw_mode.yaw_or_rate); adjustYaw(vx_new, vy_new, drivetrain, adj_yaw_mode); return waitForFunction([&]() { moveByVelocityInternal(vx_new, vy_new, vz, adj_yaw_mode); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByVelocityZBodyFrame(float vx, float vy, float z, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode) { SingleTaskCall lock(this); if (duration <= 0) return true; float pitch, roll, yaw; VectorMath::toEulerianAngle(getKinematicsEstimated().pose.orientation, pitch, roll, yaw); float vx_new = (vx * (float)std::cos(yaw)) - (vy * (float)std::sin(yaw)); float vy_new = (vx * (float)std::sin(yaw)) + (vy * (float)std::cos(yaw)); YawMode adj_yaw_mode(yaw_mode.is_rate, yaw_mode.yaw_or_rate); adjustYaw(vx_new, vy_new, drivetrain, adj_yaw_mode); return waitForFunction([&]() { moveByVelocityZInternal(vx_new, vy_new, z, adj_yaw_mode); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByMotorPWMs(float front_right_pwm, float rear_left_pwm, float front_left_pwm, float rear_right_pwm, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { commandMotorPWMs(front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByRollPitchYawZ(float roll, float pitch, float yaw, float z, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { moveByRollPitchYawZInternal(roll, pitch, yaw, z); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByRollPitchYawThrottle(float roll, float pitch, float yaw, float throttle, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { moveByRollPitchYawThrottleInternal(roll, pitch, yaw, throttle); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByRollPitchYawrateThrottle(float roll, float pitch, float yaw_rate, float throttle, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { moveByRollPitchYawrateThrottleInternal(roll, pitch, yaw_rate, throttle); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByRollPitchYawrateZ(float roll, float pitch, float yaw_rate, float z, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { moveByRollPitchYawrateZInternal(roll, pitch, yaw_rate, z); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByAngleRatesZ(float roll_rate, float pitch_rate, float yaw_rate, float z, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { moveByAngleRatesZInternal(roll_rate, pitch_rate, yaw_rate, z); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByAngleRatesThrottle(float roll_rate, float pitch_rate, float yaw_rate, float throttle, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; return waitForFunction([&]() { moveByAngleRatesThrottleInternal(roll_rate, pitch_rate, yaw_rate, throttle); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByVelocity(float vx, float vy, float vz, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode) { SingleTaskCall lock(this); if (duration <= 0) return true; YawMode adj_yaw_mode(yaw_mode.is_rate, yaw_mode.yaw_or_rate); adjustYaw(vx, vy, drivetrain, adj_yaw_mode); return waitForFunction([&]() { moveByVelocityInternal(vx, vy, vz, adj_yaw_mode); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveByVelocityZ(float vx, float vy, float z, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode) { SingleTaskCall lock(this); if (duration <= 0) return false; YawMode adj_yaw_mode(yaw_mode.is_rate, yaw_mode.yaw_or_rate); adjustYaw(vx, vy, drivetrain, adj_yaw_mode); return waitForFunction([&]() { moveByVelocityZInternal(vx, vy, z, adj_yaw_mode); return false; //keep moving until timeout }, duration) .isTimeout(); } bool MultirotorApiBase::moveOnPath(const vector<Vector3r>& path, float velocity, float timeout_sec, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead) { SingleTaskCall lock(this); //validate path size if (path.size() == 0) { Utils::log("moveOnPath terminated because path has no points", Utils::kLogLevelWarn); return true; } //validate yaw mode if (drivetrain == DrivetrainType::ForwardOnly && yaw_mode.is_rate) throw std::invalid_argument("Yaw cannot be specified as rate if drivetrain is ForwardOnly"); //validate and set auto-lookahead value float command_period_dist = velocity * getCommandPeriod(); if (lookahead == 0) throw std::invalid_argument("lookahead distance cannot be 0"); //won't allow progress on path else if (lookahead > 0) { if (command_period_dist > lookahead) throw std::invalid_argument(Utils::stringf("lookahead value %f is too small for velocity %f. It must be at least %f", lookahead, velocity, command_period_dist)); if (getDistanceAccuracy() > lookahead) throw std::invalid_argument(Utils::stringf("lookahead value %f is smaller than drone's distance accuracy %f.", lookahead, getDistanceAccuracy())); } else { //if auto mode requested for lookahead then calculate based on velocity lookahead = getAutoLookahead(velocity, adaptive_lookahead); Utils::log(Utils::stringf("lookahead = %f, adaptive_lookahead = %f", lookahead, adaptive_lookahead)); } //add current position as starting point vector<Vector3r> path3d; vector<PathSegment> path_segs; path3d.push_back(getKinematicsEstimated().pose.position); Vector3r point; float path_length = 0; //append the input path and compute segments for (uint i = 0; i < path.size(); ++i) { point = path.at(i); PathSegment path_seg(path3d.at(i), point, velocity, path_length); path_length += path_seg.seg_length; path_segs.push_back(path_seg); path3d.push_back(point); } //add last segment as zero length segment so we have equal number of segments and points. //path_segs[i] refers to segment that starts at point i path_segs.push_back(PathSegment(point, point, velocity, path_length)); //when path ends, we want to slow down float breaking_dist = 0; if (velocity > getMultirotorApiParams().breaking_vel) { breaking_dist = Utils::clip(velocity * getMultirotorApiParams().vel_to_breaking_dist, getMultirotorApiParams().min_breaking_dist, getMultirotorApiParams().max_breaking_dist); } //else no need to change velocities for last segments //setup current position on path to 0 offset PathPosition cur_path_loc, next_path_loc; cur_path_loc.seg_index = 0; cur_path_loc.offset = 0; cur_path_loc.position = path3d[0]; float lookahead_error_increasing = 0; float lookahead_error = 0; Waiter waiter(getCommandPeriod(), timeout_sec, getCancelToken()); //initialize next path position setNextPathPosition(path3d, path_segs, cur_path_loc, lookahead + lookahead_error, next_path_loc); float overshoot = 0; float goal_dist = 0; //until we are at the end of the path (last seg is always zero size) while (!waiter.isTimeout() && (next_path_loc.seg_index < path_segs.size() - 1 || goal_dist > 0)) { //current position is approximately at the last end point float seg_velocity = path_segs.at(next_path_loc.seg_index).seg_velocity; float path_length_remaining = path_length - path_segs.at(cur_path_loc.seg_index).seg_path_length - cur_path_loc.offset; if (seg_velocity > getMultirotorApiParams().min_vel_for_breaking && path_length_remaining <= breaking_dist) { seg_velocity = getMultirotorApiParams().breaking_vel; //Utils::logMessage("path_length_remaining = %f, Switched to breaking vel %f", path_length_remaining, seg_velocity); } //send drone command to get to next lookahead moveToPathPosition(next_path_loc.position, seg_velocity, drivetrain, yaw_mode, path_segs.at(cur_path_loc.seg_index).start_z); //sleep for rest of the cycle if (!waiter.sleep()) return false; /* Below, P is previous position on path, N is next goal and C is our current position. N ^ | | | C'|---C | / | / |/ P Note that PC could be at any angle relative to PN, including 0 or -ve. We increase lookahead distance by the amount of |PC|. For this, we project PC on to PN to get vector PC' and length of CC'is our adaptive lookahead error by which we will increase lookahead distance. For next iteration, we first update our current position by goal_dist and then set next goal by the amount lookahead + lookahead_error. We need to take care of following cases: 1. |PN| == 0 => lookahead_error = |PC|, goal_dist = 0 2. |PC| == 0 => lookahead_error = 0, goal_dist = 0 3. PC in opposite direction => lookahead_error = |PC|, goal_dist = 0 One good test case is if C just keeps moving perpendicular to the path (instead of along the path). In that case, we expect next goal to come up and down by the amount of lookahead_error. However under no circumstances we should go back on the path (i.e. current pos on path can only move forward). */ //how much have we moved towards last goal? const Vector3r& goal_vect = next_path_loc.position - cur_path_loc.position; if (!goal_vect.isZero()) { //goal can only be zero if we are at the end of path const Vector3r& actual_vect = getPosition() - cur_path_loc.position; //project actual vector on goal vector const Vector3r& goal_normalized = goal_vect.normalized(); goal_dist = actual_vect.dot(goal_normalized); //dist could be -ve if drone moves away from goal //if adaptive lookahead is enabled the calculate lookahead error (see above fig) if (adaptive_lookahead) { const Vector3r& actual_on_goal = goal_normalized * goal_dist; float error = (actual_vect - actual_on_goal).norm() * adaptive_lookahead; if (error > lookahead_error) { lookahead_error_increasing++; //TODO: below should be lower than 1E3 and configurable //but lower values like 100 doesn't work for simple_flight + ScalableClock if (lookahead_error_increasing > 1E5) { throw std::runtime_error("lookahead error is continually increasing so we do not have safe control, aborting moveOnPath operation"); } } else { lookahead_error_increasing = 0; } lookahead_error = error; } } else { lookahead_error_increasing = 0; goal_dist = 0; lookahead_error = 0; //this is not really required because we will exit waiter.complete(); } // Utils::logMessage("PF: cur=%s, goal_dist=%f, cur_path_loc=%s, next_path_loc=%s, lookahead_error=%f", // VectorMath::toString(getPosition()).c_str(), goal_dist, VectorMath::toString(cur_path_loc.position).c_str(), // VectorMath::toString(next_path_loc.position).c_str(), lookahead_error); //if drone moved backward, we don't want goal to move backward as well //so only climb forward on the path, never back. Also note >= which means //we climb path even if distance was 0 to take care of duplicated points on path if (goal_dist >= 0) { overshoot = setNextPathPosition(path3d, path_segs, cur_path_loc, goal_dist, cur_path_loc); if (overshoot) Utils::log(Utils::stringf("overshoot=%f", overshoot)); } //else // Utils::logMessage("goal_dist was negative: %f", goal_dist); //compute next target on path overshoot = setNextPathPosition(path3d, path_segs, cur_path_loc, lookahead + lookahead_error, next_path_loc); } return waiter.isComplete(); } bool MultirotorApiBase::moveToGPS(float latitude, float longitude, float altitude, float velocity, float timeout_sec, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead) { SingleTaskCall lock(this); GeoPoint target; target.latitude = latitude; target.longitude = longitude; target.altitude = altitude; if (!std::isnan(getHomeGeoPoint().latitude) && !std::isnan(getHomeGeoPoint().longitude) && !std::isnan(getHomeGeoPoint().altitude)) { vector<Vector3r> path{ msr::airlib::EarthUtils::GeodeticToNed(target, getHomeGeoPoint()) }; return moveOnPath(path, velocity, timeout_sec, drivetrain, yaw_mode, lookahead, adaptive_lookahead); } else { vector<Vector3r> path{ Vector3r(getPosition().x(), getPosition().y(), getPosition().z()) }; return moveOnPath(path, velocity, timeout_sec, drivetrain, yaw_mode, lookahead, adaptive_lookahead); } } bool MultirotorApiBase::moveToPosition(float x, float y, float z, float velocity, float timeout_sec, DrivetrainType drivetrain, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead) { SingleTaskCall lock(this); vector<Vector3r> path{ Vector3r(x, y, z) }; return moveOnPath(path, velocity, timeout_sec, drivetrain, yaw_mode, lookahead, adaptive_lookahead); } bool MultirotorApiBase::moveToZ(float z, float velocity, float timeout_sec, const YawMode& yaw_mode, float lookahead, float adaptive_lookahead) { SingleTaskCall lock(this); Vector2r cur_xy(getPosition().x(), getPosition().y()); vector<Vector3r> path{ Vector3r(cur_xy.x(), cur_xy.y(), z) }; return moveOnPath(path, velocity, timeout_sec, DrivetrainType::MaxDegreeOfFreedom, yaw_mode, lookahead, adaptive_lookahead); } bool MultirotorApiBase::moveByManual(float vx_max, float vy_max, float z_min, float duration, DrivetrainType drivetrain, const YawMode& yaw_mode) { SingleTaskCall lock(this); const float kMaxMessageAge = 0.1f /* 0.1 sec */, kMaxRCValue = 10000; if (duration <= 0) return true; //freeze the quaternion Quaternionr starting_quaternion = getKinematicsEstimated().pose.orientation; Waiter waiter(getCommandPeriod(), duration, getCancelToken()); do { RCData rc_data = getRCData(); TTimeDelta age = clock()->elapsedSince(rc_data.timestamp); if (rc_data.is_valid && (rc_data.timestamp == 0 || age <= kMaxMessageAge)) { //if rc message timestamp is not set OR is not too old if (rc_data_trims_.is_valid) rc_data.subtract(rc_data_trims_); //convert RC commands to velocity vector const Vector3r vel_word(rc_data.pitch * vy_max / kMaxRCValue, rc_data.roll * vx_max / kMaxRCValue, 0); Vector3r vel_body = VectorMath::transformToBodyFrame(vel_word, starting_quaternion, true); //find yaw as per terrain and remote setting YawMode adj_yaw_mode(yaw_mode.is_rate, yaw_mode.yaw_or_rate); adj_yaw_mode.yaw_or_rate += rc_data.yaw * 100.0f / kMaxRCValue; adjustYaw(vel_body, drivetrain, adj_yaw_mode); //execute command try { float vz = (rc_data.throttle / kMaxRCValue) * z_min + getPosition().z(); moveByVelocityZInternal(vel_body.x(), vel_body.y(), vz, adj_yaw_mode); } catch (const MultirotorApiBase::UnsafeMoveException& ex) { Utils::log(Utils::stringf("Safety violation: %s", ex.result.message.c_str()), Utils::kLogLevelWarn); } } else Utils::log(Utils::stringf("RCData had too old timestamp: %f", age)); } while (waiter.sleep()); //if timeout occurred then command completed successfully otherwise it was interrupted return waiter.isTimeout(); } bool MultirotorApiBase::rotateToYaw(float yaw, float timeout_sec, float margin) { SingleTaskCall lock(this); if (timeout_sec <= 0) return true; auto start_pos = getPosition(); float yaw_target = VectorMath::normalizeAngle(yaw); YawMode move_yaw_mode(false, yaw_target); YawMode stop_yaw_mode(true, 0); return waitForFunction([&]() { if (isYawWithinMargin(yaw_target, margin)) { // yaw is within margin, then trying to stop rotation moveToPositionInternal(start_pos, stop_yaw_mode); // let yaw rate be zero auto yaw_rate = getKinematicsEstimated().twist.angular.z(); if (abs(yaw_rate) <= approx_zero_angular_vel_) { // already sopped return true; //stop all for stably achieving the goal } } else { // yaw is not within margin, go on rotation moveToPositionInternal(start_pos, move_yaw_mode); } // yaw is not within margin return false; //keep moving until timeout }, timeout_sec) .isComplete(); } bool MultirotorApiBase::rotateByYawRate(float yaw_rate, float duration) { SingleTaskCall lock(this); if (duration <= 0) return true; auto start_pos = getPosition(); YawMode yaw_mode(true, yaw_rate); return waitForFunction([&]() { moveToPositionInternal(start_pos, yaw_mode); return false; //keep moving until timeout }, duration) .isTimeout(); } void MultirotorApiBase::setAngleLevelControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd) { uint8_t controller_type = 2; setControllerGains(controller_type, kp, ki, kd); } void MultirotorApiBase::setAngleRateControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd) { uint8_t controller_type = 3; setControllerGains(controller_type, kp, ki, kd); } void MultirotorApiBase::setVelocityControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd) { uint8_t controller_type = 4; setControllerGains(controller_type, kp, ki, kd); } void MultirotorApiBase::setPositionControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd) { uint8_t controller_type = 5; setControllerGains(controller_type, kp, ki, kd); } bool MultirotorApiBase::hover() { SingleTaskCall lock(this); return moveToZ(getPosition().z(), 0.5f, Utils::max<float>(), YawMode{ true, 0 }, 1.0f, false); } void MultirotorApiBase::moveByRC(const RCData& rc_data) { unused(rc_data); //by default we say that this command is not supported throw VehicleCommandNotImplementedException("moveByRC API is not implemented for this multirotor"); } void MultirotorApiBase::moveByVelocityInternal(float vx, float vy, float vz, const YawMode& yaw_mode) { if (safetyCheckVelocity(Vector3r(vx, vy, vz))) commandVelocity(vx, vy, vz, yaw_mode); } void MultirotorApiBase::moveByVelocityZInternal(float vx, float vy, float z, const YawMode& yaw_mode) { if (safetyCheckVelocityZ(vx, vy, z)) commandVelocityZ(vx, vy, z, yaw_mode); } void MultirotorApiBase::moveToPositionInternal(const Vector3r& dest, const YawMode& yaw_mode) { if (safetyCheckDestination(dest)) commandPosition(dest.x(), dest.y(), dest.z(), yaw_mode); } void MultirotorApiBase::moveByRollPitchYawZInternal(float roll, float pitch, float yaw, float z) { if (safetyCheckVelocity(getVelocity())) commandRollPitchYawZ(roll, pitch, yaw, z); } void MultirotorApiBase::moveByRollPitchYawThrottleInternal(float roll, float pitch, float yaw, float throttle) { if (safetyCheckVelocity(getVelocity())) commandRollPitchYawThrottle(roll, pitch, yaw, throttle); } void MultirotorApiBase::moveByRollPitchYawrateThrottleInternal(float roll, float pitch, float yaw_rate, float throttle) { if (safetyCheckVelocity(getVelocity())) commandRollPitchYawrateThrottle(roll, pitch, yaw_rate, throttle); } void MultirotorApiBase::moveByRollPitchYawrateZInternal(float roll, float pitch, float yaw_rate, float z) { if (safetyCheckVelocity(getVelocity())) commandRollPitchYawrateZ(roll, pitch, yaw_rate, z); } void MultirotorApiBase::moveByAngleRatesZInternal(float roll_rate, float pitch_rate, float yaw_rate, float z) { if (safetyCheckVelocity(getVelocity())) commandAngleRatesZ(roll_rate, pitch_rate, yaw_rate, z); } void MultirotorApiBase::moveByAngleRatesThrottleInternal(float roll_rate, float pitch_rate, float yaw_rate, float throttle) { if (safetyCheckVelocity(getVelocity())) commandAngleRatesThrottle(roll_rate, pitch_rate, yaw_rate, throttle); } //executes a given function until it returns true. Each execution is spaced apart at command period. //return value is true if exit was due to given function returning true, otherwise false (due to timeout) Waiter MultirotorApiBase::waitForFunction(WaitFunction function, float timeout_sec) { Waiter waiter(getCommandPeriod(), timeout_sec, getCancelToken()); if (timeout_sec <= 0) return waiter; do { if (function()) { waiter.complete(); break; } } while (waiter.sleep()); return waiter; } bool MultirotorApiBase::waitForZ(float timeout_sec, float z, float margin) { float cur_z = 100000; return waitForFunction([&]() { cur_z = getPosition().z(); return (std::abs(cur_z - z) <= margin); }, timeout_sec) .isComplete(); } void MultirotorApiBase::setSafetyEval(const shared_ptr<SafetyEval> safety_eval_ptr) { SingleCall lock(this); safety_eval_ptr_ = safety_eval_ptr; } RCData MultirotorApiBase::estimateRCTrims(float trimduration, float minCountForTrim, float maxTrim) { rc_data_trims_ = RCData(); //get trims Waiter waiter_trim(getCommandPeriod(), trimduration, getCancelToken()); uint count = 0; do { const RCData rc_data = getRCData(); if (rc_data.is_valid) { rc_data_trims_.add(rc_data); count++; } } while (waiter_trim.sleep()); rc_data_trims_.is_valid = true; if (count < minCountForTrim) { rc_data_trims_.is_valid = false; Utils::log("Cannot compute RC trim because too few readings received"); } //take average rc_data_trims_.divideBy(static_cast<float>(count)); if (rc_data_trims_.isAnyMoreThan(maxTrim)) { rc_data_trims_.is_valid = false; Utils::log(Utils::stringf("RC trims does not seem to be valid: %s", rc_data_trims_.toString().c_str())); } Utils::log(Utils::stringf("RCData Trims: %s", rc_data_trims_.toString().c_str())); return rc_data_trims_; } void MultirotorApiBase::moveToPathPosition(const Vector3r& dest, float velocity, DrivetrainType drivetrain, /* pass by value */ YawMode yaw_mode, float last_z) { unused(last_z); //validate dest if (dest.hasNaN()) throw std::invalid_argument(VectorMath::toString(dest, "dest vector cannot have NaN: ")); //what is the distance we will travel at this velocity? float expected_dist = velocity * getCommandPeriod(); //get velocity vector const Vector3r cur = getPosition(); const Vector3r cur_dest = dest - cur; float cur_dest_norm = cur_dest.norm(); //yaw for the direction of travel adjustYaw(cur_dest, drivetrain, yaw_mode); //find velocity vector Vector3r velocity_vect; if (cur_dest_norm < getDistanceAccuracy()) //our dest is approximately same as current velocity_vect = Vector3r::Zero(); else if (cur_dest_norm >= expected_dist) { velocity_vect = (cur_dest / cur_dest_norm) * velocity; //Utils::logMessage("velocity_vect=%s", VectorMath::toString(velocity_vect).c_str()); } else { //cur dest is too close than the distance we would travel //generate velocity vector that is same size as cur_dest_norm / command period //this velocity vect when executed for command period would yield cur_dest_norm Utils::log(Utils::stringf("Too close dest: cur_dest_norm=%f, expected_dist=%f", cur_dest_norm, expected_dist)); velocity_vect = (cur_dest / cur_dest_norm) * (cur_dest_norm / getCommandPeriod()); } //send commands //try to maintain altitude if path was in XY plan only, velocity based control is not as good if (std::abs(cur.z() - dest.z()) <= getDistanceAccuracy()) //for paths in XY plan current code leaves z untouched, so we can compare with strict equality moveByVelocityInternal(velocity_vect.x(), velocity_vect.y(), 0, yaw_mode); else moveByVelocityInternal(velocity_vect.x(), velocity_vect.y(), velocity_vect.z(), yaw_mode); } bool MultirotorApiBase::setSafety(SafetyEval::SafetyViolationType enable_reasons, float obs_clearance, SafetyEval::ObsAvoidanceStrategy obs_startegy, float obs_avoidance_vel, const Vector3r& origin, float xy_length, float max_z, float min_z) { if (safety_eval_ptr_ == nullptr) throw std::invalid_argument("The setSafety call requires safety_eval_ptr_ to be set first"); //default strategy is for move. In hover mode we set new strategy temporarily safety_eval_ptr_->setSafety(enable_reasons, obs_clearance, obs_startegy, origin, xy_length, max_z, min_z); obs_avoidance_vel_ = obs_avoidance_vel; Utils::log(Utils::stringf("obs_avoidance_vel: %f", obs_avoidance_vel_)); return true; } bool MultirotorApiBase::emergencyManeuverIfUnsafe(const SafetyEval::EvalResult& result) { if (!result.is_safe) { if (result.reason == SafetyEval::SafetyViolationType_::Obstacle) { //are we supposed to do EM? if (safety_eval_ptr_->getObsAvoidanceStrategy() != SafetyEval::ObsAvoidanceStrategy::RaiseException) { //get suggested velocity vector Vector3r avoidance_vel = getObsAvoidanceVelocity(result.cur_risk_dist, obs_avoidance_vel_) * result.suggested_vec; //use the unchecked command commandVelocityZ(avoidance_vel.x(), avoidance_vel.y(), getPosition().z(), YawMode::Zero()); //tell caller not to execute planned command return false; } //other wise throw exception } //otherwise there is some other reason why we are in unsafe situation //send last command to come to full stop commandVelocity(0, 0, 0, YawMode::Zero()); throw UnsafeMoveException(result); } //else no unsafe situation return true; } bool MultirotorApiBase::safetyCheckVelocity(const Vector3r& velocity) { if (safety_eval_ptr_ == nullptr) //safety checks disabled return true; const auto& result = safety_eval_ptr_->isSafeVelocity(getPosition(), velocity, getOrientation()); return emergencyManeuverIfUnsafe(result); } bool MultirotorApiBase::safetyCheckVelocityZ(float vx, float vy, float z) { if (safety_eval_ptr_ == nullptr) //safety checks disabled return true; const auto& result = safety_eval_ptr_->isSafeVelocityZ(getPosition(), vx, vy, z, getOrientation()); return emergencyManeuverIfUnsafe(result); } bool MultirotorApiBase::safetyCheckDestination(const Vector3r& dest_pos) { if (safety_eval_ptr_ == nullptr) //safety checks disabled return true; const auto& result = safety_eval_ptr_->isSafeDestination(getPosition(), dest_pos, getOrientation()); return emergencyManeuverIfUnsafe(result); } float MultirotorApiBase::setNextPathPosition(const vector<Vector3r>& path, const vector<PathSegment>& path_segs, const PathPosition& cur_path_loc, float next_dist, PathPosition& next_path_loc) { //note: cur_path_loc and next_path_loc may both point to same object uint i = cur_path_loc.seg_index; float offset = cur_path_loc.offset; while (i < path.size() - 1) { const PathSegment& seg = path_segs.at(i); if (seg.seg_length > 0 && //protect against duplicate points in path, normalized seg will have NaN seg.seg_length >= next_dist + offset) { next_path_loc.seg_index = i; next_path_loc.offset = next_dist + offset; //how much total distance we will travel on this segment next_path_loc.position = path.at(i) + seg.seg_normalized * next_path_loc.offset; return 0; } //otherwise use up this segment, move on to next one next_dist -= seg.seg_length - offset; offset = 0; if (&cur_path_loc == &next_path_loc) Utils::log(Utils::stringf("segment %d done: x=%f, y=%f, z=%f", i, path.at(i).x(), path.at(i).y(), path.at(i).z())); ++i; } //if we are here then we ran out of segments //consider last segment as zero length segment next_path_loc.seg_index = i; next_path_loc.offset = 0; next_path_loc.position = path.at(i); return next_dist; } void MultirotorApiBase::adjustYaw(const Vector3r& heading, DrivetrainType drivetrain, YawMode& yaw_mode) { //adjust yaw for the direction of travel in forward-only mode if (drivetrain == DrivetrainType::ForwardOnly && !yaw_mode.is_rate) { if (heading.norm() > getDistanceAccuracy()) { yaw_mode.yaw_or_rate = yaw_mode.yaw_or_rate + (std::atan2(heading.y(), heading.x()) * 180 / M_PIf); yaw_mode.yaw_or_rate = VectorMath::normalizeAngle(yaw_mode.yaw_or_rate); } else yaw_mode.setZeroRate(); //don't change existing yaw if heading is too small because that can generate random result } //else no adjustment needed } void MultirotorApiBase::adjustYaw(float x, float y, DrivetrainType drivetrain, YawMode& yaw_mode) { adjustYaw(Vector3r(x, y, 0), drivetrain, yaw_mode); } bool MultirotorApiBase::isYawWithinMargin(float yaw_target, float margin) const { const float yaw_current = VectorMath::getYaw(getOrientation()) * 180 / M_PIf; return std::abs(yaw_current - yaw_target) <= margin; } float MultirotorApiBase::getAutoLookahead(float velocity, float adaptive_lookahead, float max_factor, float min_factor) const { //if auto mode requested for lookahead then calculate based on velocity float command_period_dist = velocity * getCommandPeriod(); float lookahead = command_period_dist * (adaptive_lookahead > 0 ? min_factor : max_factor); lookahead = std::max(lookahead, getDistanceAccuracy() * 1.5f); //50% more than distance accuracy return lookahead; } float MultirotorApiBase::getObsAvoidanceVelocity(float risk_dist, float max_obs_avoidance_vel) const { unused(risk_dist); return max_obs_avoidance_vel; } } } //namespace #endif
AirSim/AirLib/src/vehicles/multirotor/api/MultirotorApiBase.cpp/0
{ "file_path": "AirSim/AirLib/src/vehicles/multirotor/api/MultirotorApiBase.cpp", "repo_id": "AirSim", "token_count": 17719 }
18
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.27428.2043 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DroneShell", "DroneShell\DroneShell.vcxproj", "{9FE9234B-373A-4D5A-AD6B-FB0B593312DD}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AirLib", "AirLib\AirLib.vcxproj", "{4BFB7231-077A-4671-BD21-D3ADE3EA36E7}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloDrone", "HelloDrone\HelloDrone.vcxproj", "{98BB426F-6FB5-4754-81BC-BB481900E135}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MavLinkCom", "MavLinkCom\MavLinkCom.vcxproj", "{8510C7A4-BF63-41D2-94F6-D8731D137A5A}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DroneServer", "DroneServer\DroneServer.vcxproj", "{A050F015-87E2-498F-866A-2E5AF65AF7AC}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MavLinkTest", "MavLinkCom\MavLinkTest\MavLinkTest.vcxproj", "{25EB67BE-468A-4AA5-910F-07EFD58C5516}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Examples", "Examples\Examples.vcxproj", "{C679466F-9D35-4AFC-B9AE-F9FB5448FB99}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AirLibUnitTests", "AirLibUnitTests\AirLibUnitTests.vcxproj", "{2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{11C1B3C5-35A0-46EA-B532-100A14FDAAC6}" ProjectSection(SolutionItems) = preProject .gitignore = .gitignore .gitmodules = .gitmodules .travis.yml = .travis.yml build.cmd = build.cmd build.sh = build.sh clean.cmd = clean.cmd clean.sh = clean.sh LICENSE = LICENSE README.md = README.md setup.sh = setup.sh EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCar", "HelloCar\HelloCar.vcxproj", "{4358ED90-CCA1-47A8-8D68-A260F212931E}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnrealPluginFiles", "UnrealPluginFiles.vcxproj", "{39683523-C864-4D47-8350-33FC3EC0F00F}" EndProject Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "PythonClient", "PythonClient\PythonClient.pyproj", "{E2049E20-B6DD-474E-8BCA-1C8DC54725AA}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sgmstereo", "SGM\src\sgmstereo\sgmstereo.vcxproj", "{A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "stereoPipeline", "SGM\src\stereoPipeline\stereoPipeline.vcxproj", "{E512EB59-4EAB-49D1-9174-0CAF1B40CED0}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloSpawnedDrones", "HelloSpawnedDrones\HelloSpawnedDrones.vcxproj", "{99CBF376-5EBA-4164-A657-E7D708C9D685}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM Release|x64 = Release|x64 Release|x86 = Release|x86 RelWithDebInfo|Any CPU = RelWithDebInfo|Any CPU RelWithDebInfo|ARM = RelWithDebInfo|ARM RelWithDebInfo|x64 = RelWithDebInfo|x64 RelWithDebInfo|x86 = RelWithDebInfo|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Debug|Any CPU.ActiveCfg = Debug|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Debug|ARM.ActiveCfg = Debug|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Debug|x64.ActiveCfg = Debug|x64 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Debug|x64.Build.0 = Debug|x64 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Debug|x86.ActiveCfg = Debug|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Debug|x86.Build.0 = Debug|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Release|Any CPU.ActiveCfg = Release|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Release|ARM.ActiveCfg = Release|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Release|x64.ActiveCfg = Release|x64 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Release|x64.Build.0 = Release|x64 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Release|x86.ActiveCfg = Release|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.Release|x86.Build.0 = Release|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {9FE9234B-373A-4D5A-AD6B-FB0B593312DD}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Debug|Any CPU.ActiveCfg = Debug|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Debug|ARM.ActiveCfg = Debug|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Debug|x64.ActiveCfg = Debug|x64 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Debug|x64.Build.0 = Debug|x64 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Debug|x86.ActiveCfg = Debug|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Debug|x86.Build.0 = Debug|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Release|Any CPU.ActiveCfg = Release|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Release|ARM.ActiveCfg = Release|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Release|x64.ActiveCfg = Release|x64 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Release|x64.Build.0 = Release|x64 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Release|x86.ActiveCfg = Release|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.Release|x86.Build.0 = Release|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {4BFB7231-077A-4671-BD21-D3ADE3EA36E7}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Debug|Any CPU.ActiveCfg = Debug|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Debug|ARM.ActiveCfg = Debug|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Debug|x64.ActiveCfg = Debug|x64 {98BB426F-6FB5-4754-81BC-BB481900E135}.Debug|x64.Build.0 = Debug|x64 {98BB426F-6FB5-4754-81BC-BB481900E135}.Debug|x86.ActiveCfg = Debug|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Debug|x86.Build.0 = Debug|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Release|Any CPU.ActiveCfg = Release|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Release|ARM.ActiveCfg = Release|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Release|x64.ActiveCfg = Release|x64 {98BB426F-6FB5-4754-81BC-BB481900E135}.Release|x64.Build.0 = Release|x64 {98BB426F-6FB5-4754-81BC-BB481900E135}.Release|x86.ActiveCfg = Release|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.Release|x86.Build.0 = Release|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {98BB426F-6FB5-4754-81BC-BB481900E135}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {98BB426F-6FB5-4754-81BC-BB481900E135}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {98BB426F-6FB5-4754-81BC-BB481900E135}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|Any CPU.ActiveCfg = Debug|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|ARM.ActiveCfg = Debug|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|ARM.Build.0 = Debug|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x64.ActiveCfg = Debug|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x64.Build.0 = Debug|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x86.ActiveCfg = Debug|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x86.Build.0 = Debug|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|Any CPU.ActiveCfg = Release|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|ARM.ActiveCfg = Release|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|ARM.Build.0 = Release|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x64.ActiveCfg = Release|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x64.Build.0 = Release|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x86.ActiveCfg = Release|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x86.Build.0 = Release|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|ARM.Build.0 = RelWithDebInfo|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Debug|Any CPU.ActiveCfg = Debug|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Debug|ARM.ActiveCfg = Debug|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Debug|x64.ActiveCfg = Debug|x64 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Debug|x64.Build.0 = Debug|x64 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Debug|x86.ActiveCfg = Debug|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Debug|x86.Build.0 = Debug|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Release|Any CPU.ActiveCfg = Release|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Release|ARM.ActiveCfg = Release|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Release|x64.ActiveCfg = Release|x64 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Release|x64.Build.0 = Release|x64 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Release|x86.ActiveCfg = Release|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.Release|x86.Build.0 = Release|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {A050F015-87E2-498F-866A-2E5AF65AF7AC}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|Any CPU.ActiveCfg = Debug|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|ARM.ActiveCfg = Debug|ARM {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|ARM.Build.0 = Debug|ARM {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x64.ActiveCfg = Debug|x64 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x64.Build.0 = Debug|x64 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x86.ActiveCfg = Debug|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x86.Build.0 = Debug|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|Any CPU.ActiveCfg = Release|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|ARM.ActiveCfg = Release|ARM {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|ARM.Build.0 = Release|ARM {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x64.ActiveCfg = Release|x64 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x64.Build.0 = Release|x64 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x86.ActiveCfg = Release|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x86.Build.0 = Release|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|ARM {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|ARM.Build.0 = RelWithDebInfo|ARM {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {25EB67BE-468A-4AA5-910F-07EFD58C5516}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Debug|Any CPU.ActiveCfg = Debug|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Debug|ARM.ActiveCfg = Debug|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Debug|x64.ActiveCfg = Debug|x64 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Debug|x64.Build.0 = Debug|x64 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Debug|x86.ActiveCfg = Debug|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Debug|x86.Build.0 = Debug|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Release|Any CPU.ActiveCfg = Release|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Release|ARM.ActiveCfg = Release|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Release|x64.ActiveCfg = Release|x64 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Release|x64.Build.0 = Release|x64 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Release|x86.ActiveCfg = Release|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.Release|x86.Build.0 = Release|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {C679466F-9D35-4AFC-B9AE-F9FB5448FB99}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Debug|Any CPU.ActiveCfg = Debug|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Debug|ARM.ActiveCfg = Debug|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Debug|x64.ActiveCfg = Debug|x64 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Debug|x64.Build.0 = Debug|x64 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Debug|x86.ActiveCfg = Debug|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Debug|x86.Build.0 = Debug|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Release|Any CPU.ActiveCfg = Release|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Release|ARM.ActiveCfg = Release|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Release|x64.ActiveCfg = Release|x64 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Release|x64.Build.0 = Release|x64 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Release|x86.ActiveCfg = Release|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.Release|x86.Build.0 = Release|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {2A61ED54-2B66-4B9B-99FA-299DD0EF57CD}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Debug|Any CPU.ActiveCfg = Debug|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Debug|ARM.ActiveCfg = Debug|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Debug|x64.ActiveCfg = Debug|x64 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Debug|x64.Build.0 = Debug|x64 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Debug|x86.ActiveCfg = Debug|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Debug|x86.Build.0 = Debug|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Release|Any CPU.ActiveCfg = Release|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Release|ARM.ActiveCfg = Release|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Release|x64.ActiveCfg = Release|x64 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Release|x64.Build.0 = Release|x64 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Release|x86.ActiveCfg = Release|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.Release|x86.Build.0 = Release|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {4358ED90-CCA1-47A8-8D68-A260F212931E}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {4358ED90-CCA1-47A8-8D68-A260F212931E}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {4358ED90-CCA1-47A8-8D68-A260F212931E}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.Debug|Any CPU.ActiveCfg = Debug|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.Debug|ARM.ActiveCfg = Debug|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.Debug|x64.ActiveCfg = Debug|x64 {39683523-C864-4D47-8350-33FC3EC0F00F}.Debug|x86.ActiveCfg = Debug|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.Release|Any CPU.ActiveCfg = Release|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.Release|ARM.ActiveCfg = Release|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.Release|x64.ActiveCfg = Release|x64 {39683523-C864-4D47-8350-33FC3EC0F00F}.Release|x86.ActiveCfg = Release|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {39683523-C864-4D47-8350-33FC3EC0F00F}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {39683523-C864-4D47-8350-33FC3EC0F00F}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Debug|ARM.ActiveCfg = Debug|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Debug|x64.ActiveCfg = Debug|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Debug|x86.ActiveCfg = Debug|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Release|Any CPU.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Release|ARM.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Release|x64.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Release|x86.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.RelWithDebInfo|Any CPU.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.RelWithDebInfo|ARM.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU {E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.RelWithDebInfo|x86.ActiveCfg = Release|Any CPU {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Debug|Any CPU.ActiveCfg = Debug|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Debug|ARM.ActiveCfg = Debug|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Debug|x64.ActiveCfg = Debug|x64 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Debug|x64.Build.0 = Debug|x64 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Debug|x86.ActiveCfg = Debug|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Debug|x86.Build.0 = Debug|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Release|Any CPU.ActiveCfg = Release|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Release|ARM.ActiveCfg = Release|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Release|x64.ActiveCfg = Release|x64 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Release|x64.Build.0 = Release|x64 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Release|x86.ActiveCfg = Release|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.Release|x86.Build.0 = Release|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Debug|Any CPU.ActiveCfg = Debug|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Debug|ARM.ActiveCfg = Debug|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Debug|x64.ActiveCfg = Debug|x64 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Debug|x64.Build.0 = Debug|x64 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Debug|x86.ActiveCfg = Debug|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Debug|x86.Build.0 = Debug|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Release|Any CPU.ActiveCfg = Release|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Release|ARM.ActiveCfg = Release|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Release|x64.ActiveCfg = Release|x64 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Release|x64.Build.0 = Release|x64 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Release|x86.ActiveCfg = Release|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.Release|x86.Build.0 = Release|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {E512EB59-4EAB-49D1-9174-0CAF1B40CED0}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Debug|Any CPU.ActiveCfg = Debug|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Debug|ARM.ActiveCfg = Debug|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Debug|x64.ActiveCfg = Debug|x64 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Debug|x64.Build.0 = Debug|x64 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Debug|x86.ActiveCfg = Debug|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Debug|x86.Build.0 = Debug|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Release|Any CPU.ActiveCfg = Release|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Release|ARM.ActiveCfg = Release|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Release|x64.ActiveCfg = Release|x64 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Release|x64.Build.0 = Release|x64 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Release|x86.ActiveCfg = Release|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.Release|x86.Build.0 = Release|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.RelWithDebInfo|Any CPU.ActiveCfg = RelWithDebInfo|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.RelWithDebInfo|ARM.ActiveCfg = RelWithDebInfo|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64 {99CBF376-5EBA-4164-A657-E7D708C9D685}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64 {99CBF376-5EBA-4164-A657-E7D708C9D685}.RelWithDebInfo|x86.ActiveCfg = RelWithDebInfo|Win32 {99CBF376-5EBA-4164-A657-E7D708C9D685}.RelWithDebInfo|x86.Build.0 = RelWithDebInfo|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {AA26EB02-C5EF-4DA2-B3D9-B2DAD8F1E43F} EndGlobalSection EndGlobal
AirSim/AirSim.sln/0
{ "file_path": "AirSim/AirSim.sln", "repo_id": "AirSim", "token_count": 12463 }
19
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <iostream> #include <iomanip> #include "common/Common.hpp" #include "common/common_utils/ProsumerQueue.hpp" #include "common/common_utils/FileSystem.hpp" #include "common/ClockFactory.hpp" #include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp" #include "vehicles/multirotor/api/MultirotorApiBase.hpp" #include "RandomPointPoseGenerator.hpp" STRICT_MODE_OFF #ifndef RPCLIB_MSGPACK #define RPCLIB_MSGPACK clmdep_msgpack #endif // !RPCLIB_MSGPACK #include "rpc/rpc_error.h" STRICT_MODE_ON class StereoImageGenerator { public: StereoImageGenerator(std::string storage_dir) : storage_dir_(storage_dir) { FileSystem::ensureFolder(storage_dir); } int generate(int num_samples) { msr::airlib::MultirotorRpcLibClient client; client.confirmConnection(); msr::airlib::ClockBase* clock = msr::airlib::ClockFactory::get(); RandomPointPoseGenerator pose_generator(static_cast<int>(clock->nowNanos())); std::fstream file_list(FileSystem::combine(storage_dir_, "files_list.txt"), std::ios::out | std::ios::in | std::ios_base::app); int sample = getImageCount(file_list); common_utils::ProsumerQueue<ImagesResult> results; std::thread result_process_thread(processImages, &results); try { while (sample < num_samples) { //const auto& collision_info = client.getCollisionInfo(); //if (collision_info.has_collided) { // pose_generator.next(); // client.simSetPose(pose_generator.position, pose_generator.orientation); // std::cout << "Collision at " << VectorMath::toString(collision_info.position) // << "Moving to next pose: " << VectorMath::toString(pose_generator.position) // << std::endl; // continue; //} ++sample; auto start_nanos = clock->nowNanos(); std::vector<ImageRequest> request = { ImageRequest("0", ImageType::Scene), ImageRequest("1", ImageType::Scene), ImageRequest("1", ImageType::DisparityNormalized, true) }; const std::vector<ImageResponse>& response = client.simGetImages(request); if (response.size() != 3) { std::cout << "Images were not received!" << std::endl; start_nanos = clock->nowNanos(); continue; } ImagesResult result; result.file_list = &file_list; result.response = response; result.sample = sample; result.render_time = clock->elapsedSince(start_nanos); ; result.storage_dir_ = storage_dir_; result.position = pose_generator.position; result.orientation = pose_generator.orientation; results.push(result); pose_generator.next(); client.simSetVehiclePose(Pose(pose_generator.position, pose_generator.orientation), true); } } catch (rpc::timeout& t) { // will display a message like // rpc::timeout: Timeout of 50ms while calling RPC function 'sleep' std::cout << t.what() << std::endl; } results.setIsDone(true); result_process_thread.join(); return 0; } private: typedef common_utils::FileSystem FileSystem; typedef common_utils::Utils Utils; typedef msr::airlib::VectorMath VectorMath; typedef common_utils::RandomGeneratorF RandomGeneratorF; typedef msr::airlib::Vector3r Vector3r; typedef msr::airlib::Quaternionr Quaternionr; typedef msr::airlib::Pose Pose; typedef msr::airlib::ImageCaptureBase::ImageRequest ImageRequest; typedef msr::airlib::ImageCaptureBase::ImageResponse ImageResponse; typedef msr::airlib::ImageCaptureBase::ImageType ImageType; std::string storage_dir_; bool spawn_ue4 = false; private: struct ImagesResult { std::vector<ImageResponse> response; msr::airlib::TTimeDelta render_time; std::string storage_dir_; std::fstream* file_list; int sample; Vector3r position; Quaternionr orientation; }; static int getImageCount(std::fstream& file_list) { int sample = 0; std::string line; while (std::getline(file_list, line)) ++sample; if (file_list.eof()) file_list.clear(); //otherwise we can't do any further I/O else if (file_list.bad()) { throw std::runtime_error("Error occurred while reading files_list.txt"); } return sample; } static void processImages(common_utils::ProsumerQueue<ImagesResult>* results) { while (!results->getIsDone()) { msr::airlib::ClockBase* clock = msr::airlib::ClockFactory::get(); ImagesResult result; if (!results->tryPop(result)) { clock->sleep_for(1); continue; } auto process_time = clock->nowNanos(); std::string left_file_name = Utils::stringf("left_%06d.png", result.sample); std::string right_file_name = Utils::stringf("right_%06d.png", result.sample); std::string disparity_file_name = Utils::stringf("disparity_%06d.pfm", result.sample); saveImageToFile(result.response.at(0).image_data_uint8, FileSystem::combine(result.storage_dir_, right_file_name)); saveImageToFile(result.response.at(1).image_data_uint8, FileSystem::combine(result.storage_dir_, left_file_name)); std::vector<float> disparity_data = result.response.at(2).image_data_float; //writeFilePFM(depth_data, response.at(2).width, response.at(2).height, // FileSystem::combine(storage_dir_, Utils::stringf("depth_%06d.pfm", i))); //below is not needed because we get disparity directly //convertToPlanDepth(depth_data, result.response.at(2).width, result.response.at(2).height); //float f = result.response.at(2).width / 2.0f - 1; //convertToDisparity(depth_data, result.response.at(2).width, result.response.at(2).height, f, 25 / 100.0f); denormalizeDisparity(disparity_data, result.response.at(2).width); Utils::writePFMfile(disparity_data.data(), result.response.at(2).width, result.response.at(2).height, FileSystem::combine(result.storage_dir_, disparity_file_name)); (*result.file_list) << left_file_name << "," << right_file_name << "," << disparity_file_name << std::endl; std::cout << "Image #" << result.sample << " pos:" << VectorMath::toString(result.position) << " ori:" << VectorMath::toString(result.orientation) << " render time " << result.render_time * 1E3f << "ms" << " process time " << clock->elapsedSince(process_time) * 1E3f << " ms" << std::endl; } } static void saveImageToFile(const std::vector<uint8_t>& image_data, const std::string& file_name) { std::ofstream file(file_name, std::ios::binary); file.write((char*)image_data.data(), image_data.size()); file.close(); } static void convertToPlanDepth(std::vector<float>& image_data, int width, int height, float f = 320) { float center_i = width / 2.0f - 1; float center_j = height / 2.0f - 1; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { float dist = std::sqrt((i - center_i) * (i - center_i) + (j - center_j) * (j - center_j)); float denom = (dist / f); denom *= denom; denom = std::sqrt(1 + denom); image_data[j * width + i] /= denom; } } } static void convertToDisparity(std::vector<float>& image_data, int width, int height, float f = 320, float baseline_meters = 1) { for (int i = 0; i < image_data.size(); ++i) { image_data[i] = f * baseline_meters * (1.0f / image_data[i]); } } static void denormalizeDisparity(std::vector<float>& image_data, int width) { for (int i = 0; i < image_data.size(); ++i) { image_data[i] = image_data[i] * width; } } };
AirSim/Examples/DataCollection/StereoImageGenerator.hpp/0
{ "file_path": "AirSim/Examples/DataCollection/StereoImageGenerator.hpp", "repo_id": "AirSim", "token_count": 4065 }
20
# Welcome to GazeboDrone This page has moved [here](https://github.com/microsoft/AirSim/blob/main/docs/gazebo_drone.md).
AirSim/GazeboDrone/README.md/0
{ "file_path": "AirSim/GazeboDrone/README.md", "repo_id": "AirSim", "token_count": 45 }
21
using LogViewer.Gestures; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Navigation; using System.Windows.Shapes; namespace LogViewer.Controls { /// <summary> /// Interaction logic for MeshViewer.xaml /// </summary> public partial class MeshViewer : UserControl { ModelVisual3D model; RotateGesture3D gesture; Rect3D modelBounds; double modelRadius; Point3D lookAt; public MeshViewer() { InitializeComponent(); gesture = new RotateGesture3D(this); gesture.Changed += OnGestureChanged; this.Loaded += OnMeshViewerLoaded; } public Quaternion ModelAttitude { get { return (Quaternion)GetValue(ModelAttitudeProperty); } set { SetValue(ModelAttitudeProperty, value); } } // Using a DependencyProperty as the backing store for ModelAttitude. This enables animation, styling, binding, etc... public static readonly DependencyProperty ModelAttitudeProperty = DependencyProperty.Register("ModelAttitude", typeof(Quaternion), typeof(MeshViewer), new PropertyMetadata(Quaternion.Identity, new PropertyChangedCallback(OnModelAttitudeChanged))); private static void OnModelAttitudeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((MeshViewer)d).OnModelAttitudeChanged(); } private void OnModelAttitudeChanged() { Update(); } public Vector3D CameraPosition { get { return (Vector3D)GetValue(CameraPositionProperty); } set { SetValue(CameraPositionProperty, value); } } // Using a DependencyProperty as the backing store for CameraPosition. This enables animation, styling, binding, etc... public static readonly DependencyProperty CameraPositionProperty = DependencyProperty.Register("CameraPosition", typeof(Vector3D), typeof(MeshViewer), new PropertyMetadata(new Vector3D(0,0,0), new PropertyChangedCallback(OnCameraPositionChanged))); private static void OnCameraPositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((MeshViewer)d).OnCameraPositionChanged(); } private void OnCameraPositionChanged() { Update(); } private void OnMeshViewerLoaded(object sender, RoutedEventArgs e) { LoadModel(); Update(); } void Update() { PerspectiveCamera camera = (PerspectiveCamera)MainViewPort.Camera; Vector3D position = (Vector3D)CameraPosition; camera.Position = (Point3D)position; if (this.model != null) { this.modelBounds = this.model.Content.Bounds; double radius = Math.Max(modelBounds.Size.X, Math.Max(modelBounds.Size.Y, modelBounds.Size.Z)); this.modelRadius = radius; Point3D center = new Point3D(modelBounds.X + (modelBounds.SizeX / 2), modelBounds.Y + (modelBounds.SizeY / 2), modelBounds.Z + (modelBounds.SizeZ / 2)); this.lookAt = center; if (camera.Position.X == 0 && camera.Position.Y == 0 && camera.Position.Z == 0) { position.X = this.modelBounds.X + this.modelBounds.SizeX; position.Y = this.modelBounds.Y + (this.modelBounds.SizeY / 2); position.Z = this.modelBounds.Z + this.modelBounds.SizeZ; position.Normalize(); position *= (radius * 3); camera.Position = (Point3D)position; } camera.LookDirection = this.lookAt - camera.Position; camera.FarPlaneDistance = radius * 10; Quaternion rotation = this.ModelAttitude * gesture.Rotation; QuaternionRotation3D quaternionRotation = new QuaternionRotation3D(rotation); RotateTransform3D myRotateTransform = new RotateTransform3D(quaternionRotation); model.Transform = myRotateTransform; xAxis.Transform = myRotateTransform; yAxis.Transform = myRotateTransform; } } private void OnGestureChanged(object sender, EventArgs e) { this.Dispatcher.Invoke(new Action(() => { UpdateRotation(); })); } static DiffuseMaterial material = new DiffuseMaterial(new LinearGradientBrush(Colors.BlueViolet, Colors.Violet, 45)); static DiffuseMaterial backMaterial = new DiffuseMaterial(new LinearGradientBrush(Colors.DarkGreen, Colors.Green, 45)); private void LoadModel() { MeshGeometry3D mymesh = new MeshGeometry3D(); // this resolves problems with handling of '.' versus ',' as decimal separator in the the loaded mesh. CultureInfo usCulture = new CultureInfo("en-US"); using (var stream = this.GetType().Assembly.GetManifestResourceStream("LogViewer.Assets.Mesh.txt")) { using (var reader = new StreamReader(stream)) { string line = null; do { line = reader.ReadLine(); if (line != null) { int i = line.IndexOf(','); string a = line.Substring(0, i); int j = line.IndexOf(',', i + 1); string b = line.Substring(i + 1, j - i - 1); string c = line.Substring(j + 1); double x = double.Parse(a, usCulture); double y = double.Parse(b, usCulture); double z = double.Parse(c, usCulture); mymesh.Positions.Add(new Point3D(x, y, z)); } } while (line != null); } } GeometryModel3D geometry = new GeometryModel3D(mymesh, material); geometry.BackMaterial = backMaterial; Model3DGroup group = new Model3DGroup(); group.Children.Add(geometry); this.model = new ModelVisual3D(); this.model.Content = group; this.MainViewPort.Children.Add(this.model); } private void UpdateRotation() { Quaternion rotation = this.ModelAttitude * gesture.Rotation; QuaternionRotation3D quaternionRotation = new QuaternionRotation3D(rotation); RotateTransform3D myRotateTransform = new RotateTransform3D(quaternionRotation); model.Transform = myRotateTransform; xAxis.Transform = myRotateTransform; yAxis.Transform = myRotateTransform; PerspectiveCamera camera = (PerspectiveCamera)MainViewPort.Camera; Vector3D position = (Vector3D)camera.Position; Vector3D lookDirection = this.lookAt - camera.Position; double length = lookDirection.Length; length += (gesture.Zoom * this.modelRadius / 10); // 10 clicks to travel size of model if (length <= 0.1) { length = 0.1; } lookDirection.Normalize(); lookDirection *= length; gesture.Zoom = 0; camera.Position = this.lookAt - lookDirection; } } }
AirSim/LogViewer/LogViewer/Controls/MeshViewer.xaml.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Controls/MeshViewer.xaml.cs", "repo_id": "AirSim", "token_count": 3746 }
22
using LogViewer.Utilities; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using static Microsoft.Networking.Mavlink.MAVLink; using System.Threading; namespace LogViewer.Model { class rows { public object[] data; }; class JSonDataLog : IDataLog { private DateTime startTime; private string file; private ProgressUtility progress; private Stream fileStream; public DateTime StartTime { get { throw new NotImplementedException(); } } public TimeSpan Duration { get { throw new NotImplementedException(); } } public LogItemSchema Schema { get { throw new NotImplementedException(); } } public async Task Load(string file, ProgressUtility progress) { this.file = file; this.progress = progress; string ext = System.IO.Path.GetExtension(file).ToLowerInvariant(); bool hasStartTime = false; this.startTime = DateTime.MinValue; //DateTime? gpsStartTime = null; //ulong gpsAbsoluteOffset = 0; //ulong logStartTime = 0; List<LogEntry> rows = new List<LogEntry>(); rows r = new Model.rows(); r.data = new object[1] { new mavlink_param_request_read_t() { param_id = new byte[16] } }; string result = JsonConvert.SerializeObject(r); Debug.WriteLine(result); await Task.Run(() => { using (Stream fileStream = File.OpenRead(file)) { this.fileStream = fileStream; using (TextReader textReader = new StreamReader(fileStream)) { JsonTextReader reader = new JsonTextReader(textReader); while (reader.Read()) { ReportProgress(); //if (reader.TokenType == JsonToken.StartObject) //{ // ReadObject(reader); //} if (reader.Value != null) { //Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); } else { // Console.WriteLine("Token: {0}", reader.TokenType); } } if (!hasStartTime) { hasStartTime = true; } //if (!gpsStartTime.HasValue && row.Name == "GPS") //{ // ulong time = row.GetField<ulong>("GPSTime"); // if (time > 0) // { // // ok, we got a real GPS time // gpsStartTime = GetTime(time); // // backtrack and fix up initial rows. // if (hasStartTime) // { // // compute offset from PX4 boot time (which is the log.CurrentTime) and the absolute GPS real time clock // // so we can add this offset to PX4 log.CurrentTime so all our times from here on out are in real time. // gpsStartTime = gpsStartTime.Value.AddMilliseconds((double)logStartTime - (double)log.CurrentTime); // } // ulong linuxEpochMicroseconds = ((ulong)(gpsStartTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds * 1000); // gpsAbsoluteOffset = linuxEpochMicroseconds - logStartTime; // this.startTime = gpsStartTime.Value; // // and fix existing log entries // foreach (LogEntry e in rows) // { // // add GPS absolute offset to the timestamp. // e.Timestamp += gpsAbsoluteOffset; // } // hasStartTime = true; // } } //if (gpsStartTime.HasValue) //{ // // add GPS absolute offset to the timestamp. // row.Timestamp += gpsAbsoluteOffset; //} //rows.Add(row); //if (row.Format.Name == "PARM") //{ // string name = row.GetField<string>("Name"); // float value = row.GetField<float>("Value"); // Debug.WriteLine("{0}={1}", name, value); //} } //if (log.CurrentTime != 0) //{ // DateTime endTime = GetTime(log.CurrentTime + gpsAbsoluteOffset); // this.duration = endTime - startTime; // Debug.WriteLine("StartTime={0}, EndTime={1}, Duration={2}", startTime.ToString(), endTime.ToString(), duration.ToString()); //} //CreateSchema(log); }); //this.data = rows; } private void ReportProgress() { progress.ShowProgress(0, fileStream.Length, fileStream.Position); } private void ReadObject(JsonTextReader reader) { string propertyName = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { reader.Read(); if (reader.TokenType == JsonToken.PropertyName) { propertyName = reader.ReadAsString(); } } } public IEnumerable<DataValue> GetDataValues(LogItemSchema schema, DateTime startTime, TimeSpan duration) { throw new NotImplementedException(); } public IEnumerable<DataValue> LiveQuery(LogItemSchema schema, CancellationToken token) { throw new NotImplementedException(); } public IEnumerable<LogEntry> GetRows(string typeName, DateTime startTime, TimeSpan duration) { throw new NotImplementedException(); } public IEnumerable<Flight> GetFlights() { throw new NotImplementedException(); } public DateTime GetTime(ulong timeMs) { throw new NotImplementedException(); } } }
AirSim/LogViewer/LogViewer/Model/JSonDataLog.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Model/JSonDataLog.cs", "repo_id": "AirSim", "token_count": 4409 }
23
using System; using System.Windows.Media; namespace LogViewer.Utilities { public class HlsColor { private byte red = 0; private byte green = 0; private byte blue = 0; private float hue = 0; private float luminance = 0; private float saturation = 0; /// <summary> /// Constructs an instance of the class from the specified /// System.Drawing.Color /// </summary> /// <param name="c">The System.Drawing.Color to use to initialize the /// class</param> public HlsColor(Color c) { red = c.R; green = c.G; blue = c.B; ToHLS(); } /// <summary> /// Constructs an instance of the class with the specified hue, luminance /// and saturation values. /// </summary> /// <param name="hue">The Hue (between 0.0 and 360.0)</param> /// <param name="luminance">The Luminance (between 0.0 and 1.0)</param> /// <param name="saturation">The Saturation (between 0.0 and 1.0)</param> /// <exception cref="ArgumentOutOfRangeException">If any of the H,L,S /// values are out of the acceptable range (0.0-360.0 for Hue and 0.0-1.0 /// for Luminance and Saturation)</exception> public HlsColor(float hue, float luminance, float saturation) { this.Hue = hue; this.Luminance = luminance; this.Saturation = saturation; ToRGB(); } /// <summary> /// Constructs an instance of the class with the specified red, green and /// blue values. /// </summary> /// <param name="red">The red component.</param> /// <param name="green">The green component.</param> /// <param name="blue">The blue component.</param> public HlsColor(byte red, byte green, byte blue) { this.red = red; this.green = green; this.blue = blue; ToHLS(); } /// <summary> /// Constructs an instance of the class using the settings of another /// instance. /// </summary> /// <param name="HlsColor">The instance to clone.</param> public HlsColor(HlsColor hls) { this.red = hls.red; this.blue = hls.blue; this.green = hls.green; this.luminance = hls.luminance; this.hue = hls.hue; this.saturation = hls.saturation; } /// <summary> /// Constructs a new instance of the class initialised to black. /// </summary> public HlsColor() { } public byte Red { get { return red; } } public byte Green { get { return green; } } public byte Blue { get { return blue; } } /// <summary> /// Gets or sets the Luminance (0.0 to 1.0) of the colour. /// </summary> /// <exception cref="ArgumentOutOfRangeException">If the value is out of /// the acceptable range for luminance (0.0 to 1.0)</exception> public float Luminance { get { return luminance; } set { if ((value < 0.0f) || (value > 1.0f)) { throw new ArgumentOutOfRangeException("value", "Luminance must be between 0.0 and 1.0"); } luminance = value; ToRGB(); } } /// <summary> /// Gets or sets the Hue (0.0 to 360.0) of the color. /// </summary> /// <exception cref="ArgumentOutOfRangeException">If the value is out of /// the acceptable range for hue (0.0 to 360.0)</exception> public float Hue { get { return hue; } set { if ((value < 0.0f) || (value > 360.0f)) { throw new ArgumentOutOfRangeException("value", "Hue must be between 0.0 and 360.0"); } hue = value; ToRGB(); } } /// <summary> /// Gets or sets the Saturation (0.0 to 1.0) of the color. /// </summary> /// <exception cref="ArgumentOutOfRangeException">If the value is out of /// the acceptable range for saturation (0.0 to 1.0)</exception> public float Saturation { get { return saturation; } set { if ((value < 0.0f) || (value > 1.0f)) { throw new ArgumentOutOfRangeException("value", "Saturation must be between 0.0 and 1.0"); } saturation = value; ToRGB(); } } /// <summary> /// Gets or sets the Color as a System.Drawing.Color instance /// </summary> public Color Color { get { Color c = Color.FromRgb(red, green, blue); return c; } set { red = value.R; green = value.G; blue = value.B; ToHLS(); } } /// <summary> /// Lightens the colour by the specified amount by modifying /// the luminance (for example, 0.2 would lighten the colour by 20%) /// </summary> public void Lighten(float percent) { luminance *= (1.0f + percent); if (luminance > 1.0f) { luminance = 1.0f; } ToRGB(); } /// <summary> /// Darkens the colour by the specified amount by modifying /// the luminance (for example, 0.2 would darken the colour by 20%) /// </summary> public void Darken(float percent) { luminance *= (1 - percent); ToRGB(); } private void ToHLS() { byte minval = Math.Min(red, Math.Min(green, blue)); byte maxval = Math.Max(red, Math.Max(green, blue)); float mdiff = (float)(maxval - minval); float msum = (float)(maxval + minval); luminance = msum / 510.0f; if (maxval == minval) { saturation = 0.0f; hue = 0.0f; } else { float rnorm = (maxval - red) / mdiff; float gnorm = (maxval - green) / mdiff; float bnorm = (maxval - blue) / mdiff; saturation = (luminance <= 0.5f) ? (mdiff / msum) : (mdiff / (510.0f - msum)); if (red == maxval) { hue = 60.0f * (6.0f + bnorm - gnorm); } if (green == maxval) { hue = 60.0f * (2.0f + rnorm - bnorm); } if (blue == maxval) { hue = 60.0f * (4.0f + gnorm - rnorm); } if (hue > 360.0f) { hue = hue - 360.0f; } } } private void ToRGB() { if (saturation == 0.0) { red = (byte)(luminance * 255.0F); green = red; blue = red; } else { float rm1; float rm2; if (luminance <= 0.5f) { rm2 = luminance + luminance * saturation; } else { rm2 = luminance + saturation - luminance * saturation; } rm1 = 2.0f * luminance - rm2; red = ToRGB1(rm1, rm2, hue + 120.0f); green = ToRGB1(rm1, rm2, hue); blue = ToRGB1(rm1, rm2, hue - 120.0f); } } static private byte ToRGB1(float rm1, float rm2, float rh) { if (rh > 360.0f) { rh -= 360.0f; } else if (rh < 0.0f) { rh += 360.0f; } if (rh < 60.0f) { rm1 = rm1 + (rm2 - rm1) * rh / 60.0f; } else if (rh < 180.0f) { rm1 = rm2; } else if (rh < 240.0f) { rm1 = rm1 + (rm2 - rm1) * (240.0f - rh) / 60.0f; } return (byte)(rm1 * 255); } public static Color GetRandomColor() { return new HlsColor((float)(colorRandomizer.NextDouble() * 360), 0.8f, 0.95f).Color; } static Random colorRandomizer = new Random(); } }
AirSim/LogViewer/LogViewer/Utilities/HlsColor.cs/0
{ "file_path": "AirSim/LogViewer/LogViewer/Utilities/HlsColor.cs", "repo_id": "AirSim", "token_count": 5008 }
24
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26430.15 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MavLinkMoCap", "MavlinkMoCap.vcxproj", "{9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MavLinkCom", "..\MavLinkCom.vcxproj", "{8510C7A4-BF63-41D2-94F6-D8731D137A5A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM = Debug|ARM Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|ARM = Release|ARM Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Debug|ARM.ActiveCfg = Debug|Win32 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Debug|x64.ActiveCfg = Debug|x64 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Debug|x64.Build.0 = Debug|x64 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Debug|x86.ActiveCfg = Debug|Win32 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Debug|x86.Build.0 = Debug|Win32 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Release|ARM.ActiveCfg = Release|Win32 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Release|x64.ActiveCfg = Release|x64 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Release|x64.Build.0 = Release|x64 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Release|x86.ActiveCfg = Release|Win32 {9E9D74CE-235C-4A96-BFED-A3E9AC8D9039}.Release|x86.Build.0 = Release|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|ARM.ActiveCfg = Debug|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|ARM.Build.0 = Debug|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x64.ActiveCfg = Debug|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x64.Build.0 = Debug|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x86.ActiveCfg = Debug|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x86.Build.0 = Debug|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|ARM.ActiveCfg = Release|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|ARM.Build.0 = Release|ARM {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x64.ActiveCfg = Release|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x64.Build.0 = Release|x64 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x86.ActiveCfg = Release|Win32 {8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
AirSim/MavLinkCom/MavLinkMoCap/MavLinkMoCap.sln/0
{ "file_path": "AirSim/MavLinkCom/MavLinkMoCap/MavLinkMoCap.sln", "repo_id": "AirSim", "token_count": 1310 }
25
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "UnitTests.h" #include <thread> #include <chrono> #include "Utils.hpp" #include "FileSystem.hpp" #include "MavLinkVehicle.hpp" #include "MavLinkMessages.hpp" #include "MavLinkConnection.hpp" #include "MavLinkVideoStream.hpp" #include "MavLinkTcpServer.hpp" #include "MavLinkFtpClient.hpp" #include "Semaphore.hpp" STRICT_MODE_OFF #include "json.hpp" STRICT_MODE_ON #include <iostream> using namespace mavlink_utils; using namespace mavlinkcom; extern std::string replaceAll(std::string s, char toFind, char toReplace); void UnitTests::RunAll(std::string comPort, int boardRate) { com_port_ = comPort; baud_rate_ = boardRate; if (comPort == "") { throw std::runtime_error("unit tests need a serial connection to Pixhawk, please specify -serial argument"); } RunTest("UdpPingTest", [=] { UdpPingTest(); }); RunTest("TcpPingTest", [=] { TcpPingTest(); }); RunTest("SendImageTest", [=] { SendImageTest(); }); RunTest("SerialPx4Test", [=] { SerialPx4Test(); }); RunTest("FtpTest", [=] { FtpTest(); }); RunTest("JSonLogTest", [=] { JSonLogTest(); }); } void UnitTests::RunTest(const std::string& name, TestHandler handler) { printf("%s: start\n", name.c_str()); try { handler(); printf("------------- %s test passed --------------------\n", name.c_str()); } catch (const std::exception& e) { printf("------------- %s test failed: %s --------------- \n", name.c_str(), e.what()); } } void UnitTests::UdpPingTest() { auto localConnection = MavLinkConnection::connectLocalUdp("jMavSim", "127.0.0.1", 14588); Semaphore received; auto id = localConnection->subscribe([&](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg) { printf(" Received message %d\n", msg.msgid); received.post(); }); auto remoteConnection = MavLinkConnection::connectRemoteUdp("jMavSim", "127.0.0.1", "127.0.0.1", 14588); // send a heartbeat MavLinkHeartbeat hb; hb.autopilot = 0; hb.base_mode = 0; hb.custom_mode = 0; hb.mavlink_version = 3; hb.system_status = 1; hb.type = 1; auto node = std::make_shared<MavLinkNode>(166, 1); node->connect(remoteConnection); node->sendMessage(hb); if (!received.timed_wait(2000)) { throw std::runtime_error("heartbeat not received after 2 seconds"); } localConnection->unsubscribe(id); localConnection->close(); remoteConnection->close(); node->close(); } void UnitTests::TcpPingTest() { const int testPort = 45166; std::shared_ptr<MavLinkTcpServer> server = std::make_shared<MavLinkTcpServer>("127.0.0.1", testPort); std::future<int> future = std::async(std::launch::async, [=] { // accept one incoming connection std::shared_ptr<MavLinkConnection> con = server->acceptTcp("test"); std::shared_ptr<MavLinkNode> serverNode = std::make_shared<MavLinkNode>(1, 1); serverNode->connect(con); // send a heartbeat to the client MavLinkHeartbeat hb; hb.autopilot = 0; hb.base_mode = 0; hb.custom_mode = 0; hb.mavlink_version = 3; hb.system_status = 1; hb.type = 1; serverNode->sendMessage(hb); return 0; }); Semaphore received; auto client = MavLinkConnection::connectTcp("local", "127.0.0.1", "127.0.0.1", testPort); client->subscribe([&](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg) { printf("Received msg %d\n", msg.msgid); received.post(); }); if (!received.timed_wait(2000)) { throw std::runtime_error("heartbeat not received from server"); } client->close(); } void UnitTests::SerialPx4Test() { auto connection = MavLinkConnection::connectSerial("px4", com_port_, baud_rate_); int count = 0; Semaphore received; auto id = connection->subscribe([&](std::shared_ptr<MavLinkConnection> con, const MavLinkMessage& msg) { //printf(" Received message %d\n", static_cast<int>(msg.msgid)); count++; if (msg.msgid == 0) { received.post(); } }); if (!received.timed_wait(5000)) { throw std::runtime_error("MavLink heartbeat is not being received over serial, please make sure PX4 is plugged in and the unit test is using the right COM port."); } printf("Received %d mavlink messages over serial port\n", count); connection->unsubscribe(id); connection->close(); } class ImageServer { public: ImageServer(std::shared_ptr<MavLinkConnection> con) { stream = std::make_shared<MavLinkVideoServer>(1, 1); stream->connect(con); con->subscribe([&](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg) { MavLinkVideoServer::MavLinkVideoRequest req; if (stream->hasVideoRequest(req)) { printf(" server received request for video at %f frames every second\n", req.every_n_sec); int* image = new int[10000]; int size = sizeof(int) * 10000; for (int i = 0; i < 10000; i++) { image[i] = i; } stream->sendFrame(reinterpret_cast<uint8_t*>(image), size, 100, 100, 0, 0); delete[] image; } }); } std::shared_ptr<MavLinkVideoServer> stream; }; void UnitTests::SendImageTest() { const int testPort = 42316; std::string testAddr = "127.0.0.1"; std::shared_ptr<MavLinkTcpServer> server = std::make_shared<MavLinkTcpServer>(testAddr, testPort); std::future<int> future = std::async(std::launch::async, [=] { // this is the server code, it will accept 1 connection from a client on port 14588 // for this unit test we are expecting a request to send an image. auto con = server->acceptTcp("test"); this->server_ = new ImageServer(con); return 0; }); // add a drone connection so the mavLinkCom can use it to send requests to the above server. auto drone = MavLinkConnection::connectTcp("drone", testAddr, testAddr, testPort); MavLinkVideoClient client{ 150, 1 }; client.connect(drone); client.requestVideo(1, 1, false); MavLinkVideoClient::MavLinkVideoFrame image; int retries = 100; while (!client.readNextFrame(image) && retries-- > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } if (retries <= 0) { // hmmm throw std::runtime_error("no image received after timeout"); } else { std::vector<unsigned char> raw = image.data; int* img = reinterpret_cast<int*>(raw.data()); for (int i = 0, n = static_cast<int>(raw.size() / 4); i < n; i++) { if (img[i] != i) { throw std::runtime_error("corrupt image data received"); } } } printf(" Received image %d bytes, width %d and height %d ok\n", static_cast<int>(image.data.size()), image.width, image.height); return; } void UnitTests::VerifyFile(MavLinkFtpClient& ftp, const std::string& dir, const std::string& name, bool exists, bool isdir) { MavLinkFtpProgress progress; std::vector<MavLinkFileInfo> files; ftp.list(progress, dir, files); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp list '%s' command", progress.error, progress.message.c_str(), dir.c_str())); } bool found = false; for (auto ptr = files.begin(), end = files.end(); ptr != end; ptr++) { MavLinkFileInfo i = *ptr; if (isdir == i.is_directory && i.name == name) { found = true; } } if (!found && exists) { throw std::runtime_error(Utils::stringf("The %s '%s' not found in '%s', but it should be there", isdir ? "dir" : "file", name.c_str(), dir.c_str())); } else if (found && !exists) { throw std::runtime_error(Utils::stringf("The %s '%s' was found in '%s', but it should not have been", isdir ? "dir" : "file", name.c_str(), dir.c_str())); } } void UnitTests::FtpTest() { std::shared_ptr<MavLinkConnection> connection = MavLinkConnection::connectSerial("px4", com_port_, baud_rate_); MavLinkFtpClient ftp{ 166, 1 }; ftp.connect(connection); try { MavLinkFtpProgress progress; std::vector<MavLinkFileInfo> files; // ================ ls ftp.list(progress, "/fs/microsd", files); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp list '/fs/microsd' command - does your pixhawk have an sd card?", progress.error, progress.message.c_str())); } else { printf("Found %d files in '/fs/microsd' folder\n", static_cast<int>(files.size())); } // ================ put file auto tempPath = FileSystem::getTempFolder(); tempPath = FileSystem::combine(tempPath, "ftptest.txt"); std::ofstream stream(tempPath); const char* TestPattern = "This is line %d\n"; for (int i = 0; i < 100; i++) { std::string line = Utils::stringf("%s %i", TestPattern, i); stream << line; } stream.close(); std::string remotePath = "/fs/microsd/ftptest.txt"; std::string localPath = tempPath; #if defined(_WIN32) // I wish there was a cleaner way to do this, but I can't use tempPath.native() because on windows that is a wstring and on our linux build it is a string. replaceAll(localPath, '/', '\\'); #endif ftp.put(progress, remotePath, localPath); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp put command", progress.error, progress.message.c_str())); } else { printf("put succeeded\n"); } FileSystem::remove(tempPath); VerifyFile(ftp, "/fs/microsd", "ftptest.txt", true, false); // ================ get file ftp.get(progress, remotePath, localPath); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp get command", progress.error, progress.message.c_str())); } // verify the file contents. std::ifstream istream(tempPath); int count = 0; std::string line; std::getline(istream, line); while (line.size() > 0) { line += '\n'; std::string expected = Utils::stringf("%s %i", TestPattern, count); if (line != expected) { throw std::runtime_error(Utils::stringf("ftp local file contains unexpected contents '%s' on line %d\n", line.c_str(), count)); } count++; std::getline(istream, line); } printf("get succeeded\n"); istream.close(); // ================ remove file FileSystem::remove(tempPath); ftp.remove(progress, remotePath); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp remove command", progress.error, progress.message.c_str())); } else { printf("remove succeeded\n"); } VerifyFile(ftp, "/fs/microsd", "ftptest.txt", false, false); // ================ make directory // D:\px4\src\lovettchris\Firmware\rootfs\fs\microsd ftp.mkdir(progress, "/fs/microsd/testrmdir"); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp mkdir '/fs/microsd/testrmdir' command", progress.error, progress.message.c_str())); } VerifyFile(ftp, "/fs/microsd", "testrmdir", true, true); // ================ remove directory ftp.rmdir(progress, "/fs/microsd/testrmdir"); if (progress.error != 0) { throw std::runtime_error(Utils::stringf("unexpected error %d: '%s' from ftp rmdir '/fs/microsd/testrmdir' command", progress.error, progress.message.c_str())); } VerifyFile(ftp, "/fs/microsd", "testrmdir", false, true); } catch (...) { ftp.close(); connection->close(); connection = nullptr; throw; } ftp.close(); connection->close(); connection = nullptr; } void UnitTests::JSonLogTest() { auto connection = MavLinkConnection::connectSerial("px4", com_port_, baud_rate_); MavLinkFileLog log; auto tempPath = FileSystem::getTempFolder(); tempPath = FileSystem::combine(tempPath, "test.mavlink"); log.openForWriting(tempPath, true); int count = 0; Semaphore received; auto id = connection->subscribe([&](std::shared_ptr<MavLinkConnection> con, const MavLinkMessage& msg) { count++; log.write(msg); if (count > 50) { received.post(); } }); if (!received.timed_wait(30000)) { throw std::runtime_error("PX4 is not sending 50 messages in 30 seconds."); } connection->unsubscribe(id); connection->close(); log.close(); // Now verification nlohmann::json doc; std::ifstream s; FileSystem::openTextFile(tempPath, s); if (!s.fail()) { s >> doc; } else { throw std::runtime_error(Utils::stringf("Cannot open json file at '%s'.", tempPath.c_str())); } if (doc.count("rows") == 1) { nlohmann::json rows = doc["rows"].get<nlohmann::json>(); int found = 0; int imu = 0; if (rows.is_array()) { size_t size = rows.size(); for (size_t i = 0; i < size; i++) { auto ptr = rows[i]; if (ptr.is_object()) { if (ptr.count("name") == 1) { auto name = ptr["name"].get<std::string>(); if (name == "HIGHRES_IMU") { imu++; } found++; } } } } printf("found %d valid rows in the json file, and %d HIGHRES_IMU records\n", found, imu); } }
AirSim/MavLinkCom/MavLinkTest/UnitTests.cpp/0
{ "file_path": "AirSim/MavLinkCom/MavLinkTest/UnitTests.cpp", "repo_id": "AirSim", "token_count": 7234 }
26
#ifndef MavLinkCom_UdpSocket_hpp #define MavLinkCom_UdpSocket_hpp #include <string> #include <memory> namespace mavlinkcom_impl { class UdpSocketImpl; } namespace mavlinkcom { class UdpSocket; // This class represents a simple single-threaded Socket interface specific for Udp connections // Basic socket functions are exposed through this class UdpSocket { public: UdpSocket(); // initiate a connection on a socket int connect(const std::string& addr, int port); // bind the socket to an address int bind(const std::string& localaddr, int port); void close(); // Send message on a socket // Used when the socket is in a connected state (so that the intended recipient is known) int send(const void* pkt, size_t size); // Send message to the specified address, port int sendto(const void* buf, size_t size, const std::string& address, uint16_t port); // Receive message on socket int recv(void* pkt, size_t size, uint32_t timeout_ms); // return the IP address and port of the last received packet void last_recv_address(std::string& ip_addr, uint16_t& port); bool reuseaddress(); void set_broadcast(void); public: //needed for piml pattern ~UdpSocket(); private: std::unique_ptr<mavlinkcom_impl::UdpSocketImpl> pImpl; friend class mavlinkcom_impl::UdpSocketImpl; }; } #endif
AirSim/MavLinkCom/include/UdpSocket.hpp/0
{ "file_path": "AirSim/MavLinkCom/include/UdpSocket.hpp", "repo_id": "AirSim", "token_count": 463 }
27
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "MavLinkFtpClient.hpp" #include "impl/MavLinkFtpClientImpl.hpp" using namespace mavlinkcom; using namespace mavlinkcom_impl; MavLinkFtpClient::MavLinkFtpClient(int localSystemId, int localComponentId) : MavLinkNode(localSystemId, localComponentId) { pImpl.reset(new MavLinkFtpClientImpl(localSystemId, localComponentId)); } MavLinkFtpClient::~MavLinkFtpClient() { } bool MavLinkFtpClient::isSupported() { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); return ptr->isSupported(); } void MavLinkFtpClient::cancel() { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); ptr->cancel(); } void MavLinkFtpClient::list(MavLinkFtpProgress& progress, const std::string& remotePath, std::vector<MavLinkFileInfo>& files) { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); return ptr->list(progress, remotePath, files); } void MavLinkFtpClient::get(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath) { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); ptr->get(progress, remotePath, localPath); } void MavLinkFtpClient::put(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath) { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); ptr->put(progress, remotePath, localPath); } void MavLinkFtpClient::remove(MavLinkFtpProgress& progress, const std::string& remotePath) { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); ptr->remove(progress, remotePath); } void MavLinkFtpClient::mkdir(MavLinkFtpProgress& progress, const std::string& remotePath) { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); ptr->mkdir(progress, remotePath); } void MavLinkFtpClient::rmdir(MavLinkFtpProgress& progress, const std::string& remotePath) { auto ptr = dynamic_cast<MavLinkFtpClientImpl*>(pImpl.get()); ptr->rmdir(progress, remotePath); }
AirSim/MavLinkCom/src/MavLinkFtpClient.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/MavLinkFtpClient.cpp", "repo_id": "AirSim", "token_count": 738 }
28
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "MavLinkNodeImpl.hpp" #include "Utils.hpp" #include "MavLinkMessages.hpp" #include "Semaphore.hpp" #include "ThreadUtils.hpp" using namespace mavlink_utils; using namespace mavlinkcom_impl; const int heartbeatMilliseconds = 1000; MavLinkNodeImpl::MavLinkNodeImpl(int localSystemId, int localComponentId) { local_system_id = localSystemId; local_component_id = localComponentId; } MavLinkNodeImpl::~MavLinkNodeImpl() { close(); } // start listening to this connection void MavLinkNodeImpl::connect(std::shared_ptr<MavLinkConnection> connection) { has_cap_ = false; connection_ = connection; subscription_ = connection_->subscribe([=](std::shared_ptr<MavLinkConnection> con, const MavLinkMessage& msg) { handleMessage(con, msg); }); } // Send heartbeat to drone. You should not do this if some other node is // already doing it. void MavLinkNodeImpl::startHeartbeat() { if (!heartbeat_running_) { heartbeat_running_ = true; Utils::cleanupThread(heartbeat_thread_); heartbeat_thread_ = std::thread{ &MavLinkNodeImpl::sendHeartbeat, this }; } } void MavLinkNodeImpl::sendHeartbeat() { CurrentThread::setThreadName("MavLinkThread"); while (heartbeat_running_) { sendOneHeartbeat(); std::this_thread::sleep_for(std::chrono::milliseconds(heartbeatMilliseconds)); } } // this is called for all messages received on the connection. void MavLinkNodeImpl::handleMessage(std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg) { unused(connection); switch (msg.msgid) { case static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_HEARTBEAT): // we received a heartbeat, so let's get the capabilities. if (!req_cap_) { req_cap_ = true; MavCmdRequestAutopilotCapabilities cmd{}; cmd.param1 = 1; sendCommand(cmd); } break; case static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_AUTOPILOT_VERSION): cap_.decode(msg); has_cap_ = true; break; } // this is for the subclasses to play with. We put nothing here so we are not dependent on the // subclasses remembering to call this base implementation. } // stop listening to the connection. void MavLinkNodeImpl::close() { if (subscription_ != 0 && connection_ != nullptr) { connection_->unsubscribe(subscription_); subscription_ = 0; } if (heartbeat_running_) { heartbeat_running_ = false; if (heartbeat_thread_.joinable()) { heartbeat_thread_.join(); } } if (connection_ != nullptr) { connection_->close(); } connection_ = nullptr; } AsyncResult<MavLinkAutopilotVersion> MavLinkNodeImpl::getCapabilities() { if (has_cap_) { AsyncResult<MavLinkAutopilotVersion> nowait([=](int state) { unused(state); }); nowait.setResult(cap_); return nowait; } auto con = ensureConnection(); AsyncResult<MavLinkAutopilotVersion> result([=](int state) { con->unsubscribe(state); }); int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& m) { unused(connection); unused(m); result.setResult(cap_); }); result.setState(subscription); // request capabilities, it will respond with AUTOPILOT_VERSION. MavCmdRequestAutopilotCapabilities cmd{}; cmd.param1 = 1; sendCommand(cmd); return result; } AsyncResult<MavLinkHeartbeat> MavLinkNodeImpl::waitForHeartbeat() { Utils::log("Waiting for heartbeat from PX4..."); // wait for a heartbeat msg since this will give us the port to send commands to... //this->setMessageInterval(static_cast<int>(MavLinkMessageIds::MAVLINK_MSG_ID_HEARTBEAT), 1); auto con = ensureConnection(); AsyncResult<MavLinkHeartbeat> result([=](int state) { con->unsubscribe(state); }); int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& m) { unused(connection); if (m.msgid == static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_HEARTBEAT)) { MavLinkHeartbeat heartbeat; heartbeat.decode(m); result.setResult(heartbeat); } }); result.setState(subscription); return result; } void MavLinkNodeImpl::sendOneHeartbeat() { MavLinkHeartbeat heartbeat; // send a heart beat so that the remote node knows we are still alive // (otherwise drone will trigger a failsafe operation). heartbeat.autopilot = static_cast<uint8_t>(MAV_AUTOPILOT::MAV_AUTOPILOT_GENERIC); heartbeat.type = static_cast<uint8_t>(MAV_TYPE::MAV_TYPE_GCS); heartbeat.mavlink_version = 3; heartbeat.base_mode = 0; // ignored by PX4 heartbeat.custom_mode = 0; // ignored by PX4 heartbeat.system_status = 0; // ignored by PX4 try { sendMessage(heartbeat); } catch (std::exception& e) { // ignore any failures here because we are running in our own thread here. Utils::log(Utils::stringf("Caught and ignoring exception sending heartbeat: %s", e.what())); } } void MavLinkNodeImpl::setMessageInterval(int msgId, int frequency) { float intervalMicroseconds = 1000000.0f / frequency; MavCmdSetMessageInterval cmd{}; cmd.MessageId = static_cast<float>(msgId); cmd.Interval = intervalMicroseconds; sendCommand(cmd); } union param_value_u { int8_t b; int16_t s; int32_t i; uint8_t ub; uint16_t us; uint32_t ui; float f; }; float UnpackParameter(uint8_t type, float param_value) { param_value_u pu; pu.f = param_value; float value = 0; switch (static_cast<MAV_PARAM_TYPE>(type)) { case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT8: value = static_cast<float>(pu.ub); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT8: value = static_cast<float>(pu.b); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT16: value = static_cast<float>(pu.us); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT16: value = static_cast<float>(pu.s); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT32: value = static_cast<float>(pu.ui); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT32: value = static_cast<float>(pu.i); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT64: // we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work? value = static_cast<float>(pu.ui); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT64: // we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work? value = static_cast<float>(pu.i); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL32: value = param_value; break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL64: // we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work? value = param_value; break; default: break; } return value; } float PackParameter(uint8_t type, float param_value) { param_value_u pu; pu.f = 0; switch (static_cast<MAV_PARAM_TYPE>(type)) { case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT8: pu.ub = static_cast<uint8_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT8: pu.b = static_cast<int8_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT16: pu.us = static_cast<uint16_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT16: pu.s = static_cast<int16_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT32: pu.ui = static_cast<uint32_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT32: pu.i = static_cast<int32_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_UINT64: // we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work? pu.ui = static_cast<uint32_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_INT64: // we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work? pu.i = static_cast<int32_t>(param_value); break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL32: pu.f = param_value; break; case MAV_PARAM_TYPE::MAV_PARAM_TYPE_REAL64: // we only have 4 bytes for the value in mavlink_param_value_t, so how does this one work? pu.f = param_value; break; default: break; } return pu.f; } void MavLinkNodeImpl::assertNotPublishingThread() { auto con = ensureConnection(); if (con->isPublishThread()) { throw std::runtime_error("Cannot perform blocking operation on the connection publish thread"); } } std::vector<MavLinkParameter> MavLinkNodeImpl::getParamList() { std::vector<MavLinkParameter> result; bool done = false; Semaphore paramReceived; bool waiting = false; size_t paramCount = 0; auto con = ensureConnection(); assertNotPublishingThread(); int subscription = con->subscribe([&](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) { unused(connection); if (message.msgid == MavLinkParamValue::kMessageId) { MavLinkParamValue param; param.decode(message); MavLinkParameter p; p.index = param.param_index; p.type = param.param_type; char buf[17]; std::memset(buf, 0, 17); std::memcpy(buf, param.param_id, 16); p.name = buf; p.value = param.param_value; result.push_back(p); paramCount = param.param_count; if (param.param_index == param.param_count - 1) { done = true; } if (waiting) { paramReceived.post(); } } }); //MAVLINK_MSG_ID_PARAM_REQUEST_LIST MavLinkParamRequestList cmd; cmd.target_system = getTargetSystemId(); cmd.target_component = getTargetComponentId(); sendMessage(cmd); while (!done) { waiting = true; if (!paramReceived.timed_wait(3000)) { // timeout, so we'll drop through to the code below which will try and fix this... done = true; } waiting = false; } con->unsubscribe(subscription); // note that UDP does not guarantee delivery of messages, so we have to also check if some parameters are missing and get them individually. std::vector<size_t> missing; for (size_t i = 0; i < paramCount; i++) { // nested loop is inefficient, but it is needed because UDP also doesn't guarantee in-order delivery bool found = false; for (auto iter = result.begin(), end = result.end(); iter != end; iter++) { MavLinkParameter p = *iter; if (static_cast<size_t>(p.index) == i) { found = true; break; } } if (!found) { missing.push_back(i); } } // ok, now fetch the missing parameters. for (auto iter = missing.begin(), end = missing.end(); iter != end; iter++) { size_t index = *iter; MavLinkParameter r; if (getParameterByIndex(static_cast<int16_t>(*iter)).wait(2000, &r)) { result.push_back(r); } else { Utils::log(Utils::stringf("Paremter %d does not seem to exist", index), Utils::kLogLevelWarn); } } std::sort(result.begin(), result.end(), [&](const MavLinkParameter& p1, const MavLinkParameter& p2) { return p1.name.compare(p2.name) < 0; }); this->parameters_ = result; return result; } MavLinkParameter MavLinkNodeImpl::getCachedParameter(const std::string& name) { if (this->parameters_.size() == 0) { throw std::runtime_error("Error: please call getParamList during initialization so we have cached snapshot of the parameter values"); } for (int i = static_cast<int>(this->parameters_.size()) - 1; i >= 0; i--) { MavLinkParameter p = this->parameters_[i]; if (p.name == name) { return p; } } throw std::runtime_error(Utils::stringf("Error: parameter name '%s' not found")); } AsyncResult<MavLinkParameter> MavLinkNodeImpl::getParameter(const std::string& name) { int size = static_cast<int>(name.size()); if (size > 16) { throw std::runtime_error(Utils::stringf("Error: parameter name '%s' is too long, must be <= 16 chars", name.c_str())); } else if (size < 16) { size++; // we can include the null terminator. } auto con = ensureConnection(); AsyncResult<MavLinkParameter> asyncResult([=](int state) { con->unsubscribe(state); }); MavLinkParamRequestRead cmd; std::strncpy(cmd.param_id, name.c_str(), size); cmd.param_index = -1; cmd.target_component = getTargetComponentId(); cmd.target_system = getTargetSystemId(); int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) { unused(connection); if (message.msgid == MavLinkParamValue::kMessageId) { MavLinkParamValue param; param.decode(message); if (std::strncmp(param.param_id, cmd.param_id, size) == 0) { MavLinkParameter result; result.name = name; result.type = param.param_type; result.index = param.param_index; result.value = UnpackParameter(param.param_type, param.param_value); asyncResult.setResult(result); } } }); asyncResult.setState(subscription); sendMessage(cmd); return asyncResult; } AsyncResult<MavLinkParameter> MavLinkNodeImpl::getParameterByIndex(int16_t index) { auto con = ensureConnection(); AsyncResult<MavLinkParameter> asyncResult([=](int state) { con->unsubscribe(state); }); MavLinkParamRequestRead cmd; cmd.param_id[0] = '\0'; cmd.param_index = index; cmd.target_component = getTargetComponentId(); cmd.target_system = getTargetSystemId(); int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) { unused(connection); if (message.msgid == MavLinkParamValue::kMessageId) { MavLinkParamValue param; param.decode(message); if (param.param_index == index) { MavLinkParameter result; char buf[17]; std::memset(buf, 0, 17); std::memcpy(buf, param.param_id, 16); result.name = buf; result.type = param.param_type; result.index = param.param_index; result.value = UnpackParameter(param.param_type, param.param_value); asyncResult.setResult(result); } } }); asyncResult.setState(subscription); sendMessage(cmd); return asyncResult; } AsyncResult<bool> MavLinkNodeImpl::setParameter(MavLinkParameter p) { int size = static_cast<int>(p.name.size()); if (size > 16) { throw std::runtime_error(Utils::stringf("Error: parameter name '%s' is too long, must be <= 16 chars", p.name.c_str())); } else if (size < 16) { size++; // we can include the null terminator. } auto con = ensureConnection(); assertNotPublishingThread(); AsyncResult<bool> result([=](int state) { con->unsubscribe(state); }); bool gotit = false; MavLinkParameter q; for (size_t i = 0; i < 3; i++) { if (getParameter(p.name).wait(2000, &q)) { gotit = true; break; } } if (!gotit) { throw std::runtime_error(Utils::stringf("Error: parameter name '%s' was not found", p.name.c_str())); } MavLinkParamSet setparam; setparam.target_component = getTargetComponentId(); setparam.target_system = getTargetSystemId(); std::strncpy(setparam.param_id, p.name.c_str(), size); setparam.param_type = q.type; setparam.param_value = PackParameter(q.type, p.value); sendMessage(setparam); // confirmation of the PARAM_SET is to receive the updated PARAM_VALUE. int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) { unused(connection); if (message.msgid == MavLinkParamValue::kMessageId) { MavLinkParamValue param; param.decode(message); if (std::strncmp(param.param_id, setparam.param_id, size) == 0) { bool rc = param.param_value == setparam.param_value; result.setResult(rc); } } }); result.setState(subscription); return result; } void MavLinkNodeImpl::sendMessage(MavLinkMessageBase& msg) { msg.sysid = local_system_id; msg.compid = local_component_id; ensureConnection()->sendMessage(msg); } void MavLinkNodeImpl::sendMessage(MavLinkMessage& msg) { msg.compid = local_component_id; msg.sysid = local_system_id; ensureConnection()->sendMessage(msg); } void MavLinkNodeImpl::sendCommand(MavLinkCommand& command) { MavLinkCommandLong cmd{}; command.pack(); cmd.command = command.command; cmd.target_system = getTargetSystemId(); cmd.target_component = getTargetComponentId(); cmd.confirmation = 1; cmd.param1 = command.param1; cmd.param2 = command.param2; cmd.param3 = command.param3; cmd.param4 = command.param4; cmd.param5 = command.param5; cmd.param6 = command.param6; cmd.param7 = command.param7; try { sendMessage(cmd); } catch (const std::exception& e) { // silently fail since we are on a background thread here... unused(e); } } AsyncResult<bool> MavLinkNodeImpl::sendCommandAndWaitForAck(MavLinkCommand& command) { auto con = ensureConnection(); AsyncResult<bool> result([=](int state) { con->unsubscribe(state); }); uint16_t cmd = command.command; int subscription = con->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& message) { unused(connection); if (message.msgid == MavLinkCommandAck::kMessageId) { MavLinkCommandAck ack; ack.decode(message); if (ack.command == cmd) { MAV_RESULT ackResult = static_cast<MAV_RESULT>(ack.result); if (ackResult == MAV_RESULT::MAV_RESULT_TEMPORARILY_REJECTED) { Utils::log(Utils::stringf("### command %d result: MAV_RESULT_TEMPORARILY_REJECTED", cmd)); } else if (ackResult == MAV_RESULT::MAV_RESULT_UNSUPPORTED) { Utils::log(Utils::stringf("### command %d result: MAV_RESULT_UNSUPPORTED", cmd)); } else if (ackResult == MAV_RESULT::MAV_RESULT_FAILED) { Utils::log(Utils::stringf("### command %d result: MAV_RESULT_FAILED", cmd)); } else if (ackResult == MAV_RESULT::MAV_RESULT_ACCEPTED) { Utils::log(Utils::stringf("### command %d result: MAV_RESULT_ACCEPTED", cmd)); } else { Utils::log(Utils::stringf("### command %d unexpected result: %d", cmd, ackResult)); } // tell the caller this is complete. result.setResult(ackResult == MAV_RESULT::MAV_RESULT_ACCEPTED); } } }); result.setState(subscription); sendCommand(command); return result; }
AirSim/MavLinkCom/src/impl/MavLinkNodeImpl.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/impl/MavLinkNodeImpl.cpp", "repo_id": "AirSim", "token_count": 8689 }
29
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "SocketInit.hpp" #include "Utils.hpp" #include <stdexcept> #ifdef _WIN32 #include <Windows.h> #endif using namespace mavlink_utils; bool SocketInit::socket_initialized_ = false; SocketInit::SocketInit() { if (!socket_initialized_) { socket_initialized_ = true; #ifdef _WIN32 WSADATA wsaData; // Initialize Winsock int rc = WSAStartup(MAKEWORD(2, 2), (LPWSADATA)&wsaData); if (rc != 0) { throw std::runtime_error(Utils::stringf("WSAStartup failed with error : %d\n", rc)); } #endif } }
AirSim/MavLinkCom/src/serial_com/SocketInit.cpp/0
{ "file_path": "AirSim/MavLinkCom/src/serial_com/SocketInit.cpp", "repo_id": "AirSim", "token_count": 271 }
30
import numpy as np import matplotlib.pyplot as plt import re import sys import pdb def read_pfm(file): """ Read a pfm file """ file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() header = str(bytes.decode(header, encoding='utf-8')) if header == 'PF': color = True elif header == 'Pf': color = False else: raise Exception('Not a PFM file.') pattern = r'^(\d+)\s(\d+)\s$' temp_str = str(bytes.decode(file.readline(), encoding='utf-8')) dim_match = re.match(pattern, temp_str) if dim_match: width, height = map(int, dim_match.groups()) else: temp_str += str(bytes.decode(file.readline(), encoding='utf-8')) dim_match = re.match(pattern, temp_str) if dim_match: width, height = map(int, dim_match.groups()) else: raise Exception('Malformed PFM header: width, height cannot be found') scale = float(file.readline().rstrip()) if scale < 0: # little-endian endian = '<' scale = -scale else: endian = '>' # big-endian data = np.fromfile(file, endian + 'f') shape = (height, width, 3) if color else (height, width) data = np.reshape(data, shape) # DEY: I don't know why this was there. file.close() return data, scale def write_pfm(file, image, scale=1): """ Write a pfm file """ file = open(file, 'wb') color = None if image.dtype.name != 'float32': raise Exception('Image dtype must be float32.') if len(image.shape) == 3 and image.shape[2] == 3: # color image color = True elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale color = False else: raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.') file.write(bytes('PF\n', 'UTF-8') if color else bytes('Pf\n', 'UTF-8')) temp_str = '%d %d\n' % (image.shape[1], image.shape[0]) file.write(bytes(temp_str, 'UTF-8')) endian = image.dtype.byteorder if endian == '<' or endian == '=' and sys.byteorder == 'little': scale = -scale temp_str = '%f\n' % scale file.write(bytes(temp_str, 'UTF-8')) image.tofile(file)
AirSim/PythonClient/airsim/pfm.py/0
{ "file_path": "AirSim/PythonClient/airsim/pfm.py", "repo_id": "AirSim", "token_count": 998 }
31
import setup_path import airsim import time import sys import threading def runSingleCar(id: int): client = airsim.CarClient() client.confirmConnection() vehicle_name = f"Car_{id}" pose = airsim.Pose(airsim.Vector3r(0, 7*id, 0), airsim.Quaternionr(0, 0, 0, 0)) print(f"Creating {vehicle_name}") success = client.simAddVehicle(vehicle_name, "Physxcar", pose) if not success: print(f"Falied to create {vehicle_name}") return # Sleep for some time to wait for other vehicles to be created time.sleep(1) # driveCar(vehicle_name, client) print(f"Driving {vehicle_name} for a few secs...") client.enableApiControl(True, vehicle_name) car_controls = airsim.CarControls() # go forward car_controls.throttle = 0.5 car_controls.steering = 0 client.setCarControls(car_controls, vehicle_name) time.sleep(3) # let car drive a bit # Go forward + steer right car_controls.throttle = 0.5 car_controls.steering = 1 client.setCarControls(car_controls, vehicle_name) time.sleep(3) # go reverse car_controls.throttle = -0.5 car_controls.is_manual_gear = True car_controls.manual_gear = -1 car_controls.steering = 0 client.setCarControls(car_controls, vehicle_name) time.sleep(3) car_controls.is_manual_gear = False # change back gear to auto car_controls.manual_gear = 0 # apply brakes car_controls.brake = 1 client.setCarControls(car_controls, vehicle_name) time.sleep(3) if __name__ == "__main__": num_vehicles = 3 if len(sys.argv) == 2: num_vehicles = int(sys.argv[1]) print(f"Creating {num_vehicles} vehicles") threads = [] for id in range(num_vehicles, 0, -1): t = threading.Thread(target=runSingleCar, args=(id,)) threads.append(t) t.start() for t in threads: t.join()
AirSim/PythonClient/car/runtime_car.py/0
{ "file_path": "AirSim/PythonClient/car/runtime_car.py", "repo_id": "AirSim", "token_count": 815 }
32
import setup_path import airsim import cv2 import numpy as np import pprint # connect to the AirSim simulator client = airsim.VehicleClient() client.confirmConnection() # set camera name and image type to request images and detections camera_name = "0" image_type = airsim.ImageType.Scene # set detection radius in [cm] client.simSetDetectionFilterRadius(camera_name, image_type, 200 * 100) # add desired object name to detect in wild card/regex format client.simAddDetectionFilterMeshName(camera_name, image_type, "Cylinder*") while True: rawImage = client.simGetImage(camera_name, image_type) if not rawImage: continue png = cv2.imdecode(airsim.string_to_uint8_array(rawImage), cv2.IMREAD_UNCHANGED) cylinders = client.simGetDetections(camera_name, image_type) if cylinders: for cylinder in cylinders: s = pprint.pformat(cylinder) print("Cylinder: %s" % s) cv2.rectangle(png,(int(cylinder.box2D.min.x_val),int(cylinder.box2D.min.y_val)),(int(cylinder.box2D.max.x_val),int(cylinder.box2D.max.y_val)),(255,0,0),2) cv2.putText(png, cylinder.name, (int(cylinder.box2D.min.x_val),int(cylinder.box2D.min.y_val - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36,255,12)) cv2.imshow("AirSim", png) if cv2.waitKey(1) & 0xFF == ord('q'): break elif cv2.waitKey(1) & 0xFF == ord('c'): client.simClearDetectionMeshNames(camera_name, image_type) elif cv2.waitKey(1) & 0xFF == ord('a'): client.simAddDetectionFilterMeshName(camera_name, image_type, "Cylinder*") cv2.destroyAllWindows()
AirSim/PythonClient/detection/detection.py/0
{ "file_path": "AirSim/PythonClient/detection/detection.py", "repo_id": "AirSim", "token_count": 683 }
33
import random import csv from PIL import Image import numpy as np import pandas as pd import sys import os import errno from collections import OrderedDict import h5py from pathlib import Path import copy import re # This constant is used as an upper bound for normalizing the car's speed to be between 0 and 1 MAX_SPEED = 70.0 def checkAndCreateDir(full_path): """Checks if a given path exists and if not, creates the needed directories. Inputs: full_path: path to be checked """ if not os.path.exists(os.path.dirname(full_path)): try: os.makedirs(os.path.dirname(full_path)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise def readImagesFromPath(image_names): """ Takes in a path and a list of image file names to be loaded and returns a list of all loaded images after resize. Inputs: image_names: list of image names Returns: List of all loaded and resized images """ returnValue = [] for image_name in image_names: im = Image.open(image_name) imArr = np.asarray(im) #Remove alpha channel if exists if len(imArr.shape) == 3 and imArr.shape[2] == 4: if (np.all(imArr[:, :, 3] == imArr[0, 0, 3])): imArr = imArr[:,:,0:3] if len(imArr.shape) != 3 or imArr.shape[2] != 3: print('Error: Image', image_name, 'is not RGB.') sys.exit() returnIm = np.asarray(imArr) returnValue.append(returnIm) return returnValue def splitTrainValidationAndTestData(all_data_mappings, split_ratio=(0.7, 0.2, 0.1)): """Simple function to create train, validation and test splits on the data. Inputs: all_data_mappings: mappings from the entire dataset split_ratio: (train, validation, test) split ratio Returns: train_data_mappings: mappings for training data validation_data_mappings: mappings for validation data test_data_mappings: mappings for test data """ if round(sum(split_ratio), 5) != 1.0: print("Error: Your splitting ratio should add up to 1") sys.exit() train_split = int(len(all_data_mappings) * split_ratio[0]) val_split = train_split + int(len(all_data_mappings) * split_ratio[1]) train_data_mappings = all_data_mappings[0:train_split] validation_data_mappings = all_data_mappings[train_split:val_split] test_data_mappings = all_data_mappings[val_split:] return [train_data_mappings, validation_data_mappings, test_data_mappings] def generateDataMapAirSim(folders): """ Data map generator for simulator(AirSim) data. Reads the driving_log csv file and returns a list of 'center camera image name - label(s)' tuples Inputs: folders: list of folders to collect data from Returns: mappings: All data mappings as a dictionary. Key is the image filepath, the values are a 2-tuple: 0 -> label(s) as a list of double 1 -> previous state as a list of double """ all_mappings = {} for folder in folders: print('Reading data from {0}...'.format(folder)) current_df = pd.read_csv(os.path.join(folder, 'airsim_rec.txt'), sep='\t') for i in range(1, current_df.shape[0] - 1): if current_df.iloc[i-1]['Brake'] != 0: # Consider only training examples without breaks continue norm_steering = [ (float(current_df.iloc[i-1][['Steering']]) + 1) / 2.0 ] # Normalize steering: between 0 and 1 norm_throttle = [ float(current_df.iloc[i-1][['Throttle']]) ] norm_speed = [ float(current_df.iloc[i-1][['Speed (kmph)']]) / MAX_SPEED ] # Normalize speed: between 0 and 1 previous_state = norm_steering + norm_throttle + norm_speed # Append lists #compute average steering over 3 consecutive recorded images, this will serve as the label norm_steering0 = (float(current_df.iloc[i][['Steering']]) + 1) / 2.0 norm_steering1 = (float(current_df.iloc[i+1][['Steering']]) + 1) / 2.0 temp_sum_steering = norm_steering[0] + norm_steering0 + norm_steering1 average_steering = temp_sum_steering / 3.0 current_label = [average_steering] image_filepath = os.path.join(os.path.join(folder, 'images'), current_df.iloc[i]['ImageName']).replace('\\', '/') if (image_filepath in all_mappings): print('Error: attempting to add image {0} twice.'.format(image_filepath)) all_mappings[image_filepath] = (current_label, previous_state) mappings = [(key, all_mappings[key]) for key in all_mappings] random.shuffle(mappings) return mappings def generatorForH5py(data_mappings, chunk_size=32): """ This function batches the data for saving to the H5 file """ for chunk_id in range(0, len(data_mappings), chunk_size): # Data is expected to be a dict of <image: (label, previousious_state)> data_chunk = data_mappings[chunk_id:chunk_id + chunk_size] if (len(data_chunk) == chunk_size): image_names_chunk = [a for (a, b) in data_chunk] labels_chunk = np.asarray([b[0] for (a, b) in data_chunk]) previous_state_chunk = np.asarray([b[1] for (a, b) in data_chunk]) #Flatten and yield as tuple yield (image_names_chunk, labels_chunk.astype(float), previous_state_chunk.astype(float)) if chunk_id + chunk_size > len(data_mappings): raise StopIteration raise StopIteration def saveH5pyData(data_mappings, target_file_path, chunk_size): """ Saves H5 data to file """ gen = generatorForH5py(data_mappings,chunk_size) image_names_chunk, labels_chunk, previous_state_chunk = next(gen) images_chunk = np.asarray(readImagesFromPath(image_names_chunk)) row_count = images_chunk.shape[0] checkAndCreateDir(target_file_path) with h5py.File(target_file_path, 'w') as f: # Initialize a resizable dataset to hold the output images_chunk_maxshape = (None,) + images_chunk.shape[1:] labels_chunk_maxshape = (None,) + labels_chunk.shape[1:] previous_state_maxshape = (None,) + previous_state_chunk.shape[1:] dset_images = f.create_dataset('image', shape=images_chunk.shape, maxshape=images_chunk_maxshape, chunks=images_chunk.shape, dtype=images_chunk.dtype) dset_labels = f.create_dataset('label', shape=labels_chunk.shape, maxshape=labels_chunk_maxshape, chunks=labels_chunk.shape, dtype=labels_chunk.dtype) dset_previous_state = f.create_dataset('previous_state', shape=previous_state_chunk.shape, maxshape=previous_state_maxshape, chunks=previous_state_chunk.shape, dtype=previous_state_chunk.dtype) dset_images[:] = images_chunk dset_labels[:] = labels_chunk dset_previous_state[:] = previous_state_chunk for image_names_chunk, label_chunk, previous_state_chunk in gen: image_chunk = np.asarray(readImagesFromPath(image_names_chunk)) # Resize the dataset to accommodate the next chunk of rows dset_images.resize(row_count + image_chunk.shape[0], axis=0) dset_labels.resize(row_count + label_chunk.shape[0], axis=0) dset_previous_state.resize(row_count + previous_state_chunk.shape[0], axis=0) # Create the next chunk dset_images[row_count:] = image_chunk dset_labels[row_count:] = label_chunk dset_previous_state[row_count:] = previous_state_chunk # Increment the row count row_count += image_chunk.shape[0] def cook(folders, output_directory, train_eval_test_split, chunk_size): """ Primary function for data pre-processing. Reads and saves all data as h5 files. Inputs: folders: a list of all data folders output_directory: location for saving h5 files train_eval_test_split: dataset split ratio """ output_files = [os.path.join(output_directory, f) for f in ['train.h5', 'eval.h5', 'test.h5']] if (any([os.path.isfile(f) for f in output_files])): print("Preprocessed data already exists at: {0}. Skipping preprocessing.".format(output_directory)) else: all_data_mappings = generateDataMapAirSim(folders) split_mappings = splitTrainValidationAndTestData(all_data_mappings, split_ratio=train_eval_test_split) for i in range(0, len(split_mappings)-1, 1): print('Processing {0}...'.format(output_files[i])) saveH5pyData(split_mappings[i], output_files[i], chunk_size) print('Finished saving {0}.'.format(output_files[i]))
AirSim/PythonClient/imitation_learning/Cooking.py/0
{ "file_path": "AirSim/PythonClient/imitation_learning/Cooking.py", "repo_id": "AirSim", "token_count": 4200 }
34
import setup_path import airsim import time # connect to the AirSim simulator client = airsim.MultirotorClient() client.confirmConnection() client.enableApiControl(True) client.armDisarm(True) # MultirotorClient.wait_key('Press any key to takeoff') print("Taking off") client.takeoffAsync().join() print("Ready") for i in range(5): client.moveToPositionAsync(float(-50.00), float( 50.26), float( -20.58), float( 3.5)) time.sleep(6) camera_pose = airsim.Pose(airsim.Vector3r(0, 0, 0), airsim.to_quaternion(0.5, 0.5, 0.1)) client.simSetCameraPose("0", camera_pose) client.moveToPositionAsync(float(50.00), float( -50.26), float( -10.58), float( 3.5)) time.sleep(6) camera_pose = airsim.Pose(airsim.Vector3r(0, 0, 0), airsim.to_quaternion(-0.5, -0.5, -0.1)) client.simSetCameraPose("0", camera_pose)
AirSim/PythonClient/multirotor/gimbal.py/0
{ "file_path": "AirSim/PythonClient/multirotor/gimbal.py", "repo_id": "AirSim", "token_count": 333 }
35
import setup_path import airsim import numpy as np import math import time import gym from gym import spaces from airgym.envs.airsim_env import AirSimEnv class AirSimCarEnv(AirSimEnv): def __init__(self, ip_address, image_shape): super().__init__(image_shape) self.image_shape = image_shape self.start_ts = 0 self.state = { "position": np.zeros(3), "prev_position": np.zeros(3), "pose": None, "prev_pose": None, "collision": False, } self.car = airsim.CarClient(ip=ip_address) self.action_space = spaces.Discrete(6) self.image_request = airsim.ImageRequest( "0", airsim.ImageType.DepthPerspective, True, False ) self.car_controls = airsim.CarControls() self.car_state = None def _setup_car(self): self.car.reset() self.car.enableApiControl(True) self.car.armDisarm(True) time.sleep(0.01) def __del__(self): self.car.reset() def _do_action(self, action): self.car_controls.brake = 0 self.car_controls.throttle = 1 if action == 0: self.car_controls.throttle = 0 self.car_controls.brake = 1 elif action == 1: self.car_controls.steering = 0 elif action == 2: self.car_controls.steering = 0.5 elif action == 3: self.car_controls.steering = -0.5 elif action == 4: self.car_controls.steering = 0.25 else: self.car_controls.steering = -0.25 self.car.setCarControls(self.car_controls) time.sleep(1) def transform_obs(self, response): img1d = np.array(response.image_data_float, dtype=np.float) img1d = 255 / np.maximum(np.ones(img1d.size), img1d) img2d = np.reshape(img1d, (response.height, response.width)) from PIL import Image image = Image.fromarray(img2d) im_final = np.array(image.resize((84, 84)).convert("L")) return im_final.reshape([84, 84, 1]) def _get_obs(self): responses = self.car.simGetImages([self.image_request]) image = self.transform_obs(responses[0]) self.car_state = self.car.getCarState() self.state["prev_pose"] = self.state["pose"] self.state["pose"] = self.car_state.kinematics_estimated self.state["collision"] = self.car.simGetCollisionInfo().has_collided return image def _compute_reward(self): MAX_SPEED = 300 MIN_SPEED = 10 THRESH_DIST = 3.5 BETA = 3 pts = [ np.array([x, y, 0]) for x, y in [ (0, -1), (130, -1), (130, 125), (0, 125), (0, -1), (130, -1), (130, -128), (0, -128), (0, -1), ] ] car_pt = self.state["pose"].position.to_numpy_array() dist = 10000000 for i in range(0, len(pts) - 1): dist = min( dist, np.linalg.norm( np.cross((car_pt - pts[i]), (car_pt - pts[i + 1])) ) / np.linalg.norm(pts[i] - pts[i + 1]), ) # print(dist) if dist > THRESH_DIST: reward = -3 else: reward_dist = math.exp(-BETA * dist) - 0.5 reward_speed = ( (self.car_state.speed - MIN_SPEED) / (MAX_SPEED - MIN_SPEED) ) - 0.5 reward = reward_dist + reward_speed done = 0 if reward < -1: done = 1 if self.car_controls.brake == 0: if self.car_state.speed <= 1: done = 1 if self.state["collision"]: done = 1 return reward, done def step(self, action): self._do_action(action) obs = self._get_obs() reward, done = self._compute_reward() return obs, reward, done, self.state def reset(self): self._setup_car() self._do_action(1) return self._get_obs()
AirSim/PythonClient/reinforcement_learning/airgym/envs/car_env.py/0
{ "file_path": "AirSim/PythonClient/reinforcement_learning/airgym/envs/car_env.py", "repo_id": "AirSim", "token_count": 2138 }
36
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // by Sudipta Sinha // adapted for AirSim by Matthias Mueller #pragma once #include <stdio.h> /* printf */ #include <string> struct SGMOptions { std::string inputDir; // folder contains input images std::string outputDir; // folder for output features files and match files int onlyStereo; // only stereo processing int sgmConfidenceThreshold; // value between [0 and 255] confidence threshold cutoff int maxImageDimensionWidth; int minDisparity; int maxDisparity; int numDirections; // 4 or 8 int doSequential; // do sequential message passing (or horizontal and vertical in parallel). int doVis; // if 1, then output visualization. int doOut; // if 1, then write output float smoothness; float penalty1; float penalty2; float alpha; int doSubPixRefinement; SGMOptions() { inputDir = ""; outputDir = "C:/Github/AirSimSGM/SGM/output"; sgmConfidenceThreshold = 16; maxImageDimensionWidth = -1; minDisparity = 0; maxDisparity = 192; numDirections = 4; doSequential = 0; doVis = 1; doOut = 0; smoothness = 200.0f; penalty1 = 1.0; penalty2 = 8.0; alpha = 10.0; onlyStereo = 0; doSubPixRefinement = 1; } void Print() { printf("\n\n****************** Parameter List *********************\n"); wprintf(L" sgmConfidenceThreshold = %d\n", sgmConfidenceThreshold); wprintf(L" maxImageDimensionWidth = %d\n", maxImageDimensionWidth); wprintf(L" minDisparity = %d\n", minDisparity); wprintf(L" maxDisparity = %d\n", maxDisparity); wprintf(L" numDirections = %d\n", numDirections); wprintf(L" smoothness = %f\n", smoothness); wprintf(L" penalty1 = %f\n", penalty1); wprintf(L" penalty2 = %f\n", penalty2); wprintf(L" alpha = %f\n", alpha); wprintf(L" doSequential = %d\n", doSequential); wprintf(L" doVis = %d\n", doVis); wprintf(L" doOut = %d\n", doOut); wprintf(L" onlyStereo = %d\n", onlyStereo); wprintf(L" doSubPixRefinement = %d\n", doSubPixRefinement); printf("*********************************************************\n\n\n"); } };
AirSim/SGM/src/stereoPipeline/SGMOptions.h/0
{ "file_path": "AirSim/SGM/src/stereoPipeline/SGMOptions.h", "repo_id": "AirSim", "token_count": 1012 }
37
#include "PawnSimApi.h" #include "common/ClockFactory.hpp" #include "common/EarthUtils.hpp" #include "PInvokeWrapper.h" #include "AirSimStructs.hpp" #include "UnityUtilities.hpp" PawnSimApi::PawnSimApi(const Params& params) : params_(params), ned_transform_(*params.global_transform) { } void PawnSimApi::initialize() { image_capture_.reset(new UnityImageCapture(params_.vehicle_name)); Kinematics::State initial_kinematic_state = Kinematics::State::zero(); ; initial_kinematic_state.pose = getPose(); kinematics_.reset(new Kinematics(initial_kinematic_state)); Environment::State initial_environment; initial_environment.position = initial_kinematic_state.pose.position; initial_environment.geo_point = params_.home_geopoint; environment_.reset(new Environment(initial_environment)); //initialize state UnityTransform initialTransform = GetTransformFromUnity(params_.vehicle_name.c_str()); initial_state_.mesh_origin = initialTransform.Position; setStartPosition(initialTransform.Position, initialTransform.Rotation); initial_state_.tracing_enabled = getVehicleSetting()->enable_trace; initial_state_.collisions_enabled = getVehicleSetting()->enable_collisions; initial_state_.passthrough_enabled = getVehicleSetting()->enable_collision_passthrough; initial_state_.collision_info = CollisionInfo(); initial_state_.was_last_move_teleport = false; initial_state_.was_last_move_teleport = canTeleportWhileMove(); state_ = initial_state_; } void PawnSimApi::setStartPosition(const AirSimVector& position, const AirSimQuaternion& rotator) { initial_state_.start_location = position; initial_state_.start_rotation = rotator; //compute our home point home_geo_point_ = msr::airlib::EarthUtils::nedToGeodetic(UnityUtilities::Convert_to_Vector3r(initial_state_.start_location), AirSimSettings::singleton().origin_geopoint); } void PawnSimApi::pawnTick(float dt) { //default behavior is to call update every tick //for custom physics engine, this method should be overridden and update should be //called from every physics tick update(); updateRenderedState(dt); updateRendering(dt); } bool PawnSimApi::testLineOfSightToPoint(const msr::airlib::GeoPoint& point) const { unused(point); throw std::invalid_argument(common_utils::Utils::stringf( "testLineOfSightToPoint is not supported on unity") .c_str()); return false; } void PawnSimApi::OnCollision(msr::airlib::CollisionInfo collisionInfo) { state_.collision_info.has_collided = collisionInfo.has_collided; state_.collision_info.normal = collisionInfo.normal; state_.collision_info.impact_point = collisionInfo.impact_point; state_.collision_info.position = collisionInfo.position; state_.collision_info.penetration_depth = collisionInfo.penetration_depth; state_.collision_info.time_stamp = msr::airlib::ClockFactory::get()->nowNanos(); state_.collision_info.object_name = collisionInfo.object_name; state_.collision_info.object_id = collisionInfo.object_id; ++state_.collision_info.collision_count; PrintLogMessage("Collision", Utils::stringf("#%d with %s - ObjID %d", state_.collision_info.collision_count, state_.collision_info.object_name.c_str(), state_.collision_info.object_id).c_str(), getVehicleName().c_str(), ErrorLogSeverity::Information); } const NedTransform& PawnSimApi::getNedTransform() const { return ned_transform_; } msr::airlib::RCData PawnSimApi::getRCData() const { AirSimRCData rcDataFromUnity = GetRCData(getVehicleName().c_str()); rc_data_.is_valid = rcDataFromUnity.is_valid; if (rc_data_.is_valid) { rc_data_.throttle = rcDataFromUnity.throttle; rc_data_.yaw = rcDataFromUnity.yaw; rc_data_.roll = rcDataFromUnity.roll; rc_data_.pitch = rcDataFromUnity.pitch; //these will be available for devices like steering wheels rc_data_.left_z = rcDataFromUnity.left_z; rc_data_.right_z = rcDataFromUnity.right_z; rc_data_.switches = 0; rc_data_.switches |= ((rcDataFromUnity.switch1 & 0x80) == 0 ? 0 : 1) << 0; rc_data_.switches |= ((rcDataFromUnity.switch2 & 0x80) == 0 ? 0 : 1) << 1; rc_data_.switches |= ((rcDataFromUnity.switch3 & 0x80) == 0 ? 0 : 1) << 2; rc_data_.switches |= ((rcDataFromUnity.switch4 & 0x80) == 0 ? 0 : 1) << 3; rc_data_.switches |= ((rcDataFromUnity.switch5 & 0x80) == 0 ? 0 : 1) << 4; rc_data_.switches |= ((rcDataFromUnity.switch6 & 0x80) == 0 ? 0 : 1) << 5; rc_data_.switches |= ((rcDataFromUnity.switch7 & 0x80) == 0 ? 0 : 1) << 6; rc_data_.switches |= ((rcDataFromUnity.switch8 & 0x80) == 0 ? 0 : 1) << 7; PrintLogMessage("RC Mode: ", rc_data_.getSwitch(0) == 0 ? "Angle" : "Rate", getVehicleName().c_str(), ErrorLogSeverity::Information); } return rc_data_; } int PawnSimApi::getRemoteControlID() const { return getVehicleSetting()->rc.remote_control_id; } const UnityImageCapture* PawnSimApi::getImageCapture() const { return image_capture_.get(); } AirSimPose PawnSimApi::GetInitialPose() { return AirSimPose(state_.start_location, state_.start_rotation); } void PawnSimApi::resetImplementation() { state_ = initial_state_; rc_data_ = msr::airlib::RCData(); kinematics_->reset(); environment_->reset(); } void PawnSimApi::update() { //sync environment from kinematics environment_->setPosition(kinematics_->getPose().position); environment_->update(); VehicleSimApiBase::update(); } void PawnSimApi::reportState(msr::airlib::StateReporter& reporter) { msr::airlib::VehicleSimApiBase::reportState(reporter); kinematics_->reportState(reporter); environment_->reportState(reporter); // report actual location in unreal coordinates so we can plug that into the UE editor to move the drone. //FVector unrealPosition = getUUPosition(); //reporter.writeValue("unreal pos", Vector3r(unrealPosition.X, unrealPosition.Y, unrealPosition.Z)); } PawnSimApi::CollisionInfo PawnSimApi::getCollisionInfo() const { return state_.collision_info; } PawnSimApi::CollisionInfo PawnSimApi::getCollisionInfoAndReset() { CollisionInfo collision_info = getCollisionInfo(); state_.collision_info.has_collided = false; return collision_info; } void PawnSimApi::toggleTrace() { state_.tracing_enabled = !state_.tracing_enabled; } void PawnSimApi::setTraceLine(const std::vector<float>& color_rgba, float thickness) { throw std::invalid_argument(common_utils::Utils::stringf( "setTraceLine is not supported on unity") .c_str()); } void PawnSimApi::allowPassthroughToggleInput() { state_.passthrough_enabled = !state_.passthrough_enabled; PrintLogMessage("enable_passthrough_on_collisions: ", state_.passthrough_enabled ? "true" : "false", params_.vehicle_name.c_str(), ErrorLogSeverity::Information); } //parameters in NED frame PawnSimApi::Pose PawnSimApi::getPose() const { AirSimUnity::AirSimPose airSimPose = GetPose(params_.vehicle_name.c_str()); return UnityUtilities::Convert_to_Pose(airSimPose); } void PawnSimApi::setPose(const Pose& pose, bool ignore_collision) { SetPose(UnityUtilities::Convert_to_AirSimPose(pose), ignore_collision, getVehicleName().c_str()); } bool PawnSimApi::canTeleportWhileMove() const { //allow teleportation // if collisions are not enabled // or we have collided but passthrough is enabled // we will flip-flop was_last_move_teleport flag so on one tick we have passthrough and other tick we don't // without flip flopping, collisions can't be detected return !state_.collisions_enabled || (state_.collision_info.has_collided && !state_.was_last_move_teleport && state_.passthrough_enabled); } void PawnSimApi::updateRenderedState(float dt) { //by default we update kinematics from UE pawn //if SimMod uses its own physics engine then this should be overriden updateKinematics(dt); } void PawnSimApi::updateRendering(float dt) { unused(dt); //no default action in this base class } const msr::airlib::Kinematics::State* PawnSimApi::getGroundTruthKinematics() const { return &kinematics_->getState(); } void PawnSimApi::setKinematics(const Kinematics::State& state, bool ignore_collision) { unused(ignore_collision); return kinematics_->setState(state); } const msr::airlib::Environment* PawnSimApi::getGroundTruthEnvironment() const { return environment_.get(); } msr::airlib::Kinematics* PawnSimApi::getKinematics() { return kinematics_.get(); } msr::airlib::Environment* PawnSimApi::getEnvironment() { return environment_.get(); } std::string PawnSimApi::getRecordFileLine(bool is_header_line) const { if (is_header_line) { return "TimeStamp\tPOS_X\tPOS_Y\tPOS_Z\tQ_W\tQ_X\tQ_Y\tQ_Z\t"; } const msr::airlib::Kinematics::State* kinematics = getGroundTruthKinematics(); uint64_t timestamp_millis = static_cast<uint64_t>(msr::airlib::ClockFactory::get()->nowNanos() / 1.0E6); //TODO: because this bug we are using alternative code with stringstream //https://answers.unrealengine.com/questions/664905/unreal-crashes-on-two-lines-of-extremely-simple-st.html std::string line; line.append(std::to_string(timestamp_millis)).append("\t").append(std::to_string(kinematics->pose.position.x())).append("\t").append(std::to_string(kinematics->pose.position.y())).append("\t").append(std::to_string(kinematics->pose.position.z())).append("\t").append(std::to_string(kinematics->pose.orientation.w())).append("\t").append(std::to_string(kinematics->pose.orientation.x())).append("\t").append(std::to_string(kinematics->pose.orientation.y())).append("\t").append(std::to_string(kinematics->pose.orientation.z())).append("\t"); return line; } void PawnSimApi::updateKinematics(float dt) { //update kinematics from pawn's movement instead of physics engine auto next_kinematics = kinematics_->getState(); next_kinematics.pose = getPose(); next_kinematics.twist.linear = UnityUtilities::Convert_to_Vector3r(GetVelocity(getVehicleName().c_str())); next_kinematics.twist.angular = msr::airlib::VectorMath::toAngularVelocity( kinematics_->getPose().orientation, next_kinematics.pose.orientation, dt); //TODO: update other fields? next_kinematics.accelerations.linear = (next_kinematics.twist.linear - kinematics_->getTwist().linear) / dt; next_kinematics.accelerations.angular = (next_kinematics.twist.angular - kinematics_->getTwist().angular) / dt; kinematics_->setState(next_kinematics); kinematics_->update(); }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/PawnSimApi.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/PawnSimApi.cpp", "repo_id": "AirSim", "token_count": 4140 }
38
//#pragma once #include <thread> #include "UnityUtilities.hpp" #include "SimHUD/SimHUD.h" #include "Logger.h" #ifdef _WIN32 #define EXPORT __declspec(dllexport) #else #define EXPORT __attribute__((visibility("default"))) #endif static SimHUD* key = nullptr; void StartServerThread(std::string sim_mode_name, int port_number); extern "C" EXPORT bool StartServer(char* sim_mode_name, int port_number) { LOGGER->WriteLog("Starting server for : " + std::string(sim_mode_name)); std::thread server_thread(StartServerThread, sim_mode_name, port_number); server_thread.detach(); int waitCounter = 25; // waiting for maximum 5 seconds to start a server. while ((key == nullptr || !key->server_started_Successfully_) && waitCounter > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(200)); waitCounter--; } return key->server_started_Successfully_; } extern "C" EXPORT void StopServer() { key->EndPlay(); if (key != nullptr) { delete key; key = nullptr; } LOGGER->WriteLog("Server stopped"); } extern "C" EXPORT void CallTick(float deltaSeconds) { key->Tick(deltaSeconds); } extern "C" EXPORT void InvokeCollisionDetection(char* vehicle_name, AirSimUnity::AirSimCollisionInfo collision_info) { auto simMode = key->GetSimMode(); if (simMode) { auto vehicleApi = simMode->getVehicleSimApi(vehicle_name); if (vehicleApi) { msr::airlib::CollisionInfo collisionInfo = UnityUtilities::Convert_to_AirSimCollisioinInfo(collision_info); vehicleApi->OnCollision(collisionInfo); } } }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityToAirSimCalls.h/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityToAirSimCalls.h", "repo_id": "AirSim", "token_count": 631 }
39
#include "SimModeWorldMultiRotor.h" #include "vehicles/multirotor/api/MultirotorApiBase.hpp" #include "MultirotorPawnSimApi.h" #include "vehicles/multirotor/api/MultirotorRpcLibServer.hpp" SimModeWorldMultiRotor::SimModeWorldMultiRotor(int port_number) : SimModeWorldBase(port_number) { } void SimModeWorldMultiRotor::BeginPlay() { SimModeWorldBase::BeginPlay(); //let base class setup physics world initializeForPlay(); } void SimModeWorldMultiRotor::Tick(float DeltaSeconds) { SimModeWorldBase::Tick(DeltaSeconds); } void SimModeWorldMultiRotor::EndPlay() { //stop physics thread before we dismantle stopAsyncUpdator(); SimModeWorldBase::EndPlay(); } UnityPawn* SimModeWorldMultiRotor::GetVehiclePawn(const std::string& vehicle_name) { return new FlyingPawn(vehicle_name); } void SimModeWorldMultiRotor::setupClockSpeed() { typedef msr::airlib::ClockFactory ClockFactory; float clock_speed = getSettings().clock_speed; //setup clock in ClockFactory std::string clock_type = getSettings().clock_type; if (clock_type == "ScalableClock") { //scalable clock returns interval same as wall clock but multiplied by a scale factor ClockFactory::get(std::make_shared<msr::airlib::ScalableClock>(clock_speed == 1 ? 1 : 1 / clock_speed)); } else if (clock_type == "SteppableClock") { //steppable clock returns interval that is a constant number irrespective of wall clock //we can either multiply this fixed interval by scale factor to speed up/down the clock //but that would cause vehicles like quadrotors to become unstable //so alternative we use here is instead to scale control loop frequency. The downside is that //depending on compute power available, we will max out control loop frequency and therefore can no longer //get increase in clock speed //Approach 1: scale clock period, no longer used now due to quadrotor instability //ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>( //static_cast<msr::airlib::TTimeDelta>(getPhysicsLoopPeriod() * 1E-9 * clock_speed))); //Approach 2: scale control loop frequency if clock is speeded up if (clock_speed >= 1) { ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>( static_cast<msr::airlib::TTimeDelta>(getPhysicsLoopPeriod() * 1E-9))); //no clock_speed multiplier setPhysicsLoopPeriod(getPhysicsLoopPeriod() / static_cast<long long>(clock_speed)); } else { //for slowing down, this don't generate instability ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>( static_cast<msr::airlib::TTimeDelta>(getPhysicsLoopPeriod() * 1E-9 * clock_speed))); } } else throw std::invalid_argument(common_utils::Utils::stringf( "clock_type %s is not recognized", clock_type.c_str())); } //-------------------------------- overrides -----------------------------------------------// std::unique_ptr<msr::airlib::ApiServerBase> SimModeWorldMultiRotor::createApiServer() const { #ifdef AIRLIB_NO_RPC return ASimModeBase::createApiServer(); #else auto ptr = std::unique_ptr<msr::airlib::ApiServerBase>(new msr::airlib::MultirotorRpcLibServer( getApiProvider(), getSettings().api_server_address, port_number_)); return ptr; #endif } bool SimModeWorldMultiRotor::isVehicleTypeSupported(const std::string& vehicle_type) const { return ((vehicle_type == AirSimSettings::kVehicleTypeSimpleFlight) || (vehicle_type == AirSimSettings::kVehicleTypePX4)); } std::unique_ptr<PawnSimApi> SimModeWorldMultiRotor::createVehicleSimApi( const PawnSimApi::Params& pawn_sim_api_params) const { auto vehicle_sim_api = std::unique_ptr<PawnSimApi>(new MultirotorPawnSimApi(pawn_sim_api_params)); vehicle_sim_api->initialize(); //For multirotors the vehicle_sim_api are in PhysicsWOrld container and then get reseted when world gets reseted return vehicle_sim_api; } msr::airlib::VehicleApiBase* SimModeWorldMultiRotor::getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params, const PawnSimApi* sim_api) const { const auto multirotor_sim_api = static_cast<const MultirotorPawnSimApi*>(sim_api); return multirotor_sim_api->getVehicleApi(); }
AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.cpp/0
{ "file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.cpp", "repo_id": "AirSim", "token_count": 1648 }
40
fileFormatVersion: 2 guid: 31ca9a6d3b881974c8d8c580a7eb28ec timeCreated: 1462197775 licenseType: Store NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/Hexacopter_Body.mat.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/Hexacopter_Body.mat.meta", "repo_id": "AirSim", "token_count": 73 }
41
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &8816652036562285266 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 8816652036562285271} - component: {fileID: 8816652036562285264} - component: {fileID: 8816652036562285265} m_Layer: 0 m_Name: AirSimGlobal m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &8816652036562285271 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8816652036562285266} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 424.5, y: 209, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!114 &8816652036562285264 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8816652036562285266} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 4f94f1489f5742c4ca7028300be3e3be, type: 3} m_Name: m_EditorClassIdentifier: --- !u!114 &8816652036562285265 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 8816652036562285266} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: a37d6ba6b4883614792eb67cb89a8e56, type: 3} m_Name: m_EditorClassIdentifier: WeatherFXPrefab: {fileID: 8776546933388946425, guid: cce1188248fe1c14e91df7d371a539fc, type: 3}
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/AirSimGlobal.prefab/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/AirSimGlobal.prefab", "repo_id": "AirSim", "token_count": 830 }
42
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1001 &100100000 Prefab: m_ObjectHideFlags: 1 serializedVersion: 2 m_Modification: m_TransformParent: {fileID: 0} m_Modifications: [] m_RemovedComponents: [] m_ParentPrefab: {fileID: 0} m_RootGameObject: {fileID: 1710384515616978} m_IsPrefabParent: 1 --- !u!1 &1335699149097238 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4144780179476108} - component: {fileID: 20305062872731356} - component: {fileID: 114587572861546556} m_Layer: 0 m_Name: Window1Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1710384515616978 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4063369236267772} m_Layer: 0 m_Name: WindowCameras m_TagString: ViewCameras m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1868784033965392 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4515304435196716} - component: {fileID: 20204721389804002} - component: {fileID: 114626001588283240} m_Layer: 0 m_Name: Window2Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!1 &1937218337961112 GameObject: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} serializedVersion: 5 m_Component: - component: {fileID: 4561355121857128} - component: {fileID: 20659114684065910} - component: {fileID: 114971472141651402} m_Layer: 0 m_Name: Window3Camera m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4063369236267772 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1710384515616978} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: - {fileID: 4144780179476108} - {fileID: 4515304435196716} - {fileID: 4561355121857128} m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4144780179476108 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1335699149097238} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4063369236267772} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4515304435196716 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1868784033965392} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4063369236267772} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!4 &4561355121857128 Transform: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1937218337961112} m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 4063369236267772} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!20 &20204721389804002 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1868784033965392} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.29411766, g: 0.29411766, b: 0.29411766, a: 1} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294965759 m_RenderingPath: 1 m_TargetTexture: {fileID: 8400000, guid: b1339334589473548b8a4359d6e72454, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20305062872731356 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1335699149097238} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 1, g: 1, b: 1, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294965759 m_RenderingPath: 1 m_TargetTexture: {fileID: 8400000, guid: 3e2f16f77d6e1f248a7373bf0b951154, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 0 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!20 &20659114684065910 Camera: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1937218337961112} m_Enabled: 1 serializedVersion: 2 m_ClearFlags: 1 m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} m_NormalizedViewPortRect: serializedVersion: 2 x: 0 y: 0 width: 1 height: 1 near clip plane: 0.3 far clip plane: 1000 field of view: 60 orthographic: 0 orthographic size: 5 m_Depth: 0 m_CullingMask: serializedVersion: 2 m_Bits: 4294965759 m_RenderingPath: -1 m_TargetTexture: {fileID: 8400000, guid: ca5a26a47741d2943bf1ca546bffb563, type: 2} m_TargetDisplay: 0 m_TargetEye: 3 m_HDR: 0 m_AllowMSAA: 0 m_AllowDynamicResolution: 0 m_ForceIntoRT: 1 m_OcclusionCulling: 0 m_StereoConvergence: 10 m_StereoSeparation: 0.022 --- !u!114 &114587572861546556 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1335699149097238} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 3 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114626001588283240 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1868784033965392} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 5 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3} --- !u!114 &114971472141651402 MonoBehaviour: m_ObjectHideFlags: 1 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 100100000} m_GameObject: {fileID: 1937218337961112} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3} m_Name: m_EditorClassIdentifier: effect: 0 effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3}
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/WindowCameras.prefab/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/WindowCameras.prefab", "repo_id": "AirSim", "token_count": 3445 }
43
using System; using System.IO; using AirSimUnity; using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement; public class InitializeAirSim : MonoBehaviour { void Awake() { if (GetAirSimSettingsFileName() != string.Empty) { if(AirSimSettings.Initialize()) { switch (AirSimSettings.GetSettings().SimMode) { case "Car": { LoadSceneAsPerSimMode(AirSimSettings.GetSettings().SimMode); break; } case "Multirotor": { LoadSceneAsPerSimMode(AirSimSettings.GetSettings().SimMode); break; } case "": { break; } default: { Debug.LogError("'" + AirSimSettings.GetSettings().SimMode + "' is not a supported SimMode."); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif break; } } } } else { Debug.LogError("'Settings.json' file either not present or not configured properly."); #if UNITY_EDITOR EditorUtility.DisplayDialog("Missing 'Settings.json' file!!!", "'Settings.json' file either not present or not configured properly.", "Exit"); #endif Application.Quit(); } } public static string GetAirSimSettingsFileName() { string fileName = Application.dataPath + "\\..\\settings.json"; if (File.Exists(fileName)) { return fileName; } fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Path.Combine("AirSim", "settings.json")); string linuxFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Path.Combine("Documents/AirSim", "settings.json")); if (File.Exists(fileName)) { return fileName; } else if (File.Exists(linuxFileName)) { return linuxFileName; } if (CreateSettingsFileWithDefaultValues(fileName)) return fileName; else if (CreateSettingsFileWithDefaultValues(linuxFileName)) return linuxFileName; else return string.Empty; } private static bool CreateSettingsFileWithDefaultValues(string fileName) { var result = false; try { if (fileName.Substring(0, 5) == "/home") Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Documents/AirSim")); else Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "AirSim")); string content = "{\n \"SimMode\" : \"\", \n \"SettingsVersion\" : 1.2, \n \"SeeDocsAt\" : \"https://github.com/Microsoft/AirSim/blob/main/docs/settings.md\"\n}"; //settings file created at Documents\AirSim with name "setting.json". StreamWriter writer = new StreamWriter(File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write)); writer.WriteLine(content); writer.Close(); result = true; } catch (Exception ex) { Debug.LogError("Unable to create settings.json file @ " + fileName + " Error :- " + ex.Message); result = false; } return result; } private void LoadSceneAsPerSimMode(string load_name) { if (load_name == "Car") { AirSimSettings.GetSettings().SimMode = "Car"; SceneManager.LoadSceneAsync("Scenes/CarDemo", LoadSceneMode.Single); } else if (load_name == "Multirotor") { AirSimSettings.GetSettings().SimMode = "Multirotor"; SceneManager.LoadSceneAsync("Scenes/DroneDemo", LoadSceneMode.Single); } } }
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/InitializeAirSim.cs/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/InitializeAirSim.cs", "repo_id": "AirSim", "token_count": 2084 }
44
fileFormatVersion: 2 guid: 143128f730c3edd44bd3c7cd0baf09f1 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataManager.cs.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataManager.cs.meta", "repo_id": "AirSim", "token_count": 94 }
45
using System; using System.Collections.Generic; using AirSimUnity.DroneStructs; using UnityEngine; namespace AirSimUnity { /* * Drone component that is used to control the drone object in the scene. This is based on Vehicle class that is communicating with AirLib. * This class depends on the AirLib's drone controllers based on FastPhysics engine. The controller is being used based on setting.json file in Documents\AirSim * The drone can be controlled either through keyboard or through client api calls. * This data is being constantly exchanged between AirLib and Unity through PInvoke delegates. */ public class Drone : Vehicle { public Transform[] rotors; private List<RotorInfo> rotorInfos = new List<RotorInfo>(); private float rotationFactor = 0.1f; private new void Start() { base.Start(); for (int i = 0; i < rotors.Length; i++) { rotorInfos.Add(new RotorInfo()); } } private new void FixedUpdate() { if (isServerStarted) { if (resetVehicle) { rcData.Reset(); currentPose = poseFromAirLib; resetVehicle = false; } base.FixedUpdate(); DataManager.SetToUnity(poseFromAirLib.position, ref position); DataManager.SetToUnity(poseFromAirLib.orientation, ref rotation); transform.position = position; transform.rotation = rotation; currentPose = poseFromAirLib; for (int i = 0; i < rotors.Length; i++) { float rotorSpeed = (float) (rotorInfos[i].rotorSpeed * rotorInfos[i].rotorDirection * 180 / Math.PI * rotationFactor); rotors[i].Rotate(Vector3.up, rotorSpeed * Time.deltaTime, Space.Self); } } } private new void LateUpdate() { if (isServerStarted) { //Image capture is being done in base class base.LateUpdate(); } } public KinemticState GetKinematicState() { return airsimInterface.GetKinematicState(); } #region IVehicleInterface implementation // Sets the animation for rotors on the drone. This is being done by AirLib through Pinvoke calls public override bool SetRotorSpeed(int rotorIndex, RotorInfo rotorInfo) { rotorInfos[rotorIndex] = rotorInfo; return true; } //Gets the data specific to drones for saving in the text file along with the images at the time of recording public override DataRecorder.ImageData GetRecordingData() { DataRecorder.ImageData data; data.pose = currentPose; data.carData = new CarStructs.CarData(); data.image = null; return data; } #endregion IVehicleInterface implementation } }
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Vehicles/Multirotor/Drone.cs/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Vehicles/Multirotor/Drone.cs", "repo_id": "AirSim", "token_count": 1406 }
46
fileFormatVersion: 2 guid: f557b0d47a81a7a448a4c0d85b02e8ba folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather.meta", "repo_id": "AirSim", "token_count": 73 }
47
fileFormatVersion: 2 guid: d3236a44a708bd94c9c6113ce63afaa7 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials.meta/0
{ "file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials.meta", "repo_id": "AirSim", "token_count": 69 }
48
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!55 &1 PhysicsManager: m_ObjectHideFlags: 0 serializedVersion: 7 m_Gravity: {x: 0, y: -9.81, z: 0} m_DefaultMaterial: {fileID: 0} m_BounceThreshold: 2 m_SleepThreshold: 0.005 m_DefaultContactOffset: 0.01 m_DefaultSolverIterations: 6 m_DefaultSolverVelocityIterations: 1 m_QueriesHitBackfaces: 0 m_QueriesHitTriggers: 1 m_EnableAdaptiveForce: 0 m_ClothInterCollisionDistance: 0 m_ClothInterCollisionStiffness: 0 m_ContactsGeneration: 1 m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff m_AutoSimulation: 1 m_AutoSyncTransforms: 1 m_ClothInterCollisionSettingsToggle: 0 m_ContactPairsMode: 0 m_BroadphaseType: 0 m_WorldBounds: m_Center: {x: 0, y: 0, z: 0} m_Extent: {x: 250, y: 250, z: 250} m_WorldSubdivisions: 8
AirSim/Unity/UnityDemo/ProjectSettings/DynamicsManager.asset/0
{ "file_path": "AirSim/Unity/UnityDemo/ProjectSettings/DynamicsManager.asset", "repo_id": "AirSim", "token_count": 401 }
49
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/SceneComponent.h" #include "ObjectFilter.h" #include "DetectionComponent.generated.h" USTRUCT() struct FDetectionInfo { GENERATED_BODY() UPROPERTY() AActor* Actor; UPROPERTY() FBox2D Box2D; UPROPERTY() FBox Box3D; UPROPERTY() FTransform RelativeTransform; }; UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent)) class AIRSIM_API UDetectionComponent : public USceneComponent { GENERATED_BODY() public: // Sets default values for this component's properties UDetectionComponent(); protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; const TArray<FDetectionInfo>& getDetections(); void addMeshName(const std::string& mesh_name); void setFilterRadius(const float radius_cm); void clearMeshNames(); private: bool calcBoundingFromViewInfo(AActor* actor, FBox2D& box_out); FVector getRelativeLocation(FVector in_location); FRotator getRelativeRotation(FVector in_location, FRotator in_rotation); public: UPROPERTY() UTextureRenderTarget2D* texture_target_; private: UPROPERTY() FObjectFilter object_filter_; UPROPERTY(EditAnywhere, Category = "Tracked Actors") float max_distance_to_camera_; UPROPERTY() USceneCaptureComponent2D* scene_capture_component_2D_; UPROPERTY() TArray<FDetectionInfo> cached_detections_; };
AirSim/Unreal/Plugins/AirSim/Source/DetectionComponent.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/DetectionComponent.h", "repo_id": "AirSim", "token_count": 601 }
50
#pragma once #include "CoreMinimal.h" #include "HAL/Runnable.h" #include "AirBlueprintLib.h" #include "api/VehicleSimApiBase.hpp" #include "Recording/RecordingFile.h" #include "physics/Kinematics.hpp" #include <memory> #include "common/ClockFactory.hpp" #include "common/AirSimSettings.hpp" #include "common/WorkerThread.hpp" class FRecordingThread : public FRunnable { public: typedef msr::airlib::AirSimSettings::RecordingSetting RecordingSetting; typedef msr::airlib::VehicleSimApiBase VehicleSimApiBase; typedef msr::airlib::ImageCaptureBase ImageCaptureBase; public: FRecordingThread(); virtual ~FRecordingThread(); static void init(); static void startRecording(const RecordingSetting& settings, const common_utils::UniqueValueMap<std::string, VehicleSimApiBase*>& vehicle_sim_apis); static void stopRecording(); static void killRecording(); static bool isRecording(); protected: virtual bool Init() override; virtual uint32 Run() override; virtual void Stop() override; virtual void Exit() override; private: FThreadSafeCounter stop_task_counter_; static std::unique_ptr<FRecordingThread> running_instance_; static std::unique_ptr<FRecordingThread> finishing_instance_; static msr::airlib::WorkerThreadSignal finishing_signal_; static bool first_; static std::unique_ptr<FRecordingThread> instance_; std::unique_ptr<FRunnableThread> thread_; RecordingSetting settings_; std::unique_ptr<RecordingFile> recording_file_; common_utils::UniqueValueMap<std::string, VehicleSimApiBase*> vehicle_sim_apis_; std::unordered_map<std::string, const ImageCaptureBase*> image_captures_; std::unordered_map<std::string, msr::airlib::Pose> last_poses_; msr::airlib::TTimePoint last_screenshot_on_; bool is_ready_; };
AirSim/Unreal/Plugins/AirSim/Source/Recording/RecordingThread.h/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Recording/RecordingThread.h", "repo_id": "AirSim", "token_count": 669 }
51
#include "TextureShuffleActor.h" void ATextureShuffleActor::SwapTexture_Implementation(int tex_id, int component_id, int material_id) { if (SwappableTextures.Num() < 1) return; if (!MaterialCacheInitialized) { TArray<UStaticMeshComponent*> components; GetComponents<UStaticMeshComponent>(components); NumComponents = components.Num(); DynamicMaterialInstances.Init(nullptr, components[component_id]->GetNumMaterials()); MaterialCacheInitialized = true; } if (NumComponents == 0 || DynamicMaterialInstances.Num() == 0) return; tex_id %= SwappableTextures.Num(); component_id %= NumComponents; material_id %= DynamicMaterialInstances.Num(); if (DynamicMaterialInstances[material_id] == nullptr) { DynamicMaterialInstances[material_id] = UMaterialInstanceDynamic::Create(DynamicMaterial, this); TArray<UStaticMeshComponent*> components; GetComponents<UStaticMeshComponent>(components); components[component_id]->SetMaterial(material_id, DynamicMaterialInstances[material_id]); } DynamicMaterialInstances[material_id]->SetTextureParameterValue("TextureParameter", SwappableTextures[tex_id]); }
AirSim/Unreal/Plugins/AirSim/Source/TextureShuffleActor.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/TextureShuffleActor.cpp", "repo_id": "AirSim", "token_count": 419 }
52
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CarWheelFront.h" #include "TireConfig.h" #include "UObject/ConstructorHelpers.h" UCarWheelFront::UCarWheelFront() { ShapeRadius = 18.f; ShapeWidth = 15.0f; Mass = 20.0f; DampingRate = 0.25f; bAffectedByHandbrake = false; SteerAngle = 40.f; // Setup suspension forces SuspensionForceOffset = 0.0f; SuspensionMaxRaise = 10.0f; SuspensionMaxDrop = 10.0f; SuspensionNaturalFrequency = 9.0f; SuspensionDampingRatio = 1.05f; // Find the tire object and set the data for it static ConstructorHelpers::FObjectFinder<UTireConfig> TireData(TEXT("/AirSim/VehicleAdv/Vehicle/WheelData/Vehicle_FrontTireConfig.Vehicle_FrontTireConfig")); TireConfig = TireData.Object; }
AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarWheelFront.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarWheelFront.cpp", "repo_id": "AirSim", "token_count": 306 }
53
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "SimModeWorldMultiRotor.h" #include "UObject/ConstructorHelpers.h" #include "Logging/MessageLog.h" #include "Engine/World.h" #include "GameFramework/PlayerController.h" #include "AirBlueprintLib.h" #include "vehicles/multirotor/api/MultirotorApiBase.hpp" #include "MultirotorPawnSimApi.h" #include "physics/PhysicsBody.hpp" #include "common/ClockFactory.hpp" #include <memory> #include "vehicles/multirotor/api/MultirotorRpcLibServer.hpp" #include "common/SteppableClock.hpp" void ASimModeWorldMultiRotor::BeginPlay() { Super::BeginPlay(); //let base class setup physics world initializeForPlay(); } void ASimModeWorldMultiRotor::EndPlay(const EEndPlayReason::Type EndPlayReason) { //stop physics thread before we dismantle stopAsyncUpdator(); Super::EndPlay(EndPlayReason); } void ASimModeWorldMultiRotor::setupClockSpeed() { typedef msr::airlib::ClockFactory ClockFactory; float clock_speed = getSettings().clock_speed; //setup clock in ClockFactory std::string clock_type = getSettings().clock_type; if (clock_type == "ScalableClock") { //scalable clock returns interval same as wall clock but multiplied by a scale factor ClockFactory::get(std::make_shared<msr::airlib::ScalableClock>(clock_speed == 1 ? 1 : 1 / clock_speed)); } else if (clock_type == "SteppableClock") { //steppable clock returns interval that is a constant number irrespective of wall clock //we can either multiply this fixed interval by scale factor to speed up/down the clock //but that would cause vehicles like quadrotors to become unstable //so alternative we use here is instead to scale control loop frequency. The downside is that //depending on compute power available, we will max out control loop frequency and therefore can no longer //get increase in clock speed //Approach 1: scale clock period, no longer used now due to quadrotor instability //ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>( //static_cast<msr::airlib::TTimeDelta>(getPhysicsLoopPeriod() * 1E-9 * clock_speed))); //Approach 2: scale control loop frequency if clock is speeded up if (clock_speed >= 1) { ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>( static_cast<msr::airlib::TTimeDelta>(getPhysicsLoopPeriod() * 1E-9))); //no clock_speed multiplier setPhysicsLoopPeriod(getPhysicsLoopPeriod() / static_cast<long long>(clock_speed)); } else { //for slowing down, this don't generate instability ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>( static_cast<msr::airlib::TTimeDelta>(getPhysicsLoopPeriod() * 1E-9 * clock_speed))); } } else throw std::invalid_argument(common_utils::Utils::stringf( "clock_type %s is not recognized", clock_type.c_str())); } //-------------------------------- overrides -----------------------------------------------// std::unique_ptr<msr::airlib::ApiServerBase> ASimModeWorldMultiRotor::createApiServer() const { #ifdef AIRLIB_NO_RPC return ASimModeBase::createApiServer(); #else return std::unique_ptr<msr::airlib::ApiServerBase>(new msr::airlib::MultirotorRpcLibServer( getApiProvider(), getSettings().api_server_address, getSettings().api_port)); #endif } void ASimModeWorldMultiRotor::getExistingVehiclePawns(TArray<AActor*>& pawns) const { UAirBlueprintLib::FindAllActor<TVehiclePawn>(this, pawns); } bool ASimModeWorldMultiRotor::isVehicleTypeSupported(const std::string& vehicle_type) const { return ((vehicle_type == AirSimSettings::kVehicleTypeSimpleFlight) || (vehicle_type == AirSimSettings::kVehicleTypePX4) || (vehicle_type == AirSimSettings::kVehicleTypeArduCopterSolo) || (vehicle_type == AirSimSettings::kVehicleTypeArduCopter)); } std::string ASimModeWorldMultiRotor::getVehiclePawnPathName(const AirSimSettings::VehicleSetting& vehicle_setting) const { //decide which derived BP to use std::string pawn_path = vehicle_setting.pawn_path; if (pawn_path == "") pawn_path = "DefaultQuadrotor"; return pawn_path; } PawnEvents* ASimModeWorldMultiRotor::getVehiclePawnEvents(APawn* pawn) const { return static_cast<TVehiclePawn*>(pawn)->getPawnEvents(); } const common_utils::UniqueValueMap<std::string, APIPCamera*> ASimModeWorldMultiRotor::getVehiclePawnCameras( APawn* pawn) const { return (static_cast<const TVehiclePawn*>(pawn))->getCameras(); } void ASimModeWorldMultiRotor::initializeVehiclePawn(APawn* pawn) { static_cast<TVehiclePawn*>(pawn)->initializeForBeginPlay(); } std::unique_ptr<PawnSimApi> ASimModeWorldMultiRotor::createVehicleSimApi( const PawnSimApi::Params& pawn_sim_api_params) const { auto vehicle_sim_api = std::unique_ptr<PawnSimApi>(new MultirotorPawnSimApi(pawn_sim_api_params)); vehicle_sim_api->initialize(); //For multirotors the vehicle_sim_api are in PhysicsWOrld container and then get reseted when world gets reseted //vehicle_sim_api->reset(); return vehicle_sim_api; } msr::airlib::VehicleApiBase* ASimModeWorldMultiRotor::getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params, const PawnSimApi* sim_api) const { const auto multirotor_sim_api = static_cast<const MultirotorPawnSimApi*>(sim_api); return multirotor_sim_api->getVehicleApi(); }
AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.cpp/0
{ "file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Multirotor/SimModeWorldMultiRotor.cpp", "repo_id": "AirSim", "token_count": 2099 }
54
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "VmName": { "type": "string", "metadata": { "description": "Name for the VM can be whatever you want, but can't be changed once the VM is created." } }, "AdminUsername": { "type": "string", "metadata": { "description": "Admin user name for the VM." }, "defaultValue": "AzureUser" }, "AdminPassword": { "type": "securestring", "metadata": { "description": "Admin user password for the VM." } }, "VmSize": { "type": "string", "metadata": { "description": "Desired Size of the VM (NV-series installs NVIDIA GPU drivers in WDDM mode for graphical display by default)." }, "defaultValue": "Standard_NV6", "allowedValues": [ "Standard_NV6_Promo", "Standard_NV6", "Standard_NV12", "Standard_NV24" ] }, "ScriptLocation": { "type": "string", "metadata": { "description": "Location of the setup script" }, "defaultValue": "https://raw.githubusercontent.com/microsoft/airsim/main/azure/azure-env-creation" }, "ScriptFileName": { "type": "string", "metadata": { "description": "Name of the setup script" }, "defaultValue": "configure-vm.ps1" } }, "variables": { "NetworkInterfaceCardName": "[concat(parameters('VmName'),'-nic')]", "PublicIPAddressName": "[concat(parameters('VmName'),'-ip')]", "NetworkSecurityGroupName": "[concat(parameters('VmName'),'-nsg')]", "VirtualNetworkName": "[concat(parameters('VmName'),'-vnet')]" }, "resources": [ { "type": "Microsoft.Network/networkSecurityGroups", "apiVersion": "2019-12-01", "name": "[variables('NetworkSecurityGroupName')]", "location": "[resourceGroup().location]", "properties": { "securityRules": [ { "name": "RDP", "properties": { "protocol": "Tcp", "sourcePortRange": "*", "destinationPortRange": "3389", "sourceAddressPrefix": "*", "destinationAddressPrefix": "*", "access": "Allow", "priority": 300, "direction": "Inbound" } }, { "name": "SSH", "properties": { "protocol": "Tcp", "sourcePortRange": "*", "destinationPortRange": "22", "sourceAddressPrefix": "*", "destinationAddressPrefix": "*", "access": "Allow", "priority": 320, "direction": "Inbound" } } ] } }, { "type": "Microsoft.Network/virtualNetworks/subnets", "apiVersion": "2019-12-01", "name": "[concat(variables('VirtualNetworkName'), '/default')]", "dependsOn": [ "[resourceId('Microsoft.Network/virtualNetworks', variables('VirtualNetworkName'))]" ], "properties": { "addressPrefix": "10.0.0.0/24" } }, { "type": "Microsoft.Network/virtualNetworks", "apiVersion": "2019-12-01", "name": "[variables('VirtualNetworkName')]", "location": "[resourceGroup().location]", "properties": { "addressSpace": { "addressPrefixes": [ "10.0.0.0/24" ] }, "subnets": [ { "name": "default", "properties": { "addressPrefix": "10.0.0.0/24" } } ] } }, { "type": "Microsoft.Network/publicIPAddresses", "apiVersion": "2019-12-01", "name": "[variables('PublicIPAddressName')]", "location": "[resourceGroup().location]", "properties": { "publicIPAllocationMethod": "Dynamic" } }, { "type": "Microsoft.Network/networkInterfaces", "apiVersion": "2019-12-01", "name": "[variables('NetworkInterfaceCardName')]", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Network/publicIPAddresses', variables('PublicIPAddressName'))]", "[resourceId('Microsoft.Network/networkSecurityGroups', variables('NetworkSecurityGroupName'))]", "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('VirtualNetworkName'), 'default')]" ], "properties": { "ipConfigurations": [ { "name": "ipconfig1", "properties": { "publicIPAddress": { "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('PublicIPAddressName'))]" }, "subnet": { "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('VirtualNetworkName'), 'default')]" } } } ], "networkSecurityGroup": { "id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('NetworkSecurityGroupName'))]" } } }, { "type": "Microsoft.Compute/virtualMachines", "apiVersion": "2019-07-01", "name": "[parameters('VmName')]", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Network/networkInterfaces', variables('NetworkInterfaceCardName'))]" ], "properties": { "hardwareProfile": { "vmSize": "[parameters('vmSize')]" }, "storageProfile": { "imageReference": { "publisher": "MicrosoftWindowsDesktop", "offer": "Windows-10", "sku": "rs5-pro", "version": "latest" }, "osDisk": { "osType": "Windows", "name": "[concat(parameters('VmName'), '_OsDisk')]", "createOption": "FromImage", "caching": "ReadWrite" } }, "osProfile": { "computerName": "[parameters('VmName')]", "adminUsername": "[parameters('AdminUsername')]", "adminPassword": "[parameters('AdminPassword')]" }, "networkProfile": { "networkInterfaces": [ { "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('NetworkInterfaceCardName'))]" } ] } } }, { "name": "[concat(parameters('VmName'),'/GPUDrivers')]", "type": "Microsoft.Compute/virtualMachines/extensions", "location": "[resourceGroup().location]", "apiVersion": "2019-07-01", "dependsOn": [ "[resourceId('Microsoft.Compute/virtualMachines/', parameters('VmName'))]" ], "properties": { "publisher": "Microsoft.HpcCompute", "type": "NvidiaGpuDriverWindows", "typeHandlerVersion": "1.3", "autoUpgradeMinorVersion": true, "settings": { } } }, { "name": "[concat(parameters('VmName'),'/SetupScript')]", "apiVersion": "2019-07-01", "type": "Microsoft.Compute/virtualMachines/extensions", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Compute/virtualMachines/extensions', parameters('VmName'), 'GPUDrivers')]" ], "properties": { "publisher": "Microsoft.Compute", "type": "CustomScriptExtension", "typeHandlerVersion": "1.10", "autoUpgradeMinorVersion": true, "settings": { "fileUris": [ "[concat(parameters('ScriptLocation'), '/' , parameters('ScriptFileName'))]" ], "commandToExecute": "[concat('powershell.exe -ExecutionPolicy bypass -File ./', parameters('ScriptFileName'))]" }, "protectedSettings": { } } } ], "outputs": { } }
AirSim/azure/azure-env-creation/vm-arm-template.json/0
{ "file_path": "AirSim/azure/azure-env-creation/vm-arm-template.json", "repo_id": "AirSim", "token_count": 5722 }
55
# Camera Views The camera views that are shown on screen are the camera views you can fetch via the [simGetImages API](image_apis.md). ![Cameras](images/cameras.png) From left to right is the depth view, segmentation view and the FPV view. See [Image APIs](image_apis.md) for description of various available views. ## Turning ON/OFF Views Press F1 key to see keyboard shortcuts for turning on/off any or all views. You can also select various view modes there, such as "Fly with Me" mode, FPV mode and "Ground View" mode. ## Controlling Manual Camera You can switch to manual camera control by pressing the M key. While manual camera control mode is selected, you can use the following keys to control the camera: |Key|Action| ---|--- |Arrow keys|move the camera forward/back and left/right| |Page up/down|move the camera up/down| |W/A/S/D|control pitch up/down and yaw left/right| |Left shift|increase movement speed| |Left control|decrease movement speed| ## Configuring Sub-Windows Now you can select what is shown by each of above sub windows. For instance, you can chose to show surface normals in first window (instead of depth) and disparity in second window (instead of segmentation). Below is the settings value you can use in [settings.json](settings.md): ``` { "SubWindows": [ {"WindowID": 1, "CameraName": "0", "ImageType": 5, "VehicleName": "", "Visible": false}, {"WindowID": 2, "CameraName": "0", "ImageType": 3, "VehicleName": "", "Visible": false} ] } ``` ## Performance Impact *Note*: This section is outdated and has not been updated for new performance enhancement changes. Now rendering these views does impact the FPS performance of the game, since this is additional work for the GPU. The following shows the impact on FPS when you open these views. ![fps](images/fps_views.png) This is measured on Intel core i7 computer with 32 gb RAM and a GeForce GTX 1080 graphics card running the Modular Neighborhood map, using cooked debug bits, no debugger or GameEditor open. The normal state with no subviews open is measuring around 16 ms per frame, which means it is keeping a nice steady 60 FPS (which is the target FPS). As it climbs up to 35ms the FPS drops to around 28 frames per second, spiking to 40ms means a few drops to 25 fps. The simulator can still function and fly correctly when all this is going on even in the worse case because the physics is decoupled from the rendering. However if the delay gets too high such that the communication with PX4 hardware is interrupted due to overly busy CPU then the flight can stall due to timeout in the offboard control messages. On the computer where this was measured the drone could fly the path.py program without any problems with all views open, and with 3 python scripts running to capture each view type. But there was one stall during this flight, but it recovered gracefully and completed the path. So it was right on the limit. The following shows the impact on CPU, perhaps a bit surprisingly, the CPU impact is also non trivial. ![fps](images/cpu_views.png)
AirSim/docs/camera_views.md/0
{ "file_path": "AirSim/docs/camera_views.md", "repo_id": "AirSim", "token_count": 803 }
56
# Busy Hard Drive It is not required, but we recommend running your Unreal Environment on a Solid State Drive (SSD). Between debugging, logging, and Unreal asset loading the hard drive can become your bottle neck. It is normal that your hard drive will be slammed while Unreal is loading the environment, but if your hard drive performance looks like this while the Unreal game is running then you will probably not get a good flying experience. ![Busy Hard Drive](images/busy_hard_drive.png) In fact, if the hard drive is this busy, chances are the drone will not fly properly at all. For some unknown reason this I/O bottle neck also interferes with the drone control loop and if that loop doesn't run at a high rate (300-500 Hz) then the drone will not fly. Not surprising, the control loop inside the PX4 firmware that runs on a Pixhawk flight controller runs at 1000 Hz. ### Reducing I/O If you can't whip off to Fry's Electronics and pick up an overpriced super fast SSD this weekend, then the following steps can be taken to reduce the hard drive I/O: 1. First run the Unreal Environment using Cooked content outside of the UE Editor or any debugging environment, and package the content to your fastest SSD drive. You can do that using this menu option: ![Package Unreal Project](images/package_unreal.png) 2. If you must use the UE editor (because you are actively modifying game assets), then at least don't run that in a debugger. If you are using Visual Studio use start without debugging. 3. If you must debug the app, and you are using Visual Studio debugger, stop then Visual Studio from logging Intellitrace information. Go to Tools/Options/Debugging/Intellitrace, and turn off the main checkbox. 4. Turn off any [Unreal Analytics](https://docs.unrealengine.com/latest/INT/Gameplay/Analytics/index.html) that your environment may have enabled, especially any file logging. ### I/O from Page Faults If your system is running out of RAM it may start paging memory to disk. If your operating system has enabled paging to disk, make sure it is paging to your fastest SSD. Or if you have enough RAM disable paging all together. In fact, if you disable paging and the game stops working you will know for sure you are running out of RAM. Obviously, shutting down any other unnecessary apps should also free up memory so you don't run out. ### Ideal Runtime performance This is what my slow hard drive looks like when flying from UE editor. You can see it's very busy, but the drone still flies ok: ![Package Unreal Project](images/ue_hard_drive.png) This is what my fast SSD looks like when the drone is flying in an Unreal Cooked app (no UE editor, no debugger). Not surprisingly it is flying perfectly in this case: ![Package Unreal Project](images/cooked_ssd.png)
AirSim/docs/hard_drive.md/0
{ "file_path": "AirSim/docs/hard_drive.md", "repo_id": "AirSim", "token_count": 709 }
57
# Runtime Texture Swapping ## How to Make An Actor Retexturable To be made texture-swappable, an actor must derive from the parent class TextureShuffleActor. The parent class can be set via the settings tab in the actor's blueprint. ![Parent Class](images/tex_shuffle_actor.png) After setting the parent class to TextureShuffActor, the object gains the member DynamicMaterial. DynamicMaterial needs to be set--on all actor instances in the scene--to TextureSwappableMaterial. Warning: Statically setting the Dynamic Material in the blueprint class may cause rendering errors. It seems to work better to set it on all the actor instances in the scene, using the details panel. ![TextureSwappableMaterial](images/tex_swap_material.png) ## How to Define the Set(s) of Textures to Choose From Typically, certain subsets of actors will share a set of texture options with each other. (e.g. walls that are part of the same building) It's easy to set up these groupings by using Unreal Engine's group editing functionality. Select all the instances that should have the same texture selection, and add the textures to all of them simultaneously via the Details panel. Use the same technique to add descriptive tags to groups of actors, which will be used to address them in the API. ![Group Editing](images/tex_swap_group_editing.png) It's ideal to work from larger groupings to smaller groupings, simply deselecting actors to narrow down the grouping as you go, and applying any individual actor properties last. ![Subset Editing](images/tex_swap_subset.png) ## How to Swap Textures from the API The following API is available in C++ and python. (C++ shown) ```C++ std::vector<std::string> simSwapTextures(const std::string& tags, int tex_id); ``` The string of "," or ", " delimited tags identifies on which actors to perform the swap. The tex_id indexes the array of textures assigned to each actor undergoing a swap. The function will return the list of objects which matched the provided tags and had the texture swap perfomed. If tex_id is out-of-bounds for some object's texture set, it will be taken modulo the number of textures that were available. Demo (Python): ```Python import airsim import time c = airsim.client.MultirotorClient() print(c.simSwapTextures("furniture", 0)) time.sleep(2) print(c.simSwapTextures("chair", 1)) time.sleep(2) print(c.simSwapTextures("table", 1)) time.sleep(2) print(c.simSwapTextures("chair, right", 0)) ``` Results: ```bash ['RetexturableChair', 'RetexturableChair2', 'RetexturableTable'] ['RetexturableChair', 'RetexturableChair2'] ['RetexturableTable'] ['RetexturableChair2'] ``` ![Demo](images/tex_swap_demo.gif) Note that in this example, different textures were chosen on each actor for the same index value. You can also use the `simSetObjectMaterial` and `simSetObjectMaterialFromTexture` APIs to set an object's material to any material asset or filepath of a texture. For more information on using these APIs, see [Texture APIs](apis.md#texture-apis).
AirSim/docs/retexturing.md/0
{ "file_path": "AirSim/docs/retexturing.md", "repo_id": "AirSim", "token_count": 824 }
58
# Who is Using AirSim? #### Would you like to see your own group or project here? Just add a [GitHub issue](https://github.com/microsoft/airsim/issues) with quick details and link to your website. * [NASA Ames Research Center – Systems Analysis Office](https://www.nasa.gov/ames) * [Astrobotic](https://www.astrobotic.com/technology) * [GRASP Lab, Univ of Pennsylvania](https://www.grasp.upenn.edu/) * [Department of Aeronautics and Astronautics, Stanford University](https://aa.stanford.edu/) * [Formula Technion](https://formula-technion.weebly.com/) * [Ghent University](https://www.ugent.be) * [ICARUS](http://icarus.upc.edu) * [UC, Santa Barbara](https://www.ucsb.edu/) * [WISE Lab, Univ of Waterloo](https://uwaterloo.ca/waterloo-intelligent-systems-engineering-lab/) * [HAMS project, MSR India](https://www.microsoft.com/en-us/research/project/hams/) * [Washington and Lee University](https://www.wlu.edu/) * [University of Oklahoma](https://www.ou.edu/) * [Robotics Institute, Carnegie Mellon University](https://www.ri.cmu.edu/) * [Texas A&M](https://www.tamu.edu/) * [Robotics and Perception Group, University of Zurich](http://rpg.ifi.uzh.ch/) * [National University of Ireland, Galway (NUIG)](http://www.nuigalway.ie/) * [Soda Mobility Technologies](http://sodacar.com) * [University of Cambridge](https://github.com/proroklab/private_flocking) * [Skoods - AI Autonomous cars competition](https://www.skoods.org/) * [Teledyne Scientific](https://arxiv.org/abs/2001.09822) * [BladeStack Systems](https://www.bladestack.nl) * [Unizar (Universidad de Zaragoza)](https://sites.google.com/unizar.es/poc-team/home) * [ClearSky LLC](https://deltacnc.ru/) * [Myned AI](https://www.myned.ai/) * [STPLS3D - University of Southern California Institute for Creative Technologies](http://www.stpls3d.com/) * [Central Michigan University](http://www.waynenterprises.com/research)
AirSim/docs/who_is_using.md/0
{ "file_path": "AirSim/docs/who_is_using.md", "repo_id": "AirSim", "token_count": 634 }
59
<?xml version="1.0"?> <package format="2"> <name>airsim_ros_pkgs</name> <version>0.0.1</version> <description>ROS Wrapper over AirSim's C++ client library</description> <maintainer email="ratneshmadaan@gmail.com">Ratnesh Madaan</maintainer> <license>MIT</license> <buildtool_depend>catkin</buildtool_depend> <!-- <build_depend>nodelet</build_depend> --> <build_depend>geometry_msgs</build_depend> <build_depend>image_transport</build_depend> <build_depend>message_generation</build_depend> <build_depend>message_runtime</build_depend> <build_depend>mavros_msgs</build_depend> <build_depend>nav_msgs</build_depend> <build_depend>roscpp</build_depend> <build_depend>rospy</build_depend> <build_depend>sensor_msgs</build_depend> <build_depend>std_msgs</build_depend> <build_depend>geographic_msgs</build_depend> <build_depend>geometry_msgs</build_depend> <build_depend>tf2_sensor_msgs</build_depend> <!-- <exec_depend>nodelet</exec_depend> --> <exec_depend>geometry_msgs</exec_depend> <exec_depend>image_transport</exec_depend> <exec_depend>message_generation</exec_depend> <exec_depend>message_runtime</exec_depend> <exec_depend>nav_msgs</exec_depend> <exec_depend>roscpp</exec_depend> <exec_depend>rospy</exec_depend> <exec_depend>sensor_msgs</exec_depend> <exec_depend>std_msgs</exec_depend> <exec_depend>joy</exec_depend> <!-- <export> <nodelet plugin="${prefix}/nodelet_plugins.xml" /> </export> --> </package>
AirSim/ros/src/airsim_ros_pkgs/package.xml/0
{ "file_path": "AirSim/ros/src/airsim_ros_pkgs/package.xml", "repo_id": "AirSim", "token_count": 559 }
60
# AirSim ROS Tutorials This page has moved [here](https://github.com/microsoft/AirSim/blob/main/docs/airsim_tutorial_pkgs.md).
AirSim/ros/src/airsim_tutorial_pkgs/README.md/0
{ "file_path": "AirSim/ros/src/airsim_tutorial_pkgs/README.md", "repo_id": "AirSim", "token_count": 44 }
61
#include "common/common_utils/StrictMode.hpp" STRICT_MODE_OFF //todo what does this do? #ifndef RPCLIB_MSGPACK #define RPCLIB_MSGPACK clmdep_msgpack #endif // !RPCLIB_MSGPACK #include "rpc/rpc_error.h" STRICT_MODE_ON #include "airsim_settings_parser.h" #include "common/AirSimSettings.hpp" #include "common/common_utils/FileSystem.hpp" #include "sensors/lidar/LidarSimpleParams.hpp" #include "rclcpp/rclcpp.hpp" #include "sensors/imu/ImuBase.hpp" #include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp" #include "vehicles/car/api/CarRpcLibClient.hpp" #include "yaml-cpp/yaml.h" #include <airsim_interfaces/msg/gimbal_angle_euler_cmd.hpp> #include <airsim_interfaces/msg/gimbal_angle_quat_cmd.hpp> #include <airsim_interfaces/msg/gps_yaw.hpp> #include <airsim_interfaces/srv/land.hpp> #include <airsim_interfaces/srv/land_group.hpp> #include <airsim_interfaces/srv/reset.hpp> #include <airsim_interfaces/srv/takeoff.hpp> #include <airsim_interfaces/srv/takeoff_group.hpp> #include <airsim_interfaces/msg/vel_cmd.hpp> #include <airsim_interfaces/msg/vel_cmd_group.hpp> #include <airsim_interfaces/msg/car_controls.hpp> #include <airsim_interfaces/msg/car_state.hpp> #include <airsim_interfaces/msg/environment.hpp> #include <chrono> #include <cv_bridge/cv_bridge.h> #include <geometry_msgs/msg/pose_stamped.hpp> #include <geometry_msgs/msg/transform_stamped.hpp> #include <geometry_msgs/msg/twist.hpp> #include <image_transport/image_transport.hpp> #include <iostream> #include <math.h> #include <math_common.h> #include <mavros_msgs/msg/state.hpp> #include <nav_msgs/msg/odometry.hpp> #include <opencv2/opencv.hpp> #include <sensor_msgs/msg/camera_info.hpp> #include <sensor_msgs/distortion_models.hpp> #include <sensor_msgs/msg/image.hpp> #include <sensor_msgs/image_encodings.hpp> #include <sensor_msgs/msg/imu.hpp> #include <sensor_msgs/msg/nav_sat_fix.hpp> #include <airsim_interfaces/msg/altimeter.hpp> //hector_uav_msgs defunct? #include <sensor_msgs/msg/magnetic_field.hpp> #include <sensor_msgs/msg/point_cloud2.hpp> #include <sensor_msgs/msg/range.hpp> #include <rosgraph_msgs/msg/clock.hpp> #include <std_srvs/srv/empty.hpp> #include <tf2/LinearMath/Matrix3x3.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_ros/buffer.h> #include <tf2_ros/static_transform_broadcaster.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_ros/transform_listener.h> #include <tf2/convert.h> #include <unordered_map> #include <memory> struct SimpleMatrix { int rows; int cols; double* data; SimpleMatrix(int rows, int cols, double* data) : rows(rows), cols(cols), data(data) { } }; struct VelCmd { double x; double y; double z; msr::airlib::DrivetrainType drivetrain; msr::airlib::YawMode yaw_mode; std::string vehicle_name; }; struct GimbalCmd { std::string vehicle_name; std::string camera_name; msr::airlib::Quaternionr target_quat; }; template <typename T> struct SensorPublisher { msr::airlib::SensorBase::SensorType sensor_type; std::string sensor_name; typename rclcpp::Publisher<T>::SharedPtr publisher; }; class AirsimROSWrapper { using AirSimSettings = msr::airlib::AirSimSettings; using SensorBase = msr::airlib::SensorBase; using CameraSetting = msr::airlib::AirSimSettings::CameraSetting; using CaptureSetting = msr::airlib::AirSimSettings::CaptureSetting; using LidarSetting = msr::airlib::AirSimSettings::LidarSetting; using VehicleSetting = msr::airlib::AirSimSettings::VehicleSetting; using ImageRequest = msr::airlib::ImageCaptureBase::ImageRequest; using ImageResponse = msr::airlib::ImageCaptureBase::ImageResponse; using ImageType = msr::airlib::ImageCaptureBase::ImageType; public: enum class AIRSIM_MODE : unsigned { DRONE, CAR }; AirsimROSWrapper(const std::shared_ptr<rclcpp::Node> nh, const std::shared_ptr<rclcpp::Node> nh_img, const std::shared_ptr<rclcpp::Node> nh_lidar, const std::string& host_ip); ~AirsimROSWrapper(){}; void initialize_airsim(); void initialize_ros(); bool is_used_lidar_timer_cb_queue_; bool is_used_img_timer_cb_queue_; private: // utility struct for a SINGLE robot class VehicleROS { public: virtual ~VehicleROS() {} std::string vehicle_name_; /// All things ROS rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr odom_local_pub_; rclcpp::Publisher<sensor_msgs::msg::NavSatFix>::SharedPtr global_gps_pub_; rclcpp::Publisher<airsim_interfaces::msg::Environment>::SharedPtr env_pub_; airsim_interfaces::msg::Environment env_msg_; std::vector<SensorPublisher<airsim_interfaces::msg::Altimeter>> barometer_pubs_; std::vector<SensorPublisher<sensor_msgs::msg::Imu>> imu_pubs_; std::vector<SensorPublisher<sensor_msgs::msg::NavSatFix>> gps_pubs_; std::vector<SensorPublisher<sensor_msgs::msg::MagneticField>> magnetometer_pubs_; std::vector<SensorPublisher<sensor_msgs::msg::Range>> distance_pubs_; std::vector<SensorPublisher<sensor_msgs::msg::PointCloud2>> lidar_pubs_; // handle lidar seperately for max performance as data is collected on its own thread/callback nav_msgs::msg::Odometry curr_odom_; sensor_msgs::msg::NavSatFix gps_sensor_msg_; std::vector<geometry_msgs::msg::TransformStamped> static_tf_msg_vec_; rclcpp::Time stamp_; std::string odom_frame_id_; }; class CarROS : public VehicleROS { public: msr::airlib::CarApiBase::CarState curr_car_state_; rclcpp::Subscription<airsim_interfaces::msg::CarControls>::SharedPtr car_cmd_sub_; rclcpp::Publisher<airsim_interfaces::msg::CarState>::SharedPtr car_state_pub_; airsim_interfaces::msg::CarState car_state_msg_; bool has_car_cmd_; msr::airlib::CarApiBase::CarControls car_cmd_; }; class MultiRotorROS : public VehicleROS { public: /// State msr::airlib::MultirotorState curr_drone_state_; rclcpp::Subscription<airsim_interfaces::msg::VelCmd>::SharedPtr vel_cmd_body_frame_sub_; rclcpp::Subscription<airsim_interfaces::msg::VelCmd>::SharedPtr vel_cmd_world_frame_sub_; rclcpp::Service<airsim_interfaces::srv::Takeoff>::SharedPtr takeoff_srvr_; rclcpp::Service<airsim_interfaces::srv::Land>::SharedPtr land_srvr_; bool has_vel_cmd_; VelCmd vel_cmd_; }; /// ROS timer callbacks void img_response_timer_cb(); // update images from airsim_client_ every nth sec void drone_state_timer_cb(); // update drone state from airsim_client_ every nth sec void lidar_timer_cb(); /// ROS subscriber callbacks void vel_cmd_world_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg, const std::string& vehicle_name); void vel_cmd_body_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg, const std::string& vehicle_name); void vel_cmd_group_body_frame_cb(const airsim_interfaces::msg::VelCmdGroup::SharedPtr msg); void vel_cmd_group_world_frame_cb(const airsim_interfaces::msg::VelCmdGroup::SharedPtr msg); void vel_cmd_all_world_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg); void vel_cmd_all_body_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg); // void vel_cmd_body_frame_cb(const airsim_interfaces::msg::VelCmd& msg, const std::string& vehicle_name); void gimbal_angle_quat_cmd_cb(const airsim_interfaces::msg::GimbalAngleQuatCmd::SharedPtr gimbal_angle_quat_cmd_msg); void gimbal_angle_euler_cmd_cb(const airsim_interfaces::msg::GimbalAngleEulerCmd::SharedPtr gimbal_angle_euler_cmd_msg); // commands void car_cmd_cb(const airsim_interfaces::msg::CarControls::SharedPtr msg, const std::string& vehicle_name); void update_commands(); // state, returns the simulation timestamp best guess based on drone state timestamp, airsim needs to return timestap for environment rclcpp::Time update_state(); void update_and_publish_static_transforms(VehicleROS* vehicle_ros); void publish_vehicle_state(); /// ROS service callbacks bool takeoff_srv_cb(const std::shared_ptr<airsim_interfaces::srv::Takeoff::Request> request, const std::shared_ptr<airsim_interfaces::srv::Takeoff::Response> response, const std::string& vehicle_name); bool takeoff_group_srv_cb(const std::shared_ptr<airsim_interfaces::srv::TakeoffGroup::Request> request, const std::shared_ptr<airsim_interfaces::srv::TakeoffGroup::Response> response); bool takeoff_all_srv_cb(const std::shared_ptr<airsim_interfaces::srv::Takeoff::Request> request, const std::shared_ptr<airsim_interfaces::srv::Takeoff::Response> response); bool land_srv_cb(const std::shared_ptr<airsim_interfaces::srv::Land::Request> request, const std::shared_ptr<airsim_interfaces::srv::Land::Response> response, const std::string& vehicle_name); bool land_group_srv_cb(const std::shared_ptr<airsim_interfaces::srv::LandGroup::Request> request, const std::shared_ptr<airsim_interfaces::srv::LandGroup::Response> response); bool land_all_srv_cb(const std::shared_ptr<airsim_interfaces::srv::Land::Request> request, const std::shared_ptr<airsim_interfaces::srv::Land::Response> response); bool reset_srv_cb(const std::shared_ptr<airsim_interfaces::srv::Reset::Request> request, const std::shared_ptr<airsim_interfaces::srv::Reset::Response> response); /// ROS tf broadcasters void publish_camera_tf(const ImageResponse& img_response, const rclcpp::Time& ros_time, const std::string& frame_id, const std::string& child_frame_id); void publish_odom_tf(const nav_msgs::msg::Odometry& odom_msg); /// camera helper methods sensor_msgs::msg::CameraInfo generate_cam_info(const std::string& camera_name, const CameraSetting& camera_setting, const CaptureSetting& capture_setting) const; std::shared_ptr<sensor_msgs::msg::Image> get_img_msg_from_response(const ImageResponse& img_response, const rclcpp::Time curr_ros_time, const std::string frame_id); std::shared_ptr<sensor_msgs::msg::Image> get_depth_img_msg_from_response(const ImageResponse& img_response, const rclcpp::Time curr_ros_time, const std::string frame_id); void process_and_publish_img_response(const std::vector<ImageResponse>& img_response_vec, const int img_response_idx, const std::string& vehicle_name); // methods which parse setting json ang generate ros pubsubsrv void create_ros_pubs_from_settings_json(); void convert_tf_msg_to_enu(geometry_msgs::msg::TransformStamped& tf_msg); void append_static_camera_tf(VehicleROS* vehicle_ros, const std::string& camera_name, const CameraSetting& camera_setting); void append_static_lidar_tf(VehicleROS* vehicle_ros, const std::string& lidar_name, const msr::airlib::LidarSimpleParams& lidar_setting); void append_static_vehicle_tf(VehicleROS* vehicle_ros, const VehicleSetting& vehicle_setting); void set_nans_to_zeros_in_pose(VehicleSetting& vehicle_setting) const; void set_nans_to_zeros_in_pose(const VehicleSetting& vehicle_setting, CameraSetting& camera_setting) const; void set_nans_to_zeros_in_pose(const VehicleSetting& vehicle_setting, LidarSetting& lidar_setting) const; geometry_msgs::msg::Transform get_camera_optical_tf_from_body_tf(const geometry_msgs::msg::Transform& body_tf) const; /// utils. todo parse into an Airlib<->ROS conversion class tf2::Quaternion get_tf2_quat(const msr::airlib::Quaternionr& airlib_quat) const; msr::airlib::Quaternionr get_airlib_quat(const geometry_msgs::msg::Quaternion& geometry_msgs_quat) const; msr::airlib::Quaternionr get_airlib_quat(const tf2::Quaternion& tf2_quat) const; nav_msgs::msg::Odometry get_odom_msg_from_kinematic_state(const msr::airlib::Kinematics::State& kinematics_estimated) const; nav_msgs::msg::Odometry get_odom_msg_from_multirotor_state(const msr::airlib::MultirotorState& drone_state) const; nav_msgs::msg::Odometry get_odom_msg_from_car_state(const msr::airlib::CarApiBase::CarState& car_state) const; airsim_interfaces::msg::CarState get_roscarstate_msg_from_car_state(const msr::airlib::CarApiBase::CarState& car_state) const; msr::airlib::Pose get_airlib_pose(const float& x, const float& y, const float& z, const msr::airlib::Quaternionr& airlib_quat) const; airsim_interfaces::msg::GPSYaw get_gps_msg_from_airsim_geo_point(const msr::airlib::GeoPoint& geo_point) const; sensor_msgs::msg::NavSatFix get_gps_sensor_msg_from_airsim_geo_point(const msr::airlib::GeoPoint& geo_point) const; sensor_msgs::msg::Imu get_imu_msg_from_airsim(const msr::airlib::ImuBase::Output& imu_data) const; airsim_interfaces::msg::Altimeter get_altimeter_msg_from_airsim(const msr::airlib::BarometerBase::Output& alt_data) const; sensor_msgs::msg::Range get_range_from_airsim(const msr::airlib::DistanceSensorData& dist_data) const; sensor_msgs::msg::PointCloud2 get_lidar_msg_from_airsim(const msr::airlib::LidarData& lidar_data, const std::string& vehicle_name, const std::string& sensor_name) const; sensor_msgs::msg::NavSatFix get_gps_msg_from_airsim(const msr::airlib::GpsBase::Output& gps_data) const; sensor_msgs::msg::MagneticField get_mag_msg_from_airsim(const msr::airlib::MagnetometerBase::Output& mag_data) const; airsim_interfaces::msg::Environment get_environment_msg_from_airsim(const msr::airlib::Environment::State& env_data) const; msr::airlib::GeoPoint get_origin_geo_point() const; VelCmd get_airlib_world_vel_cmd(const airsim_interfaces::msg::VelCmd& msg) const; VelCmd get_airlib_body_vel_cmd(const airsim_interfaces::msg::VelCmd& msg, const msr::airlib::Quaternionr& airlib_quat) const; geometry_msgs::msg::Transform get_transform_msg_from_airsim(const msr::airlib::Vector3r& position, const msr::airlib::AirSimSettings::Rotation& rotation); geometry_msgs::msg::Transform get_transform_msg_from_airsim(const msr::airlib::Vector3r& position, const msr::airlib::Quaternionr& quaternion); // not used anymore, but can be useful in future with an unreal camera calibration environment void read_params_from_yaml_and_fill_cam_info_msg(const std::string& file_name, sensor_msgs::msg::CameraInfo& cam_info) const; void convert_yaml_to_simple_mat(const YAML::Node& node, SimpleMatrix& m) const; // todo ugly template <typename T> const SensorPublisher<T> create_sensor_publisher(const std::string& sensor_type_name, const std::string& sensor_name, SensorBase::SensorType sensor_type, const std::string& topic_name, int QoS); private: // subscriber / services for ALL robots rclcpp::Subscription<airsim_interfaces::msg::VelCmd>::SharedPtr vel_cmd_all_body_frame_sub_; rclcpp::Subscription<airsim_interfaces::msg::VelCmd>::SharedPtr vel_cmd_all_world_frame_sub_; rclcpp::Service<airsim_interfaces::srv::Takeoff>::SharedPtr takeoff_all_srvr_; rclcpp::Service<airsim_interfaces::srv::Land>::SharedPtr land_all_srvr_; // todo - subscriber / services for a GROUP of robots, which is defined by a list of `vehicle_name`s passed in the ros msg / srv request rclcpp::Subscription<airsim_interfaces::msg::VelCmdGroup>::SharedPtr vel_cmd_group_body_frame_sub_; rclcpp::Subscription<airsim_interfaces::msg::VelCmdGroup>::SharedPtr vel_cmd_group_world_frame_sub_; rclcpp::Service<airsim_interfaces::srv::TakeoffGroup>::SharedPtr takeoff_group_srvr_; rclcpp::Service<airsim_interfaces::srv::LandGroup>::SharedPtr land_group_srvr_; AIRSIM_MODE airsim_mode_ = AIRSIM_MODE::DRONE; rclcpp::Service<airsim_interfaces::srv::Reset>::SharedPtr reset_srvr_; rclcpp::Publisher<airsim_interfaces::msg::GPSYaw>::SharedPtr origin_geo_point_pub_; // home geo coord of drones msr::airlib::GeoPoint origin_geo_point_; // gps coord of unreal origin airsim_interfaces::msg::GPSYaw origin_geo_point_msg_; // todo duplicate AirSimSettingsParser airsim_settings_parser_; std::unordered_map<std::string, std::unique_ptr<VehicleROS>> vehicle_name_ptr_map_; static const std::unordered_map<int, std::string> image_type_int_to_string_map_; bool is_vulkan_; // rosparam obtained from launch file. If vulkan is being used, we BGR encoding instead of RGB std::string host_ip_; std::unique_ptr<msr::airlib::RpcLibClientBase> airsim_client_; // seperate busy connections to airsim, update in their own thread msr::airlib::RpcLibClientBase airsim_client_images_; msr::airlib::RpcLibClientBase airsim_client_lidar_; std::shared_ptr<rclcpp::Node> nh_; std::shared_ptr<rclcpp::Node> nh_img_; std::shared_ptr<rclcpp::Node> nh_lidar_; // todo not sure if async spinners shuold be inside this class, or should be instantiated in airsim_node.cpp, and cb queues should be public // todo for multiple drones with multiple sensors, this won't scale. make it a part of VehicleROS? std::mutex control_mutex_; // gimbal control bool has_gimbal_cmd_; GimbalCmd gimbal_cmd_; /// ROS tf const std::string AIRSIM_FRAME_ID = "world_ned"; std::string world_frame_id_ = AIRSIM_FRAME_ID; const std::string AIRSIM_ODOM_FRAME_ID = "odom_local_ned"; const std::string ENU_ODOM_FRAME_ID = "odom_local_enu"; std::string odom_frame_id_ = AIRSIM_ODOM_FRAME_ID; std::shared_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster_; std::shared_ptr<tf2_ros::StaticTransformBroadcaster> static_tf_pub_; bool isENU_; std::shared_ptr<tf2_ros::Buffer> tf_buffer_; std::shared_ptr<tf2_ros::TransformListener> tf_listener_; /// ROS params double vel_cmd_duration_; /// ROS Timers. rclcpp::TimerBase::SharedPtr airsim_img_response_timer_; rclcpp::TimerBase::SharedPtr airsim_control_update_timer_; rclcpp::TimerBase::SharedPtr airsim_lidar_update_timer_; typedef std::pair<std::vector<ImageRequest>, std::string> airsim_img_request_vehicle_name_pair; std::vector<airsim_img_request_vehicle_name_pair> airsim_img_request_vehicle_name_pair_vec_; std::vector<image_transport::Publisher> image_pub_vec_; std::vector<rclcpp::Publisher<sensor_msgs::msg::CameraInfo>::SharedPtr> cam_info_pub_vec_; std::vector<sensor_msgs::msg::CameraInfo> camera_info_msg_vec_; /// ROS other publishers rclcpp::Publisher<rosgraph_msgs::msg::Clock>::SharedPtr clock_pub_; rosgraph_msgs::msg::Clock ros_clock_; bool publish_clock_; rclcpp::Subscription<airsim_interfaces::msg::GimbalAngleQuatCmd>::SharedPtr gimbal_angle_quat_cmd_sub_; rclcpp::Subscription<airsim_interfaces::msg::GimbalAngleEulerCmd>::SharedPtr gimbal_angle_euler_cmd_sub_; static constexpr char CAM_YML_NAME[] = "camera_name"; static constexpr char WIDTH_YML_NAME[] = "image_width"; static constexpr char HEIGHT_YML_NAME[] = "image_height"; static constexpr char K_YML_NAME[] = "camera_matrix"; static constexpr char D_YML_NAME[] = "distortion_coefficients"; static constexpr char R_YML_NAME[] = "rectification_matrix"; static constexpr char P_YML_NAME[] = "projection_matrix"; static constexpr char DMODEL_YML_NAME[] = "distortion_model"; };
AirSim/ros2/src/airsim_ros_pkgs/include/airsim_ros_wrapper.h/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/include/airsim_ros_wrapper.h", "repo_id": "AirSim", "token_count": 7437 }
62
#include <airsim_ros_wrapper.h> #include "common/AirSimSettings.hpp" #include <tf2_sensor_msgs/tf2_sensor_msgs.h> using namespace std::placeholders; constexpr char AirsimROSWrapper::CAM_YML_NAME[]; constexpr char AirsimROSWrapper::WIDTH_YML_NAME[]; constexpr char AirsimROSWrapper::HEIGHT_YML_NAME[]; constexpr char AirsimROSWrapper::K_YML_NAME[]; constexpr char AirsimROSWrapper::D_YML_NAME[]; constexpr char AirsimROSWrapper::R_YML_NAME[]; constexpr char AirsimROSWrapper::P_YML_NAME[]; constexpr char AirsimROSWrapper::DMODEL_YML_NAME[]; const std::unordered_map<int, std::string> AirsimROSWrapper::image_type_int_to_string_map_ = { { 0, "Scene" }, { 1, "DepthPlanar" }, { 2, "DepthPerspective" }, { 3, "DepthVis" }, { 4, "DisparityNormalized" }, { 5, "Segmentation" }, { 6, "SurfaceNormals" }, { 7, "Infrared" } }; AirsimROSWrapper::AirsimROSWrapper(const std::shared_ptr<rclcpp::Node> nh, const std::shared_ptr<rclcpp::Node> nh_img, const std::shared_ptr<rclcpp::Node> nh_lidar, const std::string& host_ip) : is_used_lidar_timer_cb_queue_(false) , is_used_img_timer_cb_queue_(false) , airsim_settings_parser_(host_ip) , host_ip_(host_ip) , airsim_client_(nullptr) , airsim_client_images_(host_ip) , airsim_client_lidar_(host_ip) , nh_(nh) , nh_img_(nh_img) , nh_lidar_(nh_lidar) , isENU_(false) , publish_clock_(false) { ros_clock_.clock = rclcpp::Time(0); if (AirSimSettings::singleton().simmode_name != AirSimSettings::kSimModeTypeCar) { airsim_mode_ = AIRSIM_MODE::DRONE; RCLCPP_INFO(nh_->get_logger(), "Setting ROS wrapper to DRONE mode"); } else { airsim_mode_ = AIRSIM_MODE::CAR; RCLCPP_INFO(nh_->get_logger(), "Setting ROS wrapper to CAR mode"); } tf_buffer_ = std::make_shared<tf2_ros::Buffer>(nh_->get_clock()); tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_); tf_broadcaster_ = std::make_shared<tf2_ros::TransformBroadcaster>(nh_); static_tf_pub_ = std::make_shared<tf2_ros::StaticTransformBroadcaster>(nh_); initialize_ros(); RCLCPP_INFO(nh_->get_logger(), "AirsimROSWrapper Initialized!"); } void AirsimROSWrapper::initialize_airsim() { // todo do not reset if already in air? try { if (airsim_mode_ == AIRSIM_MODE::DRONE) { airsim_client_ = std::unique_ptr<msr::airlib::RpcLibClientBase>(new msr::airlib::MultirotorRpcLibClient(host_ip_)); } else { airsim_client_ = std::unique_ptr<msr::airlib::RpcLibClientBase>(new msr::airlib::CarRpcLibClient(host_ip_)); } airsim_client_->confirmConnection(); airsim_client_images_.confirmConnection(); airsim_client_lidar_.confirmConnection(); for (const auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { airsim_client_->enableApiControl(true, vehicle_name_ptr_pair.first); // todo expose as rosservice? airsim_client_->armDisarm(true, vehicle_name_ptr_pair.first); // todo exposes as rosservice? } origin_geo_point_ = get_origin_geo_point(); // todo there's only one global origin geopoint for environment. but airsim API accept a parameter vehicle_name? inside carsimpawnapi.cpp, there's a geopoint being assigned in the constructor. by? origin_geo_point_msg_ = get_gps_msg_from_airsim_geo_point(origin_geo_point_); } catch (rpc::rpc_error& e) { std::string msg = e.get_error().as<std::string>(); RCLCPP_ERROR(nh_->get_logger(), "Exception raised by the API, something went wrong.\n%s", msg.c_str()); rclcpp::shutdown(); } } void AirsimROSWrapper::initialize_ros() { // ros params double update_airsim_control_every_n_sec; nh_->get_parameter("is_vulkan", is_vulkan_); nh_->get_parameter("update_airsim_control_every_n_sec", update_airsim_control_every_n_sec); nh_->get_parameter("publish_clock", publish_clock_); nh_->get_parameter_or("world_frame_id", world_frame_id_, world_frame_id_); odom_frame_id_ = world_frame_id_ == AIRSIM_FRAME_ID ? AIRSIM_ODOM_FRAME_ID : ENU_ODOM_FRAME_ID; nh_->get_parameter_or("odom_frame_id", odom_frame_id_, odom_frame_id_); isENU_ = (odom_frame_id_ == ENU_ODOM_FRAME_ID); nh_->get_parameter_or("coordinate_system_enu", isENU_, isENU_); vel_cmd_duration_ = 0.05; // todo rosparam // todo enforce dynamics constraints in this node as well? // nh_->get_parameter("max_vert_vel_", max_vert_vel_); // nh_->get_parameter("max_horz_vel", max_horz_vel_) nh_->declare_parameter("vehicle_name", rclcpp::ParameterValue("")); create_ros_pubs_from_settings_json(); airsim_control_update_timer_ = nh_->create_wall_timer(std::chrono::duration<double>(update_airsim_control_every_n_sec), std::bind(&AirsimROSWrapper::drone_state_timer_cb, this)); } void AirsimROSWrapper::create_ros_pubs_from_settings_json() { // subscribe to control commands on global nodehandle gimbal_angle_quat_cmd_sub_ = nh_->create_subscription<airsim_interfaces::msg::GimbalAngleQuatCmd>("~/gimbal_angle_quat_cmd", 50, std::bind(&AirsimROSWrapper::gimbal_angle_quat_cmd_cb, this, _1)); gimbal_angle_euler_cmd_sub_ = nh_->create_subscription<airsim_interfaces::msg::GimbalAngleEulerCmd>("~/gimbal_angle_euler_cmd", 50, std::bind(&AirsimROSWrapper::gimbal_angle_euler_cmd_cb, this, _1)); origin_geo_point_pub_ = nh_->create_publisher<airsim_interfaces::msg::GPSYaw>("~/origin_geo_point", 10); airsim_img_request_vehicle_name_pair_vec_.clear(); image_pub_vec_.clear(); cam_info_pub_vec_.clear(); camera_info_msg_vec_.clear(); vehicle_name_ptr_map_.clear(); size_t lidar_cnt = 0; image_transport::ImageTransport image_transporter(nh_); // iterate over std::map<std::string, std::unique_ptr<VehicleSetting>> vehicles; for (const auto& curr_vehicle_elem : AirSimSettings::singleton().vehicles) { auto& vehicle_setting = curr_vehicle_elem.second; auto curr_vehicle_name = curr_vehicle_elem.first; nh_->set_parameter(rclcpp::Parameter("vehicle_name", curr_vehicle_name)); set_nans_to_zeros_in_pose(*vehicle_setting); std::unique_ptr<VehicleROS> vehicle_ros = nullptr; if (airsim_mode_ == AIRSIM_MODE::DRONE) { vehicle_ros = std::unique_ptr<MultiRotorROS>(new MultiRotorROS()); } else { vehicle_ros = std::unique_ptr<CarROS>(new CarROS()); } vehicle_ros->odom_frame_id_ = curr_vehicle_name + "/" + odom_frame_id_; vehicle_ros->vehicle_name_ = curr_vehicle_name; append_static_vehicle_tf(vehicle_ros.get(), *vehicle_setting); const std::string topic_prefix = "~/" + curr_vehicle_name; vehicle_ros->odom_local_pub_ = nh_->create_publisher<nav_msgs::msg::Odometry>(topic_prefix + "/" + odom_frame_id_, 10); vehicle_ros->env_pub_ = nh_->create_publisher<airsim_interfaces::msg::Environment>(topic_prefix + "/environment", 10); vehicle_ros->global_gps_pub_ = nh_->create_publisher<sensor_msgs::msg::NavSatFix>(topic_prefix + "/global_gps", 10); if (airsim_mode_ == AIRSIM_MODE::DRONE) { auto drone = static_cast<MultiRotorROS*>(vehicle_ros.get()); // bind to a single callback. todo optimal subs queue length // bind multiple topics to a single callback, but keep track of which vehicle name it was by passing curr_vehicle_name as the 2nd argument std::function<void(const airsim_interfaces::msg::VelCmd::SharedPtr)> fcn_vel_cmd_body_frame_sub = std::bind(&AirsimROSWrapper::vel_cmd_body_frame_cb, this, _1, vehicle_ros->vehicle_name_); drone->vel_cmd_body_frame_sub_ = nh_->create_subscription<airsim_interfaces::msg::VelCmd>(topic_prefix + "/vel_cmd_body_frame", 1, fcn_vel_cmd_body_frame_sub); // todo ros::TransportHints().tcpNoDelay(); std::function<void(const airsim_interfaces::msg::VelCmd::SharedPtr)> fcn_vel_cmd_world_frame_sub = std::bind(&AirsimROSWrapper::vel_cmd_world_frame_cb, this, _1, vehicle_ros->vehicle_name_); drone->vel_cmd_world_frame_sub_ = nh_->create_subscription<airsim_interfaces::msg::VelCmd>(topic_prefix + "/vel_cmd_world_frame", 1, fcn_vel_cmd_world_frame_sub); std::function<bool(std::shared_ptr<airsim_interfaces::srv::Takeoff::Request>, std::shared_ptr<airsim_interfaces::srv::Takeoff::Response>)> fcn_takeoff_srvr = std::bind(&AirsimROSWrapper::takeoff_srv_cb, this, _1, _2, vehicle_ros->vehicle_name_); drone->takeoff_srvr_ = nh_->create_service<airsim_interfaces::srv::Takeoff>(topic_prefix + "/takeoff", fcn_takeoff_srvr); std::function<bool(std::shared_ptr<airsim_interfaces::srv::Land::Request>, std::shared_ptr<airsim_interfaces::srv::Land::Response>)> fcn_land_srvr = std::bind(&AirsimROSWrapper::land_srv_cb, this, _1, _2, vehicle_ros->vehicle_name_); drone->land_srvr_ = nh_->create_service<airsim_interfaces::srv::Land>(topic_prefix + "/land", fcn_land_srvr); // vehicle_ros.reset_srvr = nh_->create_service(curr_vehicle_name + "/reset",&AirsimROSWrapper::reset_srv_cb, this); } else { auto car = static_cast<CarROS*>(vehicle_ros.get()); std::function<void(const airsim_interfaces::msg::CarControls::SharedPtr)> fcn_car_cmd_sub = std::bind(&AirsimROSWrapper::car_cmd_cb, this, _1, vehicle_ros->vehicle_name_); car->car_cmd_sub_ = nh_->create_subscription<airsim_interfaces::msg::CarControls>(topic_prefix + "/car_cmd", 1, fcn_car_cmd_sub); car->car_state_pub_ = nh_->create_publisher<airsim_interfaces::msg::CarState>(topic_prefix + "/car_state", 10); } // iterate over camera map std::map<std::string, CameraSetting> .cameras; for (auto& curr_camera_elem : vehicle_setting->cameras) { auto& camera_setting = curr_camera_elem.second; auto& curr_camera_name = curr_camera_elem.first; set_nans_to_zeros_in_pose(*vehicle_setting, camera_setting); append_static_camera_tf(vehicle_ros.get(), curr_camera_name, camera_setting); // camera_setting.gimbal std::vector<ImageRequest> current_image_request_vec; current_image_request_vec.clear(); // iterate over capture_setting std::map<int, CaptureSetting> capture_settings for (const auto& curr_capture_elem : camera_setting.capture_settings) { auto& capture_setting = curr_capture_elem.second; // todo why does AirSimSettings::loadCaptureSettings calls AirSimSettings::initializeCaptureSettings() // which initializes default capture settings for _all_ NINE msr::airlib::ImageCaptureBase::ImageType if (!(std::isnan(capture_setting.fov_degrees))) { ImageType curr_image_type = msr::airlib::Utils::toEnum<ImageType>(capture_setting.image_type); // if scene / segmentation / surface normals / infrared, get uncompressed image with pixels_as_floats = false if (curr_image_type == ImageType::Scene || curr_image_type == ImageType::Segmentation || curr_image_type == ImageType::SurfaceNormals || curr_image_type == ImageType::Infrared) { current_image_request_vec.push_back(ImageRequest(curr_camera_name, curr_image_type, false, false)); } // if {DepthPlanar, DepthPerspective,DepthVis, DisparityNormalized}, get float image else { current_image_request_vec.push_back(ImageRequest(curr_camera_name, curr_image_type, true)); } const std::string camera_topic = topic_prefix + "/" + curr_camera_name + "/" + image_type_int_to_string_map_.at(capture_setting.image_type); image_pub_vec_.push_back(image_transporter.advertise(camera_topic, 1)); cam_info_pub_vec_.push_back(nh_->create_publisher<sensor_msgs::msg::CameraInfo>(camera_topic + "/camera_info", 10)); camera_info_msg_vec_.push_back(generate_cam_info(curr_camera_name, camera_setting, capture_setting)); } } // push back pair (vector of image captures, current vehicle name) airsim_img_request_vehicle_name_pair_vec_.push_back(std::make_pair(current_image_request_vec, curr_vehicle_name)); } // iterate over sensors for (auto& curr_sensor_map : vehicle_setting->sensors) { auto& sensor_name = curr_sensor_map.first; auto& sensor_setting = curr_sensor_map.second; if (sensor_setting->enabled) { switch (sensor_setting->sensor_type) { case SensorBase::SensorType::Barometer: { SensorPublisher<airsim_interfaces::msg::Altimeter> sensor_publisher = create_sensor_publisher<airsim_interfaces::msg::Altimeter>("Barometer", sensor_setting->sensor_name, sensor_setting->sensor_type, curr_vehicle_name + "/altimeter/" + sensor_name, 10); vehicle_ros->barometer_pubs_.emplace_back(sensor_publisher); break; } case SensorBase::SensorType::Imu: { SensorPublisher<sensor_msgs::msg::Imu> sensor_publisher = create_sensor_publisher<sensor_msgs::msg::Imu>("Imu", sensor_setting->sensor_name, sensor_setting->sensor_type, curr_vehicle_name + "/imu/" + sensor_name, 10); vehicle_ros->imu_pubs_.emplace_back(sensor_publisher); break; } case SensorBase::SensorType::Gps: { SensorPublisher<sensor_msgs::msg::NavSatFix> sensor_publisher = create_sensor_publisher<sensor_msgs::msg::NavSatFix>("Gps", sensor_setting->sensor_name, sensor_setting->sensor_type, curr_vehicle_name + "/gps/" + sensor_name, 10); vehicle_ros->gps_pubs_.emplace_back(sensor_publisher); break; } case SensorBase::SensorType::Magnetometer: { SensorPublisher<sensor_msgs::msg::MagneticField> sensor_publisher = create_sensor_publisher<sensor_msgs::msg::MagneticField>("Magnetometer", sensor_setting->sensor_name, sensor_setting->sensor_type, curr_vehicle_name + "/magnetometer/" + sensor_name, 10); vehicle_ros->magnetometer_pubs_.emplace_back(sensor_publisher); break; } case SensorBase::SensorType::Distance: { SensorPublisher<sensor_msgs::msg::Range> sensor_publisher = create_sensor_publisher<sensor_msgs::msg::Range>("Distance", sensor_setting->sensor_name, sensor_setting->sensor_type, curr_vehicle_name + "/distance/" + sensor_name, 10); vehicle_ros->distance_pubs_.emplace_back(sensor_publisher); break; } case SensorBase::SensorType::Lidar: { auto lidar_setting = *static_cast<LidarSetting*>(sensor_setting.get()); msr::airlib::LidarSimpleParams params; params.initializeFromSettings(lidar_setting); append_static_lidar_tf(vehicle_ros.get(), sensor_name, params); SensorPublisher<sensor_msgs::msg::PointCloud2> sensor_publisher = create_sensor_publisher<sensor_msgs::msg::PointCloud2>("Lidar", sensor_setting->sensor_name, sensor_setting->sensor_type, curr_vehicle_name + "/lidar/" + sensor_name, 10); vehicle_ros->lidar_pubs_.emplace_back(sensor_publisher); lidar_cnt += 1; break; } default: { throw std::invalid_argument("Unexpected sensor type"); } } } } vehicle_name_ptr_map_.emplace(curr_vehicle_name, std::move(vehicle_ros)); // allows fast lookup in command callbacks in case of a lot of drones } // add takeoff and land all services if more than 2 drones if (vehicle_name_ptr_map_.size() > 1 && airsim_mode_ == AIRSIM_MODE::DRONE) { takeoff_all_srvr_ = nh_->create_service<airsim_interfaces::srv::Takeoff>("~/all_robots/takeoff", std::bind(&AirsimROSWrapper::takeoff_all_srv_cb, this, _1, _2)); land_all_srvr_ = nh_->create_service<airsim_interfaces::srv::Land>("~/all_robots/land", std::bind(&AirsimROSWrapper::land_all_srv_cb, this, _1, _2)); vel_cmd_all_body_frame_sub_ = nh_->create_subscription<airsim_interfaces::msg::VelCmd>("~/all_robots/vel_cmd_body_frame", 1, std::bind(&AirsimROSWrapper::vel_cmd_all_body_frame_cb, this, _1)); vel_cmd_all_world_frame_sub_ = nh_->create_subscription<airsim_interfaces::msg::VelCmd>("~/all_robots/vel_cmd_world_frame", 1, std::bind(&AirsimROSWrapper::vel_cmd_all_world_frame_cb, this, _1)); vel_cmd_group_body_frame_sub_ = nh_->create_subscription<airsim_interfaces::msg::VelCmdGroup>("~/group_of_robots/vel_cmd_body_frame", 1, std::bind(&AirsimROSWrapper::vel_cmd_group_body_frame_cb, this, _1)); vel_cmd_group_world_frame_sub_ = nh_->create_subscription<airsim_interfaces::msg::VelCmdGroup>("~/group_of_robots/vel_cmd_world_frame", 1, std::bind(&AirsimROSWrapper::vel_cmd_group_world_frame_cb, this, _1)); takeoff_group_srvr_ = nh_->create_service<airsim_interfaces::srv::TakeoffGroup>("~/group_of_robots/takeoff", std::bind(&AirsimROSWrapper::takeoff_group_srv_cb, this, _1, _2)); land_group_srvr_ = nh_->create_service<airsim_interfaces::srv::LandGroup>("~/group_of_robots/land", std::bind(&AirsimROSWrapper::land_group_srv_cb, this, _1, _2)); } // todo add per vehicle reset in AirLib API reset_srvr_ = nh_->create_service<airsim_interfaces::srv::Reset>("~/reset", std::bind(&AirsimROSWrapper::reset_srv_cb, this, _1, _2)); if (publish_clock_) { clock_pub_ = nh_->create_publisher<rosgraph_msgs::msg::Clock>("~/clock", 1); } // if >0 cameras, add one more thread for img_request_timer_cb if (!airsim_img_request_vehicle_name_pair_vec_.empty()) { double update_airsim_img_response_every_n_sec; nh_->get_parameter("update_airsim_img_response_every_n_sec", update_airsim_img_response_every_n_sec); airsim_img_response_timer_ = nh_img_->create_wall_timer(std::chrono::duration<double>(update_airsim_img_response_every_n_sec), std::bind(&AirsimROSWrapper::img_response_timer_cb, this)); is_used_img_timer_cb_queue_ = true; } // lidars update on their own callback/thread at a given rate if (lidar_cnt > 0) { double update_lidar_every_n_sec; nh_->get_parameter("update_lidar_every_n_sec", update_lidar_every_n_sec); airsim_lidar_update_timer_ = nh_lidar_->create_wall_timer(std::chrono::duration<double>(update_lidar_every_n_sec), std::bind(&AirsimROSWrapper::lidar_timer_cb, this)); is_used_lidar_timer_cb_queue_ = true; } initialize_airsim(); } // QoS - The depth of the publisher message queue. // more details here - https://docs.ros.org/en/foxy/Concepts/About-Quality-of-Service-Settings.html template <typename T> const SensorPublisher<T> AirsimROSWrapper::create_sensor_publisher(const std::string& sensor_type_name, const std::string& sensor_name, SensorBase::SensorType sensor_type, const std::string& topic_name, int QoS) { RCLCPP_INFO_STREAM(nh_->get_logger(), sensor_type_name); SensorPublisher<T> sensor_publisher; sensor_publisher.sensor_name = sensor_name; sensor_publisher.sensor_type = sensor_type; sensor_publisher.publisher = nh_->create_publisher<T>("~/" + topic_name, QoS); return sensor_publisher; } // todo: error check. if state is not landed, return error. bool AirsimROSWrapper::takeoff_srv_cb(std::shared_ptr<airsim_interfaces::srv::Takeoff::Request> request, std::shared_ptr<airsim_interfaces::srv::Takeoff::Response> response, const std::string& vehicle_name) { unused(response); std::lock_guard<std::mutex> guard(control_mutex_); if (request->wait_on_last_task) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->takeoffAsync(20, vehicle_name)->waitOnLastTask(); // todo value for timeout_sec? // response->success = else static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->takeoffAsync(20, vehicle_name); // response->success = return true; } bool AirsimROSWrapper::takeoff_group_srv_cb(std::shared_ptr<airsim_interfaces::srv::TakeoffGroup::Request> request, std::shared_ptr<airsim_interfaces::srv::TakeoffGroup::Response> response) { unused(response); std::lock_guard<std::mutex> guard(control_mutex_); if (request->wait_on_last_task) for (const auto& vehicle_name : request->vehicle_names) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->takeoffAsync(20, vehicle_name)->waitOnLastTask(); // todo value for timeout_sec? // response->success = else for (const auto& vehicle_name : request->vehicle_names) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->takeoffAsync(20, vehicle_name); // response->success = return true; } bool AirsimROSWrapper::takeoff_all_srv_cb(std::shared_ptr<airsim_interfaces::srv::Takeoff::Request> request, std::shared_ptr<airsim_interfaces::srv::Takeoff::Response> response) { unused(response); std::lock_guard<std::mutex> guard(control_mutex_); if (request->wait_on_last_task) for (const auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->takeoffAsync(20, vehicle_name_ptr_pair.first)->waitOnLastTask(); // todo value for timeout_sec? // response->success = else for (const auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->takeoffAsync(20, vehicle_name_ptr_pair.first); // response->success = return true; } bool AirsimROSWrapper::land_srv_cb(std::shared_ptr<airsim_interfaces::srv::Land::Request> request, std::shared_ptr<airsim_interfaces::srv::Land::Response> response, const std::string& vehicle_name) { unused(response); std::lock_guard<std::mutex> guard(control_mutex_); if (request->wait_on_last_task) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->landAsync(60, vehicle_name)->waitOnLastTask(); else static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->landAsync(60, vehicle_name); return true; //todo } bool AirsimROSWrapper::land_group_srv_cb(std::shared_ptr<airsim_interfaces::srv::LandGroup::Request> request, std::shared_ptr<airsim_interfaces::srv::LandGroup::Response> response) { unused(response); std::lock_guard<std::mutex> guard(control_mutex_); if (request->wait_on_last_task) for (const auto& vehicle_name : request->vehicle_names) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->landAsync(60, vehicle_name)->waitOnLastTask(); else for (const auto& vehicle_name : request->vehicle_names) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->landAsync(60, vehicle_name); return true; //todo } bool AirsimROSWrapper::land_all_srv_cb(std::shared_ptr<airsim_interfaces::srv::Land::Request> request, std::shared_ptr<airsim_interfaces::srv::Land::Response> response) { unused(response); std::lock_guard<std::mutex> guard(control_mutex_); if (request->wait_on_last_task) for (const auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->landAsync(60, vehicle_name_ptr_pair.first)->waitOnLastTask(); else for (const auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->landAsync(60, vehicle_name_ptr_pair.first); return true; //todo } // todo add reset by vehicle_name API to airlib // todo not async remove wait_on_last_task bool AirsimROSWrapper::reset_srv_cb(std::shared_ptr<airsim_interfaces::srv::Reset::Request> request, std::shared_ptr<airsim_interfaces::srv::Reset::Response> response) { unused(request); unused(response); std::lock_guard<std::mutex> guard(control_mutex_); airsim_client_->reset(); return true; //todo } tf2::Quaternion AirsimROSWrapper::get_tf2_quat(const msr::airlib::Quaternionr& airlib_quat) const { return tf2::Quaternion(airlib_quat.x(), airlib_quat.y(), airlib_quat.z(), airlib_quat.w()); } msr::airlib::Quaternionr AirsimROSWrapper::get_airlib_quat(const geometry_msgs::msg::Quaternion& geometry_msgs_quat) const { return msr::airlib::Quaternionr(geometry_msgs_quat.w, geometry_msgs_quat.x, geometry_msgs_quat.y, geometry_msgs_quat.z); } msr::airlib::Quaternionr AirsimROSWrapper::get_airlib_quat(const tf2::Quaternion& tf2_quat) const { return msr::airlib::Quaternionr(tf2_quat.w(), tf2_quat.x(), tf2_quat.y(), tf2_quat.z()); } void AirsimROSWrapper::car_cmd_cb(const airsim_interfaces::msg::CarControls::SharedPtr msg, const std::string& vehicle_name) { std::lock_guard<std::mutex> guard(control_mutex_); auto car = static_cast<CarROS*>(vehicle_name_ptr_map_[vehicle_name].get()); car->car_cmd_.throttle = msg->throttle; car->car_cmd_.steering = msg->steering; car->car_cmd_.brake = msg->brake; car->car_cmd_.handbrake = msg->handbrake; car->car_cmd_.is_manual_gear = msg->manual; car->car_cmd_.manual_gear = msg->manual_gear; car->car_cmd_.gear_immediate = msg->gear_immediate; car->has_car_cmd_ = true; } msr::airlib::Pose AirsimROSWrapper::get_airlib_pose(const float& x, const float& y, const float& z, const msr::airlib::Quaternionr& airlib_quat) const { return msr::airlib::Pose(msr::airlib::Vector3r(x, y, z), airlib_quat); } void AirsimROSWrapper::vel_cmd_body_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg, const std::string& vehicle_name) { std::lock_guard<std::mutex> guard(control_mutex_); auto drone = static_cast<MultiRotorROS*>(vehicle_name_ptr_map_[vehicle_name].get()); drone->vel_cmd_ = get_airlib_body_vel_cmd(*msg, drone->curr_drone_state_.kinematics_estimated.pose.orientation); drone->has_vel_cmd_ = true; } void AirsimROSWrapper::vel_cmd_group_body_frame_cb(const airsim_interfaces::msg::VelCmdGroup::SharedPtr msg) { std::lock_guard<std::mutex> guard(control_mutex_); for (const auto& vehicle_name : msg->vehicle_names) { auto drone = static_cast<MultiRotorROS*>(vehicle_name_ptr_map_[vehicle_name].get()); drone->vel_cmd_ = get_airlib_body_vel_cmd(msg->vel_cmd, drone->curr_drone_state_.kinematics_estimated.pose.orientation); drone->has_vel_cmd_ = true; } } void AirsimROSWrapper::vel_cmd_all_body_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg) { std::lock_guard<std::mutex> guard(control_mutex_); // todo expose wait_on_last_task or nah? for (auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { auto drone = static_cast<MultiRotorROS*>(vehicle_name_ptr_pair.second.get()); drone->vel_cmd_ = get_airlib_body_vel_cmd(*msg, drone->curr_drone_state_.kinematics_estimated.pose.orientation); drone->has_vel_cmd_ = true; } } void AirsimROSWrapper::vel_cmd_world_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg, const std::string& vehicle_name) { std::lock_guard<std::mutex> guard(control_mutex_); auto drone = static_cast<MultiRotorROS*>(vehicle_name_ptr_map_[vehicle_name].get()); drone->vel_cmd_ = get_airlib_world_vel_cmd(*msg); drone->has_vel_cmd_ = true; } // this is kinda unnecessary but maybe it makes life easier for the end user. void AirsimROSWrapper::vel_cmd_group_world_frame_cb(const airsim_interfaces::msg::VelCmdGroup::SharedPtr msg) { std::lock_guard<std::mutex> guard(control_mutex_); for (const auto& vehicle_name : msg->vehicle_names) { auto drone = static_cast<MultiRotorROS*>(vehicle_name_ptr_map_[vehicle_name].get()); drone->vel_cmd_ = get_airlib_world_vel_cmd(msg->vel_cmd); drone->has_vel_cmd_ = true; } } void AirsimROSWrapper::vel_cmd_all_world_frame_cb(const airsim_interfaces::msg::VelCmd::SharedPtr msg) { std::lock_guard<std::mutex> guard(control_mutex_); // todo expose wait_on_last_task or nah? for (auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { auto drone = static_cast<MultiRotorROS*>(vehicle_name_ptr_pair.second.get()); drone->vel_cmd_ = get_airlib_world_vel_cmd(*msg); drone->has_vel_cmd_ = true; } } // todo support multiple gimbal commands void AirsimROSWrapper::gimbal_angle_quat_cmd_cb(const airsim_interfaces::msg::GimbalAngleQuatCmd::SharedPtr gimbal_angle_quat_cmd_msg) { tf2::Quaternion quat_control_cmd; try { tf2::convert(gimbal_angle_quat_cmd_msg->orientation, quat_control_cmd); quat_control_cmd.normalize(); gimbal_cmd_.target_quat = get_airlib_quat(quat_control_cmd); // airsim uses wxyz gimbal_cmd_.camera_name = gimbal_angle_quat_cmd_msg->camera_name; gimbal_cmd_.vehicle_name = gimbal_angle_quat_cmd_msg->vehicle_name; has_gimbal_cmd_ = true; } catch (tf2::TransformException& ex) { RCLCPP_WARN(nh_->get_logger(), "%s", ex.what()); } } // todo support multiple gimbal commands // 1. find quaternion of default gimbal pose // 2. forward multiply with quaternion equivalent to desired euler commands (in degrees) // 3. call airsim client's setCameraPose which sets camera pose wrt world (or takeoff?) ned frame. todo void AirsimROSWrapper::gimbal_angle_euler_cmd_cb(const airsim_interfaces::msg::GimbalAngleEulerCmd::SharedPtr gimbal_angle_euler_cmd_msg) { try { tf2::Quaternion quat_control_cmd; quat_control_cmd.setRPY(math_common::deg2rad(gimbal_angle_euler_cmd_msg->roll), math_common::deg2rad(gimbal_angle_euler_cmd_msg->pitch), math_common::deg2rad(gimbal_angle_euler_cmd_msg->yaw)); quat_control_cmd.normalize(); gimbal_cmd_.target_quat = get_airlib_quat(quat_control_cmd); gimbal_cmd_.camera_name = gimbal_angle_euler_cmd_msg->camera_name; gimbal_cmd_.vehicle_name = gimbal_angle_euler_cmd_msg->vehicle_name; has_gimbal_cmd_ = true; } catch (tf2::TransformException& ex) { RCLCPP_WARN(nh_->get_logger(), "%s", ex.what()); } } airsim_interfaces::msg::CarState AirsimROSWrapper::get_roscarstate_msg_from_car_state(const msr::airlib::CarApiBase::CarState& car_state) const { airsim_interfaces::msg::CarState state_msg; const auto odo = get_odom_msg_from_car_state(car_state); state_msg.pose = odo.pose; state_msg.twist = odo.twist; state_msg.speed = car_state.speed; state_msg.gear = car_state.gear; state_msg.rpm = car_state.rpm; state_msg.maxrpm = car_state.maxrpm; state_msg.handbrake = car_state.handbrake; state_msg.header.stamp = rclcpp::Time(car_state.timestamp); return state_msg; } nav_msgs::msg::Odometry AirsimROSWrapper::get_odom_msg_from_kinematic_state(const msr::airlib::Kinematics::State& kinematics_estimated) const { nav_msgs::msg::Odometry odom_msg; odom_msg.pose.pose.position.x = kinematics_estimated.pose.position.x(); odom_msg.pose.pose.position.y = kinematics_estimated.pose.position.y(); odom_msg.pose.pose.position.z = kinematics_estimated.pose.position.z(); odom_msg.pose.pose.orientation.x = kinematics_estimated.pose.orientation.x(); odom_msg.pose.pose.orientation.y = kinematics_estimated.pose.orientation.y(); odom_msg.pose.pose.orientation.z = kinematics_estimated.pose.orientation.z(); odom_msg.pose.pose.orientation.w = kinematics_estimated.pose.orientation.w(); odom_msg.twist.twist.linear.x = kinematics_estimated.twist.linear.x(); odom_msg.twist.twist.linear.y = kinematics_estimated.twist.linear.y(); odom_msg.twist.twist.linear.z = kinematics_estimated.twist.linear.z(); odom_msg.twist.twist.angular.x = kinematics_estimated.twist.angular.x(); odom_msg.twist.twist.angular.y = kinematics_estimated.twist.angular.y(); odom_msg.twist.twist.angular.z = kinematics_estimated.twist.angular.z(); if (isENU_) { std::swap(odom_msg.pose.pose.position.x, odom_msg.pose.pose.position.y); odom_msg.pose.pose.position.z = -odom_msg.pose.pose.position.z; std::swap(odom_msg.pose.pose.orientation.x, odom_msg.pose.pose.orientation.y); odom_msg.pose.pose.orientation.z = -odom_msg.pose.pose.orientation.z; std::swap(odom_msg.twist.twist.linear.x, odom_msg.twist.twist.linear.y); odom_msg.twist.twist.linear.z = -odom_msg.twist.twist.linear.z; std::swap(odom_msg.twist.twist.angular.x, odom_msg.twist.twist.angular.y); odom_msg.twist.twist.angular.z = -odom_msg.twist.twist.angular.z; } return odom_msg; } nav_msgs::msg::Odometry AirsimROSWrapper::get_odom_msg_from_car_state(const msr::airlib::CarApiBase::CarState& car_state) const { return get_odom_msg_from_kinematic_state(car_state.kinematics_estimated); } nav_msgs::msg::Odometry AirsimROSWrapper::get_odom_msg_from_multirotor_state(const msr::airlib::MultirotorState& drone_state) const { return get_odom_msg_from_kinematic_state(drone_state.kinematics_estimated); } // https://docs.ros.org/jade/api/sensor_msgs/html/point__cloud__conversion_8h_source.html#l00066 // look at UnrealLidarSensor.cpp UnrealLidarSensor::getPointCloud() for math // read this carefully https://docs.ros.org/kinetic/api/sensor_msgs/html/msg/PointCloud2.html sensor_msgs::msg::PointCloud2 AirsimROSWrapper::get_lidar_msg_from_airsim(const msr::airlib::LidarData& lidar_data, const std::string& vehicle_name, const std::string& sensor_name) const { sensor_msgs::msg::PointCloud2 lidar_msg; lidar_msg.header.stamp = rclcpp::Time(lidar_data.time_stamp); lidar_msg.header.frame_id = vehicle_name + "/" + sensor_name; if (lidar_data.point_cloud.size() > 3) { lidar_msg.height = 1; lidar_msg.width = lidar_data.point_cloud.size() / 3; lidar_msg.fields.resize(3); lidar_msg.fields[0].name = "x"; lidar_msg.fields[1].name = "y"; lidar_msg.fields[2].name = "z"; int offset = 0; for (size_t d = 0; d < lidar_msg.fields.size(); ++d, offset += 4) { lidar_msg.fields[d].offset = offset; lidar_msg.fields[d].datatype = sensor_msgs::msg::PointField::FLOAT32; lidar_msg.fields[d].count = 1; } lidar_msg.is_bigendian = false; lidar_msg.point_step = offset; // 4 * num fields lidar_msg.row_step = lidar_msg.point_step * lidar_msg.width; lidar_msg.is_dense = true; // todo std::vector<float> data_std = lidar_data.point_cloud; const unsigned char* bytes = reinterpret_cast<const unsigned char*>(data_std.data()); std::vector<unsigned char> lidar_msg_data(bytes, bytes + sizeof(float) * data_std.size()); lidar_msg.data = std::move(lidar_msg_data); if (isENU_) { try { sensor_msgs::msg::PointCloud2 lidar_msg_enu; auto transformStampedENU = tf_buffer_->lookupTransform(AIRSIM_FRAME_ID, vehicle_name, rclcpp::Time(0), rclcpp::Duration::from_nanoseconds(1)); tf2::doTransform(lidar_msg, lidar_msg_enu, transformStampedENU); lidar_msg_enu.header.stamp = lidar_msg.header.stamp; lidar_msg_enu.header.frame_id = lidar_msg.header.frame_id; lidar_msg = std::move(lidar_msg_enu); } catch (tf2::TransformException& ex) { RCLCPP_WARN(nh_->get_logger(), "%s", ex.what()); rclcpp::Rate(1.0).sleep(); } } } else { // msg = [] } return lidar_msg; } airsim_interfaces::msg::Environment AirsimROSWrapper::get_environment_msg_from_airsim(const msr::airlib::Environment::State& env_data) const { airsim_interfaces::msg::Environment env_msg; env_msg.position.x = env_data.position.x(); env_msg.position.y = env_data.position.y(); env_msg.position.z = env_data.position.z(); env_msg.geo_point.latitude = env_data.geo_point.latitude; env_msg.geo_point.longitude = env_data.geo_point.longitude; env_msg.geo_point.altitude = env_data.geo_point.altitude; env_msg.gravity.x = env_data.gravity.x(); env_msg.gravity.y = env_data.gravity.y(); env_msg.gravity.z = env_data.gravity.z(); env_msg.air_pressure = env_data.air_pressure; env_msg.temperature = env_data.temperature; env_msg.air_density = env_data.temperature; return env_msg; } sensor_msgs::msg::MagneticField AirsimROSWrapper::get_mag_msg_from_airsim(const msr::airlib::MagnetometerBase::Output& mag_data) const { sensor_msgs::msg::MagneticField mag_msg; mag_msg.magnetic_field.x = mag_data.magnetic_field_body.x(); mag_msg.magnetic_field.y = mag_data.magnetic_field_body.y(); mag_msg.magnetic_field.z = mag_data.magnetic_field_body.z(); std::copy(std::begin(mag_data.magnetic_field_covariance), std::end(mag_data.magnetic_field_covariance), std::begin(mag_msg.magnetic_field_covariance)); mag_msg.header.stamp = rclcpp::Time(mag_data.time_stamp); return mag_msg; } // todo covariances sensor_msgs::msg::NavSatFix AirsimROSWrapper::get_gps_msg_from_airsim(const msr::airlib::GpsBase::Output& gps_data) const { sensor_msgs::msg::NavSatFix gps_msg; gps_msg.header.stamp = rclcpp::Time(gps_data.time_stamp); gps_msg.latitude = gps_data.gnss.geo_point.latitude; gps_msg.longitude = gps_data.gnss.geo_point.longitude; gps_msg.altitude = gps_data.gnss.geo_point.altitude; gps_msg.status.service = sensor_msgs::msg::NavSatStatus::SERVICE_GLONASS; gps_msg.status.status = gps_data.gnss.fix_type; // gps_msg.position_covariance_type = // gps_msg.position_covariance = return gps_msg; } sensor_msgs::msg::Range AirsimROSWrapper::get_range_from_airsim(const msr::airlib::DistanceSensorData& dist_data) const { sensor_msgs::msg::Range dist_msg; dist_msg.header.stamp = rclcpp::Time(dist_data.time_stamp); dist_msg.range = dist_data.distance; dist_msg.min_range = dist_data.min_distance; dist_msg.max_range = dist_data.max_distance; return dist_msg; } airsim_interfaces::msg::Altimeter AirsimROSWrapper::get_altimeter_msg_from_airsim(const msr::airlib::BarometerBase::Output& alt_data) const { airsim_interfaces::msg::Altimeter alt_msg; alt_msg.header.stamp = rclcpp::Time(alt_data.time_stamp); alt_msg.altitude = alt_data.altitude; alt_msg.pressure = alt_data.pressure; alt_msg.qnh = alt_data.qnh; return alt_msg; } // todo covariances sensor_msgs::msg::Imu AirsimROSWrapper::get_imu_msg_from_airsim(const msr::airlib::ImuBase::Output& imu_data) const { sensor_msgs::msg::Imu imu_msg; // imu_msg.header.frame_id = "/airsim/odom_local_ned";// todo multiple drones imu_msg.header.stamp = rclcpp::Time(imu_data.time_stamp); imu_msg.orientation.x = imu_data.orientation.x(); imu_msg.orientation.y = imu_data.orientation.y(); imu_msg.orientation.z = imu_data.orientation.z(); imu_msg.orientation.w = imu_data.orientation.w(); // todo radians per second imu_msg.angular_velocity.x = imu_data.angular_velocity.x(); imu_msg.angular_velocity.y = imu_data.angular_velocity.y(); imu_msg.angular_velocity.z = imu_data.angular_velocity.z(); // meters/s2^m imu_msg.linear_acceleration.x = imu_data.linear_acceleration.x(); imu_msg.linear_acceleration.y = imu_data.linear_acceleration.y(); imu_msg.linear_acceleration.z = imu_data.linear_acceleration.z(); // imu_msg.orientation_covariance = ; // imu_msg.angular_velocity_covariance = ; // imu_msg.linear_acceleration_covariance = ; return imu_msg; } void AirsimROSWrapper::publish_odom_tf(const nav_msgs::msg::Odometry& odom_msg) { geometry_msgs::msg::TransformStamped odom_tf; odom_tf.header = odom_msg.header; odom_tf.child_frame_id = odom_msg.child_frame_id; odom_tf.transform.translation.x = odom_msg.pose.pose.position.x; odom_tf.transform.translation.y = odom_msg.pose.pose.position.y; odom_tf.transform.translation.z = odom_msg.pose.pose.position.z; odom_tf.transform.rotation = odom_msg.pose.pose.orientation; tf_broadcaster_->sendTransform(odom_tf); } airsim_interfaces::msg::GPSYaw AirsimROSWrapper::get_gps_msg_from_airsim_geo_point(const msr::airlib::GeoPoint& geo_point) const { airsim_interfaces::msg::GPSYaw gps_msg; gps_msg.latitude = geo_point.latitude; gps_msg.longitude = geo_point.longitude; gps_msg.altitude = geo_point.altitude; return gps_msg; } sensor_msgs::msg::NavSatFix AirsimROSWrapper::get_gps_sensor_msg_from_airsim_geo_point(const msr::airlib::GeoPoint& geo_point) const { sensor_msgs::msg::NavSatFix gps_msg; gps_msg.latitude = geo_point.latitude; gps_msg.longitude = geo_point.longitude; gps_msg.altitude = geo_point.altitude; return gps_msg; } msr::airlib::GeoPoint AirsimROSWrapper::get_origin_geo_point() const { msr::airlib::HomeGeoPoint geo_point = AirSimSettings::singleton().origin_geopoint; return geo_point.home_geo_point; } VelCmd AirsimROSWrapper::get_airlib_world_vel_cmd(const airsim_interfaces::msg::VelCmd& msg) const { VelCmd vel_cmd; vel_cmd.x = msg.twist.linear.x; vel_cmd.y = msg.twist.linear.y; vel_cmd.z = msg.twist.linear.z; vel_cmd.drivetrain = msr::airlib::DrivetrainType::MaxDegreeOfFreedom; vel_cmd.yaw_mode.is_rate = true; vel_cmd.yaw_mode.yaw_or_rate = math_common::rad2deg(msg.twist.angular.z); return vel_cmd; } VelCmd AirsimROSWrapper::get_airlib_body_vel_cmd(const airsim_interfaces::msg::VelCmd& msg, const msr::airlib::Quaternionr& airlib_quat) const { VelCmd vel_cmd; double roll, pitch, yaw; tf2::Matrix3x3(get_tf2_quat(airlib_quat)).getRPY(roll, pitch, yaw); // ros uses xyzw // todo do actual body frame? vel_cmd.x = (msg.twist.linear.x * cos(yaw)) - (msg.twist.linear.y * sin(yaw)); //body frame assuming zero pitch roll vel_cmd.y = (msg.twist.linear.x * sin(yaw)) + (msg.twist.linear.y * cos(yaw)); //body frame vel_cmd.z = msg.twist.linear.z; vel_cmd.drivetrain = msr::airlib::DrivetrainType::MaxDegreeOfFreedom; vel_cmd.yaw_mode.is_rate = true; // airsim uses degrees vel_cmd.yaw_mode.yaw_or_rate = math_common::rad2deg(msg.twist.angular.z); return vel_cmd; } geometry_msgs::msg::Transform AirsimROSWrapper::get_transform_msg_from_airsim(const msr::airlib::Vector3r& position, const msr::airlib::AirSimSettings::Rotation& rotation) { geometry_msgs::msg::Transform transform; transform.translation.x = position.x(); transform.translation.y = position.y(); transform.translation.z = position.z(); tf2::Quaternion quat; quat.setRPY(rotation.roll, rotation.pitch, rotation.yaw); transform.rotation.x = quat.x(); transform.rotation.y = quat.y(); transform.rotation.z = quat.z(); transform.rotation.w = quat.w(); return transform; } geometry_msgs::msg::Transform AirsimROSWrapper::get_transform_msg_from_airsim(const msr::airlib::Vector3r& position, const msr::airlib::Quaternionr& quaternion) { geometry_msgs::msg::Transform transform; transform.translation.x = position.x(); transform.translation.y = position.y(); transform.translation.z = position.z(); transform.rotation.x = quaternion.x(); transform.rotation.y = quaternion.y(); transform.rotation.z = quaternion.z(); transform.rotation.w = quaternion.w(); return transform; } void AirsimROSWrapper::drone_state_timer_cb() { try { // todo this is global origin origin_geo_point_pub_->publish(origin_geo_point_msg_); // get the basic vehicle pose and environmental state const auto now = update_state(); // on init, will publish 0 to /clock as expected for use_sim_time compatibility if (!airsim_client_->simIsPaused()) { // airsim_client needs to provide the simulation time in a future version of the API ros_clock_.clock = now; } // publish the simulation clock if (publish_clock_) { clock_pub_->publish(ros_clock_); } // publish vehicle state, odom, and all basic sensor types publish_vehicle_state(); // send any commands out to the vehicles update_commands(); } catch (rpc::rpc_error& e) { std::string msg = e.get_error().as<std::string>(); RCLCPP_ERROR(nh_->get_logger(), "Exception raised by the API:\n%s", msg.c_str()); } } void AirsimROSWrapper::update_and_publish_static_transforms(VehicleROS* vehicle_ros) { if (vehicle_ros && !vehicle_ros->static_tf_msg_vec_.empty()) { for (auto& static_tf_msg : vehicle_ros->static_tf_msg_vec_) { static_tf_msg.header.stamp = vehicle_ros->stamp_; static_tf_pub_->sendTransform(static_tf_msg); } } } rclcpp::Time AirsimROSWrapper::update_state() { bool got_sim_time = false; rclcpp::Time curr_ros_time = nh_->now(); //should be easier way to get the sim time through API, something like: //msr::airlib::Environment::State env = airsim_client_->simGetGroundTruthEnvironment(""); //curr_ros_time = rclcpp::Time(env.clock().nowNanos()); // iterate over drones for (auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { rclcpp::Time vehicle_time; // get drone state from airsim auto& vehicle_ros = vehicle_name_ptr_pair.second; // vehicle environment, we can get ambient temperature here and other truths auto env_data = airsim_client_->simGetGroundTruthEnvironment(vehicle_ros->vehicle_name_); if (airsim_mode_ == AIRSIM_MODE::DRONE) { auto drone = static_cast<MultiRotorROS*>(vehicle_ros.get()); auto rpc = static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get()); drone->curr_drone_state_ = rpc->getMultirotorState(vehicle_ros->vehicle_name_); vehicle_time = rclcpp::Time(drone->curr_drone_state_.timestamp); if (!got_sim_time) { curr_ros_time = vehicle_time; got_sim_time = true; } vehicle_ros->gps_sensor_msg_ = get_gps_sensor_msg_from_airsim_geo_point(drone->curr_drone_state_.gps_location); vehicle_ros->gps_sensor_msg_.header.stamp = vehicle_time; vehicle_ros->curr_odom_ = get_odom_msg_from_multirotor_state(drone->curr_drone_state_); } else { auto car = static_cast<CarROS*>(vehicle_ros.get()); auto rpc = static_cast<msr::airlib::CarRpcLibClient*>(airsim_client_.get()); car->curr_car_state_ = rpc->getCarState(vehicle_ros->vehicle_name_); vehicle_time = rclcpp::Time(car->curr_car_state_.timestamp); if (!got_sim_time) { curr_ros_time = vehicle_time; got_sim_time = true; } vehicle_ros->gps_sensor_msg_ = get_gps_sensor_msg_from_airsim_geo_point(env_data.geo_point); vehicle_ros->gps_sensor_msg_.header.stamp = vehicle_time; vehicle_ros->curr_odom_ = get_odom_msg_from_car_state(car->curr_car_state_); airsim_interfaces::msg::CarState state_msg = get_roscarstate_msg_from_car_state(car->curr_car_state_); state_msg.header.frame_id = vehicle_ros->vehicle_name_; car->car_state_msg_ = state_msg; } vehicle_ros->stamp_ = vehicle_time; airsim_interfaces::msg::Environment env_msg = get_environment_msg_from_airsim(env_data); env_msg.header.frame_id = vehicle_ros->vehicle_name_; env_msg.header.stamp = vehicle_time; vehicle_ros->env_msg_ = env_msg; // convert airsim drone state to ROS msgs vehicle_ros->curr_odom_.header.frame_id = vehicle_ros->vehicle_name_; vehicle_ros->curr_odom_.child_frame_id = vehicle_ros->odom_frame_id_; vehicle_ros->curr_odom_.header.stamp = vehicle_time; } return curr_ros_time; } void AirsimROSWrapper::publish_vehicle_state() { for (auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { auto& vehicle_ros = vehicle_name_ptr_pair.second; // simulation environment truth vehicle_ros->env_pub_->publish(vehicle_ros->env_msg_); if (airsim_mode_ == AIRSIM_MODE::CAR) { // dashboard reading from car, RPM, gear, etc auto car = static_cast<CarROS*>(vehicle_ros.get()); car->car_state_pub_->publish(car->car_state_msg_); } // odom and transforms vehicle_ros->odom_local_pub_->publish(vehicle_ros->curr_odom_); publish_odom_tf(vehicle_ros->curr_odom_); // ground truth GPS position from sim/HITL vehicle_ros->global_gps_pub_->publish(vehicle_ros->gps_sensor_msg_); for (auto& sensor_publisher : vehicle_ros->barometer_pubs_) { auto baro_data = airsim_client_->getBarometerData(sensor_publisher.sensor_name, vehicle_ros->vehicle_name_); airsim_interfaces::msg::Altimeter alt_msg = get_altimeter_msg_from_airsim(baro_data); alt_msg.header.frame_id = vehicle_ros->vehicle_name_; sensor_publisher.publisher->publish(alt_msg); } for (auto& sensor_publisher : vehicle_ros->imu_pubs_) { auto imu_data = airsim_client_->getImuData(sensor_publisher.sensor_name, vehicle_ros->vehicle_name_); sensor_msgs::msg::Imu imu_msg = get_imu_msg_from_airsim(imu_data); imu_msg.header.frame_id = vehicle_ros->vehicle_name_; sensor_publisher.publisher->publish(imu_msg); } for (auto& sensor_publisher : vehicle_ros->distance_pubs_) { auto distance_data = airsim_client_->getDistanceSensorData(sensor_publisher.sensor_name, vehicle_ros->vehicle_name_); sensor_msgs::msg::Range dist_msg = get_range_from_airsim(distance_data); dist_msg.header.frame_id = vehicle_ros->vehicle_name_; sensor_publisher.publisher->publish(dist_msg); } for (auto& sensor_publisher : vehicle_ros->gps_pubs_) { auto gps_data = airsim_client_->getGpsData(sensor_publisher.sensor_name, vehicle_ros->vehicle_name_); sensor_msgs::msg::NavSatFix gps_msg = get_gps_msg_from_airsim(gps_data); gps_msg.header.frame_id = vehicle_ros->vehicle_name_; sensor_publisher.publisher->publish(gps_msg); } for (auto& sensor_publisher : vehicle_ros->magnetometer_pubs_) { auto mag_data = airsim_client_->getMagnetometerData(sensor_publisher.sensor_name, vehicle_ros->vehicle_name_); sensor_msgs::msg::MagneticField mag_msg = get_mag_msg_from_airsim(mag_data); mag_msg.header.frame_id = vehicle_ros->vehicle_name_; sensor_publisher.publisher->publish(mag_msg); } update_and_publish_static_transforms(vehicle_ros.get()); } } void AirsimROSWrapper::update_commands() { for (auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { auto& vehicle_ros = vehicle_name_ptr_pair.second; if (airsim_mode_ == AIRSIM_MODE::DRONE) { auto drone = static_cast<MultiRotorROS*>(vehicle_ros.get()); // send control commands from the last callback to airsim if (drone->has_vel_cmd_) { std::lock_guard<std::mutex> guard(control_mutex_); static_cast<msr::airlib::MultirotorRpcLibClient*>(airsim_client_.get())->moveByVelocityAsync(drone->vel_cmd_.x, drone->vel_cmd_.y, drone->vel_cmd_.z, vel_cmd_duration_, msr::airlib::DrivetrainType::MaxDegreeOfFreedom, drone->vel_cmd_.yaw_mode, drone->vehicle_name_); } drone->has_vel_cmd_ = false; } else { // send control commands from the last callback to airsim auto car = static_cast<CarROS*>(vehicle_ros.get()); if (car->has_car_cmd_) { std::lock_guard<std::mutex> guard(control_mutex_); static_cast<msr::airlib::CarRpcLibClient*>(airsim_client_.get())->setCarControls(car->car_cmd_, vehicle_ros->vehicle_name_); } car->has_car_cmd_ = false; } } // Only camera rotation, no translation movement of camera if (has_gimbal_cmd_) { std::lock_guard<std::mutex> guard(control_mutex_); airsim_client_->simSetCameraPose(gimbal_cmd_.camera_name, get_airlib_pose(0, 0, 0, gimbal_cmd_.target_quat), gimbal_cmd_.vehicle_name); } has_gimbal_cmd_ = false; } // airsim uses nans for zeros in settings.json. we set them to zeros here for handling tfs in ROS void AirsimROSWrapper::set_nans_to_zeros_in_pose(VehicleSetting& vehicle_setting) const { if (std::isnan(vehicle_setting.position.x())) vehicle_setting.position.x() = 0.0; if (std::isnan(vehicle_setting.position.y())) vehicle_setting.position.y() = 0.0; if (std::isnan(vehicle_setting.position.z())) vehicle_setting.position.z() = 0.0; if (std::isnan(vehicle_setting.rotation.yaw)) vehicle_setting.rotation.yaw = 0.0; if (std::isnan(vehicle_setting.rotation.pitch)) vehicle_setting.rotation.pitch = 0.0; if (std::isnan(vehicle_setting.rotation.roll)) vehicle_setting.rotation.roll = 0.0; } // if any nan's in camera pose, set them to match vehicle pose (which has already converted any potential nans to zeros) void AirsimROSWrapper::set_nans_to_zeros_in_pose(const VehicleSetting& vehicle_setting, CameraSetting& camera_setting) const { if (std::isnan(camera_setting.position.x())) camera_setting.position.x() = vehicle_setting.position.x(); if (std::isnan(camera_setting.position.y())) camera_setting.position.y() = vehicle_setting.position.y(); if (std::isnan(camera_setting.position.z())) camera_setting.position.z() = vehicle_setting.position.z(); if (std::isnan(camera_setting.rotation.yaw)) camera_setting.rotation.yaw = vehicle_setting.rotation.yaw; if (std::isnan(camera_setting.rotation.pitch)) camera_setting.rotation.pitch = vehicle_setting.rotation.pitch; if (std::isnan(camera_setting.rotation.roll)) camera_setting.rotation.roll = vehicle_setting.rotation.roll; } void AirsimROSWrapper::convert_tf_msg_to_enu(geometry_msgs::msg::TransformStamped& tf_msg) { std::swap(tf_msg.transform.translation.x, tf_msg.transform.translation.y); std::swap(tf_msg.transform.rotation.x, tf_msg.transform.rotation.y); tf_msg.transform.translation.z = -tf_msg.transform.translation.z; tf_msg.transform.rotation.z = -tf_msg.transform.rotation.z; } geometry_msgs::msg::Transform AirsimROSWrapper::get_camera_optical_tf_from_body_tf(const geometry_msgs::msg::Transform& body_tf) const { geometry_msgs::msg::Transform optical_tf = body_tf; //same translation auto opticalQ = msr::airlib::Quaternionr(optical_tf.rotation.w, optical_tf.rotation.x, optical_tf.rotation.y, optical_tf.rotation.z); if (isENU_) opticalQ *= msr::airlib::Quaternionr(0.7071068, -0.7071068, 0, 0); //CamOptical in CamBodyENU is rmat[1,0,0;0,0,-1;0,1,0]==xyzw[-0.7071068,0,0,0.7071068] else opticalQ *= msr::airlib::Quaternionr(0.5, 0.5, 0.5, 0.5); //CamOptical in CamBodyNED is rmat[0,0,1;1,0,0;0,1,0]==xyzw[0.5,0.5,0.5,0.5] optical_tf.rotation.w = opticalQ.w(); optical_tf.rotation.x = opticalQ.x(); optical_tf.rotation.y = opticalQ.y(); optical_tf.rotation.z = opticalQ.z(); return optical_tf; } void AirsimROSWrapper::append_static_vehicle_tf(VehicleROS* vehicle_ros, const VehicleSetting& vehicle_setting) { geometry_msgs::msg::TransformStamped vehicle_tf_msg; vehicle_tf_msg.header.frame_id = world_frame_id_; vehicle_tf_msg.header.stamp = nh_->now(); vehicle_tf_msg.child_frame_id = vehicle_ros->vehicle_name_; vehicle_tf_msg.transform = get_transform_msg_from_airsim(vehicle_setting.position, vehicle_setting.rotation); if (isENU_) { convert_tf_msg_to_enu(vehicle_tf_msg); } vehicle_ros->static_tf_msg_vec_.emplace_back(vehicle_tf_msg); } void AirsimROSWrapper::append_static_lidar_tf(VehicleROS* vehicle_ros, const std::string& lidar_name, const msr::airlib::LidarSimpleParams& lidar_setting) { geometry_msgs::msg::TransformStamped lidar_tf_msg; lidar_tf_msg.header.frame_id = vehicle_ros->vehicle_name_ + "/" + odom_frame_id_; lidar_tf_msg.child_frame_id = vehicle_ros->vehicle_name_ + "/" + lidar_name; lidar_tf_msg.transform = get_transform_msg_from_airsim(lidar_setting.relative_pose.position, lidar_setting.relative_pose.orientation); if (isENU_) { convert_tf_msg_to_enu(lidar_tf_msg); } vehicle_ros->static_tf_msg_vec_.emplace_back(lidar_tf_msg); } void AirsimROSWrapper::append_static_camera_tf(VehicleROS* vehicle_ros, const std::string& camera_name, const CameraSetting& camera_setting) { geometry_msgs::msg::TransformStamped static_cam_tf_body_msg; static_cam_tf_body_msg.header.frame_id = vehicle_ros->vehicle_name_ + "/" + odom_frame_id_; static_cam_tf_body_msg.child_frame_id = vehicle_ros->vehicle_name_ + "/" + camera_name + "_body/static"; static_cam_tf_body_msg.transform = get_transform_msg_from_airsim(camera_setting.position, camera_setting.rotation); if (isENU_) { convert_tf_msg_to_enu(static_cam_tf_body_msg); } geometry_msgs::msg::TransformStamped static_cam_tf_optical_msg = static_cam_tf_body_msg; static_cam_tf_optical_msg.child_frame_id = vehicle_ros->vehicle_name_ + "/" + camera_name + "_optical/static"; static_cam_tf_optical_msg.child_frame_id = camera_name + "_optical/static"; static_cam_tf_optical_msg.transform = get_camera_optical_tf_from_body_tf(static_cam_tf_body_msg.transform); vehicle_ros->static_tf_msg_vec_.emplace_back(static_cam_tf_body_msg); vehicle_ros->static_tf_msg_vec_.emplace_back(static_cam_tf_optical_msg); } void AirsimROSWrapper::img_response_timer_cb() { try { int image_response_idx = 0; for (const auto& airsim_img_request_vehicle_name_pair : airsim_img_request_vehicle_name_pair_vec_) { const std::vector<ImageResponse>& img_response = airsim_client_images_.simGetImages(airsim_img_request_vehicle_name_pair.first, airsim_img_request_vehicle_name_pair.second); if (img_response.size() == airsim_img_request_vehicle_name_pair.first.size()) { process_and_publish_img_response(img_response, image_response_idx, airsim_img_request_vehicle_name_pair.second); image_response_idx += img_response.size(); } } } catch (rpc::rpc_error& e) { std::string msg = e.get_error().as<std::string>(); RCLCPP_ERROR(nh_->get_logger(), "Exception raised by the API, didn't get image response.\n%s", msg.c_str()); } } void AirsimROSWrapper::lidar_timer_cb() { try { for (auto& vehicle_name_ptr_pair : vehicle_name_ptr_map_) { if (!vehicle_name_ptr_pair.second->lidar_pubs_.empty()) { for (auto& lidar_publisher : vehicle_name_ptr_pair.second->lidar_pubs_) { auto lidar_data = airsim_client_lidar_.getLidarData(lidar_publisher.sensor_name, vehicle_name_ptr_pair.first); sensor_msgs::msg::PointCloud2 lidar_msg = get_lidar_msg_from_airsim(lidar_data, vehicle_name_ptr_pair.first, lidar_publisher.sensor_name); lidar_publisher.publisher->publish(lidar_msg); } } } } catch (rpc::rpc_error& e) { std::string msg = e.get_error().as<std::string>(); RCLCPP_ERROR(nh_->get_logger(), "Exception raised by the API, didn't get image response.\n%s", msg.c_str()); } } std::shared_ptr<sensor_msgs::msg::Image> AirsimROSWrapper::get_img_msg_from_response(const ImageResponse& img_response, const rclcpp::Time curr_ros_time, const std::string frame_id) { unused(curr_ros_time); std::shared_ptr<sensor_msgs::msg::Image> img_msg_ptr = std::make_shared<sensor_msgs::msg::Image>(); img_msg_ptr->data = img_response.image_data_uint8; img_msg_ptr->step = img_response.image_data_uint8.size() / img_response.height; img_msg_ptr->header.stamp = rclcpp::Time(img_response.time_stamp); img_msg_ptr->header.frame_id = frame_id; img_msg_ptr->height = img_response.height; img_msg_ptr->width = img_response.width; img_msg_ptr->encoding = "bgr8"; if (is_vulkan_) img_msg_ptr->encoding = "rgb8"; img_msg_ptr->is_bigendian = 0; return img_msg_ptr; } std::shared_ptr<sensor_msgs::msg::Image> AirsimROSWrapper::get_depth_img_msg_from_response(const ImageResponse& img_response, const rclcpp::Time curr_ros_time, const std::string frame_id) { unused(curr_ros_time); auto depth_img_msg = std::make_shared<sensor_msgs::msg::Image>(); depth_img_msg->width = img_response.width; depth_img_msg->height = img_response.height; depth_img_msg->data.resize(img_response.image_data_float.size() * sizeof(float)); memcpy(depth_img_msg->data.data(), img_response.image_data_float.data(), depth_img_msg->data.size()); depth_img_msg->encoding = "32FC1"; depth_img_msg->step = depth_img_msg->data.size() / img_response.height; depth_img_msg->is_bigendian = 0; depth_img_msg->header.stamp = rclcpp::Time(img_response.time_stamp); depth_img_msg->header.frame_id = frame_id; return depth_img_msg; } // todo have a special stereo pair mode and get projection matrix by calculating offset wrt drone body frame? sensor_msgs::msg::CameraInfo AirsimROSWrapper::generate_cam_info(const std::string& camera_name, const CameraSetting& camera_setting, const CaptureSetting& capture_setting) const { unused(camera_setting); sensor_msgs::msg::CameraInfo cam_info_msg; cam_info_msg.header.frame_id = camera_name + "_optical"; cam_info_msg.height = capture_setting.height; cam_info_msg.width = capture_setting.width; float f_x = (capture_setting.width / 2.0) / tan(math_common::deg2rad(capture_setting.fov_degrees / 2.0)); // todo focal length in Y direction should be same as X it seems. this can change in future a scene capture component which exactly correponds to a cine camera // float f_y = (capture_setting.height / 2.0) / tan(math_common::deg2rad(fov_degrees / 2.0)); cam_info_msg.k = { f_x, 0.0, capture_setting.width / 2.0, 0.0, f_x, capture_setting.height / 2.0, 0.0, 0.0, 1.0 }; cam_info_msg.p = { f_x, 0.0, capture_setting.width / 2.0, 0.0, 0.0, f_x, capture_setting.height / 2.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; return cam_info_msg; } void AirsimROSWrapper::process_and_publish_img_response(const std::vector<ImageResponse>& img_response_vec, const int img_response_idx, const std::string& vehicle_name) { // todo add option to use airsim time (image_response.TTimePoint) like Gazebo /use_sim_time param rclcpp::Time curr_ros_time = nh_->now(); int img_response_idx_internal = img_response_idx; for (const auto& curr_img_response : img_response_vec) { // todo publishing a tf for each capture type seems stupid. but it foolproofs us against render thread's async stuff, I hope. // Ideally, we should loop over cameras and then captures, and publish only one tf. publish_camera_tf(curr_img_response, curr_ros_time, vehicle_name, curr_img_response.camera_name); // todo simGetCameraInfo is wrong + also it's only for image type -1. // msr::airlib::CameraInfo camera_info = airsim_client_.simGetCameraInfo(curr_img_response.camera_name); // update timestamp of saved cam info msgs camera_info_msg_vec_[img_response_idx_internal].header.stamp = rclcpp::Time(curr_img_response.time_stamp); cam_info_pub_vec_[img_response_idx_internal]->publish(camera_info_msg_vec_[img_response_idx_internal]); // DepthPlanar / DepthPerspective / DepthVis / DisparityNormalized if (curr_img_response.pixels_as_float) { image_pub_vec_[img_response_idx_internal].publish(get_depth_img_msg_from_response(curr_img_response, curr_ros_time, curr_img_response.camera_name + "_optical")); } // Scene / Segmentation / SurfaceNormals / Infrared else { image_pub_vec_[img_response_idx_internal].publish(get_img_msg_from_response(curr_img_response, curr_ros_time, curr_img_response.camera_name + "_optical")); } img_response_idx_internal++; } } // publish camera transforms // camera poses are obtained from airsim's client API which are in (local) NED frame. // We first do a change of basis to camera optical frame (Z forward, X right, Y down) void AirsimROSWrapper::publish_camera_tf(const ImageResponse& img_response, const rclcpp::Time& ros_time, const std::string& frame_id, const std::string& child_frame_id) { unused(ros_time); geometry_msgs::msg::TransformStamped cam_tf_body_msg; cam_tf_body_msg.header.stamp = rclcpp::Time(img_response.time_stamp); cam_tf_body_msg.header.frame_id = frame_id; cam_tf_body_msg.child_frame_id = frame_id + "/" + child_frame_id + "_body"; cam_tf_body_msg.transform = get_transform_msg_from_airsim(img_response.camera_position, img_response.camera_orientation); if (isENU_) { convert_tf_msg_to_enu(cam_tf_body_msg); } geometry_msgs::msg::TransformStamped cam_tf_optical_msg; cam_tf_optical_msg.header.stamp = rclcpp::Time(img_response.time_stamp); cam_tf_optical_msg.header.frame_id = frame_id; cam_tf_optical_msg.child_frame_id = frame_id + "/" + child_frame_id + "_optical"; cam_tf_optical_msg.transform = get_camera_optical_tf_from_body_tf(cam_tf_body_msg.transform); tf_broadcaster_->sendTransform(cam_tf_body_msg); tf_broadcaster_->sendTransform(cam_tf_optical_msg); } void AirsimROSWrapper::convert_yaml_to_simple_mat(const YAML::Node& node, SimpleMatrix& m) const { int rows, cols; rows = node["rows"].as<int>(); cols = node["cols"].as<int>(); const YAML::Node& data = node["data"]; for (int i = 0; i < rows * cols; ++i) { m.data[i] = data[i].as<double>(); } } void AirsimROSWrapper::read_params_from_yaml_and_fill_cam_info_msg(const std::string& file_name, sensor_msgs::msg::CameraInfo& cam_info) const { std::ifstream fin(file_name.c_str()); YAML::Node doc = YAML::Load(fin); cam_info.width = doc[WIDTH_YML_NAME].as<int>(); cam_info.height = doc[HEIGHT_YML_NAME].as<int>(); SimpleMatrix K_(3, 3, &cam_info.k[0]); convert_yaml_to_simple_mat(doc[K_YML_NAME], K_); SimpleMatrix R_(3, 3, &cam_info.r[0]); convert_yaml_to_simple_mat(doc[R_YML_NAME], R_); SimpleMatrix P_(3, 4, &cam_info.p[0]); convert_yaml_to_simple_mat(doc[P_YML_NAME], P_); cam_info.distortion_model = doc[DMODEL_YML_NAME].as<std::string>(); const YAML::Node& D_node = doc[D_YML_NAME]; int D_rows, D_cols; D_rows = D_node["rows"].as<int>(); D_cols = D_node["cols"].as<int>(); const YAML::Node& D_data = D_node["data"]; cam_info.d.resize(D_rows * D_cols); for (int i = 0; i < D_rows * D_cols; ++i) { cam_info.d[i] = D_data[i].as<float>(); } }
AirSim/ros2/src/airsim_ros_pkgs/src/airsim_ros_wrapper.cpp/0
{ "file_path": "AirSim/ros2/src/airsim_ros_pkgs/src/airsim_ros_wrapper.cpp", "repo_id": "AirSim", "token_count": 30188 }
63
// CommandLineParser.cs using System; using System.Collections; namespace SevenZip.CommandLineParser { public enum SwitchType { Simple, PostMinus, LimitedPostString, UnLimitedPostString, PostChar } public class SwitchForm { public string IDString; public SwitchType Type; public bool Multi; public int MinLen; public int MaxLen; public string PostCharSet; public SwitchForm(string idString, SwitchType type, bool multi, int minLen, int maxLen, string postCharSet) { IDString = idString; Type = type; Multi = multi; MinLen = minLen; MaxLen = maxLen; PostCharSet = postCharSet; } public SwitchForm(string idString, SwitchType type, bool multi, int minLen): this(idString, type, multi, minLen, 0, "") { } public SwitchForm(string idString, SwitchType type, bool multi): this(idString, type, multi, 0) { } } public class SwitchResult { public bool ThereIs; public bool WithMinus; public ArrayList PostStrings = new ArrayList(); public int PostCharIndex; public SwitchResult() { ThereIs = false; } } public class Parser { public ArrayList NonSwitchStrings = new ArrayList(); SwitchResult[] _switches; public Parser(int numSwitches) { _switches = new SwitchResult[numSwitches]; for (int i = 0; i < numSwitches; i++) _switches[i] = new SwitchResult(); } bool ParseString(string srcString, SwitchForm[] switchForms) { int len = srcString.Length; if (len == 0) return false; int pos = 0; if (!IsItSwitchChar(srcString[pos])) return false; while (pos < len) { if (IsItSwitchChar(srcString[pos])) pos++; const int kNoLen = -1; int matchedSwitchIndex = 0; int maxLen = kNoLen; for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) { int switchLen = switchForms[switchIndex].IDString.Length; if (switchLen <= maxLen || pos + switchLen > len) continue; if (String.Compare(switchForms[switchIndex].IDString, 0, srcString, pos, switchLen, true) == 0) { matchedSwitchIndex = switchIndex; maxLen = switchLen; } } if (maxLen == kNoLen) throw new Exception("maxLen == kNoLen"); SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; SwitchForm switchForm = switchForms[matchedSwitchIndex]; if ((!switchForm.Multi) && matchedSwitch.ThereIs) throw new Exception("switch must be single"); matchedSwitch.ThereIs = true; pos += maxLen; int tailSize = len - pos; SwitchType type = switchForm.Type; switch (type) { case SwitchType.PostMinus: { if (tailSize == 0) matchedSwitch.WithMinus = false; else { matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); if (matchedSwitch.WithMinus) pos++; } break; } case SwitchType.PostChar: { if (tailSize < switchForm.MinLen) throw new Exception("switch is not full"); string charSet = switchForm.PostCharSet; const int kEmptyCharValue = -1; if (tailSize == 0) matchedSwitch.PostCharIndex = kEmptyCharValue; else { int index = charSet.IndexOf(srcString[pos]); if (index < 0) matchedSwitch.PostCharIndex = kEmptyCharValue; else { matchedSwitch.PostCharIndex = index; pos++; } } break; } case SwitchType.LimitedPostString: case SwitchType.UnLimitedPostString: { int minLen = switchForm.MinLen; if (tailSize < minLen) throw new Exception("switch is not full"); if (type == SwitchType.UnLimitedPostString) { matchedSwitch.PostStrings.Add(srcString.Substring(pos)); return true; } String stringSwitch = srcString.Substring(pos, minLen); pos += minLen; for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) { char c = srcString[pos]; if (IsItSwitchChar(c)) break; stringSwitch += c; } matchedSwitch.PostStrings.Add(stringSwitch); break; } } } return true; } public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) { int numCommandStrings = commandStrings.Length; bool stopSwitch = false; for (int i = 0; i < numCommandStrings; i++) { string s = commandStrings[i]; if (stopSwitch) NonSwitchStrings.Add(s); else if (s == kStopSwitchParsing) stopSwitch = true; else if (!ParseString(s, switchForms)) NonSwitchStrings.Add(s); } } public SwitchResult this[int index] { get { return _switches[index]; } } public static int ParseCommand(CommandForm[] commandForms, string commandString, out string postString) { for (int i = 0; i < commandForms.Length; i++) { string id = commandForms[i].IDString; if (commandForms[i].PostStringMode) { if (commandString.IndexOf(id) == 0) { postString = commandString.Substring(id.Length); return i; } } else if (commandString == id) { postString = ""; return i; } } postString = ""; return -1; } static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, string commandString, ArrayList indices) { indices.Clear(); int numUsedChars = 0; for (int i = 0; i < numForms; i++) { CommandSubCharsSet charsSet = forms[i]; int currentIndex = -1; int len = charsSet.Chars.Length; for (int j = 0; j < len; j++) { char c = charsSet.Chars[j]; int newIndex = commandString.IndexOf(c); if (newIndex >= 0) { if (currentIndex >= 0) return false; if (commandString.IndexOf(c, newIndex + 1) >= 0) return false; currentIndex = j; numUsedChars++; } } if (currentIndex == -1 && !charsSet.EmptyAllowed) return false; indices.Add(currentIndex); } return (numUsedChars == commandString.Length); } const char kSwitchID1 = '-'; const char kSwitchID2 = '/'; const char kSwitchMinus = '-'; const string kStopSwitchParsing = "--"; static bool IsItSwitchChar(char c) { return (c == kSwitchID1 || c == kSwitchID2); } } public class CommandForm { public string IDString = ""; public bool PostStringMode = false; public CommandForm(string idString, bool postStringMode) { IDString = idString; PostStringMode = postStringMode; } } class CommandSubCharsSet { public string Chars = ""; public bool EmptyAllowed = false; } }
AssetStudio/AssetStudio/7zip/Common/CommandLineParser.cs/0
{ "file_path": "AssetStudio/AssetStudio/7zip/Common/CommandLineParser.cs", "repo_id": "AssetStudio", "token_count": 2903 }
64
using System.Buffers; namespace AssetStudio { public static class BigArrayPool<T> { private static readonly ArrayPool<T> s_shared = ArrayPool<T>.Create(64 * 1024 * 1024, 3); public static ArrayPool<T> Shared => s_shared; } }
AssetStudio/AssetStudio/BigArrayPool.cs/0
{ "file_path": "AssetStudio/AssetStudio/BigArrayPool.cs", "repo_id": "AssetStudio", "token_count": 100 }
65
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public enum BuildTarget { NoTarget = -2, AnyPlayer = -1, ValidPlayer = 1, StandaloneOSX = 2, StandaloneOSXPPC = 3, StandaloneOSXIntel = 4, StandaloneWindows, WebPlayer, WebPlayerStreamed, Wii = 8, iOS = 9, PS3, XBOX360, Broadcom = 12, Android = 13, StandaloneGLESEmu = 14, StandaloneGLES20Emu = 15, NaCl = 16, StandaloneLinux = 17, FlashPlayer = 18, StandaloneWindows64 = 19, WebGL, WSAPlayer, StandaloneLinux64 = 24, StandaloneLinuxUniversal, WP8Player, StandaloneOSXIntel64, BlackBerry, Tizen, PSP2, PS4, PSM, XboxOne, SamsungTV, N3DS, WiiU, tvOS, Switch, Lumin, Stadia, CloudRendering, GameCoreXboxSeries, GameCoreXboxOne, PS5, EmbeddedLinux, QNX, UnknownPlatform = 9999 } }
AssetStudio/AssetStudio/BuildTarget.cs/0
{ "file_path": "AssetStudio/AssetStudio/BuildTarget.cs", "repo_id": "AssetStudio", "token_count": 649 }
66
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public sealed class Font : NamedObject { public byte[] m_FontData; public Font(ObjectReader reader) : base(reader) { if ((version[0] == 5 && version[1] >= 5) || version[0] > 5)//5.5 and up { var m_LineSpacing = reader.ReadSingle(); var m_DefaultMaterial = new PPtr<Material>(reader); var m_FontSize = reader.ReadSingle(); var m_Texture = new PPtr<Texture>(reader); int m_AsciiStartOffset = reader.ReadInt32(); var m_Tracking = reader.ReadSingle(); var m_CharacterSpacing = reader.ReadInt32(); var m_CharacterPadding = reader.ReadInt32(); var m_ConvertCase = reader.ReadInt32(); int m_CharacterRects_size = reader.ReadInt32(); for (int i = 0; i < m_CharacterRects_size; i++) { reader.Position += 44;//CharacterInfo data 41 } int m_KerningValues_size = reader.ReadInt32(); for (int i = 0; i < m_KerningValues_size; i++) { reader.Position += 8; } var m_PixelScale = reader.ReadSingle(); int m_FontData_size = reader.ReadInt32(); if (m_FontData_size > 0) { m_FontData = reader.ReadBytes(m_FontData_size); } } else { int m_AsciiStartOffset = reader.ReadInt32(); if (version[0] <= 3) { int m_FontCountX = reader.ReadInt32(); int m_FontCountY = reader.ReadInt32(); } float m_Kerning = reader.ReadSingle(); float m_LineSpacing = reader.ReadSingle(); if (version[0] <= 3) { int m_PerCharacterKerning_size = reader.ReadInt32(); for (int i = 0; i < m_PerCharacterKerning_size; i++) { int first = reader.ReadInt32(); float second = reader.ReadSingle(); } } else { int m_CharacterSpacing = reader.ReadInt32(); int m_CharacterPadding = reader.ReadInt32(); } int m_ConvertCase = reader.ReadInt32(); var m_DefaultMaterial = new PPtr<Material>(reader); int m_CharacterRects_size = reader.ReadInt32(); for (int i = 0; i < m_CharacterRects_size; i++) { int index = reader.ReadInt32(); //Rectf uv float uvx = reader.ReadSingle(); float uvy = reader.ReadSingle(); float uvwidth = reader.ReadSingle(); float uvheight = reader.ReadSingle(); //Rectf vert float vertx = reader.ReadSingle(); float verty = reader.ReadSingle(); float vertwidth = reader.ReadSingle(); float vertheight = reader.ReadSingle(); float width = reader.ReadSingle(); if (version[0] >= 4) { var flipped = reader.ReadBoolean(); reader.AlignStream(); } } var m_Texture = new PPtr<Texture>(reader); int m_KerningValues_size = reader.ReadInt32(); for (int i = 0; i < m_KerningValues_size; i++) { int pairfirst = reader.ReadInt16(); int pairsecond = reader.ReadInt16(); float second = reader.ReadSingle(); } if (version[0] <= 3) { var m_GridFont = reader.ReadBoolean(); reader.AlignStream(); } else { float m_PixelScale = reader.ReadSingle(); } int m_FontData_size = reader.ReadInt32(); if (m_FontData_size > 0) { m_FontData = reader.ReadBytes(m_FontData_size); } } } } }
AssetStudio/AssetStudio/Classes/Font.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/Font.cs", "repo_id": "AssetStudio", "token_count": 2588 }
67
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public abstract class RuntimeAnimatorController : NamedObject { protected RuntimeAnimatorController(ObjectReader reader) : base(reader) { } } }
AssetStudio/AssetStudio/Classes/RuntimeAnimatorController.cs/0
{ "file_path": "AssetStudio/AssetStudio/Classes/RuntimeAnimatorController.cs", "repo_id": "AssetStudio", "token_count": 104 }
68
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public class FileIdentifier { public Guid guid; public int type; //enum { kNonAssetType = 0, kDeprecatedCachedAssetType = 1, kSerializedAssetType = 2, kMetaAssetType = 3 }; public string pathName; //custom public string fileName; } }
AssetStudio/AssetStudio/FileIdentifier.cs/0
{ "file_path": "AssetStudio/AssetStudio/FileIdentifier.cs", "repo_id": "AssetStudio", "token_count": 153 }
69
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssetStudio { public class ObjectInfo { public long byteStart; public uint byteSize; public int typeID; public int classID; public ushort isDestroyed; public byte stripped; public long m_PathID; public SerializedType serializedType; } }
AssetStudio/AssetStudio/ObjectInfo.cs/0
{ "file_path": "AssetStudio/AssetStudio/ObjectInfo.cs", "repo_id": "AssetStudio", "token_count": 168 }
70
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="源文件"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="头文件"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions> </Filter> <Filter Include="资源文件"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="utils.cpp"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="api.cpp"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="asfbx_context.cpp"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="asfbx_skin_context.cpp"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="asfbx_anim_context.cpp"> <Filter>源文件</Filter> </ClCompile> <ClCompile Include="asfbx_morph_context.cpp"> <Filter>源文件</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="dllexport.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="api.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="utils.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="bool32_t.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="asfbx_context.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="asfbx_skin_context.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="asfbx_anim_context.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="asfbx_morph_context.h"> <Filter>头文件</Filter> </ClInclude> <ClInclude Include="resource.h"> <Filter>头文件</Filter> </ClInclude> </ItemGroup> <ItemGroup> <None Include="cpp.hint" /> </ItemGroup> <ItemGroup> <ResourceCompile Include="AssetStudioFBXNative.rc"> <Filter>资源文件</Filter> </ResourceCompile> </ItemGroup> </Project>
AssetStudio/AssetStudioFBXNative/AssetStudioFBXNative.vcxproj.filters/0
{ "file_path": "AssetStudio/AssetStudioFBXNative/AssetStudioFBXNative.vcxproj.filters", "repo_id": "AssetStudio", "token_count": 1187 }
71
#pragma once struct Vector3 { float X; float Y; float Z; Vector3(); Vector3(float x, float y, float z); }; struct Quaternion { float X; float Y; float Z; float W; Quaternion(); Quaternion(float x, float y, float z); Quaternion(float x, float y, float z, float w); }; Vector3 QuaternionToEuler(Quaternion q); Quaternion EulerToQuaternion(Vector3 v);
AssetStudio/AssetStudioFBXNative/utils.h/0
{ "file_path": "AssetStudio/AssetStudioFBXNative/utils.h", "repo_id": "AssetStudio", "token_count": 150 }
72
using System.Collections.Generic; using System.Text; using System.Windows.Forms; using AssetStudio; namespace AssetStudioGUI { internal class TypeTreeItem : ListViewItem { private TypeTree m_Type; public TypeTreeItem(int typeID, TypeTree m_Type) { this.m_Type = m_Type; Text = m_Type.m_Nodes[0].m_Type + " " + m_Type.m_Nodes[0].m_Name; SubItems.Add(typeID.ToString()); } public override string ToString() { var sb = new StringBuilder(); foreach (var i in m_Type.m_Nodes) { sb.AppendFormat("{0}{1} {2} {3} {4}\r\n", new string('\t', i.m_Level), i.m_Type, i.m_Name, i.m_ByteSize, (i.m_MetaFlag & 0x4000) != 0); } return sb.ToString(); } } }
AssetStudio/AssetStudioGUI/Components/TypeTreeItem.cs/0
{ "file_path": "AssetStudio/AssetStudioGUI/Components/TypeTreeItem.cs", "repo_id": "AssetStudio", "token_count": 425 }
73
/* ========================================================================================== */ /* */ /* FMOD Studio - C# Wrapper . Copyright (c), Firelight Technologies Pty, Ltd. 2004-2016. */ /* */ /* ========================================================================================== */ using System; using System.Text; using System.Runtime.InteropServices; using AssetStudio.PInvoke; namespace FMOD { /* FMOD version number. Check this against FMOD::System::getVersion / System_GetVersion 0xaaaabbcc -> aaaa = major version number. bb = minor version number. cc = development version number. */ public class VERSION { public const int number = 0x00010716; #if WIN64 public const string dll = "fmod64"; #else public const string dll = "fmod"; #endif } public class CONSTANTS { public const int MAX_CHANNEL_WIDTH = 32; public const int MAX_LISTENERS = 8; } /* FMOD types */ /* [ENUM] [ [DESCRIPTION] error codes. Returned from every function. [REMARKS] [SEE_ALSO] ] */ public enum RESULT : int { OK, /* No errors. */ ERR_BADCOMMAND, /* Tried to call a function on a data type that does not allow this type of functionality (ie calling Sound::lock on a streaming sound). */ ERR_CHANNEL_ALLOC, /* Error trying to allocate a channel. */ ERR_CHANNEL_STOLEN, /* The specified channel has been reused to play another sound. */ ERR_DMA, /* DMA Failure. See debug output for more information. */ ERR_DSP_CONNECTION, /* DSP connection error. Connection possibly caused a cyclic dependency or connected dsps with incompatible buffer counts. */ ERR_DSP_DONTPROCESS, /* DSP return code from a DSP process query callback. Tells mixer not to call the process callback and therefore not consume CPU. Use this to optimize the DSP graph. */ ERR_DSP_FORMAT, /* DSP Format error. A DSP unit may have attempted to connect to this network with the wrong format, or a matrix may have been set with the wrong size if the target unit has a specified channel map. */ ERR_DSP_INUSE, /* DSP is already in the mixer's DSP network. It must be removed before being reinserted or released. */ ERR_DSP_NOTFOUND, /* DSP connection error. Couldn't find the DSP unit specified. */ ERR_DSP_RESERVED, /* DSP operation error. Cannot perform operation on this DSP as it is reserved by the system. */ ERR_DSP_SILENCE, /* DSP return code from a DSP process query callback. Tells mixer silence would be produced from read, so go idle and not consume CPU. Use this to optimize the DSP graph. */ ERR_DSP_TYPE, /* DSP operation cannot be performed on a DSP of this type. */ ERR_FILE_BAD, /* Error loading file. */ ERR_FILE_COULDNOTSEEK, /* Couldn't perform seek operation. This is a limitation of the medium (ie netstreams) or the file format. */ ERR_FILE_DISKEJECTED, /* Media was ejected while reading. */ ERR_FILE_EOF, /* End of file unexpectedly reached while trying to read essential data (truncated?). */ ERR_FILE_ENDOFDATA, /* End of current chunk reached while trying to read data. */ ERR_FILE_NOTFOUND, /* File not found. */ ERR_FORMAT, /* Unsupported file or audio format. */ ERR_HEADER_MISMATCH, /* There is a version mismatch between the FMOD header and either the FMOD Studio library or the FMOD Low Level library. */ ERR_HTTP, /* A HTTP error occurred. This is a catch-all for HTTP errors not listed elsewhere. */ ERR_HTTP_ACCESS, /* The specified resource requires authentication or is forbidden. */ ERR_HTTP_PROXY_AUTH, /* Proxy authentication is required to access the specified resource. */ ERR_HTTP_SERVER_ERROR, /* A HTTP server error occurred. */ ERR_HTTP_TIMEOUT, /* The HTTP request timed out. */ ERR_INITIALIZATION, /* FMOD was not initialized correctly to support this function. */ ERR_INITIALIZED, /* Cannot call this command after System::init. */ ERR_INTERNAL, /* An error occurred that wasn't supposed to. Contact support. */ ERR_INVALID_FLOAT, /* Value passed in was a NaN, Inf or denormalized float. */ ERR_INVALID_HANDLE, /* An invalid object handle was used. */ ERR_INVALID_PARAM, /* An invalid parameter was passed to this function. */ ERR_INVALID_POSITION, /* An invalid seek position was passed to this function. */ ERR_INVALID_SPEAKER, /* An invalid speaker was passed to this function based on the current speaker mode. */ ERR_INVALID_SYNCPOINT, /* The syncpoint did not come from this sound handle. */ ERR_INVALID_THREAD, /* Tried to call a function on a thread that is not supported. */ ERR_INVALID_VECTOR, /* The vectors passed in are not unit length, or perpendicular. */ ERR_MAXAUDIBLE, /* Reached maximum audible playback count for this sound's soundgroup. */ ERR_MEMORY, /* Not enough memory or resources. */ ERR_MEMORY_CANTPOINT, /* Can't use FMOD_OPENMEMORY_POINT on non PCM source data, or non mp3/xma/adpcm data if FMOD_CREATECOMPRESSEDSAMPLE was used. */ ERR_NEEDS3D, /* Tried to call a command on a 2d sound when the command was meant for 3d sound. */ ERR_NEEDSHARDWARE, /* Tried to use a feature that requires hardware support. */ ERR_NET_CONNECT, /* Couldn't connect to the specified host. */ ERR_NET_SOCKET_ERROR, /* A socket error occurred. This is a catch-all for socket-related errors not listed elsewhere. */ ERR_NET_URL, /* The specified URL couldn't be resolved. */ ERR_NET_WOULD_BLOCK, /* Operation on a non-blocking socket could not complete immediately. */ ERR_NOTREADY, /* Operation could not be performed because specified sound/DSP connection is not ready. */ ERR_OUTPUT_ALLOCATED, /* Error initializing output device, but more specifically, the output device is already in use and cannot be reused. */ ERR_OUTPUT_CREATEBUFFER, /* Error creating hardware sound buffer. */ ERR_OUTPUT_DRIVERCALL, /* A call to a standard soundcard driver failed, which could possibly mean a bug in the driver or resources were missing or exhausted. */ ERR_OUTPUT_FORMAT, /* Soundcard does not support the specified format. */ ERR_OUTPUT_INIT, /* Error initializing output device. */ ERR_OUTPUT_NODRIVERS, /* The output device has no drivers installed. If pre-init, FMOD_OUTPUT_NOSOUND is selected as the output mode. If post-init, the function just fails. */ ERR_PLUGIN, /* An unspecified error has been returned from a plugin. */ ERR_PLUGIN_MISSING, /* A requested output, dsp unit type or codec was not available. */ ERR_PLUGIN_RESOURCE, /* A resource that the plugin requires cannot be found. (ie the DLS file for MIDI playback) */ ERR_PLUGIN_VERSION, /* A plugin was built with an unsupported SDK version. */ ERR_RECORD, /* An error occurred trying to initialize the recording device. */ ERR_REVERB_CHANNELGROUP, /* Reverb properties cannot be set on this channel because a parent channelgroup owns the reverb connection. */ ERR_REVERB_INSTANCE, /* Specified instance in FMOD_REVERB_PROPERTIES couldn't be set. Most likely because it is an invalid instance number or the reverb doesn't exist. */ ERR_SUBSOUNDS, /* The error occurred because the sound referenced contains subsounds when it shouldn't have, or it doesn't contain subsounds when it should have. The operation may also not be able to be performed on a parent sound. */ ERR_SUBSOUND_ALLOCATED, /* This subsound is already being used by another sound, you cannot have more than one parent to a sound. Null out the other parent's entry first. */ ERR_SUBSOUND_CANTMOVE, /* Shared subsounds cannot be replaced or moved from their parent stream, such as when the parent stream is an FSB file. */ ERR_TAGNOTFOUND, /* The specified tag could not be found or there are no tags. */ ERR_TOOMANYCHANNELS, /* The sound created exceeds the allowable input channel count. This can be increased using the 'maxinputchannels' parameter in System::setSoftwareFormat. */ ERR_TRUNCATED, /* The retrieved string is too long to fit in the supplied buffer and has been truncated. */ ERR_UNIMPLEMENTED, /* Something in FMOD hasn't been implemented when it should be! contact support! */ ERR_UNINITIALIZED, /* This command failed because System::init or System::setDriver was not called. */ ERR_UNSUPPORTED, /* A command issued was not supported by this object. Possibly a plugin without certain callbacks specified. */ ERR_VERSION, /* The version number of this file format is not supported. */ ERR_EVENT_ALREADY_LOADED, /* The specified bank has already been loaded. */ ERR_EVENT_LIVEUPDATE_BUSY, /* The live update connection failed due to the game already being connected. */ ERR_EVENT_LIVEUPDATE_MISMATCH, /* The live update connection failed due to the game data being out of sync with the tool. */ ERR_EVENT_LIVEUPDATE_TIMEOUT, /* The live update connection timed out. */ ERR_EVENT_NOTFOUND, /* The requested event, bus or vca could not be found. */ ERR_STUDIO_UNINITIALIZED, /* The Studio::System object is not yet initialized. */ ERR_STUDIO_NOT_LOADED, /* The specified resource is not loaded, so it can't be unloaded. */ ERR_INVALID_STRING, /* An invalid string was passed to this function. */ ERR_ALREADY_LOCKED, /* The specified resource is already locked. */ ERR_NOT_LOCKED, /* The specified resource is not locked, so it can't be unlocked. */ ERR_RECORD_DISCONNECTED, /* The specified recording driver has been disconnected. */ ERR_TOOMANYSAMPLES, /* The length provided exceed the allowable limit. */ } /* [ENUM] [ [DESCRIPTION] Used to distinguish if a FMOD_CHANNELCONTROL parameter is actually a channel or a channelgroup. [REMARKS] Cast the FMOD_CHANNELCONTROL to an FMOD_CHANNEL/FMOD::Channel, or FMOD_CHANNELGROUP/FMOD::ChannelGroup if specific functionality is needed for either class. Otherwise use as FMOD_CHANNELCONTROL/FMOD::ChannelControl and use that API. [SEE_ALSO] Channel::setCallback ChannelGroup::setCallback ] */ public enum CHANNELCONTROL_TYPE : int { CHANNEL, CHANNELGROUP } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a point in 3D space. [REMARKS] FMOD uses a left handed co-ordinate system by default. To use a right handed co-ordinate system specify FMOD_INIT_3D_RIGHTHANDED from FMOD_INITFLAGS in System::init. [SEE_ALSO] System::set3DListenerAttributes System::get3DListenerAttributes Channel::set3DAttributes Channel::get3DAttributes Geometry::addPolygon Geometry::setPolygonVertex Geometry::getPolygonVertex Geometry::setRotation Geometry::getRotation Geometry::setPosition Geometry::getPosition Geometry::setScale Geometry::getScale FMOD_INITFLAGS ] */ [StructLayout(LayoutKind.Sequential)] public struct VECTOR { public float x; /* X co-ordinate in 3D space. */ public float y; /* Y co-ordinate in 3D space. */ public float z; /* Z co-ordinate in 3D space. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a position, velocity and orientation. [REMARKS] [SEE_ALSO] FMOD_VECTOR FMOD_DSP_PARAMETER_3DATTRIBUTES ] */ [StructLayout(LayoutKind.Sequential)] public struct _3D_ATTRIBUTES { VECTOR position; VECTOR velocity; VECTOR forward; VECTOR up; } /* [STRUCTURE] [ [DESCRIPTION] Structure that is passed into FMOD_FILE_ASYNCREAD_CALLBACK. Use the information in this structure to perform [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value.<br> <br> Instructions: write to 'buffer', and 'bytesread' <b>BEFORE</b> setting 'result'.<br> As soon as result is set, FMOD will asynchronously continue internally using the data provided in this structure.<br> <br> Set 'result' to the result expected from a normal file read callback.<br> If the read was successful, set it to FMOD_OK.<br> If it read some data but hit the end of the file, set it to FMOD_ERR_FILE_EOF.<br> If a bad error occurred, return FMOD_ERR_FILE_BAD<br> If a disk was ejected, return FMOD_ERR_FILE_DISKEJECTED.<br> [SEE_ALSO] FMOD_FILE_ASYNCREAD_CALLBACK FMOD_FILE_ASYNCCANCEL_CALLBACK ] */ [StructLayout(LayoutKind.Sequential)] public struct ASYNCREADINFO { public IntPtr handle; /* [r] The file handle that was filled out in the open callback. */ public uint offset; /* [r] Seek position, make sure you read from this file offset. */ public uint sizebytes; /* [r] how many bytes requested for read. */ public int priority; /* [r] 0 = low importance. 100 = extremely important (ie 'must read now or stuttering may occur') */ public IntPtr userdata; /* [r] User data pointer. */ public IntPtr buffer; /* [w] Buffer to read file data into. */ public uint bytesread; /* [w] Fill this in before setting result code to tell FMOD how many bytes were read. */ public ASYNCREADINFO_DONE_CALLBACK done; /* [r] FMOD file system wake up function. Call this when user file read is finished. Pass result of file read as a parameter. */ } /* [ENUM] [ [DESCRIPTION] These output types are used with System::setOutput / System::getOutput, to choose which output method to use. [REMARKS] To pass information to the driver when initializing fmod use the *extradriverdata* parameter in System::init for the following reasons. - FMOD_OUTPUTTYPE_WAVWRITER - extradriverdata is a pointer to a char * file name that the wav writer will output to. - FMOD_OUTPUTTYPE_WAVWRITER_NRT - extradriverdata is a pointer to a char * file name that the wav writer will output to. - FMOD_OUTPUTTYPE_DSOUND - extradriverdata is cast to a HWND type, so that FMOD can set the focus on the audio for a particular window. - FMOD_OUTPUTTYPE_PS3 - extradriverdata is a pointer to a FMOD_PS3_EXTRADRIVERDATA struct. This can be found in fmodps3.h. - FMOD_OUTPUTTYPE_XBOX360 - extradriverdata is a pointer to a FMOD_360_EXTRADRIVERDATA struct. This can be found in fmodxbox360.h. Currently these are the only FMOD drivers that take extra information. Other unknown plugins may have different requirements. Note! If FMOD_OUTPUTTYPE_WAVWRITER_NRT or FMOD_OUTPUTTYPE_NOSOUND_NRT are used, and if the System::update function is being called very quickly (ie for a non realtime decode) it may be being called too quickly for the FMOD streamer thread to respond to. The result will be a skipping/stuttering output in the captured audio. To remedy this, disable the FMOD streamer thread, and use FMOD_INIT_STREAM_FROM_UPDATE to avoid skipping in the output stream, as it will lock the mixer and the streamer together in the same thread. [SEE_ALSO] System::setOutput System::getOutput System::setSoftwareFormat System::getSoftwareFormat System::init System::update FMOD_INITFLAGS ] */ public enum OUTPUTTYPE : int { AUTODETECT, /* Picks the best output mode for the platform. This is the default. */ UNKNOWN, /* All - 3rd party plugin, unknown. This is for use with System::getOutput only. */ NOSOUND, /* All - Perform all mixing but discard the final output. */ WAVWRITER, /* All - Writes output to a .wav file. */ NOSOUND_NRT, /* All - Non-realtime version of FMOD_OUTPUTTYPE_NOSOUND. User can drive mixer with System::update at whatever rate they want. */ WAVWRITER_NRT, /* All - Non-realtime version of FMOD_OUTPUTTYPE_WAVWRITER. User can drive mixer with System::update at whatever rate they want. */ DSOUND, /* Win - Direct Sound. (Default on Windows XP and below) */ WINMM, /* Win - Windows Multimedia. */ WASAPI, /* Win/WinStore/XboxOne - Windows Audio Session API. (Default on Windows Vista and above, Xbox One and Windows Store Applications) */ ASIO, /* Win - Low latency ASIO 2.0. */ PULSEAUDIO, /* Linux - Pulse Audio. (Default on Linux if available) */ ALSA, /* Linux - Advanced Linux Sound Architecture. (Default on Linux if PulseAudio isn't available) */ COREAUDIO, /* Mac/iOS - Core Audio. (Default on Mac and iOS) */ XBOX360, /* Xbox 360 - XAudio. (Default on Xbox 360) */ PS3, /* PS3 - Audio Out. (Default on PS3) */ AUDIOTRACK, /* Android - Java Audio Track. (Default on Android 2.2 and below) */ OPENSL, /* Android - OpenSL ES. (Default on Android 2.3 and above) */ WIIU, /* Wii U - AX. (Default on Wii U) */ AUDIOOUT, /* PS4/PSVita - Audio Out. (Default on PS4 and PS Vita) */ MAX, /* Maximum number of output types supported. */ } /* [ENUM] [ [DESCRIPTION] Specify the destination of log output when using the logging version of FMOD. [REMARKS] TTY destination can vary depending on platform, common examples include the Visual Studio / Xcode output window, stderr and LogCat. [SEE_ALSO] FMOD_Debug_Initialize ] */ public enum DEBUG_MODE : int { TTY, /* Default log location per platform, i.e. Visual Studio output window, stderr, LogCat, etc */ FILE, /* Write log to specified file path */ CALLBACK, /* Call specified callback with log information */ } /* [DEFINE] [ [NAME] FMOD_DEBUG_FLAGS [DESCRIPTION] Specify the requested information to be output when using the logging version of FMOD. [REMARKS] [SEE_ALSO] FMOD_Debug_Initialize ] */ [Flags] public enum DEBUG_FLAGS : uint { NONE = 0x00000000, /* Disable all messages */ ERROR = 0x00000001, /* Enable only error messages. */ WARNING = 0x00000002, /* Enable warning and error messages. */ LOG = 0x00000004, /* Enable informational, warning and error messages (default). */ TYPE_MEMORY = 0x00000100, /* Verbose logging for memory operations, only use this if you are debugging a memory related issue. */ TYPE_FILE = 0x00000200, /* Verbose logging for file access, only use this if you are debugging a file related issue. */ TYPE_CODEC = 0x00000400, /* Verbose logging for codec initialization, only use this if you are debugging a codec related issue. */ TYPE_TRACE = 0x00000800, /* Verbose logging for internal errors, use this for tracking the origin of error codes. */ DISPLAY_TIMESTAMPS = 0x00010000, /* Display the time stamp of the log message in milliseconds. */ DISPLAY_LINENUMBERS = 0x00020000, /* Display the source code file and line number for where the message originated. */ DISPLAY_THREAD = 0x00040000, /* Display the thread ID of the calling function that generated the message. */ } /* [DEFINE] [ [NAME] FMOD_MEMORY_TYPE [DESCRIPTION] Bit fields for memory allocation type being passed into FMOD memory callbacks. [REMARKS] Remember this is a bitfield. You may get more than 1 bit set (ie physical + persistent) so do not simply switch on the types! You must check each bit individually or clear out the bits that you do not want within the callback.<br> Bits can be excluded if you want during Memory_Initialize so that you never get them. [SEE_ALSO] FMOD_MEMORY_ALLOC_CALLBACK FMOD_MEMORY_REALLOC_CALLBACK FMOD_MEMORY_FREE_CALLBACK Memory_Initialize ] */ [Flags] public enum MEMORY_TYPE : uint { NORMAL = 0x00000000, /* Standard memory. */ STREAM_FILE = 0x00000001, /* Stream file buffer, size controllable with System::setStreamBufferSize. */ STREAM_DECODE = 0x00000002, /* Stream decode buffer, size controllable with FMOD_CREATESOUNDEXINFO::decodebuffersize. */ SAMPLEDATA = 0x00000004, /* Sample data buffer. Raw audio data, usually PCM/MPEG/ADPCM/XMA data. */ DSP_BUFFER = 0x00000008, /* DSP memory block allocated when more than 1 output exists on a DSP node. */ PLUGIN = 0x00000010, /* Memory allocated by a third party plugin. */ XBOX360_PHYSICAL = 0x00100000, /* Requires XPhysicalAlloc / XPhysicalFree. */ PERSISTENT = 0x00200000, /* Persistent memory. Memory will be freed when System::release is called. */ SECONDARY = 0x00400000, /* Secondary memory. Allocation should be in secondary memory. For example RSX on the PS3. */ ALL = 0xFFFFFFFF } /* [ENUM] [ [DESCRIPTION] These are speaker types defined for use with the System::setSoftwareFormat command. [REMARKS] Note below the phrase 'sound channels' is used. These are the subchannels inside a sound, they are not related and have nothing to do with the FMOD class "Channel".<br> For example a mono sound has 1 sound channel, a stereo sound has 2 sound channels, and an AC3 or 6 channel wav file have 6 "sound channels".<br> <br> FMOD_SPEAKERMODE_RAW<br> ---------------------<br> This mode is for output devices that are not specifically mono/stereo/quad/surround/5.1 or 7.1, but are multichannel.<br> Use System::setSoftwareFormat to specify the number of speakers you want to address, otherwise it will default to 2 (stereo).<br> Sound channels map to speakers sequentially, so a mono sound maps to output speaker 0, stereo sound maps to output speaker 0 & 1.<br> The user assumes knowledge of the speaker order. FMOD_SPEAKER enumerations may not apply, so raw channel indices should be used.<br> Multichannel sounds map input channels to output channels 1:1. <br> Channel::setPan and Channel::setPanLevels do not work.<br> Speaker levels must be manually set with Channel::setPanMatrix.<br> <br> FMOD_SPEAKERMODE_MONO<br> ---------------------<br> This mode is for a 1 speaker arrangement.<br> Panning does not work in this speaker mode.<br> Mono, stereo and multichannel sounds have each sound channel played on the one speaker unity.<br> Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> Channel::setPanLevels does not work.<br> <br> FMOD_SPEAKERMODE_STEREO<br> -----------------------<br> This mode is for 2 speaker arrangements that have a left and right speaker.<br> <li>Mono sounds default to an even distribution between left and right. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the middle, or full left in the left speaker and full right in the right speaker. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds have each sound channel played on each speaker at unity.<br> <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but only front left and right parameters are used, the rest are ignored.<br> <br> FMOD_SPEAKERMODE_QUAD<br> ------------------------<br> This mode is for 4 speaker arrangements that have a front left, front right, surround left and a surround right speaker.<br> <li>Mono sounds default to an even distribution between front left and front right. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right.<br> <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input.<br> <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but rear left, rear right, center and lfe are ignored.<br> <br> FMOD_SPEAKERMODE_SURROUND<br> ------------------------<br> This mode is for 5 speaker arrangements that have a left/right/center/surround left/surround right.<br> <li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input. <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but rear left / rear right are ignored.<br> <br> FMOD_SPEAKERMODE_5POINT1<br> ---------------------------------------------------------<br> This mode is for 5.1 speaker arrangements that have a left/right/center/surround left/surround right and a subwoofer speaker.<br> <li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input. <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but rear left / rear right are ignored.<br> <br> FMOD_SPEAKERMODE_7POINT1<br> ------------------------<br> This mode is for 7.1 speaker arrangements that have a left/right/center/surround left/surround right/rear left/rear right and a subwoofer speaker.<br> <li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input. <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works and every parameter is used to set the balance of a sound in any speaker.<br> <br> [SEE_ALSO] System::setSoftwareFormat System::getSoftwareFormat DSP::setChannelFormat ] */ public enum SPEAKERMODE : int { DEFAULT, /* Default speaker mode based on operating system/output mode. Windows = control panel setting, Xbox = 5.1, PS3 = 7.1 etc. */ RAW, /* There is no specific speakermode. Sound channels are mapped in order of input to output. Use System::setSoftwareFormat to specify speaker count. See remarks for more information. */ MONO, /* The speakers are monaural. */ STEREO, /* The speakers are stereo. */ QUAD, /* 4 speaker setup. This includes front left, front right, surround left, surround right. */ SURROUND, /* 5 speaker setup. This includes front left, front right, center, surround left, surround right. */ _5POINT1, /* 5.1 speaker setup. This includes front left, front right, center, surround left, surround right and an LFE speaker. */ _7POINT1, /* 7.1 speaker setup. This includes front left, front right, center, surround left, surround right, back left, back right and an LFE speaker. */ MAX, /* Maximum number of speaker modes supported. */ } /* [ENUM] [ [DESCRIPTION] Assigns an enumeration for a speaker index. [REMARKS] [SEE_ALSO] System::setSpeakerPosition System::getSpeakerPosition ] */ public enum SPEAKER : int { FRONT_LEFT, FRONT_RIGHT, FRONT_CENTER, LOW_FREQUENCY, SURROUND_LEFT, SURROUND_RIGHT, BACK_LEFT, BACK_RIGHT, MAX, /* Maximum number of speaker types supported. */ } /* [DEFINE] [ [NAME] FMOD_CHANNELMASK [DESCRIPTION] These are bitfields to describe for a certain number of channels in a signal, which channels are being represented.<br> For example, a signal could be 1 channel, but contain the LFE channel only.<br> [REMARKS] FMOD_CHANNELMASK_BACK_CENTER is not represented as an output speaker in fmod - but it is encountered in input formats and is down or upmixed appropriately to the nearest speakers.<br> [SEE_ALSO] DSP::setChannelFormat DSP::getChannelFormat FMOD_SPEAKERMODE ] */ [Flags] public enum CHANNELMASK : uint { FRONT_LEFT = 0x00000001, FRONT_RIGHT = 0x00000002, FRONT_CENTER = 0x00000004, LOW_FREQUENCY = 0x00000008, SURROUND_LEFT = 0x00000010, SURROUND_RIGHT = 0x00000020, BACK_LEFT = 0x00000040, BACK_RIGHT = 0x00000080, BACK_CENTER = 0x00000100, MONO = (FRONT_LEFT), STEREO = (FRONT_LEFT | FRONT_RIGHT), LRC = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER), QUAD = (FRONT_LEFT | FRONT_RIGHT | SURROUND_LEFT | SURROUND_RIGHT), SURROUND = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | SURROUND_LEFT | SURROUND_RIGHT), _5POINT1 = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | LOW_FREQUENCY | SURROUND_LEFT | SURROUND_RIGHT), _5POINT1_REARS = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | LOW_FREQUENCY | BACK_LEFT | BACK_RIGHT), _7POINT0 = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | SURROUND_LEFT | SURROUND_RIGHT | BACK_LEFT | BACK_RIGHT), _7POINT1 = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | LOW_FREQUENCY | SURROUND_LEFT | SURROUND_RIGHT | BACK_LEFT | BACK_RIGHT) } /* [ENUM] [ [DESCRIPTION] When creating a multichannel sound, FMOD will pan them to their default speaker locations, for example a 6 channel sound will default to one channel per 5.1 output speaker.<br> Another example is a stereo sound. It will default to left = front left, right = front right.<br> <br> This is for sounds that are not 'default'. For example you might have a sound that is 6 channels but actually made up of 3 stereo pairs, that should all be located in front left, front right only. [REMARKS] [SEE_ALSO] FMOD_CREATESOUNDEXINFO ] */ public enum CHANNELORDER : int { DEFAULT, /* Left, Right, Center, LFE, Surround Left, Surround Right, Back Left, Back Right (see FMOD_SPEAKER enumeration) */ WAVEFORMAT, /* Left, Right, Center, LFE, Back Left, Back Right, Surround Left, Surround Right (as per Microsoft .wav WAVEFORMAT structure master order) */ PROTOOLS, /* Left, Center, Right, Surround Left, Surround Right, LFE */ ALLMONO, /* Mono, Mono, Mono, Mono, Mono, Mono, ... (each channel all the way up to 32 channels are treated as if they were mono) */ ALLSTEREO, /* Left, Right, Left, Right, Left, Right, ... (each pair of channels is treated as stereo all the way up to 32 channels) */ ALSA, /* Left, Right, Surround Left, Surround Right, Center, LFE (as per Linux ALSA channel order) */ MAX, /* Maximum number of channel orderings supported. */ } /* [ENUM] [ [DESCRIPTION] These are plugin types defined for use with the System::getNumPlugins, System::getPluginInfo and System::unloadPlugin functions. [REMARKS] [SEE_ALSO] System::getNumPlugins System::getPluginInfo System::unloadPlugin ] */ public enum PLUGINTYPE : int { OUTPUT, /* The plugin type is an output module. FMOD mixed audio will play through one of these devices */ CODEC, /* The plugin type is a file format codec. FMOD will use these codecs to load file formats for playback. */ DSP, /* The plugin type is a DSP unit. FMOD will use these plugins as part of its DSP network to apply effects to output or generate sound in realtime. */ MAX, /* Maximum number of plugin types supported. */ } /* [DEFINE] [ [NAME] FMOD_INITFLAGS [DESCRIPTION] Initialization flags. Use them with System::init in the *flags* parameter to change various behavior. [REMARKS] Use System::setAdvancedSettings to adjust settings for some of the features that are enabled by these flags. [SEE_ALSO] System::init System::update System::setAdvancedSettings Channel::set3DOcclusion ] */ [Flags] public enum INITFLAGS : uint { NORMAL = 0x00000000, /* Initialize normally */ STREAM_FROM_UPDATE = 0x00000001, /* No stream thread is created internally. Streams are driven from System::update. Mainly used with non-realtime outputs. */ MIX_FROM_UPDATE = 0x00000002, /* Win/Wii/PS3/Xbox/Xbox 360 Only - FMOD Mixer thread is woken up to do a mix when System::update is called rather than waking periodically on its own timer. */ _3D_RIGHTHANDED = 0x00000004, /* FMOD will treat +X as right, +Y as up and +Z as backwards (towards you). */ CHANNEL_LOWPASS = 0x00000100, /* All FMOD_3D based voices will add a software lowpass filter effect into the DSP chain which is automatically used when Channel::set3DOcclusion is used or the geometry API. This also causes sounds to sound duller when the sound goes behind the listener, as a fake HRTF style effect. Use System::setAdvancedSettings to disable or adjust cutoff frequency for this feature. */ CHANNEL_DISTANCEFILTER = 0x00000200, /* All FMOD_3D based voices will add a software lowpass and highpass filter effect into the DSP chain which will act as a distance-automated bandpass filter. Use System::setAdvancedSettings to adjust the center frequency. */ PROFILE_ENABLE = 0x00010000, /* Enable TCP/IP based host which allows FMOD Designer or FMOD Profiler to connect to it, and view memory, CPU and the DSP network graph in real-time. */ VOL0_BECOMES_VIRTUAL = 0x00020000, /* Any sounds that are 0 volume will go virtual and not be processed except for having their positions updated virtually. Use System::setAdvancedSettings to adjust what volume besides zero to switch to virtual at. */ GEOMETRY_USECLOSEST = 0x00040000, /* With the geometry engine, only process the closest polygon rather than accumulating all polygons the sound to listener line intersects. */ PREFER_DOLBY_DOWNMIX = 0x00080000, /* When using FMOD_SPEAKERMODE_5POINT1 with a stereo output device, use the Dolby Pro Logic II downmix algorithm instead of the SRS Circle Surround algorithm. */ THREAD_UNSAFE = 0x00100000, /* Disables thread safety for API calls. Only use this if FMOD low level is being called from a single thread, and if Studio API is not being used! */ PROFILE_METER_ALL = 0x00200000 /* Slower, but adds level metering for every single DSP unit in the graph. Use DSP::setMeteringEnabled to turn meters off individually. */ } /* [ENUM] [ [DESCRIPTION] These definitions describe the type of song being played. [REMARKS] [SEE_ALSO] Sound::getFormat ] */ public enum SOUND_TYPE { UNKNOWN, /* 3rd party / unknown plugin format. */ AIFF, /* AIFF. */ ASF, /* Microsoft Advanced Systems Format (ie WMA/ASF/WMV). */ DLS, /* Sound font / downloadable sound bank. */ FLAC, /* FLAC lossless codec. */ FSB, /* FMOD Sample Bank. */ IT, /* Impulse Tracker. */ MIDI, /* MIDI. extracodecdata is a pointer to an FMOD_MIDI_EXTRACODECDATA structure. */ MOD, /* Protracker / Fasttracker MOD. */ MPEG, /* MP2/MP3 MPEG. */ OGGVORBIS, /* Ogg vorbis. */ PLAYLIST, /* Information only from ASX/PLS/M3U/WAX playlists */ RAW, /* Raw PCM data. */ S3M, /* ScreamTracker 3. */ USER, /* User created sound. */ WAV, /* Microsoft WAV. */ XM, /* FastTracker 2 XM. */ XMA, /* Xbox360 XMA */ AUDIOQUEUE, /* iPhone hardware decoder, supports AAC, ALAC and MP3. extracodecdata is a pointer to an FMOD_AUDIOQUEUE_EXTRACODECDATA structure. */ AT9, /* PS4 / PSVita ATRAC 9 format */ VORBIS, /* Vorbis */ MEDIA_FOUNDATION,/* Windows Store Application built in system codecs */ MEDIACODEC, /* Android MediaCodec */ FADPCM, /* FMOD Adaptive Differential Pulse Code Modulation */ MAX, /* Maximum number of sound types supported. */ } /* [ENUM] [ [DESCRIPTION] These definitions describe the native format of the hardware or software buffer that will be used. [REMARKS] This is the format the native hardware or software buffer will be or is created in. [SEE_ALSO] System::createSoundEx Sound::getFormat ] */ public enum SOUND_FORMAT : int { NONE, /* Unitialized / unknown */ PCM8, /* 8bit integer PCM data */ PCM16, /* 16bit integer PCM data */ PCM24, /* 24bit integer PCM data */ PCM32, /* 32bit integer PCM data */ PCMFLOAT, /* 32bit floating point PCM data */ BITSTREAM, /* Sound data is in its native compressed format. */ MAX /* Maximum number of sound formats supported. */ } /* [DEFINE] [ [NAME] FMOD_MODE [DESCRIPTION] Sound description bitfields, bitwise OR them together for loading and describing sounds. [REMARKS] By default a sound will open as a static sound that is decompressed fully into memory to PCM. (ie equivalent of FMOD_CREATESAMPLE)<br> To have a sound stream instead, use FMOD_CREATESTREAM, or use the wrapper function System::createStream.<br> Some opening modes (ie FMOD_OPENUSER, FMOD_OPENMEMORY, FMOD_OPENMEMORY_POINT, FMOD_OPENRAW) will need extra information.<br> This can be provided using the FMOD_CREATESOUNDEXINFO structure. <br> Specifying FMOD_OPENMEMORY_POINT will POINT to your memory rather allocating its own sound buffers and duplicating it internally.<br> <b><u>This means you cannot free the memory while FMOD is using it, until after Sound::release is called.</b></u> With FMOD_OPENMEMORY_POINT, for PCM formats, only WAV, FSB, and RAW are supported. For compressed formats, only those formats supported by FMOD_CREATECOMPRESSEDSAMPLE are supported.<br> With FMOD_OPENMEMORY_POINT and FMOD_OPENRAW or PCM, if using them together, note that you must pad the data on each side by 16 bytes. This is so fmod can modify the ends of the data for looping/interpolation/mixing purposes. If a wav file, you will need to insert silence, and then reset loop points to stop the playback from playing that silence.<br> <br> <b>Xbox 360 memory</b> On Xbox 360 Specifying FMOD_OPENMEMORY_POINT to a virtual memory address will cause FMOD_ERR_INVALID_ADDRESS to be returned. Use physical memory only for this functionality.<br> <br> FMOD_LOWMEM is used on a sound if you want to minimize the memory overhead, by having FMOD not allocate memory for certain features that are not likely to be used in a game environment. These are :<br> 1. Sound::getName functionality is removed. 256 bytes per sound is saved.<br> [SEE_ALSO] System::createSound System::createStream Sound::setMode Sound::getMode Channel::setMode Channel::getMode Sound::set3DCustomRolloff Channel::set3DCustomRolloff Sound::getOpenState ] */ [Flags] public enum MODE : uint { DEFAULT = 0x00000000, /* Default for all modes listed below. FMOD_LOOP_OFF, FMOD_2D, FMOD_3D_WORLDRELATIVE, FMOD_3D_INVERSEROLLOFF */ LOOP_OFF = 0x00000001, /* For non looping sounds. (default). Overrides FMOD_LOOP_NORMAL / FMOD_LOOP_BIDI. */ LOOP_NORMAL = 0x00000002, /* For forward looping sounds. */ LOOP_BIDI = 0x00000004, /* For bidirectional looping sounds. (only works on software mixed static sounds). */ _2D = 0x00000008, /* Ignores any 3d processing. (default). */ _3D = 0x00000010, /* Makes the sound positionable in 3D. Overrides FMOD_2D. */ CREATESTREAM = 0x00000080, /* Decompress at runtime, streaming from the source provided (standard stream). Overrides FMOD_CREATESAMPLE. */ CREATESAMPLE = 0x00000100, /* Decompress at loadtime, decompressing or decoding whole file into memory as the target sample format. (standard sample). */ CREATECOMPRESSEDSAMPLE = 0x00000200, /* Load MP2, MP3, IMAADPCM or XMA into memory and leave it compressed. During playback the FMOD software mixer will decode it in realtime as a 'compressed sample'. Can only be used in combination with FMOD_SOFTWARE. */ OPENUSER = 0x00000400, /* Opens a user created static sample or stream. Use FMOD_CREATESOUNDEXINFO to specify format and/or read callbacks. If a user created 'sample' is created with no read callback, the sample will be empty. Use FMOD_Sound_Lock and FMOD_Sound_Unlock to place sound data into the sound if this is the case. */ OPENMEMORY = 0x00000800, /* "name_or_data" will be interpreted as a pointer to memory instead of filename for creating sounds. */ OPENMEMORY_POINT = 0x10000000, /* "name_or_data" will be interpreted as a pointer to memory instead of filename for creating sounds. Use FMOD_CREATESOUNDEXINFO to specify length. This differs to FMOD_OPENMEMORY in that it uses the memory as is, without duplicating the memory into its own buffers. Cannot be freed after open, only after Sound::release. Will not work if the data is compressed and FMOD_CREATECOMPRESSEDSAMPLE is not used. */ OPENRAW = 0x00001000, /* Will ignore file format and treat as raw pcm. User may need to declare if data is FMOD_SIGNED or FMOD_UNSIGNED */ OPENONLY = 0x00002000, /* Just open the file, dont prebuffer or read. Good for fast opens for info, or when sound::readData is to be used. */ ACCURATETIME = 0x00004000, /* For FMOD_CreateSound - for accurate FMOD_Sound_GetLength / FMOD_Channel_SetPosition on VBR MP3, AAC and MOD/S3M/XM/IT/MIDI files. Scans file first, so takes longer to open. FMOD_OPENONLY does not affect this. */ MPEGSEARCH = 0x00008000, /* For corrupted / bad MP3 files. This will search all the way through the file until it hits a valid MPEG header. Normally only searches for 4k. */ NONBLOCKING = 0x00010000, /* For opening sounds and getting streamed subsounds (seeking) asyncronously. Use Sound::getOpenState to poll the state of the sound as it opens or retrieves the subsound in the background. */ UNIQUE = 0x00020000, /* Unique sound, can only be played one at a time */ _3D_HEADRELATIVE = 0x00040000, /* Make the sound's position, velocity and orientation relative to the listener. */ _3D_WORLDRELATIVE = 0x00080000, /* Make the sound's position, velocity and orientation absolute (relative to the world). (DEFAULT) */ _3D_INVERSEROLLOFF = 0x00100000, /* This sound will follow the inverse rolloff model where mindistance = full volume, maxdistance = where sound stops attenuating, and rolloff is fixed according to the global rolloff factor. (DEFAULT) */ _3D_LINEARROLLOFF = 0x00200000, /* This sound will follow a linear rolloff model where mindistance = full volume, maxdistance = silence. */ _3D_LINEARSQUAREROLLOFF= 0x00400000, /* This sound will follow a linear-square rolloff model where mindistance = full volume, maxdistance = silence. Rolloffscale is ignored. */ _3D_INVERSETAPEREDROLLOFF = 0x00800000, /* This sound will follow the inverse rolloff model at distances close to mindistance and a linear-square rolloff close to maxdistance. */ _3D_CUSTOMROLLOFF = 0x04000000, /* This sound will follow a rolloff model defined by Sound::set3DCustomRolloff / Channel::set3DCustomRolloff. */ _3D_IGNOREGEOMETRY = 0x40000000, /* Is not affect by geometry occlusion. If not specified in Sound::setMode, or Channel::setMode, the flag is cleared and it is affected by geometry again. */ IGNORETAGS = 0x02000000, /* Skips id3v2/asf/etc tag checks when opening a sound, to reduce seek/read overhead when opening files (helps with CD performance). */ LOWMEM = 0x08000000, /* Removes some features from samples to give a lower memory overhead, like Sound::getName. */ LOADSECONDARYRAM = 0x20000000, /* Load sound into the secondary RAM of supported platform. On PS3, sounds will be loaded into RSX/VRAM. */ VIRTUAL_PLAYFROMSTART = 0x80000000 /* For sounds that start virtual (due to being quiet or low importance), instead of swapping back to audible, and playing at the correct offset according to time, this flag makes the sound play from the start. */ } /* [ENUM] [ [DESCRIPTION] These values describe what state a sound is in after FMOD_NONBLOCKING has been used to open it. [REMARKS] With streams, if you are using FMOD_NONBLOCKING, note that if the user calls Sound::getSubSound, a stream will go into FMOD_OPENSTATE_SEEKING state and sound related commands will return FMOD_ERR_NOTREADY.<br> With streams, if you are using FMOD_NONBLOCKING, note that if the user calls Channel::getPosition, a stream will go into FMOD_OPENSTATE_SETPOSITION state and sound related commands will return FMOD_ERR_NOTREADY.<br> [SEE_ALSO] Sound::getOpenState FMOD_MODE ] */ public enum OPENSTATE : int { READY = 0, /* Opened and ready to play */ LOADING, /* Initial load in progress */ ERROR, /* Failed to open - file not found, out of memory etc. See return value of Sound::getOpenState for what happened. */ CONNECTING, /* Connecting to remote host (internet sounds only) */ BUFFERING, /* Buffering data */ SEEKING, /* Seeking to subsound and re-flushing stream buffer. */ PLAYING, /* Ready and playing, but not possible to release at this time without stalling the main thread. */ SETPOSITION, /* Seeking within a stream to a different position. */ MAX, /* Maximum number of open state types. */ } /* [ENUM] [ [DESCRIPTION] These flags are used with SoundGroup::setMaxAudibleBehavior to determine what happens when more sounds are played than are specified with SoundGroup::setMaxAudible. [REMARKS] When using FMOD_SOUNDGROUP_BEHAVIOR_MUTE, SoundGroup::setMuteFadeSpeed can be used to stop a sudden transition. Instead, the time specified will be used to cross fade between the sounds that go silent and the ones that become audible. [SEE_ALSO] SoundGroup::setMaxAudibleBehavior SoundGroup::getMaxAudibleBehavior SoundGroup::setMaxAudible SoundGroup::getMaxAudible SoundGroup::setMuteFadeSpeed SoundGroup::getMuteFadeSpeed ] */ public enum SOUNDGROUP_BEHAVIOR : int { BEHAVIOR_FAIL, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will simply fail during System::playSound. */ BEHAVIOR_MUTE, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will be silent, then if another sound in the group stops the sound that was silent before becomes audible again. */ BEHAVIOR_STEALLOWEST, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will steal the quietest / least important sound playing in the group. */ MAX, /* Maximum number of sound group behaviors. */ } /* [ENUM] [ [DESCRIPTION] These callback types are used with Channel::setCallback. [REMARKS] Each callback has commanddata parameters passed as int unique to the type of callback.<br> See reference to FMOD_CHANNELCONTROL_CALLBACK to determine what they might mean for each type of callback.<br> <br> <b>Note!</b> Currently the user must call System::update for these callbacks to trigger! [SEE_ALSO] Channel::setCallback ChannelGroup::setCallback FMOD_CHANNELCONTROL_CALLBACK System::update ] */ public enum CHANNELCONTROL_CALLBACK_TYPE : int { END, /* Called when a sound ends. */ VIRTUALVOICE, /* Called when a voice is swapped out or swapped in. */ SYNCPOINT, /* Called when a syncpoint is encountered. Can be from wav file markers. */ OCCLUSION, /* Called when the channel has its geometry occlusion value calculated. Can be used to clamp or change the value. */ MAX, /* Maximum number of callback types supported. */ } /* [ENUM] [ [DESCRIPTION] These enums denote special types of node within a DSP chain. [REMARKS] [SEE_ALSO] Channel::getDSP ChannelGroup::getDSP ] */ public struct CHANNELCONTROL_DSP_INDEX { public const int HEAD = -1; /* Head of the DSP chain. */ public const int FADER = -2; /* Built in fader DSP. */ public const int PANNER = -3; /* Built in panner DSP. */ public const int TAIL = -4; /* Tail of the DSP chain. */ } /* [ENUM] [ [DESCRIPTION] Used to distinguish the instance type passed into FMOD_ERROR_CALLBACK. [REMARKS] Cast the instance of FMOD_ERROR_CALLBACK to the appropriate class indicated by this enum. [SEE_ALSO] ] */ public enum ERRORCALLBACK_INSTANCETYPE { NONE, SYSTEM, CHANNEL, CHANNELGROUP, CHANNELCONTROL, SOUND, SOUNDGROUP, DSP, DSPCONNECTION, GEOMETRY, REVERB3D, STUDIO_SYSTEM, STUDIO_EVENTDESCRIPTION, STUDIO_EVENTINSTANCE, STUDIO_PARAMETERINSTANCE, STUDIO_CUEINSTANCE, STUDIO_BUS, STUDIO_VCA, STUDIO_BANK, STUDIO_COMMANDREPLAY } /* [STRUCTURE] [ [DESCRIPTION] Structure that is passed into FMOD_SYSTEM_CALLBACK for the FMOD_SYSTEM_CALLBACK_ERROR callback type. [REMARKS] The instance pointer will be a type corresponding to the instanceType enum. [SEE_ALSO] FMOD_ERRORCALLBACK_INSTANCETYPE ] */ [StructLayout(LayoutKind.Sequential)] public struct ERRORCALLBACK_INFO { public RESULT result; /* Error code result */ public ERRORCALLBACK_INSTANCETYPE instancetype; /* Type of instance the error occurred on */ public IntPtr instance; /* Instance pointer */ private IntPtr functionname_internal; /* Function that the error occurred on */ private IntPtr functionparams_internal; /* Function parameters that the error ocurred on */ public string functionname { get { return Marshal.PtrToStringAnsi(functionname_internal); } } public string functionparams { get { return Marshal.PtrToStringAnsi(functionparams_internal); } } } /* [DEFINE] [ [NAME] FMOD_SYSTEM_CALLBACK_TYPE [DESCRIPTION] These callback types are used with System::setCallback. [REMARKS] Each callback has commanddata parameters passed as void* unique to the type of callback.<br> See reference to FMOD_SYSTEM_CALLBACK to determine what they might mean for each type of callback.<br> <br> <b>Note!</b> Using FMOD_SYSTEM_CALLBACK_DEVICELISTCHANGED (on Mac only) requires the application to be running an event loop which will allow external changes to device list to be detected by FMOD.<br> <br> <b>Note!</b> The 'system' object pointer will be null for FMOD_SYSTEM_CALLBACK_THREADCREATED and FMOD_SYSTEM_CALLBACK_MEMORYALLOCATIONFAILED callbacks. [SEE_ALSO] System::setCallback System::update DSP::addInput ] */ [Flags] public enum SYSTEM_CALLBACK_TYPE : uint { DEVICELISTCHANGED = 0x00000001, /* Called from System::update when the enumerated list of devices has changed. */ DEVICELOST = 0x00000002, /* Called from System::update when an output device has been lost due to control panel parameter changes and FMOD cannot automatically recover. */ MEMORYALLOCATIONFAILED = 0x00000004, /* Called directly when a memory allocation fails somewhere in FMOD. (NOTE - 'system' will be NULL in this callback type.)*/ THREADCREATED = 0x00000008, /* Called directly when a thread is created. (NOTE - 'system' will be NULL in this callback type.) */ BADDSPCONNECTION = 0x00000010, /* Called when a bad connection was made with DSP::addInput. Usually called from mixer thread because that is where the connections are made. */ PREMIX = 0x00000020, /* Called each tick before a mix update happens. */ POSTMIX = 0x00000040, /* Called each tick after a mix update happens. */ ERROR = 0x00000080, /* Called when each API function returns an error code, including delayed async functions. */ MIDMIX = 0x00000100, /* Called each tick in mix update after clocks have been updated before the main mix occurs. */ THREADDESTROYED = 0x00000200, /* Called directly when a thread is destroyed. */ PREUPDATE = 0x00000400, /* Called at start of System::update function. */ POSTUPDATE = 0x00000800, /* Called at end of System::update function. */ RECORDLISTCHANGED = 0x00001000, /* Called from System::update when the enumerated list of recording devices has changed. */ ALL = 0xFFFFFFFF, /* Pass this mask to System::setCallback to receive all callback types. */ } #region wrapperinternal [StructLayout(LayoutKind.Sequential)] public struct StringWrapper { IntPtr nativeUtf8Ptr; public static implicit operator string(StringWrapper fstring) { if (fstring.nativeUtf8Ptr == IntPtr.Zero) { return ""; } int strlen = 0; while (Marshal.ReadByte(fstring.nativeUtf8Ptr, strlen) != 0) { strlen++; } if (strlen > 0) { byte[] bytes = new byte[strlen]; Marshal.Copy(fstring.nativeUtf8Ptr, bytes, 0, strlen); return Encoding.UTF8.GetString(bytes, 0, strlen); } else { return ""; } } } #endregion /* FMOD Callbacks */ public delegate RESULT ASYNCREADINFO_DONE_CALLBACK(IntPtr info, RESULT result); public delegate RESULT DEBUG_CALLBACK (DEBUG_FLAGS flags, string file, int line, string func, string message); public delegate RESULT SYSTEM_CALLBACK (IntPtr systemraw, SYSTEM_CALLBACK_TYPE type, IntPtr commanddata1, IntPtr commanddata2, IntPtr userdata); public delegate RESULT CHANNEL_CALLBACK (IntPtr channelraw, CHANNELCONTROL_TYPE controltype, CHANNELCONTROL_CALLBACK_TYPE type, IntPtr commanddata1, IntPtr commanddata2); public delegate RESULT SOUND_NONBLOCKCALLBACK (IntPtr soundraw, RESULT result); public delegate RESULT SOUND_PCMREADCALLBACK (IntPtr soundraw, IntPtr data, uint datalen); public delegate RESULT SOUND_PCMSETPOSCALLBACK (IntPtr soundraw, int subsound, uint position, TIMEUNIT postype); public delegate RESULT FILE_OPENCALLBACK (StringWrapper name, ref uint filesize, ref IntPtr handle, IntPtr userdata); public delegate RESULT FILE_CLOSECALLBACK (IntPtr handle, IntPtr userdata); public delegate RESULT FILE_READCALLBACK (IntPtr handle, IntPtr buffer, uint sizebytes, ref uint bytesread, IntPtr userdata); public delegate RESULT FILE_SEEKCALLBACK (IntPtr handle, uint pos, IntPtr userdata); public delegate RESULT FILE_ASYNCREADCALLBACK (IntPtr handle, IntPtr info, IntPtr userdata); public delegate RESULT FILE_ASYNCCANCELCALLBACK (IntPtr handle, IntPtr userdata); public delegate IntPtr MEMORY_ALLOC_CALLBACK (uint size, MEMORY_TYPE type, StringWrapper sourcestr); public delegate IntPtr MEMORY_REALLOC_CALLBACK (IntPtr ptr, uint size, MEMORY_TYPE type, StringWrapper sourcestr); public delegate void MEMORY_FREE_CALLBACK (IntPtr ptr, MEMORY_TYPE type, StringWrapper sourcestr); public delegate float CB_3D_ROLLOFFCALLBACK (IntPtr channelraw, float distance); /* [ENUM] [ [DESCRIPTION] List of interpolation types that the FMOD Ex software mixer supports. [REMARKS] The default resampler type is FMOD_DSP_RESAMPLER_LINEAR.<br> Use System::setSoftwareFormat to tell FMOD the resampling quality you require for FMOD_SOFTWARE based sounds. [SEE_ALSO] System::setSoftwareFormat System::getSoftwareFormat ] */ public enum DSP_RESAMPLER : int { DEFAULT, /* Default interpolation method. Currently equal to FMOD_DSP_RESAMPLER_LINEAR. */ NOINTERP, /* No interpolation. High frequency aliasing hiss will be audible depending on the sample rate of the sound. */ LINEAR, /* Linear interpolation (default method). Fast and good quality, causes very slight lowpass effect on low frequency sounds. */ CUBIC, /* Cubic interpolation. Slower than linear interpolation but better quality. */ SPLINE, /* 5 point spline interpolation. Slowest resampling method but best quality. */ MAX, /* Maximum number of resample methods supported. */ } /* [ENUM] [ [DESCRIPTION] List of connection types between 2 DSP nodes. [REMARKS] FMOD_DSP_CONNECTION_TYPE_STANDARD<br> ----------------------------------<br> Default DSPConnection type. Audio is mixed from the input to the output DSP's audible buffer, meaning it will be part of the audible signal. A standard connection will execute its input DSP if it has not been executed before.<br> <br> FMOD_DSP_CONNECTION_TYPE_SIDECHAIN<br> ----------------------------------<br> Sidechain DSPConnection type. Audio is mixed from the input to the output DSP's sidechain buffer, meaning it will NOT be part of the audible signal. A sidechain connection will execute its input DSP if it has not been executed before.<br> The purpose of the seperate sidechain buffer in a DSP, is so that the DSP effect can privately access for analysis purposes. An example of use in this case, could be a compressor which analyzes the signal, to control its own effect parameters (ie a compression level or gain).<br> <br> For the effect developer, to accept sidechain data, the sidechain data will appear in the FMOD_DSP_STATE struct which is passed into the read callback of a DSP unit.<br> FMOD_DSP_STATE::sidechaindata and FMOD_DSP::sidechainchannels will hold the mixed result of any sidechain data flowing into it.<br> <br> FMOD_DSP_CONNECTION_TYPE_SEND<br> -----------------------------<br> Send DSPConnection type. Audio is mixed from the input to the output DSP's audible buffer, meaning it will be part of the audible signal. A send connection will NOT execute its input DSP if it has not been executed before.<br> A send connection will only read what exists at the input's buffer at the time of executing the output DSP unit (which can be considered the 'return')<br> <br> FMOD_DSP_CONNECTION_TYPE_SEND_SIDECHAIN<br> ---------------------------------------<br> Send sidechain DSPConnection type. Audio is mixed from the input to the output DSP's sidechain buffer, meaning it will NOT be part of the audible signal. A send sidechain connection will NOT execute its input DSP if it has not been executed before.<br> A send sidechain connection will only read what exists at the input's buffer at the time of executing the output DSP unit (which can be considered the 'sidechain return'). <br> For the effect developer, to accept sidechain data, the sidechain data will appear in the FMOD_DSP_STATE struct which is passed into the read callback of a DSP unit.<br> FMOD_DSP_STATE::sidechaindata and FMOD_DSP::sidechainchannels will hold the mixed result of any sidechain data flowing into it. [SEE_ALSO] DSP::addInput DSPConnection::getType ] */ public enum DSPCONNECTION_TYPE : int { STANDARD, /* Default connection type. Audio is mixed from the input to the output DSP's audible buffer. */ SIDECHAIN, /* Sidechain connection type. Audio is mixed from the input to the output DSP's sidechain buffer. */ SEND, /* Send connection type. Audio is mixed from the input to the output DSP's audible buffer, but the input is NOT executed, only copied from. A standard connection or sidechain needs to make an input execute to generate data. */ SEND_SIDECHAIN, /* Send sidechain connection type. Audio is mixed from the input to the output DSP's sidechain buffer, but the input is NOT executed, only copied from. A standard connection or sidechain needs to make an input execute to generate data. */ MAX, /* Maximum number of DSP connection types supported. */ } /* [ENUM] [ [DESCRIPTION] List of tag types that could be stored within a sound. These include id3 tags, metadata from netstreams and vorbis/asf data. [REMARKS] [SEE_ALSO] Sound::getTag ] */ public enum TAGTYPE : int { UNKNOWN = 0, ID3V1, ID3V2, VORBISCOMMENT, SHOUTCAST, ICECAST, ASF, MIDI, PLAYLIST, FMOD, USER, MAX /* Maximum number of tag types supported. */ } /* [ENUM] [ [DESCRIPTION] List of data types that can be returned by Sound::getTag [REMARKS] [SEE_ALSO] Sound::getTag ] */ public enum TAGDATATYPE : int { BINARY = 0, INT, FLOAT, STRING, STRING_UTF16, STRING_UTF16BE, STRING_UTF8, CDTOC, MAX /* Maximum number of tag datatypes supported. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a piece of tag data. [REMARKS] Members marked with [w] mean the user sets the value before passing it to the function. Members marked with [r] mean FMOD sets the value to be used after the function exits. [SEE_ALSO] Sound::getTag TAGTYPE TAGDATATYPE ] */ [StructLayout(LayoutKind.Sequential)] public struct TAG { public TAGTYPE type; /* [r] The type of this tag. */ public TAGDATATYPE datatype; /* [r] The type of data that this tag contains */ private IntPtr name_internal;/* [r] The name of this tag i.e. "TITLE", "ARTIST" etc. */ public IntPtr data; /* [r] Pointer to the tag data - its format is determined by the datatype member */ public uint datalen; /* [r] Length of the data contained in this tag */ public bool updated; /* [r] True if this tag has been updated since last being accessed with Sound::getTag */ public string name { get { return Marshal.PtrToStringAnsi(name_internal); } } } /* [DEFINE] [ [NAME] FMOD_TIMEUNIT [DESCRIPTION] List of time types that can be returned by Sound::getLength and used with Channel::setPosition or Channel::getPosition. [REMARKS] Do not combine flags except FMOD_TIMEUNIT_BUFFERED. [SEE_ALSO] Sound::getLength Channel::setPosition Channel::getPosition ] */ [Flags] public enum TIMEUNIT : uint { MS = 0x00000001, /* Milliseconds. */ PCM = 0x00000002, /* PCM Samples, related to milliseconds * samplerate / 1000. */ PCMBYTES = 0x00000004, /* Bytes, related to PCM samples * channels * datawidth (ie 16bit = 2 bytes). */ RAWBYTES = 0x00000008, /* Raw file bytes of (compressed) sound data (does not include headers). Only used by Sound::getLength and Channel::getPosition. */ PCMFRACTION = 0x00000010, /* Fractions of 1 PCM sample. Unsigned int range 0 to 0xFFFFFFFF. Used for sub-sample granularity for DSP purposes. */ MODORDER = 0x00000100, /* MOD/S3M/XM/IT. Order in a sequenced module format. Use Sound::getFormat to determine the format. */ MODROW = 0x00000200, /* MOD/S3M/XM/IT. Current row in a sequenced module format. Sound::getLength will return the number if rows in the currently playing or seeked to pattern. */ MODPATTERN = 0x00000400, /* MOD/S3M/XM/IT. Current pattern in a sequenced module format. Sound::getLength will return the number of patterns in the song and Channel::getPosition will return the currently playing pattern. */ BUFFERED = 0x10000000, /* Time value as seen by buffered stream. This is always ahead of audible time, and is only used for processing. */ } /* [DEFINE] [ [NAME] FMOD_PORT_INDEX [DESCRIPTION] [REMARKS] [SEE_ALSO] System::AttachChannelGroupToPort ] */ public struct PORT_INDEX { public const ulong NONE = 0xFFFFFFFFFFFFFFFF; } /* [STRUCTURE] [ [DESCRIPTION] Use this structure with System::createSound when more control is needed over loading. The possible reasons to use this with System::createSound are: - Loading a file from memory. - Loading a file from within another larger (possibly wad/pak) file, by giving the loader an offset and length. - To create a user created / non file based sound. - To specify a starting subsound to seek to within a multi-sample sounds (ie FSB/DLS) when created as a stream. - To specify which subsounds to load for multi-sample sounds (ie FSB/DLS) so that memory is saved and only a subset is actually loaded/read from disk. - To specify 'piggyback' read and seek callbacks for capture of sound data as fmod reads and decodes it. Useful for ripping decoded PCM data from sounds as they are loaded / played. - To specify a MIDI DLS sample set file to load when opening a MIDI file. See below on what members to fill for each of the above types of sound you want to create. [REMARKS] This structure is optional! Specify 0 or NULL in System::createSound if you don't need it! <u>Loading a file from memory.</u> - Create the sound using the FMOD_OPENMEMORY flag. - Mandatory. Specify 'length' for the size of the memory block in bytes. - Other flags are optional. <u>Loading a file from within another larger (possibly wad/pak) file, by giving the loader an offset and length.</u> - Mandatory. Specify 'fileoffset' and 'length'. - Other flags are optional. <u>To create a user created / non file based sound.</u> - Create the sound using the FMOD_OPENUSER flag. - Mandatory. Specify 'defaultfrequency, 'numchannels' and 'format'. - Other flags are optional. <u>To specify a starting subsound to seek to and flush with, within a multi-sample stream (ie FSB/DLS).</u> - Mandatory. Specify 'initialsubsound'. <u>To specify which subsounds to load for multi-sample sounds (ie FSB/DLS) so that memory is saved and only a subset is actually loaded/read from disk.</u> - Mandatory. Specify 'inclusionlist' and 'inclusionlistnum'. <u>To specify 'piggyback' read and seek callbacks for capture of sound data as fmod reads and decodes it. Useful for ripping decoded PCM data from sounds as they are loaded / played.</u> - Mandatory. Specify 'pcmreadcallback' and 'pcmseekcallback'. <u>To specify a MIDI DLS sample set file to load when opening a MIDI file.</u> - Mandatory. Specify 'dlsname'. Setting the 'decodebuffersize' is for cpu intensive codecs that may be causing stuttering, not file intensive codecs (ie those from CD or netstreams) which are normally altered with System::setStreamBufferSize. As an example of cpu intensive codecs, an mp3 file will take more cpu to decode than a PCM wav file. If you have a stuttering effect, then it is using more cpu than the decode buffer playback rate can keep up with. Increasing the decode buffersize will most likely solve this problem. FSB codec. If inclusionlist and numsubsounds are used together, this will trigger a special mode where subsounds are shuffled down to save memory. (useful for large FSB files where you only want to load 1 sound). There will be no gaps, ie no null subsounds. As an example, if there are 10,000 subsounds and there is an inclusionlist with only 1 entry, and numsubsounds = 1, then subsound 0 will be that entry, and there will only be the memory allocated for 1 subsound. Previously there would still be 10,000 subsound pointers and other associated codec entries allocated along with it multiplied by 10,000. Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] System::createSound System::setStreamBufferSize FMOD_MODE FMOD_SOUND_FORMAT FMOD_SOUND_TYPE FMOD_CHANNELMASK FMOD_CHANNELORDER ] */ [StructLayout(LayoutKind.Sequential)] public struct CREATESOUNDEXINFO { public int cbsize; /* [w] Size of this structure. This is used so the structure can be expanded in the future and still work on older versions of FMOD Ex. */ public uint length; /* [w] Optional. Specify 0 to ignore. Size in bytes of file to load, or sound to create (in this case only if FMOD_OPENUSER is used). Required if loading from memory. If 0 is specified, then it will use the size of the file (unless loading from memory then an error will be returned). */ public uint fileoffset; /* [w] Optional. Specify 0 to ignore. Offset from start of the file to start loading from. This is useful for loading files from inside big data files. */ public int numchannels; /* [w] Optional. Specify 0 to ignore. Number of channels in a sound specified only if OPENUSER is used. */ public int defaultfrequency; /* [w] Optional. Specify 0 to ignore. Default frequency of sound in a sound specified only if OPENUSER is used. Other formats use the frequency determined by the file format. */ public SOUND_FORMAT format; /* [w] Optional. Specify 0 or SOUND_FORMAT_NONE to ignore. Format of the sound specified only if OPENUSER is used. Other formats use the format determined by the file format. */ public uint decodebuffersize; /* [w] Optional. Specify 0 to ignore. For streams. This determines the size of the double buffer (in PCM samples) that a stream uses. Use this for user created streams if you want to determine the size of the callback buffer passed to you. Specify 0 to use FMOD's default size which is currently equivalent to 400ms of the sound format created/loaded. */ public int initialsubsound; /* [w] Optional. Specify 0 to ignore. In a multi-sample file format such as .FSB/.DLS/.SF2, specify the initial subsound to seek to, only if CREATESTREAM is used. */ public int numsubsounds; /* [w] Optional. Specify 0 to ignore or have no subsounds. In a user created multi-sample sound, specify the number of subsounds within the sound that are accessable with Sound::getSubSound / SoundGetSubSound. */ public IntPtr inclusionlist; /* [w] Optional. Specify 0 to ignore. In a multi-sample format such as .FSB/.DLS/.SF2 it may be desirable to specify only a subset of sounds to be loaded out of the whole file. This is an array of subsound indicies to load into memory when created. */ public int inclusionlistnum; /* [w] Optional. Specify 0 to ignore. This is the number of integers contained within the */ public SOUND_PCMREADCALLBACK pcmreadcallback; /* [w] Optional. Specify 0 to ignore. Callback to 'piggyback' on FMOD's read functions and accept or even write PCM data while FMOD is opening the sound. Used for user sounds created with OPENUSER or for capturing decoded data as FMOD reads it. */ public SOUND_PCMSETPOSCALLBACK pcmsetposcallback; /* [w] Optional. Specify 0 to ignore. Callback for when the user calls a seeking function such as Channel::setPosition within a multi-sample sound, and for when it is opened.*/ public SOUND_NONBLOCKCALLBACK nonblockcallback; /* [w] Optional. Specify 0 to ignore. Callback for successful completion, or error while loading a sound that used the FMOD_NONBLOCKING flag.*/ public IntPtr dlsname; /* [w] Optional. Specify 0 to ignore. Filename for a DLS or SF2 sample set when loading a MIDI file. If not specified, on windows it will attempt to open /windows/system32/drivers/gm.dls, otherwise the MIDI will fail to open. */ public IntPtr encryptionkey; /* [w] Optional. Specify 0 to ignore. Key for encrypted FSB file. Without this key an encrypted FSB file will not load. */ public int maxpolyphony; /* [w] Optional. Specify 0 to ingore. For sequenced formats with dynamic channel allocation such as .MID and .IT, this specifies the maximum voice count allowed while playing. .IT defaults to 64. .MID defaults to 32. */ public IntPtr userdata; /* [w] Optional. Specify 0 to ignore. This is user data to be attached to the sound during creation. Access via Sound::getUserData. */ public SOUND_TYPE suggestedsoundtype; /* [w] Optional. Specify 0 or FMOD_SOUND_TYPE_UNKNOWN to ignore. Instead of scanning all codec types, use this to speed up loading by making it jump straight to this codec. */ public FILE_OPENCALLBACK fileuseropen; /* [w] Optional. Specify 0 to ignore. Callback for opening this file. */ public FILE_CLOSECALLBACK fileuserclose; /* [w] Optional. Specify 0 to ignore. Callback for closing this file. */ public FILE_READCALLBACK fileuserread; /* [w] Optional. Specify 0 to ignore. Callback for reading from this file. */ public FILE_SEEKCALLBACK fileuserseek; /* [w] Optional. Specify 0 to ignore. Callback for seeking within this file. */ public FILE_ASYNCREADCALLBACK fileuserasyncread; /* [w] Optional. Specify 0 to ignore. Callback for asyncronously reading from this file. */ public FILE_ASYNCCANCELCALLBACK fileuserasynccancel; /* [w] Optional. Specify 0 to ignore. Callback for cancelling an asyncronous read. */ public IntPtr fileuserdata; /* [w] Optional. Specify 0 to ignore. User data to be passed into the file callbacks. */ public CHANNELORDER channelorder; /* [w] Optional. Specify 0 to ignore. Use this to differ the way fmod maps multichannel sounds to speakers. See FMOD_CHANNELORDER for more. */ public CHANNELMASK channelmask; /* [w] Optional. Specify 0 to ignore. Use this to differ the way fmod maps multichannel sounds to speakers. See FMOD_CHANNELMASK for more. */ public IntPtr initialsoundgroup; /* [w] Optional. Specify 0 to ignore. Specify a sound group if required, to put sound in as it is created. */ public uint initialseekposition; /* [w] Optional. Specify 0 to ignore. For streams. Specify an initial position to seek the stream to. */ public TIMEUNIT initialseekpostype; /* [w] Optional. Specify 0 to ignore. For streams. Specify the time unit for the position set in initialseekposition. */ public int ignoresetfilesystem; /* [w] Optional. Specify 0 to ignore. Set to 1 to use fmod's built in file system. Ignores setFileSystem callbacks and also FMOD_CREATESOUNEXINFO file callbacks. Useful for specific cases where you don't want to use your own file system but want to use fmod's file system (ie net streaming). */ public uint audioqueuepolicy; /* [w] Optional. Specify 0 or FMOD_AUDIOQUEUE_CODECPOLICY_DEFAULT to ignore. Policy used to determine whether hardware or software is used for decoding, see FMOD_AUDIOQUEUE_CODECPOLICY for options (iOS >= 3.0 required, otherwise only hardware is available) */ public uint minmidigranularity; /* [w] Optional. Specify 0 to ignore. Allows you to set a minimum desired MIDI mixer granularity. Values smaller than 512 give greater than default accuracy at the cost of more CPU and vise versa. Specify 0 for default (512 samples). */ public int nonblockthreadid; /* [w] Optional. Specify 0 to ignore. Specifies a thread index to execute non blocking load on. Allows for up to 5 threads to be used for loading at once. This is to avoid one load blocking another. Maximum value = 4. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure defining a reverb environment for FMOD_SOFTWARE based sounds only.<br> [REMARKS] Note the default reverb properties are the same as the FMOD_PRESET_GENERIC preset.<br> Note that integer values that typically range from -10,000 to 1000 are represented in decibels, and are of a logarithmic scale, not linear, wheras float values are always linear.<br> <br> The numerical values listed below are the maximum, minimum and default values for each variable respectively.<br> <br> Hardware voice / Platform Specific reverb support.<br> WII See FMODWII.H for hardware specific reverb functionality.<br> 3DS See FMOD3DS.H for hardware specific reverb functionality.<br> PSP See FMODWII.H for hardware specific reverb functionality.<br> <br> Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value.<br> Members marked with [r/w] are either read or write depending on if you are using System::setReverbProperties (w) or System::getReverbProperties (r). [SEE_ALSO] System::setReverbProperties System::getReverbProperties FMOD_REVERB_PRESETS ] */ #pragma warning disable 414 [StructLayout(LayoutKind.Sequential)] public struct REVERB_PROPERTIES { /* MIN MAX DEFAULT DESCRIPTION */ public float DecayTime; /* [r/w] 0.0 20000.0 1500.0 Reverberation decay time in ms */ public float EarlyDelay; /* [r/w] 0.0 300.0 7.0 Initial reflection delay time */ public float LateDelay; /* [r/w] 0.0 100 11.0 Late reverberation delay time relative to initial reflection */ public float HFReference; /* [r/w] 20.0 20000.0 5000 Reference high frequency (hz) */ public float HFDecayRatio; /* [r/w] 10.0 100.0 50.0 High-frequency to mid-frequency decay time ratio */ public float Diffusion; /* [r/w] 0.0 100.0 100.0 Value that controls the echo density in the late reverberation decay. */ public float Density; /* [r/w] 0.0 100.0 100.0 Value that controls the modal density in the late reverberation decay */ public float LowShelfFrequency; /* [r/w] 20.0 1000.0 250.0 Reference low frequency (hz) */ public float LowShelfGain; /* [r/w] -36.0 12.0 0.0 Relative room effect level at low frequencies */ public float HighCut; /* [r/w] 20.0 20000.0 20000.0 Relative room effect level at high frequencies */ public float EarlyLateMix; /* [r/w] 0.0 100.0 50.0 Early reflections level relative to room effect */ public float WetLevel; /* [r/w] -80.0 20.0 -6.0 Room effect level (at mid frequencies) * */ #region wrapperinternal public REVERB_PROPERTIES(float decayTime, float earlyDelay, float lateDelay, float hfReference, float hfDecayRatio, float diffusion, float density, float lowShelfFrequency, float lowShelfGain, float highCut, float earlyLateMix, float wetLevel) { DecayTime = decayTime; EarlyDelay = earlyDelay; LateDelay = lateDelay; HFReference = hfReference; HFDecayRatio = hfDecayRatio; Diffusion = diffusion; Density = density; LowShelfFrequency = lowShelfFrequency; LowShelfGain = lowShelfGain; HighCut = highCut; EarlyLateMix = earlyLateMix; WetLevel = wetLevel; } #endregion } #pragma warning restore 414 /* [DEFINE] [ [NAME] FMOD_REVERB_PRESETS [DESCRIPTION] A set of predefined environment PARAMETERS, created by Creative Labs These are used to initialize an FMOD_REVERB_PROPERTIES structure statically. ie FMOD_REVERB_PROPERTIES prop = FMOD_PRESET_GENERIC; [SEE_ALSO] System::setReverbProperties ] */ public class PRESET { /* Instance Env Diffus Room RoomHF RmLF DecTm DecHF DecLF Refl RefDel Revb RevDel ModTm ModDp HFRef LFRef Diffus Densty FLAGS */ public static REVERB_PROPERTIES OFF() { return new REVERB_PROPERTIES( 1000, 7, 11, 5000, 100, 100, 100, 250, 0, 20, 96, -80.0f );} public static REVERB_PROPERTIES GENERIC() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 83, 100, 100, 250, 0, 14500, 96, -8.0f );} public static REVERB_PROPERTIES PADDEDCELL() { return new REVERB_PROPERTIES( 170, 1, 2, 5000, 10, 100, 100, 250, 0, 160, 84, -7.8f );} public static REVERB_PROPERTIES ROOM() { return new REVERB_PROPERTIES( 400, 2, 3, 5000, 83, 100, 100, 250, 0, 6050, 88, -9.4f );} public static REVERB_PROPERTIES BATHROOM() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 54, 100, 60, 250, 0, 2900, 83, 0.5f );} public static REVERB_PROPERTIES LIVINGROOM() { return new REVERB_PROPERTIES( 500, 3, 4, 5000, 10, 100, 100, 250, 0, 160, 58, -19.0f );} public static REVERB_PROPERTIES STONEROOM() { return new REVERB_PROPERTIES( 2300, 12, 17, 5000, 64, 100, 100, 250, 0, 7800, 71, -8.5f );} public static REVERB_PROPERTIES AUDITORIUM() { return new REVERB_PROPERTIES( 4300, 20, 30, 5000, 59, 100, 100, 250, 0, 5850, 64, -11.7f );} public static REVERB_PROPERTIES CONCERTHALL() { return new REVERB_PROPERTIES( 3900, 20, 29, 5000, 70, 100, 100, 250, 0, 5650, 80, -9.8f );} public static REVERB_PROPERTIES CAVE() { return new REVERB_PROPERTIES( 2900, 15, 22, 5000, 100, 100, 100, 250, 0, 20000, 59, -11.3f );} public static REVERB_PROPERTIES ARENA() { return new REVERB_PROPERTIES( 7200, 20, 30, 5000, 33, 100, 100, 250, 0, 4500, 80, -9.6f );} public static REVERB_PROPERTIES HANGAR() { return new REVERB_PROPERTIES( 10000, 20, 30, 5000, 23, 100, 100, 250, 0, 3400, 72, -7.4f );} public static REVERB_PROPERTIES CARPETTEDHALLWAY() { return new REVERB_PROPERTIES( 300, 2, 30, 5000, 10, 100, 100, 250, 0, 500, 56, -24.0f );} public static REVERB_PROPERTIES HALLWAY() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 59, 100, 100, 250, 0, 7800, 87, -5.5f );} public static REVERB_PROPERTIES STONECORRIDOR() { return new REVERB_PROPERTIES( 270, 13, 20, 5000, 79, 100, 100, 250, 0, 9000, 86, -6.0f );} public static REVERB_PROPERTIES ALLEY() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 86, 100, 100, 250, 0, 8300, 80, -9.8f );} public static REVERB_PROPERTIES FOREST() { return new REVERB_PROPERTIES( 1500, 162, 88, 5000, 54, 79, 100, 250, 0, 760, 94, -12.3f );} public static REVERB_PROPERTIES CITY() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 67, 50, 100, 250, 0, 4050, 66, -26.0f );} public static REVERB_PROPERTIES MOUNTAINS() { return new REVERB_PROPERTIES( 1500, 300, 100, 5000, 21, 27, 100, 250, 0, 1220, 82, -24.0f );} public static REVERB_PROPERTIES QUARRY() { return new REVERB_PROPERTIES( 1500, 61, 25, 5000, 83, 100, 100, 250, 0, 3400, 100, -5.0f );} public static REVERB_PROPERTIES PLAIN() { return new REVERB_PROPERTIES( 1500, 179, 100, 5000, 50, 21, 100, 250, 0, 1670, 65, -28.0f );} public static REVERB_PROPERTIES PARKINGLOT() { return new REVERB_PROPERTIES( 1700, 8, 12, 5000, 100, 100, 100, 250, 0, 20000, 56, -19.5f );} public static REVERB_PROPERTIES SEWERPIPE() { return new REVERB_PROPERTIES( 2800, 14, 21, 5000, 14, 80, 60, 250, 0, 3400, 66, 1.2f );} public static REVERB_PROPERTIES UNDERWATER() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 10, 100, 100, 250, 0, 500, 92, 7.0f );} } /* [STRUCTURE] [ [DESCRIPTION] Settings for advanced features like configuring memory and cpu usage for the FMOD_CREATECOMPRESSEDSAMPLE feature. [REMARKS] maxMPEGCodecs / maxADPCMCodecs / maxXMACodecs will determine the maximum cpu usage of playing realtime samples. Use this to lower potential excess cpu usage and also control memory usage.<br> [SEE_ALSO] System::setAdvancedSettings System::getAdvancedSettings ] */ [StructLayout(LayoutKind.Sequential)] public struct ADVANCEDSETTINGS { public int cbSize; /* [w] Size of this structure. Use sizeof(FMOD_ADVANCEDSETTINGS) */ public int maxMPEGCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. MPEG codecs consume 30,528 bytes per instance and this number will determine how many MPEG channels can be played simultaneously. Default = 32. */ public int maxADPCMCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. ADPCM codecs consume 3,128 bytes per instance and this number will determine how many ADPCM channels can be played simultaneously. Default = 32. */ public int maxXMACodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. XMA codecs consume 14,836 bytes per instance and this number will determine how many XMA channels can be played simultaneously. Default = 32. */ public int maxVorbisCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. Vorbis codecs consume 23,256 bytes per instance and this number will determine how many Vorbis channels can be played simultaneously. Default = 32. */ public int maxAT9Codecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. AT9 codecs consume 8,720 bytes per instance and this number will determine how many AT9 channels can be played simultaneously. Default = 32. */ public int maxFADPCMCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. This number will determine how many FADPCM channels can be played simultaneously. Default = 32. */ public int maxPCMCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with PS3 only. PCM codecs consume 12,672 bytes per instance and this number will determine how many streams and PCM voices can be played simultaneously. Default = 16. */ public int ASIONumChannels; /* [r/w] Optional. Specify 0 to ignore. Number of channels available on the ASIO device. */ public IntPtr ASIOChannelList; /* [r/w] Optional. Specify 0 to ignore. Pointer to an array of strings (number of entries defined by ASIONumChannels) with ASIO channel names. */ public IntPtr ASIOSpeakerList; /* [r/w] Optional. Specify 0 to ignore. Pointer to a list of speakers that the ASIO channels map to. This can be called after System::init to remap ASIO output. */ public float HRTFMinAngle; /* [r/w] Optional. For use with FMOD_INIT_HRTF_LOWPASS. The angle range (0-360) of a 3D sound in relation to the listener, at which the HRTF function begins to have an effect. 0 = in front of the listener. 180 = from 90 degrees to the left of the listener to 90 degrees to the right. 360 = behind the listener. Default = 180.0. */ public float HRTFMaxAngle; /* [r/w] Optional. For use with FMOD_INIT_HRTF_LOWPASS. The angle range (0-360) of a 3D sound in relation to the listener, at which the HRTF function has maximum effect. 0 = front of the listener. 180 = from 90 degrees to the left of the listener to 90 degrees to the right. 360 = behind the listener. Default = 360.0. */ public float HRTFFreq; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_HRTF_LOWPASS. The cutoff frequency of the HRTF's lowpass filter function when at maximum effect. (i.e. at HRTFMaxAngle). Default = 4000.0. */ public float vol0virtualvol; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_VOL0_BECOMES_VIRTUAL. If this flag is used, and the volume is below this, then the sound will become virtual. Use this value to raise the threshold to a different point where a sound goes virtual. */ public uint defaultDecodeBufferSize; /* [r/w] Optional. Specify 0 to ignore. For streams. This determines the default size of the double buffer (in milliseconds) that a stream uses. Default = 400ms */ public ushort profilePort; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_PROFILE_ENABLE. Specify the port to listen on for connections by the profiler application. */ public uint geometryMaxFadeTime; /* [r/w] Optional. Specify 0 to ignore. The maximum time in miliseconds it takes for a channel to fade to the new level when its occlusion changes. */ public float distanceFilterCenterFreq; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_DISTANCE_FILTERING. The default center frequency in Hz for the distance filtering effect. Default = 1500.0. */ public int reverb3Dinstance; /* [r/w] Optional. Specify 0 to ignore. Out of 0 to 3, 3d reverb spheres will create a phyical reverb unit on this instance slot. See FMOD_REVERB_PROPERTIES. */ public int DSPBufferPoolSize; /* [r/w] Optional. Specify 0 to ignore. Number of buffers in DSP buffer pool. Each buffer will be DSPBlockSize * sizeof(float) * SpeakerModeChannelCount. ie 7.1 @ 1024 DSP block size = 8 * 1024 * 4 = 32kb. Default = 8. */ public uint stackSizeStream; /* [r/w] Optional. Specify 0 to ignore. Specify the stack size for the FMOD Stream thread in bytes. Useful for custom codecs that use excess stack. Default 49,152 (48kb) */ public uint stackSizeNonBlocking; /* [r/w] Optional. Specify 0 to ignore. Specify the stack size for the FMOD_NONBLOCKING loading thread. Useful for custom codecs that use excess stack. Default 65,536 (64kb) */ public uint stackSizeMixer; /* [r/w] Optional. Specify 0 to ignore. Specify the stack size for the FMOD mixer thread. Useful for custom dsps that use excess stack. Default 49,152 (48kb) */ public DSP_RESAMPLER resamplerMethod; /* [r/w] Optional. Specify 0 to ignore. Resampling method used with fmod's software mixer. See FMOD_DSP_RESAMPLER for details on methods. */ public uint commandQueueSize; /* [r/w] Optional. Specify 0 to ignore. Specify the command queue size for thread safe processing. Default 2048 (2kb) */ public uint randomSeed; /* [r/w] Optional. Specify 0 to ignore. Seed value that FMOD will use to initialize its internal random number generators. */ } /* [DEFINE] [ [NAME] FMOD_DRIVER_STATE [DESCRIPTION] Flags that provide additional information about a particular driver. [REMARKS] [SEE_ALSO] System::getRecordDriverInfo ] */ [Flags] public enum DRIVER_STATE : uint { CONNECTED = 0x00000001, /* Device is currently plugged in. */ DEFAULT = 0x00000002, /* Device is the users preferred choice. */ } /* FMOD System factory functions. Use this to create an FMOD System Instance. below you will see System init/close to get started. */ public class Factory { static Factory() { DllLoader.PreloadDll(VERSION.dll); } public static RESULT System_Create(out System system) { system = null; RESULT result = RESULT.OK; IntPtr rawPtr = new IntPtr(); result = FMOD_System_Create(out rawPtr); if (result != RESULT.OK) { return result; } system = new System(rawPtr); return result; } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Create (out IntPtr system); #endregion } public class Memory { public static RESULT Initialize(IntPtr poolmem, int poollen, MEMORY_ALLOC_CALLBACK useralloc, MEMORY_REALLOC_CALLBACK userrealloc, MEMORY_FREE_CALLBACK userfree, MEMORY_TYPE memtypeflags) { return FMOD_Memory_Initialize(poolmem, poollen, useralloc, userrealloc, userfree, memtypeflags); } public static RESULT GetStats(out int currentalloced, out int maxalloced) { return GetStats(out currentalloced, out maxalloced, false); } public static RESULT GetStats(out int currentalloced, out int maxalloced, bool blocking) { return FMOD_Memory_GetStats(out currentalloced, out maxalloced, blocking); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Memory_Initialize(IntPtr poolmem, int poollen, MEMORY_ALLOC_CALLBACK useralloc, MEMORY_REALLOC_CALLBACK userrealloc, MEMORY_FREE_CALLBACK userfree, MEMORY_TYPE memtypeflags); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Memory_GetStats(out int currentalloced, out int maxalloced, bool blocking); #endregion } public class Debug { public static RESULT Initialize(DEBUG_FLAGS flags, DEBUG_MODE mode, DEBUG_CALLBACK callback, string filename) { return FMOD_Debug_Initialize(flags, mode, callback, filename); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Debug_Initialize(DEBUG_FLAGS flags, DEBUG_MODE mode, DEBUG_CALLBACK callback, string filename); #endregion } public class HandleBase { public HandleBase(IntPtr newPtr) { rawPtr = newPtr; } public bool isValid() { return rawPtr != IntPtr.Zero; } public IntPtr getRaw() { return rawPtr; } protected IntPtr rawPtr; #region equality public override bool Equals(Object obj) { return Equals(obj as HandleBase); } public bool Equals(HandleBase p) { // Equals if p not null and handle is the same return ((object)p != null && rawPtr == p.rawPtr); } public override int GetHashCode() { return rawPtr.ToInt32(); } public static bool operator ==(HandleBase a, HandleBase b) { // If both are null, or both are same instance, return true. if (Object.ReferenceEquals(a, b)) { return true; } // If one is null, but not both, return false. if (((object)a == null) || ((object)b == null)) { return false; } // Return true if the handle matches return (a.rawPtr == b.rawPtr); } public static bool operator !=(HandleBase a, HandleBase b) { return !(a == b); } #endregion } /* 'System' API. */ public class System : HandleBase { public RESULT release () { RESULT result = FMOD_System_Release(rawPtr); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Pre-init functions. public RESULT setOutput (OUTPUTTYPE output) { return FMOD_System_SetOutput(rawPtr, output); } public RESULT getOutput (out OUTPUTTYPE output) { return FMOD_System_GetOutput(rawPtr, out output); } public RESULT getNumDrivers (out int numdrivers) { return FMOD_System_GetNumDrivers(rawPtr, out numdrivers); } public RESULT getDriverInfo (int id, StringBuilder name, int namelen, out Guid guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_System_GetDriverInfo(rawPtr, id, stringMem, namelen, out guid, out systemrate, out speakermode, out speakermodechannels); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT setDriver (int driver) { return FMOD_System_SetDriver(rawPtr, driver); } public RESULT getDriver (out int driver) { return FMOD_System_GetDriver(rawPtr, out driver); } public RESULT setSoftwareChannels (int numsoftwarechannels) { return FMOD_System_SetSoftwareChannels(rawPtr, numsoftwarechannels); } public RESULT getSoftwareChannels (out int numsoftwarechannels) { return FMOD_System_GetSoftwareChannels(rawPtr, out numsoftwarechannels); } public RESULT setSoftwareFormat (int samplerate, SPEAKERMODE speakermode, int numrawspeakers) { return FMOD_System_SetSoftwareFormat(rawPtr, samplerate, speakermode, numrawspeakers); } public RESULT getSoftwareFormat (out int samplerate, out SPEAKERMODE speakermode, out int numrawspeakers) { return FMOD_System_GetSoftwareFormat(rawPtr, out samplerate, out speakermode, out numrawspeakers); } public RESULT setDSPBufferSize (uint bufferlength, int numbuffers) { return FMOD_System_SetDSPBufferSize(rawPtr, bufferlength, numbuffers); } public RESULT getDSPBufferSize (out uint bufferlength, out int numbuffers) { return FMOD_System_GetDSPBufferSize(rawPtr, out bufferlength, out numbuffers); } public RESULT setFileSystem (FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek, FILE_ASYNCREADCALLBACK userasyncread, FILE_ASYNCCANCELCALLBACK userasynccancel, int blockalign) { return FMOD_System_SetFileSystem(rawPtr, useropen, userclose, userread, userseek, userasyncread, userasynccancel, blockalign); } public RESULT attachFileSystem (FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek) { return FMOD_System_AttachFileSystem(rawPtr, useropen, userclose, userread, userseek); } public RESULT setAdvancedSettings (ref ADVANCEDSETTINGS settings) { settings.cbSize = Marshal.SizeOf(settings); return FMOD_System_SetAdvancedSettings(rawPtr, ref settings); } public RESULT getAdvancedSettings (ref ADVANCEDSETTINGS settings) { settings.cbSize = Marshal.SizeOf(settings); return FMOD_System_GetAdvancedSettings(rawPtr, ref settings); } public RESULT setCallback (SYSTEM_CALLBACK callback, SYSTEM_CALLBACK_TYPE callbackmask) { return FMOD_System_SetCallback(rawPtr, callback, callbackmask); } // Plug-in support. public RESULT setPluginPath (string path) { return FMOD_System_SetPluginPath(rawPtr, Encoding.UTF8.GetBytes(path + Char.MinValue)); } public RESULT loadPlugin (string filename, out uint handle, uint priority) { return FMOD_System_LoadPlugin(rawPtr, Encoding.UTF8.GetBytes(filename + Char.MinValue), out handle, priority); } public RESULT loadPlugin (string filename, out uint handle) { return loadPlugin(filename, out handle, 0); } public RESULT unloadPlugin (uint handle) { return FMOD_System_UnloadPlugin(rawPtr, handle); } public RESULT getNumPlugins (PLUGINTYPE plugintype, out int numplugins) { return FMOD_System_GetNumPlugins(rawPtr, plugintype, out numplugins); } public RESULT getPluginHandle (PLUGINTYPE plugintype, int index, out uint handle) { return FMOD_System_GetPluginHandle(rawPtr, plugintype, index, out handle); } public RESULT getPluginInfo (uint handle, out PLUGINTYPE plugintype, StringBuilder name, int namelen, out uint version) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_System_GetPluginInfo(rawPtr, handle, out plugintype, stringMem, namelen, out version); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT setOutputByPlugin (uint handle) { return FMOD_System_SetOutputByPlugin(rawPtr, handle); } public RESULT getOutputByPlugin (out uint handle) { return FMOD_System_GetOutputByPlugin(rawPtr, out handle); } public RESULT createDSPByPlugin(uint handle, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_System_CreateDSPByPlugin(rawPtr, handle, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT getDSPInfoByPlugin(uint handle, out IntPtr description) { return FMOD_System_GetDSPInfoByPlugin(rawPtr, handle, out description); } /* public RESULT registerCodec(ref CODEC_DESCRIPTION description, out uint handle, uint priority) { return FMOD_System_RegisterCodec(rawPtr, ref description, out handle, priority); } */ public RESULT registerDSP(ref DSP_DESCRIPTION description, out uint handle) { return FMOD_System_RegisterDSP(rawPtr, ref description, out handle); } /* public RESULT registerOutput(ref OUTPUT_DESCRIPTION description, out uint handle) { return FMOD_System_RegisterOutput(rawPtr, ref description, out handle); } */ // Init/Close. public RESULT init (int maxchannels, INITFLAGS flags, IntPtr extradriverdata) { return FMOD_System_Init(rawPtr, maxchannels, flags, extradriverdata); } public RESULT close () { return FMOD_System_Close(rawPtr); } // General post-init system functions. public RESULT update () { return FMOD_System_Update(rawPtr); } public RESULT setSpeakerPosition(SPEAKER speaker, float x, float y, bool active) { return FMOD_System_SetSpeakerPosition(rawPtr, speaker, x, y, active); } public RESULT getSpeakerPosition(SPEAKER speaker, out float x, out float y, out bool active) { return FMOD_System_GetSpeakerPosition(rawPtr, speaker, out x, out y, out active); } public RESULT setStreamBufferSize(uint filebuffersize, TIMEUNIT filebuffersizetype) { return FMOD_System_SetStreamBufferSize(rawPtr, filebuffersize, filebuffersizetype); } public RESULT getStreamBufferSize(out uint filebuffersize, out TIMEUNIT filebuffersizetype) { return FMOD_System_GetStreamBufferSize(rawPtr, out filebuffersize, out filebuffersizetype); } public RESULT set3DSettings (float dopplerscale, float distancefactor, float rolloffscale) { return FMOD_System_Set3DSettings(rawPtr, dopplerscale, distancefactor, rolloffscale); } public RESULT get3DSettings (out float dopplerscale, out float distancefactor, out float rolloffscale) { return FMOD_System_Get3DSettings(rawPtr, out dopplerscale, out distancefactor, out rolloffscale); } public RESULT set3DNumListeners (int numlisteners) { return FMOD_System_Set3DNumListeners(rawPtr, numlisteners); } public RESULT get3DNumListeners (out int numlisteners) { return FMOD_System_Get3DNumListeners(rawPtr, out numlisteners); } public RESULT set3DListenerAttributes(int listener, ref VECTOR pos, ref VECTOR vel, ref VECTOR forward, ref VECTOR up) { return FMOD_System_Set3DListenerAttributes(rawPtr, listener, ref pos, ref vel, ref forward, ref up); } public RESULT get3DListenerAttributes(int listener, out VECTOR pos, out VECTOR vel, out VECTOR forward, out VECTOR up) { return FMOD_System_Get3DListenerAttributes(rawPtr, listener, out pos, out vel, out forward, out up); } public RESULT set3DRolloffCallback (CB_3D_ROLLOFFCALLBACK callback) { return FMOD_System_Set3DRolloffCallback (rawPtr, callback); } public RESULT mixerSuspend () { return FMOD_System_MixerSuspend(rawPtr); } public RESULT mixerResume () { return FMOD_System_MixerResume(rawPtr); } public RESULT getDefaultMixMatrix (SPEAKERMODE sourcespeakermode, SPEAKERMODE targetspeakermode, float[] matrix, int matrixhop) { return FMOD_System_GetDefaultMixMatrix(rawPtr, sourcespeakermode, targetspeakermode, matrix, matrixhop); } public RESULT getSpeakerModeChannels (SPEAKERMODE mode, out int channels) { return FMOD_System_GetSpeakerModeChannels(rawPtr, mode, out channels); } // System information functions. public RESULT getVersion (out uint version) { return FMOD_System_GetVersion(rawPtr, out version); } public RESULT getOutputHandle (out IntPtr handle) { return FMOD_System_GetOutputHandle(rawPtr, out handle); } public RESULT getChannelsPlaying (out int channels) { return FMOD_System_GetChannelsPlaying(rawPtr, out channels); } public RESULT getChannelsReal (out int channels) { return FMOD_System_GetChannelsReal(rawPtr, out channels); } public RESULT getCPUUsage (out float dsp, out float stream, out float geometry, out float update, out float total) { return FMOD_System_GetCPUUsage(rawPtr, out dsp, out stream, out geometry, out update, out total); } public RESULT getSoundRAM (out int currentalloced, out int maxalloced, out int total) { return FMOD_System_GetSoundRAM(rawPtr, out currentalloced, out maxalloced, out total); } // Sound/DSP/Channel/FX creation and retrieval. public RESULT createSound (string name, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; byte[] stringData; stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateSound(rawPtr, stringData, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createSound (byte[] data, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateSound(rawPtr, data, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createSound (string name, MODE mode, out Sound sound) { CREATESOUNDEXINFO exinfo = new CREATESOUNDEXINFO(); exinfo.cbsize = Marshal.SizeOf(exinfo); return createSound(name, mode, ref exinfo, out sound); } public RESULT createStream (string name, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; byte[] stringData; stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateStream(rawPtr, stringData, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createStream (byte[] data, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateStream(rawPtr, data, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createStream (string name, MODE mode, out Sound sound) { CREATESOUNDEXINFO exinfo = new CREATESOUNDEXINFO(); exinfo.cbsize = Marshal.SizeOf(exinfo); return createStream(name, mode, ref exinfo, out sound); } public RESULT createDSP (ref DSP_DESCRIPTION description, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_System_CreateDSP(rawPtr, ref description, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT createDSPByType (DSP_TYPE type, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_System_CreateDSPByType(rawPtr, type, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT createChannelGroup (string name, out ChannelGroup channelgroup) { channelgroup = null; byte[] stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); IntPtr channelgroupraw; RESULT result = FMOD_System_CreateChannelGroup(rawPtr, stringData, out channelgroupraw); channelgroup = new ChannelGroup(channelgroupraw); return result; } public RESULT createSoundGroup (string name, out SoundGroup soundgroup) { soundgroup = null; byte[] stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); IntPtr soundgroupraw; RESULT result = FMOD_System_CreateSoundGroup(rawPtr, stringData, out soundgroupraw); soundgroup = new SoundGroup(soundgroupraw); return result; } public RESULT createReverb3D (out Reverb3D reverb) { IntPtr reverbraw; RESULT result = FMOD_System_CreateReverb3D(rawPtr, out reverbraw); reverb = new Reverb3D(reverbraw); return result; } public RESULT playSound (Sound sound, ChannelGroup channelGroup, bool paused, out Channel channel) { channel = null; IntPtr channelGroupRaw = (channelGroup != null) ? channelGroup.getRaw() : IntPtr.Zero; IntPtr channelraw; RESULT result = FMOD_System_PlaySound(rawPtr, sound.getRaw(), channelGroupRaw, paused, out channelraw); channel = new Channel(channelraw); return result; } public RESULT playDSP (DSP dsp, ChannelGroup channelGroup, bool paused, out Channel channel) { channel = null; IntPtr channelGroupRaw = (channelGroup != null) ? channelGroup.getRaw() : IntPtr.Zero; IntPtr channelraw; RESULT result = FMOD_System_PlayDSP(rawPtr, dsp.getRaw(), channelGroupRaw, paused, out channelraw); channel = new Channel(channelraw); return result; } public RESULT getChannel (int channelid, out Channel channel) { channel = null; IntPtr channelraw; RESULT result = FMOD_System_GetChannel(rawPtr, channelid, out channelraw); channel = new Channel(channelraw); return result; } public RESULT getMasterChannelGroup (out ChannelGroup channelgroup) { channelgroup = null; IntPtr channelgroupraw; RESULT result = FMOD_System_GetMasterChannelGroup(rawPtr, out channelgroupraw); channelgroup = new ChannelGroup(channelgroupraw); return result; } public RESULT getMasterSoundGroup (out SoundGroup soundgroup) { soundgroup = null; IntPtr soundgroupraw; RESULT result = FMOD_System_GetMasterSoundGroup(rawPtr, out soundgroupraw); soundgroup = new SoundGroup(soundgroupraw); return result; } // Routing to ports. public RESULT attachChannelGroupToPort(uint portType, ulong portIndex, ChannelGroup channelgroup, bool passThru = false) { return FMOD_System_AttachChannelGroupToPort(rawPtr, portType, portIndex, channelgroup.getRaw(), passThru); } public RESULT detachChannelGroupFromPort(ChannelGroup channelgroup) { return FMOD_System_DetachChannelGroupFromPort(rawPtr, channelgroup.getRaw()); } // Reverb api. public RESULT setReverbProperties (int instance, ref REVERB_PROPERTIES prop) { return FMOD_System_SetReverbProperties(rawPtr, instance, ref prop); } public RESULT getReverbProperties (int instance, out REVERB_PROPERTIES prop) { return FMOD_System_GetReverbProperties(rawPtr, instance, out prop); } // System level DSP functionality. public RESULT lockDSP () { return FMOD_System_LockDSP(rawPtr); } public RESULT unlockDSP () { return FMOD_System_UnlockDSP(rawPtr); } // Recording api public RESULT getRecordNumDrivers (out int numdrivers, out int numconnected) { return FMOD_System_GetRecordNumDrivers(rawPtr, out numdrivers, out numconnected); } public RESULT getRecordDriverInfo(int id, StringBuilder name, int namelen, out Guid guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels, out DRIVER_STATE state) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_System_GetRecordDriverInfo(rawPtr, id, stringMem, namelen, out guid, out systemrate, out speakermode, out speakermodechannels, out state); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getRecordPosition (int id, out uint position) { return FMOD_System_GetRecordPosition(rawPtr, id, out position); } public RESULT recordStart (int id, Sound sound, bool loop) { return FMOD_System_RecordStart(rawPtr, id, sound.getRaw(), loop); } public RESULT recordStop (int id) { return FMOD_System_RecordStop(rawPtr, id); } public RESULT isRecording (int id, out bool recording) { return FMOD_System_IsRecording(rawPtr, id, out recording); } // Geometry api public RESULT createGeometry (int maxpolygons, int maxvertices, out Geometry geometry) { geometry = null; IntPtr geometryraw; RESULT result = FMOD_System_CreateGeometry(rawPtr, maxpolygons, maxvertices, out geometryraw); geometry = new Geometry(geometryraw); return result; } public RESULT setGeometrySettings (float maxworldsize) { return FMOD_System_SetGeometrySettings(rawPtr, maxworldsize); } public RESULT getGeometrySettings (out float maxworldsize) { return FMOD_System_GetGeometrySettings(rawPtr, out maxworldsize); } public RESULT loadGeometry(IntPtr data, int datasize, out Geometry geometry) { geometry = null; IntPtr geometryraw; RESULT result = FMOD_System_LoadGeometry(rawPtr, data, datasize, out geometryraw); geometry = new Geometry(geometryraw); return result; } public RESULT getGeometryOcclusion (ref VECTOR listener, ref VECTOR source, out float direct, out float reverb) { return FMOD_System_GetGeometryOcclusion(rawPtr, ref listener, ref source, out direct, out reverb); } // Network functions public RESULT setNetworkProxy (string proxy) { return FMOD_System_SetNetworkProxy(rawPtr, Encoding.UTF8.GetBytes(proxy + Char.MinValue)); } public RESULT getNetworkProxy (StringBuilder proxy, int proxylen) { IntPtr stringMem = Marshal.AllocHGlobal(proxy.Capacity); RESULT result = FMOD_System_GetNetworkProxy(rawPtr, stringMem, proxylen); StringMarshalHelper.NativeToBuilder(proxy, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT setNetworkTimeout (int timeout) { return FMOD_System_SetNetworkTimeout(rawPtr, timeout); } public RESULT getNetworkTimeout(out int timeout) { return FMOD_System_GetNetworkTimeout(rawPtr, out timeout); } // Userdata set/get public RESULT setUserData (IntPtr userdata) { return FMOD_System_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_System_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Release (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetOutput (IntPtr system, OUTPUTTYPE output); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetOutput (IntPtr system, out OUTPUTTYPE output); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNumDrivers (IntPtr system, out int numdrivers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDriverInfo (IntPtr system, int id, IntPtr name, int namelen, out Guid guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetDriver (IntPtr system, int driver); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDriver (IntPtr system, out int driver); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetSoftwareChannels (IntPtr system, int numsoftwarechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSoftwareChannels (IntPtr system, out int numsoftwarechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetSoftwareFormat (IntPtr system, int samplerate, SPEAKERMODE speakermode, int numrawspeakers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSoftwareFormat (IntPtr system, out int samplerate, out SPEAKERMODE speakermode, out int numrawspeakers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetDSPBufferSize (IntPtr system, uint bufferlength, int numbuffers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDSPBufferSize (IntPtr system, out uint bufferlength, out int numbuffers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetFileSystem (IntPtr system, FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek, FILE_ASYNCREADCALLBACK userasyncread, FILE_ASYNCCANCELCALLBACK userasynccancel, int blockalign); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_AttachFileSystem (IntPtr system, FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetPluginPath (IntPtr system, byte[] path); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_LoadPlugin (IntPtr system, byte[] filename, out uint handle, uint priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_UnloadPlugin (IntPtr system, uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNumPlugins (IntPtr system, PLUGINTYPE plugintype, out int numplugins); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetPluginHandle (IntPtr system, PLUGINTYPE plugintype, int index, out uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetPluginInfo (IntPtr system, uint handle, out PLUGINTYPE plugintype, IntPtr name, int namelen, out uint version); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateDSPByPlugin (IntPtr system, uint handle, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetOutputByPlugin (IntPtr system, uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetOutputByPlugin (IntPtr system, out uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDSPInfoByPlugin (IntPtr system, uint handle, out IntPtr description); [DllImport(VERSION.dll)] //private static extern RESULT FMOD_System_RegisterCodec (IntPtr system, out CODEC_DESCRIPTION description, out uint handle, uint priority); //[DllImport(VERSION.dll)] private static extern RESULT FMOD_System_RegisterDSP (IntPtr system, ref DSP_DESCRIPTION description, out uint handle); [DllImport(VERSION.dll)] //private static extern RESULT FMOD_System_RegisterOutput (IntPtr system, ref OUTPUT_DESCRIPTION description, out uint handle); //[DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Init (IntPtr system, int maxchannels, INITFLAGS flags, IntPtr extradriverdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Close (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Update (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetAdvancedSettings (IntPtr system, ref ADVANCEDSETTINGS settings); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetAdvancedSettings (IntPtr system, ref ADVANCEDSETTINGS settings); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DRolloffCallback (IntPtr system, CB_3D_ROLLOFFCALLBACK callback); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_MixerSuspend (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_MixerResume (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDefaultMixMatrix (IntPtr system, SPEAKERMODE sourcespeakermode, SPEAKERMODE targetspeakermode, float[] matrix, int matrixhop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSpeakerModeChannels (IntPtr system, SPEAKERMODE mode, out int channels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetCallback (IntPtr system, SYSTEM_CALLBACK callback, SYSTEM_CALLBACK_TYPE callbackmask); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetSpeakerPosition (IntPtr system, SPEAKER speaker, float x, float y, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSpeakerPosition (IntPtr system, SPEAKER speaker, out float x, out float y, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DSettings (IntPtr system, float dopplerscale, float distancefactor, float rolloffscale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Get3DSettings (IntPtr system, out float dopplerscale, out float distancefactor, out float rolloffscale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DNumListeners (IntPtr system, int numlisteners); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Get3DNumListeners (IntPtr system, out int numlisteners); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DListenerAttributes(IntPtr system, int listener, ref VECTOR pos, ref VECTOR vel, ref VECTOR forward, ref VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Get3DListenerAttributes(IntPtr system, int listener, out VECTOR pos, out VECTOR vel, out VECTOR forward, out VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetStreamBufferSize (IntPtr system, uint filebuffersize, TIMEUNIT filebuffersizetype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetStreamBufferSize (IntPtr system, out uint filebuffersize, out TIMEUNIT filebuffersizetype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetVersion (IntPtr system, out uint version); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetOutputHandle (IntPtr system, out IntPtr handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetChannelsPlaying (IntPtr system, out int channels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetChannelsReal (IntPtr system, out int channels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetCPUUsage (IntPtr system, out float dsp, out float stream, out float geometry, out float update, out float total); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSoundRAM (IntPtr system, out int currentalloced, out int maxalloced, out int total); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateSound (IntPtr system, byte[] name_or_data, MODE mode, ref CREATESOUNDEXINFO exinfo, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateStream (IntPtr system, byte[] name_or_data, MODE mode, ref CREATESOUNDEXINFO exinfo, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateDSP (IntPtr system, ref DSP_DESCRIPTION description, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateDSPByType (IntPtr system, DSP_TYPE type, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateChannelGroup (IntPtr system, byte[] name, out IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateSoundGroup (IntPtr system, byte[] name, out IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateReverb3D (IntPtr system, out IntPtr reverb); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_PlaySound (IntPtr system, IntPtr sound, IntPtr channelGroup, bool paused, out IntPtr channel); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_PlayDSP (IntPtr system, IntPtr dsp, IntPtr channelGroup, bool paused, out IntPtr channel); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetChannel (IntPtr system, int channelid, out IntPtr channel); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetMasterChannelGroup (IntPtr system, out IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetMasterSoundGroup (IntPtr system, out IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_AttachChannelGroupToPort (IntPtr system, uint portType, ulong portIndex, IntPtr channelgroup, bool passThru); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_DetachChannelGroupFromPort(IntPtr system, IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetReverbProperties (IntPtr system, int instance, ref REVERB_PROPERTIES prop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetReverbProperties (IntPtr system, int instance, out REVERB_PROPERTIES prop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_LockDSP (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_UnlockDSP (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetRecordNumDrivers (IntPtr system, out int numdrivers, out int numconnected); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetRecordDriverInfo (IntPtr system, int id, IntPtr name, int namelen, out Guid guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels, out DRIVER_STATE state); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetRecordPosition (IntPtr system, int id, out uint position); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_RecordStart (IntPtr system, int id, IntPtr sound, bool loop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_RecordStop (IntPtr system, int id); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_IsRecording (IntPtr system, int id, out bool recording); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateGeometry (IntPtr system, int maxpolygons, int maxvertices, out IntPtr geometry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetGeometrySettings (IntPtr system, float maxworldsize); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetGeometrySettings (IntPtr system, out float maxworldsize); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_LoadGeometry (IntPtr system, IntPtr data, int datasize, out IntPtr geometry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetGeometryOcclusion (IntPtr system, ref VECTOR listener, ref VECTOR source, out float direct, out float reverb); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetNetworkProxy (IntPtr system, byte[] proxy); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNetworkProxy (IntPtr system, IntPtr proxy, int proxylen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetNetworkTimeout (IntPtr system, int timeout); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNetworkTimeout (IntPtr system, out int timeout); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetUserData (IntPtr system, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetUserData (IntPtr system, out IntPtr userdata); #endregion #region wrapperinternal public System(IntPtr raw) : base(raw) { } #endregion } /* 'Sound' API. */ public class Sound : HandleBase { public RESULT release () { RESULT result = FMOD_Sound_Release(rawPtr); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } public RESULT getSystemObject (out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_Sound_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // Standard sound manipulation functions. public RESULT @lock (uint offset, uint length, out IntPtr ptr1, out IntPtr ptr2, out uint len1, out uint len2) { return FMOD_Sound_Lock(rawPtr, offset, length, out ptr1, out ptr2, out len1, out len2); } public RESULT unlock (IntPtr ptr1, IntPtr ptr2, uint len1, uint len2) { return FMOD_Sound_Unlock(rawPtr, ptr1, ptr2, len1, len2); } public RESULT setDefaults (float frequency, int priority) { return FMOD_Sound_SetDefaults(rawPtr, frequency, priority); } public RESULT getDefaults (out float frequency, out int priority) { return FMOD_Sound_GetDefaults(rawPtr, out frequency, out priority); } public RESULT set3DMinMaxDistance (float min, float max) { return FMOD_Sound_Set3DMinMaxDistance(rawPtr, min, max); } public RESULT get3DMinMaxDistance (out float min, out float max) { return FMOD_Sound_Get3DMinMaxDistance(rawPtr, out min, out max); } public RESULT set3DConeSettings (float insideconeangle, float outsideconeangle, float outsidevolume) { return FMOD_Sound_Set3DConeSettings(rawPtr, insideconeangle, outsideconeangle, outsidevolume); } public RESULT get3DConeSettings (out float insideconeangle, out float outsideconeangle, out float outsidevolume) { return FMOD_Sound_Get3DConeSettings(rawPtr, out insideconeangle, out outsideconeangle, out outsidevolume); } public RESULT set3DCustomRolloff (ref VECTOR points, int numpoints) { return FMOD_Sound_Set3DCustomRolloff(rawPtr, ref points, numpoints); } public RESULT get3DCustomRolloff (out IntPtr points, out int numpoints) { return FMOD_Sound_Get3DCustomRolloff(rawPtr, out points, out numpoints); } public RESULT getSubSound (int index, out Sound subsound) { subsound = null; IntPtr subsoundraw; RESULT result = FMOD_Sound_GetSubSound(rawPtr, index, out subsoundraw); subsound = new Sound(subsoundraw); return result; } public RESULT getSubSoundParent(out Sound parentsound) { parentsound = null; IntPtr subsoundraw; RESULT result = FMOD_Sound_GetSubSoundParent(rawPtr, out subsoundraw); parentsound = new Sound(subsoundraw); return result; } public RESULT getName (StringBuilder name, int namelen) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_Sound_GetName(rawPtr, stringMem, namelen); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getLength (out uint length, TIMEUNIT lengthtype) { return FMOD_Sound_GetLength(rawPtr, out length, lengthtype); } public RESULT getFormat (out SOUND_TYPE type, out SOUND_FORMAT format, out int channels, out int bits) { return FMOD_Sound_GetFormat(rawPtr, out type, out format, out channels, out bits); } public RESULT getNumSubSounds (out int numsubsounds) { return FMOD_Sound_GetNumSubSounds(rawPtr, out numsubsounds); } public RESULT getNumTags (out int numtags, out int numtagsupdated) { return FMOD_Sound_GetNumTags(rawPtr, out numtags, out numtagsupdated); } public RESULT getTag (string name, int index, out TAG tag) { return FMOD_Sound_GetTag(rawPtr, name, index, out tag); } public RESULT getOpenState (out OPENSTATE openstate, out uint percentbuffered, out bool starving, out bool diskbusy) { return FMOD_Sound_GetOpenState(rawPtr, out openstate, out percentbuffered, out starving, out diskbusy); } public RESULT readData (IntPtr buffer, uint lenbytes, out uint read) { return FMOD_Sound_ReadData(rawPtr, buffer, lenbytes, out read); } public RESULT seekData (uint pcm) { return FMOD_Sound_SeekData(rawPtr, pcm); } public RESULT setSoundGroup (SoundGroup soundgroup) { return FMOD_Sound_SetSoundGroup(rawPtr, soundgroup.getRaw()); } public RESULT getSoundGroup (out SoundGroup soundgroup) { soundgroup = null; IntPtr soundgroupraw; RESULT result = FMOD_Sound_GetSoundGroup(rawPtr, out soundgroupraw); soundgroup = new SoundGroup(soundgroupraw); return result; } // Synchronization point API. These points can come from markers embedded in wav files, and can also generate channel callbacks. public RESULT getNumSyncPoints (out int numsyncpoints) { return FMOD_Sound_GetNumSyncPoints(rawPtr, out numsyncpoints); } public RESULT getSyncPoint (int index, out IntPtr point) { return FMOD_Sound_GetSyncPoint(rawPtr, index, out point); } public RESULT getSyncPointInfo (IntPtr point, StringBuilder name, int namelen, out uint offset, TIMEUNIT offsettype) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_Sound_GetSyncPointInfo(rawPtr, point, stringMem, namelen, out offset, offsettype); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT addSyncPoint (uint offset, TIMEUNIT offsettype, string name, out IntPtr point) { return FMOD_Sound_AddSyncPoint(rawPtr, offset, offsettype, name, out point); } public RESULT deleteSyncPoint (IntPtr point) { return FMOD_Sound_DeleteSyncPoint(rawPtr, point); } // Functions also in Channel class but here they are the 'default' to save having to change it in Channel all the time. public RESULT setMode (MODE mode) { return FMOD_Sound_SetMode(rawPtr, mode); } public RESULT getMode (out MODE mode) { return FMOD_Sound_GetMode(rawPtr, out mode); } public RESULT setLoopCount (int loopcount) { return FMOD_Sound_SetLoopCount(rawPtr, loopcount); } public RESULT getLoopCount (out int loopcount) { return FMOD_Sound_GetLoopCount(rawPtr, out loopcount); } public RESULT setLoopPoints (uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype) { return FMOD_Sound_SetLoopPoints(rawPtr, loopstart, loopstarttype, loopend, loopendtype); } public RESULT getLoopPoints (out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype) { return FMOD_Sound_GetLoopPoints(rawPtr, out loopstart, loopstarttype, out loopend, loopendtype); } // For MOD/S3M/XM/IT/MID sequenced formats only. public RESULT getMusicNumChannels (out int numchannels) { return FMOD_Sound_GetMusicNumChannels(rawPtr, out numchannels); } public RESULT setMusicChannelVolume (int channel, float volume) { return FMOD_Sound_SetMusicChannelVolume(rawPtr, channel, volume); } public RESULT getMusicChannelVolume (int channel, out float volume) { return FMOD_Sound_GetMusicChannelVolume(rawPtr, channel, out volume); } public RESULT setMusicSpeed(float speed) { return FMOD_Sound_SetMusicSpeed(rawPtr, speed); } public RESULT getMusicSpeed(out float speed) { return FMOD_Sound_GetMusicSpeed(rawPtr, out speed); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_Sound_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_Sound_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Release (IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSystemObject (IntPtr sound, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Lock (IntPtr sound, uint offset, uint length, out IntPtr ptr1, out IntPtr ptr2, out uint len1, out uint len2); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Unlock (IntPtr sound, IntPtr ptr1, IntPtr ptr2, uint len1, uint len2); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetDefaults (IntPtr sound, float frequency, int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetDefaults (IntPtr sound, out float frequency, out int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Set3DMinMaxDistance (IntPtr sound, float min, float max); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Get3DMinMaxDistance (IntPtr sound, out float min, out float max); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Set3DConeSettings (IntPtr sound, float insideconeangle, float outsideconeangle, float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Get3DConeSettings (IntPtr sound, out float insideconeangle, out float outsideconeangle, out float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Set3DCustomRolloff (IntPtr sound, ref VECTOR points, int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Get3DCustomRolloff (IntPtr sound, out IntPtr points, out int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSubSound (IntPtr sound, int index, out IntPtr subsound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSubSoundParent (IntPtr sound, out IntPtr parentsound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetName (IntPtr sound, IntPtr name, int namelen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetLength (IntPtr sound, out uint length, TIMEUNIT lengthtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetFormat (IntPtr sound, out SOUND_TYPE type, out SOUND_FORMAT format, out int channels, out int bits); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetNumSubSounds (IntPtr sound, out int numsubsounds); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetNumTags (IntPtr sound, out int numtags, out int numtagsupdated); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetTag (IntPtr sound, string name, int index, out TAG tag); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetOpenState (IntPtr sound, out OPENSTATE openstate, out uint percentbuffered, out bool starving, out bool diskbusy); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_ReadData (IntPtr sound, IntPtr buffer, uint lenbytes, out uint read); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SeekData (IntPtr sound, uint pcm); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetSoundGroup (IntPtr sound, IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSoundGroup (IntPtr sound, out IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetNumSyncPoints (IntPtr sound, out int numsyncpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSyncPoint (IntPtr sound, int index, out IntPtr point); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSyncPointInfo (IntPtr sound, IntPtr point, IntPtr name, int namelen, out uint offset, TIMEUNIT offsettype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_AddSyncPoint (IntPtr sound, uint offset, TIMEUNIT offsettype, string name, out IntPtr point); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_DeleteSyncPoint (IntPtr sound, IntPtr point); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetMode (IntPtr sound, MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMode (IntPtr sound, out MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetLoopCount (IntPtr sound, int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetLoopCount (IntPtr sound, out int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetLoopPoints (IntPtr sound, uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetLoopPoints (IntPtr sound, out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMusicNumChannels (IntPtr sound, out int numchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetMusicChannelVolume (IntPtr sound, int channel, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMusicChannelVolume (IntPtr sound, int channel, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetMusicSpeed (IntPtr sound, float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMusicSpeed (IntPtr sound, out float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetUserData (IntPtr sound, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetUserData (IntPtr sound, out IntPtr userdata); #endregion #region wrapperinternal public Sound(IntPtr raw) : base(raw) { } #endregion } /* 'ChannelControl' API */ public class ChannelControl : HandleBase { public RESULT getSystemObject(out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_ChannelGroup_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // General control functionality for Channels and ChannelGroups. public RESULT stop() { return FMOD_ChannelGroup_Stop(rawPtr); } public RESULT setPaused(bool paused) { return FMOD_ChannelGroup_SetPaused(rawPtr, paused); } public RESULT getPaused(out bool paused) { return FMOD_ChannelGroup_GetPaused(rawPtr, out paused); } public RESULT setVolume(float volume) { return FMOD_ChannelGroup_SetVolume(rawPtr, volume); } public RESULT getVolume(out float volume) { return FMOD_ChannelGroup_GetVolume(rawPtr, out volume); } public RESULT setVolumeRamp(bool ramp) { return FMOD_ChannelGroup_SetVolumeRamp(rawPtr, ramp); } public RESULT getVolumeRamp(out bool ramp) { return FMOD_ChannelGroup_GetVolumeRamp(rawPtr, out ramp); } public RESULT getAudibility(out float audibility) { return FMOD_ChannelGroup_GetAudibility(rawPtr, out audibility); } public RESULT setPitch(float pitch) { return FMOD_ChannelGroup_SetPitch(rawPtr, pitch); } public RESULT getPitch(out float pitch) { return FMOD_ChannelGroup_GetPitch(rawPtr, out pitch); } public RESULT setMute(bool mute) { return FMOD_ChannelGroup_SetMute(rawPtr, mute); } public RESULT getMute(out bool mute) { return FMOD_ChannelGroup_GetMute(rawPtr, out mute); } public RESULT setReverbProperties(int instance, float wet) { return FMOD_ChannelGroup_SetReverbProperties(rawPtr, instance, wet); } public RESULT getReverbProperties(int instance, out float wet) { return FMOD_ChannelGroup_GetReverbProperties(rawPtr, instance, out wet); } public RESULT setLowPassGain(float gain) { return FMOD_ChannelGroup_SetLowPassGain(rawPtr, gain); } public RESULT getLowPassGain(out float gain) { return FMOD_ChannelGroup_GetLowPassGain(rawPtr, out gain); } public RESULT setMode(MODE mode) { return FMOD_ChannelGroup_SetMode(rawPtr, mode); } public RESULT getMode(out MODE mode) { return FMOD_ChannelGroup_GetMode(rawPtr, out mode); } public RESULT setCallback(CHANNEL_CALLBACK callback) { return FMOD_ChannelGroup_SetCallback(rawPtr, callback); } public RESULT isPlaying(out bool isplaying) { return FMOD_ChannelGroup_IsPlaying(rawPtr, out isplaying); } // Panning and level adjustment. public RESULT setPan(float pan) { return FMOD_ChannelGroup_SetPan(rawPtr, pan); } public RESULT setMixLevelsOutput(float frontleft, float frontright, float center, float lfe, float surroundleft, float surroundright, float backleft, float backright) { return FMOD_ChannelGroup_SetMixLevelsOutput(rawPtr, frontleft, frontright, center, lfe, surroundleft, surroundright, backleft, backright); } public RESULT setMixLevelsInput(float[] levels, int numlevels) { return FMOD_ChannelGroup_SetMixLevelsInput(rawPtr, levels, numlevels); } public RESULT setMixMatrix(float[] matrix, int outchannels, int inchannels, int inchannel_hop) { return FMOD_ChannelGroup_SetMixMatrix(rawPtr, matrix, outchannels, inchannels, inchannel_hop); } public RESULT getMixMatrix(float[] matrix, out int outchannels, out int inchannels, int inchannel_hop) { return FMOD_ChannelGroup_GetMixMatrix(rawPtr, matrix, out outchannels, out inchannels, inchannel_hop); } // Clock based functionality. public RESULT getDSPClock(out ulong dspclock, out ulong parentclock) { return FMOD_ChannelGroup_GetDSPClock(rawPtr, out dspclock, out parentclock); } public RESULT setDelay(ulong dspclock_start, ulong dspclock_end, bool stopchannels) { return FMOD_ChannelGroup_SetDelay(rawPtr, dspclock_start, dspclock_end, stopchannels); } public RESULT getDelay(out ulong dspclock_start, out ulong dspclock_end, out bool stopchannels) { return FMOD_ChannelGroup_GetDelay(rawPtr, out dspclock_start, out dspclock_end, out stopchannels); } public RESULT addFadePoint(ulong dspclock, float volume) { return FMOD_ChannelGroup_AddFadePoint(rawPtr, dspclock, volume); } public RESULT setFadePointRamp(ulong dspclock, float volume) { return FMOD_ChannelGroup_SetFadePointRamp(rawPtr, dspclock, volume); } public RESULT removeFadePoints(ulong dspclock_start, ulong dspclock_end) { return FMOD_ChannelGroup_RemoveFadePoints(rawPtr, dspclock_start, dspclock_end); } public RESULT getFadePoints(ref uint numpoints, ulong[] point_dspclock, float[] point_volume) { return FMOD_ChannelGroup_GetFadePoints(rawPtr, ref numpoints, point_dspclock, point_volume); } // DSP effects. public RESULT getDSP(int index, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_ChannelGroup_GetDSP(rawPtr, index, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT addDSP(int index, DSP dsp) { return FMOD_ChannelGroup_AddDSP(rawPtr, index, dsp.getRaw()); } public RESULT removeDSP(DSP dsp) { return FMOD_ChannelGroup_RemoveDSP(rawPtr, dsp.getRaw()); } public RESULT getNumDSPs(out int numdsps) { return FMOD_ChannelGroup_GetNumDSPs(rawPtr, out numdsps); } public RESULT setDSPIndex(DSP dsp, int index) { return FMOD_ChannelGroup_SetDSPIndex(rawPtr, dsp.getRaw(), index); } public RESULT getDSPIndex(DSP dsp, out int index) { return FMOD_ChannelGroup_GetDSPIndex(rawPtr, dsp.getRaw(), out index); } public RESULT overridePanDSP(DSP pan) { return FMOD_ChannelGroup_OverridePanDSP(rawPtr, pan.getRaw()); } // 3D functionality. public RESULT set3DAttributes(ref VECTOR pos, ref VECTOR vel, ref VECTOR alt_pan_pos) { return FMOD_ChannelGroup_Set3DAttributes(rawPtr, ref pos, ref vel, ref alt_pan_pos); } public RESULT get3DAttributes(out VECTOR pos, out VECTOR vel, out VECTOR alt_pan_pos) { return FMOD_ChannelGroup_Get3DAttributes(rawPtr, out pos, out vel, out alt_pan_pos); } public RESULT set3DMinMaxDistance(float mindistance, float maxdistance) { return FMOD_ChannelGroup_Set3DMinMaxDistance(rawPtr, mindistance, maxdistance); } public RESULT get3DMinMaxDistance(out float mindistance, out float maxdistance) { return FMOD_ChannelGroup_Get3DMinMaxDistance(rawPtr, out mindistance, out maxdistance); } public RESULT set3DConeSettings(float insideconeangle, float outsideconeangle, float outsidevolume) { return FMOD_ChannelGroup_Set3DConeSettings(rawPtr, insideconeangle, outsideconeangle, outsidevolume); } public RESULT get3DConeSettings(out float insideconeangle, out float outsideconeangle, out float outsidevolume) { return FMOD_ChannelGroup_Get3DConeSettings(rawPtr, out insideconeangle, out outsideconeangle, out outsidevolume); } public RESULT set3DConeOrientation(ref VECTOR orientation) { return FMOD_ChannelGroup_Set3DConeOrientation(rawPtr, ref orientation); } public RESULT get3DConeOrientation(out VECTOR orientation) { return FMOD_ChannelGroup_Get3DConeOrientation(rawPtr, out orientation); } public RESULT set3DCustomRolloff(ref VECTOR points, int numpoints) { return FMOD_ChannelGroup_Set3DCustomRolloff(rawPtr, ref points, numpoints); } public RESULT get3DCustomRolloff(out IntPtr points, out int numpoints) { return FMOD_ChannelGroup_Get3DCustomRolloff(rawPtr, out points, out numpoints); } public RESULT set3DOcclusion(float directocclusion, float reverbocclusion) { return FMOD_ChannelGroup_Set3DOcclusion(rawPtr, directocclusion, reverbocclusion); } public RESULT get3DOcclusion(out float directocclusion, out float reverbocclusion) { return FMOD_ChannelGroup_Get3DOcclusion(rawPtr, out directocclusion, out reverbocclusion); } public RESULT set3DSpread(float angle) { return FMOD_ChannelGroup_Set3DSpread(rawPtr, angle); } public RESULT get3DSpread(out float angle) { return FMOD_ChannelGroup_Get3DSpread(rawPtr, out angle); } public RESULT set3DLevel(float level) { return FMOD_ChannelGroup_Set3DLevel(rawPtr, level); } public RESULT get3DLevel(out float level) { return FMOD_ChannelGroup_Get3DLevel(rawPtr, out level); } public RESULT set3DDopplerLevel(float level) { return FMOD_ChannelGroup_Set3DDopplerLevel(rawPtr, level); } public RESULT get3DDopplerLevel(out float level) { return FMOD_ChannelGroup_Get3DDopplerLevel(rawPtr, out level); } public RESULT set3DDistanceFilter(bool custom, float customLevel, float centerFreq) { return FMOD_ChannelGroup_Set3DDistanceFilter(rawPtr, custom, customLevel, centerFreq); } public RESULT get3DDistanceFilter(out bool custom, out float customLevel, out float centerFreq) { return FMOD_ChannelGroup_Get3DDistanceFilter(rawPtr, out custom, out customLevel, out centerFreq); } // Userdata set/get. public RESULT setUserData(IntPtr userdata) { return FMOD_ChannelGroup_SetUserData(rawPtr, userdata); } public RESULT getUserData(out IntPtr userdata) { return FMOD_ChannelGroup_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Stop(IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetPaused(IntPtr channelgroup, bool paused); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetPaused(IntPtr channelgroup, out bool paused); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetVolume(IntPtr channelgroup, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetVolumeRamp(IntPtr channelgroup, bool ramp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetVolumeRamp(IntPtr channelgroup, out bool ramp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetAudibility(IntPtr channelgroup, out float audibility); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetPitch(IntPtr channelgroup, float pitch); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetPitch(IntPtr channelgroup, out float pitch); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMute(IntPtr channelgroup, bool mute); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetMute(IntPtr channelgroup, out bool mute); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetReverbProperties(IntPtr channelgroup, int instance, float wet); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetReverbProperties(IntPtr channelgroup, int instance, out float wet); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetLowPassGain(IntPtr channelgroup, float gain); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetLowPassGain(IntPtr channelgroup, out float gain); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMode(IntPtr channelgroup, MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetMode(IntPtr channelgroup, out MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetCallback(IntPtr channelgroup, CHANNEL_CALLBACK callback); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_IsPlaying(IntPtr channelgroup, out bool isplaying); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetPan(IntPtr channelgroup, float pan); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMixLevelsOutput(IntPtr channelgroup, float frontleft, float frontright, float center, float lfe, float surroundleft, float surroundright, float backleft, float backright); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMixLevelsInput(IntPtr channelgroup, float[] levels, int numlevels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMixMatrix(IntPtr channelgroup, float[] matrix, int outchannels, int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetMixMatrix(IntPtr channelgroup, float[] matrix, out int outchannels, out int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDSPClock(IntPtr channelgroup, out ulong dspclock, out ulong parentclock); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetDelay(IntPtr channelgroup, ulong dspclock_start, ulong dspclock_end, bool stopchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDelay(IntPtr channelgroup, out ulong dspclock_start, out ulong dspclock_end, out bool stopchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_AddFadePoint(IntPtr channelgroup, ulong dspclock, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetFadePointRamp(IntPtr channelgroup, ulong dspclock, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_RemoveFadePoints(IntPtr channelgroup, ulong dspclock_start, ulong dspclock_end); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetFadePoints(IntPtr channelgroup, ref uint numpoints, ulong[] point_dspclock, float[] point_volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DAttributes(IntPtr channelgroup, ref VECTOR pos, ref VECTOR vel, ref VECTOR alt_pan_pos); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DAttributes(IntPtr channelgroup, out VECTOR pos, out VECTOR vel, out VECTOR alt_pan_pos); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DMinMaxDistance(IntPtr channelgroup, float mindistance, float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DMinMaxDistance(IntPtr channelgroup, out float mindistance, out float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DConeSettings(IntPtr channelgroup, float insideconeangle, float outsideconeangle, float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DConeSettings(IntPtr channelgroup, out float insideconeangle, out float outsideconeangle, out float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DConeOrientation(IntPtr channelgroup, ref VECTOR orientation); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DConeOrientation(IntPtr channelgroup, out VECTOR orientation); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DCustomRolloff(IntPtr channelgroup, ref VECTOR points, int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DCustomRolloff(IntPtr channelgroup, out IntPtr points, out int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DOcclusion(IntPtr channelgroup, float directocclusion, float reverbocclusion); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DOcclusion(IntPtr channelgroup, out float directocclusion, out float reverbocclusion); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DSpread(IntPtr channelgroup, float angle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DSpread(IntPtr channelgroup, out float angle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DLevel(IntPtr channelgroup, float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DLevel(IntPtr channelgroup, out float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DDopplerLevel(IntPtr channelgroup, float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DDopplerLevel(IntPtr channelgroup, out float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DDistanceFilter(IntPtr channelgroup, bool custom, float customLevel, float centerFreq); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DDistanceFilter(IntPtr channelgroup, out bool custom, out float customLevel, out float centerFreq); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetSystemObject(IntPtr channelgroup, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetVolume(IntPtr channelgroup, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDSP(IntPtr channelgroup, int index, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_AddDSP(IntPtr channelgroup, int index, IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_RemoveDSP(IntPtr channelgroup, IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetNumDSPs(IntPtr channelgroup, out int numdsps); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetDSPIndex(IntPtr channelgroup, IntPtr dsp, int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDSPIndex(IntPtr channelgroup, IntPtr dsp, out int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_OverridePanDSP(IntPtr channelgroup, IntPtr pan); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetUserData(IntPtr channelgroup, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetUserData(IntPtr channelgroup, out IntPtr userdata); #endregion #region wrapperinternal protected ChannelControl(IntPtr raw) : base(raw) { } #endregion } /* 'Channel' API */ public class Channel : ChannelControl { // Channel specific control functionality. public RESULT setFrequency (float frequency) { return FMOD_Channel_SetFrequency(getRaw(), frequency); } public RESULT getFrequency (out float frequency) { return FMOD_Channel_GetFrequency(getRaw(), out frequency); } public RESULT setPriority (int priority) { return FMOD_Channel_SetPriority(getRaw(), priority); } public RESULT getPriority (out int priority) { return FMOD_Channel_GetPriority(getRaw(), out priority); } public RESULT setPosition (uint position, TIMEUNIT postype) { return FMOD_Channel_SetPosition(getRaw(), position, postype); } public RESULT getPosition (out uint position, TIMEUNIT postype) { return FMOD_Channel_GetPosition(getRaw(), out position, postype); } public RESULT setChannelGroup (ChannelGroup channelgroup) { return FMOD_Channel_SetChannelGroup(getRaw(), channelgroup.getRaw()); } public RESULT getChannelGroup (out ChannelGroup channelgroup) { channelgroup = null; IntPtr channelgroupraw; RESULT result = FMOD_Channel_GetChannelGroup(getRaw(), out channelgroupraw); channelgroup = new ChannelGroup(channelgroupraw); return result; } public RESULT setLoopCount(int loopcount) { return FMOD_Channel_SetLoopCount(getRaw(), loopcount); } public RESULT getLoopCount(out int loopcount) { return FMOD_Channel_GetLoopCount(getRaw(), out loopcount); } public RESULT setLoopPoints(uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype) { return FMOD_Channel_SetLoopPoints(getRaw(), loopstart, loopstarttype, loopend, loopendtype); } public RESULT getLoopPoints(out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype) { return FMOD_Channel_GetLoopPoints(getRaw(), out loopstart, loopstarttype, out loopend, loopendtype); } // Information only functions. public RESULT isVirtual (out bool isvirtual) { return FMOD_Channel_IsVirtual(getRaw(), out isvirtual); } public RESULT getCurrentSound (out Sound sound) { sound = null; IntPtr soundraw; RESULT result = FMOD_Channel_GetCurrentSound(getRaw(), out soundraw); sound = new Sound(soundraw); return result; } public RESULT getIndex (out int index) { return FMOD_Channel_GetIndex(getRaw(), out index); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetFrequency (IntPtr channel, float frequency); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetFrequency (IntPtr channel, out float frequency); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetPriority (IntPtr channel, int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetPriority (IntPtr channel, out int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetChannelGroup (IntPtr channel, IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetChannelGroup (IntPtr channel, out IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_IsVirtual (IntPtr channel, out bool isvirtual); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetCurrentSound (IntPtr channel, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetIndex (IntPtr channel, out int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetPosition (IntPtr channel, uint position, TIMEUNIT postype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetPosition (IntPtr channel, out uint position, TIMEUNIT postype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetMode (IntPtr channel, MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetMode (IntPtr channel, out MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetLoopCount (IntPtr channel, int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetLoopCount (IntPtr channel, out int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetLoopPoints (IntPtr channel, uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetLoopPoints (IntPtr channel, out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetUserData (IntPtr channel, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetUserData (IntPtr channel, out IntPtr userdata); #endregion #region wrapperinternal public Channel(IntPtr raw) : base(raw) { } #endregion } /* 'ChannelGroup' API */ public class ChannelGroup : ChannelControl { public RESULT release () { RESULT result = FMOD_ChannelGroup_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Nested channel groups. public RESULT addGroup (ChannelGroup group, bool propagatedspclock, out DSPConnection connection) { connection = null; IntPtr connectionRaw; RESULT result = FMOD_ChannelGroup_AddGroup(getRaw(), group.getRaw(), propagatedspclock, out connectionRaw); connection = new DSPConnection(connectionRaw); return result; } public RESULT getNumGroups (out int numgroups) { return FMOD_ChannelGroup_GetNumGroups(getRaw(), out numgroups); } public RESULT getGroup (int index, out ChannelGroup group) { group = null; IntPtr groupraw; RESULT result = FMOD_ChannelGroup_GetGroup(getRaw(), index, out groupraw); group = new ChannelGroup(groupraw); return result; } public RESULT getParentGroup (out ChannelGroup group) { group = null; IntPtr groupraw; RESULT result = FMOD_ChannelGroup_GetParentGroup(getRaw(), out groupraw); group = new ChannelGroup(groupraw); return result; } // Information only functions. public RESULT getName (StringBuilder name, int namelen) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_ChannelGroup_GetName(getRaw(), stringMem, namelen); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getNumChannels (out int numchannels) { return FMOD_ChannelGroup_GetNumChannels(getRaw(), out numchannels); } public RESULT getChannel (int index, out Channel channel) { channel = null; IntPtr channelraw; RESULT result = FMOD_ChannelGroup_GetChannel(getRaw(), index, out channelraw); channel = new Channel(channelraw); return result; } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Release (IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_AddGroup (IntPtr channelgroup, IntPtr group, bool propagatedspclock, out IntPtr connection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetNumGroups (IntPtr channelgroup, out int numgroups); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetGroup (IntPtr channelgroup, int index, out IntPtr group); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetParentGroup (IntPtr channelgroup, out IntPtr group); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetName (IntPtr channelgroup, IntPtr name, int namelen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetNumChannels (IntPtr channelgroup, out int numchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetChannel (IntPtr channelgroup, int index, out IntPtr channel); #endregion #region wrapperinternal public ChannelGroup(IntPtr raw) : base(raw) { } #endregion } /* 'SoundGroup' API */ public class SoundGroup : HandleBase { public RESULT release () { RESULT result = FMOD_SoundGroup_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } public RESULT getSystemObject (out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_SoundGroup_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // SoundGroup control functions. public RESULT setMaxAudible (int maxaudible) { return FMOD_SoundGroup_SetMaxAudible(rawPtr, maxaudible); } public RESULT getMaxAudible (out int maxaudible) { return FMOD_SoundGroup_GetMaxAudible(rawPtr, out maxaudible); } public RESULT setMaxAudibleBehavior (SOUNDGROUP_BEHAVIOR behavior) { return FMOD_SoundGroup_SetMaxAudibleBehavior(rawPtr, behavior); } public RESULT getMaxAudibleBehavior (out SOUNDGROUP_BEHAVIOR behavior) { return FMOD_SoundGroup_GetMaxAudibleBehavior(rawPtr, out behavior); } public RESULT setMuteFadeSpeed (float speed) { return FMOD_SoundGroup_SetMuteFadeSpeed(rawPtr, speed); } public RESULT getMuteFadeSpeed (out float speed) { return FMOD_SoundGroup_GetMuteFadeSpeed(rawPtr, out speed); } public RESULT setVolume (float volume) { return FMOD_SoundGroup_SetVolume(rawPtr, volume); } public RESULT getVolume (out float volume) { return FMOD_SoundGroup_GetVolume(rawPtr, out volume); } public RESULT stop () { return FMOD_SoundGroup_Stop(rawPtr); } // Information only functions. public RESULT getName (StringBuilder name, int namelen) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_SoundGroup_GetName(rawPtr, stringMem, namelen); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getNumSounds (out int numsounds) { return FMOD_SoundGroup_GetNumSounds(rawPtr, out numsounds); } public RESULT getSound (int index, out Sound sound) { sound = null; IntPtr soundraw; RESULT result = FMOD_SoundGroup_GetSound(rawPtr, index, out soundraw); sound = new Sound(soundraw); return result; } public RESULT getNumPlaying (out int numplaying) { return FMOD_SoundGroup_GetNumPlaying(rawPtr, out numplaying); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_SoundGroup_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_SoundGroup_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_Release (IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetSystemObject (IntPtr soundgroup, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetMaxAudible (IntPtr soundgroup, int maxaudible); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetMaxAudible (IntPtr soundgroup, out int maxaudible); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetMaxAudibleBehavior(IntPtr soundgroup, SOUNDGROUP_BEHAVIOR behavior); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetMaxAudibleBehavior(IntPtr soundgroup, out SOUNDGROUP_BEHAVIOR behavior); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetMuteFadeSpeed (IntPtr soundgroup, float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetMuteFadeSpeed (IntPtr soundgroup, out float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetVolume (IntPtr soundgroup, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetVolume (IntPtr soundgroup, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_Stop (IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetName (IntPtr soundgroup, IntPtr name, int namelen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetNumSounds (IntPtr soundgroup, out int numsounds); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetSound (IntPtr soundgroup, int index, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetNumPlaying (IntPtr soundgroup, out int numplaying); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetUserData (IntPtr soundgroup, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetUserData (IntPtr soundgroup, out IntPtr userdata); #endregion #region wrapperinternal public SoundGroup(IntPtr raw) : base(raw) { } #endregion } /* 'DSP' API */ public class DSP : HandleBase { public RESULT release () { RESULT result = FMOD_DSP_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } public RESULT getSystemObject (out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_DSP_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // Connection / disconnection / input and output enumeration. public RESULT addInput(DSP target, out DSPConnection connection, DSPCONNECTION_TYPE type) { connection = null; IntPtr dspconnectionraw; RESULT result = FMOD_DSP_AddInput(rawPtr, target.getRaw(), out dspconnectionraw, type); connection = new DSPConnection(dspconnectionraw); return result; } public RESULT disconnectFrom (DSP target, DSPConnection connection) { return FMOD_DSP_DisconnectFrom(rawPtr, target.getRaw(), connection.getRaw()); } public RESULT disconnectAll (bool inputs, bool outputs) { return FMOD_DSP_DisconnectAll(rawPtr, inputs, outputs); } public RESULT getNumInputs (out int numinputs) { return FMOD_DSP_GetNumInputs(rawPtr, out numinputs); } public RESULT getNumOutputs (out int numoutputs) { return FMOD_DSP_GetNumOutputs(rawPtr, out numoutputs); } public RESULT getInput (int index, out DSP input, out DSPConnection inputconnection) { input = null; inputconnection = null; IntPtr dspinputraw; IntPtr dspconnectionraw; RESULT result = FMOD_DSP_GetInput(rawPtr, index, out dspinputraw, out dspconnectionraw); input = new DSP(dspinputraw); inputconnection = new DSPConnection(dspconnectionraw); return result; } public RESULT getOutput (int index, out DSP output, out DSPConnection outputconnection) { output = null; outputconnection = null; IntPtr dspoutputraw; IntPtr dspconnectionraw; RESULT result = FMOD_DSP_GetOutput(rawPtr, index, out dspoutputraw, out dspconnectionraw); output = new DSP(dspoutputraw); outputconnection = new DSPConnection(dspconnectionraw); return result; } // DSP unit control. public RESULT setActive (bool active) { return FMOD_DSP_SetActive(rawPtr, active); } public RESULT getActive (out bool active) { return FMOD_DSP_GetActive(rawPtr, out active); } public RESULT setBypass(bool bypass) { return FMOD_DSP_SetBypass(rawPtr, bypass); } public RESULT getBypass(out bool bypass) { return FMOD_DSP_GetBypass(rawPtr, out bypass); } public RESULT setWetDryMix(float prewet, float postwet, float dry) { return FMOD_DSP_SetWetDryMix(rawPtr, prewet, postwet, dry); } public RESULT getWetDryMix(out float prewet, out float postwet, out float dry) { return FMOD_DSP_GetWetDryMix(rawPtr, out prewet, out postwet, out dry); } public RESULT setChannelFormat(CHANNELMASK channelmask, int numchannels, SPEAKERMODE source_speakermode) { return FMOD_DSP_SetChannelFormat(rawPtr, channelmask, numchannels, source_speakermode); } public RESULT getChannelFormat(out CHANNELMASK channelmask, out int numchannels, out SPEAKERMODE source_speakermode) { return FMOD_DSP_GetChannelFormat(rawPtr, out channelmask, out numchannels, out source_speakermode); } public RESULT getOutputChannelFormat(CHANNELMASK inmask, int inchannels, SPEAKERMODE inspeakermode, out CHANNELMASK outmask, out int outchannels, out SPEAKERMODE outspeakermode) { return FMOD_DSP_GetOutputChannelFormat(rawPtr, inmask, inchannels, inspeakermode, out outmask, out outchannels, out outspeakermode); } public RESULT reset () { return FMOD_DSP_Reset(rawPtr); } // DSP parameter control. public RESULT setParameterFloat(int index, float value) { return FMOD_DSP_SetParameterFloat(rawPtr, index, value); } public RESULT setParameterInt(int index, int value) { return FMOD_DSP_SetParameterInt(rawPtr, index, value); } public RESULT setParameterBool(int index, bool value) { return FMOD_DSP_SetParameterBool(rawPtr, index, value); } public RESULT setParameterData(int index, byte[] data) { return FMOD_DSP_SetParameterData(rawPtr, index, Marshal.UnsafeAddrOfPinnedArrayElement(data, 0), (uint)data.Length); } public RESULT getParameterFloat(int index, out float value) { IntPtr valuestr = IntPtr.Zero; return FMOD_DSP_GetParameterFloat(rawPtr, index, out value, valuestr, 0); } public RESULT getParameterInt(int index, out int value) { IntPtr valuestr = IntPtr.Zero; return FMOD_DSP_GetParameterInt(rawPtr, index, out value, valuestr, 0); } public RESULT getParameterBool(int index, out bool value) { return FMOD_DSP_GetParameterBool(rawPtr, index, out value, IntPtr.Zero, 0); } public RESULT getParameterData(int index, out IntPtr data, out uint length) { return FMOD_DSP_GetParameterData(rawPtr, index, out data, out length, IntPtr.Zero, 0); } public RESULT getNumParameters (out int numparams) { return FMOD_DSP_GetNumParameters(rawPtr, out numparams); } public RESULT getParameterInfo (int index, out DSP_PARAMETER_DESC desc) { IntPtr descPtr; RESULT result = FMOD_DSP_GetParameterInfo(rawPtr, index, out descPtr); if (result == RESULT.OK) { desc = (DSP_PARAMETER_DESC)Marshal.PtrToStructure(descPtr, typeof(DSP_PARAMETER_DESC)); } else { desc = new DSP_PARAMETER_DESC(); } return result; } public RESULT getDataParameterIndex(int datatype, out int index) { return FMOD_DSP_GetDataParameterIndex (rawPtr, datatype, out index); } public RESULT showConfigDialog (IntPtr hwnd, bool show) { return FMOD_DSP_ShowConfigDialog (rawPtr, hwnd, show); } // DSP attributes. public RESULT getInfo (StringBuilder name, out uint version, out int channels, out int configwidth, out int configheight) { IntPtr nameMem = Marshal.AllocHGlobal(32); RESULT result = FMOD_DSP_GetInfo(rawPtr, nameMem, out version, out channels, out configwidth, out configheight); StringMarshalHelper.NativeToBuilder(name, nameMem); Marshal.FreeHGlobal(nameMem); return result; } public RESULT getType (out DSP_TYPE type) { return FMOD_DSP_GetType(rawPtr, out type); } public RESULT getIdle (out bool idle) { return FMOD_DSP_GetIdle(rawPtr, out idle); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_DSP_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_DSP_GetUserData(rawPtr, out userdata); } // Metering. public RESULT setMeteringEnabled(bool inputEnabled, bool outputEnabled) { return FMOD_DSP_SetMeteringEnabled(rawPtr, inputEnabled, outputEnabled); } public RESULT getMeteringEnabled(out bool inputEnabled, out bool outputEnabled) { return FMOD_DSP_GetMeteringEnabled(rawPtr, out inputEnabled, out outputEnabled); } public RESULT getMeteringInfo(DSP_METERING_INFO inputInfo, DSP_METERING_INFO outputInfo) { return FMOD_DSP_GetMeteringInfo(rawPtr, inputInfo, outputInfo); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_Release (IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetSystemObject (IntPtr dsp, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_AddInput (IntPtr dsp, IntPtr target, out IntPtr connection, DSPCONNECTION_TYPE type); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_DisconnectFrom (IntPtr dsp, IntPtr target, IntPtr connection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_DisconnectAll (IntPtr dsp, bool inputs, bool outputs); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetNumInputs (IntPtr dsp, out int numinputs); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetNumOutputs (IntPtr dsp, out int numoutputs); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetInput (IntPtr dsp, int index, out IntPtr input, out IntPtr inputconnection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetOutput (IntPtr dsp, int index, out IntPtr output, out IntPtr outputconnection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetActive (IntPtr dsp, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetActive (IntPtr dsp, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetBypass (IntPtr dsp, bool bypass); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetBypass (IntPtr dsp, out bool bypass); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetWetDryMix (IntPtr dsp, float prewet, float postwet, float dry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetWetDryMix (IntPtr dsp, out float prewet, out float postwet, out float dry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetChannelFormat (IntPtr dsp, CHANNELMASK channelmask, int numchannels, SPEAKERMODE source_speakermode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetChannelFormat (IntPtr dsp, out CHANNELMASK channelmask, out int numchannels, out SPEAKERMODE source_speakermode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetOutputChannelFormat (IntPtr dsp, CHANNELMASK inmask, int inchannels, SPEAKERMODE inspeakermode, out CHANNELMASK outmask, out int outchannels, out SPEAKERMODE outspeakermode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_Reset (IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterFloat (IntPtr dsp, int index, float value); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterInt (IntPtr dsp, int index, int value); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterBool (IntPtr dsp, int index, bool value); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterData (IntPtr dsp, int index, IntPtr data, uint length); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterFloat (IntPtr dsp, int index, out float value, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterInt (IntPtr dsp, int index, out int value, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterBool (IntPtr dsp, int index, out bool value, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterData (IntPtr dsp, int index, out IntPtr data, out uint length, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetNumParameters (IntPtr dsp, out int numparams); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterInfo (IntPtr dsp, int index, out IntPtr desc); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetDataParameterIndex (IntPtr dsp, int datatype, out int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_ShowConfigDialog (IntPtr dsp, IntPtr hwnd, bool show); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetInfo (IntPtr dsp, IntPtr name, out uint version, out int channels, out int configwidth, out int configheight); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetType (IntPtr dsp, out DSP_TYPE type); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetIdle (IntPtr dsp, out bool idle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetUserData (IntPtr dsp, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetUserData (IntPtr dsp, out IntPtr userdata); [DllImport(VERSION.dll)] public static extern RESULT FMOD_DSP_SetMeteringEnabled (IntPtr dsp, bool inputEnabled, bool outputEnabled); [DllImport(VERSION.dll)] public static extern RESULT FMOD_DSP_GetMeteringEnabled (IntPtr dsp, out bool inputEnabled, out bool outputEnabled); [DllImport(VERSION.dll)] public static extern RESULT FMOD_DSP_GetMeteringInfo (IntPtr dsp, [Out] DSP_METERING_INFO inputInfo, [Out] DSP_METERING_INFO outputInfo); #endregion #region wrapperinternal public DSP(IntPtr raw) : base(raw) { } #endregion } /* 'DSPConnection' API */ public class DSPConnection : HandleBase { public RESULT getInput (out DSP input) { input = null; IntPtr dspraw; RESULT result = FMOD_DSPConnection_GetInput(rawPtr, out dspraw); input = new DSP(dspraw); return result; } public RESULT getOutput (out DSP output) { output = null; IntPtr dspraw; RESULT result = FMOD_DSPConnection_GetOutput(rawPtr, out dspraw); output = new DSP(dspraw); return result; } public RESULT setMix (float volume) { return FMOD_DSPConnection_SetMix(rawPtr, volume); } public RESULT getMix (out float volume) { return FMOD_DSPConnection_GetMix(rawPtr, out volume); } public RESULT setMixMatrix(float[] matrix, int outchannels, int inchannels, int inchannel_hop) { return FMOD_DSPConnection_SetMixMatrix(rawPtr, matrix, outchannels, inchannels, inchannel_hop); } public RESULT getMixMatrix(float[] matrix, out int outchannels, out int inchannels, int inchannel_hop) { return FMOD_DSPConnection_GetMixMatrix(rawPtr, matrix, out outchannels, out inchannels, inchannel_hop); } public RESULT getType(out DSPCONNECTION_TYPE type) { return FMOD_DSPConnection_GetType(rawPtr, out type); } // Userdata set/get. public RESULT setUserData(IntPtr userdata) { return FMOD_DSPConnection_SetUserData(rawPtr, userdata); } public RESULT getUserData(out IntPtr userdata) { return FMOD_DSPConnection_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetInput (IntPtr dspconnection, out IntPtr input); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetOutput (IntPtr dspconnection, out IntPtr output); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_SetMix (IntPtr dspconnection, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetMix (IntPtr dspconnection, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_SetMixMatrix (IntPtr dspconnection, float[] matrix, int outchannels, int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetMixMatrix (IntPtr dspconnection, float[] matrix, out int outchannels, out int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetType (IntPtr dspconnection, out DSPCONNECTION_TYPE type); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_SetUserData (IntPtr dspconnection, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetUserData (IntPtr dspconnection, out IntPtr userdata); #endregion #region wrapperinternal public DSPConnection(IntPtr raw) : base(raw) { } #endregion } /* 'Geometry' API */ public class Geometry : HandleBase { public RESULT release () { RESULT result = FMOD_Geometry_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Polygon manipulation. public RESULT addPolygon (float directocclusion, float reverbocclusion, bool doublesided, int numvertices, VECTOR[] vertices, out int polygonindex) { return FMOD_Geometry_AddPolygon(rawPtr, directocclusion, reverbocclusion, doublesided, numvertices, vertices, out polygonindex); } public RESULT getNumPolygons (out int numpolygons) { return FMOD_Geometry_GetNumPolygons(rawPtr, out numpolygons); } public RESULT getMaxPolygons (out int maxpolygons, out int maxvertices) { return FMOD_Geometry_GetMaxPolygons(rawPtr, out maxpolygons, out maxvertices); } public RESULT getPolygonNumVertices (int index, out int numvertices) { return FMOD_Geometry_GetPolygonNumVertices(rawPtr, index, out numvertices); } public RESULT setPolygonVertex (int index, int vertexindex, ref VECTOR vertex) { return FMOD_Geometry_SetPolygonVertex(rawPtr, index, vertexindex, ref vertex); } public RESULT getPolygonVertex (int index, int vertexindex, out VECTOR vertex) { return FMOD_Geometry_GetPolygonVertex(rawPtr, index, vertexindex, out vertex); } public RESULT setPolygonAttributes (int index, float directocclusion, float reverbocclusion, bool doublesided) { return FMOD_Geometry_SetPolygonAttributes(rawPtr, index, directocclusion, reverbocclusion, doublesided); } public RESULT getPolygonAttributes (int index, out float directocclusion, out float reverbocclusion, out bool doublesided) { return FMOD_Geometry_GetPolygonAttributes(rawPtr, index, out directocclusion, out reverbocclusion, out doublesided); } // Object manipulation. public RESULT setActive (bool active) { return FMOD_Geometry_SetActive(rawPtr, active); } public RESULT getActive (out bool active) { return FMOD_Geometry_GetActive(rawPtr, out active); } public RESULT setRotation (ref VECTOR forward, ref VECTOR up) { return FMOD_Geometry_SetRotation(rawPtr, ref forward, ref up); } public RESULT getRotation (out VECTOR forward, out VECTOR up) { return FMOD_Geometry_GetRotation(rawPtr, out forward, out up); } public RESULT setPosition (ref VECTOR position) { return FMOD_Geometry_SetPosition(rawPtr, ref position); } public RESULT getPosition (out VECTOR position) { return FMOD_Geometry_GetPosition(rawPtr, out position); } public RESULT setScale (ref VECTOR scale) { return FMOD_Geometry_SetScale(rawPtr, ref scale); } public RESULT getScale (out VECTOR scale) { return FMOD_Geometry_GetScale(rawPtr, out scale); } public RESULT save (IntPtr data, out int datasize) { return FMOD_Geometry_Save(rawPtr, data, out datasize); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_Geometry_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_Geometry_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_Release (IntPtr geometry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_AddPolygon (IntPtr geometry, float directocclusion, float reverbocclusion, bool doublesided, int numvertices, VECTOR[] vertices, out int polygonindex); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetNumPolygons (IntPtr geometry, out int numpolygons); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetMaxPolygons (IntPtr geometry, out int maxpolygons, out int maxvertices); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPolygonNumVertices(IntPtr geometry, int index, out int numvertices); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetPolygonVertex (IntPtr geometry, int index, int vertexindex, ref VECTOR vertex); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPolygonVertex (IntPtr geometry, int index, int vertexindex, out VECTOR vertex); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetPolygonAttributes (IntPtr geometry, int index, float directocclusion, float reverbocclusion, bool doublesided); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPolygonAttributes (IntPtr geometry, int index, out float directocclusion, out float reverbocclusion, out bool doublesided); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetActive (IntPtr geometry, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetActive (IntPtr geometry, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetRotation (IntPtr geometry, ref VECTOR forward, ref VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetRotation (IntPtr geometry, out VECTOR forward, out VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetPosition (IntPtr geometry, ref VECTOR position); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPosition (IntPtr geometry, out VECTOR position); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetScale (IntPtr geometry, ref VECTOR scale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetScale (IntPtr geometry, out VECTOR scale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_Save (IntPtr geometry, IntPtr data, out int datasize); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetUserData (IntPtr geometry, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetUserData (IntPtr geometry, out IntPtr userdata); #endregion #region wrapperinternal public Geometry(IntPtr raw) : base(raw) { } #endregion } /* 'Reverb3D' API */ public class Reverb3D : HandleBase { public RESULT release() { RESULT result = FMOD_Reverb3D_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Reverb manipulation. public RESULT set3DAttributes(ref VECTOR position, float mindistance, float maxdistance) { return FMOD_Reverb3D_Set3DAttributes(rawPtr, ref position, mindistance, maxdistance); } public RESULT get3DAttributes(ref VECTOR position, ref float mindistance, ref float maxdistance) { return FMOD_Reverb3D_Get3DAttributes(rawPtr, ref position, ref mindistance, ref maxdistance); } public RESULT setProperties(ref REVERB_PROPERTIES properties) { return FMOD_Reverb3D_SetProperties(rawPtr, ref properties); } public RESULT getProperties(ref REVERB_PROPERTIES properties) { return FMOD_Reverb3D_GetProperties(rawPtr, ref properties); } public RESULT setActive(bool active) { return FMOD_Reverb3D_SetActive(rawPtr, active); } public RESULT getActive(out bool active) { return FMOD_Reverb3D_GetActive(rawPtr, out active); } // Userdata set/get. public RESULT setUserData(IntPtr userdata) { return FMOD_Reverb3D_SetUserData(rawPtr, userdata); } public RESULT getUserData(out IntPtr userdata) { return FMOD_Reverb3D_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_Release(IntPtr reverb); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_Set3DAttributes(IntPtr reverb, ref VECTOR position, float mindistance, float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_Get3DAttributes(IntPtr reverb, ref VECTOR position, ref float mindistance, ref float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_SetProperties(IntPtr reverb, ref REVERB_PROPERTIES properties); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_GetProperties(IntPtr reverb, ref REVERB_PROPERTIES properties); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_SetActive(IntPtr reverb, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_GetActive(IntPtr reverb, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_SetUserData(IntPtr reverb, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_GetUserData(IntPtr reverb, out IntPtr userdata); #endregion #region wrapperinternal public Reverb3D(IntPtr raw) : base(raw) { } #endregion } class StringMarshalHelper { static internal void NativeToBuilder(StringBuilder builder, IntPtr nativeMem) { byte[] bytes = new byte[builder.Capacity]; Marshal.Copy(nativeMem, bytes, 0, builder.Capacity); int strlen = Array.IndexOf(bytes, (byte)0); if (strlen > 0) { String str = Encoding.UTF8.GetString(bytes, 0, strlen); builder.Append(str); } } } }
AssetStudio/AssetStudioUtility/FMOD Studio API/fmod.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/FMOD Studio API/fmod.cs", "repo_id": "AssetStudio", "token_count": 95317 }
74
using System; using System.Runtime.CompilerServices; using Texture2DDecoder; namespace AssetStudio { public class Texture2DConverter { private ResourceReader reader; private int m_Width; private int m_Height; private TextureFormat m_TextureFormat; private int[] version; private BuildTarget platform; private int outPutSize; public Texture2DConverter(Texture2D m_Texture2D) { reader = m_Texture2D.image_data; m_Width = m_Texture2D.m_Width; m_Height = m_Texture2D.m_Height; m_TextureFormat = m_Texture2D.m_TextureFormat; version = m_Texture2D.version; platform = m_Texture2D.platform; outPutSize = m_Width * m_Height * 4; } public bool DecodeTexture2D(byte[] bytes) { if (reader.Size == 0 || m_Width == 0 || m_Height == 0) { return false; } var flag = false; var buff = BigArrayPool<byte>.Shared.Rent(reader.Size); reader.GetData(buff); switch (m_TextureFormat) { case TextureFormat.Alpha8: //test pass flag = DecodeAlpha8(buff, bytes); break; case TextureFormat.ARGB4444: //test pass SwapBytesForXbox(buff); flag = DecodeARGB4444(buff, bytes); break; case TextureFormat.RGB24: //test pass flag = DecodeRGB24(buff, bytes); break; case TextureFormat.RGBA32: //test pass flag = DecodeRGBA32(buff, bytes); break; case TextureFormat.ARGB32: //test pass flag = DecodeARGB32(buff, bytes); break; case TextureFormat.RGB565: //test pass SwapBytesForXbox(buff); flag = DecodeRGB565(buff, bytes); break; case TextureFormat.R16: //test pass flag = DecodeR16(buff, bytes); break; case TextureFormat.DXT1: //test pass SwapBytesForXbox(buff); flag = DecodeDXT1(buff, bytes); break; case TextureFormat.DXT3: break; case TextureFormat.DXT5: //test pass SwapBytesForXbox(buff); flag = DecodeDXT5(buff, bytes); break; case TextureFormat.RGBA4444: //test pass flag = DecodeRGBA4444(buff, bytes); break; case TextureFormat.BGRA32: //test pass flag = DecodeBGRA32(buff, bytes); break; case TextureFormat.RHalf: flag = DecodeRHalf(buff, bytes); break; case TextureFormat.RGHalf: flag = DecodeRGHalf(buff, bytes); break; case TextureFormat.RGBAHalf: //test pass flag = DecodeRGBAHalf(buff, bytes); break; case TextureFormat.RFloat: flag = DecodeRFloat(buff, bytes); break; case TextureFormat.RGFloat: flag = DecodeRGFloat(buff, bytes); break; case TextureFormat.RGBAFloat: flag = DecodeRGBAFloat(buff, bytes); break; case TextureFormat.YUY2: //test pass flag = DecodeYUY2(buff, bytes); break; case TextureFormat.RGB9e5Float: //test pass flag = DecodeRGB9e5Float(buff, bytes); break; case TextureFormat.BC6H: //test pass flag = DecodeBC6H(buff, bytes); break; case TextureFormat.BC7: //test pass flag = DecodeBC7(buff, bytes); break; case TextureFormat.BC4: //test pass flag = DecodeBC4(buff, bytes); break; case TextureFormat.BC5: //test pass flag = DecodeBC5(buff, bytes); break; case TextureFormat.DXT1Crunched: //test pass flag = DecodeDXT1Crunched(buff, bytes); break; case TextureFormat.DXT5Crunched: //test pass flag = DecodeDXT5Crunched(buff, bytes); break; case TextureFormat.PVRTC_RGB2: //test pass case TextureFormat.PVRTC_RGBA2: //test pass flag = DecodePVRTC(buff, bytes, true); break; case TextureFormat.PVRTC_RGB4: //test pass case TextureFormat.PVRTC_RGBA4: //test pass flag = DecodePVRTC(buff, bytes, false); break; case TextureFormat.ETC_RGB4: //test pass case TextureFormat.ETC_RGB4_3DS: flag = DecodeETC1(buff, bytes); break; case TextureFormat.ATC_RGB4: //test pass flag = DecodeATCRGB4(buff, bytes); break; case TextureFormat.ATC_RGBA8: //test pass flag = DecodeATCRGBA8(buff, bytes); break; case TextureFormat.EAC_R: //test pass flag = DecodeEACR(buff, bytes); break; case TextureFormat.EAC_R_SIGNED: flag = DecodeEACRSigned(buff, bytes); break; case TextureFormat.EAC_RG: //test pass flag = DecodeEACRG(buff, bytes); break; case TextureFormat.EAC_RG_SIGNED: flag = DecodeEACRGSigned(buff, bytes); break; case TextureFormat.ETC2_RGB: //test pass flag = DecodeETC2(buff, bytes); break; case TextureFormat.ETC2_RGBA1: //test pass flag = DecodeETC2A1(buff, bytes); break; case TextureFormat.ETC2_RGBA8: //test pass case TextureFormat.ETC_RGBA8_3DS: flag = DecodeETC2A8(buff, bytes); break; case TextureFormat.ASTC_RGB_4x4: //test pass case TextureFormat.ASTC_RGBA_4x4: //test pass case TextureFormat.ASTC_HDR_4x4: //test pass flag = DecodeASTC(buff, bytes, 4); break; case TextureFormat.ASTC_RGB_5x5: //test pass case TextureFormat.ASTC_RGBA_5x5: //test pass case TextureFormat.ASTC_HDR_5x5: //test pass flag = DecodeASTC(buff, bytes, 5); break; case TextureFormat.ASTC_RGB_6x6: //test pass case TextureFormat.ASTC_RGBA_6x6: //test pass case TextureFormat.ASTC_HDR_6x6: //test pass flag = DecodeASTC(buff, bytes, 6); break; case TextureFormat.ASTC_RGB_8x8: //test pass case TextureFormat.ASTC_RGBA_8x8: //test pass case TextureFormat.ASTC_HDR_8x8: //test pass flag = DecodeASTC(buff, bytes, 8); break; case TextureFormat.ASTC_RGB_10x10: //test pass case TextureFormat.ASTC_RGBA_10x10: //test pass case TextureFormat.ASTC_HDR_10x10: //test pass flag = DecodeASTC(buff, bytes, 10); break; case TextureFormat.ASTC_RGB_12x12: //test pass case TextureFormat.ASTC_RGBA_12x12: //test pass case TextureFormat.ASTC_HDR_12x12: //test pass flag = DecodeASTC(buff, bytes, 12); break; case TextureFormat.RG16: //test pass flag = DecodeRG16(buff, bytes); break; case TextureFormat.R8: //test pass flag = DecodeR8(buff, bytes); break; case TextureFormat.ETC_RGB4Crunched: //test pass flag = DecodeETC1Crunched(buff, bytes); break; case TextureFormat.ETC2_RGBA8Crunched: //test pass flag = DecodeETC2A8Crunched(buff, bytes); break; case TextureFormat.RG32: //test pass flag = DecodeRG32(buff, bytes); break; case TextureFormat.RGB48: //test pass flag = DecodeRGB48(buff, bytes); break; case TextureFormat.RGBA64: //test pass flag = DecodeRGBA64(buff, bytes); break; } BigArrayPool<byte>.Shared.Return(buff); return flag; } private void SwapBytesForXbox(byte[] image_data) { if (platform == BuildTarget.XBOX360) { for (var i = 0; i < reader.Size / 2; i++) { var b = image_data[i * 2]; image_data[i * 2] = image_data[i * 2 + 1]; image_data[i * 2 + 1] = b; } } } private bool DecodeAlpha8(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; var span = new Span<byte>(buff); span.Fill(0xFF); for (var i = 0; i < size; i++) { buff[i * 4 + 3] = image_data[i]; } return true; } private bool DecodeARGB4444(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; var pixelNew = new byte[4]; for (var i = 0; i < size; i++) { var pixelOldShort = BitConverter.ToUInt16(image_data, i * 2); pixelNew[0] = (byte)(pixelOldShort & 0x000f); pixelNew[1] = (byte)((pixelOldShort & 0x00f0) >> 4); pixelNew[2] = (byte)((pixelOldShort & 0x0f00) >> 8); pixelNew[3] = (byte)((pixelOldShort & 0xf000) >> 12); for (var j = 0; j < 4; j++) pixelNew[j] = (byte)((pixelNew[j] << 4) | pixelNew[j]); pixelNew.CopyTo(buff, i * 4); } return true; } private bool DecodeRGB24(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; for (var i = 0; i < size; i++) { buff[i * 4] = image_data[i * 3 + 2]; buff[i * 4 + 1] = image_data[i * 3 + 1]; buff[i * 4 + 2] = image_data[i * 3 + 0]; buff[i * 4 + 3] = 255; } return true; } private bool DecodeRGBA32(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = image_data[i + 2]; buff[i + 1] = image_data[i + 1]; buff[i + 2] = image_data[i + 0]; buff[i + 3] = image_data[i + 3]; } return true; } private bool DecodeARGB32(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = image_data[i + 3]; buff[i + 1] = image_data[i + 2]; buff[i + 2] = image_data[i + 1]; buff[i + 3] = image_data[i + 0]; } return true; } private bool DecodeRGB565(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; for (var i = 0; i < size; i++) { var p = BitConverter.ToUInt16(image_data, i * 2); buff[i * 4] = (byte)((p << 3) | (p >> 2 & 7)); buff[i * 4 + 1] = (byte)((p >> 3 & 0xfc) | (p >> 9 & 3)); buff[i * 4 + 2] = (byte)((p >> 8 & 0xf8) | (p >> 13)); buff[i * 4 + 3] = 255; } return true; } private bool DecodeR16(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; for (var i = 0; i < size; i++) { buff[i * 4] = 0; //b buff[i * 4 + 1] = 0; //g buff[i * 4 + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2)); //r buff[i * 4 + 3] = 255; //a } return true; } private bool DecodeDXT1(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeDXT1(image_data, m_Width, m_Height, buff); } private bool DecodeDXT5(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeDXT5(image_data, m_Width, m_Height, buff); } private bool DecodeRGBA4444(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; var pixelNew = new byte[4]; for (var i = 0; i < size; i++) { var pixelOldShort = BitConverter.ToUInt16(image_data, i * 2); pixelNew[0] = (byte)((pixelOldShort & 0x00f0) >> 4); pixelNew[1] = (byte)((pixelOldShort & 0x0f00) >> 8); pixelNew[2] = (byte)((pixelOldShort & 0xf000) >> 12); pixelNew[3] = (byte)(pixelOldShort & 0x000f); for (var j = 0; j < 4; j++) pixelNew[j] = (byte)((pixelNew[j] << 4) | pixelNew[j]); pixelNew.CopyTo(buff, i * 4); } return true; } private bool DecodeBGRA32(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = image_data[i]; buff[i + 1] = image_data[i + 1]; buff[i + 2] = image_data[i + 2]; buff[i + 3] = image_data[i + 3]; } return true; } private bool DecodeRHalf(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = 0; buff[i + 1] = 0; buff[i + 2] = (byte)Math.Round(Half.ToHalf(image_data, i / 2) * 255f); buff[i + 3] = 255; } return true; } private bool DecodeRGHalf(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = 0; buff[i + 1] = (byte)Math.Round(Half.ToHalf(image_data, i + 2) * 255f); buff[i + 2] = (byte)Math.Round(Half.ToHalf(image_data, i) * 255f); buff[i + 3] = 255; } return true; } private bool DecodeRGBAHalf(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = (byte)Math.Round(Half.ToHalf(image_data, i * 2 + 4) * 255f); buff[i + 1] = (byte)Math.Round(Half.ToHalf(image_data, i * 2 + 2) * 255f); buff[i + 2] = (byte)Math.Round(Half.ToHalf(image_data, i * 2) * 255f); buff[i + 3] = (byte)Math.Round(Half.ToHalf(image_data, i * 2 + 6) * 255f); } return true; } private bool DecodeRFloat(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = 0; buff[i + 1] = 0; buff[i + 2] = (byte)Math.Round(BitConverter.ToSingle(image_data, i) * 255f); buff[i + 3] = 255; } return true; } private bool DecodeRGFloat(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = 0; buff[i + 1] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 2 + 4) * 255f); buff[i + 2] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 2) * 255f); buff[i + 3] = 255; } return true; } private bool DecodeRGBAFloat(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4 + 8) * 255f); buff[i + 1] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4 + 4) * 255f); buff[i + 2] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4) * 255f); buff[i + 3] = (byte)Math.Round(BitConverter.ToSingle(image_data, i * 4 + 12) * 255f); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte ClampByte(int x) { return (byte)(byte.MaxValue < x ? byte.MaxValue : (x > byte.MinValue ? x : byte.MinValue)); } private bool DecodeYUY2(byte[] image_data, byte[] buff) { int p = 0; int o = 0; int halfWidth = m_Width / 2; for (int j = 0; j < m_Height; j++) { for (int i = 0; i < halfWidth; ++i) { int y0 = image_data[p++]; int u0 = image_data[p++]; int y1 = image_data[p++]; int v0 = image_data[p++]; int c = y0 - 16; int d = u0 - 128; int e = v0 - 128; buff[o++] = ClampByte((298 * c + 516 * d + 128) >> 8); // b buff[o++] = ClampByte((298 * c - 100 * d - 208 * e + 128) >> 8); // g buff[o++] = ClampByte((298 * c + 409 * e + 128) >> 8); // r buff[o++] = 255; c = y1 - 16; buff[o++] = ClampByte((298 * c + 516 * d + 128) >> 8); // b buff[o++] = ClampByte((298 * c - 100 * d - 208 * e + 128) >> 8); // g buff[o++] = ClampByte((298 * c + 409 * e + 128) >> 8); // r buff[o++] = 255; } } return true; } private bool DecodeRGB9e5Float(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { var n = BitConverter.ToInt32(image_data, i); var scale = n >> 27 & 0x1f; var scalef = Math.Pow(2, scale - 24); var b = n >> 18 & 0x1ff; var g = n >> 9 & 0x1ff; var r = n & 0x1ff; buff[i] = (byte)Math.Round(b * scalef * 255f); buff[i + 1] = (byte)Math.Round(g * scalef * 255f); buff[i + 2] = (byte)Math.Round(r * scalef * 255f); buff[i + 3] = 255; } return true; } private bool DecodeBC4(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeBC4(image_data, m_Width, m_Height, buff); } private bool DecodeBC5(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeBC5(image_data, m_Width, m_Height, buff); } private bool DecodeBC6H(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeBC6(image_data, m_Width, m_Height, buff); } private bool DecodeBC7(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeBC7(image_data, m_Width, m_Height, buff); } private bool DecodeDXT1Crunched(byte[] image_data, byte[] buff) { if (UnpackCrunch(image_data, out var result)) { if (DecodeDXT1(result, buff)) { return true; } } return false; } private bool DecodeDXT5Crunched(byte[] image_data, byte[] buff) { if (UnpackCrunch(image_data, out var result)) { if (DecodeDXT5(result, buff)) { return true; } } return false; } private bool DecodePVRTC(byte[] image_data, byte[] buff, bool is2bpp) { return TextureDecoder.DecodePVRTC(image_data, m_Width, m_Height, buff, is2bpp); } private bool DecodeETC1(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeETC1(image_data, m_Width, m_Height, buff); } private bool DecodeATCRGB4(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeATCRGB4(image_data, m_Width, m_Height, buff); } private bool DecodeATCRGBA8(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeATCRGBA8(image_data, m_Width, m_Height, buff); } private bool DecodeEACR(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeEACR(image_data, m_Width, m_Height, buff); } private bool DecodeEACRSigned(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeEACRSigned(image_data, m_Width, m_Height, buff); } private bool DecodeEACRG(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeEACRG(image_data, m_Width, m_Height, buff); } private bool DecodeEACRGSigned(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeEACRGSigned(image_data, m_Width, m_Height, buff); } private bool DecodeETC2(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeETC2(image_data, m_Width, m_Height, buff); } private bool DecodeETC2A1(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeETC2A1(image_data, m_Width, m_Height, buff); } private bool DecodeETC2A8(byte[] image_data, byte[] buff) { return TextureDecoder.DecodeETC2A8(image_data, m_Width, m_Height, buff); } private bool DecodeASTC(byte[] image_data, byte[] buff, int blocksize) { return TextureDecoder.DecodeASTC(image_data, m_Width, m_Height, blocksize, blocksize, buff); } private bool DecodeRG16(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; for (var i = 0; i < size; i++) { buff[i * 4] = 0; //B buff[i * 4 + 1] = image_data[i * 2 + 1];//G buff[i * 4 + 2] = image_data[i * 2];//R buff[i * 4 + 3] = 255;//A } return true; } private bool DecodeR8(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; for (var i = 0; i < size; i++) { buff[i * 4] = 0; //B buff[i * 4 + 1] = 0; //G buff[i * 4 + 2] = image_data[i];//R buff[i * 4 + 3] = 255;//A } return true; } private bool DecodeETC1Crunched(byte[] image_data, byte[] buff) { if (UnpackCrunch(image_data, out var result)) { if (DecodeETC1(result, buff)) { return true; } } return false; } private bool DecodeETC2A8Crunched(byte[] image_data, byte[] buff) { if (UnpackCrunch(image_data, out var result)) { if (DecodeETC2A8(result, buff)) { return true; } } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte DownScaleFrom16BitTo8Bit(ushort component) { return (byte)(((component * 255) + 32895) >> 16); } private bool DecodeRG32(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = 0; //b buff[i + 1] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i + 2)); //g buff[i + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i)); //r buff[i + 3] = byte.MaxValue; //a } return true; } private bool DecodeRGB48(byte[] image_data, byte[] buff) { var size = m_Width * m_Height; for (var i = 0; i < size; i++) { buff[i * 4] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 6 + 4)); //b buff[i * 4 + 1] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 6 + 2)); //g buff[i * 4 + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 6)); //r buff[i * 4 + 3] = byte.MaxValue; //a } return true; } private bool DecodeRGBA64(byte[] image_data, byte[] buff) { for (var i = 0; i < outPutSize; i += 4) { buff[i] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2 + 4)); //b buff[i + 1] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2 + 2)); //g buff[i + 2] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2)); //r buff[i + 3] = DownScaleFrom16BitTo8Bit(BitConverter.ToUInt16(image_data, i * 2 + 6)); //a } return true; } private bool UnpackCrunch(byte[] image_data, out byte[] result) { if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 3) //2017.3 and up || m_TextureFormat == TextureFormat.ETC_RGB4Crunched || m_TextureFormat == TextureFormat.ETC2_RGBA8Crunched) { result = TextureDecoder.UnpackUnityCrunch(image_data); } else { result = TextureDecoder.UnpackCrunch(image_data); } if (result != null) { return true; } return false; } } }
AssetStudio/AssetStudioUtility/Texture2DConverter.cs/0
{ "file_path": "AssetStudio/AssetStudioUtility/Texture2DConverter.cs", "repo_id": "AssetStudio", "token_count": 15732 }
75
#include "astc.h" #include <math.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "color.h" #include "fp16.h" static const int BitReverseTable[] = { 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF}; static const int WeightPrecTableA[] = {0, 0, 0, 3, 0, 5, 3, 0, 0, 0, 5, 3, 0, 5, 3, 0}; static const int WeightPrecTableB[] = {0, 0, 1, 0, 2, 0, 1, 3, 0, 0, 1, 2, 4, 2, 3, 5}; static const int CemTableA[] = {0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3, 0, 0}; static const int CemTableB[] = {8, 6, 5, 7, 5, 4, 6, 4, 3, 5, 3, 2, 4, 2, 1, 3, 1, 2, 1}; static inline uint_fast8_t bit_reverse_u8(const uint_fast8_t c, const int bits) { return BitReverseTable[c] >> (8 - bits); } static inline uint_fast64_t bit_reverse_u64(const uint_fast64_t d, const int bits) { uint_fast64_t ret = (uint_fast64_t)BitReverseTable[d & 0xff] << 56 | (uint_fast64_t)BitReverseTable[d >> 8 & 0xff] << 48 | (uint_fast64_t)BitReverseTable[d >> 16 & 0xff] << 40 | (uint_fast64_t)BitReverseTable[d >> 24 & 0xff] << 32 | (uint_fast32_t)BitReverseTable[d >> 32 & 0xff] << 24 | (uint_fast32_t)BitReverseTable[d >> 40 & 0xff] << 16 | (uint_fast16_t)BitReverseTable[d >> 48 & 0xff] << 8 | BitReverseTable[d >> 56 & 0xff]; return ret >> (64 - bits); } static inline int getbits(const uint8_t *buf, const int bit, const int len) { return (*(int *)(buf + bit / 8) >> (bit % 8)) & ((1 << len) - 1); } static inline uint_fast64_t getbits64(const uint8_t *buf, const int bit, const int len) { uint_fast64_t mask = len == 64 ? 0xffffffffffffffff : (1ull << len) - 1; if (len < 1) return 0; else if (bit >= 64) return (*(uint_fast64_t *)(buf + 8)) >> (bit - 64) & mask; else if (bit <= 0) return (*(uint_fast64_t *)buf) << -bit & mask; else if (bit + len <= 64) return (*(uint_fast64_t *)buf) >> bit & mask; else return ((*(uint_fast64_t *)buf) >> bit | *(uint_fast64_t *)(buf + 8) << (64 - bit)) & mask; } static inline uint16_t u8ptr_to_u16(const uint8_t *ptr) { return lton16(*(uint16_t *)ptr); } static inline uint_fast8_t clamp(const int n) { return n < 0 ? 0 : n > 255 ? 255 : n; } static inline void bit_transfer_signed(int *a, int *b) { *b = (*b >> 1) | (*a & 0x80); *a = (*a >> 1) & 0x3f; if (*a & 0x20) *a -= 0x40; } static inline void set_endpoint(int endpoint[8], int r1, int g1, int b1, int a1, int r2, int g2, int b2, int a2) { endpoint[0] = r1; endpoint[1] = g1; endpoint[2] = b1; endpoint[3] = a1; endpoint[4] = r2; endpoint[5] = g2; endpoint[6] = b2; endpoint[7] = a2; } static inline void set_endpoint_clamp(int endpoint[8], int r1, int g1, int b1, int a1, int r2, int g2, int b2, int a2) { endpoint[0] = clamp(r1); endpoint[1] = clamp(g1); endpoint[2] = clamp(b1); endpoint[3] = clamp(a1); endpoint[4] = clamp(r2); endpoint[5] = clamp(g2); endpoint[6] = clamp(b2); endpoint[7] = clamp(a2); } static inline void set_endpoint_blue(int endpoint[8], int r1, int g1, int b1, int a1, int r2, int g2, int b2, int a2) { endpoint[0] = (r1 + b1) >> 1; endpoint[1] = (g1 + b1) >> 1; endpoint[2] = b1; endpoint[3] = a1; endpoint[4] = (r2 + b2) >> 1; endpoint[5] = (g2 + b2) >> 1; endpoint[6] = b2; endpoint[7] = a2; } static inline void set_endpoint_blue_clamp(int endpoint[8], int r1, int g1, int b1, int a1, int r2, int g2, int b2, int a2) { endpoint[0] = clamp((r1 + b1) >> 1); endpoint[1] = clamp((g1 + b1) >> 1); endpoint[2] = clamp(b1); endpoint[3] = clamp(a1); endpoint[4] = clamp((r2 + b2) >> 1); endpoint[5] = clamp((g2 + b2) >> 1); endpoint[6] = clamp(b2); endpoint[7] = clamp(a2); } static inline uint_fast16_t clamp_hdr(const int n) { return n < 0 ? 0 : n > 0xfff ? 0xfff : n; } static inline void set_endpoint_hdr(int endpoint[8], int r1, int g1, int b1, int a1, int r2, int g2, int b2, int a2) { endpoint[0] = r1; endpoint[1] = g1; endpoint[2] = b1; endpoint[3] = a1; endpoint[4] = r2; endpoint[5] = g2; endpoint[6] = b2; endpoint[7] = a2; } static inline void set_endpoint_hdr_clamp(int endpoint[8], int r1, int g1, int b1, int a1, int r2, int g2, int b2, int a2) { endpoint[0] = clamp_hdr(r1); endpoint[1] = clamp_hdr(g1); endpoint[2] = clamp_hdr(b1); endpoint[3] = clamp_hdr(a1); endpoint[4] = clamp_hdr(r2); endpoint[5] = clamp_hdr(g2); endpoint[6] = clamp_hdr(b2); endpoint[7] = clamp_hdr(a2); } typedef uint_fast8_t (*t_select_folor_func_ptr)(int, int, int); static uint_fast8_t select_color(int v0, int v1, int weight) { return ((((v0 << 8 | v0) * (64 - weight) + (v1 << 8 | v1) * weight + 32) >> 6) * 255 + 32768) / 65536; } static uint_fast8_t select_color_hdr(int v0, int v1, int weight) { uint16_t c = ((v0 << 4) * (64 - weight) + (v1 << 4) * weight + 32) >> 6; uint16_t m = c & 0x7ff; if (m < 512) m *= 3; else if (m < 1536) m = 4 * m - 512; else m = 5 * m - 2048; float f = fp16_ieee_to_fp32_value((c >> 1 & 0x7c00) | m >> 3); return isfinite(f) ? clamp(roundf(f * 255)) : 255; } static inline uint8_t f32_to_u8(const float f) { float c = roundf(f * 255); if (c < 0) return 0; else if (c > 255) return 255; else return c; } static inline uint8_t f16ptr_to_u8(const uint8_t *ptr) { return f32_to_u8(fp16_ieee_to_fp32_value(lton16(*(uint16_t *)ptr))); } typedef struct { int bw; int bh; int width; int height; int part_num; int dual_plane; int plane_selector; int weight_range; int weight_num; int cem[4]; int cem_range; int endpoint_value_num; int endpoints[4][8]; int weights[144][2]; int partition[144]; } BlockData; typedef struct { int bits; int nonbits; } IntSeqData; void decode_intseq(const uint8_t *buf, int offset, const int a, const int b, const int count, const int reverse, IntSeqData *out) { static int mt[] = {0, 2, 4, 5, 7}; static int mq[] = {0, 3, 5}; static int TritsTable[5][256] = { {0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 1, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 1, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 1, 0, 1, 2, 2, 0, 1, 2, 2}, {0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 0, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 0, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 0, 0, 0, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1}, {0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}}; static int QuintsTable[3][128] = { {0, 1, 2, 3, 4, 0, 4, 4, 0, 1, 2, 3, 4, 1, 4, 4, 0, 1, 2, 3, 4, 2, 4, 4, 0, 1, 2, 3, 4, 3, 4, 4, 0, 1, 2, 3, 4, 0, 4, 0, 0, 1, 2, 3, 4, 1, 4, 1, 0, 1, 2, 3, 4, 2, 4, 2, 0, 1, 2, 3, 4, 3, 4, 3, 0, 1, 2, 3, 4, 0, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 0, 1, 2, 3, 4, 2, 2, 3, 0, 1, 2, 3, 4, 3, 2, 3, 0, 1, 2, 3, 4, 0, 0, 1, 0, 1, 2, 3, 4, 1, 0, 1, 0, 1, 2, 3, 4, 2, 0, 1, 0, 1, 2, 3, 4, 3, 0, 1}, {0, 0, 0, 0, 0, 4, 4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 2, 2, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3, 3, 4, 4, 4, 0, 0, 0, 0, 0, 4, 0, 4, 1, 1, 1, 1, 1, 4, 1, 4, 2, 2, 2, 2, 2, 4, 2, 4, 3, 3, 3, 3, 3, 4, 3, 4, 0, 0, 0, 0, 0, 4, 0, 0, 1, 1, 1, 1, 1, 4, 1, 1, 2, 2, 2, 2, 2, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3, 0, 0, 0, 0, 0, 4, 0, 0, 1, 1, 1, 1, 1, 4, 1, 1, 2, 2, 2, 2, 2, 4, 2, 2, 3, 3, 3, 3, 3, 4, 3, 3}, {0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 4, 0, 0, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 3, 4, 1, 1, 1, 1, 1, 1, 4, 4, 1, 1, 1, 1, 1, 1, 4, 4, 1, 1, 1, 1, 1, 1, 4, 4, 1, 1, 1, 1, 1, 1, 4, 4, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4}}; if (count <= 0) return; int n = 0; if (a == 3) { int mask = (1 << b) - 1; int block_count = (count + 4) / 5; int last_block_count = (count + 4) % 5 + 1; int block_size = 8 + 5 * b; int last_block_size = (block_size * last_block_count + 4) / 5; if (reverse) { for (int i = 0, p = offset; i < block_count; i++, p -= block_size) { int now_size = (i < block_count - 1) ? block_size : last_block_size; uint_fast64_t d = bit_reverse_u64(getbits64(buf, p - now_size, now_size), now_size); int x = (d >> b & 3) | (d >> b * 2 & 0xc) | (d >> b * 3 & 0x10) | (d >> b * 4 & 0x60) | (d >> b * 5 & 0x80); for (int j = 0; j < 5 && n < count; j++, n++) out[n] = { static_cast<int>(d >> (mt[j] + b * j) & mask), TritsTable[j][x]}; } } else { for (int i = 0, p = offset; i < block_count; i++, p += block_size) { uint_fast64_t d = getbits64(buf, p, (i < block_count - 1) ? block_size : last_block_size); int x = (d >> b & 3) | (d >> b * 2 & 0xc) | (d >> b * 3 & 0x10) | (d >> b * 4 & 0x60) | (d >> b * 5 & 0x80); for (int j = 0; j < 5 && n < count; j++, n++) out[n] = { static_cast<int>(d >> (mt[j] + b * j) & mask), TritsTable[j][x]}; } } } else if (a == 5) { int mask = (1 << b) - 1; int block_count = (count + 2) / 3; int last_block_count = (count + 2) % 3 + 1; int block_size = 7 + 3 * b; int last_block_size = (block_size * last_block_count + 2) / 3; if (reverse) { for (int i = 0, p = offset; i < block_count; i++, p -= block_size) { int now_size = (i < block_count - 1) ? block_size : last_block_size; uint_fast64_t d = bit_reverse_u64(getbits64(buf, p - now_size, now_size), now_size); int x = (d >> b & 7) | (d >> b * 2 & 0x18) | (d >> b * 3 & 0x60); for (int j = 0; j < 3 && n < count; j++, n++) out[n] = { static_cast<int>(d >> (mq[j] + b * j) & mask), QuintsTable[j][x]}; } } else { for (int i = 0, p = offset; i < block_count; i++, p += block_size) { uint_fast64_t d = getbits64(buf, p, (i < block_count - 1) ? block_size : last_block_size); int x = (d >> b & 7) | (d >> b * 2 & 0x18) | (d >> b * 3 & 0x60); for (int j = 0; j < 3 && n < count; j++, n++) out[n] = { static_cast<int>(d >> (mq[j] + b * j) & mask), QuintsTable[j][x]}; } } } else { if (reverse) for (int p = offset - b; n < count; n++, p -= b) out[n] = {bit_reverse_u8(getbits(buf, p, b), b), 0}; else for (int p = offset; n < count; n++, p += b) out[n] = {getbits(buf, p, b), 0}; } } void decode_block_params(const uint8_t *buf, BlockData *block_data) { block_data->dual_plane = !!(buf[1] & 4); block_data->weight_range = (buf[0] >> 4 & 1) | (buf[1] << 2 & 8); if (buf[0] & 3) { block_data->weight_range |= buf[0] << 1 & 6; switch (buf[0] & 0xc) { case 0: block_data->width = (u8ptr_to_u16(buf) >> 7 & 3) + 4; block_data->height = (buf[0] >> 5 & 3) + 2; break; case 4: block_data->width = (u8ptr_to_u16(buf) >> 7 & 3) + 8; block_data->height = (buf[0] >> 5 & 3) + 2; break; case 8: block_data->width = (buf[0] >> 5 & 3) + 2; block_data->height = (u8ptr_to_u16(buf) >> 7 & 3) + 8; break; case 12: if (buf[1] & 1) { block_data->width = (buf[0] >> 7 & 1) + 2; block_data->height = (buf[0] >> 5 & 3) + 2; } else { block_data->width = (buf[0] >> 5 & 3) + 2; block_data->height = (buf[0] >> 7 & 1) + 6; } break; } } else { block_data->weight_range |= buf[0] >> 1 & 6; switch (u8ptr_to_u16(buf) & 0x180) { case 0: block_data->width = 12; block_data->height = (buf[0] >> 5 & 3) + 2; break; case 0x80: block_data->width = (buf[0] >> 5 & 3) + 2; block_data->height = 12; break; case 0x100: block_data->width = (buf[0] >> 5 & 3) + 6; block_data->height = (buf[1] >> 1 & 3) + 6; block_data->dual_plane = 0; block_data->weight_range &= 7; break; case 0x180: block_data->width = (buf[0] & 0x20) ? 10 : 6; block_data->height = (buf[0] & 0x20) ? 6 : 10; break; } } block_data->part_num = (buf[1] >> 3 & 3) + 1; block_data->weight_num = block_data->width * block_data->height; if (block_data->dual_plane) block_data->weight_num *= 2; int weight_bits, config_bits, cem_base = 0; switch (WeightPrecTableA[block_data->weight_range]) { case 3: weight_bits = block_data->weight_num * WeightPrecTableB[block_data->weight_range] + (block_data->weight_num * 8 + 4) / 5; break; case 5: weight_bits = block_data->weight_num * WeightPrecTableB[block_data->weight_range] + (block_data->weight_num * 7 + 2) / 3; break; default: weight_bits = block_data->weight_num * WeightPrecTableB[block_data->weight_range]; } if (block_data->part_num == 1) { block_data->cem[0] = u8ptr_to_u16(buf + 1) >> 5 & 0xf; config_bits = 17; } else { cem_base = u8ptr_to_u16(buf + 2) >> 7 & 3; if (cem_base == 0) { int cem = buf[3] >> 1 & 0xf; for (int i = 0; i < block_data->part_num; i++) block_data->cem[i] = cem; config_bits = 29; } else { for (int i = 0; i < block_data->part_num; i++) block_data->cem[i] = ((buf[3] >> (i + 1) & 1) + cem_base - 1) << 2; switch (block_data->part_num) { case 2: block_data->cem[0] |= buf[3] >> 3 & 3; block_data->cem[1] |= getbits(buf, 126 - weight_bits, 2); break; case 3: block_data->cem[0] |= buf[3] >> 4 & 1; block_data->cem[0] |= getbits(buf, 122 - weight_bits, 2) & 2; block_data->cem[1] |= getbits(buf, 124 - weight_bits, 2); block_data->cem[2] |= getbits(buf, 126 - weight_bits, 2); break; case 4: for (int i = 0; i < 4; i++) block_data->cem[i] |= getbits(buf, 120 + i * 2 - weight_bits, 2); break; } config_bits = 25 + block_data->part_num * 3; } } if (block_data->dual_plane) { config_bits += 2; block_data->plane_selector = getbits(buf, cem_base ? 130 - weight_bits - block_data->part_num * 3 : 126 - weight_bits, 2); } int remain_bits = 128 - config_bits - weight_bits; block_data->endpoint_value_num = 0; for (int i = 0; i < block_data->part_num; i++) block_data->endpoint_value_num += (block_data->cem[i] >> 1 & 6) + 2; for (int i = 0, endpoint_bits; i < (int)(sizeof(CemTableA) / sizeof(int)); i++) { switch (CemTableA[i]) { case 3: endpoint_bits = block_data->endpoint_value_num * CemTableB[i] + (block_data->endpoint_value_num * 8 + 4) / 5; break; case 5: endpoint_bits = block_data->endpoint_value_num * CemTableB[i] + (block_data->endpoint_value_num * 7 + 2) / 3; break; default: endpoint_bits = block_data->endpoint_value_num * CemTableB[i]; } if (endpoint_bits <= remain_bits) { block_data->cem_range = i; break; } } } void decode_endpoints_hdr7(int *endpoints, int *v) { int modeval = (v[2] >> 4 & 0x8) | (v[1] >> 5 & 0x4) | (v[0] >> 6); int major_component, mode; if ((modeval & 0xc) != 0xc) { major_component = modeval >> 2; mode = modeval & 3; } else if (modeval != 0xf) { major_component = modeval & 3; mode = 4; } else { major_component = 0; mode = 5; } int c[] = {v[0] & 0x3f, v[1] & 0x1f, v[2] & 0x1f, v[3] & 0x1f}; switch (mode) { case 0: c[3] |= v[3] & 0x60; c[0] |= v[3] >> 1 & 0x40; c[0] |= v[2] << 1 & 0x80; c[0] |= v[1] << 3 & 0x300; c[0] |= v[2] << 5 & 0x400; c[0] <<= 1; c[1] <<= 1; c[2] <<= 1; c[3] <<= 1; break; case 1: c[1] |= v[1] & 0x20; c[2] |= v[2] & 0x20; c[0] |= v[3] >> 1 & 0x40; c[0] |= v[2] << 1 & 0x80; c[0] |= v[1] << 2 & 0x100; c[0] |= v[3] << 4 & 0x600; c[0] <<= 1; c[1] <<= 1; c[2] <<= 1; c[3] <<= 1; break; case 2: c[3] |= v[3] & 0xe0; c[0] |= v[2] << 1 & 0xc0; c[0] |= v[1] << 3 & 0x300; c[0] <<= 2; c[1] <<= 2; c[2] <<= 2; c[3] <<= 2; break; case 3: c[1] |= v[1] & 0x20; c[2] |= v[2] & 0x20; c[3] |= v[3] & 0x60; c[0] |= v[3] >> 1 & 0x40; c[0] |= v[2] << 1 & 0x80; c[0] |= v[1] << 2 & 0x100; c[0] <<= 3; c[1] <<= 3; c[2] <<= 3; c[3] <<= 3; break; case 4: c[1] |= v[1] & 0x60; c[2] |= v[2] & 0x60; c[3] |= v[3] & 0x20; c[0] |= v[3] >> 1 & 0x40; c[0] |= v[3] << 1 & 0x80; c[0] <<= 4; c[1] <<= 4; c[2] <<= 4; c[3] <<= 4; break; case 5: c[1] |= v[1] & 0x60; c[2] |= v[2] & 0x60; c[3] |= v[3] & 0x60; c[0] |= v[3] >> 1 & 0x40; c[0] <<= 5; c[1] <<= 5; c[2] <<= 5; c[3] <<= 5; break; } if (mode != 5) { c[1] = c[0] - c[1]; c[2] = c[0] - c[2]; } if (major_component == 1) set_endpoint_hdr_clamp(endpoints, c[1] - c[3], c[0] - c[3], c[2] - c[3], 0x780, c[1], c[0], c[2], 0x780); else if (major_component == 2) set_endpoint_hdr_clamp(endpoints, c[2] - c[3], c[1] - c[3], c[0] - c[3], 0x780, c[2], c[1], c[0], 0x780); else set_endpoint_hdr_clamp(endpoints, c[0] - c[3], c[1] - c[3], c[2] - c[3], 0x780, c[0], c[1], c[2], 0x780); } void decode_endpoints_hdr11(int *endpoints, int *v, int alpha1, int alpha2) { int major_component = (v[4] >> 7) | (v[5] >> 6 & 2); if (major_component == 3) { set_endpoint_hdr(endpoints, v[0] << 4, v[2] << 4, v[4] << 5 & 0xfe0, alpha1, v[1] << 4, v[3] << 4, v[5] << 5 & 0xfe0, alpha2); return; } int mode = (v[1] >> 7) | (v[2] >> 6 & 2) | (v[3] >> 5 & 4); int va = v[0] | (v[1] << 2 & 0x100); int vb0 = v[2] & 0x3f, vb1 = v[3] & 0x3f; int vc = v[1] & 0x3f; int16_t vd0, vd1; switch (mode) { case 0: case 2: vd0 = v[4] & 0x7f; if (vd0 & 0x40) vd0 |= 0xff80; vd1 = v[5] & 0x7f; if (vd1 & 0x40) vd1 |= 0xff80; break; case 1: case 3: case 5: case 7: vd0 = v[4] & 0x3f; if (vd0 & 0x20) vd0 |= 0xffc0; vd1 = v[5] & 0x3f; if (vd1 & 0x20) vd1 |= 0xffc0; break; default: vd0 = v[4] & 0x1f; if (vd0 & 0x10) vd0 |= 0xffe0; vd1 = v[5] & 0x1f; if (vd1 & 0x10) vd1 |= 0xffe0; break; } switch (mode) { case 0: vb0 |= v[2] & 0x40; vb1 |= v[3] & 0x40; break; case 1: vb0 |= v[2] & 0x40; vb1 |= v[3] & 0x40; vb0 |= v[4] << 1 & 0x80; vb1 |= v[5] << 1 & 0x80; break; case 2: va |= v[2] << 3 & 0x200; vc |= v[3] & 0x40; break; case 3: va |= v[4] << 3 & 0x200; vc |= v[5] & 0x40; vb0 |= v[2] & 0x40; vb1 |= v[3] & 0x40; break; case 4: va |= v[4] << 4 & 0x200; va |= v[5] << 5 & 0x400; vb0 |= v[2] & 0x40; vb1 |= v[3] & 0x40; vb0 |= v[4] << 1 & 0x80; vb1 |= v[5] << 1 & 0x80; break; case 5: va |= v[2] << 3 & 0x200; va |= v[3] << 4 & 0x400; vc |= v[5] & 0x40; vc |= v[4] << 1 & 0x80; break; case 6: va |= v[4] << 4 & 0x200; va |= v[5] << 5 & 0x400; va |= v[4] << 5 & 0x800; vc |= v[5] & 0x40; vb0 |= v[2] & 0x40; vb1 |= v[3] & 0x40; break; case 7: va |= v[2] << 3 & 0x200; va |= v[3] << 4 & 0x400; va |= v[4] << 5 & 0x800; vc |= v[5] & 0x40; break; } int shamt = (mode >> 1) ^ 3; va <<= shamt; vb0 <<= shamt; vb1 <<= shamt; vc <<= shamt; int mult = 1 << shamt; vd0 *= mult; vd1 *= mult; if (major_component == 1) set_endpoint_hdr_clamp(endpoints, va - vb0 - vc - vd0, va - vc, va - vb1 - vc - vd1, alpha1, va - vb0, va, va - vb1, alpha2); else if (major_component == 2) set_endpoint_hdr_clamp(endpoints, va - vb1 - vc - vd1, va - vb0 - vc - vd0, va - vc, alpha1, va - vb1, va - vb0, va, alpha2); else set_endpoint_hdr_clamp(endpoints, va - vc, va - vb0 - vc - vd0, va - vb1 - vc - vd1, alpha1, va, va - vb0, va - vb1, alpha2); } void decode_endpoints(const uint8_t *buf, BlockData *data) { static const int TritsTable[] = {0, 204, 93, 44, 22, 11, 5}; static const int QuintsTable[] = {0, 113, 54, 26, 13, 6}; IntSeqData seq[32]; int ev[32]; decode_intseq(buf, data->part_num == 1 ? 17 : 29, CemTableA[data->cem_range], CemTableB[data->cem_range], data->endpoint_value_num, 0, seq); switch (CemTableA[data->cem_range]) { case 3: for (int i = 0, b, c = TritsTable[CemTableB[data->cem_range]]; i < data->endpoint_value_num; i++) { int a = (seq[i].bits & 1) * 0x1ff; int x = seq[i].bits >> 1; switch (CemTableB[data->cem_range]) { case 1: b = 0; break; case 2: b = 0b100010110 * x; break; case 3: b = x << 7 | x << 2 | x; break; case 4: b = x << 6 | x; break; case 5: b = x << 5 | x >> 2; break; case 6: b = x << 4 | x >> 4; break; } ev[i] = (a & 0x80) | ((seq[i].nonbits * c + b) ^ a) >> 2; } break; case 5: for (int i = 0, b, c = QuintsTable[CemTableB[data->cem_range]]; i < data->endpoint_value_num; i++) { int a = (seq[i].bits & 1) * 0x1ff; int x = seq[i].bits >> 1; switch (CemTableB[data->cem_range]) { case 1: b = 0; break; case 2: b = 0b100001100 * x; break; case 3: b = x << 7 | x << 1 | x >> 1; break; case 4: b = x << 6 | x >> 1; break; case 5: b = x << 5 | x >> 3; break; } ev[i] = (a & 0x80) | ((seq[i].nonbits * c + b) ^ a) >> 2; } break; default: switch (CemTableB[data->cem_range]) { case 1: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits * 0xff; break; case 2: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits * 0x55; break; case 3: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits << 5 | seq[i].bits << 2 | seq[i].bits >> 1; break; case 4: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits << 4 | seq[i].bits; break; case 5: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits << 3 | seq[i].bits >> 2; break; case 6: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits << 2 | seq[i].bits >> 4; break; case 7: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits << 1 | seq[i].bits >> 6; break; case 8: for (int i = 0; i < data->endpoint_value_num; i++) ev[i] = seq[i].bits; break; } } int *v = ev; for (int cem = 0; cem < data->part_num; v += (data->cem[cem] / 4 + 1) * 2, cem++) { switch (data->cem[cem]) { case 0: set_endpoint(data->endpoints[cem], v[0], v[0], v[0], 255, v[1], v[1], v[1], 255); break; case 1: { int l0 = (v[0] >> 2) | (v[1] & 0xc0); int l1 = clamp(l0 + (v[1] & 0x3f)); set_endpoint(data->endpoints[cem], l0, l0, l0, 255, l1, l1, l1, 255); } break; case 2: { int y0, y1; if (v[0] <= v[1]) { y0 = v[0] << 4; y1 = v[1] << 4; } else { y0 = (v[1] << 4) + 8; y1 = (v[0] << 4) - 8; } set_endpoint_hdr(data->endpoints[cem], y0, y0, y0, 0x780, y1, y1, y1, 0x780); } break; case 3: { int y0, d; if (v[0] & 0x80) { y0 = (v[1] & 0xe0) << 4 | (v[0] & 0x7f) << 2; d = (v[1] & 0x1f) << 2; } else { y0 = (v[1] & 0xf0) << 4 | (v[0] & 0x7f) << 1; d = (v[1] & 0x0f) << 1; } int y1 = clamp_hdr(y0 + d); set_endpoint_hdr(data->endpoints[cem], y0, y0, y0, 0x780, y1, y1, y1, 0x780); } break; case 4: set_endpoint(data->endpoints[cem], v[0], v[0], v[0], v[2], v[1], v[1], v[1], v[3]); break; case 5: bit_transfer_signed(&v[1], &v[0]); bit_transfer_signed(&v[3], &v[2]); v[1] += v[0]; set_endpoint_clamp(data->endpoints[cem], v[0], v[0], v[0], v[2], v[1], v[1], v[1], v[2] + v[3]); break; case 6: set_endpoint(data->endpoints[cem], v[0] * v[3] >> 8, v[1] * v[3] >> 8, v[2] * v[3] >> 8, 255, v[0], v[1], v[2], 255); break; case 7: decode_endpoints_hdr7(data->endpoints[cem], v); break; case 8: if (v[0] + v[2] + v[4] <= v[1] + v[3] + v[5]) set_endpoint(data->endpoints[cem], v[0], v[2], v[4], 255, v[1], v[3], v[5], 255); else set_endpoint_blue(data->endpoints[cem], v[1], v[3], v[5], 255, v[0], v[2], v[4], 255); break; case 9: bit_transfer_signed(&v[1], &v[0]); bit_transfer_signed(&v[3], &v[2]); bit_transfer_signed(&v[5], &v[4]); if (v[1] + v[3] + v[5] >= 0) set_endpoint_clamp(data->endpoints[cem], v[0], v[2], v[4], 255, v[0] + v[1], v[2] + v[3], v[4] + v[5], 255); else set_endpoint_blue_clamp(data->endpoints[cem], v[0] + v[1], v[2] + v[3], v[4] + v[5], 255, v[0], v[2], v[4], 255); break; case 10: set_endpoint(data->endpoints[cem], v[0] * v[3] >> 8, v[1] * v[3] >> 8, v[2] * v[3] >> 8, v[4], v[0], v[1], v[2], v[5]); break; case 11: decode_endpoints_hdr11(data->endpoints[cem], v, 0x780, 0x780); break; case 12: if (v[0] + v[2] + v[4] <= v[1] + v[3] + v[5]) set_endpoint(data->endpoints[cem], v[0], v[2], v[4], v[6], v[1], v[3], v[5], v[7]); else set_endpoint_blue(data->endpoints[cem], v[1], v[3], v[5], v[7], v[0], v[2], v[4], v[6]); break; case 13: bit_transfer_signed(&v[1], &v[0]); bit_transfer_signed(&v[3], &v[2]); bit_transfer_signed(&v[5], &v[4]); bit_transfer_signed(&v[7], &v[6]); if (v[1] + v[3] + v[5] >= 0) set_endpoint_clamp(data->endpoints[cem], v[0], v[2], v[4], v[6], v[0] + v[1], v[2] + v[3], v[4] + v[5], v[6] + v[7]); else set_endpoint_blue_clamp(data->endpoints[cem], v[0] + v[1], v[2] + v[3], v[4] + v[5], v[6] + v[7], v[0], v[2], v[4], v[6]); break; case 14: decode_endpoints_hdr11(data->endpoints[cem], v, v[6], v[7]); break; case 15: { int mode = ((v[6] >> 7) & 1) | ((v[7] >> 6) & 2); v[6] &= 0x7f; v[7] &= 0x7f; if (mode == 3) { decode_endpoints_hdr11(data->endpoints[cem], v, v[6] << 5, v[7] << 5); } else { v[6] |= (v[7] << (mode + 1)) & 0x780; v[7] = ((v[7] & (0x3f >> mode)) ^ (0x20 >> mode)) - (0x20 >> mode); v[6] <<= 4 - mode; v[7] <<= 4 - mode; decode_endpoints_hdr11(data->endpoints[cem], v, v[6], clamp_hdr(v[6] + v[7])); } } break; //default: // rb_raise(rb_eStandardError, "Unsupported ASTC format"); } } } void decode_weights(const uint8_t *buf, BlockData *data) { IntSeqData seq[128]; int wv[128] = {}; decode_intseq(buf, 128, WeightPrecTableA[data->weight_range], WeightPrecTableB[data->weight_range], data->weight_num, 1, seq); if (WeightPrecTableA[data->weight_range] == 0) { switch (WeightPrecTableB[data->weight_range]) { case 1: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].bits ? 63 : 0; break; case 2: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].bits << 4 | seq[i].bits << 2 | seq[i].bits; break; case 3: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].bits << 3 | seq[i].bits; break; case 4: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].bits << 2 | seq[i].bits >> 2; break; case 5: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].bits << 1 | seq[i].bits >> 4; break; } for (int i = 0; i < data->weight_num; i++) if (wv[i] > 32) ++wv[i]; } else if (WeightPrecTableB[data->weight_range] == 0) { int s = WeightPrecTableA[data->weight_range] == 3 ? 32 : 16; for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].nonbits * s; } else { if (WeightPrecTableA[data->weight_range] == 3) { switch (WeightPrecTableB[data->weight_range]) { case 1: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].nonbits * 50; break; case 2: for (int i = 0; i < data->weight_num; i++) { wv[i] = seq[i].nonbits * 23; if (seq[i].bits & 2) wv[i] += 0b1000101; } break; case 3: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].nonbits * 11 + ((seq[i].bits << 4 | seq[i].bits >> 1) & 0b1100011); break; } } else if (WeightPrecTableA[data->weight_range] == 5) { switch (WeightPrecTableB[data->weight_range]) { case 1: for (int i = 0; i < data->weight_num; i++) wv[i] = seq[i].nonbits * 28; break; case 2: for (int i = 0; i < data->weight_num; i++) { wv[i] = seq[i].nonbits * 13; if (seq[i].bits & 2) wv[i] += 0b1000010; } break; } } for (int i = 0; i < data->weight_num; i++) { int a = (seq[i].bits & 1) * 0x7f; wv[i] = (a & 0x20) | ((wv[i] ^ a) >> 2); if (wv[i] > 32) ++wv[i]; } } int ds = (1024 + data->bw / 2) / (data->bw - 1); int dt = (1024 + data->bh / 2) / (data->bh - 1); int pn = data->dual_plane ? 2 : 1; for (int t = 0, i = 0; t < data->bh; t++) { for (int s = 0; s < data->bw; s++, i++) { int gs = (ds * s * (data->width - 1) + 32) >> 6; int gt = (dt * t * (data->height - 1) + 32) >> 6; int fs = gs & 0xf; int ft = gt & 0xf; int v = (gs >> 4) + (gt >> 4) * data->width; int w11 = (fs * ft + 8) >> 4; int w10 = ft - w11; int w01 = fs - w11; int w00 = 16 - fs - ft + w11; for (int p = 0; p < pn; p++) { int p00 = wv[v * pn + p]; int p01 = wv[(v + 1) * pn + p]; int p10 = wv[(v + data->width) * pn + p]; int p11 = wv[(v + data->width + 1) * pn + p]; data->weights[i][p] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4; } } } } void select_partition(const uint8_t *buf, BlockData *data) { int small_block = data->bw * data->bh < 31; int seed = (*(int *)buf >> 13 & 0x3ff) | (data->part_num - 1) << 10; uint32_t rnum = seed; rnum ^= rnum >> 15; rnum -= rnum << 17; rnum += rnum << 7; rnum += rnum << 4; rnum ^= rnum >> 5; rnum += rnum << 16; rnum ^= rnum >> 7; rnum ^= rnum >> 3; rnum ^= rnum << 6; rnum ^= rnum >> 17; int seeds[8]; for (int i = 0; i < 8; i++) { seeds[i] = (rnum >> (i * 4)) & 0xF; seeds[i] *= seeds[i]; } int sh[2] = {seed & 2 ? 4 : 5, data->part_num == 3 ? 6 : 5}; if (seed & 1) for (int i = 0; i < 8; i++) seeds[i] >>= sh[i % 2]; else for (int i = 0; i < 8; i++) seeds[i] >>= sh[1 - i % 2]; if (small_block) { for (int t = 0, i = 0; t < data->bh; t++) { for (int s = 0; s < data->bw; s++, i++) { int x = s << 1; int y = t << 1; int a = (seeds[0] * x + seeds[1] * y + (rnum >> 14)) & 0x3f; int b = (seeds[2] * x + seeds[3] * y + (rnum >> 10)) & 0x3f; int c = data->part_num < 3 ? 0 : (seeds[4] * x + seeds[5] * y + (rnum >> 6)) & 0x3f; int d = data->part_num < 4 ? 0 : (seeds[6] * x + seeds[7] * y + (rnum >> 2)) & 0x3f; data->partition[i] = (a >= b && a >= c && a >= d) ? 0 : (b >= c && b >= d) ? 1 : (c >= d) ? 2 : 3; } } } else { for (int y = 0, i = 0; y < data->bh; y++) { for (int x = 0; x < data->bw; x++, i++) { int a = (seeds[0] * x + seeds[1] * y + (rnum >> 14)) & 0x3f; int b = (seeds[2] * x + seeds[3] * y + (rnum >> 10)) & 0x3f; int c = data->part_num < 3 ? 0 : (seeds[4] * x + seeds[5] * y + (rnum >> 6)) & 0x3f; int d = data->part_num < 4 ? 0 : (seeds[6] * x + seeds[7] * y + (rnum >> 2)) & 0x3f; data->partition[i] = (a >= b && a >= c && a >= d) ? 0 : (b >= c && b >= d) ? 1 : (c >= d) ? 2 : 3; } } } } void applicate_color(const BlockData *data, uint32_t *outbuf) { static const t_select_folor_func_ptr FuncTableC[] = { select_color, select_color, select_color_hdr, select_color_hdr, select_color, select_color, select_color, select_color_hdr, select_color, select_color, select_color, select_color_hdr, select_color, select_color, select_color_hdr, select_color_hdr}; static const t_select_folor_func_ptr FuncTableA[] = { select_color, select_color, select_color_hdr, select_color_hdr, select_color, select_color, select_color, select_color_hdr, select_color, select_color, select_color, select_color_hdr, select_color, select_color, select_color, select_color_hdr}; if (data->dual_plane) { int ps[] = {0, 0, 0, 0}; ps[data->plane_selector] = 1; if (data->part_num > 1) { for (int i = 0; i < data->bw * data->bh; i++) { int p = data->partition[i]; uint_fast8_t r = FuncTableC[data->cem[p]](data->endpoints[p][0], data->endpoints[p][4], data->weights[i][ps[0]]); uint_fast8_t g = FuncTableC[data->cem[p]](data->endpoints[p][1], data->endpoints[p][5], data->weights[i][ps[1]]); uint_fast8_t b = FuncTableC[data->cem[p]](data->endpoints[p][2], data->endpoints[p][6], data->weights[i][ps[2]]); uint_fast8_t a = FuncTableA[data->cem[p]](data->endpoints[p][3], data->endpoints[p][7], data->weights[i][ps[3]]); outbuf[i] = color(r, g, b, a); } } else { for (int i = 0; i < data->bw * data->bh; i++) { uint_fast8_t r = FuncTableC[data->cem[0]](data->endpoints[0][0], data->endpoints[0][4], data->weights[i][ps[0]]); uint_fast8_t g = FuncTableC[data->cem[0]](data->endpoints[0][1], data->endpoints[0][5], data->weights[i][ps[1]]); uint_fast8_t b = FuncTableC[data->cem[0]](data->endpoints[0][2], data->endpoints[0][6], data->weights[i][ps[2]]); uint_fast8_t a = FuncTableA[data->cem[0]](data->endpoints[0][3], data->endpoints[0][7], data->weights[i][ps[3]]); outbuf[i] = color(r, g, b, a); } } } else if (data->part_num > 1) { for (int i = 0; i < data->bw * data->bh; i++) { int p = data->partition[i]; uint_fast8_t r = FuncTableC[data->cem[p]](data->endpoints[p][0], data->endpoints[p][4], data->weights[i][0]); uint_fast8_t g = FuncTableC[data->cem[p]](data->endpoints[p][1], data->endpoints[p][5], data->weights[i][0]); uint_fast8_t b = FuncTableC[data->cem[p]](data->endpoints[p][2], data->endpoints[p][6], data->weights[i][0]); uint_fast8_t a = FuncTableA[data->cem[p]](data->endpoints[p][3], data->endpoints[p][7], data->weights[i][0]); outbuf[i] = color(r, g, b, a); } } else { for (int i = 0; i < data->bw * data->bh; i++) { uint_fast8_t r = FuncTableC[data->cem[0]](data->endpoints[0][0], data->endpoints[0][4], data->weights[i][0]); uint_fast8_t g = FuncTableC[data->cem[0]](data->endpoints[0][1], data->endpoints[0][5], data->weights[i][0]); uint_fast8_t b = FuncTableC[data->cem[0]](data->endpoints[0][2], data->endpoints[0][6], data->weights[i][0]); uint_fast8_t a = FuncTableA[data->cem[0]](data->endpoints[0][3], data->endpoints[0][7], data->weights[i][0]); outbuf[i] = color(r, g, b, a); } } } void decode_block(const uint8_t *buf, const int bw, const int bh, uint32_t *outbuf) { if (buf[0] == 0xfc && (buf[1] & 1) == 1) { uint_fast32_t c; if (buf[1] & 2) c = color(f16ptr_to_u8(buf + 8), f16ptr_to_u8(buf + 10), f16ptr_to_u8(buf + 12), f16ptr_to_u8(buf + 14)); else c = color(buf[9], buf[11], buf[13], buf[15]); for (int i = 0; i < bw * bh; i++) outbuf[i] = c; } else if (((buf[0] & 0xc3) == 0xc0 && (buf[1] & 1) == 1) || (buf[0] & 0xf) == 0) { uint_fast32_t c = color(255, 0, 255, 255); for (int i = 0; i < bw * bh; i++) outbuf[i] = c; } else { BlockData block_data; block_data.bw = bw; block_data.bh = bh; decode_block_params(buf, &block_data); decode_endpoints(buf, &block_data); decode_weights(buf, &block_data); if (block_data.part_num > 1) select_partition(buf, &block_data); applicate_color(&block_data, outbuf); } } int decode_astc(const uint8_t *data, const long w, const long h, const int bw, const int bh, uint32_t *image) { const long num_blocks_x = (w + bw - 1) / bw; const long num_blocks_y = (h + bh - 1) / bh; uint32_t buffer[144]; const uint8_t *d = data; for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, d += 16) { decode_block(d, bw, bh, buffer); copy_block_buffer(bx, by, w, h, bw, bh, buffer, image); } } return 1; }
AssetStudio/Texture2DDecoderNative/astc.cpp/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/astc.cpp", "repo_id": "AssetStudio", "token_count": 27816 }
76
#include "etc.h" #include <stdint.h> #include <string.h> #include "color.h" const uint_fast8_t WriteOrderTable[16] = {0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15}; const uint_fast8_t WriteOrderTableRev[16] = {15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0}; const uint_fast8_t Etc1ModifierTable[8][2] = {{2, 8}, {5, 17}, {9, 29}, {13, 42}, {18, 60}, {24, 80}, {33, 106}, {47, 183}}; const uint_fast8_t Etc2aModifierTable[2][8][2] = { {{0, 8}, {0, 17}, {0, 29}, {0, 42}, {0, 60}, {0, 80}, {0, 106}, {0, 183}}, {{2, 8}, {5, 17}, {9, 29}, {13, 42}, {18, 60}, {24, 80}, {33, 106}, {47, 183}}}; const uint_fast8_t Etc1SubblockTable[2][16] = {{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1}}; const uint_fast8_t Etc2DistanceTable[8] = {3, 6, 11, 16, 23, 32, 41, 64}; const int_fast8_t Etc2AlphaModTable[16][8] = { {-3, -6, -9, -15, 2, 5, 8, 14}, {-3, -7, -10, -13, 2, 6, 9, 12}, {-2, -5, -8, -13, 1, 4, 7, 12}, {-2, -4, -6, -13, 1, 3, 5, 12}, {-3, -6, -8, -12, 2, 5, 7, 11}, {-3, -7, -9, -11, 2, 6, 8, 10}, {-4, -7, -8, -11, 3, 6, 7, 10}, {-3, -5, -8, -11, 2, 4, 7, 10}, {-2, -6, -8, -10, 1, 5, 7, 9}, {-2, -5, -8, -10, 1, 4, 7, 9}, {-2, -4, -8, -10, 1, 3, 7, 9}, {-2, -5, -7, -10, 1, 4, 6, 9}, {-3, -4, -7, -10, 2, 3, 6, 9}, {-1, -2, -3, -10, 0, 1, 2, 9}, {-4, -6, -8, -9, 3, 5, 7, 8}, {-3, -5, -7, -9, 2, 4, 6, 8}}; static inline uint_fast8_t clamp(const int n) { return n < 0 ? 0 : n > 255 ? 255 : n; } static inline uint32_t applicate_color(uint_fast8_t c[3], int_fast16_t m) { return color(clamp(c[0] + m), clamp(c[1] + m), clamp(c[2] + m), 255); } static inline uint32_t applicate_color_alpha(uint_fast8_t c[3], int_fast16_t m, int transparent) { return color(clamp(c[0] + m), clamp(c[1] + m), clamp(c[2] + m), transparent ? 0 : 255); } static inline uint32_t applicate_color_raw(uint_fast8_t c[3]) { return color(c[0], c[1], c[2], 255); } static void decode_etc1_block(const uint8_t *data, uint32_t *outbuf) { const uint_fast8_t code[2] = {data[3] >> 5, data[3] >> 2 & 7}; // Table codewords const uint_fast8_t *table = Etc1SubblockTable[data[3] & 1]; uint_fast8_t c[2][3]; if (data[3] & 2) { // diff bit == 1 c[0][0] = data[0] & 0xf8; c[0][1] = data[1] & 0xf8; c[0][2] = data[2] & 0xf8; c[1][0] = c[0][0] + (data[0] << 3 & 0x18) - (data[0] << 3 & 0x20); c[1][1] = c[0][1] + (data[1] << 3 & 0x18) - (data[1] << 3 & 0x20); c[1][2] = c[0][2] + (data[2] << 3 & 0x18) - (data[2] << 3 & 0x20); c[0][0] |= c[0][0] >> 5; c[0][1] |= c[0][1] >> 5; c[0][2] |= c[0][2] >> 5; c[1][0] |= c[1][0] >> 5; c[1][1] |= c[1][1] >> 5; c[1][2] |= c[1][2] >> 5; } else { // diff bit == 0 c[0][0] = (data[0] & 0xf0) | data[0] >> 4; c[1][0] = (data[0] & 0x0f) | data[0] << 4; c[0][1] = (data[1] & 0xf0) | data[1] >> 4; c[1][1] = (data[1] & 0x0f) | data[1] << 4; c[0][2] = (data[2] & 0xf0) | data[2] >> 4; c[1][2] = (data[2] & 0x0f) | data[2] << 4; } uint_fast16_t j = data[6] << 8 | data[7]; // less significant pixel index bits uint_fast16_t k = data[4] << 8 | data[5]; // more significant pixel index bits for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) { uint_fast8_t s = table[i]; uint_fast8_t m = Etc1ModifierTable[code[s]][j & 1]; outbuf[WriteOrderTable[i]] = applicate_color(c[s], k & 1 ? -m : m); } } static void decode_etc2_block(const uint8_t *data, uint32_t *outbuf) { uint_fast16_t j = data[6] << 8 | data[7]; // 15 -> 0 uint_fast32_t k = data[4] << 8 | data[5]; // 31 -> 16 uint_fast8_t c[3][3] = {}; if (data[3] & 2) { // diff bit == 1 uint_fast8_t r = data[0] & 0xf8; int_fast16_t dr = (data[0] << 3 & 0x18) - (data[0] << 3 & 0x20); uint_fast8_t g = data[1] & 0xf8; int_fast16_t dg = (data[1] << 3 & 0x18) - (data[1] << 3 & 0x20); uint_fast8_t b = data[2] & 0xf8; int_fast16_t db = (data[2] << 3 & 0x18) - (data[2] << 3 & 0x20); if (r + dr < 0 || r + dr > 255) { // T c[0][0] = (data[0] << 3 & 0xc0) | (data[0] << 4 & 0x30) | (data[0] >> 1 & 0xc) | (data[0] & 3); c[0][1] = (data[1] & 0xf0) | data[1] >> 4; c[0][2] = (data[1] & 0x0f) | data[1] << 4; c[1][0] = (data[2] & 0xf0) | data[2] >> 4; c[1][1] = (data[2] & 0x0f) | data[2] << 4; c[1][2] = (data[3] & 0xf0) | data[3] >> 4; const uint_fast8_t d = Etc2DistanceTable[(data[3] >> 1 & 6) | (data[3] & 1)]; uint_fast32_t color_set[4] = {applicate_color_raw(c[0]), applicate_color(c[1], d), applicate_color_raw(c[1]), applicate_color(c[1], -d)}; k <<= 1; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) outbuf[WriteOrderTable[i]] = color_set[(k & 2) | (j & 1)]; } else if (g + dg < 0 || g + dg > 255) { // H c[0][0] = (data[0] << 1 & 0xf0) | (data[0] >> 3 & 0xf); c[0][1] = (data[0] << 5 & 0xe0) | (data[1] & 0x10); c[0][1] |= c[0][1] >> 4; c[0][2] = (data[1] & 8) | (data[1] << 1 & 6) | data[2] >> 7; c[0][2] |= c[0][2] << 4; c[1][0] = (data[2] << 1 & 0xf0) | (data[2] >> 3 & 0xf); c[1][1] = (data[2] << 5 & 0xe0) | (data[3] >> 3 & 0x10); c[1][1] |= c[1][1] >> 4; c[1][2] = (data[3] << 1 & 0xf0) | (data[3] >> 3 & 0xf); uint_fast8_t d = (data[3] & 4) | (data[3] << 1 & 2); if (c[0][0] > c[1][0] || (c[0][0] == c[1][0] && (c[0][1] > c[1][1] || (c[0][1] == c[1][1] && c[0][2] >= c[1][2])))) ++d; d = Etc2DistanceTable[d]; uint_fast32_t color_set[4] = {applicate_color(c[0], d), applicate_color(c[0], -d), applicate_color(c[1], d), applicate_color(c[1], -d)}; k <<= 1; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) outbuf[WriteOrderTable[i]] = color_set[(k & 2) | (j & 1)]; } else if (b + db < 0 || b + db > 255) { // planar c[0][0] = (data[0] << 1 & 0xfc) | (data[0] >> 5 & 3); c[0][1] = (data[0] << 7 & 0x80) | (data[1] & 0x7e) | (data[0] & 1); c[0][2] = (data[1] << 7 & 0x80) | (data[2] << 2 & 0x60) | (data[2] << 3 & 0x18) | (data[3] >> 5 & 4); c[0][2] |= c[0][2] >> 6; c[1][0] = (data[3] << 1 & 0xf8) | (data[3] << 2 & 4) | (data[3] >> 5 & 3); c[1][1] = (data[4] & 0xfe) | data[4] >> 7; c[1][2] = (data[4] << 7 & 0x80) | (data[5] >> 1 & 0x7c); c[1][2] |= c[1][2] >> 6; c[2][0] = (data[5] << 5 & 0xe0) | (data[6] >> 3 & 0x1c) | (data[5] >> 1 & 3); c[2][1] = (data[6] << 3 & 0xf8) | (data[7] >> 5 & 0x6) | (data[6] >> 4 & 1); c[2][2] = data[7] << 2 | (data[7] >> 4 & 3); for (int y = 0, i = 0; y < 4; y++) { for (int x = 0; x < 4; x++, i++) { uint8_t r = clamp((x * (c[1][0] - c[0][0]) + y * (c[2][0] - c[0][0]) + 4 * c[0][0] + 2) >> 2); uint8_t g = clamp((x * (c[1][1] - c[0][1]) + y * (c[2][1] - c[0][1]) + 4 * c[0][1] + 2) >> 2); uint8_t b = clamp((x * (c[1][2] - c[0][2]) + y * (c[2][2] - c[0][2]) + 4 * c[0][2] + 2) >> 2); outbuf[i] = color(r, g, b, 255); } } } else { // differential const uint_fast8_t code[2] = {data[3] >> 5, data[3] >> 2 & 7}; const uint_fast8_t *table = Etc1SubblockTable[data[3] & 1]; c[0][0] = r | r >> 5; c[0][1] = g | g >> 5; c[0][2] = b | b >> 5; c[1][0] = r + dr; c[1][1] = g + dg; c[1][2] = b + db; c[1][0] |= c[1][0] >> 5; c[1][1] |= c[1][1] >> 5; c[1][2] |= c[1][2] >> 5; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) { uint_fast8_t s = table[i]; uint_fast8_t m = Etc1ModifierTable[code[s]][j & 1]; outbuf[WriteOrderTable[i]] = applicate_color(c[s], k & 1 ? -m : m); } } } else { // individual (diff bit == 0) const uint_fast8_t code[2] = {data[3] >> 5, data[3] >> 2 & 7}; const uint_fast8_t *table = Etc1SubblockTable[data[3] & 1]; c[0][0] = (data[0] & 0xf0) | data[0] >> 4; c[1][0] = (data[0] & 0x0f) | data[0] << 4; c[0][1] = (data[1] & 0xf0) | data[1] >> 4; c[1][1] = (data[1] & 0x0f) | data[1] << 4; c[0][2] = (data[2] & 0xf0) | data[2] >> 4; c[1][2] = (data[2] & 0x0f) | data[2] << 4; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) { uint_fast8_t s = table[i]; uint_fast8_t m = Etc1ModifierTable[code[s]][j & 1]; outbuf[WriteOrderTable[i]] = applicate_color(c[s], k & 1 ? -m : m); } } } static void decode_etc2a1_block(const uint8_t *data, uint32_t *outbuf) { uint_fast16_t j = data[6] << 8 | data[7]; // 15 -> 0 uint_fast32_t k = data[4] << 8 | data[5]; // 31 -> 16 uint_fast8_t c[3][3] = {}; int obaq = data[3] >> 1 & 1; // diff bit == 1 uint_fast8_t r = data[0] & 0xf8; int_fast16_t dr = (data[0] << 3 & 0x18) - (data[0] << 3 & 0x20); uint_fast8_t g = data[1] & 0xf8; int_fast16_t dg = (data[1] << 3 & 0x18) - (data[1] << 3 & 0x20); uint_fast8_t b = data[2] & 0xf8; int_fast16_t db = (data[2] << 3 & 0x18) - (data[2] << 3 & 0x20); if (r + dr < 0 || r + dr > 255) { // T c[0][0] = (data[0] << 3 & 0xc0) | (data[0] << 4 & 0x30) | (data[0] >> 1 & 0xc) | (data[0] & 3); c[0][1] = (data[1] & 0xf0) | data[1] >> 4; c[0][2] = (data[1] & 0x0f) | data[1] << 4; c[1][0] = (data[2] & 0xf0) | data[2] >> 4; c[1][1] = (data[2] & 0x0f) | data[2] << 4; c[1][2] = (data[3] & 0xf0) | data[3] >> 4; const uint_fast8_t d = Etc2DistanceTable[(data[3] >> 1 & 6) | (data[3] & 1)]; uint_fast32_t color_set[4] = {applicate_color_raw(c[0]), applicate_color(c[1], d), applicate_color_raw(c[1]), applicate_color(c[1], -d)}; k <<= 1; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) { int index = (k & 2) | (j & 1); outbuf[WriteOrderTable[i]] = color_set[index]; if (!obaq && index == 2) outbuf[WriteOrderTable[i]] &= TRANSPARENT_MASK; } } else if (g + dg < 0 || g + dg > 255) { // H c[0][0] = (data[0] << 1 & 0xf0) | (data[0] >> 3 & 0xf); c[0][1] = (data[0] << 5 & 0xe0) | (data[1] & 0x10); c[0][1] |= c[0][1] >> 4; c[0][2] = (data[1] & 8) | (data[1] << 1 & 6) | data[2] >> 7; c[0][2] |= c[0][2] << 4; c[1][0] = (data[2] << 1 & 0xf0) | (data[2] >> 3 & 0xf); c[1][1] = (data[2] << 5 & 0xe0) | (data[3] >> 3 & 0x10); c[1][1] |= c[1][1] >> 4; c[1][2] = (data[3] << 1 & 0xf0) | (data[3] >> 3 & 0xf); uint_fast8_t d = (data[3] & 4) | (data[3] << 1 & 2); if (c[0][0] > c[1][0] || (c[0][0] == c[1][0] && (c[0][1] > c[1][1] || (c[0][1] == c[1][1] && c[0][2] >= c[1][2])))) ++d; d = Etc2DistanceTable[d]; uint_fast32_t color_set[4] = {applicate_color(c[0], d), applicate_color(c[0], -d), applicate_color(c[1], d), applicate_color(c[1], -d)}; k <<= 1; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) { int index = (k & 2) | (j & 1); outbuf[WriteOrderTable[i]] = color_set[index]; if (!obaq && index == 2) outbuf[WriteOrderTable[i]] &= TRANSPARENT_MASK; } } else if (b + db < 0 || b + db > 255) { // planar c[0][0] = (data[0] << 1 & 0xfc) | (data[0] >> 5 & 3); c[0][1] = (data[0] << 7 & 0x80) | (data[1] & 0x7e) | (data[0] & 1); c[0][2] = (data[1] << 7 & 0x80) | (data[2] << 2 & 0x60) | (data[2] << 3 & 0x18) | (data[3] >> 5 & 4); c[0][2] |= c[0][2] >> 6; c[1][0] = (data[3] << 1 & 0xf8) | (data[3] << 2 & 4) | (data[3] >> 5 & 3); c[1][1] = (data[4] & 0xfe) | data[4] >> 7; c[1][2] = (data[4] << 7 & 0x80) | (data[5] >> 1 & 0x7c); c[1][2] |= c[1][2] >> 6; c[2][0] = (data[5] << 5 & 0xe0) | (data[6] >> 3 & 0x1c) | (data[5] >> 1 & 3); c[2][1] = (data[6] << 3 & 0xf8) | (data[7] >> 5 & 0x6) | (data[6] >> 4 & 1); c[2][2] = data[7] << 2 | (data[7] >> 4 & 3); for (int y = 0, i = 0; y < 4; y++) { for (int x = 0; x < 4; x++, i++) { uint8_t r = clamp((x * (c[1][0] - c[0][0]) + y * (c[2][0] - c[0][0]) + 4 * c[0][0] + 2) >> 2); uint8_t g = clamp((x * (c[1][1] - c[0][1]) + y * (c[2][1] - c[0][1]) + 4 * c[0][1] + 2) >> 2); uint8_t b = clamp((x * (c[1][2] - c[0][2]) + y * (c[2][2] - c[0][2]) + 4 * c[0][2] + 2) >> 2); outbuf[i] = color(r, g, b, 255); } } } else { // differential const uint_fast8_t code[2] = {data[3] >> 5, data[3] >> 2 & 7}; const uint_fast8_t *table = Etc1SubblockTable[data[3] & 1]; c[0][0] = r | r >> 5; c[0][1] = g | g >> 5; c[0][2] = b | b >> 5; c[1][0] = r + dr; c[1][1] = g + dg; c[1][2] = b + db; c[1][0] |= c[1][0] >> 5; c[1][1] |= c[1][1] >> 5; c[1][2] |= c[1][2] >> 5; for (int i = 0; i < 16; i++, j >>= 1, k >>= 1) { uint_fast8_t s = table[i]; uint_fast8_t m = Etc2aModifierTable[obaq][code[s]][j & 1]; outbuf[WriteOrderTable[i]] = applicate_color_alpha(c[s], k & 1 ? -m : m, !obaq && (k & 1) && !(j & 1)); } } } static void decode_etc2a8_block(const uint8_t *data, uint32_t *outbuf) { if (data[1] & 0xf0) { // multiplier != 0 const uint_fast8_t multiplier = data[1] >> 4; const int_fast8_t *table = Etc2AlphaModTable[data[1] & 0xf]; uint_fast64_t l = bton64(*(uint64_t*)data); for (int i = 0; i < 16; i++, l >>= 3) ((uint8_t *)(outbuf + WriteOrderTableRev[i]))[3] = clamp(data[0] + multiplier * table[l & 7]); } else { // multiplier == 0 (always same as base codeword) for (int i = 0; i < 16; i++, outbuf++) ((uint8_t *)outbuf)[3] = data[0]; } } static void decode_eac_block(const uint8_t *data, int color, uint32_t *outbuf) { uint_fast8_t multiplier = data[1] >> 1 & 0x78; if (multiplier == 0) multiplier = 1; const int_fast8_t *table = Etc2AlphaModTable[data[1] & 0xf]; uint_fast64_t l = bton64(*(uint64_t*)data); for (int i = 0; i < 16; i++, l >>= 3) { int_fast16_t val = data[0] * 8 + multiplier * table[l & 7] + 4; ((uint8_t *)(outbuf + WriteOrderTableRev[i]))[color] = val < 0 ? 0 : val >= 2048 ? 0xff : val >> 3; } } static void decode_eac_signed_block(const uint8_t *data, int color, uint32_t *outbuf) { int8_t base = (int8_t)data[0]; uint_fast8_t multiplier = data[1] >> 1 & 0x78; if (multiplier == 0) multiplier = 1; const int_fast8_t *table = Etc2AlphaModTable[data[1] & 0xf]; uint_fast64_t l = bton64(*(uint64_t*)data); for (int i = 0; i < 16; i++, l >>= 3) { int_fast16_t val = base * 8 + multiplier * table[l & 7] + 1023; ((uint8_t *)(outbuf + WriteOrderTableRev[i]))[color] = val < 0 ? 0 : val >= 2048 ? 0xff : val >> 3; } } int decode_etc1(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 8) { decode_etc1_block(data, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_etc2(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 8) { decode_etc2_block(data, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_etc2a1(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 8) { decode_etc2a1_block(data, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_etc2a8(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 16) { decode_etc2_block(data + 8, buffer); decode_etc2a8_block(data, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_eacr(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; uint32_t base_buffer[16]; for (int i = 0; i < 16; i++) base_buffer[i] = color(0, 0, 0, 255); for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 8) { memcpy(buffer, base_buffer, sizeof(buffer)); decode_eac_block(data, 2, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_eacr_signed(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; uint32_t base_buffer[16]; for (int i = 0; i < 16; i++) base_buffer[i] = color(0, 0, 0, 255); for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 8) { memcpy(buffer, base_buffer, sizeof(buffer)); decode_eac_signed_block(data, 2, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_eacrg(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; uint32_t base_buffer[16]; for (int i = 0; i < 16; i++) base_buffer[i] = color(0, 0, 0, 255); for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 16) { memcpy(buffer, base_buffer, sizeof(buffer)); decode_eac_block(data, 2, buffer); decode_eac_block(data + 8, 1, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; } int decode_eacrg_signed(const uint8_t *data, const long w, const long h, uint32_t *image) { long num_blocks_x = (w + 3) / 4; long num_blocks_y = (h + 3) / 4; uint32_t buffer[16]; uint32_t base_buffer[16]; for (int i = 0; i < 16; i++) base_buffer[i] = color(0, 0, 0, 255); for (long by = 0; by < num_blocks_y; by++) { for (long bx = 0; bx < num_blocks_x; bx++, data += 16) { memcpy(buffer, base_buffer, sizeof(buffer)); decode_eac_signed_block(data, 2, buffer); decode_eac_signed_block(data + 8, 1, buffer); copy_block_buffer(bx, by, w, h, 4, 4, buffer, image); } } return 1; }
AssetStudio/Texture2DDecoderNative/etc.cpp/0
{ "file_path": "AssetStudio/Texture2DDecoderNative/etc.cpp", "repo_id": "AssetStudio", "token_count": 11479 }
77
using System; using System.Runtime.InteropServices; using AssetStudio.PInvoke; namespace Texture2DDecoder { public static unsafe partial class TextureDecoder { static TextureDecoder() { DllLoader.PreloadDll(T2DDll.DllName); } public static bool DecodeDXT1(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeDXT1(pData, width, height, pImage); } } } public static bool DecodeDXT5(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeDXT5(pData, width, height, pImage); } } } public static bool DecodePVRTC(byte[] data, int width, int height, byte[] image, bool is2bpp) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodePVRTC(pData, width, height, pImage, is2bpp); } } } public static bool DecodeETC1(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeETC1(pData, width, height, pImage); } } } public static bool DecodeETC2(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeETC2(pData, width, height, pImage); } } } public static bool DecodeETC2A1(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeETC2A1(pData, width, height, pImage); } } } public static bool DecodeETC2A8(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeETC2A8(pData, width, height, pImage); } } } public static bool DecodeEACR(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeEACR(pData, width, height, pImage); } } } public static bool DecodeEACRSigned(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeEACRSigned(pData, width, height, pImage); } } } public static bool DecodeEACRG(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeEACRG(pData, width, height, pImage); } } } public static bool DecodeEACRGSigned(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeEACRGSigned(pData, width, height, pImage); } } } public static bool DecodeBC4(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeBC4(pData, width, height, pImage); } } } public static bool DecodeBC5(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeBC5(pData, width, height, pImage); } } } public static bool DecodeBC6(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeBC6(pData, width, height, pImage); } } } public static bool DecodeBC7(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeBC7(pData, width, height, pImage); } } } public static bool DecodeATCRGB4(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeATCRGB4(pData, width, height, pImage); } } } public static bool DecodeATCRGBA8(byte[] data, int width, int height, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeATCRGBA8(pData, width, height, pImage); } } } public static bool DecodeASTC(byte[] data, int width, int height, int blockWidth, int blockHeight, byte[] image) { fixed (byte* pData = data) { fixed (byte* pImage = image) { return DecodeASTC(pData, width, height, blockWidth, blockHeight, pImage); } } } public static byte[] UnpackCrunch(byte[] data) { void* pBuffer; uint bufferSize; fixed (byte* pData = data) { UnpackCrunch(pData, (uint)data.Length, out pBuffer, out bufferSize); } if (pBuffer == null) { return null; } var result = new byte[bufferSize]; Marshal.Copy(new IntPtr(pBuffer), result, 0, (int)bufferSize); DisposeBuffer(ref pBuffer); return result; } public static byte[] UnpackUnityCrunch(byte[] data) { void* pBuffer; uint bufferSize; fixed (byte* pData = data) { UnpackUnityCrunch(pData, (uint)data.Length, out pBuffer, out bufferSize); } if (pBuffer == null) { return null; } var result = new byte[bufferSize]; Marshal.Copy(new IntPtr(pBuffer), result, 0, (int)bufferSize); DisposeBuffer(ref pBuffer); return result; } } }
AssetStudio/Texture2DDecoderWrapper/TextureDecoder.cs/0
{ "file_path": "AssetStudio/Texture2DDecoderWrapper/TextureDecoder.cs", "repo_id": "AssetStudio", "token_count": 4233 }
78
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <RootNamespace>ET</RootNamespace> <LangVersion>12</LangVersion> <AssemblyName>Hotfix</AssemblyName> </PropertyGroup> <PropertyGroup> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> <SatelliteResourceLanguages>en</SatelliteResourceLanguages> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DefineConstants>DOTNET</DefineConstants> <OutputPath>..\..\Bin\</OutputPath> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <NoWarn>0169,0649,3021,8981,CS9193,CS9192</NoWarn> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DefineConstants>DOTNET</DefineConstants> <OutputPath>..\..\Bin\</OutputPath> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Optimize>false</Optimize> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <NoWarn>0169,0649,3021,8981,CS9193,CS9192</NoWarn> </PropertyGroup> <ItemGroup> <Compile Include="..\..\Unity\Assets\Scripts\Hotfix\Client\**\*.cs"> <Link>Client\%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\Hotfix\Server\**\*.cs"> <Link>Server\%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> <Compile Include="..\..\Unity\Assets\Scripts\Hotfix\Share\**\*.cs"> <Link>Share\%(RecursiveDir)%(FileName)%(Extension)</Link> </Compile> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Share\Analyzer\Share.Analyzer.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\..\Share\Share.SourceGenerator\Share.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\Loader\DotNet.Loader.csproj" /> <ProjectReference Include="..\Model\DotNet.Model.csproj" /> </ItemGroup> </Project>
ET/DotNet/Hotfix/DotNet.Hotfix.csproj/0
{ "file_path": "ET/DotNet/Hotfix/DotNet.Hotfix.csproj", "repo_id": "ET", "token_count": 948 }
79
using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class AsyncMethodReturnTypeAnalyzer: DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AsyncMethodReturnTypeAnalyzerRule.Rule); public override void Initialize(AnalysisContext context) { if (!AnalyzerGlobalSetting.EnableAnalyzer) { return; } context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSyntaxNodeAction(this.Analyzer, SyntaxKind.MethodDeclaration,SyntaxKind.LocalFunctionStatement); } private void Analyzer(SyntaxNodeAnalysisContext context) { IMethodSymbol? methodSymbol = null; if (context.Node is MethodDeclarationSyntax methodDeclarationSyntax) { methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclarationSyntax); } else if (context.Node is LocalFunctionStatementSyntax localFunctionStatementSyntax) { methodSymbol = context.SemanticModel.GetDeclaredSymbol(localFunctionStatementSyntax) as IMethodSymbol; } if (methodSymbol==null) { return; } if (methodSymbol.IsAsync && methodSymbol.ReturnsVoid) { Diagnostic diagnostic = Diagnostic.Create(AsyncMethodReturnTypeAnalyzerRule.Rule, context.Node.GetLocation()); context.ReportDiagnostic(diagnostic); } } } }
ET/Share/Analyzer/Analyzer/AsyncMethodReturnTypeAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/AsyncMethodReturnTypeAnalyzer.cs", "repo_id": "ET", "token_count": 838 }
80
using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace ET.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticClassCircularDependencyAnalyzer: DiagnosticAnalyzer { private const string Title = "静态类之间禁止环形依赖"; private const string MessageFormat = "ET0013 静态类函数引用存在环形依赖 请修改为单向依赖 静态类{0}被 静态类{1}引用"; private const string Description = "静态类之间禁止环形依赖."; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticIds.StaticClassCircularDedendencyAnalyzerRuleId, Title, MessageFormat, DiagnosticCategories.Hotfix, DiagnosticSeverity.Error, true, Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); private object lockObj = new object(); public override void Initialize(AnalysisContext context) { if (!AnalyzerGlobalSetting.EnableAnalyzer) { return; } context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterCompilationStartAction(this.CompilationStartAnalysis); } private void CompilationStartAnalysis(CompilationStartAnalysisContext context) { var dependencyMap = new ConcurrentDictionary<string, HashSet<string>>(); var staticClassSet = new HashSet<string>(); if (AnalyzerHelper.IsAssemblyNeedAnalyze(context.Compilation.AssemblyName, AnalyzeAssembly.AllHotfix)) { context.RegisterSyntaxNodeAction(analysisContext => { this.StaticClassDependencyAnalyze(analysisContext, dependencyMap, staticClassSet); }, SyntaxKind.InvocationExpression); context.RegisterCompilationEndAction(analysisContext => { this.CircularDependencyAnalyze(analysisContext, dependencyMap, staticClassSet); }); } } /// <summary> /// 静态类依赖分析 构建depedencyMap /// </summary> private void StaticClassDependencyAnalyze(SyntaxNodeAnalysisContext context, ConcurrentDictionary<string, HashSet<string>> dependencyMap, HashSet<string> staticClassSet) { if (!(context.Node is InvocationExpressionSyntax invocationExpressionSyntax)) { return; } if (context.ContainingSymbol == null) { return; } INamedTypeSymbol? selfClassType = context.ContainingSymbol.ContainingType; //筛选出自身为静态类 if (selfClassType == null || !selfClassType.IsStatic) { return; } //筛选出函数调用 if (!(context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol methodSymbol)) { return; } string selfClassTypeName = selfClassType.ToString(); string methodClassTypeName = methodSymbol.ContainingType.ToString(); lock (this.lockObj) { if (!staticClassSet.Contains(selfClassTypeName)) { staticClassSet.Add(selfClassTypeName); } } // 筛选出对其他静态类的函数调用 if (selfClassTypeName == methodClassTypeName) { return; } if (!methodSymbol.ContainingType.IsStatic) { return; } if (!dependencyMap.ContainsKey(methodClassTypeName)) { dependencyMap[methodClassTypeName] = new HashSet<string>(); } var set = dependencyMap[methodClassTypeName]; lock (set) { if (!set.Contains(selfClassTypeName)) { set.Add(selfClassTypeName); } } } /// <summary> /// 环形依赖分析 /// </summary> private void CircularDependencyAnalyze(CompilationAnalysisContext context, ConcurrentDictionary<string, HashSet<string>> dependencyMap, HashSet<string> staticClassSet) { // 排除只引用其他静态类的静态类 while (true) { string noDependencyStaticClass = this.GetClassNotReferencedByOtherStaticClass(dependencyMap, staticClassSet); if (!string.IsNullOrEmpty(noDependencyStaticClass)) { foreach (var dependency in dependencyMap) { if (dependency.Value.Contains(noDependencyStaticClass)) { dependency.Value.Remove(noDependencyStaticClass); } } staticClassSet.Remove(noDependencyStaticClass); } else { break; } } var staticClassDependencyMap = new ConcurrentDictionary<string, HashSet<string>>(); foreach (string? staticClass in staticClassSet) { staticClassDependencyMap[staticClass] = dependencyMap[staticClass]; } //排除只被其他静态类引用的静态类 while (true) { string staticClass = this.GetClassNotReferenceAnyStaticClass(staticClassDependencyMap, staticClassSet); if (!string.IsNullOrEmpty(staticClass)) { staticClassSet.Remove(staticClass); } else { break; } } if (staticClassSet.Count > 0) { foreach (string? staticClass in staticClassSet) { Diagnostic diagnostic = Diagnostic.Create(Rule, null, staticClass, FormatSet(dependencyMap[staticClass])); context.ReportDiagnostic(diagnostic); } } string FormatSet(HashSet<string> hashSet) { StringBuilder stringBuilder = new StringBuilder(); foreach (string? value in hashSet) { stringBuilder.Append($"{value} "); } return stringBuilder.ToString(); } } /// <summary> /// 获取没有被任何其他静态类引用的静态类 /// </summary> private string GetClassNotReferencedByOtherStaticClass(ConcurrentDictionary<string, HashSet<string>> dependencyMap, HashSet<string> staticClassSet) { foreach (string? staticClass in staticClassSet) { // 该静态类 没有被任何其他静态类引用 if (!dependencyMap.ContainsKey(staticClass) || dependencyMap[staticClass].Count == 0) { return staticClass; } } return string.Empty; } /// <summary> /// 获取没有引用任何其他静态类的静态类 /// </summary> private string GetClassNotReferenceAnyStaticClass(ConcurrentDictionary<string, HashSet<string>> dependencyMap, HashSet<string> staticClassSet) { foreach (string? staticClass in staticClassSet) { var result = dependencyMap.Where(x => x.Value.Contains(staticClass)); if (result.Count() == 0) { return staticClass; } } return string.Empty; } } }
ET/Share/Analyzer/Analyzer/StaticClassCircularDependencyAnalyzer.cs/0
{ "file_path": "ET/Share/Analyzer/Analyzer/StaticClassCircularDependencyAnalyzer.cs", "repo_id": "ET", "token_count": 4327 }
81
#ifndef INVOKE_HELPER_H #define INVOKE_HELPER_H #if !RECASTNAVIGATION_STATIC && WIN32 #define RECAST_DLL _declspec(dllexport) #else #define RECAST_DLL #endif #include "DetourNavMesh.h" #include <cstdint> #include <string> #include <map> #ifdef __cplusplus extern "C" { #endif class NavMeshContex; RECAST_DLL NavMeshContex* RecastLoad(const char* buffer, int32_t n); RECAST_DLL void RecastClear(NavMeshContex* navMeshContex); RECAST_DLL int32_t RecastFind(NavMeshContex* navMeshContex, float* extents, float* startPos, float* endPos, float* straightPath); RECAST_DLL int32_t RecastFindNearestPoint(NavMeshContex* navMeshContex, float* extents, float* pos, float* nearestPos); RECAST_DLL int32_t RecastFindRandomPoint(NavMeshContex* navMeshContex, float* pos); RECAST_DLL int32_t RecastFindRandomPointAroundCircle(NavMeshContex* navMeshContex, float* extents, const float* centerPos, const float maxRadius, float* pos); #ifdef __cplusplus } #endif int32_t InitNav(const char* buffer, int32_t n, dtNavMesh*& navMesh); #endif
ET/Share/Libs/RecastDll/Include/InvokeHelper.h/0
{ "file_path": "ET/Share/Libs/RecastDll/Include/InvokeHelper.h", "repo_id": "ET", "token_count": 393 }
82
using System.Collections.Generic; using System.Text; using ET.Analyzer; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ET.Generator; [Generator(LanguageNames.CSharp)] public class ETEntitySerializeFormatterGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { context.RegisterForSyntaxNotifications((() => ETEntitySerializeFormatterSyntaxContextReceiver.Create())); } public void Execute(GeneratorExecutionContext context) { if (context.SyntaxContextReceiver is not ETEntitySerializeFormatterSyntaxContextReceiver receiver || receiver.entities.Count==0) { return; } int count = receiver.entities.Count; string typeHashCodeMapDeclaration = GenerateTypeHashCodeMapDeclaration(receiver); string serializeContent = GenerateSerializeContent(receiver); string deserializeContent = GenerateDeserializeContent(receiver); string genericTypeParam = context.Compilation.AssemblyName == AnalyzeAssembly.DotNetModel? "<TBufferWriter>" : ""; string scopedCode = context.Compilation.AssemblyName == AnalyzeAssembly.DotNetModel? "scoped" : ""; string code = $$""" #nullable enable #pragma warning disable CS0108 // hides inherited member #pragma warning disable CS0162 // Unreachable code #pragma warning disable CS0164 // This label has not been referenced #pragma warning disable CS0219 // Variable assigned but never used #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning disable CS8601 // Possible null reference assignment #pragma warning disable CS8602 #pragma warning disable CS8604 // Possible null reference argument for parameter #pragma warning disable CS8619 #pragma warning disable CS8620 #pragma warning disable CS8631 // The type cannot be used as type parameter in the generic type or method #pragma warning disable CS8765 // Nullability of type of parameter #pragma warning disable CS9074 // The 'scoped' modifier of parameter doesn't match overridden or implemented member #pragma warning disable CA1050 // Declare types in namespaces. using System; using MemoryPack; [global::MemoryPack.Internal.Preserve] public class ETEntitySerializeFormatter : MemoryPackFormatter<global::{{Definition.EntityType}}> { static readonly System.Collections.Generic.Dictionary<Type, long> __typeToTag = new({{count}}) { {{typeHashCodeMapDeclaration}} }; [global::MemoryPack.Internal.Preserve] public override void Serialize{{genericTypeParam}}(ref MemoryPackWriter{{genericTypeParam}} writer,{{scopedCode}} ref global::{{Definition.EntityType}}? value) { if (value == null) { writer.WriteNullUnionHeader(); return; } if (__typeToTag.TryGetValue(value.GetType(), out var tag)) { writer.WriteValue<byte>(global::MemoryPack.MemoryPackCode.WideTag); writer.WriteValue<long>(tag); switch (tag) { {{serializeContent}} default: break; } } else { MemoryPackSerializationException.ThrowNotFoundInUnionType(value.GetType(), typeof(global::{{Definition.EntityType}})); } } [global::MemoryPack.Internal.Preserve] public override void Deserialize(ref MemoryPackReader reader,{{scopedCode}} ref global::{{Definition.EntityType}}? value) { bool isNull = reader.ReadValue<byte>() == global::MemoryPack.MemoryPackCode.NullObject; if (isNull) { value = default; return; } var tag = reader.ReadValue<long>(); switch (tag) { {{deserializeContent}} default: //MemoryPackSerializationException.ThrowInvalidTag(tag, typeof(global::IForExternalUnion)); break; } } } namespace ET { public static partial class EntitySerializeRegister { static partial void Register() { if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<global::{{Definition.EntityType}}>()) { global::MemoryPack.MemoryPackFormatterProvider.Register(new ETEntitySerializeFormatter()); } } } } """; context.AddSource($"ETEntitySerializeFormatterGenerator.g.cs",code); } private string GenerateTypeHashCodeMapDeclaration(ETEntitySerializeFormatterSyntaxContextReceiver receiver) { StringBuilder sb = new StringBuilder(); foreach (var entityName in receiver.entities) { sb.AppendLine($$""" { typeof(global::{{entityName}}), {{entityName.GetLongHashCode()}} },"""); } return sb.ToString(); } private string GenerateSerializeContent(ETEntitySerializeFormatterSyntaxContextReceiver receiver) { StringBuilder sb = new StringBuilder(); foreach (var entityName in receiver.entities) { sb.AppendLine($$""" case {{entityName.GetLongHashCode()}}: writer.WritePackable(System.Runtime.CompilerServices.Unsafe.As<global::{{Definition.EntityType}}?, global::{{entityName}}>(ref value)); break;"""); } return sb.ToString(); } private string GenerateDeserializeContent(ETEntitySerializeFormatterSyntaxContextReceiver receiver) { StringBuilder sb = new StringBuilder(); foreach (var entityName in receiver.entities) { sb.AppendLine($$""" case {{entityName.GetLongHashCode()}}: if(value is global::{{entityName}}) { reader.ReadPackable(ref System.Runtime.CompilerServices.Unsafe.As<global::{{Definition.EntityType}}?, global::{{entityName}}>(ref value)); }else{ value = (global::{{entityName}})reader.ReadPackable<global::{{entityName}}>(); } break; """); } return sb.ToString(); } class ETEntitySerializeFormatterSyntaxContextReceiver : ISyntaxContextReceiver { internal static ISyntaxContextReceiver Create() { return new ETEntitySerializeFormatterSyntaxContextReceiver(); } public HashSet<string> entities = new HashSet<string>(); public void OnVisitSyntaxNode(GeneratorSyntaxContext context) { if (!AnalyzerHelper.IsAssemblyNeedAnalyze(context.SemanticModel.Compilation.AssemblyName,AnalyzeAssembly.AllLogicModel)) { return; } if (context.Node is not ClassDeclarationSyntax classDeclarationSyntax) { return; } var classTypeSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax); if (classTypeSymbol==null) { return; } var baseType = classTypeSymbol.BaseType?.ToString(); // 筛选出实体类 if (baseType!= Definition.EntityType && baseType != Definition.LSEntityType) { return; } if (!classTypeSymbol.HasAttribute("MemoryPack.MemoryPackableAttribute")) { return; } entities.Add(classTypeSymbol.ToString()); } } }
ET/Share/Share.SourceGenerator/Generator/ETEntitySerializeFormatterGenerator.cs/0
{ "file_path": "ET/Share/Share.SourceGenerator/Generator/ETEntitySerializeFormatterGenerator.cs", "repo_id": "ET", "token_count": 3159 }
83
# ET-EUI 基于ET框架的封装的WebSocket,支持WebGL #### 使用方式 - 在SceneFactory的CreateZoneScene上添加 zoneScene.AddComponent<NetWSJSComponent, int>(SessionStreamDispatcherType.SessionStreamDispatcherClientOuter); - 在使用的时候先创建Session Session gateSession = zoneScene.GetComponent<NetWSJSComponent>().Create($"ws://{r2CLoginZone.GateAddrss}"); - 拿到Session正常发送就行 G2C_Login2Gate g2CLogin2Gate = (G2C_Login2Gate)await gateSession.Call(new C2G_Login2Gate() { GateKey = r2CLoginZone.GateKey }); #### 插件地址 https://gitee.com/chen_fen_hui/web-socket-js.git
ET/Store/WebSocketJs.md/0
{ "file_path": "ET/Store/WebSocketJs.md", "repo_id": "ET", "token_count": 272 }
84
## 使用说明 双击打开RecastDemo.exe文件 (如果出现报错说明是电脑本身缺少VisualC++库,可以下载一个Visual Studio然后安装如图所示模块即可) ![QQ截图20220113193347](https://user-images.githubusercontent.com/35335061/149324942-01a7cf02-81b8-4620-9f73-77427819316e.png) 随后选中模型,并进行参数调控与Nav数据烘焙即可 ![QQ截图20220113193440](https://user-images.githubusercontent.com/35335061/149324982-1c1f26a9-e53f-4b9c-914a-4bffe3ba129b.png) ![QQ截图20220113193509](https://user-images.githubusercontent.com/35335061/149325003-6d6fc062-7123-443a-ae07-a852fe50d3f9.png) 导出的nav数据文件位于 ![QQ截图20220113193546](https://user-images.githubusercontent.com/35335061/149324992-465257b9-0274-49ce-bb12-9fac113ed1a2.png) 可根据需要放置到指定目录
ET/Tools/RecastNavExportor/Readme.md/0
{ "file_path": "ET/Tools/RecastNavExportor/Readme.md", "repo_id": "ET", "token_count": 482 }
85
fileFormatVersion: 2 guid: a5294483f20f40d449699101bb428cda DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Bundles/Scenes/Map1.unity.meta/0
{ "file_path": "ET/Unity/Assets/Bundles/Scenes/Map1.unity.meta", "repo_id": "ET", "token_count": 62 }
86
fileFormatVersion: 2 guid: 691adf980066447bb8b1247c60c73827 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Bundles/UI/LockStep.meta/0
{ "file_path": "ET/Unity/Assets/Bundles/UI/LockStep.meta", "repo_id": "ET", "token_count": 69 }
87
fileFormatVersion: 2 guid: f5acaa5394763914297715289ae69489 DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Config/Excel/StartConfig/Localhost/StartZoneConfig@s.xlsx.meta/0
{ "file_path": "ET/Unity/Assets/Config/Excel/StartConfig/Localhost/StartZoneConfig@s.xlsx.meta", "repo_id": "ET", "token_count": 61 }
88
fileFormatVersion: 2 guid: 8fc4f69252da4c94d979a92a0b0c153f DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Config/Excel/StartConfig/RouterTest/StartSceneConfig@s.xlsx.meta/0
{ "file_path": "ET/Unity/Assets/Config/Excel/StartConfig/RouterTest/StartSceneConfig@s.xlsx.meta", "repo_id": "ET", "token_count": 67 }
89
fileFormatVersion: 2 guid: 064fc127e21b5c24da06dd305a52cf4a folderAsset: yes DefaultImporter: userData:
ET/Unity/Assets/Plugins.meta/0
{ "file_path": "ET/Unity/Assets/Plugins.meta", "repo_id": "ET", "token_count": 45 }
90
fileFormatVersion: 2 guid: b1494958bf9856a479bec1767c02878e timeCreated: 18446744011573954816 NativeFormatImporter: mainObjectFileID: 0 userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Res/Unit/Skeleton/Ani/Materials/skeleton_D.mat.meta/0
{ "file_path": "ET/Unity/Assets/Res/Unit/Skeleton/Ani/Materials/skeleton_D.mat.meta", "repo_id": "ET", "token_count": 76 }
91
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!114 &11400000 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 0} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3} m_Name: UniversalRenderPipelineAsset m_EditorClassIdentifier: k_AssetVersion: 11 k_AssetPreviousVersion: 11 m_RendererType: 1 m_RendererData: {fileID: 0} m_RendererDataList: - {fileID: 11400000, guid: 254392dcb48c57643972335fc1a510eb, type: 2} m_DefaultRendererIndex: 0 m_RequireDepthTexture: 0 m_RequireOpaqueTexture: 0 m_OpaqueDownsampling: 1 m_SupportsTerrainHoles: 1 m_SupportsHDR: 1 m_HDRColorBufferPrecision: 0 m_MSAA: 1 m_RenderScale: 1 m_UpscalingFilter: 0 m_FsrOverrideSharpness: 0 m_FsrSharpness: 0.92 m_EnableLODCrossFade: 1 m_LODCrossFadeDitheringType: 1 m_ShEvalMode: 0 m_MainLightRenderingMode: 1 m_MainLightShadowsSupported: 1 m_MainLightShadowmapResolution: 2048 m_AdditionalLightsRenderingMode: 1 m_AdditionalLightsPerObjectLimit: 0 m_AdditionalLightShadowsSupported: 0 m_AdditionalLightsShadowmapResolution: 512 m_AdditionalLightsShadowResolutionTierLow: 128 m_AdditionalLightsShadowResolutionTierMedium: 256 m_AdditionalLightsShadowResolutionTierHigh: 512 m_ReflectionProbeBlending: 0 m_ReflectionProbeBoxProjection: 0 m_ShadowDistance: 100 m_ShadowCascadeCount: 4 m_Cascade2Split: 0.099999994 m_Cascade3Split: {x: 0.1, y: 0.3} m_Cascade4Split: {x: 0.09999999, y: 0.29999998, z: 0.59999996} m_CascadeBorder: 0.13333337 m_ShadowDepthBias: 1 m_ShadowNormalBias: 1 m_AnyShadowsSupported: 1 m_SoftShadowsSupported: 0 m_ConservativeEnclosingSphere: 0 m_NumIterationsEnclosingSphere: 64 m_SoftShadowQuality: 2 m_AdditionalLightsCookieResolution: 2048 m_AdditionalLightsCookieFormat: 3 m_UseSRPBatcher: 1 m_SupportsDynamicBatching: 0 m_MixedLightingSupported: 1 m_SupportsLightCookies: 1 m_SupportsLightLayers: 0 m_DebugLevel: 0 m_StoreActionsOptimization: 0 m_EnableRenderGraph: 0 m_UseAdaptivePerformance: 1 m_ColorGradingMode: 0 m_ColorGradingLutSize: 32 m_UseFastSRGBLinearConversion: 0 m_SupportDataDrivenLensFlare: 1 m_ShadowType: 1 m_LocalShadowsSupported: 0 m_LocalShadowsAtlasResolution: 256 m_MaxPixelLights: 0 m_ShadowAtlasResolution: 256 m_VolumeFrameworkUpdateMode: 0 m_Textures: blueNoise64LTex: {fileID: 2800000, guid: e3d24661c1e055f45a7560c033dbb837, type: 3} bayerMatrixTex: {fileID: 2800000, guid: f9ee4ed84c1d10c49aabb9b210b0fc44, type: 3} m_PrefilteringModeMainLightShadows: 1 m_PrefilteringModeAdditionalLight: 4 m_PrefilteringModeAdditionalLightShadows: 1 m_PrefilterXRKeywords: 0 m_PrefilteringModeForwardPlus: 1 m_PrefilteringModeDeferredRendering: 1 m_PrefilteringModeScreenSpaceOcclusion: 1 m_PrefilterDebugKeywords: 0 m_PrefilterWriteRenderingLayers: 0 m_PrefilterHDROutput: 0 m_PrefilterSSAODepthNormals: 0 m_PrefilterSSAOSourceDepthLow: 0 m_PrefilterSSAOSourceDepthMedium: 0 m_PrefilterSSAOSourceDepthHigh: 0 m_PrefilterSSAOInterleaved: 0 m_PrefilterSSAOBlueNoise: 0 m_PrefilterSSAOSampleCountLow: 0 m_PrefilterSSAOSampleCountMedium: 0 m_PrefilterSSAOSampleCountHigh: 0 m_PrefilterDBufferMRT1: 0 m_PrefilterDBufferMRT2: 0 m_PrefilterDBufferMRT3: 0 m_PrefilterSoftShadowsQualityLow: 0 m_PrefilterSoftShadowsQualityMedium: 0 m_PrefilterSoftShadowsQualityHigh: 0 m_PrefilterSoftShadows: 0 m_PrefilterScreenCoord: 0 m_PrefilterNativeRenderPass: 0 m_ShaderVariantLogLevel: 0 m_ShadowCascades: 0
ET/Unity/Assets/Res/UniversalRenderPipelineAsset.asset/0
{ "file_path": "ET/Unity/Assets/Res/UniversalRenderPipelineAsset.asset", "repo_id": "ET", "token_count": 1496 }
92
using System; namespace ET { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class EntitySystemAttribute: BaseAttribute { } }
ET/Unity/Assets/Scripts/Core/Entity/EntitySystemAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/EntitySystemAttribute.cs", "repo_id": "ET", "token_count": 52 }
93
using System; namespace ET { public interface ISerialize { } public interface ISerializeSystem: ISystemType { void Run(Entity o); } /// <summary> /// 序列化前执行的System /// </summary> /// <typeparam name="T"></typeparam> [EntitySystem] public abstract class SerializeSystem<T> : SystemObject, ISerializeSystem where T: Entity, ISerialize { void ISerializeSystem.Run(Entity o) { this.Serialize((T)o); } Type ISystemType.SystemType() { return typeof(ISerializeSystem); } int ISystemType.GetInstanceQueueIndex() { return InstanceQueueIndex.None; } Type ISystemType.Type() { return typeof(T); } protected abstract void Serialize(T self); } }
ET/Unity/Assets/Scripts/Core/Entity/ISerializeSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/ISerializeSystem.cs", "repo_id": "ET", "token_count": 280 }
94
fileFormatVersion: 2 guid: 2fd29b3ff6f09434a9de8b2a26016ea8 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Fiber.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber.meta", "repo_id": "ET", "token_count": 71 }
95
fileFormatVersion: 2 guid: 45dca9d6f16557645a7ce5b1dfad7176 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Fiber/Module/Actor/MessageSenderStruct.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber/Module/Actor/MessageSenderStruct.cs.meta", "repo_id": "ET", "token_count": 96 }
96
using System; using System.Threading; namespace ET { [Invoke(TimerCoreInvokeType.CoroutineTimeout)] public class WaitCoroutineLockTimer: ATimer<WaitCoroutineLock> { protected override void Run(WaitCoroutineLock waitCoroutineLock) { if (waitCoroutineLock.IsDisposed()) { return; } waitCoroutineLock.SetException(new Exception("coroutine is timeout!")); } } public class WaitCoroutineLock { public static WaitCoroutineLock Create() { WaitCoroutineLock waitCoroutineLock = new WaitCoroutineLock(); waitCoroutineLock.tcs = ETTask<CoroutineLock>.Create(true); return waitCoroutineLock; } private ETTask<CoroutineLock> tcs; public void SetResult(CoroutineLock coroutineLock) { if (this.tcs == null) { throw new NullReferenceException("SetResult tcs is null"); } var t = this.tcs; this.tcs = null; t.SetResult(coroutineLock); } public void SetException(Exception exception) { if (this.tcs == null) { throw new NullReferenceException("SetException tcs is null"); } var t = this.tcs; this.tcs = null; t.SetException(exception); } public bool IsDisposed() { return this.tcs == null; } public async ETTask<CoroutineLock> Wait() { return await this.tcs; } } }
ET/Unity/Assets/Scripts/Core/Fiber/Module/CoroutineLock/WaitCoroutineLock.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber/Module/CoroutineLock/WaitCoroutineLock.cs", "repo_id": "ET", "token_count": 820 }
97
using System.Text; namespace ET { public static class ByteHelper { public static string ToHex(this byte b) { return b.ToString("X2"); } public static string ToHex(this byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(); foreach (byte b in bytes) { stringBuilder.Append(b.ToString("X2")); } return stringBuilder.ToString(); } public static string ToHex(this byte[] bytes, string format) { StringBuilder stringBuilder = new StringBuilder(); foreach (byte b in bytes) { stringBuilder.Append(b.ToString(format)); } return stringBuilder.ToString(); } public static string ToHex(this byte[] bytes, int offset, int count) { StringBuilder stringBuilder = new StringBuilder(); for (int i = offset; i < offset + count; ++i) { stringBuilder.Append(bytes[i].ToString("X2")); } return stringBuilder.ToString(); } public static string ToStr(this byte[] bytes) { return Encoding.Default.GetString(bytes); } public static string ToStr(this byte[] bytes, int index, int count) { return Encoding.Default.GetString(bytes, index, count); } public static string Utf8ToStr(this byte[] bytes) { return Encoding.UTF8.GetString(bytes); } public static string Utf8ToStr(this byte[] bytes, int index, int count) { return Encoding.UTF8.GetString(bytes, index, count); } public static void WriteTo(this byte[] bytes, int offset, uint num) { bytes[offset] = (byte)(num & 0xff); bytes[offset + 1] = (byte)((num & 0xff00) >> 8); bytes[offset + 2] = (byte)((num & 0xff0000) >> 16); bytes[offset + 3] = (byte)((num & 0xff000000) >> 24); } public static void WriteTo(this byte[] bytes, int offset, ActorId num) { bytes.WriteTo(offset, num.Process); bytes.WriteTo(offset + 4, num.Fiber); bytes.WriteTo(offset + 8, num.InstanceId); } public static void WriteTo(this byte[] bytes, int offset, int num) { bytes[offset] = (byte)(num & 0xff); bytes[offset + 1] = (byte)((num & 0xff00) >> 8); bytes[offset + 2] = (byte)((num & 0xff0000) >> 16); bytes[offset + 3] = (byte)((num & 0xff000000) >> 24); } public static void WriteTo(this byte[] bytes, int offset, byte num) { bytes[offset] = num; } public static void WriteTo(this byte[] bytes, int offset, short num) { bytes[offset] = (byte)(num & 0xff); bytes[offset + 1] = (byte)((num & 0xff00) >> 8); } public static void WriteTo(this byte[] bytes, int offset, ushort num) { bytes[offset] = (byte)(num & 0xff); bytes[offset + 1] = (byte)((num & 0xff00) >> 8); } public static unsafe void WriteTo(this byte[] bytes, int offset, long num) { byte* bPoint = (byte*)&num; for (int i = 0; i < sizeof(long); ++i) { bytes[offset + i] = bPoint[i]; } } public static long Hash(this byte[] data, int index, int length) { const int p = 16777619; long hash = 2166136261L; for (int i = index; i < index + length; i++) { hash = (hash ^ data[i]) * p; } hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return hash; } } }
ET/Unity/Assets/Scripts/Core/Helper/ByteHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/ByteHelper.cs", "repo_id": "ET", "token_count": 1289 }
98
using System; using System.Collections.Generic; using Random = System.Random; namespace ET { // 支持多线程 public static class RandomGenerator { [StaticField] [ThreadStatic] private static Random random; private static Random GetRandom() { return random ??= new Random(Guid.NewGuid().GetHashCode() ^ Environment.TickCount); } public static ulong RandUInt64() { int r1 = RandInt32(); int r2 = RandInt32(); return ((ulong)r1 << 32) | (uint)r2; } public static int RandInt32() { return GetRandom().Next(); } public static uint RandUInt32() { return (uint) GetRandom().Next(); } public static long RandInt64() { uint r1 = RandUInt32(); uint r2 = RandUInt32(); return (long)(((ulong)r1 << 32) | r2); } /// <summary> /// 获取lower与Upper之间的随机数,包含下限,不包含上限 /// </summary> /// <param name="lower"></param> /// <param name="upper"></param> /// <returns></returns> public static int RandomNumber(int lower, int upper) { int value = GetRandom().Next(lower, upper); return value; } public static bool RandomBool() { return GetRandom().Next(2) == 0; } public static T RandomArray<T>(T[] array) { return array[RandomNumber(0, array.Length)]; } public static T RandomArray<T>(List<T> array) { return array[RandomNumber(0, array.Count)]; } /// <summary> /// 打乱数组 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arr">要打乱的数组</param> public static void BreakRank<T>(List<T> arr) { if (arr == null || arr.Count < 2) { return; } for (int i = 0; i < arr.Count; i++) { int index = GetRandom().Next(0, arr.Count); (arr[index], arr[i]) = (arr[i], arr[index]); } } public static float RandFloat01() { int a = RandomNumber(0, 1000000); return a / 1000000f; } } }
ET/Unity/Assets/Scripts/Core/Helper/RandomGenerator.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/RandomGenerator.cs", "repo_id": "ET", "token_count": 1270 }
99
using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; namespace ET { public interface IKcpTransport: IDisposable { void Send(byte[] bytes, int index, int length, EndPoint endPoint); int Recv(byte[] buffer, ref EndPoint endPoint); int Available(); void Update(); void OnError(long id, int error); } public class UdpTransport: IKcpTransport { private readonly Socket socket; public UdpTransport(AddressFamily addressFamily) { this.socket = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp); NetworkHelper.SetSioUdpConnReset(this.socket); } public UdpTransport(IPEndPoint ipEndPoint) { this.socket = new Socket(ipEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { this.socket.SendBufferSize = Kcp.OneM * 64; this.socket.ReceiveBufferSize = Kcp.OneM * 64; } try { this.socket.Bind(ipEndPoint); } catch (Exception e) { throw new Exception($"bind error: {ipEndPoint}", e); } NetworkHelper.SetSioUdpConnReset(this.socket); } public void Send(byte[] bytes, int index, int length, EndPoint endPoint) { this.socket.SendTo(bytes, index, length, SocketFlags.None, endPoint); } public int Recv(byte[] buffer, ref EndPoint endPoint) { return this.socket.ReceiveFrom(buffer, ref endPoint); } public int Available() { return this.socket.Available; } public void Update() { } public void OnError(long id, int error) { } public void Dispose() { this.socket?.Dispose(); } } public class TcpTransport: IKcpTransport { private readonly TService tService; private readonly DoubleMap<long, EndPoint> idEndpoints = new(); private readonly Queue<(EndPoint, MemoryBuffer)> channelRecvDatas = new(); private readonly Dictionary<long, long> readWriteTime = new(); private readonly Queue<long> channelIds = new(); public TcpTransport(AddressFamily addressFamily) { this.tService = new TService(addressFamily, ServiceType.Outer); this.tService.ErrorCallback = this.OnError; this.tService.ReadCallback = this.OnRead; } public TcpTransport(IPEndPoint ipEndPoint) { this.tService = new TService(ipEndPoint, ServiceType.Outer); this.tService.AcceptCallback = this.OnAccept; this.tService.ErrorCallback = this.OnError; this.tService.ReadCallback = this.OnRead; } private void OnAccept(long id, IPEndPoint ipEndPoint) { TChannel channel = this.tService.Get(id); long timeNow = TimeInfo.Instance.ClientFrameTime(); this.readWriteTime[id] = timeNow; this.channelIds.Enqueue(id); this.idEndpoints.Add(id, channel.RemoteAddress); } public void OnError(long id, int error) { Log.Warning($"IKcpTransport tcp error: {id} {error}"); this.tService.Remove(id, error); this.idEndpoints.RemoveByKey(id); this.readWriteTime.Remove(id); } private void OnRead(long id, MemoryBuffer memoryBuffer) { long timeNow = TimeInfo.Instance.ClientFrameTime(); this.readWriteTime[id] = timeNow; TChannel channel = this.tService.Get(id); channelRecvDatas.Enqueue((channel.RemoteAddress, memoryBuffer)); } public void Send(byte[] bytes, int index, int length, EndPoint endPoint) { long id = this.idEndpoints.GetKeyByValue(endPoint); if (id == 0) { id = IdGenerater.Instance.GenerateInstanceId(); this.tService.Create(id, (IPEndPoint)endPoint); this.idEndpoints.Add(id, endPoint); this.channelIds.Enqueue(id); } MemoryBuffer memoryBuffer = this.tService.Fetch(); memoryBuffer.Write(bytes, index, length); memoryBuffer.Seek(0, SeekOrigin.Begin); this.tService.Send(id, memoryBuffer); long timeNow = TimeInfo.Instance.ClientFrameTime(); this.readWriteTime[id] = timeNow; } public int Recv(byte[] buffer, ref EndPoint endPoint) { return RecvNonAlloc(buffer, ref endPoint); } public int RecvNonAlloc(byte[] buffer, ref EndPoint endPoint) { (EndPoint e, MemoryBuffer memoryBuffer) = this.channelRecvDatas.Dequeue(); endPoint = e; int count = memoryBuffer.Read(buffer); this.tService.Recycle(memoryBuffer); return count; } public int Available() { return this.channelRecvDatas.Count; } public void Update() { // 检查长时间不读写的TChannel, 超时断开, 一次update检查10个 long timeNow = TimeInfo.Instance.ClientFrameTime(); const int MaxCheckNum = 10; int n = this.channelIds.Count < MaxCheckNum? this.channelIds.Count : MaxCheckNum; for (int i = 0; i < n; ++i) { long id = this.channelIds.Dequeue(); if (!this.readWriteTime.TryGetValue(id, out long rwTime)) { continue; } if (timeNow - rwTime > 30 * 1000) { this.OnError(id, ErrorCore.ERR_KcpReadWriteTimeout); continue; } this.channelIds.Enqueue(id); } this.tService.Update(); } public void Dispose() { this.tService?.Dispose(); } } }
ET/Unity/Assets/Scripts/Core/Network/IKcpTransport.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/IKcpTransport.cs", "repo_id": "ET", "token_count": 3157 }
100
using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; namespace ET { public enum NetworkProtocol { TCP, KCP, Websocket, UDP, } public class NetServices: Singleton<NetServices>, ISingletonAwake { private long idGenerator; public void Awake() { } // 这个因为是NetClientComponent中使用,不会与Accept冲突 public uint CreateConnectChannelId() { return RandomGenerator.RandUInt32(); } // 防止与内网进程号的ChannelId冲突,所以设置为一个大的随机数 private int acceptIdGenerator = int.MinValue; public uint CreateAcceptChannelId() { return (uint)Interlocked.Add(ref this.acceptIdGenerator, 1); } } }
ET/Unity/Assets/Scripts/Core/Network/NetServices.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/NetServices.cs", "repo_id": "ET", "token_count": 432 }
101
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; namespace ET { public enum TcpOp { StartSend, StartRecv, Connect, } public struct TArgs { public TcpOp Op; public long ChannelId; public SocketAsyncEventArgs SocketAsyncEventArgs; } public sealed class TService : AService { private readonly Dictionary<long, TChannel> idChannels = new(); private readonly SocketAsyncEventArgs innArgs = new(); private Socket acceptor; public ConcurrentQueue<TArgs> Queue = new(); public TService(AddressFamily addressFamily, ServiceType serviceType) { this.ServiceType = serviceType; } public TService(IPEndPoint ipEndPoint, ServiceType serviceType) { this.ServiceType = serviceType; this.acceptor = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // 容易出问题,先注释掉,按需开启 //this.acceptor.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); this.innArgs.Completed += this.OnComplete; try { this.acceptor.Bind(ipEndPoint); } catch (Exception e) { throw new Exception($"bind error: {ipEndPoint}", e); } this.acceptor.Listen(1000); this.AcceptAsync(); } private void OnComplete(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Accept: this.Queue.Enqueue(new TArgs() {SocketAsyncEventArgs = e}); break; default: throw new Exception($"socket error: {e.LastOperation}"); } } private void OnAcceptComplete(SocketError socketError, Socket acceptSocket) { if (this.acceptor == null) { return; } if (socketError != SocketError.Success) { Log.Error($"accept error {socketError}"); this.AcceptAsync(); return; } try { long id = NetServices.Instance.CreateAcceptChannelId(); TChannel channel = new TChannel(id, acceptSocket, this); this.idChannels.Add(channel.Id, channel); long channelId = channel.Id; this.AcceptCallback(channelId, channel.RemoteAddress); } catch (Exception e) { Log.Error(e); } // 开始新的accept this.AcceptAsync(); } private void AcceptAsync() { this.innArgs.AcceptSocket = null; if (this.acceptor.AcceptAsync(this.innArgs)) { return; } OnAcceptComplete(this.innArgs.SocketError, this.innArgs.AcceptSocket); } public override void Create(long id, IPEndPoint ipEndPoint) { if (this.idChannels.TryGetValue(id, out TChannel _)) { return; } TChannel channel = new(id, ipEndPoint, this); this.idChannels.Add(channel.Id, channel); } public TChannel Get(long id) { TChannel channel = null; this.idChannels.TryGetValue(id, out channel); return channel; } public override void Dispose() { base.Dispose(); this.acceptor?.Close(); this.acceptor = null; this.innArgs.Dispose(); foreach (long id in this.idChannels.Keys.ToArray()) { TChannel channel = this.idChannels[id]; channel.Dispose(); } this.idChannels.Clear(); } public override void Remove(long id, int error = 0) { if (this.idChannels.TryGetValue(id, out TChannel channel)) { channel.Error = error; channel.Dispose(); } this.idChannels.Remove(id); } public override void Send(long channelId, MemoryBuffer memoryBuffer) { try { TChannel aChannel = this.Get(channelId); if (aChannel == null) { this.ErrorCallback(channelId, ErrorCore.ERR_SendMessageNotFoundTChannel); return; } aChannel.Send(memoryBuffer); } catch (Exception e) { Log.Error(e); } } public override void Update() { while (true) { if (!this.Queue.TryDequeue(out var result)) { break; } SocketAsyncEventArgs e = result.SocketAsyncEventArgs; if (e == null) { switch (result.Op) { case TcpOp.StartSend: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.StartSend(); } break; } case TcpOp.StartRecv: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.StartRecv(); } break; } case TcpOp.Connect: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.ConnectAsync(); } break; } } continue; } switch (e.LastOperation) { case SocketAsyncOperation.Accept: { SocketError socketError = e.SocketError; Socket acceptSocket = e.AcceptSocket; this.OnAcceptComplete(socketError, acceptSocket); break; } case SocketAsyncOperation.Connect: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.OnConnectComplete(e); } break; } case SocketAsyncOperation.Disconnect: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.OnDisconnectComplete(e); } break; } case SocketAsyncOperation.Receive: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.OnRecvComplete(e); } break; } case SocketAsyncOperation.Send: { TChannel tChannel = this.Get(result.ChannelId); if (tChannel != null) { tChannel.OnSendComplete(e); } break; } default: throw new ArgumentOutOfRangeException($"{e.LastOperation}"); } } } public override bool IsDisposed() { return this.acceptor == null; } } }
ET/Unity/Assets/Scripts/Core/Network/TService.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/TService.cs", "repo_id": "ET", "token_count": 2647 }
102
fileFormatVersion: 2 guid: 90d2aa9a80bc74140bc36eef78a1a34e MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Object/ProtoObject.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Object/ProtoObject.cs.meta", "repo_id": "ET", "token_count": 95 }
103
using System; using System.Collections.Generic; namespace ET { public class UnOrderMultiMap<T, K>: Dictionary<T, List<K>> { public void Add(T t, K k) { List<K> list; this.TryGetValue(t, out list); if (list == null) { list = new List<K>(); base[t] = list; } list.Add(k); } public bool Remove(T t, K k) { List<K> list; this.TryGetValue(t, out list); if (list == null) { return false; } if (!list.Remove(k)) { return false; } if (list.Count == 0) { this.Remove(t); } return true; } /// <summary> /// 不返回内部的list,copy一份出来 /// </summary> /// <param name="t"></param> /// <returns></returns> public K[] GetAll(T t) { List<K> list; this.TryGetValue(t, out list); if (list == null) { return Array.Empty<K>(); } return list.ToArray(); } /// <summary> /// 返回内部的list /// </summary> /// <param name="t"></param> /// <returns></returns> public new List<K> this[T t] { get { List<K> list; this.TryGetValue(t, out list); return list; } } public K GetOne(T t) { List<K> list; this.TryGetValue(t, out list); if (list != null && list.Count > 0) { return list[0]; } return default(K); } public bool Contains(T t, K k) { List<K> list; this.TryGetValue(t, out list); if (list == null) { return false; } return list.Contains(k); } } }
ET/Unity/Assets/Scripts/Core/UnOrderMultiMap.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/UnOrderMultiMap.cs", "repo_id": "ET", "token_count": 745 }
104
fileFormatVersion: 2 guid: e502791ab03091f4b8bd9e6a3292dff2 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Actor/MessageDispatcher.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Actor/MessageDispatcher.cs.meta", "repo_id": "ET", "token_count": 96 }
105
namespace ET { public class InvokeAttribute: BaseAttribute { public long Type { get; } public InvokeAttribute(long type = 0) { this.Type = type; } } }
ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/InvokeAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/InvokeAttribute.cs", "repo_id": "ET", "token_count": 101 }
106
fileFormatVersion: 2 guid: 7267a4e71eb917547afb0bdd52d9a360 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Fiber/ThreadScheduler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Fiber/ThreadScheduler.cs.meta", "repo_id": "ET", "token_count": 95 }
107
fileFormatVersion: 2 guid: b0ae23f776aa91d40a8d8b6a21ba483f folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Options.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Options.meta", "repo_id": "ET", "token_count": 71 }
108
fileFormatVersion: 2 guid: 52a0058e2cd667648a8ba92689e0263c folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/AssetPostProcessor.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/AssetPostProcessor.meta", "repo_id": "ET", "token_count": 69 }
109
using System; using UnityEditor; namespace ET { [TypeDrawer] public class BoolTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (bool); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.Toggle(memberName, (bool) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/BoolTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/BoolTypeDrawer.cs", "repo_id": "ET", "token_count": 185 }
110
using System; using UnityEditor; namespace ET { [TypeDrawer] public class EnumTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type.IsEnum; } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { if (memberType == typeof (SceneType)) { string sceneType = EditorGUILayout.DelayedTextField(memberName, value.ToString()); return EnumHelper.FromString<SceneType>(sceneType); } if (memberType.IsDefined(typeof (FlagsAttribute), false)) { return EditorGUILayout.EnumFlagsField(memberName, (Enum) value); } return EditorGUILayout.EnumPopup(memberName, (Enum) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/EnumTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/EnumTypeDrawer.cs", "repo_id": "ET", "token_count": 410 }
111
using System; using Unity.Mathematics; using UnityEditor; using UnityEngine; namespace ET { [TypeDrawer] public class QuaternionTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (quaternion); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { Vector4 v = ((quaternion)value).value; return new quaternion(EditorGUILayout.Vector4Field(memberName, v)); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/QuaternionTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/QuaternionTypeDrawer.cs", "repo_id": "ET", "token_count": 229 }
112
fileFormatVersion: 2 guid: 10ce5e5130790b9468addf1a602cf8f0 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/GlobalConfigEditor.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/GlobalConfigEditor.meta", "repo_id": "ET", "token_count": 69 }
113