From fad06ae1e7b2140a52c6c9131c78603a3468e922 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Tue, 15 Oct 2024 23:42:57 -0700 Subject: [PATCH] Merge .inc files into headers (#7215) --- .../include/cameraserver/CameraServer.h | 17 +- .../include/cameraserver/CameraServer.inc | 33 - .../main/native/include/vision/VisionRunner.h | 27 +- .../native/include/vision/VisionRunner.inc | 36 - cscore/src/main/native/include/cscore_oo.h | 613 ++++++++++++++--- cscore/src/main/native/include/cscore_oo.inc | 649 ------------------ glass/src/lib/native/include/glass/Provider.h | 75 +- .../src/lib/native/include/glass/Provider.inc | 102 --- .../src/main/native/include/WSHalProviders.h | 19 +- .../main/native/include/WSHalProviders.inc | 34 - .../frc2/command/SwerveControllerCommand.h | 70 +- .../frc2/command/SwerveControllerCommand.inc | 114 --- .../frc/motorcontrol/MotorControllerGroup.h | 8 +- .../frc/motorcontrol/MotorControllerGroup.inc | 22 - .../frc/shuffleboard/ShuffleboardComponent.h | 28 +- .../shuffleboard/ShuffleboardComponent.inc | 47 -- .../frc/shuffleboard/SuppliedValueWidget.h | 1 - .../frc/smartdashboard/SendableChooser.h | 102 ++- .../frc/smartdashboard/SendableChooser.inc | 131 ---- .../src/main/native/include/wpinet/HttpUtil.h | 40 +- .../main/native/include/wpinet/HttpUtil.inc | 55 -- .../wpinet/HttpWebSocketServerConnection.h | 40 +- .../wpinet/HttpWebSocketServerConnection.inc | 57 -- .../main/native/include/wpi/circular_buffer.h | 51 +- .../native/include/wpi/circular_buffer.inc | 64 -- 25 files changed, 914 insertions(+), 1521 deletions(-) delete mode 100644 cameraserver/src/main/native/include/cameraserver/CameraServer.inc delete mode 100644 cameraserver/src/main/native/include/vision/VisionRunner.inc delete mode 100644 cscore/src/main/native/include/cscore_oo.inc delete mode 100644 glass/src/lib/native/include/glass/Provider.inc delete mode 100644 simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc delete mode 100644 wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.inc delete mode 100644 wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc delete mode 100644 wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc delete mode 100644 wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc delete mode 100644 wpinet/src/main/native/include/wpinet/HttpUtil.inc delete mode 100644 wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.inc delete mode 100644 wpiutil/src/main/native/include/wpi/circular_buffer.inc diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.h b/cameraserver/src/main/native/include/cameraserver/CameraServer.h index 0dfa97f178a..68f37f22b05 100644 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.h +++ b/cameraserver/src/main/native/include/cameraserver/CameraServer.h @@ -9,10 +9,10 @@ #include #include #include +#include #include -#include "cscore.h" #include "cscore_cv.h" namespace frc { @@ -130,7 +130,9 @@ class CameraServer { */ template [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] - static cs::AxisCamera AddAxisCamera(std::initializer_list hosts); + static cs::AxisCamera AddAxisCamera(std::initializer_list hosts) { + return AddAxisCamera("Axis Camera", hosts); + } /** * Adds an Axis IP camera. @@ -185,7 +187,14 @@ class CameraServer { template [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view name, - std::initializer_list hosts); + std::initializer_list hosts) { + std::vector vec; + vec.reserve(hosts.size()); + for (const auto& host : hosts) { + vec.emplace_back(host); + } + return AddAxisCamera(name, vec); + } WPI_UNIGNORE_DEPRECATED /** @@ -316,5 +325,3 @@ class CameraServer { }; } // namespace frc - -#include "cameraserver/CameraServer.inc" diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc deleted file mode 100644 index 5ae14f7f9a9..00000000000 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include - -#include "cameraserver/CameraServer.h" - -namespace frc { - -WPI_IGNORE_DEPRECATED -template -inline cs::AxisCamera CameraServer::AddAxisCamera( - std::initializer_list hosts) { - return AddAxisCamera("Axis Camera", hosts); -} - -template -inline cs::AxisCamera CameraServer::AddAxisCamera( - std::string_view name, std::initializer_list hosts) { - std::vector vec; - vec.reserve(hosts.size()); - for (const auto& host : hosts) { - vec.emplace_back(host); - } - return AddAxisCamera(name, vec); -} -WPI_UNIGNORE_DEPRECATED - -} // namespace frc diff --git a/cameraserver/src/main/native/include/vision/VisionRunner.h b/cameraserver/src/main/native/include/vision/VisionRunner.h index 6e6e93adfab..750d15797a3 100644 --- a/cameraserver/src/main/native/include/vision/VisionRunner.h +++ b/cameraserver/src/main/native/include/vision/VisionRunner.h @@ -8,7 +8,6 @@ #include #include -#include "cscore.h" #include "cscore_cv.h" #include "vision/VisionPipeline.h" @@ -81,17 +80,35 @@ class VisionRunnerBase { template class VisionRunner : public VisionRunnerBase { public: + /** + * Creates a new vision runner. It will take images from the {@code + * videoSource}, send them to the {@code pipeline}, and call the {@code + * listener} when the pipeline has finished to alert user code when it is safe + * to access the pipeline's outputs. + * + * @param videoSource The video source to use to supply images for the + * pipeline + * @param pipeline The vision pipeline to run + * @param listener A function to call after the pipeline has finished + * running + */ VisionRunner(cs::VideoSource videoSource, T* pipeline, - std::function listener); + std::function listener) + : VisionRunnerBase(videoSource), + m_pipeline(pipeline), + m_listener(listener) {} + virtual ~VisionRunner() = default; protected: - void DoProcess(cv::Mat& image) override; + void DoProcess(cv::Mat& image) override { + m_pipeline->Process(image); + m_listener(*m_pipeline); + } private: T* m_pipeline; std::function m_listener; }; -} // namespace frc -#include "VisionRunner.inc" +} // namespace frc diff --git a/cameraserver/src/main/native/include/vision/VisionRunner.inc b/cameraserver/src/main/native/include/vision/VisionRunner.inc deleted file mode 100644 index 56cfe695e40..00000000000 --- a/cameraserver/src/main/native/include/vision/VisionRunner.inc +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include - -#include "vision/VisionRunner.h" - -namespace frc { - -/** - * Creates a new vision runner. It will take images from the {@code - * videoSource}, send them to the {@code pipeline}, and call the {@code - * listener} when the pipeline has finished to alert user code when it is safe - * to access the pipeline's outputs. - * - * @param videoSource The video source to use to supply images for the pipeline - * @param pipeline The vision pipeline to run - * @param listener A function to call after the pipeline has finished running - */ -template -VisionRunner::VisionRunner(cs::VideoSource videoSource, T* pipeline, - std::function listener) - : VisionRunnerBase(videoSource), - m_pipeline(pipeline), - m_listener(listener) {} - -template -void VisionRunner::DoProcess(cv::Mat& image) { - m_pipeline->Process(image); - m_listener(*m_pipeline); -} - -} // namespace frc diff --git a/cscore/src/main/native/include/cscore_oo.h b/cscore/src/main/native/include/cscore_oo.h index 8fb8f4be32f..2c6d64171af 100644 --- a/cscore/src/main/native/include/cscore_oo.h +++ b/cscore/src/main/native/include/cscore_oo.h @@ -13,6 +13,8 @@ #include #include +#include + #include "cscore_cpp.h" namespace cs { @@ -63,7 +65,10 @@ class VideoProperty { * * @return Property name. */ - std::string GetName() const; + std::string GetName() const { + m_status = 0; + return GetPropertyName(m_handle, &m_status); + } /** * Returns property kind. @@ -112,42 +117,60 @@ class VideoProperty { * * @return Property value. */ - int Get() const; + int Get() const { + m_status = 0; + return GetProperty(m_handle, &m_status); + } /** * Sets property value. * * @param value Property value. */ - void Set(int value); + void Set(int value) { + m_status = 0; + SetProperty(m_handle, value, &m_status); + } /** * Returns property minimum value. * * @return Property minimum value. */ - int GetMin() const; + int GetMin() const { + m_status = 0; + return GetPropertyMin(m_handle, &m_status); + } /** * Returns property maximum value. * * @return Property maximum value. */ - int GetMax() const; + int GetMax() const { + m_status = 0; + return GetPropertyMax(m_handle, &m_status); + } /** * Returns property step size. * * @return Property step size. */ - int GetStep() const; + int GetStep() const { + m_status = 0; + return GetPropertyStep(m_handle, &m_status); + } /** * Returns property default value. * * @return Property default value. */ - int GetDefault() const; + int GetDefault() const { + m_status = 0; + return GetPropertyDefault(m_handle, &m_status); + } /** * Returns the string property value. @@ -156,7 +179,10 @@ class VideoProperty { * * @return The string property value. */ - std::string GetString() const; + std::string GetString() const { + m_status = 0; + return GetStringProperty(m_handle, &m_status); + } /** * Returns the string property value as a reference to the given buffer. @@ -166,7 +192,10 @@ class VideoProperty { * @param buf The backing storage to which to write the property value. * @return The string property value as a reference to the given buffer. */ - std::string_view GetString(wpi::SmallVectorImpl& buf) const; + std::string_view GetString(wpi::SmallVectorImpl& buf) const { + m_status = 0; + return GetStringProperty(m_handle, buf, &m_status); + } /** * Sets the string property value. @@ -175,7 +204,10 @@ class VideoProperty { * * @param value String property value. */ - void SetString(std::string_view value); + void SetString(std::string_view value) { + m_status = 0; + SetStringProperty(m_handle, value, &m_status); + } /** * Returns the possible values for the enum property value. @@ -184,7 +216,10 @@ class VideoProperty { * * @return The possible values for the enum property value. */ - std::vector GetChoices() const; + std::vector GetChoices() const { + m_status = 0; + return GetEnumPropertyChoices(m_handle, &m_status); + } /** * Returns the last status. @@ -194,8 +229,18 @@ class VideoProperty { CS_Status GetLastStatus() const { return m_status; } private: - explicit VideoProperty(CS_Property handle); - VideoProperty(CS_Property handle, Kind kind); + explicit VideoProperty(CS_Property handle) { + m_status = 0; + if (handle == 0) { + m_kind = kNone; + } else { + m_kind = static_cast( + static_cast(GetPropertyKind(handle, &m_status))); + } + } + + VideoProperty(CS_Property handle, Kind kind) + : m_handle(handle), m_kind(kind) {} mutable CS_Status m_status{0}; CS_Property m_handle{0}; @@ -248,10 +293,27 @@ class VideoSource { }; VideoSource() noexcept = default; - VideoSource(const VideoSource& source); - VideoSource(VideoSource&& other) noexcept; - VideoSource& operator=(VideoSource other) noexcept; - ~VideoSource(); + + VideoSource(const VideoSource& source) + : m_handle( + source.m_handle == 0 ? 0 : CopySource(source.m_handle, &m_status)) { + } + + VideoSource(VideoSource&& other) noexcept : VideoSource() { + swap(*this, other); + } + + VideoSource& operator=(VideoSource other) noexcept { + swap(*this, other); + return *this; + } + + ~VideoSource() { + m_status = 0; + if (m_handle != 0) { + ReleaseSource(m_handle, &m_status); + } + } explicit operator bool() const { return m_handle != 0; } @@ -264,18 +326,27 @@ class VideoSource { /** * Get the kind of the source. */ - Kind GetKind() const; + Kind GetKind() const { + m_status = 0; + return static_cast(GetSourceKind(m_handle, &m_status)); + } /** * Get the name of the source. The name is an arbitrary identifier * provided when the source is created, and should be unique. */ - std::string GetName() const; + std::string GetName() const { + m_status = 0; + return GetSourceName(m_handle, &m_status); + } /** * Get the source description. This is source-kind specific. */ - std::string GetDescription() const; + std::string GetDescription() const { + m_status = 0; + return GetSourceDescription(m_handle, &m_status); + } /** * Get the last time a frame was captured. @@ -283,7 +354,10 @@ class VideoSource { * * @return Time in 1 us increments. */ - uint64_t GetLastFrameTime() const; + uint64_t GetLastFrameTime() const { + m_status = 0; + return GetSourceLastFrameTime(m_handle, &m_status); + } /** * Sets the connection strategy. By default, the source will automatically @@ -294,12 +368,21 @@ class VideoSource { * * @param strategy connection strategy (auto, keep open, or force close) */ - void SetConnectionStrategy(ConnectionStrategy strategy); + void SetConnectionStrategy(ConnectionStrategy strategy) { + m_status = 0; + SetSourceConnectionStrategy( + m_handle, + static_cast(static_cast(strategy)), + &m_status); + } /** * Is the source currently connected to whatever is providing the images? */ - bool IsConnected() const; + bool IsConnected() const { + m_status = 0; + return IsSourceConnected(m_handle, &m_status); + } /** * Gets source enable status. This is determined with a combination of @@ -307,7 +390,10 @@ class VideoSource { * * @return True if enabled, false otherwise. */ - bool IsEnabled() const; + bool IsEnabled() const { + m_status = 0; + return IsSourceEnabled(m_handle, &m_status); + } /** Get a property. * @@ -315,7 +401,10 @@ class VideoSource { * @return Property contents (of kind Property::kNone if no property with * the given name exists) */ - VideoProperty GetProperty(std::string_view name); + VideoProperty GetProperty(std::string_view name) { + m_status = 0; + return VideoProperty{GetSourceProperty(m_handle, name, &m_status)}; + } /** * Enumerate all properties of this source. @@ -325,14 +414,20 @@ class VideoSource { /** * Get the current video mode. */ - VideoMode GetVideoMode() const; + VideoMode GetVideoMode() const { + m_status = 0; + return GetSourceVideoMode(m_handle, &m_status); + } /** * Set the video mode. * * @param mode Video mode */ - bool SetVideoMode(const VideoMode& mode); + bool SetVideoMode(const VideoMode& mode) { + m_status = 0; + return SetSourceVideoMode(m_handle, mode, &m_status); + } /** * Set the video mode. @@ -344,7 +439,11 @@ class VideoSource { * @return True if set successfully */ bool SetVideoMode(VideoMode::PixelFormat pixelFormat, int width, int height, - int fps); + int fps) { + m_status = 0; + return SetSourceVideoMode( + m_handle, VideoMode{pixelFormat, width, height, fps}, &m_status); + } /** * Set the pixel format. @@ -352,7 +451,10 @@ class VideoSource { * @param pixelFormat desired pixel format * @return True if set successfully */ - bool SetPixelFormat(VideoMode::PixelFormat pixelFormat); + bool SetPixelFormat(VideoMode::PixelFormat pixelFormat) { + m_status = 0; + return SetSourcePixelFormat(m_handle, pixelFormat, &m_status); + } /** * Set the resolution. @@ -361,7 +463,10 @@ class VideoSource { * @param height desired height * @return True if set successfully */ - bool SetResolution(int width, int height); + bool SetResolution(int width, int height) { + m_status = 0; + return SetSourceResolution(m_handle, width, height, &m_status); + } /** * Set the frames per second (FPS). @@ -369,7 +474,10 @@ class VideoSource { * @param fps desired FPS * @return True if set successfully */ - bool SetFPS(int fps); + bool SetFPS(int fps) { + m_status = 0; + return SetSourceFPS(m_handle, fps, &m_status); + } /** * Set video mode and properties from a JSON configuration string. @@ -397,7 +505,10 @@ class VideoSource { * @param config configuration * @return True if set successfully */ - bool SetConfigJson(std::string_view config); + bool SetConfigJson(std::string_view config) { + m_status = 0; + return SetSourceConfigJson(m_handle, config, &m_status); + } /** * Set video mode and properties from a JSON configuration object. @@ -405,14 +516,20 @@ class VideoSource { * @param config configuration * @return True if set successfully */ - bool SetConfigJson(const wpi::json& config); + bool SetConfigJson(const wpi::json& config) { + m_status = 0; + return SetSourceConfigJson(m_handle, config, &m_status); + } /** * Get a JSON configuration string. * * @return JSON configuration string */ - std::string GetConfigJson() const; + std::string GetConfigJson() const { + m_status = 0; + return GetSourceConfigJson(m_handle, &m_status); + } /** * Get a JSON configuration object. @@ -428,7 +545,11 @@ class VideoSource { * * @return Actual FPS averaged over the telemetry period. */ - double GetActualFPS() const; + double GetActualFPS() const { + m_status = 0; + return cs::GetTelemetryAverageValue(m_handle, CS_SOURCE_FRAMES_RECEIVED, + &m_status); + } /** * Get the data rate (in bytes per second). @@ -437,12 +558,19 @@ class VideoSource { * * @return Data rate averaged over the telemetry period. */ - double GetActualDataRate() const; + double GetActualDataRate() const { + m_status = 0; + return cs::GetTelemetryAverageValue(m_handle, CS_SOURCE_BYTES_RECEIVED, + &m_status); + } /** * Enumerate all known video modes for this source. */ - std::vector EnumerateVideoModes() const; + std::vector EnumerateVideoModes() const { + CS_Status status = 0; + return EnumerateSourceVideoModes(m_handle, &status); + } CS_Status GetLastStatus() const { return m_status; } @@ -501,42 +629,66 @@ class VideoCamera : public VideoSource { /** * Set the brightness, as a percentage (0-100). */ - void SetBrightness(int brightness); + void SetBrightness(int brightness) { + m_status = 0; + SetCameraBrightness(m_handle, brightness, &m_status); + } /** * Get the brightness, as a percentage (0-100). */ - int GetBrightness(); + int GetBrightness() { + m_status = 0; + return GetCameraBrightness(m_handle, &m_status); + } /** * Set the white balance to auto. */ - void SetWhiteBalanceAuto(); + void SetWhiteBalanceAuto() { + m_status = 0; + SetCameraWhiteBalanceAuto(m_handle, &m_status); + } /** * Set the white balance to hold current. */ - void SetWhiteBalanceHoldCurrent(); + void SetWhiteBalanceHoldCurrent() { + m_status = 0; + SetCameraWhiteBalanceHoldCurrent(m_handle, &m_status); + } /** * Set the white balance to manual, with specified color temperature. */ - void SetWhiteBalanceManual(int value); + void SetWhiteBalanceManual(int value) { + m_status = 0; + SetCameraWhiteBalanceManual(m_handle, value, &m_status); + } /** * Set the exposure to auto aperture. */ - void SetExposureAuto(); + void SetExposureAuto() { + m_status = 0; + SetCameraExposureAuto(m_handle, &m_status); + } /** * Set the exposure to hold current. */ - void SetExposureHoldCurrent(); + void SetExposureHoldCurrent() { + m_status = 0; + SetCameraExposureHoldCurrent(m_handle, &m_status); + } /** * Set the exposure to manual, as a percentage (0-100). */ - void SetExposureManual(int value); + void SetExposureManual(int value) { + m_status = 0; + SetCameraExposureManual(m_handle, value, &m_status); + } protected: explicit VideoCamera(CS_Source handle) : VideoSource(handle) {} @@ -555,7 +707,9 @@ class UsbCamera : public VideoCamera { * @param name Source name (arbitrary unique identifier) * @param dev Device number (e.g. 0 for /dev/video0) */ - UsbCamera(std::string_view name, int dev); + UsbCamera(std::string_view name, int dev) { + m_handle = CreateUsbCameraDev(name, dev, &m_status); + } /** * Create a source for a USB camera based on device path. @@ -563,36 +717,54 @@ class UsbCamera : public VideoCamera { * @param name Source name (arbitrary unique identifier) * @param path Path to device (e.g. "/dev/video0" on Linux) */ - UsbCamera(std::string_view name, std::string_view path); + UsbCamera(std::string_view name, std::string_view path) { + m_handle = CreateUsbCameraPath(name, path, &m_status); + } /** * Enumerate USB cameras on the local system. * * @return Vector of USB camera information (one for each camera) */ - static std::vector EnumerateUsbCameras(); + static std::vector EnumerateUsbCameras() { + CS_Status status = 0; + return ::cs::EnumerateUsbCameras(&status); + } /** * Change the path to the device. */ - void SetPath(std::string_view path); + void SetPath(std::string_view path) { + m_status = 0; + return ::cs::SetUsbCameraPath(m_handle, path, &m_status); + } /** * Get the path to the device. */ - std::string GetPath() const; + std::string GetPath() const { + m_status = 0; + return ::cs::GetUsbCameraPath(m_handle, &m_status); + } /** * Get the full camera information for the device. */ - UsbCameraInfo GetInfo() const; + UsbCameraInfo GetInfo() const { + m_status = 0; + return ::cs::GetUsbCameraInfo(m_handle, &m_status); + } /** * Set how verbose the camera connection messages are. * * @param level 0=don't display Connecting message, 1=do display message */ - void SetConnectVerbose(int level); + void SetConnectVerbose(int level) { + m_status = 0; + SetProperty(GetSourceProperty(m_handle, "connect_verbose", &m_status), + level, &m_status); + } }; /** @@ -622,7 +794,11 @@ class HttpCamera : public VideoCamera { * @param kind Camera kind (e.g. kAxis) */ HttpCamera(std::string_view name, std::string_view url, - HttpCameraKind kind = kUnknown); + HttpCameraKind kind = kUnknown) { + m_handle = CreateHttpCamera( + name, url, static_cast(static_cast(kind)), + &m_status); + } /** * Create a source for a MJPEG-over-HTTP (IP) camera. @@ -632,7 +808,11 @@ class HttpCamera : public VideoCamera { * @param kind Camera kind (e.g. kAxis) */ HttpCamera(std::string_view name, const char* url, - HttpCameraKind kind = kUnknown); + HttpCameraKind kind = kUnknown) { + m_handle = CreateHttpCamera( + name, url, static_cast(static_cast(kind)), + &m_status); + } /** * Create a source for a MJPEG-over-HTTP (IP) camera. @@ -642,7 +822,8 @@ class HttpCamera : public VideoCamera { * @param kind Camera kind (e.g. kAxis) */ HttpCamera(std::string_view name, const std::string& url, - HttpCameraKind kind = kUnknown); + HttpCameraKind kind = kUnknown) + : HttpCamera(name, std::string_view{url}, kind) {} /** * Create a source for a MJPEG-over-HTTP (IP) camera. @@ -652,7 +833,11 @@ class HttpCamera : public VideoCamera { * @param kind Camera kind (e.g. kAxis) */ HttpCamera(std::string_view name, std::span urls, - HttpCameraKind kind = kUnknown); + HttpCameraKind kind = kUnknown) { + m_handle = CreateHttpCamera( + name, urls, static_cast(static_cast(kind)), + &m_status); + } /** * Create a source for a MJPEG-over-HTTP (IP) camera. @@ -663,7 +848,16 @@ class HttpCamera : public VideoCamera { */ template HttpCamera(std::string_view name, std::initializer_list urls, - HttpCameraKind kind = kUnknown); + HttpCameraKind kind = kUnknown) { + std::vector vec; + vec.reserve(urls.size()); + for (const auto& url : urls) { + vec.emplace_back(url); + } + m_handle = CreateHttpCamera( + name, vec, static_cast(static_cast(kind)), + &m_status); + } /** * Get the kind of HTTP camera. @@ -671,23 +865,41 @@ class HttpCamera : public VideoCamera { *

Autodetection can result in returning a different value than the camera * was created with. */ - HttpCameraKind GetHttpCameraKind() const; + HttpCameraKind GetHttpCameraKind() const { + m_status = 0; + return static_cast( + static_cast(::cs::GetHttpCameraKind(m_handle, &m_status))); + } /** * Change the URLs used to connect to the camera. */ - void SetUrls(std::span urls); + void SetUrls(std::span urls) { + m_status = 0; + ::cs::SetHttpCameraUrls(m_handle, urls, &m_status); + } /** * Change the URLs used to connect to the camera. */ template - void SetUrls(std::initializer_list urls); + void SetUrls(std::initializer_list urls) { + std::vector vec; + vec.reserve(urls.size()); + for (const auto& url : urls) { + vec.emplace_back(url); + } + m_status = 0; + ::cs::SetHttpCameraUrls(m_handle, vec, &m_status); + } /** * Get the URLs used to connect to the camera. */ - std::vector GetUrls() const; + std::vector GetUrls() const { + m_status = 0; + return ::cs::GetHttpCameraUrls(m_handle, &m_status); + } }; /** @@ -697,9 +909,26 @@ class HttpCamera : public VideoCamera { */ class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { static std::string HostToUrl(std::string_view host); - static std::vector HostToUrl(std::span hosts); + + static std::vector HostToUrl( + std::span hosts) { + std::vector rv; + rv.reserve(hosts.size()); + for (const auto& host : hosts) { + rv.emplace_back(HostToUrl(std::string_view{host})); + } + return rv; + } + template - static std::vector HostToUrl(std::initializer_list hosts); + static std::vector HostToUrl(std::initializer_list hosts) { + std::vector rv; + rv.reserve(hosts.size()); + for (const auto& host : hosts) { + rv.emplace_back(HostToUrl(std::string_view{host})); + } + return rv; + } public: /** @@ -708,7 +937,8 @@ class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { * @param name Source name (arbitrary unique identifier) * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - AxisCamera(std::string_view name, std::string_view host); + AxisCamera(std::string_view name, std::string_view host) + : HttpCamera(name, HostToUrl(host), kAxis) {} /** * Create a source for an Axis IP camera. @@ -716,7 +946,8 @@ class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { * @param name Source name (arbitrary unique identifier) * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - AxisCamera(std::string_view name, const char* host); + AxisCamera(std::string_view name, const char* host) + : HttpCamera(name, HostToUrl(host), kAxis) {} /** * Create a source for an Axis IP camera. @@ -724,7 +955,8 @@ class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { * @param name Source name (arbitrary unique identifier) * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - AxisCamera(std::string_view name, const std::string& host); + AxisCamera(std::string_view name, const std::string& host) + : HttpCamera(name, HostToUrl(std::string_view{host}), kAxis) {} /** * Create a source for an Axis IP camera. @@ -732,7 +964,8 @@ class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { * @param name Source name (arbitrary unique identifier) * @param hosts Array of Camera host IPs/DNS names */ - AxisCamera(std::string_view name, std::span hosts); + AxisCamera(std::string_view name, std::span hosts) + : HttpCamera(name, HostToUrl(hosts), kAxis) {} /** * Create a source for an Axis IP camera. @@ -741,7 +974,8 @@ class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { * @param hosts Array of Camera host IPs/DNS names */ template - AxisCamera(std::string_view name, std::initializer_list hosts); + AxisCamera(std::string_view name, std::initializer_list hosts) + : HttpCamera(name, HostToUrl(hosts), kAxis) {} }; /** @@ -758,21 +992,30 @@ class ImageSource : public VideoSource { * * @param msg Notification message. */ - void NotifyError(std::string_view msg); + void NotifyError(std::string_view msg) { + m_status = 0; + NotifySourceError(m_handle, msg, &m_status); + } /** * Set source connection status. Defaults to true. * * @param connected True for connected, false for disconnected */ - void SetConnected(bool connected); + void SetConnected(bool connected) { + m_status = 0; + SetSourceConnected(m_handle, connected, &m_status); + } /** * Set source description. * * @param description Description */ - void SetDescription(std::string_view description); + void SetDescription(std::string_view description) { + m_status = 0; + SetSourceDescription(m_handle, description, &m_status); + } /** * Create a property. @@ -788,7 +1031,12 @@ class ImageSource : public VideoSource { */ VideoProperty CreateProperty(std::string_view name, VideoProperty::Kind kind, int minimum, int maximum, int step, - int defaultValue, int value); + int defaultValue, int value) { + m_status = 0; + return VideoProperty{CreateSourceProperty( + m_handle, name, static_cast(static_cast(kind)), + minimum, maximum, step, defaultValue, value, &m_status)}; + } /** * Create an integer property. @@ -803,7 +1051,14 @@ class ImageSource : public VideoSource { */ VideoProperty CreateIntegerProperty(std::string_view name, int minimum, int maximum, int step, int defaultValue, - int value); + int value) { + m_status = 0; + return VideoProperty{CreateSourceProperty( + m_handle, name, + static_cast( + static_cast(VideoProperty::Kind::kInteger)), + minimum, maximum, step, defaultValue, value, &m_status)}; + } /** * Create a boolean property. @@ -814,7 +1069,14 @@ class ImageSource : public VideoSource { * @return Property */ VideoProperty CreateBooleanProperty(std::string_view name, bool defaultValue, - bool value); + bool value) { + m_status = 0; + return VideoProperty{CreateSourceProperty( + m_handle, name, + static_cast( + static_cast(VideoProperty::Kind::kBoolean)), + 0, 1, 1, defaultValue ? 1 : 0, value ? 1 : 0, &m_status)}; + } /** * Create a string property. @@ -824,7 +1086,16 @@ class ImageSource : public VideoSource { * @return Property */ VideoProperty CreateStringProperty(std::string_view name, - std::string_view value); + std::string_view value) { + m_status = 0; + auto prop = VideoProperty{CreateSourceProperty( + m_handle, name, + static_cast( + static_cast(VideoProperty::Kind::kString)), + 0, 0, 0, 0, 0, &m_status)}; + prop.SetString(value); + return prop; + } /** * Configure enum property choices. @@ -833,7 +1104,11 @@ class ImageSource : public VideoSource { * @param choices Choices */ void SetEnumPropertyChoices(const VideoProperty& property, - std::span choices); + std::span choices) { + m_status = 0; + SetSourceEnumPropertyChoices(m_handle, property.m_handle, choices, + &m_status); + } /** * Configure enum property choices. @@ -843,7 +1118,15 @@ class ImageSource : public VideoSource { */ template void SetEnumPropertyChoices(const VideoProperty& property, - std::initializer_list choices); + std::initializer_list choices) { + std::vector vec; + vec.reserve(choices.size()); + for (const auto& choice : choices) { + vec.emplace_back(choice); + } + m_status = 0; + SetSourceEnumPropertyChoices(m_handle, property.m_handle, vec, &m_status); + } }; /** @@ -866,10 +1149,23 @@ class VideoSink { }; VideoSink() noexcept = default; - VideoSink(const VideoSink& sink); - VideoSink(VideoSink&& sink) noexcept; - VideoSink& operator=(VideoSink other) noexcept; - ~VideoSink(); + + VideoSink(const VideoSink& sink) + : m_handle(sink.m_handle == 0 ? 0 : CopySink(sink.m_handle, &m_status)) {} + + VideoSink(VideoSink&& other) noexcept : VideoSink() { swap(*this, other); } + + VideoSink& operator=(VideoSink other) noexcept { + swap(*this, other); + return *this; + } + + ~VideoSink() { + m_status = 0; + if (m_handle != 0) { + ReleaseSink(m_handle, &m_status); + } + } /** * Returns true if the VideoSink is valid. @@ -892,18 +1188,27 @@ class VideoSink { /** * Get the kind of the sink. */ - Kind GetKind() const; + Kind GetKind() const { + m_status = 0; + return static_cast(GetSinkKind(m_handle, &m_status)); + } /** * Get the name of the sink. The name is an arbitrary identifier * provided when the sink is created, and should be unique. */ - std::string GetName() const; + std::string GetName() const { + m_status = 0; + return GetSinkName(m_handle, &m_status); + } /** * Get the sink description. This is sink-kind specific. */ - std::string GetDescription() const; + std::string GetDescription() const { + m_status = 0; + return GetSinkDescription(m_handle, &m_status); + } /** * Get a property of the sink. @@ -912,7 +1217,10 @@ class VideoSink { * @return Property (kind Property::kNone if no property with * the given name exists) */ - VideoProperty GetProperty(std::string_view name); + VideoProperty GetProperty(std::string_view name) { + m_status = 0; + return VideoProperty{GetSinkProperty(m_handle, name, &m_status)}; + } /** * Enumerate all properties of this sink. @@ -938,7 +1246,10 @@ class VideoSink { * @param config configuration * @return True if set successfully */ - bool SetConfigJson(std::string_view config); + bool SetConfigJson(std::string_view config) { + m_status = 0; + return SetSinkConfigJson(m_handle, config, &m_status); + } /** * Set properties from a JSON configuration object. @@ -946,14 +1257,20 @@ class VideoSink { * @param config configuration * @return True if set successfully */ - bool SetConfigJson(const wpi::json& config); + bool SetConfigJson(const wpi::json& config) { + m_status = 0; + return SetSinkConfigJson(m_handle, config, &m_status); + } /** * Get a JSON configuration string. * * @return JSON configuration string */ - std::string GetConfigJson() const; + std::string GetConfigJson() const { + m_status = 0; + return GetSinkConfigJson(m_handle, &m_status); + } /** * Get a JSON configuration object. @@ -969,14 +1286,25 @@ class VideoSink { * * @param source Source */ - void SetSource(VideoSource source); + void SetSource(VideoSource source) { + m_status = 0; + if (!source) { + SetSinkSource(m_handle, 0, &m_status); + } else { + SetSinkSource(m_handle, source.m_handle, &m_status); + } + } /** * Get the connected source. * * @return Connected source (empty if none connected). */ - VideoSource GetSource() const; + VideoSource GetSource() const { + m_status = 0; + auto handle = GetSinkSource(m_handle, &m_status); + return VideoSource{handle == 0 ? 0 : CopySource(handle, &m_status)}; + } /** * Get a property of the associated source. @@ -985,7 +1313,10 @@ class VideoSink { * @return Property (kind Property::kNone if no property with * the given name exists or no source connected) */ - VideoProperty GetSourceProperty(std::string_view name); + VideoProperty GetSourceProperty(std::string_view name) { + m_status = 0; + return VideoProperty{GetSinkSourceProperty(m_handle, name, &m_status)}; + } CS_Status GetLastStatus() const { return m_status; } @@ -1023,7 +1354,9 @@ class MjpegServer : public VideoSink { * @param listenAddress TCP listen address (empty string for all addresses) * @param port TCP port number */ - MjpegServer(std::string_view name, std::string_view listenAddress, int port); + MjpegServer(std::string_view name, std::string_view listenAddress, int port) { + m_handle = CreateMjpegServer(name, listenAddress, port, &m_status); + } /** * Create a MJPEG-over-HTTP server sink. @@ -1036,12 +1369,18 @@ class MjpegServer : public VideoSink { /** * Get the listen address of the server. */ - std::string GetListenAddress() const; + std::string GetListenAddress() const { + m_status = 0; + return cs::GetMjpegServerListenAddress(m_handle, &m_status); + } /** * Get the port number of the server. */ - int GetPort() const; + int GetPort() const { + m_status = 0; + return cs::GetMjpegServerPort(m_handle, &m_status); + } /** * Set the stream resolution for clients that don't specify it. @@ -1057,7 +1396,13 @@ class MjpegServer : public VideoSink { * @param width width, 0 for unspecified * @param height height, 0 for unspecified */ - void SetResolution(int width, int height); + void SetResolution(int width, int height) { + m_status = 0; + SetProperty(GetSinkProperty(m_handle, "width", &m_status), width, + &m_status); + SetProperty(GetSinkProperty(m_handle, "height", &m_status), height, + &m_status); + } /** * Set the stream frames per second (FPS) for clients that don't specify it. @@ -1066,7 +1411,10 @@ class MjpegServer : public VideoSink { * * @param fps FPS, 0 for unspecified */ - void SetFPS(int fps); + void SetFPS(int fps) { + m_status = 0; + SetProperty(GetSinkProperty(m_handle, "fps", &m_status), fps, &m_status); + } /** * Set the compression for clients that don't specify it. @@ -1077,7 +1425,11 @@ class MjpegServer : public VideoSink { * * @param quality JPEG compression quality (0-100), -1 for unspecified */ - void SetCompression(int quality); + void SetCompression(int quality) { + m_status = 0; + SetProperty(GetSinkProperty(m_handle, "compression", &m_status), quality, + &m_status); + } /** * Set the default compression used for non-MJPEG sources. If not set, @@ -1086,7 +1438,11 @@ class MjpegServer : public VideoSink { * * @param quality JPEG compression quality (0-100) */ - void SetDefaultCompression(int quality); + void SetDefaultCompression(int quality) { + m_status = 0; + SetProperty(GetSinkProperty(m_handle, "default_compression", &m_status), + quality, &m_status); + } }; /** @@ -1102,13 +1458,19 @@ class ImageSink : public VideoSink { * * @param description Description */ - void SetDescription(std::string_view description); + void SetDescription(std::string_view description) { + m_status = 0; + SetSinkDescription(m_handle, description, &m_status); + } /** * Get error string. Call this if WaitForFrame() returns 0 to determine * what the error is. */ - std::string GetError() const; + std::string GetError() const { + m_status = 0; + return GetSinkError(m_handle, &m_status); + } /** * Enable or disable getting new frames. @@ -1117,7 +1479,10 @@ class ImageSink : public VideoSink { * be called and WaitForFrame() to not return. This can be used to save * processor resources when frames are not needed. */ - void SetEnabled(bool enabled); + void SetEnabled(bool enabled) { + m_status = 0; + SetSinkEnabled(m_handle, enabled, &m_status); + } }; /** @@ -1130,21 +1495,31 @@ class VideoEvent : public RawEvent { * * @return The source associated with the event (if any). */ - VideoSource GetSource() const; + VideoSource GetSource() const { + CS_Status status = 0; + return VideoSource{sourceHandle == 0 ? 0 + : CopySource(sourceHandle, &status)}; + } /** * Returns the sink associated with the event (if any). * * @return The sink associated with the event (if any). */ - VideoSink GetSink() const; + VideoSink GetSink() const { + CS_Status status = 0; + return VideoSink{sinkHandle == 0 ? 0 : CopySink(sinkHandle, &status)}; + } /** * Returns the property associated with the event (if any). * * @return The property associated with the event (if any). */ - VideoProperty GetProperty() const; + VideoProperty GetProperty() const { + return VideoProperty{propertyHandle, + static_cast(propertyKind)}; + } }; /** @@ -1164,13 +1539,33 @@ class VideoListener { * a representative set of events for the current library state. */ VideoListener(std::function callback, - int eventMask, bool immediateNotify); + int eventMask, bool immediateNotify) { + CS_Status status = 0; + m_handle = AddListener( + [=](const RawEvent& event) { + callback(static_cast(event)); + }, + eventMask, immediateNotify, &status); + } VideoListener(const VideoListener&) = delete; VideoListener& operator=(const VideoListener&) = delete; - VideoListener(VideoListener&& other) noexcept; - VideoListener& operator=(VideoListener&& other) noexcept; - ~VideoListener(); + + VideoListener(VideoListener&& other) noexcept : VideoListener() { + swap(*this, other); + } + + VideoListener& operator=(VideoListener&& other) noexcept { + swap(*this, other); + return *this; + } + + ~VideoListener() { + CS_Status status = 0; + if (m_handle != 0) { + RemoveListener(m_handle, &status); + } + } friend void swap(VideoListener& first, VideoListener& second) noexcept { using std::swap; @@ -1185,6 +1580,4 @@ class VideoListener { } // namespace cs -#include "cscore_oo.inc" - #endif // CSCORE_CSCORE_OO_H_ diff --git a/cscore/src/main/native/include/cscore_oo.inc b/cscore/src/main/native/include/cscore_oo.inc deleted file mode 100644 index 20960f20e65..00000000000 --- a/cscore/src/main/native/include/cscore_oo.inc +++ /dev/null @@ -1,649 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#ifndef CSCORE_CSCORE_OO_INC_ -#define CSCORE_CSCORE_OO_INC_ - -#include -#include -#include -#include -#include - -#include - -#include "cscore_oo.h" - -namespace cs { - -inline std::string VideoProperty::GetName() const { - m_status = 0; - return GetPropertyName(m_handle, &m_status); -} - -inline int VideoProperty::Get() const { - m_status = 0; - return GetProperty(m_handle, &m_status); -} - -inline void VideoProperty::Set(int value) { - m_status = 0; - SetProperty(m_handle, value, &m_status); -} - -inline int VideoProperty::GetMin() const { - m_status = 0; - return GetPropertyMin(m_handle, &m_status); -} - -inline int VideoProperty::GetMax() const { - m_status = 0; - return GetPropertyMax(m_handle, &m_status); -} - -inline int VideoProperty::GetStep() const { - m_status = 0; - return GetPropertyStep(m_handle, &m_status); -} - -inline int VideoProperty::GetDefault() const { - m_status = 0; - return GetPropertyDefault(m_handle, &m_status); -} - -inline std::string VideoProperty::GetString() const { - m_status = 0; - return GetStringProperty(m_handle, &m_status); -} - -inline std::string_view VideoProperty::GetString( - wpi::SmallVectorImpl& buf) const { - m_status = 0; - return GetStringProperty(m_handle, buf, &m_status); -} - -inline void VideoProperty::SetString(std::string_view value) { - m_status = 0; - SetStringProperty(m_handle, value, &m_status); -} - -inline std::vector VideoProperty::GetChoices() const { - m_status = 0; - return GetEnumPropertyChoices(m_handle, &m_status); -} - -inline VideoProperty::VideoProperty(CS_Property handle) : m_handle(handle) { - m_status = 0; - if (handle == 0) { - m_kind = kNone; - } else { - m_kind = - static_cast(static_cast(GetPropertyKind(handle, &m_status))); - } -} - -inline VideoProperty::VideoProperty(CS_Property handle, Kind kind) - : m_handle(handle), m_kind(kind) {} - -inline VideoSource::VideoSource(const VideoSource& source) - : m_handle(source.m_handle == 0 ? 0 - : CopySource(source.m_handle, &m_status)) {} - -inline VideoSource::VideoSource(VideoSource&& other) noexcept : VideoSource() { - swap(*this, other); -} - -inline VideoSource& VideoSource::operator=(VideoSource other) noexcept { - swap(*this, other); - return *this; -} - -inline VideoSource::~VideoSource() { - m_status = 0; - if (m_handle != 0) { - ReleaseSource(m_handle, &m_status); - } -} - -inline VideoSource::Kind VideoSource::GetKind() const { - m_status = 0; - return static_cast(GetSourceKind(m_handle, &m_status)); -} - -inline std::string VideoSource::GetName() const { - m_status = 0; - return GetSourceName(m_handle, &m_status); -} - -inline std::string VideoSource::GetDescription() const { - m_status = 0; - return GetSourceDescription(m_handle, &m_status); -} - -inline uint64_t VideoSource::GetLastFrameTime() const { - m_status = 0; - return GetSourceLastFrameTime(m_handle, &m_status); -} - -inline void VideoSource::SetConnectionStrategy(ConnectionStrategy strategy) { - m_status = 0; - SetSourceConnectionStrategy( - m_handle, static_cast(static_cast(strategy)), - &m_status); -} - -inline bool VideoSource::IsConnected() const { - m_status = 0; - return IsSourceConnected(m_handle, &m_status); -} - -inline bool VideoSource::IsEnabled() const { - m_status = 0; - return IsSourceEnabled(m_handle, &m_status); -} - -inline VideoProperty VideoSource::GetProperty(std::string_view name) { - m_status = 0; - return VideoProperty{GetSourceProperty(m_handle, name, &m_status)}; -} - -inline VideoMode VideoSource::GetVideoMode() const { - m_status = 0; - return GetSourceVideoMode(m_handle, &m_status); -} - -inline bool VideoSource::SetVideoMode(const VideoMode& mode) { - m_status = 0; - return SetSourceVideoMode(m_handle, mode, &m_status); -} - -inline bool VideoSource::SetVideoMode(VideoMode::PixelFormat pixelFormat, - int width, int height, int fps) { - m_status = 0; - return SetSourceVideoMode( - m_handle, VideoMode{pixelFormat, width, height, fps}, &m_status); -} - -inline bool VideoSource::SetPixelFormat(VideoMode::PixelFormat pixelFormat) { - m_status = 0; - return SetSourcePixelFormat(m_handle, pixelFormat, &m_status); -} - -inline bool VideoSource::SetResolution(int width, int height) { - m_status = 0; - return SetSourceResolution(m_handle, width, height, &m_status); -} - -inline bool VideoSource::SetFPS(int fps) { - m_status = 0; - return SetSourceFPS(m_handle, fps, &m_status); -} - -inline bool VideoSource::SetConfigJson(std::string_view config) { - m_status = 0; - return SetSourceConfigJson(m_handle, config, &m_status); -} - -inline bool VideoSource::SetConfigJson(const wpi::json& config) { - m_status = 0; - return SetSourceConfigJson(m_handle, config, &m_status); -} - -inline std::string VideoSource::GetConfigJson() const { - m_status = 0; - return GetSourceConfigJson(m_handle, &m_status); -} - -inline double VideoSource::GetActualFPS() const { - m_status = 0; - return cs::GetTelemetryAverageValue(m_handle, CS_SOURCE_FRAMES_RECEIVED, - &m_status); -} - -inline double VideoSource::GetActualDataRate() const { - m_status = 0; - return cs::GetTelemetryAverageValue(m_handle, CS_SOURCE_BYTES_RECEIVED, - &m_status); -} - -inline std::vector VideoSource::EnumerateVideoModes() const { - CS_Status status = 0; - return EnumerateSourceVideoModes(m_handle, &status); -} - -inline void VideoCamera::SetBrightness(int brightness) { - m_status = 0; - SetCameraBrightness(m_handle, brightness, &m_status); -} - -inline int VideoCamera::GetBrightness() { - m_status = 0; - return GetCameraBrightness(m_handle, &m_status); -} - -inline void VideoCamera::SetWhiteBalanceAuto() { - m_status = 0; - SetCameraWhiteBalanceAuto(m_handle, &m_status); -} - -inline void VideoCamera::SetWhiteBalanceHoldCurrent() { - m_status = 0; - SetCameraWhiteBalanceHoldCurrent(m_handle, &m_status); -} - -inline void VideoCamera::SetWhiteBalanceManual(int value) { - m_status = 0; - SetCameraWhiteBalanceManual(m_handle, value, &m_status); -} - -inline void VideoCamera::SetExposureAuto() { - m_status = 0; - SetCameraExposureAuto(m_handle, &m_status); -} - -inline void VideoCamera::SetExposureHoldCurrent() { - m_status = 0; - SetCameraExposureHoldCurrent(m_handle, &m_status); -} - -inline void VideoCamera::SetExposureManual(int value) { - m_status = 0; - SetCameraExposureManual(m_handle, value, &m_status); -} - -inline UsbCamera::UsbCamera(std::string_view name, int dev) { - m_handle = CreateUsbCameraDev(name, dev, &m_status); -} - -inline UsbCamera::UsbCamera(std::string_view name, std::string_view path) { - m_handle = CreateUsbCameraPath(name, path, &m_status); -} - -inline std::vector UsbCamera::EnumerateUsbCameras() { - CS_Status status = 0; - return ::cs::EnumerateUsbCameras(&status); -} - -inline void UsbCamera::SetPath(std::string_view path) { - m_status = 0; - return ::cs::SetUsbCameraPath(m_handle, path, &m_status); -} - -inline std::string UsbCamera::GetPath() const { - m_status = 0; - return ::cs::GetUsbCameraPath(m_handle, &m_status); -} - -inline UsbCameraInfo UsbCamera::GetInfo() const { - m_status = 0; - return ::cs::GetUsbCameraInfo(m_handle, &m_status); -} - -inline void UsbCamera::SetConnectVerbose(int level) { - m_status = 0; - SetProperty(GetSourceProperty(m_handle, "connect_verbose", &m_status), level, - &m_status); -} - -inline HttpCamera::HttpCamera(std::string_view name, std::string_view url, - HttpCameraKind kind) { - m_handle = CreateHttpCamera( - name, url, static_cast(static_cast(kind)), - &m_status); -} - -inline HttpCamera::HttpCamera(std::string_view name, const char* url, - HttpCameraKind kind) { - m_handle = CreateHttpCamera( - name, url, static_cast(static_cast(kind)), - &m_status); -} - -inline HttpCamera::HttpCamera(std::string_view name, const std::string& url, - HttpCameraKind kind) - : HttpCamera(name, std::string_view{url}, kind) {} - -inline HttpCamera::HttpCamera(std::string_view name, - std::span urls, - HttpCameraKind kind) { - m_handle = CreateHttpCamera( - name, urls, static_cast(static_cast(kind)), - &m_status); -} - -template -inline HttpCamera::HttpCamera(std::string_view name, - std::initializer_list urls, - HttpCameraKind kind) { - std::vector vec; - vec.reserve(urls.size()); - for (const auto& url : urls) { - vec.emplace_back(url); - } - m_handle = CreateHttpCamera( - name, vec, static_cast(static_cast(kind)), - &m_status); -} - -inline HttpCamera::HttpCameraKind HttpCamera::GetHttpCameraKind() const { - m_status = 0; - return static_cast( - static_cast(::cs::GetHttpCameraKind(m_handle, &m_status))); -} - -inline void HttpCamera::SetUrls(std::span urls) { - m_status = 0; - ::cs::SetHttpCameraUrls(m_handle, urls, &m_status); -} - -template -inline void HttpCamera::SetUrls(std::initializer_list urls) { - std::vector vec; - vec.reserve(urls.size()); - for (const auto& url : urls) { - vec.emplace_back(url); - } - m_status = 0; - ::cs::SetHttpCameraUrls(m_handle, vec, &m_status); -} - -inline std::vector HttpCamera::GetUrls() const { - m_status = 0; - return ::cs::GetHttpCameraUrls(m_handle, &m_status); -} -WPI_IGNORE_DEPRECATED -inline std::vector AxisCamera::HostToUrl( - std::span hosts) { - std::vector rv; - rv.reserve(hosts.size()); - for (const auto& host : hosts) { - rv.emplace_back(HostToUrl(std::string_view{host})); - } - return rv; -} - -template -inline std::vector AxisCamera::HostToUrl( - std::initializer_list hosts) { - std::vector rv; - rv.reserve(hosts.size()); - for (const auto& host : hosts) { - rv.emplace_back(HostToUrl(std::string_view{host})); - } - return rv; -} - -inline AxisCamera::AxisCamera(std::string_view name, std::string_view host) - : HttpCamera(name, HostToUrl(host), kAxis) {} - -inline AxisCamera::AxisCamera(std::string_view name, const char* host) - : HttpCamera(name, HostToUrl(host), kAxis) {} - -inline AxisCamera::AxisCamera(std::string_view name, const std::string& host) - : HttpCamera(name, HostToUrl(std::string_view{host}), kAxis) {} - -inline AxisCamera::AxisCamera(std::string_view name, - std::span hosts) - : HttpCamera(name, HostToUrl(hosts), kAxis) {} - -template -inline AxisCamera::AxisCamera(std::string_view name, - std::initializer_list hosts) - : HttpCamera(name, HostToUrl(hosts), kAxis) {} -WPI_UNIGNORE_DEPRECATED - -inline void ImageSource::NotifyError(std::string_view msg) { - m_status = 0; - NotifySourceError(m_handle, msg, &m_status); -} - -inline void ImageSource::SetConnected(bool connected) { - m_status = 0; - SetSourceConnected(m_handle, connected, &m_status); -} - -inline void ImageSource::SetDescription(std::string_view description) { - m_status = 0; - SetSourceDescription(m_handle, description, &m_status); -} - -inline VideoProperty ImageSource::CreateProperty(std::string_view name, - VideoProperty::Kind kind, - int minimum, int maximum, - int step, int defaultValue, - int value) { - m_status = 0; - return VideoProperty{CreateSourceProperty( - m_handle, name, static_cast(static_cast(kind)), - minimum, maximum, step, defaultValue, value, &m_status)}; -} - -inline VideoProperty ImageSource::CreateIntegerProperty(std::string_view name, - int minimum, - int maximum, int step, - int defaultValue, - int value) { - m_status = 0; - return VideoProperty{CreateSourceProperty( - m_handle, name, - static_cast( - static_cast(VideoProperty::Kind::kInteger)), - minimum, maximum, step, defaultValue, value, &m_status)}; -} - -inline VideoProperty ImageSource::CreateBooleanProperty(std::string_view name, - bool defaultValue, - bool value) { - m_status = 0; - return VideoProperty{CreateSourceProperty( - m_handle, name, - static_cast( - static_cast(VideoProperty::Kind::kBoolean)), - 0, 1, 1, defaultValue ? 1 : 0, value ? 1 : 0, &m_status)}; -} - -inline VideoProperty ImageSource::CreateStringProperty(std::string_view name, - std::string_view value) { - m_status = 0; - auto prop = VideoProperty{ - CreateSourceProperty(m_handle, name, - static_cast( - static_cast(VideoProperty::Kind::kString)), - 0, 0, 0, 0, 0, &m_status)}; - prop.SetString(value); - return prop; -} - -inline void ImageSource::SetEnumPropertyChoices( - const VideoProperty& property, std::span choices) { - m_status = 0; - SetSourceEnumPropertyChoices(m_handle, property.m_handle, choices, &m_status); -} - -template -inline void ImageSource::SetEnumPropertyChoices( - const VideoProperty& property, std::initializer_list choices) { - std::vector vec; - vec.reserve(choices.size()); - for (const auto& choice : choices) { - vec.emplace_back(choice); - } - m_status = 0; - SetSourceEnumPropertyChoices(m_handle, property.m_handle, vec, &m_status); -} - -inline VideoSink::VideoSink(const VideoSink& sink) - : m_handle(sink.m_handle == 0 ? 0 : CopySink(sink.m_handle, &m_status)) {} - -inline VideoSink::VideoSink(VideoSink&& other) noexcept : VideoSink() { - swap(*this, other); -} - -inline VideoSink& VideoSink::operator=(VideoSink other) noexcept { - swap(*this, other); - return *this; -} - -inline VideoSink::~VideoSink() { - m_status = 0; - if (m_handle != 0) { - ReleaseSink(m_handle, &m_status); - } -} - -inline VideoSink::Kind VideoSink::GetKind() const { - m_status = 0; - return static_cast(GetSinkKind(m_handle, &m_status)); -} - -inline std::string VideoSink::GetName() const { - m_status = 0; - return GetSinkName(m_handle, &m_status); -} - -inline std::string VideoSink::GetDescription() const { - m_status = 0; - return GetSinkDescription(m_handle, &m_status); -} - -inline VideoProperty VideoSink::GetProperty(std::string_view name) { - m_status = 0; - return VideoProperty{GetSinkProperty(m_handle, name, &m_status)}; -} - -inline void VideoSink::SetSource(VideoSource source) { - m_status = 0; - if (!source) { - SetSinkSource(m_handle, 0, &m_status); - } else { - SetSinkSource(m_handle, source.m_handle, &m_status); - } -} - -inline VideoSource VideoSink::GetSource() const { - m_status = 0; - auto handle = GetSinkSource(m_handle, &m_status); - return VideoSource{handle == 0 ? 0 : CopySource(handle, &m_status)}; -} - -inline VideoProperty VideoSink::GetSourceProperty(std::string_view name) { - m_status = 0; - return VideoProperty{GetSinkSourceProperty(m_handle, name, &m_status)}; -} - -inline bool VideoSink::SetConfigJson(std::string_view config) { - m_status = 0; - return SetSinkConfigJson(m_handle, config, &m_status); -} - -inline bool VideoSink::SetConfigJson(const wpi::json& config) { - m_status = 0; - return SetSinkConfigJson(m_handle, config, &m_status); -} - -inline std::string VideoSink::GetConfigJson() const { - m_status = 0; - return GetSinkConfigJson(m_handle, &m_status); -} - -inline MjpegServer::MjpegServer(std::string_view name, - std::string_view listenAddress, int port) { - m_handle = CreateMjpegServer(name, listenAddress, port, &m_status); -} - -inline std::string MjpegServer::GetListenAddress() const { - m_status = 0; - return cs::GetMjpegServerListenAddress(m_handle, &m_status); -} - -inline int MjpegServer::GetPort() const { - m_status = 0; - return cs::GetMjpegServerPort(m_handle, &m_status); -} - -inline void MjpegServer::SetResolution(int width, int height) { - m_status = 0; - SetProperty(GetSinkProperty(m_handle, "width", &m_status), width, &m_status); - SetProperty(GetSinkProperty(m_handle, "height", &m_status), height, - &m_status); -} - -inline void MjpegServer::SetFPS(int fps) { - m_status = 0; - SetProperty(GetSinkProperty(m_handle, "fps", &m_status), fps, &m_status); -} - -inline void MjpegServer::SetCompression(int quality) { - m_status = 0; - SetProperty(GetSinkProperty(m_handle, "compression", &m_status), quality, - &m_status); -} - -inline void MjpegServer::SetDefaultCompression(int quality) { - m_status = 0; - SetProperty(GetSinkProperty(m_handle, "default_compression", &m_status), - quality, &m_status); -} - -inline void ImageSink::SetDescription(std::string_view description) { - m_status = 0; - SetSinkDescription(m_handle, description, &m_status); -} - -inline std::string ImageSink::GetError() const { - m_status = 0; - return GetSinkError(m_handle, &m_status); -} - -inline void ImageSink::SetEnabled(bool enabled) { - m_status = 0; - SetSinkEnabled(m_handle, enabled, &m_status); -} - -inline VideoSource VideoEvent::GetSource() const { - CS_Status status = 0; - return VideoSource{sourceHandle == 0 ? 0 : CopySource(sourceHandle, &status)}; -} - -inline VideoSink VideoEvent::GetSink() const { - CS_Status status = 0; - return VideoSink{sinkHandle == 0 ? 0 : CopySink(sinkHandle, &status)}; -} - -inline VideoProperty VideoEvent::GetProperty() const { - return VideoProperty{propertyHandle, - static_cast(propertyKind)}; -} - -inline VideoListener::VideoListener( - std::function callback, int eventMask, - bool immediateNotify) { - CS_Status status = 0; - m_handle = AddListener( - [=](const RawEvent& event) { - callback(static_cast(event)); - }, - eventMask, immediateNotify, &status); -} - -inline VideoListener::VideoListener(VideoListener&& other) noexcept - : VideoListener() { - swap(*this, other); -} - -inline VideoListener& VideoListener::operator=(VideoListener&& other) noexcept { - swap(*this, other); - return *this; -} - -inline VideoListener::~VideoListener() { - CS_Status status = 0; - if (m_handle != 0) { - RemoveListener(m_handle, &status); - } -} - -} // namespace cs - -#endif // CSCORE_CSCORE_OO_INC_ diff --git a/glass/src/lib/native/include/glass/Provider.h b/glass/src/lib/native/include/glass/Provider.h index f620d523b8d..95750de486e 100644 --- a/glass/src/lib/native/include/glass/Provider.h +++ b/glass/src/lib/native/include/glass/Provider.h @@ -62,7 +62,10 @@ class Provider : public WindowManager { * Perform global initialization. This should be called prior to * wpi::gui::Initialize(). */ - void GlobalInit() override; + void GlobalInit() override { + WindowManager::GlobalInit(); + wpi::gui::AddEarlyExecute([this] { Update(); }); + } /** * Show the specified view by default on first load. Has no effect if @@ -70,7 +73,17 @@ class Provider : public WindowManager { * * @param name View name */ - void ShowDefault(std::string_view name); + void ShowDefault(std::string_view name) { + auto win = GetWindow(name); + if (win) { + return; + } + auto it = FindViewEntry(name); + if (it == m_viewEntries.end() || (*it)->name != name) { + return; + } + (*it)->showDefault = true; + } /** * Register a model and view combination. Equivalent to calling both @@ -82,7 +95,10 @@ class Provider : public WindowManager { * @param createView Functor for creating view */ void Register(std::string_view name, ExistsFunc exists, - CreateModelFunc createModel, CreateViewFunc createView); + CreateModelFunc createModel, CreateViewFunc createView) { + RegisterModel(name, std::move(exists), std::move(createModel)); + RegisterView(name, name, nullptr, std::move(createView)); + } /** * Register a model. @@ -92,7 +108,16 @@ class Provider : public WindowManager { * @param createModel Functor for creating model */ void RegisterModel(std::string_view name, ExistsFunc exists, - CreateModelFunc createModel); + CreateModelFunc createModel) { + auto it = FindModelEntry(name); + // ignore if exists + if (it != m_modelEntries.end() && (*it)->name == name) { + return; + } + // insert in sorted location + m_modelEntries.emplace( + it, MakeModelEntry(name, std::move(exists), std::move(createModel))); + } /** * Register a view. @@ -103,10 +128,33 @@ class Provider : public WindowManager { * @param createView Functor for creating view */ void RegisterView(std::string_view name, std::string_view modelName, - ViewExistsFunc exists, CreateViewFunc createView); + ViewExistsFunc exists, CreateViewFunc createView) { + // find model; if model doesn't exist, ignore + auto modelIt = FindModelEntry(modelName); + if (modelIt == m_modelEntries.end() || (*modelIt)->name != modelName) { + return; + } + + auto viewIt = FindViewEntry(name); + // ignore if exists + if (viewIt != m_viewEntries.end() && (*viewIt)->name == name) { + return; + } + // insert in sorted location + m_viewEntries.emplace(viewIt, + MakeViewEntry(name, modelIt->get(), std::move(exists), + std::move(createView))); + } protected: - virtual void Update(); + virtual void Update() { + // update entries + for (auto&& entry : m_modelEntries) { + if (entry->model) { + entry->model->Update(); + } + } + } struct ModelEntry { ModelEntry(std::string_view name, ExistsFunc exists, @@ -145,8 +193,17 @@ class Provider : public WindowManager { using ViewEntries = std::vector>; ViewEntries m_viewEntries; - typename ModelEntries::iterator FindModelEntry(std::string_view name); - typename ViewEntries::iterator FindViewEntry(std::string_view name); + typename ModelEntries::iterator FindModelEntry(std::string_view name) { + return std::lower_bound( + m_modelEntries.begin(), m_modelEntries.end(), name, + [](const auto& elem, std::string_view s) { return elem->name < s; }); + } + + typename ViewEntries::iterator FindViewEntry(std::string_view name) { + return std::lower_bound( + m_viewEntries.begin(), m_viewEntries.end(), name, + [](const auto& elem, std::string_view s) { return elem->name < s; }); + } virtual std::unique_ptr MakeModelEntry( std::string_view name, ExistsFunc exists, CreateModelFunc createModel) { @@ -166,5 +223,3 @@ class Provider : public WindowManager { }; } // namespace glass - -#include "Provider.inc" diff --git a/glass/src/lib/native/include/glass/Provider.inc b/glass/src/lib/native/include/glass/Provider.inc deleted file mode 100644 index 7370cca13b1..00000000000 --- a/glass/src/lib/native/include/glass/Provider.inc +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include - -#include "glass/Provider.h" - -namespace glass { - -template -void Provider::GlobalInit() { - WindowManager::GlobalInit(); - wpi::gui::AddEarlyExecute([this] { Update(); }); -} - -template -void Provider::ShowDefault(std::string_view name) { - auto win = GetWindow(name); - if (win) { - return; - } - auto it = FindViewEntry(name); - if (it == m_viewEntries.end() || (*it)->name != name) { - return; - } - (*it)->showDefault = true; -} - -template -void Provider::Register(std::string_view name, ExistsFunc exists, - CreateModelFunc createModel, - CreateViewFunc createView) { - RegisterModel(name, std::move(exists), std::move(createModel)); - RegisterView(name, name, nullptr, std::move(createView)); -} - -template -void Provider::RegisterModel(std::string_view name, - ExistsFunc exists, - CreateModelFunc createModel) { - auto it = FindModelEntry(name); - // ignore if exists - if (it != m_modelEntries.end() && (*it)->name == name) { - return; - } - // insert in sorted location - m_modelEntries.emplace( - it, MakeModelEntry(name, std::move(exists), std::move(createModel))); -} - -template -void Provider::RegisterView(std::string_view name, - std::string_view modelName, - ViewExistsFunc exists, - CreateViewFunc createView) { - // find model; if model doesn't exist, ignore - auto modelIt = FindModelEntry(modelName); - if (modelIt == m_modelEntries.end() || (*modelIt)->name != modelName) { - return; - } - - auto viewIt = FindViewEntry(name); - // ignore if exists - if (viewIt != m_viewEntries.end() && (*viewIt)->name == name) { - return; - } - // insert in sorted location - m_viewEntries.emplace(viewIt, - MakeViewEntry(name, modelIt->get(), std::move(exists), - std::move(createView))); -} - -template -void Provider::Update() { - // update entries - for (auto&& entry : m_modelEntries) { - if (entry->model) { - entry->model->Update(); - } - } -} - -template -typename Provider::ModelEntries::iterator -Provider::FindModelEntry(std::string_view name) { - return std::lower_bound( - m_modelEntries.begin(), m_modelEntries.end(), name, - [](const auto& elem, std::string_view s) { return elem->name < s; }); -} - -template -typename Provider::ViewEntries::iterator -Provider::FindViewEntry(std::string_view name) { - return std::lower_bound( - m_viewEntries.begin(), m_viewEntries.end(), name, - [](const auto& elem, std::string_view s) { return elem->name < s; }); -} - -} // namespace glass diff --git a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h index 849edebc08c..adf6135eb1c 100644 --- a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h +++ b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h @@ -6,9 +6,10 @@ #include #include -#include #include +#include +#include #include #include #include @@ -56,11 +57,19 @@ using WSRegisterFunc = std::function void CreateProviders(std::string_view prefix, int32_t numChannels, - WSRegisterFunc webRegisterFunc); + WSRegisterFunc webRegisterFunc) { + for (int32_t i = 0; i < numChannels; i++) { + auto key = fmt::format("{}/{}", prefix, i); + auto ptr = std::make_unique(i, key, prefix); + webRegisterFunc(key, std::move(ptr)); + } +} template -void CreateSingleProvider(std::string_view key, WSRegisterFunc webRegisterFunc); +void CreateSingleProvider(std::string_view key, + WSRegisterFunc webRegisterFunc) { + auto ptr = std::make_unique(key, key); + webRegisterFunc(key, std::move(ptr)); +} } // namespace wpilibws - -#include "WSHalProviders.inc" diff --git a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc deleted file mode 100644 index c9ce9d14d83..00000000000 --- a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include - -#include - -#include "WSHalProviders.h" - -namespace wpilibws { - -template -void CreateProviders(std::string_view prefix, int numChannels, - WSRegisterFunc webRegisterFunc) { - for (int32_t i = 0; i < numChannels; i++) { - auto key = fmt::format("{}/{}", prefix, i); - auto ptr = std::make_unique(i, key, prefix); - webRegisterFunc(key, std::move(ptr)); - } -} - -template -void CreateSingleProvider(std::string_view key, - WSRegisterFunc webRegisterFunc) { - auto ptr = std::make_unique(key, key); - webRegisterFunc(key, std::move(ptr)); -} - -} // namespace wpilibws diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h index 388730f89c3..75205e99289 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h @@ -3,6 +3,8 @@ // the WPILib BSD license file in the root directory of this project. #include +#include +#include #include #include @@ -91,7 +93,15 @@ class SwerveControllerCommand std::function desiredRotation, std::function)> output, - Requirements requirements = {}); + Requirements requirements = {}) + : m_trajectory(std::move(trajectory)), + m_pose(std::move(pose)), + m_kinematics(kinematics), + m_controller(xController, yController, thetaController), + m_desiredRotation(std::move(desiredRotation)), + m_outputStates(output) { + this->AddRequirements(requirements); + } /** * Constructs a new SwerveControllerCommand that when executed will follow the @@ -129,7 +139,14 @@ class SwerveControllerCommand frc::ProfiledPIDController thetaController, std::function)> output, - Requirements requirements = {}); + Requirements requirements = {}) + : m_trajectory(std::move(trajectory)), + m_pose(std::move(pose)), + m_kinematics(kinematics), + m_controller(xController, yController, thetaController), + m_outputStates(output) { + this->AddRequirements(requirements); + } /** * Constructs a new SwerveControllerCommand that when executed will follow the @@ -159,7 +176,15 @@ class SwerveControllerCommand std::function desiredRotation, std::function)> output, - Requirements requirements = {}); + Requirements requirements = {}) + : m_trajectory(std::move(trajectory)), + m_pose(std::move(pose)), + m_kinematics(kinematics), + m_controller(std::move(controller)), + m_desiredRotation(std::move(desiredRotation)), + m_outputStates(output) { + this->AddRequirements(requirements); + } /** * Constructs a new SwerveControllerCommand that when executed will follow the @@ -191,15 +216,41 @@ class SwerveControllerCommand frc::HolonomicDriveController controller, std::function)> output, - Requirements requirements = {}); + Requirements requirements = {}) + : m_trajectory(std::move(trajectory)), + m_pose(std::move(pose)), + m_kinematics(kinematics), + m_controller(std::move(controller)), + m_outputStates(output) { + this->AddRequirements(requirements); + } - void Initialize() override; + void Initialize() override { + if (m_desiredRotation == nullptr) { + m_desiredRotation = [&] { + return m_trajectory.States().back().pose.Rotation(); + }; + } + m_timer.Restart(); + } - void Execute() override; + void Execute() override { + auto curTime = m_timer.Get(); + auto m_desiredState = m_trajectory.Sample(curTime); - void End(bool interrupted) override; + auto targetChassisSpeeds = + m_controller.Calculate(m_pose(), m_desiredState, m_desiredRotation()); + auto targetModuleStates = + m_kinematics.ToSwerveModuleStates(targetChassisSpeeds); - bool IsFinished() override; + m_outputStates(targetModuleStates); + } + + void End(bool interrupted) override { m_timer.Stop(); } + + bool IsFinished() override { + return m_timer.HasElapsed(m_trajectory.TotalTime()); + } private: frc::Trajectory m_trajectory; @@ -215,6 +266,5 @@ class SwerveControllerCommand units::second_t m_prevTime; frc::Rotation2d m_finalRotation; }; -} // namespace frc2 -#include "SwerveControllerCommand.inc" +} // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.inc b/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.inc deleted file mode 100644 index d0c34af2b72..00000000000 --- a/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.inc +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include - -#include "frc2/command/SwerveControllerCommand.h" - -namespace frc2 { - -template -SwerveControllerCommand::SwerveControllerCommand( - frc::Trajectory trajectory, std::function pose, - frc::SwerveDriveKinematics kinematics, - frc::PIDController xController, frc::PIDController yController, - frc::ProfiledPIDController thetaController, - std::function desiredRotation, - std::function)> output, - Requirements requirements) - : m_trajectory(std::move(trajectory)), - m_pose(std::move(pose)), - m_kinematics(kinematics), - m_controller(xController, yController, thetaController), - m_desiredRotation(std::move(desiredRotation)), - m_outputStates(output) { - this->AddRequirements(requirements); -} - -template -SwerveControllerCommand::SwerveControllerCommand( - frc::Trajectory trajectory, std::function pose, - frc::SwerveDriveKinematics kinematics, - frc::PIDController xController, frc::PIDController yController, - frc::ProfiledPIDController thetaController, - std::function)> output, - Requirements requirements) - : m_trajectory(std::move(trajectory)), - m_pose(std::move(pose)), - m_kinematics(kinematics), - m_controller(xController, yController, thetaController), - m_outputStates(output) { - this->AddRequirements(requirements); -} - -template -SwerveControllerCommand::SwerveControllerCommand( - frc::Trajectory trajectory, std::function pose, - frc::SwerveDriveKinematics kinematics, - frc::HolonomicDriveController controller, - std::function desiredRotation, - std::function)> output, - Requirements requirements) - : m_trajectory(std::move(trajectory)), - m_pose(std::move(pose)), - m_kinematics(kinematics), - m_controller(std::move(controller)), - m_desiredRotation(std::move(desiredRotation)), - m_outputStates(output) { - this->AddRequirements(requirements); -} - -template -SwerveControllerCommand::SwerveControllerCommand( - frc::Trajectory trajectory, std::function pose, - frc::SwerveDriveKinematics kinematics, - frc::HolonomicDriveController controller, - std::function)> output, - Requirements requirements) - : m_trajectory(std::move(trajectory)), - m_pose(std::move(pose)), - m_kinematics(kinematics), - m_controller(std::move(controller)), - m_outputStates(output) { - this->AddRequirements(requirements); -} - -template -void SwerveControllerCommand::Initialize() { - if (m_desiredRotation == nullptr) { - m_desiredRotation = [&] { - return m_trajectory.States().back().pose.Rotation(); - }; - } - m_timer.Restart(); -} - -template -void SwerveControllerCommand::Execute() { - auto curTime = m_timer.Get(); - auto m_desiredState = m_trajectory.Sample(curTime); - - auto targetChassisSpeeds = - m_controller.Calculate(m_pose(), m_desiredState, m_desiredRotation()); - auto targetModuleStates = - m_kinematics.ToSwerveModuleStates(targetChassisSpeeds); - - m_outputStates(targetModuleStates); -} - -template -void SwerveControllerCommand::End(bool interrupted) { - m_timer.Stop(); -} - -template -bool SwerveControllerCommand::IsFinished() { - return m_timer.HasElapsed(m_trajectory.TotalTime()); -} - -} // namespace frc2 diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h index 6500fb3e2f0..532fecde7f5 100644 --- a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h +++ b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h @@ -36,7 +36,11 @@ class [[deprecated( */ template explicit MotorControllerGroup(MotorController& motorController, - MotorControllers&... motorControllers); + MotorControllers&... motorControllers) + : m_motorControllers(std::vector>{ + motorController, motorControllers...}) { + Initialize(); + } /** * Create a new MotorControllerGroup with the provided MotorControllers. @@ -68,6 +72,4 @@ class [[deprecated( } // namespace frc -#include "frc/motorcontrol/MotorControllerGroup.inc" - WPI_UNIGNORE_DEPRECATED diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc deleted file mode 100644 index 8f876354a19..00000000000 --- a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include - -#include "frc/motorcontrol/MotorControllerGroup.h" - -namespace frc { - -template -MotorControllerGroup::MotorControllerGroup( - MotorController& motorController, MotorControllers&... motorControllers) - : m_motorControllers(std::vector>{ - motorController, motorControllers...}) { - Initialize(); -} - -} // namespace frc diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h index 8cb867388bc..3441c5784df 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h @@ -4,8 +4,6 @@ #pragma once -#include -#include #include #include @@ -34,7 +32,9 @@ class ShuffleboardComponent : public ShuffleboardComponentBase { * @param type The component type. */ ShuffleboardComponent(ShuffleboardContainer& parent, std::string_view title, - std::string_view type = ""); + std::string_view type = "") + : ShuffleboardValue(title), + ShuffleboardComponentBase(parent, title, type) {} /** * Sets custom properties for this component. Property names are @@ -44,7 +44,11 @@ class ShuffleboardComponent : public ShuffleboardComponentBase { * @param properties the properties for this component * @return this component */ - Derived& WithProperties(const wpi::StringMap& properties); + Derived& WithProperties(const wpi::StringMap& properties) { + m_properties = properties; + m_metadataDirty = true; + return *static_cast(this); + } /** * Sets the position of this component in the tab. This has no effect if this @@ -59,7 +63,12 @@ class ShuffleboardComponent : public ShuffleboardComponentBase { * @param rowIndex the row in the tab to place this component * @return this component */ - Derived& WithPosition(int columnIndex, int rowIndex); + Derived& WithPosition(int columnIndex, int rowIndex) { + m_column = columnIndex; + m_row = rowIndex; + m_metadataDirty = true; + return *static_cast(this); + } /** * Sets the size of this component in the tab. This has no effect if this @@ -69,9 +78,12 @@ class ShuffleboardComponent : public ShuffleboardComponentBase { * @param height how many rows high the component should be * @return this component */ - Derived& WithSize(int width, int height); + Derived& WithSize(int width, int height) { + m_width = width; + m_height = height; + m_metadataDirty = true; + return *static_cast(this); + } }; } // namespace frc - -#include "frc/shuffleboard/ShuffleboardComponent.inc" diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc deleted file mode 100644 index 63a4933181e..00000000000 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include - -#include "frc/shuffleboard/ShuffleboardComponent.h" - -namespace frc { - -template -ShuffleboardComponent::ShuffleboardComponent( - ShuffleboardContainer& parent, std::string_view title, - std::string_view type) - : ShuffleboardValue(title), - ShuffleboardComponentBase(parent, title, type) {} - -template -Derived& ShuffleboardComponent::WithProperties( - const wpi::StringMap& properties) { - m_properties = properties; - m_metadataDirty = true; - return *static_cast(this); -} - -template -Derived& ShuffleboardComponent::WithPosition(int columnIndex, - int rowIndex) { - m_column = columnIndex; - m_row = rowIndex; - m_metadataDirty = true; - return *static_cast(this); -} - -template -Derived& ShuffleboardComponent::WithSize(int width, int height) { - m_width = width; - m_height = height; - m_metadataDirty = true; - return *static_cast(this); -} - -} // namespace frc diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h b/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h index 4f82dc61196..c044f25d351 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h @@ -14,7 +14,6 @@ #include #include "frc/shuffleboard/ShuffleboardComponent.h" -#include "frc/shuffleboard/ShuffleboardComponent.inc" #include "frc/shuffleboard/ShuffleboardComponentBase.h" #include "frc/shuffleboard/ShuffleboardWidget.h" diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h index 0c17fdefe96..3cf022ba126 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h @@ -4,12 +4,17 @@ #pragma once +#include #include #include #include +#include #include +#include +#include #include +#include #include "frc/smartdashboard/SendableChooserBase.h" @@ -34,10 +39,14 @@ class SendableChooser : public SendableChooserBase { wpi::StringMap m_choices; std::function m_listener; template - static U _unwrap_smart_ptr(const U& value); + static U _unwrap_smart_ptr(const U& value) { + return value; + } template - static std::weak_ptr _unwrap_smart_ptr(const std::shared_ptr& value); + static std::weak_ptr _unwrap_smart_ptr(const std::shared_ptr& value) { + return value; + } public: using CopyType = decltype(_unwrap_smart_ptr(m_choices.lookup(""))); @@ -56,7 +65,9 @@ class SendableChooser : public SendableChooserBase { * @param name the name of the option * @param object the option */ - void AddOption(std::string_view name, T object); + void AddOption(std::string_view name, T object) { + m_choices[name] = std::move(object); + } /** * Add the given object to the list of options and marks it as the default. @@ -67,7 +78,10 @@ class SendableChooser : public SendableChooserBase { * @param name the name of the option * @param object the option */ - void SetDefaultOption(std::string_view name, T object); + void SetDefaultOption(std::string_view name, T object) { + m_defaultChoice = name; + AddOption(name, std::move(object)); + } /** * Returns a copy of the selected option (a std::weak_ptr if T = @@ -80,7 +94,20 @@ class SendableChooser : public SendableChooserBase { * * @return The option selected */ - CopyType GetSelected() const; + CopyType GetSelected() const { + std::string selected = m_defaultChoice; + { + std::scoped_lock lock(m_mutex); + if (m_haveSelected) { + selected = m_selected; + } + } + if (selected.empty()) { + return CopyType{}; + } else { + return _unwrap_smart_ptr(m_choices.lookup(selected)); + } + } /** * Bind a listener that's called when the selected value changes. @@ -88,11 +115,66 @@ class SendableChooser : public SendableChooserBase { * previous listener. * @param listener The function to call that accepts the new value */ - void OnChange(std::function); - - void InitSendable(wpi::SendableBuilder& builder) override; + void OnChange(std::function listener) { + std::scoped_lock lock(m_mutex); + m_listener = listener; + } + + void InitSendable(wpi::SendableBuilder& builder) override { + builder.SetSmartDashboardType("String Chooser"); + builder.PublishConstInteger(kInstance, m_instance); + builder.AddStringArrayProperty( + kOptions, + [=, this] { + std::vector keys; + for (const auto& choice : m_choices) { + keys.emplace_back(choice.first()); + } + + // Unlike std::map, wpi::StringMap elements + // are not sorted + std::sort(keys.begin(), keys.end()); + + return keys; + }, + nullptr); + builder.AddSmallStringProperty( + kDefault, + [=, this](wpi::SmallVectorImpl&) -> std::string_view { + return m_defaultChoice; + }, + nullptr); + builder.AddSmallStringProperty( + kActive, + [=, this](wpi::SmallVectorImpl& buf) -> std::string_view { + std::scoped_lock lock(m_mutex); + if (m_haveSelected) { + buf.assign(m_selected.begin(), m_selected.end()); + return {buf.data(), buf.size()}; + } else { + return m_defaultChoice; + } + }, + nullptr); + builder.AddStringProperty(kSelected, nullptr, + [=, this](std::string_view val) { + T choice{}; + std::function listener; + { + std::scoped_lock lock(m_mutex); + m_haveSelected = true; + m_selected = val; + if (m_previousVal != val && m_listener) { + choice = m_choices[val]; + listener = m_listener; + } + m_previousVal = val; + } + if (listener) { + listener(choice); + } + }); + } }; } // namespace frc - -#include "frc/smartdashboard/SendableChooser.inc" diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc deleted file mode 100644 index 2b93629959c..00000000000 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "frc/smartdashboard/SendableChooser.h" - -namespace frc { - -template - requires std::copy_constructible && std::default_initializable -void SendableChooser::AddOption(std::string_view name, T object) { - m_choices[name] = std::move(object); -} - -template - requires std::copy_constructible && std::default_initializable -void SendableChooser::SetDefaultOption(std::string_view name, T object) { - m_defaultChoice = name; - AddOption(name, std::move(object)); -} - -template - requires std::copy_constructible && std::default_initializable -typename SendableChooser::CopyType SendableChooser::GetSelected() const { - std::string selected = m_defaultChoice; - { - std::scoped_lock lock(m_mutex); - if (m_haveSelected) { - selected = m_selected; - } - } - if (selected.empty()) { - return CopyType{}; - } else { - return _unwrap_smart_ptr(m_choices.lookup(selected)); - } -} - -template - requires std::copy_constructible && std::default_initializable -void SendableChooser::OnChange(std::function listener) { - std::scoped_lock lock(m_mutex); - m_listener = listener; -} - -template - requires std::copy_constructible && std::default_initializable -void SendableChooser::InitSendable(wpi::SendableBuilder& builder) { - builder.SetSmartDashboardType("String Chooser"); - builder.PublishConstInteger(kInstance, m_instance); - builder.AddStringArrayProperty( - kOptions, - [=, this] { - std::vector keys; - for (const auto& choice : m_choices) { - keys.emplace_back(choice.first()); - } - - // Unlike std::map, wpi::StringMap elements - // are not sorted - std::sort(keys.begin(), keys.end()); - - return keys; - }, - nullptr); - builder.AddSmallStringProperty( - kDefault, - [=, this](wpi::SmallVectorImpl&) -> std::string_view { - return m_defaultChoice; - }, - nullptr); - builder.AddSmallStringProperty( - kActive, - [=, this](wpi::SmallVectorImpl& buf) -> std::string_view { - std::scoped_lock lock(m_mutex); - if (m_haveSelected) { - buf.assign(m_selected.begin(), m_selected.end()); - return {buf.data(), buf.size()}; - } else { - return m_defaultChoice; - } - }, - nullptr); - builder.AddStringProperty(kSelected, nullptr, - [=, this](std::string_view val) { - T choice{}; - std::function listener; - { - std::scoped_lock lock(m_mutex); - m_haveSelected = true; - m_selected = val; - if (m_previousVal != val && m_listener) { - choice = m_choices[val]; - listener = m_listener; - } - m_previousVal = val; - } - if (listener) { - listener(choice); - } - }); -} - -template - requires std::copy_constructible && std::default_initializable -template -U SendableChooser::_unwrap_smart_ptr(const U& value) { - return value; -} - -template - requires std::copy_constructible && std::default_initializable -template -std::weak_ptr SendableChooser::_unwrap_smart_ptr( - const std::shared_ptr& value) { - return value; -} - -} // namespace frc diff --git a/wpinet/src/main/native/include/wpinet/HttpUtil.h b/wpinet/src/main/native/include/wpinet/HttpUtil.h index fcf68871a4c..0d44557f57f 100644 --- a/wpinet/src/main/native/include/wpinet/HttpUtil.h +++ b/wpinet/src/main/native/include/wpinet/HttpUtil.h @@ -316,7 +316,18 @@ class HttpRequest { } template - HttpRequest(const HttpLocation& loc, const T& extraParams); + HttpRequest(const HttpLocation& loc, const T& extraParams) + : host{loc.host}, port{loc.port} { + StringMap params; + for (const auto& p : loc.params) { + params.insert(std::make_pair(GetFirst(p), GetSecond(p))); + } + for (const auto& p : extraParams) { + params.insert(std::make_pair(GetFirst(p), GetSecond(p))); + } + SetPath(loc.path, params); + SetAuth(loc); + } HttpRequest(const HttpLocation& loc, std::string_view path_) : host{loc.host}, port{loc.port}, path{path_} { @@ -337,8 +348,27 @@ class HttpRequest { private: void SetAuth(const HttpLocation& loc); + template - void SetPath(std::string_view path_, const T& params); + void SetPath(std::string_view path_, const T& params) { + // Build location including query string + raw_svector_ostream pathOs{path}; + pathOs << path_; + bool first = true; + for (const auto& param : params) { + if (first) { + pathOs << '?'; + first = false; + } else { + pathOs << '&'; + } + SmallString<64> escapeBuf; + pathOs << EscapeURI(GetFirst(param), escapeBuf, false); + if (!GetSecond(param).empty()) { + pathOs << '=' << EscapeURI(GetSecond(param), escapeBuf, false); + } + } + } template static std::string_view GetFirst(const T& elem) { @@ -416,8 +446,10 @@ class HttpMultipartScanner { std::string m_buf; }; -} // namespace wpi +inline HttpPathRef HttpPath::drop_front(size_t n) const { + return HttpPathRef(*this, n); +} -#include "HttpUtil.inc" +} // namespace wpi #endif // WPINET_HTTPUTIL_H_ diff --git a/wpinet/src/main/native/include/wpinet/HttpUtil.inc b/wpinet/src/main/native/include/wpinet/HttpUtil.inc deleted file mode 100644 index f70b8dda01a..00000000000 --- a/wpinet/src/main/native/include/wpinet/HttpUtil.inc +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#ifndef WPINET_HTTPUTIL_INC_ -#define WPINET_HTTPUTIL_INC_ - -#include - -#include "wpinet/HttpUtil.h" - -namespace wpi { - -inline HttpPathRef HttpPath::drop_front(size_t n) const { - return HttpPathRef(*this, n); -} - -template -HttpRequest::HttpRequest(const HttpLocation& loc, const T& extraParams) - : host{loc.host}, port{loc.port} { - StringMap params; - for (const auto& p : loc.params) { - params.insert(std::make_pair(GetFirst(p), GetSecond(p))); - } - for (const auto& p : extraParams) { - params.insert(std::make_pair(GetFirst(p), GetSecond(p))); - } - SetPath(loc.path, params); - SetAuth(loc); -} - -template -void HttpRequest::SetPath(std::string_view path_, const T& params) { - // Build location including query string - raw_svector_ostream pathOs{path}; - pathOs << path_; - bool first = true; - for (const auto& param : params) { - if (first) { - pathOs << '?'; - first = false; - } else { - pathOs << '&'; - } - SmallString<64> escapeBuf; - pathOs << EscapeURI(GetFirst(param), escapeBuf, false); - if (!GetSecond(param).empty()) { - pathOs << '=' << EscapeURI(GetSecond(param), escapeBuf, false); - } - } -} - -} // namespace wpi - -#endif // WPINET_HTTPUTIL_INC_ diff --git a/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.h b/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.h index 4095a9ca460..0b273ee7301 100644 --- a/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.h +++ b/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.h @@ -37,7 +37,43 @@ class HttpWebSocketServerConnection * @param protocols Acceptable subprotocols */ HttpWebSocketServerConnection(std::shared_ptr stream, - std::span protocols); + std::span protocols) + : HttpServerConnection{stream}, + m_helper{m_request}, + m_protocols{protocols.begin(), protocols.end()} { + // Handle upgrade event + m_helper.upgrade.connect([this] { + // Negotiate sub-protocol + SmallVector protocols{m_protocols.begin(), + m_protocols.end()}; + std::string_view protocol = m_helper.MatchProtocol(protocols).second; + + // Check that the upgrade is valid + if (!IsValidWsUpgrade(protocol)) { + return; + } + + // Disconnect HttpServerConnection header reader + m_dataConn.disconnect(); + m_messageCompleteConn.disconnect(); + + // Accepting the stream may destroy this (as it replaces the stream user + // data), so grab a shared pointer first. + auto self = this->shared_from_this(); + + // Accept the upgrade + auto ws = m_helper.Accept(m_stream, protocol); + + // Set this as the websocket user data to keep it around + ws->SetData(self); + + // Store in member + m_websocket = ws.get(); + + // Call derived class function + ProcessWsUpgrade(); + }); + } /** * Constructor. @@ -88,6 +124,4 @@ class HttpWebSocketServerConnection } // namespace wpi -#include "HttpWebSocketServerConnection.inc" - #endif // WPINET_HTTPWEBSOCKETSERVERCONNECTION_H_ diff --git a/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.inc b/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.inc deleted file mode 100644 index 750439de2d9..00000000000 --- a/wpinet/src/main/native/include/wpinet/HttpWebSocketServerConnection.inc +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#ifndef WPINET_HTTPWEBSOCKETSERVERCONNECTION_INC_ -#define WPINET_HTTPWEBSOCKETSERVERCONNECTION_INC_ - -#include - -#include "wpinet/HttpWebSocketServerConnection.h" - -namespace wpi { - -template -HttpWebSocketServerConnection::HttpWebSocketServerConnection( - std::shared_ptr stream, - std::span protocols) - : HttpServerConnection{stream}, - m_helper{m_request}, - m_protocols{protocols.begin(), protocols.end()} { - // Handle upgrade event - m_helper.upgrade.connect([this] { - // Negotiate sub-protocol - SmallVector protocols{m_protocols.begin(), - m_protocols.end()}; - std::string_view protocol = m_helper.MatchProtocol(protocols).second; - - // Check that the upgrade is valid - if (!IsValidWsUpgrade(protocol)) { - return; - } - - // Disconnect HttpServerConnection header reader - m_dataConn.disconnect(); - m_messageCompleteConn.disconnect(); - - // Accepting the stream may destroy this (as it replaces the stream user - // data), so grab a shared pointer first. - auto self = this->shared_from_this(); - - // Accept the upgrade - auto ws = m_helper.Accept(m_stream, protocol); - - // Set this as the websocket user data to keep it around - ws->SetData(self); - - // Store in member - m_websocket = ws.get(); - - // Call derived class function - ProcessWsUpgrade(); - }); -} - -} // namespace wpi - -#endif // WPINET_HTTPWEBSOCKETSERVERCONNECTION_INC_ diff --git a/wpiutil/src/main/native/include/wpi/circular_buffer.h b/wpiutil/src/main/native/include/wpi/circular_buffer.h index a40a627db41..44f535c21ec 100644 --- a/wpiutil/src/main/native/include/wpi/circular_buffer.h +++ b/wpiutil/src/main/native/include/wpi/circular_buffer.h @@ -242,7 +242,54 @@ class circular_buffer { /** * Resizes internal buffer to given size. */ - void resize(size_t size); + void resize(size_t size) { + if (size > m_data.size()) { + // Find end of buffer + size_t insertLocation = (m_front + m_length) % m_data.size(); + + // If insertion location precedes front of buffer, push front index back + if (insertLocation <= m_front) { + m_front += size - m_data.size(); + } + + // Add elements to end of buffer + m_data.insert(m_data.begin() + insertLocation, size - m_data.size(), 0); + } else if (size < m_data.size()) { + /* 1) Shift element block start at "front" left as many blocks as were + * removed up to but not exceeding buffer[0] + * 2) Shrink buffer, which will remove even more elements automatically if + * necessary + */ + size_t elemsToRemove = m_data.size() - size; + auto frontIter = m_data.begin() + m_front; + if (m_front < elemsToRemove) { + /* Remove elements from end of buffer before shifting start of element + * block. Doing so saves a few copies. + */ + m_data.erase(frontIter + size, m_data.end()); + + // Shift start of element block to left + m_data.erase(m_data.begin(), frontIter); + + // Update metadata + m_front = 0; + } else { + // Shift start of element block to left + m_data.erase(frontIter - elemsToRemove, frontIter); + + // Update metadata + m_front -= elemsToRemove; + } + + /* Length only changes during a shrink if all unused spaces have been + * removed. Length decreases as used spaces are removed to meet the + * required size. + */ + if (m_length > size) { + m_length = size; + } + } + } /** * Empties internal buffer. @@ -299,5 +346,3 @@ class circular_buffer { }; } // namespace wpi - -#include "wpi/circular_buffer.inc" diff --git a/wpiutil/src/main/native/include/wpi/circular_buffer.inc b/wpiutil/src/main/native/include/wpi/circular_buffer.inc deleted file mode 100644 index 038af50d821..00000000000 --- a/wpiutil/src/main/native/include/wpi/circular_buffer.inc +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include "wpi/circular_buffer.h" - -namespace wpi { - -/** - * Resizes internal buffer to given size. - */ -template -void circular_buffer::resize(size_t size) { - if (size > m_data.size()) { - // Find end of buffer - size_t insertLocation = (m_front + m_length) % m_data.size(); - - // If insertion location precedes front of buffer, push front index back - if (insertLocation <= m_front) { - m_front += size - m_data.size(); - } - - // Add elements to end of buffer - m_data.insert(m_data.begin() + insertLocation, size - m_data.size(), 0); - } else if (size < m_data.size()) { - /* 1) Shift element block start at "front" left as many blocks as were - * removed up to but not exceeding buffer[0] - * 2) Shrink buffer, which will remove even more elements automatically if - * necessary - */ - size_t elemsToRemove = m_data.size() - size; - auto frontIter = m_data.begin() + m_front; - if (m_front < elemsToRemove) { - /* Remove elements from end of buffer before shifting start of element - * block. Doing so saves a few copies. - */ - m_data.erase(frontIter + size, m_data.end()); - - // Shift start of element block to left - m_data.erase(m_data.begin(), frontIter); - - // Update metadata - m_front = 0; - } else { - // Shift start of element block to left - m_data.erase(frontIter - elemsToRemove, frontIter); - - // Update metadata - m_front -= elemsToRemove; - } - - /* Length only changes during a shrink if all unused spaces have been - * removed. Length decreases as used spaces are removed to meet the - * required size. - */ - if (m_length > size) { - m_length = size; - } - } -} - -} // namespace wpi